1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.6.22.  By combining all the individual C code files into this
4** single large file, the entire code can be compiled as a one 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% are 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** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
64*/
65#ifndef SQLITE_DISABLE_LFS
66# define _LARGE_FILE       1
67# ifndef _FILE_OFFSET_BITS
68#   define _FILE_OFFSET_BITS 64
69# endif
70# define _LARGEFILE_SOURCE 1
71#endif
72
73/*
74** Include the configuration header output by 'configure' if we're using the
75** autoconf-based build
76*/
77#ifdef _HAVE_SQLITE_CONFIG_H
78#include "config.h"
79#endif
80
81/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
82/************** Begin file sqliteLimit.h *************************************/
83/*
84** 2007 May 7
85**
86** The author disclaims copyright to this source code.  In place of
87** a legal notice, here is a blessing:
88**
89**    May you do good and not evil.
90**    May you find forgiveness for yourself and forgive others.
91**    May you share freely, never taking more than you give.
92**
93*************************************************************************
94**
95** This file defines various limits of what SQLite can process.
96*/
97
98/*
99** The maximum length of a TEXT or BLOB in bytes.   This also
100** limits the size of a row in a table or index.
101**
102** The hard limit is the ability of a 32-bit signed integer
103** to count the size: 2^31-1 or 2147483647.
104*/
105#ifndef SQLITE_MAX_LENGTH
106# define SQLITE_MAX_LENGTH 1000000000
107#endif
108
109/*
110** This is the maximum number of
111**
112**    * Columns in a table
113**    * Columns in an index
114**    * Columns in a view
115**    * Terms in the SET clause of an UPDATE statement
116**    * Terms in the result set of a SELECT statement
117**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
118**    * Terms in the VALUES clause of an INSERT statement
119**
120** The hard upper limit here is 32676.  Most database people will
121** tell you that in a well-normalized database, you usually should
122** not have more than a dozen or so columns in any table.  And if
123** that is the case, there is no point in having more than a few
124** dozen values in any of the other situations described above.
125*/
126#ifndef SQLITE_MAX_COLUMN
127# define SQLITE_MAX_COLUMN 2000
128#endif
129
130/*
131** The maximum length of a single SQL statement in bytes.
132**
133** It used to be the case that setting this value to zero would
134** turn the limit off.  That is no longer true.  It is not possible
135** to turn this limit off.
136*/
137#ifndef SQLITE_MAX_SQL_LENGTH
138# define SQLITE_MAX_SQL_LENGTH 1000000000
139#endif
140
141/*
142** The maximum depth of an expression tree. This is limited to
143** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
144** want to place more severe limits on the complexity of an
145** expression.
146**
147** A value of 0 used to mean that the limit was not enforced.
148** But that is no longer true.  The limit is now strictly enforced
149** at all times.
150*/
151#ifndef SQLITE_MAX_EXPR_DEPTH
152# define SQLITE_MAX_EXPR_DEPTH 1000
153#endif
154
155/*
156** The maximum number of terms in a compound SELECT statement.
157** The code generator for compound SELECT statements does one
158** level of recursion for each term.  A stack overflow can result
159** if the number of terms is too large.  In practice, most SQL
160** never has more than 3 or 4 terms.  Use a value of 0 to disable
161** any limit on the number of terms in a compount SELECT.
162*/
163#ifndef SQLITE_MAX_COMPOUND_SELECT
164# define SQLITE_MAX_COMPOUND_SELECT 500
165#endif
166
167/*
168** The maximum number of opcodes in a VDBE program.
169** Not currently enforced.
170*/
171#ifndef SQLITE_MAX_VDBE_OP
172# define SQLITE_MAX_VDBE_OP 25000
173#endif
174
175/*
176** The maximum number of arguments to an SQL function.
177*/
178#ifndef SQLITE_MAX_FUNCTION_ARG
179# define SQLITE_MAX_FUNCTION_ARG 127
180#endif
181
182/*
183** The maximum number of in-memory pages to use for the main database
184** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
185*/
186#ifndef SQLITE_DEFAULT_CACHE_SIZE
187# define SQLITE_DEFAULT_CACHE_SIZE  2000
188#endif
189#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
190# define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
191#endif
192
193/*
194** The maximum number of attached databases.  This must be between 0
195** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
196** is used internally to track attached databases.
197*/
198#ifndef SQLITE_MAX_ATTACHED
199# define SQLITE_MAX_ATTACHED 10
200#endif
201
202
203/*
204** The maximum value of a ?nnn wildcard that the parser will accept.
205*/
206#ifndef SQLITE_MAX_VARIABLE_NUMBER
207# define SQLITE_MAX_VARIABLE_NUMBER 999
208#endif
209
210/* Maximum page size.  The upper bound on this value is 32768.  This a limit
211** imposed by the necessity of storing the value in a 2-byte unsigned integer
212** and the fact that the page size must be a power of 2.
213**
214** If this limit is changed, then the compiled library is technically
215** incompatible with an SQLite library compiled with a different limit. If
216** a process operating on a database with a page-size of 65536 bytes
217** crashes, then an instance of SQLite compiled with the default page-size
218** limit will not be able to rollback the aborted transaction. This could
219** lead to database corruption.
220*/
221#ifndef SQLITE_MAX_PAGE_SIZE
222# define SQLITE_MAX_PAGE_SIZE 32768
223#endif
224
225
226/*
227** The default size of a database page.
228*/
229#ifndef SQLITE_DEFAULT_PAGE_SIZE
230# define SQLITE_DEFAULT_PAGE_SIZE 1024
231#endif
232#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
233# undef SQLITE_DEFAULT_PAGE_SIZE
234# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
235#endif
236
237/*
238** Ordinarily, if no value is explicitly provided, SQLite creates databases
239** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
240** device characteristics (sector-size and atomic write() support),
241** SQLite may choose a larger value. This constant is the maximum value
242** SQLite will choose on its own.
243*/
244#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
245# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
246#endif
247#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
248# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
249# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
250#endif
251
252
253/*
254** Maximum number of pages in one database file.
255**
256** This is really just the default value for the max_page_count pragma.
257** This value can be lowered (or raised) at run-time using that the
258** max_page_count macro.
259*/
260#ifndef SQLITE_MAX_PAGE_COUNT
261# define SQLITE_MAX_PAGE_COUNT 1073741823
262#endif
263
264/*
265** Maximum length (in bytes) of the pattern in a LIKE or GLOB
266** operator.
267*/
268#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
269# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
270#endif
271
272/*
273** Maximum depth of recursion for triggers.
274**
275** A value of 1 means that a trigger program will not be able to itself
276** fire any triggers. A value of 0 means that no trigger programs at all
277** may be executed.
278*/
279#ifndef SQLITE_MAX_TRIGGER_DEPTH
280# define SQLITE_MAX_TRIGGER_DEPTH 1000
281#endif
282
283/************** End of sqliteLimit.h *****************************************/
284/************** Continuing where we left off in sqliteInt.h ******************/
285
286/* Disable nuisance warnings on Borland compilers */
287#if defined(__BORLANDC__)
288#pragma warn -rch /* unreachable code */
289#pragma warn -ccc /* Condition is always true or false */
290#pragma warn -aus /* Assigned value is never used */
291#pragma warn -csu /* Comparing signed and unsigned */
292#pragma warn -spa /* Suspicious pointer arithmetic */
293#endif
294
295/* Needed for various definitions... */
296#ifndef _GNU_SOURCE
297# define _GNU_SOURCE
298#endif
299
300/*
301** Include standard header files as necessary
302*/
303#ifdef HAVE_STDINT_H
304#include <stdint.h>
305#endif
306#ifdef HAVE_INTTYPES_H
307#include <inttypes.h>
308#endif
309
310#define SQLITE_INDEX_SAMPLES 10
311
312/*
313** This macro is used to "hide" some ugliness in casting an int
314** value to a ptr value under the MSVC 64-bit compiler.   Casting
315** non 64-bit values to ptr types results in a "hard" error with
316** the MSVC 64-bit compiler which this attempts to avoid.
317**
318** A simple compiler pragma or casting sequence could not be found
319** to correct this in all situations, so this macro was introduced.
320**
321** It could be argued that the intptr_t type could be used in this
322** case, but that type is not available on all compilers, or
323** requires the #include of specific headers which differs between
324** platforms.
325**
326** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
327** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
328** So we have to define the macros in different ways depending on the
329** compiler.
330*/
331#if defined(__GNUC__)
332# if defined(HAVE_STDINT_H)
333#   define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
334#   define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
335# else
336#   define SQLITE_INT_TO_PTR(X)  ((void*)(X))
337#   define SQLITE_PTR_TO_INT(X)  ((int)(X))
338# endif
339#else
340# define SQLITE_INT_TO_PTR(X)   ((void*)&((char*)0)[X])
341# define SQLITE_PTR_TO_INT(X)   ((int)(((char*)X)-(char*)0))
342#endif
343
344
345/*
346** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
347** Older versions of SQLite used an optional THREADSAFE macro.
348** We support that for legacy
349*/
350#if !defined(SQLITE_THREADSAFE)
351#if defined(THREADSAFE)
352# define SQLITE_THREADSAFE THREADSAFE
353#else
354# define SQLITE_THREADSAFE 1
355#endif
356#endif
357
358/*
359** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
360** It determines whether or not the features related to
361** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
362** be overridden at runtime using the sqlite3_config() API.
363*/
364#if !defined(SQLITE_DEFAULT_MEMSTATUS)
365# define SQLITE_DEFAULT_MEMSTATUS 1
366#endif
367
368/*
369** Exactly one of the following macros must be defined in order to
370** specify which memory allocation subsystem to use.
371**
372**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
373**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
374**     SQLITE_MEMORY_SIZE            // internal allocator #1
375**     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
376**     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
377**
378** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
379** the default.
380*/
381#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
382    defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
383    defined(SQLITE_POW2_MEMORY_SIZE)>1
384# error "At most one of the following compile-time configuration options\
385 is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
386 SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
387#endif
388#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
389    defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
390    defined(SQLITE_POW2_MEMORY_SIZE)==0
391# define SQLITE_SYSTEM_MALLOC 1
392#endif
393
394/*
395** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
396** sizes of memory allocations below this value where possible.
397*/
398#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
399# define SQLITE_MALLOC_SOFT_LIMIT 1024
400#endif
401
402/*
403** We need to define _XOPEN_SOURCE as follows in order to enable
404** recursive mutexes on most Unix systems.  But Mac OS X is different.
405** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
406** so it is omitted there.  See ticket #2673.
407**
408** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
409** implemented on some systems.  So we avoid defining it at all
410** if it is already defined or if it is unneeded because we are
411** not doing a threadsafe build.  Ticket #2681.
412**
413** See also ticket #2741.
414*/
415#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
416#  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
417#endif
418
419/*
420** The TCL headers are only needed when compiling the TCL bindings.
421*/
422#if defined(SQLITE_TCL) || defined(TCLSH)
423# include <tcl.h>
424#endif
425
426/*
427** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
428** Setting NDEBUG makes the code smaller and run faster.  So the following
429** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
430** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
431** feature.
432*/
433#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
434# define NDEBUG 1
435#endif
436
437/*
438** The testcase() macro is used to aid in coverage testing.  When
439** doing coverage testing, the condition inside the argument to
440** testcase() must be evaluated both true and false in order to
441** get full branch coverage.  The testcase() macro is inserted
442** to help ensure adequate test coverage in places where simple
443** condition/decision coverage is inadequate.  For example, testcase()
444** can be used to make sure boundary values are tested.  For
445** bitmask tests, testcase() can be used to make sure each bit
446** is significant and used at least once.  On switch statements
447** where multiple cases go to the same block of code, testcase()
448** can insure that all cases are evaluated.
449**
450*/
451#ifdef SQLITE_COVERAGE_TEST
452SQLITE_PRIVATE   void sqlite3Coverage(int);
453# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
454#else
455# define testcase(X)
456#endif
457
458/*
459** The TESTONLY macro is used to enclose variable declarations or
460** other bits of code that are needed to support the arguments
461** within testcase() and assert() macros.
462*/
463#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
464# define TESTONLY(X)  X
465#else
466# define TESTONLY(X)
467#endif
468
469/*
470** Sometimes we need a small amount of code such as a variable initialization
471** to setup for a later assert() statement.  We do not want this code to
472** appear when assert() is disabled.  The following macro is therefore
473** used to contain that setup code.  The "VVA" acronym stands for
474** "Verification, Validation, and Accreditation".  In other words, the
475** code within VVA_ONLY() will only run during verification processes.
476*/
477#ifndef NDEBUG
478# define VVA_ONLY(X)  X
479#else
480# define VVA_ONLY(X)
481#endif
482
483/*
484** The ALWAYS and NEVER macros surround boolean expressions which
485** are intended to always be true or false, respectively.  Such
486** expressions could be omitted from the code completely.  But they
487** are included in a few cases in order to enhance the resilience
488** of SQLite to unexpected behavior - to make the code "self-healing"
489** or "ductile" rather than being "brittle" and crashing at the first
490** hint of unplanned behavior.
491**
492** In other words, ALWAYS and NEVER are added for defensive code.
493**
494** When doing coverage testing ALWAYS and NEVER are hard-coded to
495** be true and false so that the unreachable code then specify will
496** not be counted as untested code.
497*/
498#if defined(SQLITE_COVERAGE_TEST)
499# define ALWAYS(X)      (1)
500# define NEVER(X)       (0)
501#elif !defined(NDEBUG)
502# define ALWAYS(X)      ((X)?1:(assert(0),0))
503# define NEVER(X)       ((X)?(assert(0),1):0)
504#else
505# define ALWAYS(X)      (X)
506# define NEVER(X)       (X)
507#endif
508
509/*
510** The macro unlikely() is a hint that surrounds a boolean
511** expression that is usually false.  Macro likely() surrounds
512** a boolean expression that is usually true.  GCC is able to
513** use these hints to generate better code, sometimes.
514*/
515#if defined(__GNUC__) && 0
516# define likely(X)    __builtin_expect((X),1)
517# define unlikely(X)  __builtin_expect((X),0)
518#else
519# define likely(X)    !!(X)
520# define unlikely(X)  !!(X)
521#endif
522
523/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
524/************** Begin file sqlite3.h *****************************************/
525/*
526** 2001 September 15
527**
528** The author disclaims copyright to this source code.  In place of
529** a legal notice, here is a blessing:
530**
531**    May you do good and not evil.
532**    May you find forgiveness for yourself and forgive others.
533**    May you share freely, never taking more than you give.
534**
535*************************************************************************
536** This header file defines the interface that the SQLite library
537** presents to client programs.  If a C-function, structure, datatype,
538** or constant definition does not appear in this file, then it is
539** not a published API of SQLite, is subject to change without
540** notice, and should not be referenced by programs that use SQLite.
541**
542** Some of the definitions that are in this file are marked as
543** "experimental".  Experimental interfaces are normally new
544** features recently added to SQLite.  We do not anticipate changes
545** to experimental interfaces but reserve the right to make minor changes
546** if experience from use "in the wild" suggest such changes are prudent.
547**
548** The official C-language API documentation for SQLite is derived
549** from comments in this file.  This file is the authoritative source
550** on how SQLite interfaces are suppose to operate.
551**
552** The name of this file under configuration management is "sqlite.h.in".
553** The makefile makes some minor changes to this file (such as inserting
554** the version number) and changes its name to "sqlite3.h" as
555** part of the build process.
556*/
557#ifndef _SQLITE3_H_
558#define _SQLITE3_H_
559#include <stdarg.h>     /* Needed for the definition of va_list */
560
561/*
562** Make sure we can call this stuff from C++.
563*/
564#if 0
565extern "C" {
566#endif
567
568
569/*
570** Add the ability to override 'extern'
571*/
572#ifndef SQLITE_EXTERN
573# define SQLITE_EXTERN extern
574#endif
575
576#ifndef SQLITE_API
577# define SQLITE_API
578#endif
579
580
581/*
582** These no-op macros are used in front of interfaces to mark those
583** interfaces as either deprecated or experimental.  New applications
584** should not use deprecated interfaces - they are support for backwards
585** compatibility only.  Application writers should be aware that
586** experimental interfaces are subject to change in point releases.
587**
588** These macros used to resolve to various kinds of compiler magic that
589** would generate warning messages when they were used.  But that
590** compiler magic ended up generating such a flurry of bug reports
591** that we have taken it all out and gone back to using simple
592** noop macros.
593*/
594#define SQLITE_DEPRECATED
595#define SQLITE_EXPERIMENTAL
596
597/*
598** Ensure these symbols were not defined by some previous header file.
599*/
600#ifdef SQLITE_VERSION
601# undef SQLITE_VERSION
602#endif
603#ifdef SQLITE_VERSION_NUMBER
604# undef SQLITE_VERSION_NUMBER
605#endif
606
607/*
608** CAPI3REF: Compile-Time Library Version Numbers
609**
610** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
611** evaluates to a string literal that is the SQLite version in the
612** format "X.Y.Z" where X is the major version number (always 3 for
613** SQLite3) and Y is the minor version number and Z is the release number.)^
614** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
615** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
616** numbers used in [SQLITE_VERSION].)^
617** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
618** be larger than the release from which it is derived.  Either Y will
619** be held constant and Z will be incremented or else Y will be incremented
620** and Z will be reset to zero.
621**
622** Since version 3.6.18, SQLite source code has been stored in the
623** <a href="http://www.fossil-scm.org/">Fossil configuration management
624** system</a>.  ^The SQLITE_SOURCE_ID macro evalutes to
625** a string which identifies a particular check-in of SQLite
626** within its configuration management system.  ^The SQLITE_SOURCE_ID
627** string contains the date and time of the check-in (UTC) and an SHA1
628** hash of the entire source tree.
629**
630** See also: [sqlite3_libversion()],
631** [sqlite3_libversion_number()], [sqlite3_sourceid()],
632** [sqlite_version()] and [sqlite_source_id()].
633*/
634#define SQLITE_VERSION        "3.6.22"
635#define SQLITE_VERSION_NUMBER 3006022
636#define SQLITE_SOURCE_ID      "2010-03-22 23:55:10 82dd61fccff3e4c77e060e5734cd4b4e2eeb7c32"
637
638/*
639** CAPI3REF: Run-Time Library Version Numbers
640** KEYWORDS: sqlite3_version
641**
642** These interfaces provide the same information as the [SQLITE_VERSION],
643** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
644** but are associated with the library instead of the header file.  ^(Cautious
645** programmers might include assert() statements in their application to
646** verify that values returned by these interfaces match the macros in
647** the header, and thus insure that the application is
648** compiled with matching library and header files.
649**
650** <blockquote><pre>
651** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
652** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
653** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
654** </pre></blockquote>)^
655**
656** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
657** macro.  ^The sqlite3_libversion() function returns a pointer to the
658** to the sqlite3_version[] string constant.  The sqlite3_libversion()
659** function is provided for use in DLLs since DLL users usually do not have
660** direct access to string constants within the DLL.  ^The
661** sqlite3_libversion_number() function returns an integer equal to
662** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function a pointer
663** to a string constant whose value is the same as the [SQLITE_SOURCE_ID]
664** C preprocessor macro.
665**
666** See also: [sqlite_version()] and [sqlite_source_id()].
667*/
668SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
669SQLITE_API const char *sqlite3_libversion(void);
670SQLITE_API const char *sqlite3_sourceid(void);
671SQLITE_API int sqlite3_libversion_number(void);
672
673/*
674** CAPI3REF: Test To See If The Library Is Threadsafe
675**
676** ^The sqlite3_threadsafe() function returns zero if and only if
677** SQLite was compiled mutexing code omitted due to the
678** [SQLITE_THREADSAFE] compile-time option being set to 0.
679**
680** SQLite can be compiled with or without mutexes.  When
681** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
682** are enabled and SQLite is threadsafe.  When the
683** [SQLITE_THREADSAFE] macro is 0,
684** the mutexes are omitted.  Without the mutexes, it is not safe
685** to use SQLite concurrently from more than one thread.
686**
687** Enabling mutexes incurs a measurable performance penalty.
688** So if speed is of utmost importance, it makes sense to disable
689** the mutexes.  But for maximum safety, mutexes should be enabled.
690** ^The default behavior is for mutexes to be enabled.
691**
692** This interface can be used by an application to make sure that the
693** version of SQLite that it is linking against was compiled with
694** the desired setting of the [SQLITE_THREADSAFE] macro.
695**
696** This interface only reports on the compile-time mutex setting
697** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
698** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
699** can be fully or partially disabled using a call to [sqlite3_config()]
700** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
701** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
702** sqlite3_threadsafe() function shows only the compile-time setting of
703** thread safety, not any run-time changes to that setting made by
704** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
705** is unchanged by calls to sqlite3_config().)^
706**
707** See the [threading mode] documentation for additional information.
708*/
709SQLITE_API int sqlite3_threadsafe(void);
710
711/*
712** CAPI3REF: Database Connection Handle
713** KEYWORDS: {database connection} {database connections}
714**
715** Each open SQLite database is represented by a pointer to an instance of
716** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
717** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
718** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
719** is its destructor.  There are many other interfaces (such as
720** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
721** [sqlite3_busy_timeout()] to name but three) that are methods on an
722** sqlite3 object.
723*/
724typedef struct sqlite3 sqlite3;
725
726/*
727** CAPI3REF: 64-Bit Integer Types
728** KEYWORDS: sqlite_int64 sqlite_uint64
729**
730** Because there is no cross-platform way to specify 64-bit integer types
731** SQLite includes typedefs for 64-bit signed and unsigned integers.
732**
733** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
734** The sqlite_int64 and sqlite_uint64 types are supported for backwards
735** compatibility only.
736**
737** ^The sqlite3_int64 and sqlite_int64 types can store integer values
738** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
739** sqlite3_uint64 and sqlite_uint64 types can store integer values
740** between 0 and +18446744073709551615 inclusive.
741*/
742#ifdef SQLITE_INT64_TYPE
743  typedef SQLITE_INT64_TYPE sqlite_int64;
744  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
745#elif defined(_MSC_VER) || defined(__BORLANDC__)
746  typedef __int64 sqlite_int64;
747  typedef unsigned __int64 sqlite_uint64;
748#else
749  typedef long long int sqlite_int64;
750  typedef unsigned long long int sqlite_uint64;
751#endif
752typedef sqlite_int64 sqlite3_int64;
753typedef sqlite_uint64 sqlite3_uint64;
754
755/*
756** If compiling for a processor that lacks floating point support,
757** substitute integer for floating-point.
758*/
759#ifdef SQLITE_OMIT_FLOATING_POINT
760# define double sqlite3_int64
761#endif
762
763/*
764** CAPI3REF: Closing A Database Connection
765**
766** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
767** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
768** successfullly destroyed and all associated resources are deallocated.
769**
770** Applications must [sqlite3_finalize | finalize] all [prepared statements]
771** and [sqlite3_blob_close | close] all [BLOB handles] associated with
772** the [sqlite3] object prior to attempting to close the object.  ^If
773** sqlite3_close() is called on a [database connection] that still has
774** outstanding [prepared statements] or [BLOB handles], then it returns
775** SQLITE_BUSY.
776**
777** ^If [sqlite3_close()] is invoked while a transaction is open,
778** the transaction is automatically rolled back.
779**
780** The C parameter to [sqlite3_close(C)] must be either a NULL
781** pointer or an [sqlite3] object pointer obtained
782** from [sqlite3_open()], [sqlite3_open16()], or
783** [sqlite3_open_v2()], and not previously closed.
784** ^Calling sqlite3_close() with a NULL pointer argument is a
785** harmless no-op.
786*/
787SQLITE_API int sqlite3_close(sqlite3 *);
788
789/*
790** The type for a callback function.
791** This is legacy and deprecated.  It is included for historical
792** compatibility and is not documented.
793*/
794typedef int (*sqlite3_callback)(void*,int,char**, char**);
795
796/*
797** CAPI3REF: One-Step Query Execution Interface
798**
799** The sqlite3_exec() interface is a convenience wrapper around
800** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
801** that allows an application to run multiple statements of SQL
802** without having to use a lot of C code.
803**
804** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
805** semicolon-separate SQL statements passed into its 2nd argument,
806** in the context of the [database connection] passed in as its 1st
807** argument.  ^If the callback function of the 3rd argument to
808** sqlite3_exec() is not NULL, then it is invoked for each result row
809** coming out of the evaluated SQL statements.  ^The 4th argument to
810** to sqlite3_exec() is relayed through to the 1st argument of each
811** callback invocation.  ^If the callback pointer to sqlite3_exec()
812** is NULL, then no callback is ever invoked and result rows are
813** ignored.
814**
815** ^If an error occurs while evaluating the SQL statements passed into
816** sqlite3_exec(), then execution of the current statement stops and
817** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
818** is not NULL then any error message is written into memory obtained
819** from [sqlite3_malloc()] and passed back through the 5th parameter.
820** To avoid memory leaks, the application should invoke [sqlite3_free()]
821** on error message strings returned through the 5th parameter of
822** of sqlite3_exec() after the error message string is no longer needed.
823** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
824** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
825** NULL before returning.
826**
827** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
828** routine returns SQLITE_ABORT without invoking the callback again and
829** without running any subsequent SQL statements.
830**
831** ^The 2nd argument to the sqlite3_exec() callback function is the
832** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
833** callback is an array of pointers to strings obtained as if from
834** [sqlite3_column_text()], one for each column.  ^If an element of a
835** result row is NULL then the corresponding string pointer for the
836** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
837** sqlite3_exec() callback is an array of pointers to strings where each
838** entry represents the name of corresponding result column as obtained
839** from [sqlite3_column_name()].
840**
841** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
842** to an empty string, or a pointer that contains only whitespace and/or
843** SQL comments, then no SQL statements are evaluated and the database
844** is not changed.
845**
846** Restrictions:
847**
848** <ul>
849** <li> The application must insure that the 1st parameter to sqlite3_exec()
850**      is a valid and open [database connection].
851** <li> The application must not close [database connection] specified by
852**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
853** <li> The application must not modify the SQL statement text passed into
854**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
855** </ul>
856*/
857SQLITE_API int sqlite3_exec(
858  sqlite3*,                                  /* An open database */
859  const char *sql,                           /* SQL to be evaluated */
860  int (*callback)(void*,int,char**,char**),  /* Callback function */
861  void *,                                    /* 1st argument to callback */
862  char **errmsg                              /* Error msg written here */
863);
864
865/*
866** CAPI3REF: Result Codes
867** KEYWORDS: SQLITE_OK {error code} {error codes}
868** KEYWORDS: {result code} {result codes}
869**
870** Many SQLite functions return an integer result code from the set shown
871** here in order to indicates success or failure.
872**
873** New error codes may be added in future versions of SQLite.
874**
875** See also: [SQLITE_IOERR_READ | extended result codes]
876*/
877#define SQLITE_OK           0   /* Successful result */
878/* beginning-of-error-codes */
879#define SQLITE_ERROR        1   /* SQL error or missing database */
880#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
881#define SQLITE_PERM         3   /* Access permission denied */
882#define SQLITE_ABORT        4   /* Callback routine requested an abort */
883#define SQLITE_BUSY         5   /* The database file is locked */
884#define SQLITE_LOCKED       6   /* A table in the database is locked */
885#define SQLITE_NOMEM        7   /* A malloc() failed */
886#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
887#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
888#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
889#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
890#define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
891#define SQLITE_FULL        13   /* Insertion failed because database is full */
892#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
893#define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
894#define SQLITE_EMPTY       16   /* Database is empty */
895#define SQLITE_SCHEMA      17   /* The database schema changed */
896#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
897#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
898#define SQLITE_MISMATCH    20   /* Data type mismatch */
899#define SQLITE_MISUSE      21   /* Library used incorrectly */
900#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
901#define SQLITE_AUTH        23   /* Authorization denied */
902#define SQLITE_FORMAT      24   /* Auxiliary database format error */
903#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
904#define SQLITE_NOTADB      26   /* File opened that is not a database file */
905#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
906#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
907/* end-of-error-codes */
908
909/*
910** CAPI3REF: Extended Result Codes
911** KEYWORDS: {extended error code} {extended error codes}
912** KEYWORDS: {extended result code} {extended result codes}
913**
914** In its default configuration, SQLite API routines return one of 26 integer
915** [SQLITE_OK | result codes].  However, experience has shown that many of
916** these result codes are too coarse-grained.  They do not provide as
917** much information about problems as programmers might like.  In an effort to
918** address this, newer versions of SQLite (version 3.3.8 and later) include
919** support for additional result codes that provide more detailed information
920** about errors. The extended result codes are enabled or disabled
921** on a per database connection basis using the
922** [sqlite3_extended_result_codes()] API.
923**
924** Some of the available extended result codes are listed here.
925** One may expect the number of extended result codes will be expand
926** over time.  Software that uses extended result codes should expect
927** to see new result codes in future releases of SQLite.
928**
929** The SQLITE_OK result code will never be extended.  It will always
930** be exactly zero.
931*/
932#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
933#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
934#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
935#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
936#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
937#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
938#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
939#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
940#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
941#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
942#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
943#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
944#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
945#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
946#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
947#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
948#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
949#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED | (1<<8) )
950
951/*
952** CAPI3REF: Flags For File Open Operations
953**
954** These bit values are intended for use in the
955** 3rd parameter to the [sqlite3_open_v2()] interface and
956** in the 4th parameter to the xOpen method of the
957** [sqlite3_vfs] object.
958*/
959#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
960#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
961#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
962#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
963#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
964#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
965#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
966#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
967#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
968#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
969#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
970#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
971#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
972#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
973#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
974#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
975
976/*
977** CAPI3REF: Device Characteristics
978**
979** The xDeviceCapabilities method of the [sqlite3_io_methods]
980** object returns an integer which is a vector of the these
981** bit values expressing I/O characteristics of the mass storage
982** device that holds the file that the [sqlite3_io_methods]
983** refers to.
984**
985** The SQLITE_IOCAP_ATOMIC property means that all writes of
986** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
987** mean that writes of blocks that are nnn bytes in size and
988** are aligned to an address which is an integer multiple of
989** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
990** that when data is appended to a file, the data is appended
991** first then the size of the file is extended, never the other
992** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
993** information is written to disk in the same order as calls
994** to xWrite().
995*/
996#define SQLITE_IOCAP_ATOMIC          0x00000001
997#define SQLITE_IOCAP_ATOMIC512       0x00000002
998#define SQLITE_IOCAP_ATOMIC1K        0x00000004
999#define SQLITE_IOCAP_ATOMIC2K        0x00000008
1000#define SQLITE_IOCAP_ATOMIC4K        0x00000010
1001#define SQLITE_IOCAP_ATOMIC8K        0x00000020
1002#define SQLITE_IOCAP_ATOMIC16K       0x00000040
1003#define SQLITE_IOCAP_ATOMIC32K       0x00000080
1004#define SQLITE_IOCAP_ATOMIC64K       0x00000100
1005#define SQLITE_IOCAP_SAFE_APPEND     0x00000200
1006#define SQLITE_IOCAP_SEQUENTIAL      0x00000400
1007
1008/*
1009** CAPI3REF: File Locking Levels
1010**
1011** SQLite uses one of these integer values as the second
1012** argument to calls it makes to the xLock() and xUnlock() methods
1013** of an [sqlite3_io_methods] object.
1014*/
1015#define SQLITE_LOCK_NONE          0
1016#define SQLITE_LOCK_SHARED        1
1017#define SQLITE_LOCK_RESERVED      2
1018#define SQLITE_LOCK_PENDING       3
1019#define SQLITE_LOCK_EXCLUSIVE     4
1020
1021/*
1022** CAPI3REF: Synchronization Type Flags
1023**
1024** When SQLite invokes the xSync() method of an
1025** [sqlite3_io_methods] object it uses a combination of
1026** these integer values as the second argument.
1027**
1028** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1029** sync operation only needs to flush data to mass storage.  Inode
1030** information need not be flushed. If the lower four bits of the flag
1031** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1032** If the lower four bits equal SQLITE_SYNC_FULL, that means
1033** to use Mac OS X style fullsync instead of fsync().
1034*/
1035#define SQLITE_SYNC_NORMAL        0x00002
1036#define SQLITE_SYNC_FULL          0x00003
1037#define SQLITE_SYNC_DATAONLY      0x00010
1038
1039/*
1040** CAPI3REF: OS Interface Open File Handle
1041**
1042** An [sqlite3_file] object represents an open file in the
1043** [sqlite3_vfs | OS interface layer].  Individual OS interface
1044** implementations will
1045** want to subclass this object by appending additional fields
1046** for their own use.  The pMethods entry is a pointer to an
1047** [sqlite3_io_methods] object that defines methods for performing
1048** I/O operations on the open file.
1049*/
1050typedef struct sqlite3_file sqlite3_file;
1051struct sqlite3_file {
1052  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1053};
1054
1055/*
1056** CAPI3REF: OS Interface File Virtual Methods Object
1057**
1058** Every file opened by the [sqlite3_vfs] xOpen method populates an
1059** [sqlite3_file] object (or, more commonly, a subclass of the
1060** [sqlite3_file] object) with a pointer to an instance of this object.
1061** This object defines the methods used to perform various operations
1062** against the open file represented by the [sqlite3_file] object.
1063**
1064** If the xOpen method sets the sqlite3_file.pMethods element
1065** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1066** may be invoked even if the xOpen reported that it failed.  The
1067** only way to prevent a call to xClose following a failed xOpen
1068** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
1069**
1070** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1071** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1072** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1073** flag may be ORed in to indicate that only the data of the file
1074** and not its inode needs to be synced.
1075**
1076** The integer values to xLock() and xUnlock() are one of
1077** <ul>
1078** <li> [SQLITE_LOCK_NONE],
1079** <li> [SQLITE_LOCK_SHARED],
1080** <li> [SQLITE_LOCK_RESERVED],
1081** <li> [SQLITE_LOCK_PENDING], or
1082** <li> [SQLITE_LOCK_EXCLUSIVE].
1083** </ul>
1084** xLock() increases the lock. xUnlock() decreases the lock.
1085** The xCheckReservedLock() method checks whether any database connection,
1086** either in this process or in some other process, is holding a RESERVED,
1087** PENDING, or EXCLUSIVE lock on the file.  It returns true
1088** if such a lock exists and false otherwise.
1089**
1090** The xFileControl() method is a generic interface that allows custom
1091** VFS implementations to directly control an open file using the
1092** [sqlite3_file_control()] interface.  The second "op" argument is an
1093** integer opcode.  The third argument is a generic pointer intended to
1094** point to a structure that may contain arguments or space in which to
1095** write return values.  Potential uses for xFileControl() might be
1096** functions to enable blocking locks with timeouts, to change the
1097** locking strategy (for example to use dot-file locks), to inquire
1098** about the status of a lock, or to break stale locks.  The SQLite
1099** core reserves all opcodes less than 100 for its own use.
1100** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1101** Applications that define a custom xFileControl method should use opcodes
1102** greater than 100 to avoid conflicts.
1103**
1104** The xSectorSize() method returns the sector size of the
1105** device that underlies the file.  The sector size is the
1106** minimum write that can be performed without disturbing
1107** other bytes in the file.  The xDeviceCharacteristics()
1108** method returns a bit vector describing behaviors of the
1109** underlying device:
1110**
1111** <ul>
1112** <li> [SQLITE_IOCAP_ATOMIC]
1113** <li> [SQLITE_IOCAP_ATOMIC512]
1114** <li> [SQLITE_IOCAP_ATOMIC1K]
1115** <li> [SQLITE_IOCAP_ATOMIC2K]
1116** <li> [SQLITE_IOCAP_ATOMIC4K]
1117** <li> [SQLITE_IOCAP_ATOMIC8K]
1118** <li> [SQLITE_IOCAP_ATOMIC16K]
1119** <li> [SQLITE_IOCAP_ATOMIC32K]
1120** <li> [SQLITE_IOCAP_ATOMIC64K]
1121** <li> [SQLITE_IOCAP_SAFE_APPEND]
1122** <li> [SQLITE_IOCAP_SEQUENTIAL]
1123** </ul>
1124**
1125** The SQLITE_IOCAP_ATOMIC property means that all writes of
1126** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1127** mean that writes of blocks that are nnn bytes in size and
1128** are aligned to an address which is an integer multiple of
1129** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1130** that when data is appended to a file, the data is appended
1131** first then the size of the file is extended, never the other
1132** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1133** information is written to disk in the same order as calls
1134** to xWrite().
1135**
1136** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1137** in the unread portions of the buffer with zeros.  A VFS that
1138** fails to zero-fill short reads might seem to work.  However,
1139** failure to zero-fill short reads will eventually lead to
1140** database corruption.
1141*/
1142typedef struct sqlite3_io_methods sqlite3_io_methods;
1143struct sqlite3_io_methods {
1144  int iVersion;
1145  int (*xClose)(sqlite3_file*);
1146  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1147  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1148  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1149  int (*xSync)(sqlite3_file*, int flags);
1150  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1151  int (*xLock)(sqlite3_file*, int);
1152  int (*xUnlock)(sqlite3_file*, int);
1153  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1154  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1155  int (*xSectorSize)(sqlite3_file*);
1156  int (*xDeviceCharacteristics)(sqlite3_file*);
1157  /* Additional methods may be added in future releases */
1158};
1159
1160/*
1161** CAPI3REF: Standard File Control Opcodes
1162**
1163** These integer constants are opcodes for the xFileControl method
1164** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1165** interface.
1166**
1167** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1168** opcode causes the xFileControl method to write the current state of
1169** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1170** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1171** into an integer that the pArg argument points to. This capability
1172** is used during testing and only needs to be supported when SQLITE_TEST
1173** is defined.
1174*/
1175#define SQLITE_FCNTL_LOCKSTATE        1
1176#define SQLITE_GET_LOCKPROXYFILE      2
1177#define SQLITE_SET_LOCKPROXYFILE      3
1178#define SQLITE_LAST_ERRNO             4
1179
1180/*
1181** CAPI3REF: Mutex Handle
1182**
1183** The mutex module within SQLite defines [sqlite3_mutex] to be an
1184** abstract type for a mutex object.  The SQLite core never looks
1185** at the internal representation of an [sqlite3_mutex].  It only
1186** deals with pointers to the [sqlite3_mutex] object.
1187**
1188** Mutexes are created using [sqlite3_mutex_alloc()].
1189*/
1190typedef struct sqlite3_mutex sqlite3_mutex;
1191
1192/*
1193** CAPI3REF: OS Interface Object
1194**
1195** An instance of the sqlite3_vfs object defines the interface between
1196** the SQLite core and the underlying operating system.  The "vfs"
1197** in the name of the object stands for "virtual file system".
1198**
1199** The value of the iVersion field is initially 1 but may be larger in
1200** future versions of SQLite.  Additional fields may be appended to this
1201** object when the iVersion value is increased.  Note that the structure
1202** of the sqlite3_vfs object changes in the transaction between
1203** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1204** modified.
1205**
1206** The szOsFile field is the size of the subclassed [sqlite3_file]
1207** structure used by this VFS.  mxPathname is the maximum length of
1208** a pathname in this VFS.
1209**
1210** Registered sqlite3_vfs objects are kept on a linked list formed by
1211** the pNext pointer.  The [sqlite3_vfs_register()]
1212** and [sqlite3_vfs_unregister()] interfaces manage this list
1213** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1214** searches the list.  Neither the application code nor the VFS
1215** implementation should use the pNext pointer.
1216**
1217** The pNext field is the only field in the sqlite3_vfs
1218** structure that SQLite will ever modify.  SQLite will only access
1219** or modify this field while holding a particular static mutex.
1220** The application should never modify anything within the sqlite3_vfs
1221** object once the object has been registered.
1222**
1223** The zName field holds the name of the VFS module.  The name must
1224** be unique across all VFS modules.
1225**
1226** SQLite will guarantee that the zFilename parameter to xOpen
1227** is either a NULL pointer or string obtained
1228** from xFullPathname().  SQLite further guarantees that
1229** the string will be valid and unchanged until xClose() is
1230** called. Because of the previous sentence,
1231** the [sqlite3_file] can safely store a pointer to the
1232** filename if it needs to remember the filename for some reason.
1233** If the zFilename parameter is xOpen is a NULL pointer then xOpen
1234** must invent its own temporary name for the file.  Whenever the
1235** xFilename parameter is NULL it will also be the case that the
1236** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1237**
1238** The flags argument to xOpen() includes all bits set in
1239** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1240** or [sqlite3_open16()] is used, then flags includes at least
1241** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1242** If xOpen() opens a file read-only then it sets *pOutFlags to
1243** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1244**
1245** SQLite will also add one of the following flags to the xOpen()
1246** call, depending on the object being opened:
1247**
1248** <ul>
1249** <li>  [SQLITE_OPEN_MAIN_DB]
1250** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1251** <li>  [SQLITE_OPEN_TEMP_DB]
1252** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1253** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1254** <li>  [SQLITE_OPEN_SUBJOURNAL]
1255** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1256** </ul>
1257**
1258** The file I/O implementation can use the object type flags to
1259** change the way it deals with files.  For example, an application
1260** that does not care about crash recovery or rollback might make
1261** the open of a journal file a no-op.  Writes to this journal would
1262** also be no-ops, and any attempt to read the journal would return
1263** SQLITE_IOERR.  Or the implementation might recognize that a database
1264** file will be doing page-aligned sector reads and writes in a random
1265** order and set up its I/O subsystem accordingly.
1266**
1267** SQLite might also add one of the following flags to the xOpen method:
1268**
1269** <ul>
1270** <li> [SQLITE_OPEN_DELETEONCLOSE]
1271** <li> [SQLITE_OPEN_EXCLUSIVE]
1272** </ul>
1273**
1274** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1275** deleted when it is closed.  The [SQLITE_OPEN_DELETEONCLOSE]
1276** will be set for TEMP  databases, journals and for subjournals.
1277**
1278** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1279** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1280** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1281** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1282** SQLITE_OPEN_CREATE, is used to indicate that file should always
1283** be created, and that it is an error if it already exists.
1284** It is <i>not</i> used to indicate the file should be opened
1285** for exclusive access.
1286**
1287** At least szOsFile bytes of memory are allocated by SQLite
1288** to hold the  [sqlite3_file] structure passed as the third
1289** argument to xOpen.  The xOpen method does not have to
1290** allocate the structure; it should just fill it in.  Note that
1291** the xOpen method must set the sqlite3_file.pMethods to either
1292** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1293** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1294** element will be valid after xOpen returns regardless of the success
1295** or failure of the xOpen call.
1296**
1297** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1298** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1299** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1300** to test whether a file is at least readable.   The file can be a
1301** directory.
1302**
1303** SQLite will always allocate at least mxPathname+1 bytes for the
1304** output buffer xFullPathname.  The exact size of the output buffer
1305** is also passed as a parameter to both  methods. If the output buffer
1306** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1307** handled as a fatal error by SQLite, vfs implementations should endeavor
1308** to prevent this by setting mxPathname to a sufficiently large value.
1309**
1310** The xRandomness(), xSleep(), and xCurrentTime() interfaces
1311** are not strictly a part of the filesystem, but they are
1312** included in the VFS structure for completeness.
1313** The xRandomness() function attempts to return nBytes bytes
1314** of good-quality randomness into zOut.  The return value is
1315** the actual number of bytes of randomness obtained.
1316** The xSleep() method causes the calling thread to sleep for at
1317** least the number of microseconds given.  The xCurrentTime()
1318** method returns a Julian Day Number for the current date and time.
1319**
1320*/
1321typedef struct sqlite3_vfs sqlite3_vfs;
1322struct sqlite3_vfs {
1323  int iVersion;            /* Structure version number */
1324  int szOsFile;            /* Size of subclassed sqlite3_file */
1325  int mxPathname;          /* Maximum file pathname length */
1326  sqlite3_vfs *pNext;      /* Next registered VFS */
1327  const char *zName;       /* Name of this virtual file system */
1328  void *pAppData;          /* Pointer to application-specific data */
1329  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1330               int flags, int *pOutFlags);
1331  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1332  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1333  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1334  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1335  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1336  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1337  void (*xDlClose)(sqlite3_vfs*, void*);
1338  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1339  int (*xSleep)(sqlite3_vfs*, int microseconds);
1340  int (*xCurrentTime)(sqlite3_vfs*, double*);
1341  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1342  /* New fields may be appended in figure versions.  The iVersion
1343  ** value will increment whenever this happens. */
1344};
1345
1346/*
1347** CAPI3REF: Flags for the xAccess VFS method
1348**
1349** These integer constants can be used as the third parameter to
1350** the xAccess method of an [sqlite3_vfs] object.  They determine
1351** what kind of permissions the xAccess method is looking for.
1352** With SQLITE_ACCESS_EXISTS, the xAccess method
1353** simply checks whether the file exists.
1354** With SQLITE_ACCESS_READWRITE, the xAccess method
1355** checks whether the file is both readable and writable.
1356** With SQLITE_ACCESS_READ, the xAccess method
1357** checks whether the file is readable.
1358*/
1359#define SQLITE_ACCESS_EXISTS    0
1360#define SQLITE_ACCESS_READWRITE 1
1361#define SQLITE_ACCESS_READ      2
1362
1363/*
1364** CAPI3REF: Initialize The SQLite Library
1365**
1366** ^The sqlite3_initialize() routine initializes the
1367** SQLite library.  ^The sqlite3_shutdown() routine
1368** deallocates any resources that were allocated by sqlite3_initialize().
1369** These routines are designed to aid in process initialization and
1370** shutdown on embedded systems.  Workstation applications using
1371** SQLite normally do not need to invoke either of these routines.
1372**
1373** A call to sqlite3_initialize() is an "effective" call if it is
1374** the first time sqlite3_initialize() is invoked during the lifetime of
1375** the process, or if it is the first time sqlite3_initialize() is invoked
1376** following a call to sqlite3_shutdown().  ^(Only an effective call
1377** of sqlite3_initialize() does any initialization.  All other calls
1378** are harmless no-ops.)^
1379**
1380** A call to sqlite3_shutdown() is an "effective" call if it is the first
1381** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1382** an effective call to sqlite3_shutdown() does any deinitialization.
1383** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1384**
1385** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1386** is not.  The sqlite3_shutdown() interface must only be called from a
1387** single thread.  All open [database connections] must be closed and all
1388** other SQLite resources must be deallocated prior to invoking
1389** sqlite3_shutdown().
1390**
1391** Among other things, ^sqlite3_initialize() will invoke
1392** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1393** will invoke sqlite3_os_end().
1394**
1395** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1396** ^If for some reason, sqlite3_initialize() is unable to initialize
1397** the library (perhaps it is unable to allocate a needed resource such
1398** as a mutex) it returns an [error code] other than [SQLITE_OK].
1399**
1400** ^The sqlite3_initialize() routine is called internally by many other
1401** SQLite interfaces so that an application usually does not need to
1402** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1403** calls sqlite3_initialize() so the SQLite library will be automatically
1404** initialized when [sqlite3_open()] is called if it has not be initialized
1405** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1406** compile-time option, then the automatic calls to sqlite3_initialize()
1407** are omitted and the application must call sqlite3_initialize() directly
1408** prior to using any other SQLite interface.  For maximum portability,
1409** it is recommended that applications always invoke sqlite3_initialize()
1410** directly prior to using any other SQLite interface.  Future releases
1411** of SQLite may require this.  In other words, the behavior exhibited
1412** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1413** default behavior in some future release of SQLite.
1414**
1415** The sqlite3_os_init() routine does operating-system specific
1416** initialization of the SQLite library.  The sqlite3_os_end()
1417** routine undoes the effect of sqlite3_os_init().  Typical tasks
1418** performed by these routines include allocation or deallocation
1419** of static resources, initialization of global variables,
1420** setting up a default [sqlite3_vfs] module, or setting up
1421** a default configuration using [sqlite3_config()].
1422**
1423** The application should never invoke either sqlite3_os_init()
1424** or sqlite3_os_end() directly.  The application should only invoke
1425** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1426** interface is called automatically by sqlite3_initialize() and
1427** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1428** implementations for sqlite3_os_init() and sqlite3_os_end()
1429** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1430** When [custom builds | built for other platforms]
1431** (using the [SQLITE_OS_OTHER=1] compile-time
1432** option) the application must supply a suitable implementation for
1433** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1434** implementation of sqlite3_os_init() or sqlite3_os_end()
1435** must return [SQLITE_OK] on success and some other [error code] upon
1436** failure.
1437*/
1438SQLITE_API int sqlite3_initialize(void);
1439SQLITE_API int sqlite3_shutdown(void);
1440SQLITE_API int sqlite3_os_init(void);
1441SQLITE_API int sqlite3_os_end(void);
1442
1443/*
1444** CAPI3REF: Configuring The SQLite Library
1445**
1446** The sqlite3_config() interface is used to make global configuration
1447** changes to SQLite in order to tune SQLite to the specific needs of
1448** the application.  The default configuration is recommended for most
1449** applications and so this routine is usually not necessary.  It is
1450** provided to support rare applications with unusual needs.
1451**
1452** The sqlite3_config() interface is not threadsafe.  The application
1453** must insure that no other SQLite interfaces are invoked by other
1454** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1455** may only be invoked prior to library initialization using
1456** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1457** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1458** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1459** Note, however, that ^sqlite3_config() can be called as part of the
1460** implementation of an application-defined [sqlite3_os_init()].
1461**
1462** The first argument to sqlite3_config() is an integer
1463** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1464** what property of SQLite is to be configured.  Subsequent arguments
1465** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1466** in the first argument.
1467**
1468** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1469** ^If the option is unknown or SQLite is unable to set the option
1470** then this routine returns a non-zero [error code].
1471*/
1472SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
1473
1474/*
1475** CAPI3REF: Configure database connections
1476** EXPERIMENTAL
1477**
1478** The sqlite3_db_config() interface is used to make configuration
1479** changes to a [database connection].  The interface is similar to
1480** [sqlite3_config()] except that the changes apply to a single
1481** [database connection] (specified in the first argument).  The
1482** sqlite3_db_config() interface should only be used immediately after
1483** the database connection is created using [sqlite3_open()],
1484** [sqlite3_open16()], or [sqlite3_open_v2()].
1485**
1486** The second argument to sqlite3_db_config(D,V,...)  is the
1487** configuration verb - an integer code that indicates what
1488** aspect of the [database connection] is being configured.
1489** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1490** New verbs are likely to be added in future releases of SQLite.
1491** Additional arguments depend on the verb.
1492**
1493** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1494** the call is considered successful.
1495*/
1496SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
1497
1498/*
1499** CAPI3REF: Memory Allocation Routines
1500** EXPERIMENTAL
1501**
1502** An instance of this object defines the interface between SQLite
1503** and low-level memory allocation routines.
1504**
1505** This object is used in only one place in the SQLite interface.
1506** A pointer to an instance of this object is the argument to
1507** [sqlite3_config()] when the configuration option is
1508** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1509** By creating an instance of this object
1510** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1511** during configuration, an application can specify an alternative
1512** memory allocation subsystem for SQLite to use for all of its
1513** dynamic memory needs.
1514**
1515** Note that SQLite comes with several [built-in memory allocators]
1516** that are perfectly adequate for the overwhelming majority of applications
1517** and that this object is only useful to a tiny minority of applications
1518** with specialized memory allocation requirements.  This object is
1519** also used during testing of SQLite in order to specify an alternative
1520** memory allocator that simulates memory out-of-memory conditions in
1521** order to verify that SQLite recovers gracefully from such
1522** conditions.
1523**
1524** The xMalloc and xFree methods must work like the
1525** malloc() and free() functions from the standard C library.
1526** The xRealloc method must work like realloc() from the standard C library
1527** with the exception that if the second argument to xRealloc is zero,
1528** xRealloc must be a no-op - it must not perform any allocation or
1529** deallocation.  ^SQLite guarantees that the second argument to
1530** xRealloc is always a value returned by a prior call to xRoundup.
1531** And so in cases where xRoundup always returns a positive number,
1532** xRealloc can perform exactly as the standard library realloc() and
1533** still be in compliance with this specification.
1534**
1535** xSize should return the allocated size of a memory allocation
1536** previously obtained from xMalloc or xRealloc.  The allocated size
1537** is always at least as big as the requested size but may be larger.
1538**
1539** The xRoundup method returns what would be the allocated size of
1540** a memory allocation given a particular requested size.  Most memory
1541** allocators round up memory allocations at least to the next multiple
1542** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1543** Every memory allocation request coming in through [sqlite3_malloc()]
1544** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1545** that causes the corresponding memory allocation to fail.
1546**
1547** The xInit method initializes the memory allocator.  (For example,
1548** it might allocate any require mutexes or initialize internal data
1549** structures.  The xShutdown method is invoked (indirectly) by
1550** [sqlite3_shutdown()] and should deallocate any resources acquired
1551** by xInit.  The pAppData pointer is used as the only parameter to
1552** xInit and xShutdown.
1553**
1554** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1555** the xInit method, so the xInit method need not be threadsafe.  The
1556** xShutdown method is only called from [sqlite3_shutdown()] so it does
1557** not need to be threadsafe either.  For all other methods, SQLite
1558** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1559** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1560** it is by default) and so the methods are automatically serialized.
1561** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1562** methods must be threadsafe or else make their own arrangements for
1563** serialization.
1564**
1565** SQLite will never invoke xInit() more than once without an intervening
1566** call to xShutdown().
1567*/
1568typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1569struct sqlite3_mem_methods {
1570  void *(*xMalloc)(int);         /* Memory allocation function */
1571  void (*xFree)(void*);          /* Free a prior allocation */
1572  void *(*xRealloc)(void*,int);  /* Resize an allocation */
1573  int (*xSize)(void*);           /* Return the size of an allocation */
1574  int (*xRoundup)(int);          /* Round up request size to allocation size */
1575  int (*xInit)(void*);           /* Initialize the memory allocator */
1576  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1577  void *pAppData;                /* Argument to xInit() and xShutdown() */
1578};
1579
1580/*
1581** CAPI3REF: Configuration Options
1582** EXPERIMENTAL
1583**
1584** These constants are the available integer configuration options that
1585** can be passed as the first argument to the [sqlite3_config()] interface.
1586**
1587** New configuration options may be added in future releases of SQLite.
1588** Existing configuration options might be discontinued.  Applications
1589** should check the return code from [sqlite3_config()] to make sure that
1590** the call worked.  The [sqlite3_config()] interface will return a
1591** non-zero [error code] if a discontinued or unsupported configuration option
1592** is invoked.
1593**
1594** <dl>
1595** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1596** <dd>There are no arguments to this option.  ^This option sets the
1597** [threading mode] to Single-thread.  In other words, it disables
1598** all mutexing and puts SQLite into a mode where it can only be used
1599** by a single thread.   ^If SQLite is compiled with
1600** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1601** it is not possible to change the [threading mode] from its default
1602** value of Single-thread and so [sqlite3_config()] will return
1603** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1604** configuration option.</dd>
1605**
1606** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1607** <dd>There are no arguments to this option.  ^This option sets the
1608** [threading mode] to Multi-thread.  In other words, it disables
1609** mutexing on [database connection] and [prepared statement] objects.
1610** The application is responsible for serializing access to
1611** [database connections] and [prepared statements].  But other mutexes
1612** are enabled so that SQLite will be safe to use in a multi-threaded
1613** environment as long as no two threads attempt to use the same
1614** [database connection] at the same time.  ^If SQLite is compiled with
1615** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1616** it is not possible to set the Multi-thread [threading mode] and
1617** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1618** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1619**
1620** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1621** <dd>There are no arguments to this option.  ^This option sets the
1622** [threading mode] to Serialized. In other words, this option enables
1623** all mutexes including the recursive
1624** mutexes on [database connection] and [prepared statement] objects.
1625** In this mode (which is the default when SQLite is compiled with
1626** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1627** to [database connections] and [prepared statements] so that the
1628** application is free to use the same [database connection] or the
1629** same [prepared statement] in different threads at the same time.
1630** ^If SQLite is compiled with
1631** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1632** it is not possible to set the Serialized [threading mode] and
1633** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1634** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1635**
1636** <dt>SQLITE_CONFIG_MALLOC</dt>
1637** <dd> ^(This option takes a single argument which is a pointer to an
1638** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1639** alternative low-level memory allocation routines to be used in place of
1640** the memory allocation routines built into SQLite.)^ ^SQLite makes
1641** its own private copy of the content of the [sqlite3_mem_methods] structure
1642** before the [sqlite3_config()] call returns.</dd>
1643**
1644** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1645** <dd> ^(This option takes a single argument which is a pointer to an
1646** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1647** structure is filled with the currently defined memory allocation routines.)^
1648** This option can be used to overload the default memory allocation
1649** routines with a wrapper that simulations memory allocation failure or
1650** tracks memory usage, for example. </dd>
1651**
1652** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1653** <dd> ^This option takes single argument of type int, interpreted as a
1654** boolean, which enables or disables the collection of memory allocation
1655** statistics. ^(When memory allocation statistics are disabled, the
1656** following SQLite interfaces become non-operational:
1657**   <ul>
1658**   <li> [sqlite3_memory_used()]
1659**   <li> [sqlite3_memory_highwater()]
1660**   <li> [sqlite3_soft_heap_limit()]
1661**   <li> [sqlite3_status()]
1662**   </ul>)^
1663** ^Memory allocation statistics are enabled by default unless SQLite is
1664** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1665** allocation statistics are disabled by default.
1666** </dd>
1667**
1668** <dt>SQLITE_CONFIG_SCRATCH</dt>
1669** <dd> ^This option specifies a static memory buffer that SQLite can use for
1670** scratch memory.  There are three arguments:  A pointer an 8-byte
1671** aligned memory buffer from which the scrach allocations will be
1672** drawn, the size of each scratch allocation (sz),
1673** and the maximum number of scratch allocations (N).  The sz
1674** argument must be a multiple of 16. The sz parameter should be a few bytes
1675** larger than the actual scratch space required due to internal overhead.
1676** The first argument must be a pointer to an 8-byte aligned buffer
1677** of at least sz*N bytes of memory.
1678** ^SQLite will use no more than one scratch buffer per thread.  So
1679** N should be set to the expected maximum number of threads.  ^SQLite will
1680** never require a scratch buffer that is more than 6 times the database
1681** page size. ^If SQLite needs needs additional scratch memory beyond
1682** what is provided by this configuration option, then
1683** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1684**
1685** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1686** <dd> ^This option specifies a static memory buffer that SQLite can use for
1687** the database page cache with the default page cache implemenation.
1688** This configuration should not be used if an application-define page
1689** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1690** There are three arguments to this option: A pointer to 8-byte aligned
1691** memory, the size of each page buffer (sz), and the number of pages (N).
1692** The sz argument should be the size of the largest database page
1693** (a power of two between 512 and 32768) plus a little extra for each
1694** page header.  ^The page header size is 20 to 40 bytes depending on
1695** the host architecture.  ^It is harmless, apart from the wasted memory,
1696** to make sz a little too large.  The first
1697** argument should point to an allocation of at least sz*N bytes of memory.
1698** ^SQLite will use the memory provided by the first argument to satisfy its
1699** memory needs for the first N pages that it adds to cache.  ^If additional
1700** page cache memory is needed beyond what is provided by this option, then
1701** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1702** ^The implementation might use one or more of the N buffers to hold
1703** memory accounting information. The pointer in the first argument must
1704** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1705** will be undefined.</dd>
1706**
1707** <dt>SQLITE_CONFIG_HEAP</dt>
1708** <dd> ^This option specifies a static memory buffer that SQLite will use
1709** for all of its dynamic memory allocation needs beyond those provided
1710** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1711** There are three arguments: An 8-byte aligned pointer to the memory,
1712** the number of bytes in the memory buffer, and the minimum allocation size.
1713** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1714** to using its default memory allocator (the system malloc() implementation),
1715** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1716** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1717** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1718** allocator is engaged to handle all of SQLites memory allocation needs.
1719** The first pointer (the memory pointer) must be aligned to an 8-byte
1720** boundary or subsequent behavior of SQLite will be undefined.</dd>
1721**
1722** <dt>SQLITE_CONFIG_MUTEX</dt>
1723** <dd> ^(This option takes a single argument which is a pointer to an
1724** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1725** alternative low-level mutex routines to be used in place
1726** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1727** content of the [sqlite3_mutex_methods] structure before the call to
1728** [sqlite3_config()] returns. ^If SQLite is compiled with
1729** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1730** the entire mutexing subsystem is omitted from the build and hence calls to
1731** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1732** return [SQLITE_ERROR].</dd>
1733**
1734** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1735** <dd> ^(This option takes a single argument which is a pointer to an
1736** instance of the [sqlite3_mutex_methods] structure.  The
1737** [sqlite3_mutex_methods]
1738** structure is filled with the currently defined mutex routines.)^
1739** This option can be used to overload the default mutex allocation
1740** routines with a wrapper used to track mutex usage for performance
1741** profiling or testing, for example.   ^If SQLite is compiled with
1742** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1743** the entire mutexing subsystem is omitted from the build and hence calls to
1744** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1745** return [SQLITE_ERROR].</dd>
1746**
1747** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1748** <dd> ^(This option takes two arguments that determine the default
1749** memory allocation for the lookaside memory allocator on each
1750** [database connection].  The first argument is the
1751** size of each lookaside buffer slot and the second is the number of
1752** slots allocated to each database connection.)^  ^(This option sets the
1753** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1754** verb to [sqlite3_db_config()] can be used to change the lookaside
1755** configuration on individual connections.)^ </dd>
1756**
1757** <dt>SQLITE_CONFIG_PCACHE</dt>
1758** <dd> ^(This option takes a single argument which is a pointer to
1759** an [sqlite3_pcache_methods] object.  This object specifies the interface
1760** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1761** object and uses it for page cache memory allocations.</dd>
1762**
1763** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1764** <dd> ^(This option takes a single argument which is a pointer to an
1765** [sqlite3_pcache_methods] object.  SQLite copies of the current
1766** page cache implementation into that object.)^ </dd>
1767**
1768** </dl>
1769*/
1770#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1771#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1772#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1773#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1774#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1775#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1776#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1777#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1778#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1779#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1780#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1781/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
1782#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1783#define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1784#define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1785#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1786
1787/*
1788** CAPI3REF: Configuration Options
1789** EXPERIMENTAL
1790**
1791** These constants are the available integer configuration options that
1792** can be passed as the second argument to the [sqlite3_db_config()] interface.
1793**
1794** New configuration options may be added in future releases of SQLite.
1795** Existing configuration options might be discontinued.  Applications
1796** should check the return code from [sqlite3_db_config()] to make sure that
1797** the call worked.  ^The [sqlite3_db_config()] interface will return a
1798** non-zero [error code] if a discontinued or unsupported configuration option
1799** is invoked.
1800**
1801** <dl>
1802** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1803** <dd> ^This option takes three additional arguments that determine the
1804** [lookaside memory allocator] configuration for the [database connection].
1805** ^The first argument (the third parameter to [sqlite3_db_config()] is a
1806** pointer to an memory buffer to use for lookaside memory.
1807** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
1808** may be NULL in which case SQLite will allocate the
1809** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
1810** size of each lookaside buffer slot.  ^The third argument is the number of
1811** slots.  The size of the buffer in the first argument must be greater than
1812** or equal to the product of the second and third arguments.  The buffer
1813** must be aligned to an 8-byte boundary.  ^If the second argument to
1814** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1815** rounded down to the next smaller
1816** multiple of 8.  See also: [SQLITE_CONFIG_LOOKASIDE]</dd>
1817**
1818** </dl>
1819*/
1820#define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
1821
1822
1823/*
1824** CAPI3REF: Enable Or Disable Extended Result Codes
1825**
1826** ^The sqlite3_extended_result_codes() routine enables or disables the
1827** [extended result codes] feature of SQLite. ^The extended result
1828** codes are disabled by default for historical compatibility.
1829*/
1830SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1831
1832/*
1833** CAPI3REF: Last Insert Rowid
1834**
1835** ^Each entry in an SQLite table has a unique 64-bit signed
1836** integer key called the [ROWID | "rowid"]. ^The rowid is always available
1837** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1838** names are not also used by explicitly declared columns. ^If
1839** the table has a column of type [INTEGER PRIMARY KEY] then that column
1840** is another alias for the rowid.
1841**
1842** ^This routine returns the [rowid] of the most recent
1843** successful [INSERT] into the database from the [database connection]
1844** in the first argument.  ^If no successful [INSERT]s
1845** have ever occurred on that database connection, zero is returned.
1846**
1847** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
1848** row is returned by this routine as long as the trigger is running.
1849** But once the trigger terminates, the value returned by this routine
1850** reverts to the last value inserted before the trigger fired.)^
1851**
1852** ^An [INSERT] that fails due to a constraint violation is not a
1853** successful [INSERT] and does not change the value returned by this
1854** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1855** and INSERT OR ABORT make no changes to the return value of this
1856** routine when their insertion fails.  ^(When INSERT OR REPLACE
1857** encounters a constraint violation, it does not fail.  The
1858** INSERT continues to completion after deleting rows that caused
1859** the constraint problem so INSERT OR REPLACE will always change
1860** the return value of this interface.)^
1861**
1862** ^For the purposes of this routine, an [INSERT] is considered to
1863** be successful even if it is subsequently rolled back.
1864**
1865** This function is accessible to SQL statements via the
1866** [last_insert_rowid() SQL function].
1867**
1868** If a separate thread performs a new [INSERT] on the same
1869** database connection while the [sqlite3_last_insert_rowid()]
1870** function is running and thus changes the last insert [rowid],
1871** then the value returned by [sqlite3_last_insert_rowid()] is
1872** unpredictable and might not equal either the old or the new
1873** last insert [rowid].
1874*/
1875SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1876
1877/*
1878** CAPI3REF: Count The Number Of Rows Modified
1879**
1880** ^This function returns the number of database rows that were changed
1881** or inserted or deleted by the most recently completed SQL statement
1882** on the [database connection] specified by the first parameter.
1883** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
1884** or [DELETE] statement are counted.  Auxiliary changes caused by
1885** triggers or [foreign key actions] are not counted.)^ Use the
1886** [sqlite3_total_changes()] function to find the total number of changes
1887** including changes caused by triggers and foreign key actions.
1888**
1889** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
1890** are not counted.  Only real table changes are counted.
1891**
1892** ^(A "row change" is a change to a single row of a single table
1893** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
1894** are changed as side effects of [REPLACE] constraint resolution,
1895** rollback, ABORT processing, [DROP TABLE], or by any other
1896** mechanisms do not count as direct row changes.)^
1897**
1898** A "trigger context" is a scope of execution that begins and
1899** ends with the script of a [CREATE TRIGGER | trigger].
1900** Most SQL statements are
1901** evaluated outside of any trigger.  This is the "top level"
1902** trigger context.  If a trigger fires from the top level, a
1903** new trigger context is entered for the duration of that one
1904** trigger.  Subtriggers create subcontexts for their duration.
1905**
1906** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
1907** not create a new trigger context.
1908**
1909** ^This function returns the number of direct row changes in the
1910** most recent INSERT, UPDATE, or DELETE statement within the same
1911** trigger context.
1912**
1913** ^Thus, when called from the top level, this function returns the
1914** number of changes in the most recent INSERT, UPDATE, or DELETE
1915** that also occurred at the top level.  ^(Within the body of a trigger,
1916** the sqlite3_changes() interface can be called to find the number of
1917** changes in the most recently completed INSERT, UPDATE, or DELETE
1918** statement within the body of the same trigger.
1919** However, the number returned does not include changes
1920** caused by subtriggers since those have their own context.)^
1921**
1922** See also the [sqlite3_total_changes()] interface, the
1923** [count_changes pragma], and the [changes() SQL function].
1924**
1925** If a separate thread makes changes on the same database connection
1926** while [sqlite3_changes()] is running then the value returned
1927** is unpredictable and not meaningful.
1928*/
1929SQLITE_API int sqlite3_changes(sqlite3*);
1930
1931/*
1932** CAPI3REF: Total Number Of Rows Modified
1933**
1934** ^This function returns the number of row changes caused by [INSERT],
1935** [UPDATE] or [DELETE] statements since the [database connection] was opened.
1936** ^(The count returned by sqlite3_total_changes() includes all changes
1937** from all [CREATE TRIGGER | trigger] contexts and changes made by
1938** [foreign key actions]. However,
1939** the count does not include changes used to implement [REPLACE] constraints,
1940** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
1941** count does not include rows of views that fire an [INSTEAD OF trigger],
1942** though if the INSTEAD OF trigger makes changes of its own, those changes
1943** are counted.)^
1944** ^The sqlite3_total_changes() function counts the changes as soon as
1945** the statement that makes them is completed (when the statement handle
1946** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
1947**
1948** See also the [sqlite3_changes()] interface, the
1949** [count_changes pragma], and the [total_changes() SQL function].
1950**
1951** If a separate thread makes changes on the same database connection
1952** while [sqlite3_total_changes()] is running then the value
1953** returned is unpredictable and not meaningful.
1954*/
1955SQLITE_API int sqlite3_total_changes(sqlite3*);
1956
1957/*
1958** CAPI3REF: Interrupt A Long-Running Query
1959**
1960** ^This function causes any pending database operation to abort and
1961** return at its earliest opportunity. This routine is typically
1962** called in response to a user action such as pressing "Cancel"
1963** or Ctrl-C where the user wants a long query operation to halt
1964** immediately.
1965**
1966** ^It is safe to call this routine from a thread different from the
1967** thread that is currently running the database operation.  But it
1968** is not safe to call this routine with a [database connection] that
1969** is closed or might close before sqlite3_interrupt() returns.
1970**
1971** ^If an SQL operation is very nearly finished at the time when
1972** sqlite3_interrupt() is called, then it might not have an opportunity
1973** to be interrupted and might continue to completion.
1974**
1975** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
1976** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
1977** that is inside an explicit transaction, then the entire transaction
1978** will be rolled back automatically.
1979**
1980** ^The sqlite3_interrupt(D) call is in effect until all currently running
1981** SQL statements on [database connection] D complete.  ^Any new SQL statements
1982** that are started after the sqlite3_interrupt() call and before the
1983** running statements reaches zero are interrupted as if they had been
1984** running prior to the sqlite3_interrupt() call.  ^New SQL statements
1985** that are started after the running statement count reaches zero are
1986** not effected by the sqlite3_interrupt().
1987** ^A call to sqlite3_interrupt(D) that occurs when there are no running
1988** SQL statements is a no-op and has no effect on SQL statements
1989** that are started after the sqlite3_interrupt() call returns.
1990**
1991** If the database connection closes while [sqlite3_interrupt()]
1992** is running then bad things will likely happen.
1993*/
1994SQLITE_API void sqlite3_interrupt(sqlite3*);
1995
1996/*
1997** CAPI3REF: Determine If An SQL Statement Is Complete
1998**
1999** These routines are useful during command-line input to determine if the
2000** currently entered text seems to form a complete SQL statement or
2001** if additional input is needed before sending the text into
2002** SQLite for parsing.  ^These routines return 1 if the input string
2003** appears to be a complete SQL statement.  ^A statement is judged to be
2004** complete if it ends with a semicolon token and is not a prefix of a
2005** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2006** string literals or quoted identifier names or comments are not
2007** independent tokens (they are part of the token in which they are
2008** embedded) and thus do not count as a statement terminator.  ^Whitespace
2009** and comments that follow the final semicolon are ignored.
2010**
2011** ^These routines return 0 if the statement is incomplete.  ^If a
2012** memory allocation fails, then SQLITE_NOMEM is returned.
2013**
2014** ^These routines do not parse the SQL statements thus
2015** will not detect syntactically incorrect SQL.
2016**
2017** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2018** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2019** automatically by sqlite3_complete16().  If that initialization fails,
2020** then the return value from sqlite3_complete16() will be non-zero
2021** regardless of whether or not the input SQL is complete.)^
2022**
2023** The input to [sqlite3_complete()] must be a zero-terminated
2024** UTF-8 string.
2025**
2026** The input to [sqlite3_complete16()] must be a zero-terminated
2027** UTF-16 string in native byte order.
2028*/
2029SQLITE_API int sqlite3_complete(const char *sql);
2030SQLITE_API int sqlite3_complete16(const void *sql);
2031
2032/*
2033** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2034**
2035** ^This routine sets a callback function that might be invoked whenever
2036** an attempt is made to open a database table that another thread
2037** or process has locked.
2038**
2039** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2040** is returned immediately upon encountering the lock.  ^If the busy callback
2041** is not NULL, then the callback might be invoked with two arguments.
2042**
2043** ^The first argument to the busy handler is a copy of the void* pointer which
2044** is the third argument to sqlite3_busy_handler().  ^The second argument to
2045** the busy handler callback is the number of times that the busy handler has
2046** been invoked for this locking event.  ^If the
2047** busy callback returns 0, then no additional attempts are made to
2048** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2049** ^If the callback returns non-zero, then another attempt
2050** is made to open the database for reading and the cycle repeats.
2051**
2052** The presence of a busy handler does not guarantee that it will be invoked
2053** when there is lock contention. ^If SQLite determines that invoking the busy
2054** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2055** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2056** Consider a scenario where one process is holding a read lock that
2057** it is trying to promote to a reserved lock and
2058** a second process is holding a reserved lock that it is trying
2059** to promote to an exclusive lock.  The first process cannot proceed
2060** because it is blocked by the second and the second process cannot
2061** proceed because it is blocked by the first.  If both processes
2062** invoke the busy handlers, neither will make any progress.  Therefore,
2063** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2064** will induce the first process to release its read lock and allow
2065** the second process to proceed.
2066**
2067** ^The default busy callback is NULL.
2068**
2069** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2070** when SQLite is in the middle of a large transaction where all the
2071** changes will not fit into the in-memory cache.  SQLite will
2072** already hold a RESERVED lock on the database file, but it needs
2073** to promote this lock to EXCLUSIVE so that it can spill cache
2074** pages into the database file without harm to concurrent
2075** readers.  ^If it is unable to promote the lock, then the in-memory
2076** cache will be left in an inconsistent state and so the error
2077** code is promoted from the relatively benign [SQLITE_BUSY] to
2078** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2079** forces an automatic rollback of the changes.  See the
2080** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2081** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2082** this is important.
2083**
2084** ^(There can only be a single busy handler defined for each
2085** [database connection].  Setting a new busy handler clears any
2086** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2087** will also set or clear the busy handler.
2088**
2089** The busy callback should not take any actions which modify the
2090** database connection that invoked the busy handler.  Any such actions
2091** result in undefined behavior.
2092**
2093** A busy handler must not close the database connection
2094** or [prepared statement] that invoked the busy handler.
2095*/
2096SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2097
2098/*
2099** CAPI3REF: Set A Busy Timeout
2100**
2101** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2102** for a specified amount of time when a table is locked.  ^The handler
2103** will sleep multiple times until at least "ms" milliseconds of sleeping
2104** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2105** the handler returns 0 which causes [sqlite3_step()] to return
2106** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2107**
2108** ^Calling this routine with an argument less than or equal to zero
2109** turns off all busy handlers.
2110**
2111** ^(There can only be a single busy handler for a particular
2112** [database connection] any any given moment.  If another busy handler
2113** was defined  (using [sqlite3_busy_handler()]) prior to calling
2114** this routine, that other busy handler is cleared.)^
2115*/
2116SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2117
2118/*
2119** CAPI3REF: Convenience Routines For Running Queries
2120**
2121** Definition: A <b>result table</b> is memory data structure created by the
2122** [sqlite3_get_table()] interface.  A result table records the
2123** complete query results from one or more queries.
2124**
2125** The table conceptually has a number of rows and columns.  But
2126** these numbers are not part of the result table itself.  These
2127** numbers are obtained separately.  Let N be the number of rows
2128** and M be the number of columns.
2129**
2130** A result table is an array of pointers to zero-terminated UTF-8 strings.
2131** There are (N+1)*M elements in the array.  The first M pointers point
2132** to zero-terminated strings that  contain the names of the columns.
2133** The remaining entries all point to query results.  NULL values result
2134** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2135** string representation as returned by [sqlite3_column_text()].
2136**
2137** A result table might consist of one or more memory allocations.
2138** It is not safe to pass a result table directly to [sqlite3_free()].
2139** A result table should be deallocated using [sqlite3_free_table()].
2140**
2141** As an example of the result table format, suppose a query result
2142** is as follows:
2143**
2144** <blockquote><pre>
2145**        Name        | Age
2146**        -----------------------
2147**        Alice       | 43
2148**        Bob         | 28
2149**        Cindy       | 21
2150** </pre></blockquote>
2151**
2152** There are two column (M==2) and three rows (N==3).  Thus the
2153** result table has 8 entries.  Suppose the result table is stored
2154** in an array names azResult.  Then azResult holds this content:
2155**
2156** <blockquote><pre>
2157**        azResult&#91;0] = "Name";
2158**        azResult&#91;1] = "Age";
2159**        azResult&#91;2] = "Alice";
2160**        azResult&#91;3] = "43";
2161**        azResult&#91;4] = "Bob";
2162**        azResult&#91;5] = "28";
2163**        azResult&#91;6] = "Cindy";
2164**        azResult&#91;7] = "21";
2165** </pre></blockquote>
2166**
2167** ^The sqlite3_get_table() function evaluates one or more
2168** semicolon-separated SQL statements in the zero-terminated UTF-8
2169** string of its 2nd parameter and returns a result table to the
2170** pointer given in its 3rd parameter.
2171**
2172** After the application has finished with the result from sqlite3_get_table(),
2173** it should pass the result table pointer to sqlite3_free_table() in order to
2174** release the memory that was malloced.  Because of the way the
2175** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2176** function must not try to call [sqlite3_free()] directly.  Only
2177** [sqlite3_free_table()] is able to release the memory properly and safely.
2178**
2179** ^(The sqlite3_get_table() interface is implemented as a wrapper around
2180** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2181** to any internal data structures of SQLite.  It uses only the public
2182** interface defined here.  As a consequence, errors that occur in the
2183** wrapper layer outside of the internal [sqlite3_exec()] call are not
2184** reflected in subsequent calls to [sqlite3_errcode()] or
2185** [sqlite3_errmsg()].)^
2186*/
2187SQLITE_API int sqlite3_get_table(
2188  sqlite3 *db,          /* An open database */
2189  const char *zSql,     /* SQL to be evaluated */
2190  char ***pazResult,    /* Results of the query */
2191  int *pnRow,           /* Number of result rows written here */
2192  int *pnColumn,        /* Number of result columns written here */
2193  char **pzErrmsg       /* Error msg written here */
2194);
2195SQLITE_API void sqlite3_free_table(char **result);
2196
2197/*
2198** CAPI3REF: Formatted String Printing Functions
2199**
2200** These routines are work-alikes of the "printf()" family of functions
2201** from the standard C library.
2202**
2203** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2204** results into memory obtained from [sqlite3_malloc()].
2205** The strings returned by these two routines should be
2206** released by [sqlite3_free()].  ^Both routines return a
2207** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2208** memory to hold the resulting string.
2209**
2210** ^(In sqlite3_snprintf() routine is similar to "snprintf()" from
2211** the standard C library.  The result is written into the
2212** buffer supplied as the second parameter whose size is given by
2213** the first parameter. Note that the order of the
2214** first two parameters is reversed from snprintf().)^  This is an
2215** historical accident that cannot be fixed without breaking
2216** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2217** returns a pointer to its buffer instead of the number of
2218** characters actually written into the buffer.)^  We admit that
2219** the number of characters written would be a more useful return
2220** value but we cannot change the implementation of sqlite3_snprintf()
2221** now without breaking compatibility.
2222**
2223** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2224** guarantees that the buffer is always zero-terminated.  ^The first
2225** parameter "n" is the total size of the buffer, including space for
2226** the zero terminator.  So the longest string that can be completely
2227** written will be n-1 characters.
2228**
2229** These routines all implement some additional formatting
2230** options that are useful for constructing SQL statements.
2231** All of the usual printf() formatting options apply.  In addition, there
2232** is are "%q", "%Q", and "%z" options.
2233**
2234** ^(The %q option works like %s in that it substitutes a null-terminated
2235** string from the argument list.  But %q also doubles every '\'' character.
2236** %q is designed for use inside a string literal.)^  By doubling each '\''
2237** character it escapes that character and allows it to be inserted into
2238** the string.
2239**
2240** For example, assume the string variable zText contains text as follows:
2241**
2242** <blockquote><pre>
2243**  char *zText = "It's a happy day!";
2244** </pre></blockquote>
2245**
2246** One can use this text in an SQL statement as follows:
2247**
2248** <blockquote><pre>
2249**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2250**  sqlite3_exec(db, zSQL, 0, 0, 0);
2251**  sqlite3_free(zSQL);
2252** </pre></blockquote>
2253**
2254** Because the %q format string is used, the '\'' character in zText
2255** is escaped and the SQL generated is as follows:
2256**
2257** <blockquote><pre>
2258**  INSERT INTO table1 VALUES('It''s a happy day!')
2259** </pre></blockquote>
2260**
2261** This is correct.  Had we used %s instead of %q, the generated SQL
2262** would have looked like this:
2263**
2264** <blockquote><pre>
2265**  INSERT INTO table1 VALUES('It's a happy day!');
2266** </pre></blockquote>
2267**
2268** This second example is an SQL syntax error.  As a general rule you should
2269** always use %q instead of %s when inserting text into a string literal.
2270**
2271** ^(The %Q option works like %q except it also adds single quotes around
2272** the outside of the total string.  Additionally, if the parameter in the
2273** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2274** single quotes).)^  So, for example, one could say:
2275**
2276** <blockquote><pre>
2277**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2278**  sqlite3_exec(db, zSQL, 0, 0, 0);
2279**  sqlite3_free(zSQL);
2280** </pre></blockquote>
2281**
2282** The code above will render a correct SQL statement in the zSQL
2283** variable even if the zText variable is a NULL pointer.
2284**
2285** ^(The "%z" formatting option works like "%s" but with the
2286** addition that after the string has been read and copied into
2287** the result, [sqlite3_free()] is called on the input string.)^
2288*/
2289SQLITE_API char *sqlite3_mprintf(const char*,...);
2290SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2291SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2292
2293/*
2294** CAPI3REF: Memory Allocation Subsystem
2295**
2296** The SQLite core uses these three routines for all of its own
2297** internal memory allocation needs. "Core" in the previous sentence
2298** does not include operating-system specific VFS implementation.  The
2299** Windows VFS uses native malloc() and free() for some operations.
2300**
2301** ^The sqlite3_malloc() routine returns a pointer to a block
2302** of memory at least N bytes in length, where N is the parameter.
2303** ^If sqlite3_malloc() is unable to obtain sufficient free
2304** memory, it returns a NULL pointer.  ^If the parameter N to
2305** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2306** a NULL pointer.
2307**
2308** ^Calling sqlite3_free() with a pointer previously returned
2309** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2310** that it might be reused.  ^The sqlite3_free() routine is
2311** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2312** to sqlite3_free() is harmless.  After being freed, memory
2313** should neither be read nor written.  Even reading previously freed
2314** memory might result in a segmentation fault or other severe error.
2315** Memory corruption, a segmentation fault, or other severe error
2316** might result if sqlite3_free() is called with a non-NULL pointer that
2317** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2318**
2319** ^(The sqlite3_realloc() interface attempts to resize a
2320** prior memory allocation to be at least N bytes, where N is the
2321** second parameter.  The memory allocation to be resized is the first
2322** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2323** is a NULL pointer then its behavior is identical to calling
2324** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2325** ^If the second parameter to sqlite3_realloc() is zero or
2326** negative then the behavior is exactly the same as calling
2327** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2328** ^sqlite3_realloc() returns a pointer to a memory allocation
2329** of at least N bytes in size or NULL if sufficient memory is unavailable.
2330** ^If M is the size of the prior allocation, then min(N,M) bytes
2331** of the prior allocation are copied into the beginning of buffer returned
2332** by sqlite3_realloc() and the prior allocation is freed.
2333** ^If sqlite3_realloc() returns NULL, then the prior allocation
2334** is not freed.
2335**
2336** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2337** is always aligned to at least an 8 byte boundary.
2338**
2339** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2340** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2341** implementation of these routines to be omitted.  That capability
2342** is no longer provided.  Only built-in memory allocators can be used.
2343**
2344** The Windows OS interface layer calls
2345** the system malloc() and free() directly when converting
2346** filenames between the UTF-8 encoding used by SQLite
2347** and whatever filename encoding is used by the particular Windows
2348** installation.  Memory allocation errors are detected, but
2349** they are reported back as [SQLITE_CANTOPEN] or
2350** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2351**
2352** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2353** must be either NULL or else pointers obtained from a prior
2354** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2355** not yet been released.
2356**
2357** The application must not read or write any part of
2358** a block of memory after it has been released using
2359** [sqlite3_free()] or [sqlite3_realloc()].
2360*/
2361SQLITE_API void *sqlite3_malloc(int);
2362SQLITE_API void *sqlite3_realloc(void*, int);
2363SQLITE_API void sqlite3_free(void*);
2364
2365/*
2366** CAPI3REF: Memory Allocator Statistics
2367**
2368** SQLite provides these two interfaces for reporting on the status
2369** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2370** routines, which form the built-in memory allocation subsystem.
2371**
2372** ^The [sqlite3_memory_used()] routine returns the number of bytes
2373** of memory currently outstanding (malloced but not freed).
2374** ^The [sqlite3_memory_highwater()] routine returns the maximum
2375** value of [sqlite3_memory_used()] since the high-water mark
2376** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2377** [sqlite3_memory_highwater()] include any overhead
2378** added by SQLite in its implementation of [sqlite3_malloc()],
2379** but not overhead added by the any underlying system library
2380** routines that [sqlite3_malloc()] may call.
2381**
2382** ^The memory high-water mark is reset to the current value of
2383** [sqlite3_memory_used()] if and only if the parameter to
2384** [sqlite3_memory_highwater()] is true.  ^The value returned
2385** by [sqlite3_memory_highwater(1)] is the high-water mark
2386** prior to the reset.
2387*/
2388SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2389SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2390
2391/*
2392** CAPI3REF: Pseudo-Random Number Generator
2393**
2394** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2395** select random [ROWID | ROWIDs] when inserting new records into a table that
2396** already uses the largest possible [ROWID].  The PRNG is also used for
2397** the build-in random() and randomblob() SQL functions.  This interface allows
2398** applications to access the same PRNG for other purposes.
2399**
2400** ^A call to this routine stores N bytes of randomness into buffer P.
2401**
2402** ^The first time this routine is invoked (either internally or by
2403** the application) the PRNG is seeded using randomness obtained
2404** from the xRandomness method of the default [sqlite3_vfs] object.
2405** ^On all subsequent invocations, the pseudo-randomness is generated
2406** internally and without recourse to the [sqlite3_vfs] xRandomness
2407** method.
2408*/
2409SQLITE_API void sqlite3_randomness(int N, void *P);
2410
2411/*
2412** CAPI3REF: Compile-Time Authorization Callbacks
2413**
2414** ^This routine registers a authorizer callback with a particular
2415** [database connection], supplied in the first argument.
2416** ^The authorizer callback is invoked as SQL statements are being compiled
2417** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2418** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2419** points during the compilation process, as logic is being created
2420** to perform various actions, the authorizer callback is invoked to
2421** see if those actions are allowed.  ^The authorizer callback should
2422** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2423** specific action but allow the SQL statement to continue to be
2424** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2425** rejected with an error.  ^If the authorizer callback returns
2426** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2427** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2428** the authorizer will fail with an error message.
2429**
2430** When the callback returns [SQLITE_OK], that means the operation
2431** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2432** [sqlite3_prepare_v2()] or equivalent call that triggered the
2433** authorizer will fail with an error message explaining that
2434** access is denied.
2435**
2436** ^The first parameter to the authorizer callback is a copy of the third
2437** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2438** to the callback is an integer [SQLITE_COPY | action code] that specifies
2439** the particular action to be authorized. ^The third through sixth parameters
2440** to the callback are zero-terminated strings that contain additional
2441** details about the action to be authorized.
2442**
2443** ^If the action code is [SQLITE_READ]
2444** and the callback returns [SQLITE_IGNORE] then the
2445** [prepared statement] statement is constructed to substitute
2446** a NULL value in place of the table column that would have
2447** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2448** return can be used to deny an untrusted user access to individual
2449** columns of a table.
2450** ^If the action code is [SQLITE_DELETE] and the callback returns
2451** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2452** [truncate optimization] is disabled and all rows are deleted individually.
2453**
2454** An authorizer is used when [sqlite3_prepare | preparing]
2455** SQL statements from an untrusted source, to ensure that the SQL statements
2456** do not try to access data they are not allowed to see, or that they do not
2457** try to execute malicious statements that damage the database.  For
2458** example, an application may allow a user to enter arbitrary
2459** SQL queries for evaluation by a database.  But the application does
2460** not want the user to be able to make arbitrary changes to the
2461** database.  An authorizer could then be put in place while the
2462** user-entered SQL is being [sqlite3_prepare | prepared] that
2463** disallows everything except [SELECT] statements.
2464**
2465** Applications that need to process SQL from untrusted sources
2466** might also consider lowering resource limits using [sqlite3_limit()]
2467** and limiting database size using the [max_page_count] [PRAGMA]
2468** in addition to using an authorizer.
2469**
2470** ^(Only a single authorizer can be in place on a database connection
2471** at a time.  Each call to sqlite3_set_authorizer overrides the
2472** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2473** The authorizer is disabled by default.
2474**
2475** The authorizer callback must not do anything that will modify
2476** the database connection that invoked the authorizer callback.
2477** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2478** database connections for the meaning of "modify" in this paragraph.
2479**
2480** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2481** statement might be re-prepared during [sqlite3_step()] due to a
2482** schema change.  Hence, the application should ensure that the
2483** correct authorizer callback remains in place during the [sqlite3_step()].
2484**
2485** ^Note that the authorizer callback is invoked only during
2486** [sqlite3_prepare()] or its variants.  Authorization is not
2487** performed during statement evaluation in [sqlite3_step()], unless
2488** as stated in the previous paragraph, sqlite3_step() invokes
2489** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2490*/
2491SQLITE_API int sqlite3_set_authorizer(
2492  sqlite3*,
2493  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2494  void *pUserData
2495);
2496
2497/*
2498** CAPI3REF: Authorizer Return Codes
2499**
2500** The [sqlite3_set_authorizer | authorizer callback function] must
2501** return either [SQLITE_OK] or one of these two constants in order
2502** to signal SQLite whether or not the action is permitted.  See the
2503** [sqlite3_set_authorizer | authorizer documentation] for additional
2504** information.
2505*/
2506#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2507#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2508
2509/*
2510** CAPI3REF: Authorizer Action Codes
2511**
2512** The [sqlite3_set_authorizer()] interface registers a callback function
2513** that is invoked to authorize certain SQL statement actions.  The
2514** second parameter to the callback is an integer code that specifies
2515** what action is being authorized.  These are the integer action codes that
2516** the authorizer callback may be passed.
2517**
2518** These action code values signify what kind of operation is to be
2519** authorized.  The 3rd and 4th parameters to the authorization
2520** callback function will be parameters or NULL depending on which of these
2521** codes is used as the second parameter.  ^(The 5th parameter to the
2522** authorizer callback is the name of the database ("main", "temp",
2523** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2524** is the name of the inner-most trigger or view that is responsible for
2525** the access attempt or NULL if this access attempt is directly from
2526** top-level SQL code.
2527*/
2528/******************************************* 3rd ************ 4th ***********/
2529#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2530#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2531#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2532#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2533#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2534#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2535#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2536#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2537#define SQLITE_DELETE                9   /* Table Name      NULL            */
2538#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2539#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2540#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2541#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2542#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2543#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2544#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2545#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2546#define SQLITE_INSERT               18   /* Table Name      NULL            */
2547#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2548#define SQLITE_READ                 20   /* Table Name      Column Name     */
2549#define SQLITE_SELECT               21   /* NULL            NULL            */
2550#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2551#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2552#define SQLITE_ATTACH               24   /* Filename        NULL            */
2553#define SQLITE_DETACH               25   /* Database Name   NULL            */
2554#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2555#define SQLITE_REINDEX              27   /* Index Name      NULL            */
2556#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2557#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2558#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2559#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2560#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2561#define SQLITE_COPY                  0   /* No longer used */
2562
2563/*
2564** CAPI3REF: Tracing And Profiling Functions
2565** EXPERIMENTAL
2566**
2567** These routines register callback functions that can be used for
2568** tracing and profiling the execution of SQL statements.
2569**
2570** ^The callback function registered by sqlite3_trace() is invoked at
2571** various times when an SQL statement is being run by [sqlite3_step()].
2572** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2573** SQL statement text as the statement first begins executing.
2574** ^(Additional sqlite3_trace() callbacks might occur
2575** as each triggered subprogram is entered.  The callbacks for triggers
2576** contain a UTF-8 SQL comment that identifies the trigger.)^
2577**
2578** ^The callback function registered by sqlite3_profile() is invoked
2579** as each SQL statement finishes.  ^The profile callback contains
2580** the original statement text and an estimate of wall-clock time
2581** of how long that statement took to run.
2582*/
2583SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2584SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2585   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2586
2587/*
2588** CAPI3REF: Query Progress Callbacks
2589**
2590** ^This routine configures a callback function - the
2591** progress callback - that is invoked periodically during long
2592** running calls to [sqlite3_exec()], [sqlite3_step()] and
2593** [sqlite3_get_table()].  An example use for this
2594** interface is to keep a GUI updated during a large query.
2595**
2596** ^If the progress callback returns non-zero, the operation is
2597** interrupted.  This feature can be used to implement a
2598** "Cancel" button on a GUI progress dialog box.
2599**
2600** The progress handler must not do anything that will modify
2601** the database connection that invoked the progress handler.
2602** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2603** database connections for the meaning of "modify" in this paragraph.
2604**
2605*/
2606SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2607
2608/*
2609** CAPI3REF: Opening A New Database Connection
2610**
2611** ^These routines open an SQLite database file whose name is given by the
2612** filename argument. ^The filename argument is interpreted as UTF-8 for
2613** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2614** order for sqlite3_open16(). ^(A [database connection] handle is usually
2615** returned in *ppDb, even if an error occurs.  The only exception is that
2616** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2617** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2618** object.)^ ^(If the database is opened (and/or created) successfully, then
2619** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2620** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2621** an English language description of the error following a failure of any
2622** of the sqlite3_open() routines.
2623**
2624** ^The default encoding for the database will be UTF-8 if
2625** sqlite3_open() or sqlite3_open_v2() is called and
2626** UTF-16 in the native byte order if sqlite3_open16() is used.
2627**
2628** Whether or not an error occurs when it is opened, resources
2629** associated with the [database connection] handle should be released by
2630** passing it to [sqlite3_close()] when it is no longer required.
2631**
2632** The sqlite3_open_v2() interface works like sqlite3_open()
2633** except that it accepts two additional parameters for additional control
2634** over the new database connection.  ^(The flags parameter to
2635** sqlite3_open_v2() can take one of
2636** the following three values, optionally combined with the
2637** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2638** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
2639**
2640** <dl>
2641** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2642** <dd>The database is opened in read-only mode.  If the database does not
2643** already exist, an error is returned.</dd>)^
2644**
2645** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2646** <dd>The database is opened for reading and writing if possible, or reading
2647** only if the file is write protected by the operating system.  In either
2648** case the database must already exist, otherwise an error is returned.</dd>)^
2649**
2650** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2651** <dd>The database is opened for reading and writing, and is creates it if
2652** it does not already exist. This is the behavior that is always used for
2653** sqlite3_open() and sqlite3_open16().</dd>)^
2654** </dl>
2655**
2656** If the 3rd parameter to sqlite3_open_v2() is not one of the
2657** combinations shown above or one of the combinations shown above combined
2658** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2659** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
2660** then the behavior is undefined.
2661**
2662** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2663** opens in the multi-thread [threading mode] as long as the single-thread
2664** mode has not been set at compile-time or start-time.  ^If the
2665** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2666** in the serialized [threading mode] unless single-thread was
2667** previously selected at compile-time or start-time.
2668** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2669** eligible to use [shared cache mode], regardless of whether or not shared
2670** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2671** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2672** participate in [shared cache mode] even if it is enabled.
2673**
2674** ^If the filename is ":memory:", then a private, temporary in-memory database
2675** is created for the connection.  ^This in-memory database will vanish when
2676** the database connection is closed.  Future versions of SQLite might
2677** make use of additional special filenames that begin with the ":" character.
2678** It is recommended that when a database filename actually does begin with
2679** a ":" character you should prefix the filename with a pathname such as
2680** "./" to avoid ambiguity.
2681**
2682** ^If the filename is an empty string, then a private, temporary
2683** on-disk database will be created.  ^This private database will be
2684** automatically deleted as soon as the database connection is closed.
2685**
2686** ^The fourth parameter to sqlite3_open_v2() is the name of the
2687** [sqlite3_vfs] object that defines the operating system interface that
2688** the new database connection should use.  ^If the fourth parameter is
2689** a NULL pointer then the default [sqlite3_vfs] object is used.
2690**
2691** <b>Note to Windows users:</b>  The encoding used for the filename argument
2692** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2693** codepage is currently defined.  Filenames containing international
2694** characters must be converted to UTF-8 prior to passing them into
2695** sqlite3_open() or sqlite3_open_v2().
2696*/
2697SQLITE_API int sqlite3_open(
2698  const char *filename,   /* Database filename (UTF-8) */
2699  sqlite3 **ppDb          /* OUT: SQLite db handle */
2700);
2701SQLITE_API int sqlite3_open16(
2702  const void *filename,   /* Database filename (UTF-16) */
2703  sqlite3 **ppDb          /* OUT: SQLite db handle */
2704);
2705SQLITE_API int sqlite3_open_v2(
2706  const char *filename,   /* Database filename (UTF-8) */
2707  sqlite3 **ppDb,         /* OUT: SQLite db handle */
2708  int flags,              /* Flags */
2709  const char *zVfs        /* Name of VFS module to use */
2710);
2711
2712/*
2713** CAPI3REF: Error Codes And Messages
2714**
2715** ^The sqlite3_errcode() interface returns the numeric [result code] or
2716** [extended result code] for the most recent failed sqlite3_* API call
2717** associated with a [database connection]. If a prior API call failed
2718** but the most recent API call succeeded, the return value from
2719** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
2720** interface is the same except that it always returns the
2721** [extended result code] even when extended result codes are
2722** disabled.
2723**
2724** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2725** text that describes the error, as either UTF-8 or UTF-16 respectively.
2726** ^(Memory to hold the error message string is managed internally.
2727** The application does not need to worry about freeing the result.
2728** However, the error string might be overwritten or deallocated by
2729** subsequent calls to other SQLite interface functions.)^
2730**
2731** When the serialized [threading mode] is in use, it might be the
2732** case that a second error occurs on a separate thread in between
2733** the time of the first error and the call to these interfaces.
2734** When that happens, the second error will be reported since these
2735** interfaces always report the most recent result.  To avoid
2736** this, each thread can obtain exclusive use of the [database connection] D
2737** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2738** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2739** all calls to the interfaces listed here are completed.
2740**
2741** If an interface fails with SQLITE_MISUSE, that means the interface
2742** was invoked incorrectly by the application.  In that case, the
2743** error code and message may or may not be set.
2744*/
2745SQLITE_API int sqlite3_errcode(sqlite3 *db);
2746SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
2747SQLITE_API const char *sqlite3_errmsg(sqlite3*);
2748SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
2749
2750/*
2751** CAPI3REF: SQL Statement Object
2752** KEYWORDS: {prepared statement} {prepared statements}
2753**
2754** An instance of this object represents a single SQL statement.
2755** This object is variously known as a "prepared statement" or a
2756** "compiled SQL statement" or simply as a "statement".
2757**
2758** The life of a statement object goes something like this:
2759**
2760** <ol>
2761** <li> Create the object using [sqlite3_prepare_v2()] or a related
2762**      function.
2763** <li> Bind values to [host parameters] using the sqlite3_bind_*()
2764**      interfaces.
2765** <li> Run the SQL by calling [sqlite3_step()] one or more times.
2766** <li> Reset the statement using [sqlite3_reset()] then go back
2767**      to step 2.  Do this zero or more times.
2768** <li> Destroy the object using [sqlite3_finalize()].
2769** </ol>
2770**
2771** Refer to documentation on individual methods above for additional
2772** information.
2773*/
2774typedef struct sqlite3_stmt sqlite3_stmt;
2775
2776/*
2777** CAPI3REF: Run-time Limits
2778**
2779** ^(This interface allows the size of various constructs to be limited
2780** on a connection by connection basis.  The first parameter is the
2781** [database connection] whose limit is to be set or queried.  The
2782** second parameter is one of the [limit categories] that define a
2783** class of constructs to be size limited.  The third parameter is the
2784** new limit for that construct.  The function returns the old limit.)^
2785**
2786** ^If the new limit is a negative number, the limit is unchanged.
2787** ^(For the limit category of SQLITE_LIMIT_XYZ there is a
2788** [limits | hard upper bound]
2789** set by a compile-time C preprocessor macro named
2790** [limits | SQLITE_MAX_XYZ].
2791** (The "_LIMIT_" in the name is changed to "_MAX_".))^
2792** ^Attempts to increase a limit above its hard upper bound are
2793** silently truncated to the hard upper bound.
2794**
2795** Run-time limits are intended for use in applications that manage
2796** both their own internal database and also databases that are controlled
2797** by untrusted external sources.  An example application might be a
2798** web browser that has its own databases for storing history and
2799** separate databases controlled by JavaScript applications downloaded
2800** off the Internet.  The internal databases can be given the
2801** large, default limits.  Databases managed by external sources can
2802** be given much smaller limits designed to prevent a denial of service
2803** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
2804** interface to further control untrusted SQL.  The size of the database
2805** created by an untrusted script can be contained using the
2806** [max_page_count] [PRAGMA].
2807**
2808** New run-time limit categories may be added in future releases.
2809*/
2810SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
2811
2812/*
2813** CAPI3REF: Run-Time Limit Categories
2814** KEYWORDS: {limit category} {*limit categories}
2815**
2816** These constants define various performance limits
2817** that can be lowered at run-time using [sqlite3_limit()].
2818** The synopsis of the meanings of the various limits is shown below.
2819** Additional information is available at [limits | Limits in SQLite].
2820**
2821** <dl>
2822** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
2823** <dd>The maximum size of any string or BLOB or table row.<dd>)^
2824**
2825** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
2826** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
2827**
2828** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
2829** <dd>The maximum number of columns in a table definition or in the
2830** result set of a [SELECT] or the maximum number of columns in an index
2831** or in an ORDER BY or GROUP BY clause.</dd>)^
2832**
2833** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
2834** <dd>The maximum depth of the parse tree on any expression.</dd>)^
2835**
2836** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
2837** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
2838**
2839** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
2840** <dd>The maximum number of instructions in a virtual machine program
2841** used to implement an SQL statement.</dd>)^
2842**
2843** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
2844** <dd>The maximum number of arguments on a function.</dd>)^
2845**
2846** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
2847** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
2848**
2849** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
2850** <dd>The maximum length of the pattern argument to the [LIKE] or
2851** [GLOB] operators.</dd>)^
2852**
2853** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
2854** <dd>The maximum number of variables in an SQL statement that can
2855** be bound.</dd>)^
2856**
2857** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
2858** <dd>The maximum depth of recursion for triggers.</dd>)^
2859** </dl>
2860*/
2861#define SQLITE_LIMIT_LENGTH                    0
2862#define SQLITE_LIMIT_SQL_LENGTH                1
2863#define SQLITE_LIMIT_COLUMN                    2
2864#define SQLITE_LIMIT_EXPR_DEPTH                3
2865#define SQLITE_LIMIT_COMPOUND_SELECT           4
2866#define SQLITE_LIMIT_VDBE_OP                   5
2867#define SQLITE_LIMIT_FUNCTION_ARG              6
2868#define SQLITE_LIMIT_ATTACHED                  7
2869#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
2870#define SQLITE_LIMIT_VARIABLE_NUMBER           9
2871#define SQLITE_LIMIT_TRIGGER_DEPTH            10
2872
2873/*
2874** CAPI3REF: Compiling An SQL Statement
2875** KEYWORDS: {SQL statement compiler}
2876**
2877** To execute an SQL query, it must first be compiled into a byte-code
2878** program using one of these routines.
2879**
2880** The first argument, "db", is a [database connection] obtained from a
2881** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
2882** [sqlite3_open16()].  The database connection must not have been closed.
2883**
2884** The second argument, "zSql", is the statement to be compiled, encoded
2885** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
2886** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
2887** use UTF-16.
2888**
2889** ^If the nByte argument is less than zero, then zSql is read up to the
2890** first zero terminator. ^If nByte is non-negative, then it is the maximum
2891** number of  bytes read from zSql.  ^When nByte is non-negative, the
2892** zSql string ends at either the first '\000' or '\u0000' character or
2893** the nByte-th byte, whichever comes first. If the caller knows
2894** that the supplied string is nul-terminated, then there is a small
2895** performance advantage to be gained by passing an nByte parameter that
2896** is equal to the number of bytes in the input string <i>including</i>
2897** the nul-terminator bytes.
2898**
2899** ^If pzTail is not NULL then *pzTail is made to point to the first byte
2900** past the end of the first SQL statement in zSql.  These routines only
2901** compile the first statement in zSql, so *pzTail is left pointing to
2902** what remains uncompiled.
2903**
2904** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
2905** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
2906** to NULL.  ^If the input text contains no SQL (if the input is an empty
2907** string or a comment) then *ppStmt is set to NULL.
2908** The calling procedure is responsible for deleting the compiled
2909** SQL statement using [sqlite3_finalize()] after it has finished with it.
2910** ppStmt may not be NULL.
2911**
2912** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
2913** otherwise an [error code] is returned.
2914**
2915** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
2916** recommended for all new programs. The two older interfaces are retained
2917** for backwards compatibility, but their use is discouraged.
2918** ^In the "v2" interfaces, the prepared statement
2919** that is returned (the [sqlite3_stmt] object) contains a copy of the
2920** original SQL text. This causes the [sqlite3_step()] interface to
2921** behave differently in three ways:
2922**
2923** <ol>
2924** <li>
2925** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
2926** always used to do, [sqlite3_step()] will automatically recompile the SQL
2927** statement and try to run it again.  ^If the schema has changed in
2928** a way that makes the statement no longer valid, [sqlite3_step()] will still
2929** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
2930** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
2931** error go away.  Note: use [sqlite3_errmsg()] to find the text
2932** of the parsing error that results in an [SQLITE_SCHEMA] return.
2933** </li>
2934**
2935** <li>
2936** ^When an error occurs, [sqlite3_step()] will return one of the detailed
2937** [error codes] or [extended error codes].  ^The legacy behavior was that
2938** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
2939** and the application would have to make a second call to [sqlite3_reset()]
2940** in order to find the underlying cause of the problem. With the "v2" prepare
2941** interfaces, the underlying reason for the error is returned immediately.
2942** </li>
2943**
2944** <li>
2945** ^If the value of a [parameter | host parameter] in the WHERE clause might
2946** change the query plan for a statement, then the statement may be
2947** automatically recompiled (as if there had been a schema change) on the first
2948** [sqlite3_step()] call following any change to the
2949** [sqlite3_bind_text | bindings] of the [parameter].
2950** </li>
2951** </ol>
2952*/
2953SQLITE_API int sqlite3_prepare(
2954  sqlite3 *db,            /* Database handle */
2955  const char *zSql,       /* SQL statement, UTF-8 encoded */
2956  int nByte,              /* Maximum length of zSql in bytes. */
2957  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2958  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
2959);
2960SQLITE_API int sqlite3_prepare_v2(
2961  sqlite3 *db,            /* Database handle */
2962  const char *zSql,       /* SQL statement, UTF-8 encoded */
2963  int nByte,              /* Maximum length of zSql in bytes. */
2964  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2965  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
2966);
2967SQLITE_API int sqlite3_prepare16(
2968  sqlite3 *db,            /* Database handle */
2969  const void *zSql,       /* SQL statement, UTF-16 encoded */
2970  int nByte,              /* Maximum length of zSql in bytes. */
2971  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2972  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
2973);
2974SQLITE_API int sqlite3_prepare16_v2(
2975  sqlite3 *db,            /* Database handle */
2976  const void *zSql,       /* SQL statement, UTF-16 encoded */
2977  int nByte,              /* Maximum length of zSql in bytes. */
2978  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2979  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
2980);
2981
2982/*
2983** CAPI3REF: Retrieving Statement SQL
2984**
2985** ^This interface can be used to retrieve a saved copy of the original
2986** SQL text used to create a [prepared statement] if that statement was
2987** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
2988*/
2989SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
2990
2991/*
2992** CAPI3REF: Dynamically Typed Value Object
2993** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
2994**
2995** SQLite uses the sqlite3_value object to represent all values
2996** that can be stored in a database table. SQLite uses dynamic typing
2997** for the values it stores.  ^Values stored in sqlite3_value objects
2998** can be integers, floating point values, strings, BLOBs, or NULL.
2999**
3000** An sqlite3_value object may be either "protected" or "unprotected".
3001** Some interfaces require a protected sqlite3_value.  Other interfaces
3002** will accept either a protected or an unprotected sqlite3_value.
3003** Every interface that accepts sqlite3_value arguments specifies
3004** whether or not it requires a protected sqlite3_value.
3005**
3006** The terms "protected" and "unprotected" refer to whether or not
3007** a mutex is held.  A internal mutex is held for a protected
3008** sqlite3_value object but no mutex is held for an unprotected
3009** sqlite3_value object.  If SQLite is compiled to be single-threaded
3010** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3011** or if SQLite is run in one of reduced mutex modes
3012** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3013** then there is no distinction between protected and unprotected
3014** sqlite3_value objects and they can be used interchangeably.  However,
3015** for maximum code portability it is recommended that applications
3016** still make the distinction between between protected and unprotected
3017** sqlite3_value objects even when not strictly required.
3018**
3019** ^The sqlite3_value objects that are passed as parameters into the
3020** implementation of [application-defined SQL functions] are protected.
3021** ^The sqlite3_value object returned by
3022** [sqlite3_column_value()] is unprotected.
3023** Unprotected sqlite3_value objects may only be used with
3024** [sqlite3_result_value()] and [sqlite3_bind_value()].
3025** The [sqlite3_value_blob | sqlite3_value_type()] family of
3026** interfaces require protected sqlite3_value objects.
3027*/
3028typedef struct Mem sqlite3_value;
3029
3030/*
3031** CAPI3REF: SQL Function Context Object
3032**
3033** The context in which an SQL function executes is stored in an
3034** sqlite3_context object.  ^A pointer to an sqlite3_context object
3035** is always first parameter to [application-defined SQL functions].
3036** The application-defined SQL function implementation will pass this
3037** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3038** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3039** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3040** and/or [sqlite3_set_auxdata()].
3041*/
3042typedef struct sqlite3_context sqlite3_context;
3043
3044/*
3045** CAPI3REF: Binding Values To Prepared Statements
3046** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3047** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3048**
3049** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3050** literals may be replaced by a [parameter] that matches one of following
3051** templates:
3052**
3053** <ul>
3054** <li>  ?
3055** <li>  ?NNN
3056** <li>  :VVV
3057** <li>  @VVV
3058** <li>  $VVV
3059** </ul>
3060**
3061** In the templates above, NNN represents an integer literal,
3062** and VVV represents an alphanumeric identifer.)^  ^The values of these
3063** parameters (also called "host parameter names" or "SQL parameters")
3064** can be set using the sqlite3_bind_*() routines defined here.
3065**
3066** ^The first argument to the sqlite3_bind_*() routines is always
3067** a pointer to the [sqlite3_stmt] object returned from
3068** [sqlite3_prepare_v2()] or its variants.
3069**
3070** ^The second argument is the index of the SQL parameter to be set.
3071** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3072** SQL parameter is used more than once, second and subsequent
3073** occurrences have the same index as the first occurrence.
3074** ^The index for named parameters can be looked up using the
3075** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3076** for "?NNN" parameters is the value of NNN.
3077** ^The NNN value must be between 1 and the [sqlite3_limit()]
3078** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3079**
3080** ^The third argument is the value to bind to the parameter.
3081**
3082** ^(In those routines that have a fourth argument, its value is the
3083** number of bytes in the parameter.  To be clear: the value is the
3084** number of <u>bytes</u> in the value, not the number of characters.)^
3085** ^If the fourth parameter is negative, the length of the string is
3086** the number of bytes up to the first zero terminator.
3087**
3088** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3089** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3090** string after SQLite has finished with it. ^If the fifth argument is
3091** the special value [SQLITE_STATIC], then SQLite assumes that the
3092** information is in static, unmanaged space and does not need to be freed.
3093** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3094** SQLite makes its own private copy of the data immediately, before
3095** the sqlite3_bind_*() routine returns.
3096**
3097** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3098** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3099** (just an integer to hold its size) while it is being processed.
3100** Zeroblobs are intended to serve as placeholders for BLOBs whose
3101** content is later written using
3102** [sqlite3_blob_open | incremental BLOB I/O] routines.
3103** ^A negative value for the zeroblob results in a zero-length BLOB.
3104**
3105** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3106** for the [prepared statement] or with a prepared statement for which
3107** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3108** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3109** routine is passed a [prepared statement] that has been finalized, the
3110** result is undefined and probably harmful.
3111**
3112** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3113** ^Unbound parameters are interpreted as NULL.
3114**
3115** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3116** [error code] if anything goes wrong.
3117** ^[SQLITE_RANGE] is returned if the parameter
3118** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3119**
3120** See also: [sqlite3_bind_parameter_count()],
3121** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3122*/
3123SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3124SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3125SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3126SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3127SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3128SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3129SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3130SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3131SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3132
3133/*
3134** CAPI3REF: Number Of SQL Parameters
3135**
3136** ^This routine can be used to find the number of [SQL parameters]
3137** in a [prepared statement].  SQL parameters are tokens of the
3138** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3139** placeholders for values that are [sqlite3_bind_blob | bound]
3140** to the parameters at a later time.
3141**
3142** ^(This routine actually returns the index of the largest (rightmost)
3143** parameter. For all forms except ?NNN, this will correspond to the
3144** number of unique parameters.  If parameters of the ?NNN form are used,
3145** there may be gaps in the list.)^
3146**
3147** See also: [sqlite3_bind_blob|sqlite3_bind()],
3148** [sqlite3_bind_parameter_name()], and
3149** [sqlite3_bind_parameter_index()].
3150*/
3151SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3152
3153/*
3154** CAPI3REF: Name Of A Host Parameter
3155**
3156** ^The sqlite3_bind_parameter_name(P,N) interface returns
3157** the name of the N-th [SQL parameter] in the [prepared statement] P.
3158** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3159** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3160** respectively.
3161** In other words, the initial ":" or "$" or "@" or "?"
3162** is included as part of the name.)^
3163** ^Parameters of the form "?" without a following integer have no name
3164** and are referred to as "nameless" or "anonymous parameters".
3165**
3166** ^The first host parameter has an index of 1, not 0.
3167**
3168** ^If the value N is out of range or if the N-th parameter is
3169** nameless, then NULL is returned.  ^The returned string is
3170** always in UTF-8 encoding even if the named parameter was
3171** originally specified as UTF-16 in [sqlite3_prepare16()] or
3172** [sqlite3_prepare16_v2()].
3173**
3174** See also: [sqlite3_bind_blob|sqlite3_bind()],
3175** [sqlite3_bind_parameter_count()], and
3176** [sqlite3_bind_parameter_index()].
3177*/
3178SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3179
3180/*
3181** CAPI3REF: Index Of A Parameter With A Given Name
3182**
3183** ^Return the index of an SQL parameter given its name.  ^The
3184** index value returned is suitable for use as the second
3185** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3186** is returned if no matching parameter is found.  ^The parameter
3187** name must be given in UTF-8 even if the original statement
3188** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3189**
3190** See also: [sqlite3_bind_blob|sqlite3_bind()],
3191** [sqlite3_bind_parameter_count()], and
3192** [sqlite3_bind_parameter_index()].
3193*/
3194SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3195
3196/*
3197** CAPI3REF: Reset All Bindings On A Prepared Statement
3198**
3199** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3200** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3201** ^Use this routine to reset all host parameters to NULL.
3202*/
3203SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3204
3205/*
3206** CAPI3REF: Number Of Columns In A Result Set
3207**
3208** ^Return the number of columns in the result set returned by the
3209** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3210** statement that does not return data (for example an [UPDATE]).
3211*/
3212SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3213
3214/*
3215** CAPI3REF: Column Names In A Result Set
3216**
3217** ^These routines return the name assigned to a particular column
3218** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3219** interface returns a pointer to a zero-terminated UTF-8 string
3220** and sqlite3_column_name16() returns a pointer to a zero-terminated
3221** UTF-16 string.  ^The first parameter is the [prepared statement]
3222** that implements the [SELECT] statement. ^The second parameter is the
3223** column number.  ^The leftmost column is number 0.
3224**
3225** ^The returned string pointer is valid until either the [prepared statement]
3226** is destroyed by [sqlite3_finalize()] or until the next call to
3227** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3228**
3229** ^If sqlite3_malloc() fails during the processing of either routine
3230** (for example during a conversion from UTF-8 to UTF-16) then a
3231** NULL pointer is returned.
3232**
3233** ^The name of a result column is the value of the "AS" clause for
3234** that column, if there is an AS clause.  If there is no AS clause
3235** then the name of the column is unspecified and may change from
3236** one release of SQLite to the next.
3237*/
3238SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3239SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3240
3241/*
3242** CAPI3REF: Source Of Data In A Query Result
3243**
3244** ^These routines provide a means to determine the database, table, and
3245** table column that is the origin of a particular result column in
3246** [SELECT] statement.
3247** ^The name of the database or table or column can be returned as
3248** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3249** the database name, the _table_ routines return the table name, and
3250** the origin_ routines return the column name.
3251** ^The returned string is valid until the [prepared statement] is destroyed
3252** using [sqlite3_finalize()] or until the same information is requested
3253** again in a different encoding.
3254**
3255** ^The names returned are the original un-aliased names of the
3256** database, table, and column.
3257**
3258** ^The first argument to these interfaces is a [prepared statement].
3259** ^These functions return information about the Nth result column returned by
3260** the statement, where N is the second function argument.
3261** ^The left-most column is column 0 for these routines.
3262**
3263** ^If the Nth column returned by the statement is an expression or
3264** subquery and is not a column value, then all of these functions return
3265** NULL.  ^These routine might also return NULL if a memory allocation error
3266** occurs.  ^Otherwise, they return the name of the attached database, table,
3267** or column that query result column was extracted from.
3268**
3269** ^As with all other SQLite APIs, those whose names end with "16" return
3270** UTF-16 encoded strings and the other functions return UTF-8.
3271**
3272** ^These APIs are only available if the library was compiled with the
3273** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3274**
3275** If two or more threads call one or more of these routines against the same
3276** prepared statement and column at the same time then the results are
3277** undefined.
3278**
3279** If two or more threads call one or more
3280** [sqlite3_column_database_name | column metadata interfaces]
3281** for the same [prepared statement] and result column
3282** at the same time then the results are undefined.
3283*/
3284SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3285SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3286SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3287SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3288SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3289SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3290
3291/*
3292** CAPI3REF: Declared Datatype Of A Query Result
3293**
3294** ^(The first parameter is a [prepared statement].
3295** If this statement is a [SELECT] statement and the Nth column of the
3296** returned result set of that [SELECT] is a table column (not an
3297** expression or subquery) then the declared type of the table
3298** column is returned.)^  ^If the Nth column of the result set is an
3299** expression or subquery, then a NULL pointer is returned.
3300** ^The returned string is always UTF-8 encoded.
3301**
3302** ^(For example, given the database schema:
3303**
3304** CREATE TABLE t1(c1 VARIANT);
3305**
3306** and the following statement to be compiled:
3307**
3308** SELECT c1 + 1, c1 FROM t1;
3309**
3310** this routine would return the string "VARIANT" for the second result
3311** column (i==1), and a NULL pointer for the first result column (i==0).)^
3312**
3313** ^SQLite uses dynamic run-time typing.  ^So just because a column
3314** is declared to contain a particular type does not mean that the
3315** data stored in that column is of the declared type.  SQLite is
3316** strongly typed, but the typing is dynamic not static.  ^Type
3317** is associated with individual values, not with the containers
3318** used to hold those values.
3319*/
3320SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3321SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3322
3323/*
3324** CAPI3REF: Evaluate An SQL Statement
3325**
3326** After a [prepared statement] has been prepared using either
3327** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3328** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3329** must be called one or more times to evaluate the statement.
3330**
3331** The details of the behavior of the sqlite3_step() interface depend
3332** on whether the statement was prepared using the newer "v2" interface
3333** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3334** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3335** new "v2" interface is recommended for new applications but the legacy
3336** interface will continue to be supported.
3337**
3338** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3339** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3340** ^With the "v2" interface, any of the other [result codes] or
3341** [extended result codes] might be returned as well.
3342**
3343** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3344** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3345** or occurs outside of an explicit transaction, then you can retry the
3346** statement.  If the statement is not a [COMMIT] and occurs within a
3347** explicit transaction then you should rollback the transaction before
3348** continuing.
3349**
3350** ^[SQLITE_DONE] means that the statement has finished executing
3351** successfully.  sqlite3_step() should not be called again on this virtual
3352** machine without first calling [sqlite3_reset()] to reset the virtual
3353** machine back to its initial state.
3354**
3355** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3356** is returned each time a new row of data is ready for processing by the
3357** caller. The values may be accessed using the [column access functions].
3358** sqlite3_step() is called again to retrieve the next row of data.
3359**
3360** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3361** violation) has occurred.  sqlite3_step() should not be called again on
3362** the VM. More information may be found by calling [sqlite3_errmsg()].
3363** ^With the legacy interface, a more specific error code (for example,
3364** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3365** can be obtained by calling [sqlite3_reset()] on the
3366** [prepared statement].  ^In the "v2" interface,
3367** the more specific error code is returned directly by sqlite3_step().
3368**
3369** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3370** Perhaps it was called on a [prepared statement] that has
3371** already been [sqlite3_finalize | finalized] or on one that had
3372** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3373** be the case that the same database connection is being used by two or
3374** more threads at the same moment in time.
3375**
3376** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3377** API always returns a generic error code, [SQLITE_ERROR], following any
3378** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3379** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3380** specific [error codes] that better describes the error.
3381** We admit that this is a goofy design.  The problem has been fixed
3382** with the "v2" interface.  If you prepare all of your SQL statements
3383** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3384** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3385** then the more specific [error codes] are returned directly
3386** by sqlite3_step().  The use of the "v2" interface is recommended.
3387*/
3388SQLITE_API int sqlite3_step(sqlite3_stmt*);
3389
3390/*
3391** CAPI3REF: Number of columns in a result set
3392**
3393** ^The sqlite3_data_count(P) the number of columns in the
3394** of the result set of [prepared statement] P.
3395*/
3396SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3397
3398/*
3399** CAPI3REF: Fundamental Datatypes
3400** KEYWORDS: SQLITE_TEXT
3401**
3402** ^(Every value in SQLite has one of five fundamental datatypes:
3403**
3404** <ul>
3405** <li> 64-bit signed integer
3406** <li> 64-bit IEEE floating point number
3407** <li> string
3408** <li> BLOB
3409** <li> NULL
3410** </ul>)^
3411**
3412** These constants are codes for each of those types.
3413**
3414** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3415** for a completely different meaning.  Software that links against both
3416** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3417** SQLITE_TEXT.
3418*/
3419#define SQLITE_INTEGER  1
3420#define SQLITE_FLOAT    2
3421#define SQLITE_BLOB     4
3422#define SQLITE_NULL     5
3423#ifdef SQLITE_TEXT
3424# undef SQLITE_TEXT
3425#else
3426# define SQLITE_TEXT     3
3427#endif
3428#define SQLITE3_TEXT     3
3429
3430/*
3431** CAPI3REF: Result Values From A Query
3432** KEYWORDS: {column access functions}
3433**
3434** These routines form the "result set" interface.
3435**
3436** ^These routines return information about a single column of the current
3437** result row of a query.  ^In every case the first argument is a pointer
3438** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3439** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3440** and the second argument is the index of the column for which information
3441** should be returned. ^The leftmost column of the result set has the index 0.
3442** ^The number of columns in the result can be determined using
3443** [sqlite3_column_count()].
3444**
3445** If the SQL statement does not currently point to a valid row, or if the
3446** column index is out of range, the result is undefined.
3447** These routines may only be called when the most recent call to
3448** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3449** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3450** If any of these routines are called after [sqlite3_reset()] or
3451** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3452** something other than [SQLITE_ROW], the results are undefined.
3453** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3454** are called from a different thread while any of these routines
3455** are pending, then the results are undefined.
3456**
3457** ^The sqlite3_column_type() routine returns the
3458** [SQLITE_INTEGER | datatype code] for the initial data type
3459** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3460** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3461** returned by sqlite3_column_type() is only meaningful if no type
3462** conversions have occurred as described below.  After a type conversion,
3463** the value returned by sqlite3_column_type() is undefined.  Future
3464** versions of SQLite may change the behavior of sqlite3_column_type()
3465** following a type conversion.
3466**
3467** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3468** routine returns the number of bytes in that BLOB or string.
3469** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3470** the string to UTF-8 and then returns the number of bytes.
3471** ^If the result is a numeric value then sqlite3_column_bytes() uses
3472** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3473** the number of bytes in that string.
3474** ^The value returned does not include the zero terminator at the end
3475** of the string.  ^For clarity: the value returned is the number of
3476** bytes in the string, not the number of characters.
3477**
3478** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3479** even empty strings, are always zero terminated.  ^The return
3480** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
3481** pointer, possibly even a NULL pointer.
3482**
3483** ^The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
3484** but leaves the result in UTF-16 in native byte order instead of UTF-8.
3485** ^The zero terminator is not included in this count.
3486**
3487** ^The object returned by [sqlite3_column_value()] is an
3488** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3489** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3490** If the [unprotected sqlite3_value] object returned by
3491** [sqlite3_column_value()] is used in any other way, including calls
3492** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3493** or [sqlite3_value_bytes()], then the behavior is undefined.
3494**
3495** These routines attempt to convert the value where appropriate.  ^For
3496** example, if the internal representation is FLOAT and a text result
3497** is requested, [sqlite3_snprintf()] is used internally to perform the
3498** conversion automatically.  ^(The following table details the conversions
3499** that are applied:
3500**
3501** <blockquote>
3502** <table border="1">
3503** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3504**
3505** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3506** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3507** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3508** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3509** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3510** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3511** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
3512** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3513** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3514** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3515** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3516** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3517** <tr><td>  TEXT    <td>   BLOB    <td> No change
3518** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3519** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3520** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3521** </table>
3522** </blockquote>)^
3523**
3524** The table above makes reference to standard C library functions atoi()
3525** and atof().  SQLite does not really use these functions.  It has its
3526** own equivalent internal routines.  The atoi() and atof() names are
3527** used in the table for brevity and because they are familiar to most
3528** C programmers.
3529**
3530** ^Note that when type conversions occur, pointers returned by prior
3531** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3532** sqlite3_column_text16() may be invalidated.
3533** ^(Type conversions and pointer invalidations might occur
3534** in the following cases:
3535**
3536** <ul>
3537** <li> The initial content is a BLOB and sqlite3_column_text() or
3538**      sqlite3_column_text16() is called.  A zero-terminator might
3539**      need to be added to the string.</li>
3540** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3541**      sqlite3_column_text16() is called.  The content must be converted
3542**      to UTF-16.</li>
3543** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3544**      sqlite3_column_text() is called.  The content must be converted
3545**      to UTF-8.</li>
3546** </ul>)^
3547**
3548** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3549** not invalidate a prior pointer, though of course the content of the buffer
3550** that the prior pointer points to will have been modified.  Other kinds
3551** of conversion are done in place when it is possible, but sometimes they
3552** are not possible and in those cases prior pointers are invalidated.
3553**
3554** ^(The safest and easiest to remember policy is to invoke these routines
3555** in one of the following ways:
3556**
3557** <ul>
3558**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3559**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3560**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3561** </ul>)^
3562**
3563** In other words, you should call sqlite3_column_text(),
3564** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3565** into the desired format, then invoke sqlite3_column_bytes() or
3566** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
3567** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3568** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3569** with calls to sqlite3_column_bytes().
3570**
3571** ^The pointers returned are valid until a type conversion occurs as
3572** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3573** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
3574** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
3575** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3576** [sqlite3_free()].
3577**
3578** ^(If a memory allocation error occurs during the evaluation of any
3579** of these routines, a default value is returned.  The default value
3580** is either the integer 0, the floating point number 0.0, or a NULL
3581** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3582** [SQLITE_NOMEM].)^
3583*/
3584SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3585SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3586SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3587SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3588SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3589SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3590SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3591SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3592SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3593SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3594
3595/*
3596** CAPI3REF: Destroy A Prepared Statement Object
3597**
3598** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3599** ^If the statement was executed successfully or not executed at all, then
3600** SQLITE_OK is returned. ^If execution of the statement failed then an
3601** [error code] or [extended error code] is returned.
3602**
3603** ^This routine can be called at any point during the execution of the
3604** [prepared statement].  ^If the virtual machine has not
3605** completed execution when this routine is called, that is like
3606** encountering an error or an [sqlite3_interrupt | interrupt].
3607** ^Incomplete updates may be rolled back and transactions canceled,
3608** depending on the circumstances, and the
3609** [error code] returned will be [SQLITE_ABORT].
3610*/
3611SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3612
3613/*
3614** CAPI3REF: Reset A Prepared Statement Object
3615**
3616** The sqlite3_reset() function is called to reset a [prepared statement]
3617** object back to its initial state, ready to be re-executed.
3618** ^Any SQL statement variables that had values bound to them using
3619** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3620** Use [sqlite3_clear_bindings()] to reset the bindings.
3621**
3622** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3623** back to the beginning of its program.
3624**
3625** ^If the most recent call to [sqlite3_step(S)] for the
3626** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3627** or if [sqlite3_step(S)] has never before been called on S,
3628** then [sqlite3_reset(S)] returns [SQLITE_OK].
3629**
3630** ^If the most recent call to [sqlite3_step(S)] for the
3631** [prepared statement] S indicated an error, then
3632** [sqlite3_reset(S)] returns an appropriate [error code].
3633**
3634** ^The [sqlite3_reset(S)] interface does not change the values
3635** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3636*/
3637SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3638
3639/*
3640** CAPI3REF: Create Or Redefine SQL Functions
3641** KEYWORDS: {function creation routines}
3642** KEYWORDS: {application-defined SQL function}
3643** KEYWORDS: {application-defined SQL functions}
3644**
3645** ^These two functions (collectively known as "function creation routines")
3646** are used to add SQL functions or aggregates or to redefine the behavior
3647** of existing SQL functions or aggregates.  The only difference between the
3648** two is that the second parameter, the name of the (scalar) function or
3649** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
3650** for sqlite3_create_function16().
3651**
3652** ^The first parameter is the [database connection] to which the SQL
3653** function is to be added.  ^If an application uses more than one database
3654** connection then application-defined SQL functions must be added
3655** to each database connection separately.
3656**
3657** The second parameter is the name of the SQL function to be created or
3658** redefined.  ^The length of the name is limited to 255 bytes, exclusive of
3659** the zero-terminator.  Note that the name length limit is in bytes, not
3660** characters.  ^Any attempt to create a function with a longer name
3661** will result in [SQLITE_ERROR] being returned.
3662**
3663** ^The third parameter (nArg)
3664** is the number of arguments that the SQL function or
3665** aggregate takes. ^If this parameter is -1, then the SQL function or
3666** aggregate may take any number of arguments between 0 and the limit
3667** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
3668** parameter is less than -1 or greater than 127 then the behavior is
3669** undefined.
3670**
3671** The fourth parameter, eTextRep, specifies what
3672** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3673** its parameters.  Any SQL function implementation should be able to work
3674** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
3675** more efficient with one encoding than another.  ^An application may
3676** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3677** times with the same function but with different values of eTextRep.
3678** ^When multiple implementations of the same function are available, SQLite
3679** will pick the one that involves the least amount of data conversion.
3680** If there is only a single implementation which does not care what text
3681** encoding is used, then the fourth argument should be [SQLITE_ANY].
3682**
3683** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
3684** function can gain access to this pointer using [sqlite3_user_data()].)^
3685**
3686** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3687** pointers to C-language functions that implement the SQL function or
3688** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3689** callback only; NULL pointers should be passed as the xStep and xFinal
3690** parameters. ^An aggregate SQL function requires an implementation of xStep
3691** and xFinal and NULL should be passed for xFunc. ^To delete an existing
3692** SQL function or aggregate, pass NULL for all three function callbacks.
3693**
3694** ^It is permitted to register multiple implementations of the same
3695** functions with the same name but with either differing numbers of
3696** arguments or differing preferred text encodings.  ^SQLite will use
3697** the implementation that most closely matches the way in which the
3698** SQL function is used.  ^A function implementation with a non-negative
3699** nArg parameter is a better match than a function implementation with
3700** a negative nArg.  ^A function where the preferred text encoding
3701** matches the database encoding is a better
3702** match than a function where the encoding is different.
3703** ^A function where the encoding difference is between UTF16le and UTF16be
3704** is a closer match than a function where the encoding difference is
3705** between UTF8 and UTF16.
3706**
3707** ^Built-in functions may be overloaded by new application-defined functions.
3708** ^The first application-defined function with a given name overrides all
3709** built-in functions in the same [database connection] with the same name.
3710** ^Subsequent application-defined functions of the same name only override
3711** prior application-defined functions that are an exact match for the
3712** number of parameters and preferred encoding.
3713**
3714** ^An application-defined function is permitted to call other
3715** SQLite interfaces.  However, such calls must not
3716** close the database connection nor finalize or reset the prepared
3717** statement in which the function is running.
3718*/
3719SQLITE_API int sqlite3_create_function(
3720  sqlite3 *db,
3721  const char *zFunctionName,
3722  int nArg,
3723  int eTextRep,
3724  void *pApp,
3725  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3726  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3727  void (*xFinal)(sqlite3_context*)
3728);
3729SQLITE_API int sqlite3_create_function16(
3730  sqlite3 *db,
3731  const void *zFunctionName,
3732  int nArg,
3733  int eTextRep,
3734  void *pApp,
3735  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3736  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3737  void (*xFinal)(sqlite3_context*)
3738);
3739
3740/*
3741** CAPI3REF: Text Encodings
3742**
3743** These constant define integer codes that represent the various
3744** text encodings supported by SQLite.
3745*/
3746#define SQLITE_UTF8           1
3747#define SQLITE_UTF16LE        2
3748#define SQLITE_UTF16BE        3
3749#define SQLITE_UTF16          4    /* Use native byte order */
3750#define SQLITE_ANY            5    /* sqlite3_create_function only */
3751#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
3752
3753/*
3754** CAPI3REF: Deprecated Functions
3755** DEPRECATED
3756**
3757** These functions are [deprecated].  In order to maintain
3758** backwards compatibility with older code, these functions continue
3759** to be supported.  However, new applications should avoid
3760** the use of these functions.  To help encourage people to avoid
3761** using these functions, we are not going to tell you what they do.
3762*/
3763#ifndef SQLITE_OMIT_DEPRECATED
3764SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
3765SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
3766SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
3767SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
3768SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
3769SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
3770#endif
3771
3772/*
3773** CAPI3REF: Obtaining SQL Function Parameter Values
3774**
3775** The C-language implementation of SQL functions and aggregates uses
3776** this set of interface routines to access the parameter values on
3777** the function or aggregate.
3778**
3779** The xFunc (for scalar functions) or xStep (for aggregates) parameters
3780** to [sqlite3_create_function()] and [sqlite3_create_function16()]
3781** define callbacks that implement the SQL functions and aggregates.
3782** The 4th parameter to these callbacks is an array of pointers to
3783** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
3784** each parameter to the SQL function.  These routines are used to
3785** extract values from the [sqlite3_value] objects.
3786**
3787** These routines work only with [protected sqlite3_value] objects.
3788** Any attempt to use these routines on an [unprotected sqlite3_value]
3789** object results in undefined behavior.
3790**
3791** ^These routines work just like the corresponding [column access functions]
3792** except that  these routines take a single [protected sqlite3_value] object
3793** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
3794**
3795** ^The sqlite3_value_text16() interface extracts a UTF-16 string
3796** in the native byte-order of the host machine.  ^The
3797** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
3798** extract UTF-16 strings as big-endian and little-endian respectively.
3799**
3800** ^(The sqlite3_value_numeric_type() interface attempts to apply
3801** numeric affinity to the value.  This means that an attempt is
3802** made to convert the value to an integer or floating point.  If
3803** such a conversion is possible without loss of information (in other
3804** words, if the value is a string that looks like a number)
3805** then the conversion is performed.  Otherwise no conversion occurs.
3806** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
3807**
3808** Please pay particular attention to the fact that the pointer returned
3809** from [sqlite3_value_blob()], [sqlite3_value_text()], or
3810** [sqlite3_value_text16()] can be invalidated by a subsequent call to
3811** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
3812** or [sqlite3_value_text16()].
3813**
3814** These routines must be called from the same thread as
3815** the SQL function that supplied the [sqlite3_value*] parameters.
3816*/
3817SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
3818SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
3819SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
3820SQLITE_API double sqlite3_value_double(sqlite3_value*);
3821SQLITE_API int sqlite3_value_int(sqlite3_value*);
3822SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
3823SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
3824SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
3825SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
3826SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
3827SQLITE_API int sqlite3_value_type(sqlite3_value*);
3828SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
3829
3830/*
3831** CAPI3REF: Obtain Aggregate Function Context
3832**
3833** Implementions of aggregate SQL functions use this
3834** routine to allocate memory for storing their state.
3835**
3836** ^The first time the sqlite3_aggregate_context(C,N) routine is called
3837** for a particular aggregate function, SQLite
3838** allocates N of memory, zeroes out that memory, and returns a pointer
3839** to the new memory. ^On second and subsequent calls to
3840** sqlite3_aggregate_context() for the same aggregate function instance,
3841** the same buffer is returned.  Sqlite3_aggregate_context() is normally
3842** called once for each invocation of the xStep callback and then one
3843** last time when the xFinal callback is invoked.  ^(When no rows match
3844** an aggregate query, the xStep() callback of the aggregate function
3845** implementation is never called and xFinal() is called exactly once.
3846** In those cases, sqlite3_aggregate_context() might be called for the
3847** first time from within xFinal().)^
3848**
3849** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
3850** less than or equal to zero or if a memory allocate error occurs.
3851**
3852** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
3853** determined by the N parameter on first successful call.  Changing the
3854** value of N in subsequent call to sqlite3_aggregate_context() within
3855** the same aggregate function instance will not resize the memory
3856** allocation.)^
3857**
3858** ^SQLite automatically frees the memory allocated by
3859** sqlite3_aggregate_context() when the aggregate query concludes.
3860**
3861** The first parameter must be a copy of the
3862** [sqlite3_context | SQL function context] that is the first parameter
3863** to the xStep or xFinal callback routine that implements the aggregate
3864** function.
3865**
3866** This routine must be called from the same thread in which
3867** the aggregate SQL function is running.
3868*/
3869SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
3870
3871/*
3872** CAPI3REF: User Data For Functions
3873**
3874** ^The sqlite3_user_data() interface returns a copy of
3875** the pointer that was the pUserData parameter (the 5th parameter)
3876** of the [sqlite3_create_function()]
3877** and [sqlite3_create_function16()] routines that originally
3878** registered the application defined function.
3879**
3880** This routine must be called from the same thread in which
3881** the application-defined function is running.
3882*/
3883SQLITE_API void *sqlite3_user_data(sqlite3_context*);
3884
3885/*
3886** CAPI3REF: Database Connection For Functions
3887**
3888** ^The sqlite3_context_db_handle() interface returns a copy of
3889** the pointer to the [database connection] (the 1st parameter)
3890** of the [sqlite3_create_function()]
3891** and [sqlite3_create_function16()] routines that originally
3892** registered the application defined function.
3893*/
3894SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
3895
3896/*
3897** CAPI3REF: Function Auxiliary Data
3898**
3899** The following two functions may be used by scalar SQL functions to
3900** associate metadata with argument values. If the same value is passed to
3901** multiple invocations of the same SQL function during query execution, under
3902** some circumstances the associated metadata may be preserved. This may
3903** be used, for example, to add a regular-expression matching scalar
3904** function. The compiled version of the regular expression is stored as
3905** metadata associated with the SQL value passed as the regular expression
3906** pattern.  The compiled regular expression can be reused on multiple
3907** invocations of the same function so that the original pattern string
3908** does not need to be recompiled on each invocation.
3909**
3910** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
3911** associated by the sqlite3_set_auxdata() function with the Nth argument
3912** value to the application-defined function. ^If no metadata has been ever
3913** been set for the Nth argument of the function, or if the corresponding
3914** function parameter has changed since the meta-data was set,
3915** then sqlite3_get_auxdata() returns a NULL pointer.
3916**
3917** ^The sqlite3_set_auxdata() interface saves the metadata
3918** pointed to by its 3rd parameter as the metadata for the N-th
3919** argument of the application-defined function.  Subsequent
3920** calls to sqlite3_get_auxdata() might return this data, if it has
3921** not been destroyed.
3922** ^If it is not NULL, SQLite will invoke the destructor
3923** function given by the 4th parameter to sqlite3_set_auxdata() on
3924** the metadata when the corresponding function parameter changes
3925** or when the SQL statement completes, whichever comes first.
3926**
3927** SQLite is free to call the destructor and drop metadata on any
3928** parameter of any function at any time.  ^The only guarantee is that
3929** the destructor will be called before the metadata is dropped.
3930**
3931** ^(In practice, metadata is preserved between function calls for
3932** expressions that are constant at compile time. This includes literal
3933** values and [parameters].)^
3934**
3935** These routines must be called from the same thread in which
3936** the SQL function is running.
3937*/
3938SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
3939SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
3940
3941
3942/*
3943** CAPI3REF: Constants Defining Special Destructor Behavior
3944**
3945** These are special values for the destructor that is passed in as the
3946** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
3947** argument is SQLITE_STATIC, it means that the content pointer is constant
3948** and will never change.  It does not need to be destroyed.  ^The
3949** SQLITE_TRANSIENT value means that the content will likely change in
3950** the near future and that SQLite should make its own private copy of
3951** the content before returning.
3952**
3953** The typedef is necessary to work around problems in certain
3954** C++ compilers.  See ticket #2191.
3955*/
3956typedef void (*sqlite3_destructor_type)(void*);
3957#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
3958#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
3959
3960/*
3961** CAPI3REF: Setting The Result Of An SQL Function
3962**
3963** These routines are used by the xFunc or xFinal callbacks that
3964** implement SQL functions and aggregates.  See
3965** [sqlite3_create_function()] and [sqlite3_create_function16()]
3966** for additional information.
3967**
3968** These functions work very much like the [parameter binding] family of
3969** functions used to bind values to host parameters in prepared statements.
3970** Refer to the [SQL parameter] documentation for additional information.
3971**
3972** ^The sqlite3_result_blob() interface sets the result from
3973** an application-defined function to be the BLOB whose content is pointed
3974** to by the second parameter and which is N bytes long where N is the
3975** third parameter.
3976**
3977** ^The sqlite3_result_zeroblob() interfaces set the result of
3978** the application-defined function to be a BLOB containing all zero
3979** bytes and N bytes in size, where N is the value of the 2nd parameter.
3980**
3981** ^The sqlite3_result_double() interface sets the result from
3982** an application-defined function to be a floating point value specified
3983** by its 2nd argument.
3984**
3985** ^The sqlite3_result_error() and sqlite3_result_error16() functions
3986** cause the implemented SQL function to throw an exception.
3987** ^SQLite uses the string pointed to by the
3988** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
3989** as the text of an error message.  ^SQLite interprets the error
3990** message string from sqlite3_result_error() as UTF-8. ^SQLite
3991** interprets the string from sqlite3_result_error16() as UTF-16 in native
3992** byte order.  ^If the third parameter to sqlite3_result_error()
3993** or sqlite3_result_error16() is negative then SQLite takes as the error
3994** message all text up through the first zero character.
3995** ^If the third parameter to sqlite3_result_error() or
3996** sqlite3_result_error16() is non-negative then SQLite takes that many
3997** bytes (not characters) from the 2nd parameter as the error message.
3998** ^The sqlite3_result_error() and sqlite3_result_error16()
3999** routines make a private copy of the error message text before
4000** they return.  Hence, the calling function can deallocate or
4001** modify the text after they return without harm.
4002** ^The sqlite3_result_error_code() function changes the error code
4003** returned by SQLite as a result of an error in a function.  ^By default,
4004** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4005** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4006**
4007** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4008** indicating that a string or BLOB is too long to represent.
4009**
4010** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4011** indicating that a memory allocation failed.
4012**
4013** ^The sqlite3_result_int() interface sets the return value
4014** of the application-defined function to be the 32-bit signed integer
4015** value given in the 2nd argument.
4016** ^The sqlite3_result_int64() interface sets the return value
4017** of the application-defined function to be the 64-bit signed integer
4018** value given in the 2nd argument.
4019**
4020** ^The sqlite3_result_null() interface sets the return value
4021** of the application-defined function to be NULL.
4022**
4023** ^The sqlite3_result_text(), sqlite3_result_text16(),
4024** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4025** set the return value of the application-defined function to be
4026** a text string which is represented as UTF-8, UTF-16 native byte order,
4027** UTF-16 little endian, or UTF-16 big endian, respectively.
4028** ^SQLite takes the text result from the application from
4029** the 2nd parameter of the sqlite3_result_text* interfaces.
4030** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4031** is negative, then SQLite takes result text from the 2nd parameter
4032** through the first zero character.
4033** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4034** is non-negative, then as many bytes (not characters) of the text
4035** pointed to by the 2nd parameter are taken as the application-defined
4036** function result.
4037** ^If the 4th parameter to the sqlite3_result_text* interfaces
4038** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4039** function as the destructor on the text or BLOB result when it has
4040** finished using that result.
4041** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4042** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4043** assumes that the text or BLOB result is in constant space and does not
4044** copy the content of the parameter nor call a destructor on the content
4045** when it has finished using that result.
4046** ^If the 4th parameter to the sqlite3_result_text* interfaces
4047** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4048** then SQLite makes a copy of the result into space obtained from
4049** from [sqlite3_malloc()] before it returns.
4050**
4051** ^The sqlite3_result_value() interface sets the result of
4052** the application-defined function to be a copy the
4053** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4054** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4055** so that the [sqlite3_value] specified in the parameter may change or
4056** be deallocated after sqlite3_result_value() returns without harm.
4057** ^A [protected sqlite3_value] object may always be used where an
4058** [unprotected sqlite3_value] object is required, so either
4059** kind of [sqlite3_value] object can be used with this interface.
4060**
4061** If these routines are called from within the different thread
4062** than the one containing the application-defined function that received
4063** the [sqlite3_context] pointer, the results are undefined.
4064*/
4065SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4066SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4067SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4068SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4069SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4070SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4071SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4072SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4073SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4074SQLITE_API void sqlite3_result_null(sqlite3_context*);
4075SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4076SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4077SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4078SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4079SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4080SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4081
4082/*
4083** CAPI3REF: Define New Collating Sequences
4084**
4085** These functions are used to add new collation sequences to the
4086** [database connection] specified as the first argument.
4087**
4088** ^The name of the new collation sequence is specified as a UTF-8 string
4089** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4090** and a UTF-16 string for sqlite3_create_collation16(). ^In all cases
4091** the name is passed as the second function argument.
4092**
4093** ^The third argument may be one of the constants [SQLITE_UTF8],
4094** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
4095** routine expects to be passed pointers to strings encoded using UTF-8,
4096** UTF-16 little-endian, or UTF-16 big-endian, respectively. ^The
4097** third argument might also be [SQLITE_UTF16] to indicate that the routine
4098** expects pointers to be UTF-16 strings in the native byte order, or the
4099** argument can be [SQLITE_UTF16_ALIGNED] if the
4100** the routine expects pointers to 16-bit word aligned strings
4101** of UTF-16 in the native byte order.
4102**
4103** A pointer to the user supplied routine must be passed as the fifth
4104** argument.  ^If it is NULL, this is the same as deleting the collation
4105** sequence (so that SQLite cannot call it anymore).
4106** ^Each time the application supplied function is invoked, it is passed
4107** as its first parameter a copy of the void* passed as the fourth argument
4108** to sqlite3_create_collation() or sqlite3_create_collation16().
4109**
4110** ^The remaining arguments to the application-supplied routine are two strings,
4111** each represented by a (length, data) pair and encoded in the encoding
4112** that was passed as the third argument when the collation sequence was
4113** registered.  The application defined collation routine should
4114** return negative, zero or positive if the first string is less than,
4115** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
4116**
4117** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4118** except that it takes an extra argument which is a destructor for
4119** the collation.  ^The destructor is called when the collation is
4120** destroyed and is passed a copy of the fourth parameter void* pointer
4121** of the sqlite3_create_collation_v2().
4122** ^Collations are destroyed when they are overridden by later calls to the
4123** collation creation functions or when the [database connection] is closed
4124** using [sqlite3_close()].
4125**
4126** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4127*/
4128SQLITE_API int sqlite3_create_collation(
4129  sqlite3*,
4130  const char *zName,
4131  int eTextRep,
4132  void*,
4133  int(*xCompare)(void*,int,const void*,int,const void*)
4134);
4135SQLITE_API int sqlite3_create_collation_v2(
4136  sqlite3*,
4137  const char *zName,
4138  int eTextRep,
4139  void*,
4140  int(*xCompare)(void*,int,const void*,int,const void*),
4141  void(*xDestroy)(void*)
4142);
4143SQLITE_API int sqlite3_create_collation16(
4144  sqlite3*,
4145  const void *zName,
4146  int eTextRep,
4147  void*,
4148  int(*xCompare)(void*,int,const void*,int,const void*)
4149);
4150
4151/*
4152** CAPI3REF: Collation Needed Callbacks
4153**
4154** ^To avoid having to register all collation sequences before a database
4155** can be used, a single callback function may be registered with the
4156** [database connection] to be invoked whenever an undefined collation
4157** sequence is required.
4158**
4159** ^If the function is registered using the sqlite3_collation_needed() API,
4160** then it is passed the names of undefined collation sequences as strings
4161** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4162** the names are passed as UTF-16 in machine native byte order.
4163** ^A call to either function replaces the existing collation-needed callback.
4164**
4165** ^(When the callback is invoked, the first argument passed is a copy
4166** of the second argument to sqlite3_collation_needed() or
4167** sqlite3_collation_needed16().  The second argument is the database
4168** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4169** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4170** sequence function required.  The fourth parameter is the name of the
4171** required collation sequence.)^
4172**
4173** The callback function should register the desired collation using
4174** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4175** [sqlite3_create_collation_v2()].
4176*/
4177SQLITE_API int sqlite3_collation_needed(
4178  sqlite3*,
4179  void*,
4180  void(*)(void*,sqlite3*,int eTextRep,const char*)
4181);
4182SQLITE_API int sqlite3_collation_needed16(
4183  sqlite3*,
4184  void*,
4185  void(*)(void*,sqlite3*,int eTextRep,const void*)
4186);
4187
4188/*
4189** Specify the key for an encrypted database.  This routine should be
4190** called right after sqlite3_open().
4191**
4192** The code to implement this API is not available in the public release
4193** of SQLite.
4194*/
4195SQLITE_API int sqlite3_key(
4196  sqlite3 *db,                   /* Database to be rekeyed */
4197  const void *pKey, int nKey     /* The key */
4198);
4199
4200/*
4201** Change the key on an open database.  If the current database is not
4202** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4203** database is decrypted.
4204**
4205** The code to implement this API is not available in the public release
4206** of SQLite.
4207*/
4208SQLITE_API int sqlite3_rekey(
4209  sqlite3 *db,                   /* Database to be rekeyed */
4210  const void *pKey, int nKey     /* The new key */
4211);
4212
4213/*
4214** CAPI3REF: Suspend Execution For A Short Time
4215**
4216** ^The sqlite3_sleep() function causes the current thread to suspend execution
4217** for at least a number of milliseconds specified in its parameter.
4218**
4219** ^If the operating system does not support sleep requests with
4220** millisecond time resolution, then the time will be rounded up to
4221** the nearest second. ^The number of milliseconds of sleep actually
4222** requested from the operating system is returned.
4223**
4224** ^SQLite implements this interface by calling the xSleep()
4225** method of the default [sqlite3_vfs] object.
4226*/
4227SQLITE_API int sqlite3_sleep(int);
4228
4229/*
4230** CAPI3REF: Name Of The Folder Holding Temporary Files
4231**
4232** ^(If this global variable is made to point to a string which is
4233** the name of a folder (a.k.a. directory), then all temporary files
4234** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4235** will be placed in that directory.)^  ^If this variable
4236** is a NULL pointer, then SQLite performs a search for an appropriate
4237** temporary file directory.
4238**
4239** It is not safe to read or modify this variable in more than one
4240** thread at a time.  It is not safe to read or modify this variable
4241** if a [database connection] is being used at the same time in a separate
4242** thread.
4243** It is intended that this variable be set once
4244** as part of process initialization and before any SQLite interface
4245** routines have been called and that this variable remain unchanged
4246** thereafter.
4247**
4248** ^The [temp_store_directory pragma] may modify this variable and cause
4249** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4250** the [temp_store_directory pragma] always assumes that any string
4251** that this variable points to is held in memory obtained from
4252** [sqlite3_malloc] and the pragma may attempt to free that memory
4253** using [sqlite3_free].
4254** Hence, if this variable is modified directly, either it should be
4255** made NULL or made to point to memory obtained from [sqlite3_malloc]
4256** or else the use of the [temp_store_directory pragma] should be avoided.
4257*/
4258SQLITE_API char *sqlite3_temp_directory;
4259
4260/*
4261** CAPI3REF: Test For Auto-Commit Mode
4262** KEYWORDS: {autocommit mode}
4263**
4264** ^The sqlite3_get_autocommit() interface returns non-zero or
4265** zero if the given database connection is or is not in autocommit mode,
4266** respectively.  ^Autocommit mode is on by default.
4267** ^Autocommit mode is disabled by a [BEGIN] statement.
4268** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4269**
4270** If certain kinds of errors occur on a statement within a multi-statement
4271** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4272** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4273** transaction might be rolled back automatically.  The only way to
4274** find out whether SQLite automatically rolled back the transaction after
4275** an error is to use this function.
4276**
4277** If another thread changes the autocommit status of the database
4278** connection while this routine is running, then the return value
4279** is undefined.
4280*/
4281SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4282
4283/*
4284** CAPI3REF: Find The Database Handle Of A Prepared Statement
4285**
4286** ^The sqlite3_db_handle interface returns the [database connection] handle
4287** to which a [prepared statement] belongs.  ^The [database connection]
4288** returned by sqlite3_db_handle is the same [database connection]
4289** that was the first argument
4290** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4291** create the statement in the first place.
4292*/
4293SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4294
4295/*
4296** CAPI3REF: Find the next prepared statement
4297**
4298** ^This interface returns a pointer to the next [prepared statement] after
4299** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4300** then this interface returns a pointer to the first prepared statement
4301** associated with the database connection pDb.  ^If no prepared statement
4302** satisfies the conditions of this routine, it returns NULL.
4303**
4304** The [database connection] pointer D in a call to
4305** [sqlite3_next_stmt(D,S)] must refer to an open database
4306** connection and in particular must not be a NULL pointer.
4307*/
4308SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4309
4310/*
4311** CAPI3REF: Commit And Rollback Notification Callbacks
4312**
4313** ^The sqlite3_commit_hook() interface registers a callback
4314** function to be invoked whenever a transaction is [COMMIT | committed].
4315** ^Any callback set by a previous call to sqlite3_commit_hook()
4316** for the same database connection is overridden.
4317** ^The sqlite3_rollback_hook() interface registers a callback
4318** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4319** ^Any callback set by a previous call to sqlite3_rollback_hook()
4320** for the same database connection is overridden.
4321** ^The pArg argument is passed through to the callback.
4322** ^If the callback on a commit hook function returns non-zero,
4323** then the commit is converted into a rollback.
4324**
4325** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4326** return the P argument from the previous call of the same function
4327** on the same [database connection] D, or NULL for
4328** the first call for each function on D.
4329**
4330** The callback implementation must not do anything that will modify
4331** the database connection that invoked the callback.  Any actions
4332** to modify the database connection must be deferred until after the
4333** completion of the [sqlite3_step()] call that triggered the commit
4334** or rollback hook in the first place.
4335** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4336** database connections for the meaning of "modify" in this paragraph.
4337**
4338** ^Registering a NULL function disables the callback.
4339**
4340** ^When the commit hook callback routine returns zero, the [COMMIT]
4341** operation is allowed to continue normally.  ^If the commit hook
4342** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4343** ^The rollback hook is invoked on a rollback that results from a commit
4344** hook returning non-zero, just as it would be with any other rollback.
4345**
4346** ^For the purposes of this API, a transaction is said to have been
4347** rolled back if an explicit "ROLLBACK" statement is executed, or
4348** an error or constraint causes an implicit rollback to occur.
4349** ^The rollback callback is not invoked if a transaction is
4350** automatically rolled back because the database connection is closed.
4351** ^The rollback callback is not invoked if a transaction is
4352** rolled back because a commit callback returned non-zero.
4353**
4354** See also the [sqlite3_update_hook()] interface.
4355*/
4356SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4357SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4358
4359/*
4360** CAPI3REF: Data Change Notification Callbacks
4361**
4362** ^The sqlite3_update_hook() interface registers a callback function
4363** with the [database connection] identified by the first argument
4364** to be invoked whenever a row is updated, inserted or deleted.
4365** ^Any callback set by a previous call to this function
4366** for the same database connection is overridden.
4367**
4368** ^The second argument is a pointer to the function to invoke when a
4369** row is updated, inserted or deleted.
4370** ^The first argument to the callback is a copy of the third argument
4371** to sqlite3_update_hook().
4372** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4373** or [SQLITE_UPDATE], depending on the operation that caused the callback
4374** to be invoked.
4375** ^The third and fourth arguments to the callback contain pointers to the
4376** database and table name containing the affected row.
4377** ^The final callback parameter is the [rowid] of the row.
4378** ^In the case of an update, this is the [rowid] after the update takes place.
4379**
4380** ^(The update hook is not invoked when internal system tables are
4381** modified (i.e. sqlite_master and sqlite_sequence).)^
4382**
4383** ^In the current implementation, the update hook
4384** is not invoked when duplication rows are deleted because of an
4385** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4386** invoked when rows are deleted using the [truncate optimization].
4387** The exceptions defined in this paragraph might change in a future
4388** release of SQLite.
4389**
4390** The update hook implementation must not do anything that will modify
4391** the database connection that invoked the update hook.  Any actions
4392** to modify the database connection must be deferred until after the
4393** completion of the [sqlite3_step()] call that triggered the update hook.
4394** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4395** database connections for the meaning of "modify" in this paragraph.
4396**
4397** ^The sqlite3_update_hook(D,C,P) function
4398** returns the P argument from the previous call
4399** on the same [database connection] D, or NULL for
4400** the first call on D.
4401**
4402** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4403** interfaces.
4404*/
4405SQLITE_API void *sqlite3_update_hook(
4406  sqlite3*,
4407  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4408  void*
4409);
4410
4411/*
4412** CAPI3REF: Enable Or Disable Shared Pager Cache
4413** KEYWORDS: {shared cache}
4414**
4415** ^(This routine enables or disables the sharing of the database cache
4416** and schema data structures between [database connection | connections]
4417** to the same database. Sharing is enabled if the argument is true
4418** and disabled if the argument is false.)^
4419**
4420** ^Cache sharing is enabled and disabled for an entire process.
4421** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4422** sharing was enabled or disabled for each thread separately.
4423**
4424** ^(The cache sharing mode set by this interface effects all subsequent
4425** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4426** Existing database connections continue use the sharing mode
4427** that was in effect at the time they were opened.)^
4428**
4429** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4430** successfully.  An [error code] is returned otherwise.)^
4431**
4432** ^Shared cache is disabled by default. But this might change in
4433** future releases of SQLite.  Applications that care about shared
4434** cache setting should set it explicitly.
4435**
4436** See Also:  [SQLite Shared-Cache Mode]
4437*/
4438SQLITE_API int sqlite3_enable_shared_cache(int);
4439
4440/*
4441** CAPI3REF: Attempt To Free Heap Memory
4442**
4443** ^The sqlite3_release_memory() interface attempts to free N bytes
4444** of heap memory by deallocating non-essential memory allocations
4445** held by the database library.   Memory used to cache database
4446** pages to improve performance is an example of non-essential memory.
4447** ^sqlite3_release_memory() returns the number of bytes actually freed,
4448** which might be more or less than the amount requested.
4449*/
4450SQLITE_API int sqlite3_release_memory(int);
4451
4452/*
4453** CAPI3REF: Impose A Limit On Heap Size
4454**
4455** ^The sqlite3_soft_heap_limit() interface places a "soft" limit
4456** on the amount of heap memory that may be allocated by SQLite.
4457** ^If an internal allocation is requested that would exceed the
4458** soft heap limit, [sqlite3_release_memory()] is invoked one or
4459** more times to free up some space before the allocation is performed.
4460**
4461** ^The limit is called "soft" because if [sqlite3_release_memory()]
4462** cannot free sufficient memory to prevent the limit from being exceeded,
4463** the memory is allocated anyway and the current operation proceeds.
4464**
4465** ^A negative or zero value for N means that there is no soft heap limit and
4466** [sqlite3_release_memory()] will only be called when memory is exhausted.
4467** ^The default value for the soft heap limit is zero.
4468**
4469** ^(SQLite makes a best effort to honor the soft heap limit.
4470** But if the soft heap limit cannot be honored, execution will
4471** continue without error or notification.)^  This is why the limit is
4472** called a "soft" limit.  It is advisory only.
4473**
4474** Prior to SQLite version 3.5.0, this routine only constrained the memory
4475** allocated by a single thread - the same thread in which this routine
4476** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
4477** applied to all threads. The value specified for the soft heap limit
4478** is an upper bound on the total memory allocation for all threads. In
4479** version 3.5.0 there is no mechanism for limiting the heap usage for
4480** individual threads.
4481*/
4482SQLITE_API void sqlite3_soft_heap_limit(int);
4483
4484/*
4485** CAPI3REF: Extract Metadata About A Column Of A Table
4486**
4487** ^This routine returns metadata about a specific column of a specific
4488** database table accessible using the [database connection] handle
4489** passed as the first function argument.
4490**
4491** ^The column is identified by the second, third and fourth parameters to
4492** this function. ^The second parameter is either the name of the database
4493** (i.e. "main", "temp", or an attached database) containing the specified
4494** table or NULL. ^If it is NULL, then all attached databases are searched
4495** for the table using the same algorithm used by the database engine to
4496** resolve unqualified table references.
4497**
4498** ^The third and fourth parameters to this function are the table and column
4499** name of the desired column, respectively. Neither of these parameters
4500** may be NULL.
4501**
4502** ^Metadata is returned by writing to the memory locations passed as the 5th
4503** and subsequent parameters to this function. ^Any of these arguments may be
4504** NULL, in which case the corresponding element of metadata is omitted.
4505**
4506** ^(<blockquote>
4507** <table border="1">
4508** <tr><th> Parameter <th> Output<br>Type <th>  Description
4509**
4510** <tr><td> 5th <td> const char* <td> Data type
4511** <tr><td> 6th <td> const char* <td> Name of default collation sequence
4512** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
4513** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
4514** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
4515** </table>
4516** </blockquote>)^
4517**
4518** ^The memory pointed to by the character pointers returned for the
4519** declaration type and collation sequence is valid only until the next
4520** call to any SQLite API function.
4521**
4522** ^If the specified table is actually a view, an [error code] is returned.
4523**
4524** ^If the specified column is "rowid", "oid" or "_rowid_" and an
4525** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
4526** parameters are set for the explicitly declared column. ^(If there is no
4527** explicitly declared [INTEGER PRIMARY KEY] column, then the output
4528** parameters are set as follows:
4529**
4530** <pre>
4531**     data type: "INTEGER"
4532**     collation sequence: "BINARY"
4533**     not null: 0
4534**     primary key: 1
4535**     auto increment: 0
4536** </pre>)^
4537**
4538** ^(This function may load one or more schemas from database files. If an
4539** error occurs during this process, or if the requested table or column
4540** cannot be found, an [error code] is returned and an error message left
4541** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
4542**
4543** ^This API is only available if the library was compiled with the
4544** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
4545*/
4546SQLITE_API int sqlite3_table_column_metadata(
4547  sqlite3 *db,                /* Connection handle */
4548  const char *zDbName,        /* Database name or NULL */
4549  const char *zTableName,     /* Table name */
4550  const char *zColumnName,    /* Column name */
4551  char const **pzDataType,    /* OUTPUT: Declared data type */
4552  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
4553  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
4554  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
4555  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
4556);
4557
4558/*
4559** CAPI3REF: Load An Extension
4560**
4561** ^This interface loads an SQLite extension library from the named file.
4562**
4563** ^The sqlite3_load_extension() interface attempts to load an
4564** SQLite extension library contained in the file zFile.
4565**
4566** ^The entry point is zProc.
4567** ^zProc may be 0, in which case the name of the entry point
4568** defaults to "sqlite3_extension_init".
4569** ^The sqlite3_load_extension() interface returns
4570** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
4571** ^If an error occurs and pzErrMsg is not 0, then the
4572** [sqlite3_load_extension()] interface shall attempt to
4573** fill *pzErrMsg with error message text stored in memory
4574** obtained from [sqlite3_malloc()]. The calling function
4575** should free this memory by calling [sqlite3_free()].
4576**
4577** ^Extension loading must be enabled using
4578** [sqlite3_enable_load_extension()] prior to calling this API,
4579** otherwise an error will be returned.
4580**
4581** See also the [load_extension() SQL function].
4582*/
4583SQLITE_API int sqlite3_load_extension(
4584  sqlite3 *db,          /* Load the extension into this database connection */
4585  const char *zFile,    /* Name of the shared library containing extension */
4586  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
4587  char **pzErrMsg       /* Put error message here if not 0 */
4588);
4589
4590/*
4591** CAPI3REF: Enable Or Disable Extension Loading
4592**
4593** ^So as not to open security holes in older applications that are
4594** unprepared to deal with extension loading, and as a means of disabling
4595** extension loading while evaluating user-entered SQL, the following API
4596** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
4597**
4598** ^Extension loading is off by default. See ticket #1863.
4599** ^Call the sqlite3_enable_load_extension() routine with onoff==1
4600** to turn extension loading on and call it with onoff==0 to turn
4601** it back off again.
4602*/
4603SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
4604
4605/*
4606** CAPI3REF: Automatically Load An Extensions
4607**
4608** ^This API can be invoked at program startup in order to register
4609** one or more statically linked extensions that will be available
4610** to all new [database connections].
4611**
4612** ^(This routine stores a pointer to the extension entry point
4613** in an array that is obtained from [sqlite3_malloc()].  That memory
4614** is deallocated by [sqlite3_reset_auto_extension()].)^
4615**
4616** ^This function registers an extension entry point that is
4617** automatically invoked whenever a new [database connection]
4618** is opened using [sqlite3_open()], [sqlite3_open16()],
4619** or [sqlite3_open_v2()].
4620** ^Duplicate extensions are detected so calling this routine
4621** multiple times with the same extension is harmless.
4622** ^Automatic extensions apply across all threads.
4623*/
4624SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
4625
4626/*
4627** CAPI3REF: Reset Automatic Extension Loading
4628**
4629** ^(This function disables all previously registered automatic
4630** extensions. It undoes the effect of all prior
4631** [sqlite3_auto_extension()] calls.)^
4632**
4633** ^This function disables automatic extensions in all threads.
4634*/
4635SQLITE_API void sqlite3_reset_auto_extension(void);
4636
4637/*
4638****** EXPERIMENTAL - subject to change without notice **************
4639**
4640** The interface to the virtual-table mechanism is currently considered
4641** to be experimental.  The interface might change in incompatible ways.
4642** If this is a problem for you, do not use the interface at this time.
4643**
4644** When the virtual-table mechanism stabilizes, we will declare the
4645** interface fixed, support it indefinitely, and remove this comment.
4646*/
4647
4648/*
4649** Structures used by the virtual table interface
4650*/
4651typedef struct sqlite3_vtab sqlite3_vtab;
4652typedef struct sqlite3_index_info sqlite3_index_info;
4653typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
4654typedef struct sqlite3_module sqlite3_module;
4655
4656/*
4657** CAPI3REF: Virtual Table Object
4658** KEYWORDS: sqlite3_module {virtual table module}
4659** EXPERIMENTAL
4660**
4661** This structure, sometimes called a a "virtual table module",
4662** defines the implementation of a [virtual tables].
4663** This structure consists mostly of methods for the module.
4664**
4665** ^A virtual table module is created by filling in a persistent
4666** instance of this structure and passing a pointer to that instance
4667** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
4668** ^The registration remains valid until it is replaced by a different
4669** module or until the [database connection] closes.  The content
4670** of this structure must not change while it is registered with
4671** any database connection.
4672*/
4673struct sqlite3_module {
4674  int iVersion;
4675  int (*xCreate)(sqlite3*, void *pAux,
4676               int argc, const char *const*argv,
4677               sqlite3_vtab **ppVTab, char**);
4678  int (*xConnect)(sqlite3*, void *pAux,
4679               int argc, const char *const*argv,
4680               sqlite3_vtab **ppVTab, char**);
4681  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
4682  int (*xDisconnect)(sqlite3_vtab *pVTab);
4683  int (*xDestroy)(sqlite3_vtab *pVTab);
4684  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
4685  int (*xClose)(sqlite3_vtab_cursor*);
4686  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
4687                int argc, sqlite3_value **argv);
4688  int (*xNext)(sqlite3_vtab_cursor*);
4689  int (*xEof)(sqlite3_vtab_cursor*);
4690  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
4691  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
4692  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
4693  int (*xBegin)(sqlite3_vtab *pVTab);
4694  int (*xSync)(sqlite3_vtab *pVTab);
4695  int (*xCommit)(sqlite3_vtab *pVTab);
4696  int (*xRollback)(sqlite3_vtab *pVTab);
4697  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
4698                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
4699                       void **ppArg);
4700  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
4701};
4702
4703/*
4704** CAPI3REF: Virtual Table Indexing Information
4705** KEYWORDS: sqlite3_index_info
4706** EXPERIMENTAL
4707**
4708** The sqlite3_index_info structure and its substructures is used to
4709** pass information into and receive the reply from the [xBestIndex]
4710** method of a [virtual table module].  The fields under **Inputs** are the
4711** inputs to xBestIndex and are read-only.  xBestIndex inserts its
4712** results into the **Outputs** fields.
4713**
4714** ^(The aConstraint[] array records WHERE clause constraints of the form:
4715**
4716** <pre>column OP expr</pre>
4717**
4718** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
4719** stored in aConstraint[].op.)^  ^(The index of the column is stored in
4720** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
4721** expr on the right-hand side can be evaluated (and thus the constraint
4722** is usable) and false if it cannot.)^
4723**
4724** ^The optimizer automatically inverts terms of the form "expr OP column"
4725** and makes other simplifications to the WHERE clause in an attempt to
4726** get as many WHERE clause terms into the form shown above as possible.
4727** ^The aConstraint[] array only reports WHERE clause terms that are
4728** relevant to the particular virtual table being queried.
4729**
4730** ^Information about the ORDER BY clause is stored in aOrderBy[].
4731** ^Each term of aOrderBy records a column of the ORDER BY clause.
4732**
4733** The [xBestIndex] method must fill aConstraintUsage[] with information
4734** about what parameters to pass to xFilter.  ^If argvIndex>0 then
4735** the right-hand side of the corresponding aConstraint[] is evaluated
4736** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
4737** is true, then the constraint is assumed to be fully handled by the
4738** virtual table and is not checked again by SQLite.)^
4739**
4740** ^The idxNum and idxPtr values are recorded and passed into the
4741** [xFilter] method.
4742** ^[sqlite3_free()] is used to free idxPtr if and only if
4743** needToFreeIdxPtr is true.
4744**
4745** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
4746** the correct order to satisfy the ORDER BY clause so that no separate
4747** sorting step is required.
4748**
4749** ^The estimatedCost value is an estimate of the cost of doing the
4750** particular lookup.  A full scan of a table with N entries should have
4751** a cost of N.  A binary search of a table of N entries should have a
4752** cost of approximately log(N).
4753*/
4754struct sqlite3_index_info {
4755  /* Inputs */
4756  int nConstraint;           /* Number of entries in aConstraint */
4757  struct sqlite3_index_constraint {
4758     int iColumn;              /* Column on left-hand side of constraint */
4759     unsigned char op;         /* Constraint operator */
4760     unsigned char usable;     /* True if this constraint is usable */
4761     int iTermOffset;          /* Used internally - xBestIndex should ignore */
4762  } *aConstraint;            /* Table of WHERE clause constraints */
4763  int nOrderBy;              /* Number of terms in the ORDER BY clause */
4764  struct sqlite3_index_orderby {
4765     int iColumn;              /* Column number */
4766     unsigned char desc;       /* True for DESC.  False for ASC. */
4767  } *aOrderBy;               /* The ORDER BY clause */
4768  /* Outputs */
4769  struct sqlite3_index_constraint_usage {
4770    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
4771    unsigned char omit;      /* Do not code a test for this constraint */
4772  } *aConstraintUsage;
4773  int idxNum;                /* Number used to identify the index */
4774  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
4775  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
4776  int orderByConsumed;       /* True if output is already ordered */
4777  double estimatedCost;      /* Estimated cost of using this index */
4778};
4779#define SQLITE_INDEX_CONSTRAINT_EQ    2
4780#define SQLITE_INDEX_CONSTRAINT_GT    4
4781#define SQLITE_INDEX_CONSTRAINT_LE    8
4782#define SQLITE_INDEX_CONSTRAINT_LT    16
4783#define SQLITE_INDEX_CONSTRAINT_GE    32
4784#define SQLITE_INDEX_CONSTRAINT_MATCH 64
4785
4786/*
4787** CAPI3REF: Register A Virtual Table Implementation
4788** EXPERIMENTAL
4789**
4790** ^These routines are used to register a new [virtual table module] name.
4791** ^Module names must be registered before
4792** creating a new [virtual table] using the module and before using a
4793** preexisting [virtual table] for the module.
4794**
4795** ^The module name is registered on the [database connection] specified
4796** by the first parameter.  ^The name of the module is given by the
4797** second parameter.  ^The third parameter is a pointer to
4798** the implementation of the [virtual table module].   ^The fourth
4799** parameter is an arbitrary client data pointer that is passed through
4800** into the [xCreate] and [xConnect] methods of the virtual table module
4801** when a new virtual table is be being created or reinitialized.
4802**
4803** ^The sqlite3_create_module_v2() interface has a fifth parameter which
4804** is a pointer to a destructor for the pClientData.  ^SQLite will
4805** invoke the destructor function (if it is not NULL) when SQLite
4806** no longer needs the pClientData pointer.  ^The sqlite3_create_module()
4807** interface is equivalent to sqlite3_create_module_v2() with a NULL
4808** destructor.
4809*/
4810SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
4811  sqlite3 *db,               /* SQLite connection to register module with */
4812  const char *zName,         /* Name of the module */
4813  const sqlite3_module *p,   /* Methods for the module */
4814  void *pClientData          /* Client data for xCreate/xConnect */
4815);
4816SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
4817  sqlite3 *db,               /* SQLite connection to register module with */
4818  const char *zName,         /* Name of the module */
4819  const sqlite3_module *p,   /* Methods for the module */
4820  void *pClientData,         /* Client data for xCreate/xConnect */
4821  void(*xDestroy)(void*)     /* Module destructor function */
4822);
4823
4824/*
4825** CAPI3REF: Virtual Table Instance Object
4826** KEYWORDS: sqlite3_vtab
4827** EXPERIMENTAL
4828**
4829** Every [virtual table module] implementation uses a subclass
4830** of this object to describe a particular instance
4831** of the [virtual table].  Each subclass will
4832** be tailored to the specific needs of the module implementation.
4833** The purpose of this superclass is to define certain fields that are
4834** common to all module implementations.
4835**
4836** ^Virtual tables methods can set an error message by assigning a
4837** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
4838** take care that any prior string is freed by a call to [sqlite3_free()]
4839** prior to assigning a new string to zErrMsg.  ^After the error message
4840** is delivered up to the client application, the string will be automatically
4841** freed by sqlite3_free() and the zErrMsg field will be zeroed.
4842*/
4843struct sqlite3_vtab {
4844  const sqlite3_module *pModule;  /* The module for this virtual table */
4845  int nRef;                       /* NO LONGER USED */
4846  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
4847  /* Virtual table implementations will typically add additional fields */
4848};
4849
4850/*
4851** CAPI3REF: Virtual Table Cursor Object
4852** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
4853** EXPERIMENTAL
4854**
4855** Every [virtual table module] implementation uses a subclass of the
4856** following structure to describe cursors that point into the
4857** [virtual table] and are used
4858** to loop through the virtual table.  Cursors are created using the
4859** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
4860** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
4861** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
4862** of the module.  Each module implementation will define
4863** the content of a cursor structure to suit its own needs.
4864**
4865** This superclass exists in order to define fields of the cursor that
4866** are common to all implementations.
4867*/
4868struct sqlite3_vtab_cursor {
4869  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
4870  /* Virtual table implementations will typically add additional fields */
4871};
4872
4873/*
4874** CAPI3REF: Declare The Schema Of A Virtual Table
4875** EXPERIMENTAL
4876**
4877** ^The [xCreate] and [xConnect] methods of a
4878** [virtual table module] call this interface
4879** to declare the format (the names and datatypes of the columns) of
4880** the virtual tables they implement.
4881*/
4882SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
4883
4884/*
4885** CAPI3REF: Overload A Function For A Virtual Table
4886** EXPERIMENTAL
4887**
4888** ^(Virtual tables can provide alternative implementations of functions
4889** using the [xFindFunction] method of the [virtual table module].
4890** But global versions of those functions
4891** must exist in order to be overloaded.)^
4892**
4893** ^(This API makes sure a global version of a function with a particular
4894** name and number of parameters exists.  If no such function exists
4895** before this API is called, a new function is created.)^  ^The implementation
4896** of the new function always causes an exception to be thrown.  So
4897** the new function is not good for anything by itself.  Its only
4898** purpose is to be a placeholder function that can be overloaded
4899** by a [virtual table].
4900*/
4901SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
4902
4903/*
4904** The interface to the virtual-table mechanism defined above (back up
4905** to a comment remarkably similar to this one) is currently considered
4906** to be experimental.  The interface might change in incompatible ways.
4907** If this is a problem for you, do not use the interface at this time.
4908**
4909** When the virtual-table mechanism stabilizes, we will declare the
4910** interface fixed, support it indefinitely, and remove this comment.
4911**
4912****** EXPERIMENTAL - subject to change without notice **************
4913*/
4914
4915/*
4916** CAPI3REF: A Handle To An Open BLOB
4917** KEYWORDS: {BLOB handle} {BLOB handles}
4918**
4919** An instance of this object represents an open BLOB on which
4920** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
4921** ^Objects of this type are created by [sqlite3_blob_open()]
4922** and destroyed by [sqlite3_blob_close()].
4923** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
4924** can be used to read or write small subsections of the BLOB.
4925** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
4926*/
4927typedef struct sqlite3_blob sqlite3_blob;
4928
4929/*
4930** CAPI3REF: Open A BLOB For Incremental I/O
4931**
4932** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
4933** in row iRow, column zColumn, table zTable in database zDb;
4934** in other words, the same BLOB that would be selected by:
4935**
4936** <pre>
4937**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
4938** </pre>)^
4939**
4940** ^If the flags parameter is non-zero, then the BLOB is opened for read
4941** and write access. ^If it is zero, the BLOB is opened for read access.
4942** ^It is not possible to open a column that is part of an index or primary
4943** key for writing. ^If [foreign key constraints] are enabled, it is
4944** not possible to open a column that is part of a [child key] for writing.
4945**
4946** ^Note that the database name is not the filename that contains
4947** the database but rather the symbolic name of the database that
4948** appears after the AS keyword when the database is connected using [ATTACH].
4949** ^For the main database file, the database name is "main".
4950** ^For TEMP tables, the database name is "temp".
4951**
4952** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
4953** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
4954** to be a null pointer.)^
4955** ^This function sets the [database connection] error code and message
4956** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
4957** functions. ^Note that the *ppBlob variable is always initialized in a
4958** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
4959** regardless of the success or failure of this routine.
4960**
4961** ^(If the row that a BLOB handle points to is modified by an
4962** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
4963** then the BLOB handle is marked as "expired".
4964** This is true if any column of the row is changed, even a column
4965** other than the one the BLOB handle is open on.)^
4966** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
4967** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
4968** ^(Changes written into a BLOB prior to the BLOB expiring are not
4969** rolled back by the expiration of the BLOB.  Such changes will eventually
4970** commit if the transaction continues to completion.)^
4971**
4972** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
4973** the opened blob.  ^The size of a blob may not be changed by this
4974** interface.  Use the [UPDATE] SQL command to change the size of a
4975** blob.
4976**
4977** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
4978** and the built-in [zeroblob] SQL function can be used, if desired,
4979** to create an empty, zero-filled blob in which to read or write using
4980** this interface.
4981**
4982** To avoid a resource leak, every open [BLOB handle] should eventually
4983** be released by a call to [sqlite3_blob_close()].
4984*/
4985SQLITE_API int sqlite3_blob_open(
4986  sqlite3*,
4987  const char *zDb,
4988  const char *zTable,
4989  const char *zColumn,
4990  sqlite3_int64 iRow,
4991  int flags,
4992  sqlite3_blob **ppBlob
4993);
4994
4995/*
4996** CAPI3REF: Close A BLOB Handle
4997**
4998** ^Closes an open [BLOB handle].
4999**
5000** ^Closing a BLOB shall cause the current transaction to commit
5001** if there are no other BLOBs, no pending prepared statements, and the
5002** database connection is in [autocommit mode].
5003** ^If any writes were made to the BLOB, they might be held in cache
5004** until the close operation if they will fit.
5005**
5006** ^(Closing the BLOB often forces the changes
5007** out to disk and so if any I/O errors occur, they will likely occur
5008** at the time when the BLOB is closed.  Any errors that occur during
5009** closing are reported as a non-zero return value.)^
5010**
5011** ^(The BLOB is closed unconditionally.  Even if this routine returns
5012** an error code, the BLOB is still closed.)^
5013**
5014** ^Calling this routine with a null pointer (such as would be returned
5015** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5016*/
5017SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5018
5019/*
5020** CAPI3REF: Return The Size Of An Open BLOB
5021**
5022** ^Returns the size in bytes of the BLOB accessible via the
5023** successfully opened [BLOB handle] in its only argument.  ^The
5024** incremental blob I/O routines can only read or overwriting existing
5025** blob content; they cannot change the size of a blob.
5026**
5027** This routine only works on a [BLOB handle] which has been created
5028** by a prior successful call to [sqlite3_blob_open()] and which has not
5029** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5030** to this routine results in undefined and probably undesirable behavior.
5031*/
5032SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5033
5034/*
5035** CAPI3REF: Read Data From A BLOB Incrementally
5036**
5037** ^(This function is used to read data from an open [BLOB handle] into a
5038** caller-supplied buffer. N bytes of data are copied into buffer Z
5039** from the open BLOB, starting at offset iOffset.)^
5040**
5041** ^If offset iOffset is less than N bytes from the end of the BLOB,
5042** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5043** less than zero, [SQLITE_ERROR] is returned and no data is read.
5044** ^The size of the blob (and hence the maximum value of N+iOffset)
5045** can be determined using the [sqlite3_blob_bytes()] interface.
5046**
5047** ^An attempt to read from an expired [BLOB handle] fails with an
5048** error code of [SQLITE_ABORT].
5049**
5050** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5051** Otherwise, an [error code] or an [extended error code] is returned.)^
5052**
5053** This routine only works on a [BLOB handle] which has been created
5054** by a prior successful call to [sqlite3_blob_open()] and which has not
5055** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5056** to this routine results in undefined and probably undesirable behavior.
5057**
5058** See also: [sqlite3_blob_write()].
5059*/
5060SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5061
5062/*
5063** CAPI3REF: Write Data Into A BLOB Incrementally
5064**
5065** ^This function is used to write data into an open [BLOB handle] from a
5066** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5067** into the open BLOB, starting at offset iOffset.
5068**
5069** ^If the [BLOB handle] passed as the first argument was not opened for
5070** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5071** this function returns [SQLITE_READONLY].
5072**
5073** ^This function may only modify the contents of the BLOB; it is
5074** not possible to increase the size of a BLOB using this API.
5075** ^If offset iOffset is less than N bytes from the end of the BLOB,
5076** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5077** less than zero [SQLITE_ERROR] is returned and no data is written.
5078** The size of the BLOB (and hence the maximum value of N+iOffset)
5079** can be determined using the [sqlite3_blob_bytes()] interface.
5080**
5081** ^An attempt to write to an expired [BLOB handle] fails with an
5082** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5083** before the [BLOB handle] expired are not rolled back by the
5084** expiration of the handle, though of course those changes might
5085** have been overwritten by the statement that expired the BLOB handle
5086** or by other independent statements.
5087**
5088** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5089** Otherwise, an  [error code] or an [extended error code] is returned.)^
5090**
5091** This routine only works on a [BLOB handle] which has been created
5092** by a prior successful call to [sqlite3_blob_open()] and which has not
5093** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5094** to this routine results in undefined and probably undesirable behavior.
5095**
5096** See also: [sqlite3_blob_read()].
5097*/
5098SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5099
5100/*
5101** CAPI3REF: Virtual File System Objects
5102**
5103** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5104** that SQLite uses to interact
5105** with the underlying operating system.  Most SQLite builds come with a
5106** single default VFS that is appropriate for the host computer.
5107** New VFSes can be registered and existing VFSes can be unregistered.
5108** The following interfaces are provided.
5109**
5110** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5111** ^Names are case sensitive.
5112** ^Names are zero-terminated UTF-8 strings.
5113** ^If there is no match, a NULL pointer is returned.
5114** ^If zVfsName is NULL then the default VFS is returned.
5115**
5116** ^New VFSes are registered with sqlite3_vfs_register().
5117** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5118** ^The same VFS can be registered multiple times without injury.
5119** ^To make an existing VFS into the default VFS, register it again
5120** with the makeDflt flag set.  If two different VFSes with the
5121** same name are registered, the behavior is undefined.  If a
5122** VFS is registered with a name that is NULL or an empty string,
5123** then the behavior is undefined.
5124**
5125** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5126** ^(If the default VFS is unregistered, another VFS is chosen as
5127** the default.  The choice for the new VFS is arbitrary.)^
5128*/
5129SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5130SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5131SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5132
5133/*
5134** CAPI3REF: Mutexes
5135**
5136** The SQLite core uses these routines for thread
5137** synchronization. Though they are intended for internal
5138** use by SQLite, code that links against SQLite is
5139** permitted to use any of these routines.
5140**
5141** The SQLite source code contains multiple implementations
5142** of these mutex routines.  An appropriate implementation
5143** is selected automatically at compile-time.  ^(The following
5144** implementations are available in the SQLite core:
5145**
5146** <ul>
5147** <li>   SQLITE_MUTEX_OS2
5148** <li>   SQLITE_MUTEX_PTHREAD
5149** <li>   SQLITE_MUTEX_W32
5150** <li>   SQLITE_MUTEX_NOOP
5151** </ul>)^
5152**
5153** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5154** that does no real locking and is appropriate for use in
5155** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5156** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5157** are appropriate for use on OS/2, Unix, and Windows.
5158**
5159** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5160** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5161** implementation is included with the library. In this case the
5162** application must supply a custom mutex implementation using the
5163** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5164** before calling sqlite3_initialize() or any other public sqlite3_
5165** function that calls sqlite3_initialize().)^
5166**
5167** ^The sqlite3_mutex_alloc() routine allocates a new
5168** mutex and returns a pointer to it. ^If it returns NULL
5169** that means that a mutex could not be allocated.  ^SQLite
5170** will unwind its stack and return an error.  ^(The argument
5171** to sqlite3_mutex_alloc() is one of these integer constants:
5172**
5173** <ul>
5174** <li>  SQLITE_MUTEX_FAST
5175** <li>  SQLITE_MUTEX_RECURSIVE
5176** <li>  SQLITE_MUTEX_STATIC_MASTER
5177** <li>  SQLITE_MUTEX_STATIC_MEM
5178** <li>  SQLITE_MUTEX_STATIC_MEM2
5179** <li>  SQLITE_MUTEX_STATIC_PRNG
5180** <li>  SQLITE_MUTEX_STATIC_LRU
5181** <li>  SQLITE_MUTEX_STATIC_LRU2
5182** </ul>)^
5183**
5184** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5185** cause sqlite3_mutex_alloc() to create
5186** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5187** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5188** The mutex implementation does not need to make a distinction
5189** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5190** not want to.  ^SQLite will only request a recursive mutex in
5191** cases where it really needs one.  ^If a faster non-recursive mutex
5192** implementation is available on the host platform, the mutex subsystem
5193** might return such a mutex in response to SQLITE_MUTEX_FAST.
5194**
5195** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5196** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5197** a pointer to a static preexisting mutex.  ^Six static mutexes are
5198** used by the current version of SQLite.  Future versions of SQLite
5199** may add additional static mutexes.  Static mutexes are for internal
5200** use by SQLite only.  Applications that use SQLite mutexes should
5201** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5202** SQLITE_MUTEX_RECURSIVE.
5203**
5204** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5205** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5206** returns a different mutex on every call.  ^But for the static
5207** mutex types, the same mutex is returned on every call that has
5208** the same type number.
5209**
5210** ^The sqlite3_mutex_free() routine deallocates a previously
5211** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5212** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5213** use when they are deallocated.  Attempting to deallocate a static
5214** mutex results in undefined behavior.  ^SQLite never deallocates
5215** a static mutex.
5216**
5217** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5218** to enter a mutex.  ^If another thread is already within the mutex,
5219** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5220** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5221** upon successful entry.  ^(Mutexes created using
5222** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5223** In such cases the,
5224** mutex must be exited an equal number of times before another thread
5225** can enter.)^  ^(If the same thread tries to enter any other
5226** kind of mutex more than once, the behavior is undefined.
5227** SQLite will never exhibit
5228** such behavior in its own use of mutexes.)^
5229**
5230** ^(Some systems (for example, Windows 95) do not support the operation
5231** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5232** will always return SQLITE_BUSY.  The SQLite core only ever uses
5233** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5234**
5235** ^The sqlite3_mutex_leave() routine exits a mutex that was
5236** previously entered by the same thread.   ^(The behavior
5237** is undefined if the mutex is not currently entered by the
5238** calling thread or is not currently allocated.  SQLite will
5239** never do either.)^
5240**
5241** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5242** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5243** behave as no-ops.
5244**
5245** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5246*/
5247SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5248SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5249SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5250SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5251SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5252
5253/*
5254** CAPI3REF: Mutex Methods Object
5255** EXPERIMENTAL
5256**
5257** An instance of this structure defines the low-level routines
5258** used to allocate and use mutexes.
5259**
5260** Usually, the default mutex implementations provided by SQLite are
5261** sufficient, however the user has the option of substituting a custom
5262** implementation for specialized deployments or systems for which SQLite
5263** does not provide a suitable implementation. In this case, the user
5264** creates and populates an instance of this structure to pass
5265** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5266** Additionally, an instance of this structure can be used as an
5267** output variable when querying the system for the current mutex
5268** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5269**
5270** ^The xMutexInit method defined by this structure is invoked as
5271** part of system initialization by the sqlite3_initialize() function.
5272** ^The xMutexInit routine is calle by SQLite exactly once for each
5273** effective call to [sqlite3_initialize()].
5274**
5275** ^The xMutexEnd method defined by this structure is invoked as
5276** part of system shutdown by the sqlite3_shutdown() function. The
5277** implementation of this method is expected to release all outstanding
5278** resources obtained by the mutex methods implementation, especially
5279** those obtained by the xMutexInit method.  ^The xMutexEnd()
5280** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5281**
5282** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5283** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5284** xMutexNotheld) implement the following interfaces (respectively):
5285**
5286** <ul>
5287**   <li>  [sqlite3_mutex_alloc()] </li>
5288**   <li>  [sqlite3_mutex_free()] </li>
5289**   <li>  [sqlite3_mutex_enter()] </li>
5290**   <li>  [sqlite3_mutex_try()] </li>
5291**   <li>  [sqlite3_mutex_leave()] </li>
5292**   <li>  [sqlite3_mutex_held()] </li>
5293**   <li>  [sqlite3_mutex_notheld()] </li>
5294** </ul>)^
5295**
5296** The only difference is that the public sqlite3_XXX functions enumerated
5297** above silently ignore any invocations that pass a NULL pointer instead
5298** of a valid mutex handle. The implementations of the methods defined
5299** by this structure are not required to handle this case, the results
5300** of passing a NULL pointer instead of a valid mutex handle are undefined
5301** (i.e. it is acceptable to provide an implementation that segfaults if
5302** it is passed a NULL pointer).
5303**
5304** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5305** invoke xMutexInit() mutiple times within the same process and without
5306** intervening calls to xMutexEnd().  Second and subsequent calls to
5307** xMutexInit() must be no-ops.
5308**
5309** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5310** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5311** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5312** memory allocation for a fast or recursive mutex.
5313**
5314** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5315** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5316** If xMutexInit fails in any way, it is expected to clean up after itself
5317** prior to returning.
5318*/
5319typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5320struct sqlite3_mutex_methods {
5321  int (*xMutexInit)(void);
5322  int (*xMutexEnd)(void);
5323  sqlite3_mutex *(*xMutexAlloc)(int);
5324  void (*xMutexFree)(sqlite3_mutex *);
5325  void (*xMutexEnter)(sqlite3_mutex *);
5326  int (*xMutexTry)(sqlite3_mutex *);
5327  void (*xMutexLeave)(sqlite3_mutex *);
5328  int (*xMutexHeld)(sqlite3_mutex *);
5329  int (*xMutexNotheld)(sqlite3_mutex *);
5330};
5331
5332/*
5333** CAPI3REF: Mutex Verification Routines
5334**
5335** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5336** are intended for use inside assert() statements.  ^The SQLite core
5337** never uses these routines except inside an assert() and applications
5338** are advised to follow the lead of the core.  ^The SQLite core only
5339** provides implementations for these routines when it is compiled
5340** with the SQLITE_DEBUG flag.  ^External mutex implementations
5341** are only required to provide these routines if SQLITE_DEBUG is
5342** defined and if NDEBUG is not defined.
5343**
5344** ^These routines should return true if the mutex in their argument
5345** is held or not held, respectively, by the calling thread.
5346**
5347** ^The implementation is not required to provided versions of these
5348** routines that actually work. If the implementation does not provide working
5349** versions of these routines, it should at least provide stubs that always
5350** return true so that one does not get spurious assertion failures.
5351**
5352** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
5353** the routine should return 1.   This seems counter-intuitive since
5354** clearly the mutex cannot be held if it does not exist.  But the
5355** the reason the mutex does not exist is because the build is not
5356** using mutexes.  And we do not want the assert() containing the
5357** call to sqlite3_mutex_held() to fail, so a non-zero return is
5358** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
5359** interface should also return 1 when given a NULL pointer.
5360*/
5361#ifndef NDEBUG
5362SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5363SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5364#endif
5365
5366/*
5367** CAPI3REF: Mutex Types
5368**
5369** The [sqlite3_mutex_alloc()] interface takes a single argument
5370** which is one of these integer constants.
5371**
5372** The set of static mutexes may change from one SQLite release to the
5373** next.  Applications that override the built-in mutex logic must be
5374** prepared to accommodate additional static mutexes.
5375*/
5376#define SQLITE_MUTEX_FAST             0
5377#define SQLITE_MUTEX_RECURSIVE        1
5378#define SQLITE_MUTEX_STATIC_MASTER    2
5379#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5380#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
5381#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
5382#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5383#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5384#define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
5385
5386/*
5387** CAPI3REF: Retrieve the mutex for a database connection
5388**
5389** ^This interface returns a pointer the [sqlite3_mutex] object that
5390** serializes access to the [database connection] given in the argument
5391** when the [threading mode] is Serialized.
5392** ^If the [threading mode] is Single-thread or Multi-thread then this
5393** routine returns a NULL pointer.
5394*/
5395SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
5396
5397/*
5398** CAPI3REF: Low-Level Control Of Database Files
5399**
5400** ^The [sqlite3_file_control()] interface makes a direct call to the
5401** xFileControl method for the [sqlite3_io_methods] object associated
5402** with a particular database identified by the second argument. ^The
5403** name of the database "main" for the main database or "temp" for the
5404** TEMP database, or the name that appears after the AS keyword for
5405** databases that are added using the [ATTACH] SQL command.
5406** ^A NULL pointer can be used in place of "main" to refer to the
5407** main database file.
5408** ^The third and fourth parameters to this routine
5409** are passed directly through to the second and third parameters of
5410** the xFileControl method.  ^The return value of the xFileControl
5411** method becomes the return value of this routine.
5412**
5413** ^If the second parameter (zDbName) does not match the name of any
5414** open database file, then SQLITE_ERROR is returned.  ^This error
5415** code is not remembered and will not be recalled by [sqlite3_errcode()]
5416** or [sqlite3_errmsg()].  The underlying xFileControl method might
5417** also return SQLITE_ERROR.  There is no way to distinguish between
5418** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5419** xFileControl method.
5420**
5421** See also: [SQLITE_FCNTL_LOCKSTATE]
5422*/
5423SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5424
5425/*
5426** CAPI3REF: Testing Interface
5427**
5428** ^The sqlite3_test_control() interface is used to read out internal
5429** state of SQLite and to inject faults into SQLite for testing
5430** purposes.  ^The first parameter is an operation code that determines
5431** the number, meaning, and operation of all subsequent parameters.
5432**
5433** This interface is not for use by applications.  It exists solely
5434** for verifying the correct operation of the SQLite library.  Depending
5435** on how the SQLite library is compiled, this interface might not exist.
5436**
5437** The details of the operation codes, their meanings, the parameters
5438** they take, and what they do are all subject to change without notice.
5439** Unlike most of the SQLite API, this function is not guaranteed to
5440** operate consistently from one release to the next.
5441*/
5442SQLITE_API int sqlite3_test_control(int op, ...);
5443
5444/*
5445** CAPI3REF: Testing Interface Operation Codes
5446**
5447** These constants are the valid operation code parameters used
5448** as the first argument to [sqlite3_test_control()].
5449**
5450** These parameters and their meanings are subject to change
5451** without notice.  These values are for testing purposes only.
5452** Applications should not use any of these parameters or the
5453** [sqlite3_test_control()] interface.
5454*/
5455#define SQLITE_TESTCTRL_FIRST                    5
5456#define SQLITE_TESTCTRL_PRNG_SAVE                5
5457#define SQLITE_TESTCTRL_PRNG_RESTORE             6
5458#define SQLITE_TESTCTRL_PRNG_RESET               7
5459#define SQLITE_TESTCTRL_BITVEC_TEST              8
5460#define SQLITE_TESTCTRL_FAULT_INSTALL            9
5461#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
5462#define SQLITE_TESTCTRL_PENDING_BYTE            11
5463#define SQLITE_TESTCTRL_ASSERT                  12
5464#define SQLITE_TESTCTRL_ALWAYS                  13
5465#define SQLITE_TESTCTRL_RESERVE                 14
5466#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5467#define SQLITE_TESTCTRL_ISKEYWORD               16
5468#define SQLITE_TESTCTRL_LAST                    16
5469
5470/*
5471** CAPI3REF: SQLite Runtime Status
5472** EXPERIMENTAL
5473**
5474** ^This interface is used to retrieve runtime status information
5475** about the preformance of SQLite, and optionally to reset various
5476** highwater marks.  ^The first argument is an integer code for
5477** the specific parameter to measure.  ^(Recognized integer codes
5478** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5479** ^The current value of the parameter is returned into *pCurrent.
5480** ^The highest recorded value is returned in *pHighwater.  ^If the
5481** resetFlag is true, then the highest record value is reset after
5482** *pHighwater is written.  ^(Some parameters do not record the highest
5483** value.  For those parameters
5484** nothing is written into *pHighwater and the resetFlag is ignored.)^
5485** ^(Other parameters record only the highwater mark and not the current
5486** value.  For these latter parameters nothing is written into *pCurrent.)^
5487**
5488** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5489** non-zero [error code] on failure.
5490**
5491** This routine is threadsafe but is not atomic.  This routine can be
5492** called while other threads are running the same or different SQLite
5493** interfaces.  However the values returned in *pCurrent and
5494** *pHighwater reflect the status of SQLite at different points in time
5495** and it is possible that another thread might change the parameter
5496** in between the times when *pCurrent and *pHighwater are written.
5497**
5498** See also: [sqlite3_db_status()]
5499*/
5500SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5501
5502
5503/*
5504** CAPI3REF: Status Parameters
5505** EXPERIMENTAL
5506**
5507** These integer constants designate various run-time status parameters
5508** that can be returned by [sqlite3_status()].
5509**
5510** <dl>
5511** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
5512** <dd>This parameter is the current amount of memory checked out
5513** using [sqlite3_malloc()], either directly or indirectly.  The
5514** figure includes calls made to [sqlite3_malloc()] by the application
5515** and internal memory usage by the SQLite library.  Scratch memory
5516** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
5517** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
5518** this parameter.  The amount returned is the sum of the allocation
5519** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
5520**
5521** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
5522** <dd>This parameter records the largest memory allocation request
5523** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
5524** internal equivalents).  Only the value returned in the
5525** *pHighwater parameter to [sqlite3_status()] is of interest.
5526** The value written into the *pCurrent parameter is undefined.</dd>)^
5527**
5528** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
5529** <dd>This parameter returns the number of pages used out of the
5530** [pagecache memory allocator] that was configured using
5531** [SQLITE_CONFIG_PAGECACHE].  The
5532** value returned is in pages, not in bytes.</dd>)^
5533**
5534** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
5535** <dd>This parameter returns the number of bytes of page cache
5536** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
5537** buffer and where forced to overflow to [sqlite3_malloc()].  The
5538** returned value includes allocations that overflowed because they
5539** where too large (they were larger than the "sz" parameter to
5540** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
5541** no space was left in the page cache.</dd>)^
5542**
5543** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
5544** <dd>This parameter records the largest memory allocation request
5545** handed to [pagecache memory allocator].  Only the value returned in the
5546** *pHighwater parameter to [sqlite3_status()] is of interest.
5547** The value written into the *pCurrent parameter is undefined.</dd>)^
5548**
5549** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
5550** <dd>This parameter returns the number of allocations used out of the
5551** [scratch memory allocator] configured using
5552** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
5553** in bytes.  Since a single thread may only have one scratch allocation
5554** outstanding at time, this parameter also reports the number of threads
5555** using scratch memory at the same time.</dd>)^
5556**
5557** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
5558** <dd>This parameter returns the number of bytes of scratch memory
5559** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
5560** buffer and where forced to overflow to [sqlite3_malloc()].  The values
5561** returned include overflows because the requested allocation was too
5562** larger (that is, because the requested allocation was larger than the
5563** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
5564** slots were available.
5565** </dd>)^
5566**
5567** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
5568** <dd>This parameter records the largest memory allocation request
5569** handed to [scratch memory allocator].  Only the value returned in the
5570** *pHighwater parameter to [sqlite3_status()] is of interest.
5571** The value written into the *pCurrent parameter is undefined.</dd>)^
5572**
5573** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
5574** <dd>This parameter records the deepest parser stack.  It is only
5575** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
5576** </dl>
5577**
5578** New status parameters may be added from time to time.
5579*/
5580#define SQLITE_STATUS_MEMORY_USED          0
5581#define SQLITE_STATUS_PAGECACHE_USED       1
5582#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
5583#define SQLITE_STATUS_SCRATCH_USED         3
5584#define SQLITE_STATUS_SCRATCH_OVERFLOW     4
5585#define SQLITE_STATUS_MALLOC_SIZE          5
5586#define SQLITE_STATUS_PARSER_STACK         6
5587#define SQLITE_STATUS_PAGECACHE_SIZE       7
5588#define SQLITE_STATUS_SCRATCH_SIZE         8
5589
5590/*
5591** CAPI3REF: Database Connection Status
5592** EXPERIMENTAL
5593**
5594** ^This interface is used to retrieve runtime status information
5595** about a single [database connection].  ^The first argument is the
5596** database connection object to be interrogated.  ^The second argument
5597** is the parameter to interrogate.  ^Currently, the only allowed value
5598** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
5599** Additional options will likely appear in future releases of SQLite.
5600**
5601** ^The current value of the requested parameter is written into *pCur
5602** and the highest instantaneous value is written into *pHiwtr.  ^If
5603** the resetFlg is true, then the highest instantaneous value is
5604** reset back down to the current value.
5605**
5606** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5607*/
5608SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5609
5610/*
5611** CAPI3REF: Status Parameters for database connections
5612** EXPERIMENTAL
5613**
5614** These constants are the available integer "verbs" that can be passed as
5615** the second argument to the [sqlite3_db_status()] interface.
5616**
5617** New verbs may be added in future releases of SQLite. Existing verbs
5618** might be discontinued. Applications should check the return code from
5619** [sqlite3_db_status()] to make sure that the call worked.
5620** The [sqlite3_db_status()] interface will return a non-zero error code
5621** if a discontinued or unsupported verb is invoked.
5622**
5623** <dl>
5624** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
5625** <dd>This parameter returns the number of lookaside memory slots currently
5626** checked out.</dd>)^
5627** </dl>
5628*/
5629#define SQLITE_DBSTATUS_LOOKASIDE_USED     0
5630
5631
5632/*
5633** CAPI3REF: Prepared Statement Status
5634** EXPERIMENTAL
5635**
5636** ^(Each prepared statement maintains various
5637** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
5638** of times it has performed specific operations.)^  These counters can
5639** be used to monitor the performance characteristics of the prepared
5640** statements.  For example, if the number of table steps greatly exceeds
5641** the number of table searches or result rows, that would tend to indicate
5642** that the prepared statement is using a full table scan rather than
5643** an index.
5644**
5645** ^(This interface is used to retrieve and reset counter values from
5646** a [prepared statement].  The first argument is the prepared statement
5647** object to be interrogated.  The second argument
5648** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
5649** to be interrogated.)^
5650** ^The current value of the requested counter is returned.
5651** ^If the resetFlg is true, then the counter is reset to zero after this
5652** interface call returns.
5653**
5654** See also: [sqlite3_status()] and [sqlite3_db_status()].
5655*/
5656SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
5657
5658/*
5659** CAPI3REF: Status Parameters for prepared statements
5660** EXPERIMENTAL
5661**
5662** These preprocessor macros define integer codes that name counter
5663** values associated with the [sqlite3_stmt_status()] interface.
5664** The meanings of the various counters are as follows:
5665**
5666** <dl>
5667** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
5668** <dd>^This is the number of times that SQLite has stepped forward in
5669** a table as part of a full table scan.  Large numbers for this counter
5670** may indicate opportunities for performance improvement through
5671** careful use of indices.</dd>
5672**
5673** <dt>SQLITE_STMTSTATUS_SORT</dt>
5674** <dd>^This is the number of sort operations that have occurred.
5675** A non-zero value in this counter may indicate an opportunity to
5676** improvement performance through careful use of indices.</dd>
5677**
5678** </dl>
5679*/
5680#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
5681#define SQLITE_STMTSTATUS_SORT              2
5682
5683/*
5684** CAPI3REF: Custom Page Cache Object
5685** EXPERIMENTAL
5686**
5687** The sqlite3_pcache type is opaque.  It is implemented by
5688** the pluggable module.  The SQLite core has no knowledge of
5689** its size or internal structure and never deals with the
5690** sqlite3_pcache object except by holding and passing pointers
5691** to the object.
5692**
5693** See [sqlite3_pcache_methods] for additional information.
5694*/
5695typedef struct sqlite3_pcache sqlite3_pcache;
5696
5697/*
5698** CAPI3REF: Application Defined Page Cache.
5699** KEYWORDS: {page cache}
5700** EXPERIMENTAL
5701**
5702** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
5703** register an alternative page cache implementation by passing in an
5704** instance of the sqlite3_pcache_methods structure.)^ The majority of the
5705** heap memory used by SQLite is used by the page cache to cache data read
5706** from, or ready to be written to, the database file. By implementing a
5707** custom page cache using this API, an application can control more
5708** precisely the amount of memory consumed by SQLite, the way in which
5709** that memory is allocated and released, and the policies used to
5710** determine exactly which parts of a database file are cached and for
5711** how long.
5712**
5713** ^(The contents of the sqlite3_pcache_methods structure are copied to an
5714** internal buffer by SQLite within the call to [sqlite3_config].  Hence
5715** the application may discard the parameter after the call to
5716** [sqlite3_config()] returns.)^
5717**
5718** ^The xInit() method is called once for each call to [sqlite3_initialize()]
5719** (usually only once during the lifetime of the process). ^(The xInit()
5720** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
5721** ^The xInit() method can set up up global structures and/or any mutexes
5722** required by the custom page cache implementation.
5723**
5724** ^The xShutdown() method is called from within [sqlite3_shutdown()],
5725** if the application invokes this API. It can be used to clean up
5726** any outstanding resources before process shutdown, if required.
5727**
5728** ^SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
5729** the xInit method, so the xInit method need not be threadsafe.  ^The
5730** xShutdown method is only called from [sqlite3_shutdown()] so it does
5731** not need to be threadsafe either.  All other methods must be threadsafe
5732** in multithreaded applications.
5733**
5734** ^SQLite will never invoke xInit() more than once without an intervening
5735** call to xShutdown().
5736**
5737** ^The xCreate() method is used to construct a new cache instance.  SQLite
5738** will typically create one cache instance for each open database file,
5739** though this is not guaranteed. ^The
5740** first parameter, szPage, is the size in bytes of the pages that must
5741** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
5742** will the page size of the database file that is to be cached plus an
5743** increment (here called "R") of about 100 or 200.  ^SQLite will use the
5744** extra R bytes on each page to store metadata about the underlying
5745** database page on disk.  The value of R depends
5746** on the SQLite version, the target platform, and how SQLite was compiled.
5747** ^R is constant for a particular build of SQLite.  ^The second argument to
5748** xCreate(), bPurgeable, is true if the cache being created will
5749** be used to cache database pages of a file stored on disk, or
5750** false if it is used for an in-memory database. ^The cache implementation
5751** does not have to do anything special based with the value of bPurgeable;
5752** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
5753** never invoke xUnpin() except to deliberately delete a page.
5754** ^In other words, a cache created with bPurgeable set to false will
5755** never contain any unpinned pages.
5756**
5757** ^(The xCachesize() method may be called at any time by SQLite to set the
5758** suggested maximum cache-size (number of pages stored by) the cache
5759** instance passed as the first argument. This is the value configured using
5760** the SQLite "[PRAGMA cache_size]" command.)^  ^As with the bPurgeable
5761** parameter, the implementation is not required to do anything with this
5762** value; it is advisory only.
5763**
5764** ^The xPagecount() method should return the number of pages currently
5765** stored in the cache.
5766**
5767** ^The xFetch() method is used to fetch a page and return a pointer to it.
5768** ^A 'page', in this context, is a buffer of szPage bytes aligned at an
5769** 8-byte boundary. ^The page to be fetched is determined by the key. ^The
5770** mimimum key value is 1. After it has been retrieved using xFetch, the page
5771** is considered to be "pinned".
5772**
5773** ^If the requested page is already in the page cache, then the page cache
5774** implementation must return a pointer to the page buffer with its content
5775** intact.  ^(If the requested page is not already in the cache, then the
5776** behavior of the cache implementation is determined by the value of the
5777** createFlag parameter passed to xFetch, according to the following table:
5778**
5779** <table border=1 width=85% align=center>
5780** <tr><th> createFlag <th> Behaviour when page is not already in cache
5781** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
5782** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
5783**                 Otherwise return NULL.
5784** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
5785**                 NULL if allocating a new page is effectively impossible.
5786** </table>)^
5787**
5788** SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  If
5789** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
5790** attempt to unpin one or more cache pages by spilling the content of
5791** pinned pages to disk and synching the operating system disk cache. After
5792** attempting to unpin pages, the xFetch() method will be invoked again with
5793** a createFlag of 2.
5794**
5795** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
5796** as its second argument. ^(If the third parameter, discard, is non-zero,
5797** then the page should be evicted from the cache. In this case SQLite
5798** assumes that the next time the page is retrieved from the cache using
5799** the xFetch() method, it will be zeroed.)^ ^If the discard parameter is
5800** zero, then the page is considered to be unpinned. ^The cache implementation
5801** may choose to evict unpinned pages at any time.
5802**
5803** ^(The cache is not required to perform any reference counting. A single
5804** call to xUnpin() unpins the page regardless of the number of prior calls
5805** to xFetch().)^
5806**
5807** ^The xRekey() method is used to change the key value associated with the
5808** page passed as the second argument from oldKey to newKey. ^If the cache
5809** previously contains an entry associated with newKey, it should be
5810** discarded. ^Any prior cache entry associated with newKey is guaranteed not
5811** to be pinned.
5812**
5813** ^When SQLite calls the xTruncate() method, the cache must discard all
5814** existing cache entries with page numbers (keys) greater than or equal
5815** to the value of the iLimit parameter passed to xTruncate(). ^If any
5816** of these pages are pinned, they are implicitly unpinned, meaning that
5817** they can be safely discarded.
5818**
5819** ^The xDestroy() method is used to delete a cache allocated by xCreate().
5820** All resources associated with the specified cache should be freed. ^After
5821** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
5822** handle invalid, and will not use it with any other sqlite3_pcache_methods
5823** functions.
5824*/
5825typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
5826struct sqlite3_pcache_methods {
5827  void *pArg;
5828  int (*xInit)(void*);
5829  void (*xShutdown)(void*);
5830  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
5831  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
5832  int (*xPagecount)(sqlite3_pcache*);
5833  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
5834  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
5835  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
5836  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
5837  void (*xDestroy)(sqlite3_pcache*);
5838};
5839
5840/*
5841** CAPI3REF: Online Backup Object
5842** EXPERIMENTAL
5843**
5844** The sqlite3_backup object records state information about an ongoing
5845** online backup operation.  ^The sqlite3_backup object is created by
5846** a call to [sqlite3_backup_init()] and is destroyed by a call to
5847** [sqlite3_backup_finish()].
5848**
5849** See Also: [Using the SQLite Online Backup API]
5850*/
5851typedef struct sqlite3_backup sqlite3_backup;
5852
5853/*
5854** CAPI3REF: Online Backup API.
5855** EXPERIMENTAL
5856**
5857** The backup API copies the content of one database into another.
5858** It is useful either for creating backups of databases or
5859** for copying in-memory databases to or from persistent files.
5860**
5861** See Also: [Using the SQLite Online Backup API]
5862**
5863** ^Exclusive access is required to the destination database for the
5864** duration of the operation. ^However the source database is only
5865** read-locked while it is actually being read; it is not locked
5866** continuously for the entire backup operation. ^Thus, the backup may be
5867** performed on a live source database without preventing other users from
5868** reading or writing to the source database while the backup is underway.
5869**
5870** ^(To perform a backup operation:
5871**   <ol>
5872**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
5873**         backup,
5874**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
5875**         the data between the two databases, and finally
5876**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
5877**         associated with the backup operation.
5878**   </ol>)^
5879** There should be exactly one call to sqlite3_backup_finish() for each
5880** successful call to sqlite3_backup_init().
5881**
5882** <b>sqlite3_backup_init()</b>
5883**
5884** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
5885** [database connection] associated with the destination database
5886** and the database name, respectively.
5887** ^The database name is "main" for the main database, "temp" for the
5888** temporary database, or the name specified after the AS keyword in
5889** an [ATTACH] statement for an attached database.
5890** ^The S and M arguments passed to
5891** sqlite3_backup_init(D,N,S,M) identify the [database connection]
5892** and database name of the source database, respectively.
5893** ^The source and destination [database connections] (parameters S and D)
5894** must be different or else sqlite3_backup_init(D,N,S,M) will file with
5895** an error.
5896**
5897** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
5898** returned and an error code and error message are store3d in the
5899** destination [database connection] D.
5900** ^The error code and message for the failed call to sqlite3_backup_init()
5901** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
5902** [sqlite3_errmsg16()] functions.
5903** ^A successful call to sqlite3_backup_init() returns a pointer to an
5904** [sqlite3_backup] object.
5905** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
5906** sqlite3_backup_finish() functions to perform the specified backup
5907** operation.
5908**
5909** <b>sqlite3_backup_step()</b>
5910**
5911** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
5912** the source and destination databases specified by [sqlite3_backup] object B.
5913** ^If N is negative, all remaining source pages are copied.
5914** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
5915** are still more pages to be copied, then the function resturns [SQLITE_OK].
5916** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
5917** from source to destination, then it returns [SQLITE_DONE].
5918** ^If an error occurs while running sqlite3_backup_step(B,N),
5919** then an [error code] is returned. ^As well as [SQLITE_OK] and
5920** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
5921** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
5922** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
5923**
5924** ^The sqlite3_backup_step() might return [SQLITE_READONLY] if the destination
5925** database was opened read-only or if
5926** the destination is an in-memory database with a different page size
5927** from the source database.
5928**
5929** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
5930** the [sqlite3_busy_handler | busy-handler function]
5931** is invoked (if one is specified). ^If the
5932** busy-handler returns non-zero before the lock is available, then
5933** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
5934** sqlite3_backup_step() can be retried later. ^If the source
5935** [database connection]
5936** is being used to write to the source database when sqlite3_backup_step()
5937** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
5938** case the call to sqlite3_backup_step() can be retried later on. ^(If
5939** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
5940** [SQLITE_READONLY] is returned, then
5941** there is no point in retrying the call to sqlite3_backup_step(). These
5942** errors are considered fatal.)^  The application must accept
5943** that the backup operation has failed and pass the backup operation handle
5944** to the sqlite3_backup_finish() to release associated resources.
5945**
5946** ^The first call to sqlite3_backup_step() obtains an exclusive lock
5947** on the destination file. ^The exclusive lock is not released until either
5948** sqlite3_backup_finish() is called or the backup operation is complete
5949** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
5950** sqlite3_backup_step() obtains a [shared lock] on the source database that
5951** lasts for the duration of the sqlite3_backup_step() call.
5952** ^Because the source database is not locked between calls to
5953** sqlite3_backup_step(), the source database may be modified mid-way
5954** through the backup process.  ^If the source database is modified by an
5955** external process or via a database connection other than the one being
5956** used by the backup operation, then the backup will be automatically
5957** restarted by the next call to sqlite3_backup_step(). ^If the source
5958** database is modified by the using the same database connection as is used
5959** by the backup operation, then the backup database is automatically
5960** updated at the same time.
5961**
5962** <b>sqlite3_backup_finish()</b>
5963**
5964** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
5965** application wishes to abandon the backup operation, the application
5966** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
5967** ^The sqlite3_backup_finish() interfaces releases all
5968** resources associated with the [sqlite3_backup] object.
5969** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
5970** active write-transaction on the destination database is rolled back.
5971** The [sqlite3_backup] object is invalid
5972** and may not be used following a call to sqlite3_backup_finish().
5973**
5974** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
5975** sqlite3_backup_step() errors occurred, regardless or whether or not
5976** sqlite3_backup_step() completed.
5977** ^If an out-of-memory condition or IO error occurred during any prior
5978** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
5979** sqlite3_backup_finish() returns the corresponding [error code].
5980**
5981** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
5982** is not a permanent error and does not affect the return value of
5983** sqlite3_backup_finish().
5984**
5985** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
5986**
5987** ^Each call to sqlite3_backup_step() sets two values inside
5988** the [sqlite3_backup] object: the number of pages still to be backed
5989** up and the total number of pages in the source databae file.
5990** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
5991** retrieve these two values, respectively.
5992**
5993** ^The values returned by these functions are only updated by
5994** sqlite3_backup_step(). ^If the source database is modified during a backup
5995** operation, then the values are not updated to account for any extra
5996** pages that need to be updated or the size of the source database file
5997** changing.
5998**
5999** <b>Concurrent Usage of Database Handles</b>
6000**
6001** ^The source [database connection] may be used by the application for other
6002** purposes while a backup operation is underway or being initialized.
6003** ^If SQLite is compiled and configured to support threadsafe database
6004** connections, then the source database connection may be used concurrently
6005** from within other threads.
6006**
6007** However, the application must guarantee that the destination
6008** [database connection] is not passed to any other API (by any thread) after
6009** sqlite3_backup_init() is called and before the corresponding call to
6010** sqlite3_backup_finish().  SQLite does not currently check to see
6011** if the application incorrectly accesses the destination [database connection]
6012** and so no error code is reported, but the operations may malfunction
6013** nevertheless.  Use of the destination database connection while a
6014** backup is in progress might also also cause a mutex deadlock.
6015**
6016** If running in [shared cache mode], the application must
6017** guarantee that the shared cache used by the destination database
6018** is not accessed while the backup is running. In practice this means
6019** that the application must guarantee that the disk file being
6020** backed up to is not accessed by any connection within the process,
6021** not just the specific connection that was passed to sqlite3_backup_init().
6022**
6023** The [sqlite3_backup] object itself is partially threadsafe. Multiple
6024** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6025** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6026** APIs are not strictly speaking threadsafe. If they are invoked at the
6027** same time as another thread is invoking sqlite3_backup_step() it is
6028** possible that they return invalid values.
6029*/
6030SQLITE_API sqlite3_backup *sqlite3_backup_init(
6031  sqlite3 *pDest,                        /* Destination database handle */
6032  const char *zDestName,                 /* Destination database name */
6033  sqlite3 *pSource,                      /* Source database handle */
6034  const char *zSourceName                /* Source database name */
6035);
6036SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6037SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6038SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6039SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6040
6041/*
6042** CAPI3REF: Unlock Notification
6043** EXPERIMENTAL
6044**
6045** ^When running in shared-cache mode, a database operation may fail with
6046** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6047** individual tables within the shared-cache cannot be obtained. See
6048** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
6049** ^This API may be used to register a callback that SQLite will invoke
6050** when the connection currently holding the required lock relinquishes it.
6051** ^This API is only available if the library was compiled with the
6052** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6053**
6054** See Also: [Using the SQLite Unlock Notification Feature].
6055**
6056** ^Shared-cache locks are released when a database connection concludes
6057** its current transaction, either by committing it or rolling it back.
6058**
6059** ^When a connection (known as the blocked connection) fails to obtain a
6060** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6061** identity of the database connection (the blocking connection) that
6062** has locked the required resource is stored internally. ^After an
6063** application receives an SQLITE_LOCKED error, it may call the
6064** sqlite3_unlock_notify() method with the blocked connection handle as
6065** the first argument to register for a callback that will be invoked
6066** when the blocking connections current transaction is concluded. ^The
6067** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6068** call that concludes the blocking connections transaction.
6069**
6070** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6071** there is a chance that the blocking connection will have already
6072** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6073** If this happens, then the specified callback is invoked immediately,
6074** from within the call to sqlite3_unlock_notify().)^
6075**
6076** ^If the blocked connection is attempting to obtain a write-lock on a
6077** shared-cache table, and more than one other connection currently holds
6078** a read-lock on the same table, then SQLite arbitrarily selects one of
6079** the other connections to use as the blocking connection.
6080**
6081** ^(There may be at most one unlock-notify callback registered by a
6082** blocked connection. If sqlite3_unlock_notify() is called when the
6083** blocked connection already has a registered unlock-notify callback,
6084** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6085** called with a NULL pointer as its second argument, then any existing
6086** unlock-notify callback is cancelled. ^The blocked connections
6087** unlock-notify callback may also be canceled by closing the blocked
6088** connection using [sqlite3_close()].
6089**
6090** The unlock-notify callback is not reentrant. If an application invokes
6091** any sqlite3_xxx API functions from within an unlock-notify callback, a
6092** crash or deadlock may be the result.
6093**
6094** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6095** returns SQLITE_OK.
6096**
6097** <b>Callback Invocation Details</b>
6098**
6099** When an unlock-notify callback is registered, the application provides a
6100** single void* pointer that is passed to the callback when it is invoked.
6101** However, the signature of the callback function allows SQLite to pass
6102** it an array of void* context pointers. The first argument passed to
6103** an unlock-notify callback is a pointer to an array of void* pointers,
6104** and the second is the number of entries in the array.
6105**
6106** When a blocking connections transaction is concluded, there may be
6107** more than one blocked connection that has registered for an unlock-notify
6108** callback. ^If two or more such blocked connections have specified the
6109** same callback function, then instead of invoking the callback function
6110** multiple times, it is invoked once with the set of void* context pointers
6111** specified by the blocked connections bundled together into an array.
6112** This gives the application an opportunity to prioritize any actions
6113** related to the set of unblocked database connections.
6114**
6115** <b>Deadlock Detection</b>
6116**
6117** Assuming that after registering for an unlock-notify callback a
6118** database waits for the callback to be issued before taking any further
6119** action (a reasonable assumption), then using this API may cause the
6120** application to deadlock. For example, if connection X is waiting for
6121** connection Y's transaction to be concluded, and similarly connection
6122** Y is waiting on connection X's transaction, then neither connection
6123** will proceed and the system may remain deadlocked indefinitely.
6124**
6125** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6126** detection. ^If a given call to sqlite3_unlock_notify() would put the
6127** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6128** unlock-notify callback is registered. The system is said to be in
6129** a deadlocked state if connection A has registered for an unlock-notify
6130** callback on the conclusion of connection B's transaction, and connection
6131** B has itself registered for an unlock-notify callback when connection
6132** A's transaction is concluded. ^Indirect deadlock is also detected, so
6133** the system is also considered to be deadlocked if connection B has
6134** registered for an unlock-notify callback on the conclusion of connection
6135** C's transaction, where connection C is waiting on connection A. ^Any
6136** number of levels of indirection are allowed.
6137**
6138** <b>The "DROP TABLE" Exception</b>
6139**
6140** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
6141** always appropriate to call sqlite3_unlock_notify(). There is however,
6142** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6143** SQLite checks if there are any currently executing SELECT statements
6144** that belong to the same connection. If there are, SQLITE_LOCKED is
6145** returned. In this case there is no "blocking connection", so invoking
6146** sqlite3_unlock_notify() results in the unlock-notify callback being
6147** invoked immediately. If the application then re-attempts the "DROP TABLE"
6148** or "DROP INDEX" query, an infinite loop might be the result.
6149**
6150** One way around this problem is to check the extended error code returned
6151** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6152** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6153** the special "DROP TABLE/INDEX" case, the extended error code is just
6154** SQLITE_LOCKED.)^
6155*/
6156SQLITE_API int sqlite3_unlock_notify(
6157  sqlite3 *pBlocked,                          /* Waiting connection */
6158  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6159  void *pNotifyArg                            /* Argument to pass to xNotify */
6160);
6161
6162
6163/*
6164** CAPI3REF: String Comparison
6165** EXPERIMENTAL
6166**
6167** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6168** compare the contents of two buffers containing UTF-8 strings in a
6169** case-indendent fashion, using the same definition of case independence
6170** that SQLite uses internally when comparing identifiers.
6171*/
6172SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6173
6174/*
6175** CAPI3REF: Error Logging Interface
6176** EXPERIMENTAL
6177**
6178** ^The [sqlite3_log()] interface writes a message into the error log
6179** established by the [SQLITE_CONFIG_ERRORLOG] option to [sqlite3_config()].
6180**
6181** The sqlite3_log() interface is intended for use by extensions such as
6182** virtual tables, collating functions, and SQL functions.  While there is
6183** nothing to prevent an application from calling sqlite3_log(), doing so
6184** is considered bad form.
6185**
6186** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6187** will not use dynamically allocated memory.  The log message is stored in
6188** a fixed-length buffer on the stack.  If the log message is longer than
6189** a few hundred characters, it will be truncated to the length of the
6190** buffer.
6191*/
6192SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6193
6194/*
6195** Undo the hack that converts floating point types to integer for
6196** builds on processors without floating point support.
6197*/
6198#ifdef SQLITE_OMIT_FLOATING_POINT
6199# undef double
6200#endif
6201
6202#if 0
6203}  /* End of the 'extern "C"' block */
6204#endif
6205#endif
6206
6207
6208/************** End of sqlite3.h *********************************************/
6209/************** Continuing where we left off in sqliteInt.h ******************/
6210/************** Include hash.h in the middle of sqliteInt.h ******************/
6211/************** Begin file hash.h ********************************************/
6212/*
6213** 2001 September 22
6214**
6215** The author disclaims copyright to this source code.  In place of
6216** a legal notice, here is a blessing:
6217**
6218**    May you do good and not evil.
6219**    May you find forgiveness for yourself and forgive others.
6220**    May you share freely, never taking more than you give.
6221**
6222*************************************************************************
6223** This is the header file for the generic hash-table implemenation
6224** used in SQLite.
6225*/
6226#ifndef _SQLITE_HASH_H_
6227#define _SQLITE_HASH_H_
6228
6229/* Forward declarations of structures. */
6230typedef struct Hash Hash;
6231typedef struct HashElem HashElem;
6232
6233/* A complete hash table is an instance of the following structure.
6234** The internals of this structure are intended to be opaque -- client
6235** code should not attempt to access or modify the fields of this structure
6236** directly.  Change this structure only by using the routines below.
6237** However, some of the "procedures" and "functions" for modifying and
6238** accessing this structure are really macros, so we can't really make
6239** this structure opaque.
6240**
6241** All elements of the hash table are on a single doubly-linked list.
6242** Hash.first points to the head of this list.
6243**
6244** There are Hash.htsize buckets.  Each bucket points to a spot in
6245** the global doubly-linked list.  The contents of the bucket are the
6246** element pointed to plus the next _ht.count-1 elements in the list.
6247**
6248** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
6249** by a linear search of the global list.  For small tables, the
6250** Hash.ht table is never allocated because if there are few elements
6251** in the table, it is faster to do a linear search than to manage
6252** the hash table.
6253*/
6254struct Hash {
6255  unsigned int htsize;      /* Number of buckets in the hash table */
6256  unsigned int count;       /* Number of entries in this table */
6257  HashElem *first;          /* The first element of the array */
6258  struct _ht {              /* the hash table */
6259    int count;                 /* Number of entries with this hash */
6260    HashElem *chain;           /* Pointer to first entry with this hash */
6261  } *ht;
6262};
6263
6264/* Each element in the hash table is an instance of the following
6265** structure.  All elements are stored on a single doubly-linked list.
6266**
6267** Again, this structure is intended to be opaque, but it can't really
6268** be opaque because it is used by macros.
6269*/
6270struct HashElem {
6271  HashElem *next, *prev;       /* Next and previous elements in the table */
6272  void *data;                  /* Data associated with this element */
6273  const char *pKey; int nKey;  /* Key associated with this element */
6274};
6275
6276/*
6277** Access routines.  To delete, insert a NULL pointer.
6278*/
6279SQLITE_PRIVATE void sqlite3HashInit(Hash*);
6280SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
6281SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
6282SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6283
6284/*
6285** Macros for looping over all elements of a hash table.  The idiom is
6286** like this:
6287**
6288**   Hash h;
6289**   HashElem *p;
6290**   ...
6291**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
6292**     SomeStructure *pData = sqliteHashData(p);
6293**     // do something with pData
6294**   }
6295*/
6296#define sqliteHashFirst(H)  ((H)->first)
6297#define sqliteHashNext(E)   ((E)->next)
6298#define sqliteHashData(E)   ((E)->data)
6299/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
6300/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
6301
6302/*
6303** Number of entries in a hash table
6304*/
6305/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
6306
6307#endif /* _SQLITE_HASH_H_ */
6308
6309/************** End of hash.h ************************************************/
6310/************** Continuing where we left off in sqliteInt.h ******************/
6311/************** Include parse.h in the middle of sqliteInt.h *****************/
6312/************** Begin file parse.h *******************************************/
6313#define TK_SEMI                            1
6314#define TK_EXPLAIN                         2
6315#define TK_QUERY                           3
6316#define TK_PLAN                            4
6317#define TK_BEGIN                           5
6318#define TK_TRANSACTION                     6
6319#define TK_DEFERRED                        7
6320#define TK_IMMEDIATE                       8
6321#define TK_EXCLUSIVE                       9
6322#define TK_COMMIT                         10
6323#define TK_END                            11
6324#define TK_ROLLBACK                       12
6325#define TK_SAVEPOINT                      13
6326#define TK_RELEASE                        14
6327#define TK_TO                             15
6328#define TK_TABLE                          16
6329#define TK_CREATE                         17
6330#define TK_IF                             18
6331#define TK_NOT                            19
6332#define TK_EXISTS                         20
6333#define TK_TEMP                           21
6334#define TK_LP                             22
6335#define TK_RP                             23
6336#define TK_AS                             24
6337#define TK_COMMA                          25
6338#define TK_ID                             26
6339#define TK_INDEXED                        27
6340#define TK_ABORT                          28
6341#define TK_ACTION                         29
6342#define TK_AFTER                          30
6343#define TK_ANALYZE                        31
6344#define TK_ASC                            32
6345#define TK_ATTACH                         33
6346#define TK_BEFORE                         34
6347#define TK_BY                             35
6348#define TK_CASCADE                        36
6349#define TK_CAST                           37
6350#define TK_COLUMNKW                       38
6351#define TK_CONFLICT                       39
6352#define TK_DATABASE                       40
6353#define TK_DESC                           41
6354#define TK_DETACH                         42
6355#define TK_EACH                           43
6356#define TK_FAIL                           44
6357#define TK_FOR                            45
6358#define TK_IGNORE                         46
6359#define TK_INITIALLY                      47
6360#define TK_INSTEAD                        48
6361#define TK_LIKE_KW                        49
6362#define TK_MATCH                          50
6363#define TK_NO                             51
6364#define TK_KEY                            52
6365#define TK_OF                             53
6366#define TK_OFFSET                         54
6367#define TK_PRAGMA                         55
6368#define TK_RAISE                          56
6369#define TK_REPLACE                        57
6370#define TK_RESTRICT                       58
6371#define TK_ROW                            59
6372#define TK_TRIGGER                        60
6373#define TK_VACUUM                         61
6374#define TK_VIEW                           62
6375#define TK_VIRTUAL                        63
6376#define TK_REINDEX                        64
6377#define TK_RENAME                         65
6378#define TK_CTIME_KW                       66
6379#define TK_ANY                            67
6380#define TK_OR                             68
6381#define TK_AND                            69
6382#define TK_IS                             70
6383#define TK_BETWEEN                        71
6384#define TK_IN                             72
6385#define TK_ISNULL                         73
6386#define TK_NOTNULL                        74
6387#define TK_NE                             75
6388#define TK_EQ                             76
6389#define TK_GT                             77
6390#define TK_LE                             78
6391#define TK_LT                             79
6392#define TK_GE                             80
6393#define TK_ESCAPE                         81
6394#define TK_BITAND                         82
6395#define TK_BITOR                          83
6396#define TK_LSHIFT                         84
6397#define TK_RSHIFT                         85
6398#define TK_PLUS                           86
6399#define TK_MINUS                          87
6400#define TK_STAR                           88
6401#define TK_SLASH                          89
6402#define TK_REM                            90
6403#define TK_CONCAT                         91
6404#define TK_COLLATE                        92
6405#define TK_BITNOT                         93
6406#define TK_STRING                         94
6407#define TK_JOIN_KW                        95
6408#define TK_CONSTRAINT                     96
6409#define TK_DEFAULT                        97
6410#define TK_NULL                           98
6411#define TK_PRIMARY                        99
6412#define TK_UNIQUE                         100
6413#define TK_CHECK                          101
6414#define TK_REFERENCES                     102
6415#define TK_AUTOINCR                       103
6416#define TK_ON                             104
6417#define TK_INSERT                         105
6418#define TK_DELETE                         106
6419#define TK_UPDATE                         107
6420#define TK_SET                            108
6421#define TK_DEFERRABLE                     109
6422#define TK_FOREIGN                        110
6423#define TK_DROP                           111
6424#define TK_UNION                          112
6425#define TK_ALL                            113
6426#define TK_EXCEPT                         114
6427#define TK_INTERSECT                      115
6428#define TK_SELECT                         116
6429#define TK_DISTINCT                       117
6430#define TK_DOT                            118
6431#define TK_FROM                           119
6432#define TK_JOIN                           120
6433#define TK_USING                          121
6434#define TK_ORDER                          122
6435#define TK_GROUP                          123
6436#define TK_HAVING                         124
6437#define TK_LIMIT                          125
6438#define TK_WHERE                          126
6439#define TK_INTO                           127
6440#define TK_VALUES                         128
6441#define TK_INTEGER                        129
6442#define TK_FLOAT                          130
6443#define TK_BLOB                           131
6444#define TK_REGISTER                       132
6445#define TK_VARIABLE                       133
6446#define TK_CASE                           134
6447#define TK_WHEN                           135
6448#define TK_THEN                           136
6449#define TK_ELSE                           137
6450#define TK_INDEX                          138
6451#define TK_ALTER                          139
6452#define TK_ADD                            140
6453#define TK_TO_TEXT                        141
6454#define TK_TO_BLOB                        142
6455#define TK_TO_NUMERIC                     143
6456#define TK_TO_INT                         144
6457#define TK_TO_REAL                        145
6458#define TK_ISNOT                          146
6459#define TK_END_OF_FILE                    147
6460#define TK_ILLEGAL                        148
6461#define TK_SPACE                          149
6462#define TK_UNCLOSED_STRING                150
6463#define TK_FUNCTION                       151
6464#define TK_COLUMN                         152
6465#define TK_AGG_FUNCTION                   153
6466#define TK_AGG_COLUMN                     154
6467#define TK_CONST_FUNC                     155
6468#define TK_UMINUS                         156
6469#define TK_UPLUS                          157
6470
6471/************** End of parse.h ***********************************************/
6472/************** Continuing where we left off in sqliteInt.h ******************/
6473#include <stdio.h>
6474#include <stdlib.h>
6475#include <string.h>
6476#include <assert.h>
6477#include <stddef.h>
6478
6479/*
6480** If compiling for a processor that lacks floating point support,
6481** substitute integer for floating-point
6482*/
6483#ifdef SQLITE_OMIT_FLOATING_POINT
6484# define double sqlite_int64
6485# define LONGDOUBLE_TYPE sqlite_int64
6486# ifndef SQLITE_BIG_DBL
6487#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
6488# endif
6489# define SQLITE_OMIT_DATETIME_FUNCS 1
6490# define SQLITE_OMIT_TRACE 1
6491# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
6492# undef SQLITE_HAVE_ISNAN
6493#endif
6494#ifndef SQLITE_BIG_DBL
6495# define SQLITE_BIG_DBL (1e99)
6496#endif
6497
6498/*
6499** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
6500** afterward. Having this macro allows us to cause the C compiler
6501** to omit code used by TEMP tables without messy #ifndef statements.
6502*/
6503#ifdef SQLITE_OMIT_TEMPDB
6504#define OMIT_TEMPDB 1
6505#else
6506#define OMIT_TEMPDB 0
6507#endif
6508
6509/*
6510** If the following macro is set to 1, then NULL values are considered
6511** distinct when determining whether or not two entries are the same
6512** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
6513** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
6514** is the way things are suppose to work.
6515**
6516** If the following macro is set to 0, the NULLs are indistinct for
6517** a UNIQUE index.  In this mode, you can only have a single NULL entry
6518** for a column declared UNIQUE.  This is the way Informix and SQL Server
6519** work.
6520*/
6521#define NULL_DISTINCT_FOR_UNIQUE 1
6522
6523/*
6524** The "file format" number is an integer that is incremented whenever
6525** the VDBE-level file format changes.  The following macros define the
6526** the default file format for new databases and the maximum file format
6527** that the library can read.
6528*/
6529#define SQLITE_MAX_FILE_FORMAT 4
6530#ifndef SQLITE_DEFAULT_FILE_FORMAT
6531# define SQLITE_DEFAULT_FILE_FORMAT 1
6532#endif
6533
6534#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
6535# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
6536#endif
6537
6538/*
6539** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
6540** on the command-line
6541*/
6542#ifndef SQLITE_TEMP_STORE
6543# define SQLITE_TEMP_STORE 1
6544#endif
6545
6546/*
6547** GCC does not define the offsetof() macro so we'll have to do it
6548** ourselves.
6549*/
6550#ifndef offsetof
6551#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
6552#endif
6553
6554/*
6555** Check to see if this machine uses EBCDIC.  (Yes, believe it or
6556** not, there are still machines out there that use EBCDIC.)
6557*/
6558#if 'A' == '\301'
6559# define SQLITE_EBCDIC 1
6560#else
6561# define SQLITE_ASCII 1
6562#endif
6563
6564/*
6565** Integers of known sizes.  These typedefs might change for architectures
6566** where the sizes very.  Preprocessor macros are available so that the
6567** types can be conveniently redefined at compile-type.  Like this:
6568**
6569**         cc '-DUINTPTR_TYPE=long long int' ...
6570*/
6571#ifndef UINT32_TYPE
6572# ifdef HAVE_UINT32_T
6573#  define UINT32_TYPE uint32_t
6574# else
6575#  define UINT32_TYPE unsigned int
6576# endif
6577#endif
6578#ifndef UINT16_TYPE
6579# ifdef HAVE_UINT16_T
6580#  define UINT16_TYPE uint16_t
6581# else
6582#  define UINT16_TYPE unsigned short int
6583# endif
6584#endif
6585#ifndef INT16_TYPE
6586# ifdef HAVE_INT16_T
6587#  define INT16_TYPE int16_t
6588# else
6589#  define INT16_TYPE short int
6590# endif
6591#endif
6592#ifndef UINT8_TYPE
6593# ifdef HAVE_UINT8_T
6594#  define UINT8_TYPE uint8_t
6595# else
6596#  define UINT8_TYPE unsigned char
6597# endif
6598#endif
6599#ifndef INT8_TYPE
6600# ifdef HAVE_INT8_T
6601#  define INT8_TYPE int8_t
6602# else
6603#  define INT8_TYPE signed char
6604# endif
6605#endif
6606#ifndef LONGDOUBLE_TYPE
6607# define LONGDOUBLE_TYPE long double
6608#endif
6609typedef sqlite_int64 i64;          /* 8-byte signed integer */
6610typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
6611typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
6612typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
6613typedef INT16_TYPE i16;            /* 2-byte signed integer */
6614typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
6615typedef INT8_TYPE i8;              /* 1-byte signed integer */
6616
6617/*
6618** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
6619** that can be stored in a u32 without loss of data.  The value
6620** is 0x00000000ffffffff.  But because of quirks of some compilers, we
6621** have to specify the value in the less intuitive manner shown:
6622*/
6623#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
6624
6625/*
6626** Macros to determine whether the machine is big or little endian,
6627** evaluated at runtime.
6628*/
6629#ifdef SQLITE_AMALGAMATION
6630SQLITE_PRIVATE const int sqlite3one = 1;
6631#else
6632SQLITE_PRIVATE const int sqlite3one;
6633#endif
6634#if defined(i386) || defined(__i386__) || defined(_M_IX86)\
6635                             || defined(__x86_64) || defined(__x86_64__)
6636# define SQLITE_BIGENDIAN    0
6637# define SQLITE_LITTLEENDIAN 1
6638# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
6639#else
6640# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
6641# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
6642# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
6643#endif
6644
6645/*
6646** Constants for the largest and smallest possible 64-bit signed integers.
6647** These macros are designed to work correctly on both 32-bit and 64-bit
6648** compilers.
6649*/
6650#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
6651#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
6652
6653/*
6654** Round up a number to the next larger multiple of 8.  This is used
6655** to force 8-byte alignment on 64-bit architectures.
6656*/
6657#define ROUND8(x)     (((x)+7)&~7)
6658
6659/*
6660** Round down to the nearest multiple of 8
6661*/
6662#define ROUNDDOWN8(x) ((x)&~7)
6663
6664/*
6665** Assert that the pointer X is aligned to an 8-byte boundary.  This
6666** macro is used only within assert() to verify that the code gets
6667** all alignment restrictions correct.
6668**
6669** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
6670** underlying malloc() implemention might return us 4-byte aligned
6671** pointers.  In that case, only verify 4-byte alignment.
6672*/
6673#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
6674# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
6675#else
6676# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
6677#endif
6678
6679
6680/*
6681** An instance of the following structure is used to store the busy-handler
6682** callback for a given sqlite handle.
6683**
6684** The sqlite.busyHandler member of the sqlite struct contains the busy
6685** callback for the database handle. Each pager opened via the sqlite
6686** handle is passed a pointer to sqlite.busyHandler. The busy-handler
6687** callback is currently invoked only from within pager.c.
6688*/
6689typedef struct BusyHandler BusyHandler;
6690struct BusyHandler {
6691  int (*xFunc)(void *,int);  /* The busy callback */
6692  void *pArg;                /* First arg to busy callback */
6693  int nBusy;                 /* Incremented with each busy call */
6694};
6695
6696/*
6697** Name of the master database table.  The master database table
6698** is a special table that holds the names and attributes of all
6699** user tables and indices.
6700*/
6701#define MASTER_NAME       "sqlite_master"
6702#define TEMP_MASTER_NAME  "sqlite_temp_master"
6703
6704/*
6705** The root-page of the master database table.
6706*/
6707#define MASTER_ROOT       1
6708
6709/*
6710** The name of the schema table.
6711*/
6712#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
6713
6714/*
6715** A convenience macro that returns the number of elements in
6716** an array.
6717*/
6718#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
6719
6720/*
6721** The following value as a destructor means to use sqlite3DbFree().
6722** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
6723*/
6724#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
6725
6726/*
6727** When SQLITE_OMIT_WSD is defined, it means that the target platform does
6728** not support Writable Static Data (WSD) such as global and static variables.
6729** All variables must either be on the stack or dynamically allocated from
6730** the heap.  When WSD is unsupported, the variable declarations scattered
6731** throughout the SQLite code must become constants instead.  The SQLITE_WSD
6732** macro is used for this purpose.  And instead of referencing the variable
6733** directly, we use its constant as a key to lookup the run-time allocated
6734** buffer that holds real variable.  The constant is also the initializer
6735** for the run-time allocated buffer.
6736**
6737** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
6738** macros become no-ops and have zero performance impact.
6739*/
6740#ifdef SQLITE_OMIT_WSD
6741  #define SQLITE_WSD const
6742  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
6743  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
6744SQLITE_API   int sqlite3_wsd_init(int N, int J);
6745SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
6746#else
6747  #define SQLITE_WSD
6748  #define GLOBAL(t,v) v
6749  #define sqlite3GlobalConfig sqlite3Config
6750#endif
6751
6752/*
6753** The following macros are used to suppress compiler warnings and to
6754** make it clear to human readers when a function parameter is deliberately
6755** left unused within the body of a function. This usually happens when
6756** a function is called via a function pointer. For example the
6757** implementation of an SQL aggregate step callback may not use the
6758** parameter indicating the number of arguments passed to the aggregate,
6759** if it knows that this is enforced elsewhere.
6760**
6761** When a function parameter is not used at all within the body of a function,
6762** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
6763** However, these macros may also be used to suppress warnings related to
6764** parameters that may or may not be used depending on compilation options.
6765** For example those parameters only used in assert() statements. In these
6766** cases the parameters are named as per the usual conventions.
6767*/
6768#define UNUSED_PARAMETER(x) (void)(x)
6769#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
6770
6771/*
6772** Forward references to structures
6773*/
6774typedef struct AggInfo AggInfo;
6775typedef struct AuthContext AuthContext;
6776typedef struct AutoincInfo AutoincInfo;
6777typedef struct Bitvec Bitvec;
6778typedef struct RowSet RowSet;
6779typedef struct CollSeq CollSeq;
6780typedef struct Column Column;
6781typedef struct Db Db;
6782typedef struct Schema Schema;
6783typedef struct Expr Expr;
6784typedef struct ExprList ExprList;
6785typedef struct ExprSpan ExprSpan;
6786typedef struct FKey FKey;
6787typedef struct FuncDef FuncDef;
6788typedef struct FuncDefHash FuncDefHash;
6789typedef struct IdList IdList;
6790typedef struct Index Index;
6791typedef struct IndexSample IndexSample;
6792typedef struct KeyClass KeyClass;
6793typedef struct KeyInfo KeyInfo;
6794typedef struct Lookaside Lookaside;
6795typedef struct LookasideSlot LookasideSlot;
6796typedef struct Module Module;
6797typedef struct NameContext NameContext;
6798typedef struct Parse Parse;
6799typedef struct Savepoint Savepoint;
6800typedef struct Select Select;
6801typedef struct SrcList SrcList;
6802typedef struct StrAccum StrAccum;
6803typedef struct Table Table;
6804typedef struct TableLock TableLock;
6805typedef struct Token Token;
6806typedef struct TriggerPrg TriggerPrg;
6807typedef struct TriggerStep TriggerStep;
6808typedef struct Trigger Trigger;
6809typedef struct UnpackedRecord UnpackedRecord;
6810typedef struct VTable VTable;
6811typedef struct Walker Walker;
6812typedef struct WherePlan WherePlan;
6813typedef struct WhereInfo WhereInfo;
6814typedef struct WhereLevel WhereLevel;
6815
6816/*
6817** Defer sourcing vdbe.h and btree.h until after the "u8" and
6818** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
6819** pointer types (i.e. FuncDef) defined above.
6820*/
6821/************** Include btree.h in the middle of sqliteInt.h *****************/
6822/************** Begin file btree.h *******************************************/
6823/*
6824** 2001 September 15
6825**
6826** The author disclaims copyright to this source code.  In place of
6827** a legal notice, here is a blessing:
6828**
6829**    May you do good and not evil.
6830**    May you find forgiveness for yourself and forgive others.
6831**    May you share freely, never taking more than you give.
6832**
6833*************************************************************************
6834** This header file defines the interface that the sqlite B-Tree file
6835** subsystem.  See comments in the source code for a detailed description
6836** of what each interface routine does.
6837*/
6838#ifndef _BTREE_H_
6839#define _BTREE_H_
6840
6841/* TODO: This definition is just included so other modules compile. It
6842** needs to be revisited.
6843*/
6844#define SQLITE_N_BTREE_META 10
6845
6846/*
6847** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
6848** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
6849*/
6850#ifndef SQLITE_DEFAULT_AUTOVACUUM
6851  #define SQLITE_DEFAULT_AUTOVACUUM 0
6852#endif
6853
6854#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
6855#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
6856#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
6857
6858/*
6859** Forward declarations of structure
6860*/
6861typedef struct Btree Btree;
6862typedef struct BtCursor BtCursor;
6863typedef struct BtShared BtShared;
6864typedef struct BtreeMutexArray BtreeMutexArray;
6865
6866/*
6867** This structure records all of the Btrees that need to hold
6868** a mutex before we enter sqlite3VdbeExec().  The Btrees are
6869** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
6870** we can always lock and unlock them all quickly.
6871*/
6872struct BtreeMutexArray {
6873  int nMutex;
6874  Btree *aBtree[SQLITE_MAX_ATTACHED+1];
6875};
6876
6877
6878SQLITE_PRIVATE int sqlite3BtreeOpen(
6879  const char *zFilename,   /* Name of database file to open */
6880  sqlite3 *db,             /* Associated database connection */
6881  Btree **ppBtree,         /* Return open Btree* here */
6882  int flags,               /* Flags */
6883  int vfsFlags             /* Flags passed through to VFS open */
6884);
6885
6886/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
6887** following values.
6888**
6889** NOTE:  These values must match the corresponding PAGER_ values in
6890** pager.h.
6891*/
6892#define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
6893#define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
6894#define BTREE_MEMORY        4  /* In-memory DB.  No argument */
6895#define BTREE_READONLY      8  /* Open the database in read-only mode */
6896#define BTREE_READWRITE    16  /* Open for both reading and writing */
6897#define BTREE_CREATE       32  /* Create the database if it does not exist */
6898
6899SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
6900SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
6901SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
6902SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
6903SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
6904SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
6905SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
6906SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
6907SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
6908SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
6909SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
6910SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
6911SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
6912SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
6913SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
6914SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
6915SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
6916SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
6917SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
6918SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
6919SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
6920SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
6921SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
6922SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
6923
6924SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
6925SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
6926SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
6927
6928SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
6929
6930/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
6931** of the following flags:
6932*/
6933#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
6934#define BTREE_ZERODATA   2    /* Table has keys only - no data */
6935#define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
6936
6937SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
6938SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
6939SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
6940
6941SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
6942SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
6943
6944/*
6945** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
6946** should be one of the following values. The integer values are assigned
6947** to constants so that the offset of the corresponding field in an
6948** SQLite database header may be found using the following formula:
6949**
6950**   offset = 36 + (idx * 4)
6951**
6952** For example, the free-page-count field is located at byte offset 36 of
6953** the database file header. The incr-vacuum-flag field is located at
6954** byte offset 64 (== 36+4*7).
6955*/
6956#define BTREE_FREE_PAGE_COUNT     0
6957#define BTREE_SCHEMA_VERSION      1
6958#define BTREE_FILE_FORMAT         2
6959#define BTREE_DEFAULT_CACHE_SIZE  3
6960#define BTREE_LARGEST_ROOT_PAGE   4
6961#define BTREE_TEXT_ENCODING       5
6962#define BTREE_USER_VERSION        6
6963#define BTREE_INCR_VACUUM         7
6964
6965SQLITE_PRIVATE int sqlite3BtreeCursor(
6966  Btree*,                              /* BTree containing table to open */
6967  int iTable,                          /* Index of root page */
6968  int wrFlag,                          /* 1 for writing.  0 for read-only */
6969  struct KeyInfo*,                     /* First argument to compare function */
6970  BtCursor *pCursor                    /* Space to write cursor structure */
6971);
6972SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
6973SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
6974
6975SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
6976SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
6977  BtCursor*,
6978  UnpackedRecord *pUnKey,
6979  i64 intKey,
6980  int bias,
6981  int *pRes
6982);
6983SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
6984SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
6985SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
6986                                  const void *pData, int nData,
6987                                  int nZero, int bias, int seekResult);
6988SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
6989SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
6990SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
6991SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
6992SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
6993SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
6994SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
6995SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
6996SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
6997SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
6998SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
6999SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
7000SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
7001
7002SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7003SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7004
7005SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7006SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7007SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7008
7009#ifndef NDEBUG
7010SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7011#endif
7012
7013#ifndef SQLITE_OMIT_BTREECOUNT
7014SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
7015#endif
7016
7017#ifdef SQLITE_TEST
7018SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7019SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7020#endif
7021
7022/*
7023** If we are not using shared cache, then there is no need to
7024** use mutexes to access the BtShared structures.  So make the
7025** Enter and Leave procedures no-ops.
7026*/
7027#ifndef SQLITE_OMIT_SHARED_CACHE
7028SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7029SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7030#else
7031# define sqlite3BtreeEnter(X)
7032# define sqlite3BtreeEnterAll(X)
7033#endif
7034
7035#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7036SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7037SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7038SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7039SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7040SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7041SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7042SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7043#ifndef NDEBUG
7044  /* These routines are used inside assert() statements only. */
7045SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7046SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7047#endif
7048#else
7049
7050# define sqlite3BtreeLeave(X)
7051# define sqlite3BtreeEnterCursor(X)
7052# define sqlite3BtreeLeaveCursor(X)
7053# define sqlite3BtreeLeaveAll(X)
7054# define sqlite3BtreeMutexArrayEnter(X)
7055# define sqlite3BtreeMutexArrayLeave(X)
7056# define sqlite3BtreeMutexArrayInsert(X,Y)
7057
7058# define sqlite3BtreeHoldsMutex(X) 1
7059# define sqlite3BtreeHoldsAllMutexes(X) 1
7060#endif
7061
7062
7063#endif /* _BTREE_H_ */
7064
7065/************** End of btree.h ***********************************************/
7066/************** Continuing where we left off in sqliteInt.h ******************/
7067/************** Include vdbe.h in the middle of sqliteInt.h ******************/
7068/************** Begin file vdbe.h ********************************************/
7069/*
7070** 2001 September 15
7071**
7072** The author disclaims copyright to this source code.  In place of
7073** a legal notice, here is a blessing:
7074**
7075**    May you do good and not evil.
7076**    May you find forgiveness for yourself and forgive others.
7077**    May you share freely, never taking more than you give.
7078**
7079*************************************************************************
7080** Header file for the Virtual DataBase Engine (VDBE)
7081**
7082** This header defines the interface to the virtual database engine
7083** or VDBE.  The VDBE implements an abstract machine that runs a
7084** simple program to access and modify the underlying database.
7085*/
7086#ifndef _SQLITE_VDBE_H_
7087#define _SQLITE_VDBE_H_
7088
7089/*
7090** A single VDBE is an opaque structure named "Vdbe".  Only routines
7091** in the source file sqliteVdbe.c are allowed to see the insides
7092** of this structure.
7093*/
7094typedef struct Vdbe Vdbe;
7095
7096/*
7097** The names of the following types declared in vdbeInt.h are required
7098** for the VdbeOp definition.
7099*/
7100typedef struct VdbeFunc VdbeFunc;
7101typedef struct Mem Mem;
7102typedef struct SubProgram SubProgram;
7103
7104/*
7105** A single instruction of the virtual machine has an opcode
7106** and as many as three operands.  The instruction is recorded
7107** as an instance of the following structure:
7108*/
7109struct VdbeOp {
7110  u8 opcode;          /* What operation to perform */
7111  signed char p4type; /* One of the P4_xxx constants for p4 */
7112  u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
7113  u8 p5;              /* Fifth parameter is an unsigned character */
7114  int p1;             /* First operand */
7115  int p2;             /* Second parameter (often the jump destination) */
7116  int p3;             /* The third parameter */
7117  union {             /* fourth parameter */
7118    int i;                 /* Integer value if p4type==P4_INT32 */
7119    void *p;               /* Generic pointer */
7120    char *z;               /* Pointer to data for string (char array) types */
7121    i64 *pI64;             /* Used when p4type is P4_INT64 */
7122    double *pReal;         /* Used when p4type is P4_REAL */
7123    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7124    VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7125    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7126    Mem *pMem;             /* Used when p4type is P4_MEM */
7127    VTable *pVtab;         /* Used when p4type is P4_VTAB */
7128    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7129    int *ai;               /* Used when p4type is P4_INTARRAY */
7130    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
7131  } p4;
7132#ifdef SQLITE_DEBUG
7133  char *zComment;          /* Comment to improve readability */
7134#endif
7135#ifdef VDBE_PROFILE
7136  int cnt;                 /* Number of times this instruction was executed */
7137  u64 cycles;              /* Total time spent executing this instruction */
7138#endif
7139};
7140typedef struct VdbeOp VdbeOp;
7141
7142
7143/*
7144** A sub-routine used to implement a trigger program.
7145*/
7146struct SubProgram {
7147  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
7148  int nOp;                      /* Elements in aOp[] */
7149  int nMem;                     /* Number of memory cells required */
7150  int nCsr;                     /* Number of cursors required */
7151  int nRef;                     /* Number of pointers to this structure */
7152  void *token;                  /* id that may be used to recursive triggers */
7153};
7154
7155/*
7156** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7157** it takes up less space.
7158*/
7159struct VdbeOpList {
7160  u8 opcode;          /* What operation to perform */
7161  signed char p1;     /* First operand */
7162  signed char p2;     /* Second parameter (often the jump destination) */
7163  signed char p3;     /* Third parameter */
7164};
7165typedef struct VdbeOpList VdbeOpList;
7166
7167/*
7168** Allowed values of VdbeOp.p4type
7169*/
7170#define P4_NOTUSED    0   /* The P4 parameter is not used */
7171#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7172#define P4_STATIC   (-2)  /* Pointer to a static string */
7173#define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7174#define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7175#define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7176#define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7177#define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7178#define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
7179#define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7180#define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7181#define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7182#define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7183#define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7184#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7185#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
7186
7187/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7188** is made.  That copy is freed when the Vdbe is finalized.  But if the
7189** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7190** gets freed when the Vdbe is finalized so it still should be obtained
7191** from a single sqliteMalloc().  But no copy is made and the calling
7192** function should *not* try to free the KeyInfo.
7193*/
7194#define P4_KEYINFO_HANDOFF (-16)
7195#define P4_KEYINFO_STATIC  (-17)
7196
7197/*
7198** The Vdbe.aColName array contains 5n Mem structures, where n is the
7199** number of columns of data returned by the statement.
7200*/
7201#define COLNAME_NAME     0
7202#define COLNAME_DECLTYPE 1
7203#define COLNAME_DATABASE 2
7204#define COLNAME_TABLE    3
7205#define COLNAME_COLUMN   4
7206#ifdef SQLITE_ENABLE_COLUMN_METADATA
7207# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
7208#else
7209# ifdef SQLITE_OMIT_DECLTYPE
7210#   define COLNAME_N      1      /* Store only the name */
7211# else
7212#   define COLNAME_N      2      /* Store the name and decltype */
7213# endif
7214#endif
7215
7216/*
7217** The following macro converts a relative address in the p2 field
7218** of a VdbeOp structure into a negative number so that
7219** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
7220** the macro again restores the address.
7221*/
7222#define ADDR(X)  (-1-(X))
7223
7224/*
7225** The makefile scans the vdbe.c source file and creates the "opcodes.h"
7226** header file that defines a number for each opcode used by the VDBE.
7227*/
7228/************** Include opcodes.h in the middle of vdbe.h ********************/
7229/************** Begin file opcodes.h *****************************************/
7230/* Automatically generated.  Do not edit */
7231/* See the mkopcodeh.awk script for details */
7232#define OP_Goto                                 1
7233#define OP_Gosub                                2
7234#define OP_Return                               3
7235#define OP_Yield                                4
7236#define OP_HaltIfNull                           5
7237#define OP_Halt                                 6
7238#define OP_Integer                              7
7239#define OP_Int64                                8
7240#define OP_Real                               130   /* same as TK_FLOAT    */
7241#define OP_String8                             94   /* same as TK_STRING   */
7242#define OP_String                               9
7243#define OP_Null                                10
7244#define OP_Blob                                11
7245#define OP_Variable                            12
7246#define OP_Move                                13
7247#define OP_Copy                                14
7248#define OP_SCopy                               15
7249#define OP_ResultRow                           16
7250#define OP_Concat                              91   /* same as TK_CONCAT   */
7251#define OP_Add                                 86   /* same as TK_PLUS     */
7252#define OP_Subtract                            87   /* same as TK_MINUS    */
7253#define OP_Multiply                            88   /* same as TK_STAR     */
7254#define OP_Divide                              89   /* same as TK_SLASH    */
7255#define OP_Remainder                           90   /* same as TK_REM      */
7256#define OP_CollSeq                             17
7257#define OP_Function                            18
7258#define OP_BitAnd                              82   /* same as TK_BITAND   */
7259#define OP_BitOr                               83   /* same as TK_BITOR    */
7260#define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
7261#define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
7262#define OP_AddImm                              20
7263#define OP_MustBeInt                           21
7264#define OP_RealAffinity                        22
7265#define OP_ToText                             141   /* same as TK_TO_TEXT  */
7266#define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
7267#define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
7268#define OP_ToInt                              144   /* same as TK_TO_INT   */
7269#define OP_ToReal                             145   /* same as TK_TO_REAL  */
7270#define OP_Eq                                  76   /* same as TK_EQ       */
7271#define OP_Ne                                  75   /* same as TK_NE       */
7272#define OP_Lt                                  79   /* same as TK_LT       */
7273#define OP_Le                                  78   /* same as TK_LE       */
7274#define OP_Gt                                  77   /* same as TK_GT       */
7275#define OP_Ge                                  80   /* same as TK_GE       */
7276#define OP_Permutation                         23
7277#define OP_Compare                             24
7278#define OP_Jump                                25
7279#define OP_And                                 69   /* same as TK_AND      */
7280#define OP_Or                                  68   /* same as TK_OR       */
7281#define OP_Not                                 19   /* same as TK_NOT      */
7282#define OP_BitNot                              93   /* same as TK_BITNOT   */
7283#define OP_If                                  26
7284#define OP_IfNot                               27
7285#define OP_IsNull                              73   /* same as TK_ISNULL   */
7286#define OP_NotNull                             74   /* same as TK_NOTNULL  */
7287#define OP_Column                              28
7288#define OP_Affinity                            29
7289#define OP_MakeRecord                          30
7290#define OP_Count                               31
7291#define OP_Savepoint                           32
7292#define OP_AutoCommit                          33
7293#define OP_Transaction                         34
7294#define OP_ReadCookie                          35
7295#define OP_SetCookie                           36
7296#define OP_VerifyCookie                        37
7297#define OP_OpenRead                            38
7298#define OP_OpenWrite                           39
7299#define OP_OpenEphemeral                       40
7300#define OP_OpenPseudo                          41
7301#define OP_Close                               42
7302#define OP_SeekLt                              43
7303#define OP_SeekLe                              44
7304#define OP_SeekGe                              45
7305#define OP_SeekGt                              46
7306#define OP_Seek                                47
7307#define OP_NotFound                            48
7308#define OP_Found                               49
7309#define OP_IsUnique                            50
7310#define OP_NotExists                           51
7311#define OP_Sequence                            52
7312#define OP_NewRowid                            53
7313#define OP_Insert                              54
7314#define OP_InsertInt                           55
7315#define OP_Delete                              56
7316#define OP_ResetCount                          57
7317#define OP_RowKey                              58
7318#define OP_RowData                             59
7319#define OP_Rowid                               60
7320#define OP_NullRow                             61
7321#define OP_Last                                62
7322#define OP_Sort                                63
7323#define OP_Rewind                              64
7324#define OP_Prev                                65
7325#define OP_Next                                66
7326#define OP_IdxInsert                           67
7327#define OP_IdxDelete                           70
7328#define OP_IdxRowid                            71
7329#define OP_IdxLT                               72
7330#define OP_IdxGE                               81
7331#define OP_Destroy                             92
7332#define OP_Clear                               95
7333#define OP_CreateIndex                         96
7334#define OP_CreateTable                         97
7335#define OP_ParseSchema                         98
7336#define OP_LoadAnalysis                        99
7337#define OP_DropTable                          100
7338#define OP_DropIndex                          101
7339#define OP_DropTrigger                        102
7340#define OP_IntegrityCk                        103
7341#define OP_RowSetAdd                          104
7342#define OP_RowSetRead                         105
7343#define OP_RowSetTest                         106
7344#define OP_Program                            107
7345#define OP_Param                              108
7346#define OP_FkCounter                          109
7347#define OP_FkIfZero                           110
7348#define OP_MemMax                             111
7349#define OP_IfPos                              112
7350#define OP_IfNeg                              113
7351#define OP_IfZero                             114
7352#define OP_AggStep                            115
7353#define OP_AggFinal                           116
7354#define OP_Vacuum                             117
7355#define OP_IncrVacuum                         118
7356#define OP_Expire                             119
7357#define OP_TableLock                          120
7358#define OP_VBegin                             121
7359#define OP_VCreate                            122
7360#define OP_VDestroy                           123
7361#define OP_VOpen                              124
7362#define OP_VFilter                            125
7363#define OP_VColumn                            126
7364#define OP_VNext                              127
7365#define OP_VRename                            128
7366#define OP_VUpdate                            129
7367#define OP_Pagecount                          131
7368#define OP_Trace                              132
7369#define OP_Noop                               133
7370#define OP_Explain                            134
7371
7372/* The following opcode values are never used */
7373#define OP_NotUsed_135                        135
7374#define OP_NotUsed_136                        136
7375#define OP_NotUsed_137                        137
7376#define OP_NotUsed_138                        138
7377#define OP_NotUsed_139                        139
7378#define OP_NotUsed_140                        140
7379
7380
7381/* Properties such as "out2" or "jump" that are specified in
7382** comments following the "case" for each opcode in the vdbe.c
7383** are encoded into bitvectors as follows:
7384*/
7385#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
7386#define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
7387#define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
7388#define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
7389#define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
7390#define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
7391#define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
7392#define OPFLG_INITIALIZER {\
7393/*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
7394/*   8 */ 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x24,\
7395/*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
7396/*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7397/*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
7398/*  40 */ 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x08,\
7399/*  48 */ 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00, 0x00,\
7400/*  56 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x01,\
7401/*  64 */ 0x01, 0x01, 0x01, 0x08, 0x4c, 0x4c, 0x00, 0x02,\
7402/*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
7403/*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
7404/*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x02, 0x24, 0x02, 0x00,\
7405/*  96 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7406/* 104 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
7407/* 112 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00,\
7408/* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01,\
7409/* 128 */ 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00,\
7410/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
7411/* 144 */ 0x04, 0x04,}
7412
7413/************** End of opcodes.h *********************************************/
7414/************** Continuing where we left off in vdbe.h ***********************/
7415
7416/*
7417** Prototypes for the VDBE interface.  See comments on the implementation
7418** for a description of what each of these routines does.
7419*/
7420SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
7421SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
7422SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
7423SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
7424SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
7425SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
7426SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
7427SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
7428SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
7429SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
7430SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
7431SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
7432SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
7433SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
7434SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
7435SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
7436SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
7437SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
7438SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
7439SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
7440SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
7441SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
7442SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
7443SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
7444#ifdef SQLITE_DEBUG
7445SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
7446SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
7447#endif
7448SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
7449SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
7450SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
7451SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
7452SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
7453SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
7454SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
7455SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
7456SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
7457SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *, SubProgram *, int);
7458SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
7459SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
7460#ifndef SQLITE_OMIT_TRACE
7461SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
7462#endif
7463
7464SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
7465SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
7466SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
7467
7468
7469#ifndef NDEBUG
7470SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
7471# define VdbeComment(X)  sqlite3VdbeComment X
7472SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
7473# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
7474#else
7475# define VdbeComment(X)
7476# define VdbeNoopComment(X)
7477#endif
7478
7479#endif
7480
7481/************** End of vdbe.h ************************************************/
7482/************** Continuing where we left off in sqliteInt.h ******************/
7483/************** Include pager.h in the middle of sqliteInt.h *****************/
7484/************** Begin file pager.h *******************************************/
7485/*
7486** 2001 September 15
7487**
7488** The author disclaims copyright to this source code.  In place of
7489** a legal notice, here is a blessing:
7490**
7491**    May you do good and not evil.
7492**    May you find forgiveness for yourself and forgive others.
7493**    May you share freely, never taking more than you give.
7494**
7495*************************************************************************
7496** This header file defines the interface that the sqlite page cache
7497** subsystem.  The page cache subsystem reads and writes a file a page
7498** at a time and provides a journal for rollback.
7499*/
7500
7501#ifndef _PAGER_H_
7502#define _PAGER_H_
7503
7504/*
7505** Default maximum size for persistent journal files. A negative
7506** value means no limit. This value may be overridden using the
7507** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
7508*/
7509#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
7510  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
7511#endif
7512
7513/*
7514** The type used to represent a page number.  The first page in a file
7515** is called page 1.  0 is used to represent "not a page".
7516*/
7517typedef u32 Pgno;
7518
7519/*
7520** Each open file is managed by a separate instance of the "Pager" structure.
7521*/
7522typedef struct Pager Pager;
7523
7524/*
7525** Handle type for pages.
7526*/
7527typedef struct PgHdr DbPage;
7528
7529/*
7530** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
7531** reserved for working around a windows/posix incompatibility). It is
7532** used in the journal to signify that the remainder of the journal file
7533** is devoted to storing a master journal name - there are no more pages to
7534** roll back. See comments for function writeMasterJournal() in pager.c
7535** for details.
7536*/
7537#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
7538
7539/*
7540** Allowed values for the flags parameter to sqlite3PagerOpen().
7541**
7542** NOTE: These values must match the corresponding BTREE_ values in btree.h.
7543*/
7544#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
7545#define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
7546
7547/*
7548** Valid values for the second argument to sqlite3PagerLockingMode().
7549*/
7550#define PAGER_LOCKINGMODE_QUERY      -1
7551#define PAGER_LOCKINGMODE_NORMAL      0
7552#define PAGER_LOCKINGMODE_EXCLUSIVE   1
7553
7554/*
7555** Valid values for the second argument to sqlite3PagerJournalMode().
7556*/
7557#define PAGER_JOURNALMODE_QUERY      -1
7558#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
7559#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
7560#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
7561#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
7562#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
7563
7564/*
7565** The remainder of this file contains the declarations of the functions
7566** that make up the Pager sub-system API. See source code comments for
7567** a detailed description of each routine.
7568*/
7569
7570/* Open and close a Pager connection. */
7571SQLITE_PRIVATE int sqlite3PagerOpen(
7572  sqlite3_vfs*,
7573  Pager **ppPager,
7574  const char*,
7575  int,
7576  int,
7577  int,
7578  void(*)(DbPage*)
7579);
7580SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
7581SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
7582
7583/* Functions used to configure a Pager object. */
7584SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
7585SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*, int);
7586SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
7587SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
7588SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
7589SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
7590SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
7591SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
7592SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
7593
7594/* Functions used to obtain and release page references. */
7595SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
7596#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
7597SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
7598SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
7599SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
7600
7601/* Operations on page references. */
7602SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
7603SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
7604SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
7605SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
7606SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
7607SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
7608
7609/* Functions used to manage pager transactions and savepoints. */
7610SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
7611SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
7612SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
7613SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
7614SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7615SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
7616SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
7617SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
7618SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
7619
7620/* Functions used to query pager state and configuration. */
7621SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
7622SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
7623SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
7624SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
7625SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
7626SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
7627SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
7628SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
7629SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
7630
7631/* Functions used to truncate the database file. */
7632SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
7633
7634/* Functions to support testing and debugging. */
7635#if !defined(NDEBUG) || defined(SQLITE_TEST)
7636SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
7637SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
7638#endif
7639#ifdef SQLITE_TEST
7640SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
7641SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
7642  void disable_simulated_io_errors(void);
7643  void enable_simulated_io_errors(void);
7644#else
7645# define disable_simulated_io_errors()
7646# define enable_simulated_io_errors()
7647#endif
7648
7649#endif /* _PAGER_H_ */
7650
7651/************** End of pager.h ***********************************************/
7652/************** Continuing where we left off in sqliteInt.h ******************/
7653/************** Include pcache.h in the middle of sqliteInt.h ****************/
7654/************** Begin file pcache.h ******************************************/
7655/*
7656** 2008 August 05
7657**
7658** The author disclaims copyright to this source code.  In place of
7659** a legal notice, here is a blessing:
7660**
7661**    May you do good and not evil.
7662**    May you find forgiveness for yourself and forgive others.
7663**    May you share freely, never taking more than you give.
7664**
7665*************************************************************************
7666** This header file defines the interface that the sqlite page cache
7667** subsystem.
7668*/
7669
7670#ifndef _PCACHE_H_
7671
7672typedef struct PgHdr PgHdr;
7673typedef struct PCache PCache;
7674
7675/*
7676** Every page in the cache is controlled by an instance of the following
7677** structure.
7678*/
7679struct PgHdr {
7680  void *pData;                   /* Content of this page */
7681  void *pExtra;                  /* Extra content */
7682  PgHdr *pDirty;                 /* Transient list of dirty pages */
7683  Pgno pgno;                     /* Page number for this page */
7684  Pager *pPager;                 /* The pager this page is part of */
7685#ifdef SQLITE_CHECK_PAGES
7686  u32 pageHash;                  /* Hash of page content */
7687#endif
7688  u16 flags;                     /* PGHDR flags defined below */
7689
7690  /**********************************************************************
7691  ** Elements above are public.  All that follows is private to pcache.c
7692  ** and should not be accessed by other modules.
7693  */
7694  i16 nRef;                      /* Number of users of this page */
7695  PCache *pCache;                /* Cache that owns this page */
7696
7697  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
7698  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
7699};
7700
7701/* Bit values for PgHdr.flags */
7702#define PGHDR_DIRTY             0x002  /* Page has changed */
7703#define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
7704                                       ** writing this page to the database */
7705#define PGHDR_NEED_READ         0x008  /* Content is unread */
7706#define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
7707#define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
7708
7709/* Initialize and shutdown the page cache subsystem */
7710SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
7711SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
7712
7713/* Page cache buffer management:
7714** These routines implement SQLITE_CONFIG_PAGECACHE.
7715*/
7716SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
7717
7718/* Create a new pager cache.
7719** Under memory stress, invoke xStress to try to make pages clean.
7720** Only clean and unpinned pages can be reclaimed.
7721*/
7722SQLITE_PRIVATE void sqlite3PcacheOpen(
7723  int szPage,                    /* Size of every page */
7724  int szExtra,                   /* Extra space associated with each page */
7725  int bPurgeable,                /* True if pages are on backing store */
7726  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
7727  void *pStress,                 /* Argument to xStress */
7728  PCache *pToInit                /* Preallocated space for the PCache */
7729);
7730
7731/* Modify the page-size after the cache has been created. */
7732SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
7733
7734/* Return the size in bytes of a PCache object.  Used to preallocate
7735** storage space.
7736*/
7737SQLITE_PRIVATE int sqlite3PcacheSize(void);
7738
7739/* One release per successful fetch.  Page is pinned until released.
7740** Reference counted.
7741*/
7742SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
7743SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
7744
7745SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
7746SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
7747SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
7748SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
7749
7750/* Change a page number.  Used by incr-vacuum. */
7751SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
7752
7753/* Remove all pages with pgno>x.  Reset the cache if x==0 */
7754SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
7755
7756/* Get a list of all dirty pages in the cache, sorted by page number */
7757SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
7758
7759/* Reset and close the cache object */
7760SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
7761
7762/* Clear flags from pages of the page cache */
7763SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
7764
7765/* Discard the contents of the cache */
7766SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
7767
7768/* Return the total number of outstanding page references */
7769SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
7770
7771/* Increment the reference count of an existing page */
7772SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
7773
7774SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
7775
7776/* Return the total number of pages stored in the cache */
7777SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
7778
7779#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
7780/* Iterate through all dirty pages currently stored in the cache. This
7781** interface is only available if SQLITE_CHECK_PAGES is defined when the
7782** library is built.
7783*/
7784SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
7785#endif
7786
7787/* Set and get the suggested cache-size for the specified pager-cache.
7788**
7789** If no global maximum is configured, then the system attempts to limit
7790** the total number of pages cached by purgeable pager-caches to the sum
7791** of the suggested cache-sizes.
7792*/
7793SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
7794#ifdef SQLITE_TEST
7795SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
7796#endif
7797
7798#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
7799/* Try to return memory used by the pcache module to the main memory heap */
7800SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
7801#endif
7802
7803#ifdef SQLITE_TEST
7804SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
7805#endif
7806
7807SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
7808
7809#endif /* _PCACHE_H_ */
7810
7811/************** End of pcache.h **********************************************/
7812/************** Continuing where we left off in sqliteInt.h ******************/
7813
7814/************** Include os.h in the middle of sqliteInt.h ********************/
7815/************** Begin file os.h **********************************************/
7816/*
7817** 2001 September 16
7818**
7819** The author disclaims copyright to this source code.  In place of
7820** a legal notice, here is a blessing:
7821**
7822**    May you do good and not evil.
7823**    May you find forgiveness for yourself and forgive others.
7824**    May you share freely, never taking more than you give.
7825**
7826******************************************************************************
7827**
7828** This header file (together with is companion C source-code file
7829** "os.c") attempt to abstract the underlying operating system so that
7830** the SQLite library will work on both POSIX and windows systems.
7831**
7832** This header file is #include-ed by sqliteInt.h and thus ends up
7833** being included by every source file.
7834*/
7835#ifndef _SQLITE_OS_H_
7836#define _SQLITE_OS_H_
7837
7838/*
7839** Figure out if we are dealing with Unix, Windows, or some other
7840** operating system.  After the following block of preprocess macros,
7841** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
7842** will defined to either 1 or 0.  One of the four will be 1.  The other
7843** three will be 0.
7844*/
7845#if defined(SQLITE_OS_OTHER)
7846# if SQLITE_OS_OTHER==1
7847#   undef SQLITE_OS_UNIX
7848#   define SQLITE_OS_UNIX 0
7849#   undef SQLITE_OS_WIN
7850#   define SQLITE_OS_WIN 0
7851#   undef SQLITE_OS_OS2
7852#   define SQLITE_OS_OS2 0
7853# else
7854#   undef SQLITE_OS_OTHER
7855# endif
7856#endif
7857#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
7858# define SQLITE_OS_OTHER 0
7859# ifndef SQLITE_OS_WIN
7860#   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
7861#     define SQLITE_OS_WIN 1
7862#     define SQLITE_OS_UNIX 0
7863#     define SQLITE_OS_OS2 0
7864#   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
7865#     define SQLITE_OS_WIN 0
7866#     define SQLITE_OS_UNIX 0
7867#     define SQLITE_OS_OS2 1
7868#   else
7869#     define SQLITE_OS_WIN 0
7870#     define SQLITE_OS_UNIX 1
7871#     define SQLITE_OS_OS2 0
7872#  endif
7873# else
7874#  define SQLITE_OS_UNIX 0
7875#  define SQLITE_OS_OS2 0
7876# endif
7877#else
7878# ifndef SQLITE_OS_WIN
7879#  define SQLITE_OS_WIN 0
7880# endif
7881#endif
7882
7883/*
7884** Determine if we are dealing with WindowsCE - which has a much
7885** reduced API.
7886*/
7887#if defined(_WIN32_WCE)
7888# define SQLITE_OS_WINCE 1
7889#else
7890# define SQLITE_OS_WINCE 0
7891#endif
7892
7893
7894/*
7895** Define the maximum size of a temporary filename
7896*/
7897#if SQLITE_OS_WIN
7898# include <windows.h>
7899# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
7900#elif SQLITE_OS_OS2
7901# if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
7902#  include <os2safe.h> /* has to be included before os2.h for linking to work */
7903# endif
7904# define INCL_DOSDATETIME
7905# define INCL_DOSFILEMGR
7906# define INCL_DOSERRORS
7907# define INCL_DOSMISC
7908# define INCL_DOSPROCESS
7909# define INCL_DOSMODULEMGR
7910# define INCL_DOSSEMAPHORES
7911# include <os2.h>
7912# include <uconv.h>
7913# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
7914#else
7915# define SQLITE_TEMPNAME_SIZE 200
7916#endif
7917
7918/* If the SET_FULLSYNC macro is not defined above, then make it
7919** a no-op
7920*/
7921#ifndef SET_FULLSYNC
7922# define SET_FULLSYNC(x,y)
7923#endif
7924
7925/*
7926** The default size of a disk sector
7927*/
7928#ifndef SQLITE_DEFAULT_SECTOR_SIZE
7929# define SQLITE_DEFAULT_SECTOR_SIZE 512
7930#endif
7931
7932/*
7933** Temporary files are named starting with this prefix followed by 16 random
7934** alphanumeric characters, and no file extension. They are stored in the
7935** OS's standard temporary file directory, and are deleted prior to exit.
7936** If sqlite is being embedded in another program, you may wish to change the
7937** prefix to reflect your program's name, so that if your program exits
7938** prematurely, old temporary files can be easily identified. This can be done
7939** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
7940**
7941** 2006-10-31:  The default prefix used to be "sqlite_".  But then
7942** Mcafee started using SQLite in their anti-virus product and it
7943** started putting files with the "sqlite" name in the c:/temp folder.
7944** This annoyed many windows users.  Those users would then do a
7945** Google search for "sqlite", find the telephone numbers of the
7946** developers and call to wake them up at night and complain.
7947** For this reason, the default name prefix is changed to be "sqlite"
7948** spelled backwards.  So the temp files are still identified, but
7949** anybody smart enough to figure out the code is also likely smart
7950** enough to know that calling the developer will not help get rid
7951** of the file.
7952*/
7953#ifndef SQLITE_TEMP_FILE_PREFIX
7954# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
7955#endif
7956
7957/*
7958** The following values may be passed as the second argument to
7959** sqlite3OsLock(). The various locks exhibit the following semantics:
7960**
7961** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
7962** RESERVED:  A single process may hold a RESERVED lock on a file at
7963**            any time. Other processes may hold and obtain new SHARED locks.
7964** PENDING:   A single process may hold a PENDING lock on a file at
7965**            any one time. Existing SHARED locks may persist, but no new
7966**            SHARED locks may be obtained by other processes.
7967** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
7968**
7969** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
7970** process that requests an EXCLUSIVE lock may actually obtain a PENDING
7971** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
7972** sqlite3OsLock().
7973*/
7974#define NO_LOCK         0
7975#define SHARED_LOCK     1
7976#define RESERVED_LOCK   2
7977#define PENDING_LOCK    3
7978#define EXCLUSIVE_LOCK  4
7979
7980/*
7981** File Locking Notes:  (Mostly about windows but also some info for Unix)
7982**
7983** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
7984** those functions are not available.  So we use only LockFile() and
7985** UnlockFile().
7986**
7987** LockFile() prevents not just writing but also reading by other processes.
7988** A SHARED_LOCK is obtained by locking a single randomly-chosen
7989** byte out of a specific range of bytes. The lock byte is obtained at
7990** random so two separate readers can probably access the file at the
7991** same time, unless they are unlucky and choose the same lock byte.
7992** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
7993** There can only be one writer.  A RESERVED_LOCK is obtained by locking
7994** a single byte of the file that is designated as the reserved lock byte.
7995** A PENDING_LOCK is obtained by locking a designated byte different from
7996** the RESERVED_LOCK byte.
7997**
7998** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
7999** which means we can use reader/writer locks.  When reader/writer locks
8000** are used, the lock is placed on the same range of bytes that is used
8001** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8002** will support two or more Win95 readers or two or more WinNT readers.
8003** But a single Win95 reader will lock out all WinNT readers and a single
8004** WinNT reader will lock out all other Win95 readers.
8005**
8006** The following #defines specify the range of bytes used for locking.
8007** SHARED_SIZE is the number of bytes available in the pool from which
8008** a random byte is selected for a shared lock.  The pool of bytes for
8009** shared locks begins at SHARED_FIRST.
8010**
8011** The same locking strategy and
8012** byte ranges are used for Unix.  This leaves open the possiblity of having
8013** clients on win95, winNT, and unix all talking to the same shared file
8014** and all locking correctly.  To do so would require that samba (or whatever
8015** tool is being used for file sharing) implements locks correctly between
8016** windows and unix.  I'm guessing that isn't likely to happen, but by
8017** using the same locking range we are at least open to the possibility.
8018**
8019** Locking in windows is manditory.  For this reason, we cannot store
8020** actual data in the bytes used for locking.  The pager never allocates
8021** the pages involved in locking therefore.  SHARED_SIZE is selected so
8022** that all locks will fit on a single page even at the minimum page size.
8023** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8024** is set high so that we don't have to allocate an unused page except
8025** for very large databases.  But one should test the page skipping logic
8026** by setting PENDING_BYTE low and running the entire regression suite.
8027**
8028** Changing the value of PENDING_BYTE results in a subtly incompatible
8029** file format.  Depending on how it is changed, you might not notice
8030** the incompatibility right away, even running a full regression test.
8031** The default location of PENDING_BYTE is the first byte past the
8032** 1GB boundary.
8033**
8034*/
8035#define PENDING_BYTE      sqlite3PendingByte
8036#define RESERVED_BYTE     (PENDING_BYTE+1)
8037#define SHARED_FIRST      (PENDING_BYTE+2)
8038#define SHARED_SIZE       510
8039
8040/*
8041** Wrapper around OS specific sqlite3_os_init() function.
8042*/
8043SQLITE_PRIVATE int sqlite3OsInit(void);
8044
8045/*
8046** Functions for accessing sqlite3_file methods
8047*/
8048SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8049SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8050SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8051SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8052SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8053SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8054SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8055SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8056SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8057SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8058#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8059SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8060SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8061
8062/*
8063** Functions for accessing sqlite3_vfs methods
8064*/
8065SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8066SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8067SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8068SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8069#ifndef SQLITE_OMIT_LOAD_EXTENSION
8070SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8071SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8072SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8073SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8074#endif /* SQLITE_OMIT_LOAD_EXTENSION */
8075SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8076SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8077SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
8078
8079/*
8080** Convenience functions for opening and closing files using
8081** sqlite3_malloc() to obtain space for the file-handle structure.
8082*/
8083SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8084SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8085
8086#endif /* _SQLITE_OS_H_ */
8087
8088/************** End of os.h **************************************************/
8089/************** Continuing where we left off in sqliteInt.h ******************/
8090/************** Include mutex.h in the middle of sqliteInt.h *****************/
8091/************** Begin file mutex.h *******************************************/
8092/*
8093** 2007 August 28
8094**
8095** The author disclaims copyright to this source code.  In place of
8096** a legal notice, here is a blessing:
8097**
8098**    May you do good and not evil.
8099**    May you find forgiveness for yourself and forgive others.
8100**    May you share freely, never taking more than you give.
8101**
8102*************************************************************************
8103**
8104** This file contains the common header for all mutex implementations.
8105** The sqliteInt.h header #includes this file so that it is available
8106** to all source files.  We break it out in an effort to keep the code
8107** better organized.
8108**
8109** NOTE:  source files should *not* #include this header file directly.
8110** Source files should #include the sqliteInt.h file and let that file
8111** include this one indirectly.
8112*/
8113
8114
8115/*
8116** Figure out what version of the code to use.  The choices are
8117**
8118**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8119**                             mutexes implemention cannot be overridden
8120**                             at start-time.
8121**
8122**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8123**                             mutual exclusion is provided.  But this
8124**                             implementation can be overridden at
8125**                             start-time.
8126**
8127**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8128**
8129**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8130**
8131**   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8132*/
8133#if !SQLITE_THREADSAFE
8134# define SQLITE_MUTEX_OMIT
8135#endif
8136#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8137#  if SQLITE_OS_UNIX
8138#    define SQLITE_MUTEX_PTHREADS
8139#  elif SQLITE_OS_WIN
8140#    define SQLITE_MUTEX_W32
8141#  elif SQLITE_OS_OS2
8142#    define SQLITE_MUTEX_OS2
8143#  else
8144#    define SQLITE_MUTEX_NOOP
8145#  endif
8146#endif
8147
8148#ifdef SQLITE_MUTEX_OMIT
8149/*
8150** If this is a no-op implementation, implement everything as macros.
8151*/
8152#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8153#define sqlite3_mutex_free(X)
8154#define sqlite3_mutex_enter(X)
8155#define sqlite3_mutex_try(X)      SQLITE_OK
8156#define sqlite3_mutex_leave(X)
8157#define sqlite3_mutex_held(X)     1
8158#define sqlite3_mutex_notheld(X)  1
8159#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8160#define sqlite3MutexInit()        SQLITE_OK
8161#define sqlite3MutexEnd()
8162#endif /* defined(SQLITE_MUTEX_OMIT) */
8163
8164/************** End of mutex.h ***********************************************/
8165/************** Continuing where we left off in sqliteInt.h ******************/
8166
8167
8168/*
8169** Each database file to be accessed by the system is an instance
8170** of the following structure.  There are normally two of these structures
8171** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8172** aDb[1] is the database file used to hold temporary tables.  Additional
8173** databases may be attached.
8174*/
8175struct Db {
8176  char *zName;         /* Name of this database */
8177  Btree *pBt;          /* The B*Tree structure for this database file */
8178  u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8179  u8 safety_level;     /* How aggressive at syncing data to disk */
8180  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
8181};
8182
8183/*
8184** An instance of the following structure stores a database schema.
8185**
8186** If there are no virtual tables configured in this schema, the
8187** Schema.db variable is set to NULL. After the first virtual table
8188** has been added, it is set to point to the database connection
8189** used to create the connection. Once a virtual table has been
8190** added to the Schema structure and the Schema.db variable populated,
8191** only that database connection may use the Schema to prepare
8192** statements.
8193*/
8194struct Schema {
8195  int schema_cookie;   /* Database schema version number for this file */
8196  Hash tblHash;        /* All tables indexed by name */
8197  Hash idxHash;        /* All (named) indices indexed by name */
8198  Hash trigHash;       /* All triggers indexed by name */
8199  Hash fkeyHash;       /* All foreign keys by referenced table name */
8200  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
8201  u8 file_format;      /* Schema format version for this file */
8202  u8 enc;              /* Text encoding used by this database */
8203  u16 flags;           /* Flags associated with this schema */
8204  int cache_size;      /* Number of pages to use in the cache */
8205#ifndef SQLITE_OMIT_VIRTUALTABLE
8206  sqlite3 *db;         /* "Owner" connection. See comment above */
8207#endif
8208};
8209
8210/*
8211** These macros can be used to test, set, or clear bits in the
8212** Db.flags field.
8213*/
8214#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
8215#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
8216#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
8217#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
8218
8219/*
8220** Allowed values for the DB.flags field.
8221**
8222** The DB_SchemaLoaded flag is set after the database schema has been
8223** read into internal hash tables.
8224**
8225** DB_UnresetViews means that one or more views have column names that
8226** have been filled out.  If the schema changes, these column names might
8227** changes and so the view will need to be reset.
8228*/
8229#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
8230#define DB_UnresetViews    0x0002  /* Some views have defined column names */
8231#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
8232
8233/*
8234** The number of different kinds of things that can be limited
8235** using the sqlite3_limit() interface.
8236*/
8237#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
8238
8239/*
8240** Lookaside malloc is a set of fixed-size buffers that can be used
8241** to satisfy small transient memory allocation requests for objects
8242** associated with a particular database connection.  The use of
8243** lookaside malloc provides a significant performance enhancement
8244** (approx 10%) by avoiding numerous malloc/free requests while parsing
8245** SQL statements.
8246**
8247** The Lookaside structure holds configuration information about the
8248** lookaside malloc subsystem.  Each available memory allocation in
8249** the lookaside subsystem is stored on a linked list of LookasideSlot
8250** objects.
8251**
8252** Lookaside allocations are only allowed for objects that are associated
8253** with a particular database connection.  Hence, schema information cannot
8254** be stored in lookaside because in shared cache mode the schema information
8255** is shared by multiple database connections.  Therefore, while parsing
8256** schema information, the Lookaside.bEnabled flag is cleared so that
8257** lookaside allocations are not used to construct the schema objects.
8258*/
8259struct Lookaside {
8260  u16 sz;                 /* Size of each buffer in bytes */
8261  u8 bEnabled;            /* False to disable new lookaside allocations */
8262  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
8263  int nOut;               /* Number of buffers currently checked out */
8264  int mxOut;              /* Highwater mark for nOut */
8265  LookasideSlot *pFree;   /* List of available buffers */
8266  void *pStart;           /* First byte of available memory space */
8267  void *pEnd;             /* First byte past end of available space */
8268};
8269struct LookasideSlot {
8270  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
8271};
8272
8273/*
8274** A hash table for function definitions.
8275**
8276** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
8277** Collisions are on the FuncDef.pHash chain.
8278*/
8279struct FuncDefHash {
8280  FuncDef *a[23];       /* Hash table for functions */
8281};
8282
8283/*
8284** Each database is an instance of the following structure.
8285**
8286** The sqlite.lastRowid records the last insert rowid generated by an
8287** insert statement.  Inserts on views do not affect its value.  Each
8288** trigger has its own context, so that lastRowid can be updated inside
8289** triggers as usual.  The previous value will be restored once the trigger
8290** exits.  Upon entering a before or instead of trigger, lastRowid is no
8291** longer (since after version 2.8.12) reset to -1.
8292**
8293** The sqlite.nChange does not count changes within triggers and keeps no
8294** context.  It is reset at start of sqlite3_exec.
8295** The sqlite.lsChange represents the number of changes made by the last
8296** insert, update, or delete statement.  It remains constant throughout the
8297** length of a statement and is then updated by OP_SetCounts.  It keeps a
8298** context stack just like lastRowid so that the count of changes
8299** within a trigger is not seen outside the trigger.  Changes to views do not
8300** affect the value of lsChange.
8301** The sqlite.csChange keeps track of the number of current changes (since
8302** the last statement) and is used to update sqlite_lsChange.
8303**
8304** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
8305** store the most recent error code and, if applicable, string. The
8306** internal function sqlite3Error() is used to set these variables
8307** consistently.
8308*/
8309struct sqlite3 {
8310  sqlite3_vfs *pVfs;            /* OS Interface */
8311  int nDb;                      /* Number of backends currently in use */
8312  Db *aDb;                      /* All backends */
8313  int flags;                    /* Miscellaneous flags. See below */
8314  int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
8315  int errCode;                  /* Most recent error code (SQLITE_*) */
8316  int errMask;                  /* & result codes with this before returning */
8317  u8 autoCommit;                /* The auto-commit flag. */
8318  u8 temp_store;                /* 1: file 2: memory 0: default */
8319  u8 mallocFailed;              /* True if we have seen a malloc failure */
8320  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8321  u8 dfltJournalMode;           /* Default journal mode for attached dbs */
8322  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8323  u8 suppressErr;               /* Do not issue error messages if true */
8324  int nextPagesize;             /* Pagesize after VACUUM if >0 */
8325  int nTable;                   /* Number of tables in the database */
8326  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
8327  i64 lastRowid;                /* ROWID of most recent insert (see above) */
8328  u32 magic;                    /* Magic number for detect library misuse */
8329  int nChange;                  /* Value returned by sqlite3_changes() */
8330  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
8331  sqlite3_mutex *mutex;         /* Connection mutex */
8332  int aLimit[SQLITE_N_LIMIT];   /* Limits */
8333  struct sqlite3InitInfo {      /* Information used during initialization */
8334    int iDb;                    /* When back is being initialized */
8335    int newTnum;                /* Rootpage of table being initialized */
8336    u8 busy;                    /* TRUE if currently initializing */
8337    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
8338  } init;
8339  int nExtension;               /* Number of loaded extensions */
8340  void **aExtension;            /* Array of shared library handles */
8341  struct Vdbe *pVdbe;           /* List of active virtual machines */
8342  int activeVdbeCnt;            /* Number of VDBEs currently executing */
8343  int writeVdbeCnt;             /* Number of active VDBEs that are writing */
8344  void (*xTrace)(void*,const char*);        /* Trace function */
8345  void *pTraceArg;                          /* Argument to the trace function */
8346  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
8347  void *pProfileArg;                        /* Argument to profile function */
8348  void *pCommitArg;                 /* Argument to xCommitCallback() */
8349  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
8350  void *pRollbackArg;               /* Argument to xRollbackCallback() */
8351  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
8352  void *pUpdateArg;
8353  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
8354  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
8355  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
8356  void *pCollNeededArg;
8357  sqlite3_value *pErr;          /* Most recent error message */
8358  char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
8359  char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
8360  union {
8361    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
8362    double notUsed1;            /* Spacer */
8363  } u1;
8364  Lookaside lookaside;          /* Lookaside malloc configuration */
8365#ifndef SQLITE_OMIT_AUTHORIZATION
8366  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
8367                                /* Access authorization function */
8368  void *pAuthArg;               /* 1st argument to the access auth function */
8369#endif
8370#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8371  int (*xProgress)(void *);     /* The progress callback */
8372  void *pProgressArg;           /* Argument to the progress callback */
8373  int nProgressOps;             /* Number of opcodes for progress callback */
8374#endif
8375#ifndef SQLITE_OMIT_VIRTUALTABLE
8376  Hash aModule;                 /* populated by sqlite3_create_module() */
8377  Table *pVTab;                 /* vtab with active Connect/Create method */
8378  VTable **aVTrans;             /* Virtual tables with open transactions */
8379  int nVTrans;                  /* Allocated size of aVTrans */
8380  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
8381#endif
8382  FuncDefHash aFunc;            /* Hash table of connection functions */
8383  Hash aCollSeq;                /* All collating sequences */
8384  BusyHandler busyHandler;      /* Busy callback */
8385  int busyTimeout;              /* Busy handler timeout, in msec */
8386  Db aDbStatic[2];              /* Static space for the 2 default backends */
8387  Savepoint *pSavepoint;        /* List of active savepoints */
8388  int nSavepoint;               /* Number of non-transaction savepoints */
8389  int nStatement;               /* Number of nested statement-transactions  */
8390  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
8391  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
8392
8393#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
8394  /* The following variables are all protected by the STATIC_MASTER
8395  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
8396  **
8397  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
8398  ** unlock so that it can proceed.
8399  **
8400  ** When X.pBlockingConnection==Y, that means that something that X tried
8401  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
8402  ** held by Y.
8403  */
8404  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
8405  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
8406  void *pUnlockArg;                     /* Argument to xUnlockNotify */
8407  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
8408  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
8409#endif
8410};
8411
8412/*
8413** A macro to discover the encoding of a database.
8414*/
8415#define ENC(db) ((db)->aDb[0].pSchema->enc)
8416
8417/*
8418** Possible values for the sqlite3.flags.
8419*/
8420#define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
8421#define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
8422#define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
8423#define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
8424#define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
8425                                          /*   DELETE, or UPDATE and return */
8426                                          /*   the count using a callback. */
8427#define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
8428                                          /*   result set is empty */
8429#define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
8430#define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
8431#define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
8432#define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when
8433                                          ** accessing read-only databases */
8434#define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
8435#define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
8436#define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
8437#define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
8438#define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
8439#define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
8440#define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
8441#define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
8442#define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
8443
8444/*
8445** Bits of the sqlite3.flags field that are used by the
8446** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
8447** These must be the low-order bits of the flags field.
8448*/
8449#define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
8450#define SQLITE_ColumnCache    0x02        /* Disable the column cache */
8451#define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
8452#define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
8453#define SQLITE_IndexCover     0x10        /* Disable index covering table */
8454#define SQLITE_OptMask        0x1f        /* Mask of all disablable opts */
8455
8456/*
8457** Possible values for the sqlite.magic field.
8458** The numbers are obtained at random and have no special meaning, other
8459** than being distinct from one another.
8460*/
8461#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
8462#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
8463#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
8464#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
8465#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
8466
8467/*
8468** Each SQL function is defined by an instance of the following
8469** structure.  A pointer to this structure is stored in the sqlite.aFunc
8470** hash table.  When multiple functions have the same name, the hash table
8471** points to a linked list of these structures.
8472*/
8473struct FuncDef {
8474  i16 nArg;            /* Number of arguments.  -1 means unlimited */
8475  u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
8476  u8 flags;            /* Some combination of SQLITE_FUNC_* */
8477  void *pUserData;     /* User data parameter */
8478  FuncDef *pNext;      /* Next function with same name */
8479  void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
8480  void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
8481  void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
8482  char *zName;         /* SQL name of the function. */
8483  FuncDef *pHash;      /* Next with a different name but the same hash */
8484};
8485
8486/*
8487** Possible values for FuncDef.flags
8488*/
8489#define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
8490#define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
8491#define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
8492#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
8493#define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
8494#define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
8495#define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
8496
8497/*
8498** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
8499** used to create the initializers for the FuncDef structures.
8500**
8501**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
8502**     Used to create a scalar function definition of a function zName
8503**     implemented by C function xFunc that accepts nArg arguments. The
8504**     value passed as iArg is cast to a (void*) and made available
8505**     as the user-data (sqlite3_user_data()) for the function. If
8506**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
8507**
8508**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
8509**     Used to create an aggregate function definition implemented by
8510**     the C functions xStep and xFinal. The first four parameters
8511**     are interpreted in the same way as the first 4 parameters to
8512**     FUNCTION().
8513**
8514**   LIKEFUNC(zName, nArg, pArg, flags)
8515**     Used to create a scalar function definition of a function zName
8516**     that accepts nArg arguments and is implemented by a call to C
8517**     function likeFunc. Argument pArg is cast to a (void *) and made
8518**     available as the function user-data (sqlite3_user_data()). The
8519**     FuncDef.flags variable is set to the value passed as the flags
8520**     parameter.
8521*/
8522#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
8523  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8524   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
8525#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
8526  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8527   pArg, 0, xFunc, 0, 0, #zName, 0}
8528#define LIKEFUNC(zName, nArg, arg, flags) \
8529  {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
8530#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
8531  {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
8532   SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
8533
8534/*
8535** All current savepoints are stored in a linked list starting at
8536** sqlite3.pSavepoint. The first element in the list is the most recently
8537** opened savepoint. Savepoints are added to the list by the vdbe
8538** OP_Savepoint instruction.
8539*/
8540struct Savepoint {
8541  char *zName;                        /* Savepoint name (nul-terminated) */
8542  i64 nDeferredCons;                  /* Number of deferred fk violations */
8543  Savepoint *pNext;                   /* Parent savepoint (if any) */
8544};
8545
8546/*
8547** The following are used as the second parameter to sqlite3Savepoint(),
8548** and as the P1 argument to the OP_Savepoint instruction.
8549*/
8550#define SAVEPOINT_BEGIN      0
8551#define SAVEPOINT_RELEASE    1
8552#define SAVEPOINT_ROLLBACK   2
8553
8554
8555/*
8556** Each SQLite module (virtual table definition) is defined by an
8557** instance of the following structure, stored in the sqlite3.aModule
8558** hash table.
8559*/
8560struct Module {
8561  const sqlite3_module *pModule;       /* Callback pointers */
8562  const char *zName;                   /* Name passed to create_module() */
8563  void *pAux;                          /* pAux passed to create_module() */
8564  void (*xDestroy)(void *);            /* Module destructor function */
8565};
8566
8567/*
8568** information about each column of an SQL table is held in an instance
8569** of this structure.
8570*/
8571struct Column {
8572  char *zName;     /* Name of this column */
8573  Expr *pDflt;     /* Default value of this column */
8574  char *zDflt;     /* Original text of the default value */
8575  char *zType;     /* Data type for this column */
8576  char *zColl;     /* Collating sequence.  If NULL, use the default */
8577  u8 notNull;      /* True if there is a NOT NULL constraint */
8578  u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
8579  char affinity;   /* One of the SQLITE_AFF_... values */
8580#ifndef SQLITE_OMIT_VIRTUALTABLE
8581  u8 isHidden;     /* True if this column is 'hidden' */
8582#endif
8583};
8584
8585/*
8586** A "Collating Sequence" is defined by an instance of the following
8587** structure. Conceptually, a collating sequence consists of a name and
8588** a comparison routine that defines the order of that sequence.
8589**
8590** There may two separate implementations of the collation function, one
8591** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
8592** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
8593** native byte order. When a collation sequence is invoked, SQLite selects
8594** the version that will require the least expensive encoding
8595** translations, if any.
8596**
8597** The CollSeq.pUser member variable is an extra parameter that passed in
8598** as the first argument to the UTF-8 comparison function, xCmp.
8599** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
8600** xCmp16.
8601**
8602** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
8603** collating sequence is undefined.  Indices built on an undefined
8604** collating sequence may not be read or written.
8605*/
8606struct CollSeq {
8607  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
8608  u8 enc;               /* Text encoding handled by xCmp() */
8609  u8 type;              /* One of the SQLITE_COLL_... values below */
8610  void *pUser;          /* First argument to xCmp() */
8611  int (*xCmp)(void*,int, const void*, int, const void*);
8612  void (*xDel)(void*);  /* Destructor for pUser */
8613};
8614
8615/*
8616** Allowed values of CollSeq.type:
8617*/
8618#define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
8619#define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
8620#define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
8621#define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
8622
8623/*
8624** A sort order can be either ASC or DESC.
8625*/
8626#define SQLITE_SO_ASC       0  /* Sort in ascending order */
8627#define SQLITE_SO_DESC      1  /* Sort in ascending order */
8628
8629/*
8630** Column affinity types.
8631**
8632** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
8633** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
8634** the speed a little by numbering the values consecutively.
8635**
8636** But rather than start with 0 or 1, we begin with 'a'.  That way,
8637** when multiple affinity types are concatenated into a string and
8638** used as the P4 operand, they will be more readable.
8639**
8640** Note also that the numeric types are grouped together so that testing
8641** for a numeric type is a single comparison.
8642*/
8643#define SQLITE_AFF_TEXT     'a'
8644#define SQLITE_AFF_NONE     'b'
8645#define SQLITE_AFF_NUMERIC  'c'
8646#define SQLITE_AFF_INTEGER  'd'
8647#define SQLITE_AFF_REAL     'e'
8648
8649#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
8650
8651/*
8652** The SQLITE_AFF_MASK values masks off the significant bits of an
8653** affinity value.
8654*/
8655#define SQLITE_AFF_MASK     0x67
8656
8657/*
8658** Additional bit values that can be ORed with an affinity without
8659** changing the affinity.
8660*/
8661#define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
8662#define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
8663#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
8664
8665/*
8666** An object of this type is created for each virtual table present in
8667** the database schema.
8668**
8669** If the database schema is shared, then there is one instance of this
8670** structure for each database connection (sqlite3*) that uses the shared
8671** schema. This is because each database connection requires its own unique
8672** instance of the sqlite3_vtab* handle used to access the virtual table
8673** implementation. sqlite3_vtab* handles can not be shared between
8674** database connections, even when the rest of the in-memory database
8675** schema is shared, as the implementation often stores the database
8676** connection handle passed to it via the xConnect() or xCreate() method
8677** during initialization internally. This database connection handle may
8678** then used by the virtual table implementation to access real tables
8679** within the database. So that they appear as part of the callers
8680** transaction, these accesses need to be made via the same database
8681** connection as that used to execute SQL operations on the virtual table.
8682**
8683** All VTable objects that correspond to a single table in a shared
8684** database schema are initially stored in a linked-list pointed to by
8685** the Table.pVTable member variable of the corresponding Table object.
8686** When an sqlite3_prepare() operation is required to access the virtual
8687** table, it searches the list for the VTable that corresponds to the
8688** database connection doing the preparing so as to use the correct
8689** sqlite3_vtab* handle in the compiled query.
8690**
8691** When an in-memory Table object is deleted (for example when the
8692** schema is being reloaded for some reason), the VTable objects are not
8693** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
8694** immediately. Instead, they are moved from the Table.pVTable list to
8695** another linked list headed by the sqlite3.pDisconnect member of the
8696** corresponding sqlite3 structure. They are then deleted/xDisconnected
8697** next time a statement is prepared using said sqlite3*. This is done
8698** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
8699** Refer to comments above function sqlite3VtabUnlockList() for an
8700** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
8701** list without holding the corresponding sqlite3.mutex mutex.
8702**
8703** The memory for objects of this type is always allocated by
8704** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
8705** the first argument.
8706*/
8707struct VTable {
8708  sqlite3 *db;              /* Database connection associated with this table */
8709  Module *pMod;             /* Pointer to module implementation */
8710  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
8711  int nRef;                 /* Number of pointers to this structure */
8712  VTable *pNext;            /* Next in linked list (see above) */
8713};
8714
8715/*
8716** Each SQL table is represented in memory by an instance of the
8717** following structure.
8718**
8719** Table.zName is the name of the table.  The case of the original
8720** CREATE TABLE statement is stored, but case is not significant for
8721** comparisons.
8722**
8723** Table.nCol is the number of columns in this table.  Table.aCol is a
8724** pointer to an array of Column structures, one for each column.
8725**
8726** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
8727** the column that is that key.   Otherwise Table.iPKey is negative.  Note
8728** that the datatype of the PRIMARY KEY must be INTEGER for this field to
8729** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
8730** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
8731** is generated for each row of the table.  TF_HasPrimaryKey is set if
8732** the table has any PRIMARY KEY, INTEGER or otherwise.
8733**
8734** Table.tnum is the page number for the root BTree page of the table in the
8735** database file.  If Table.iDb is the index of the database table backend
8736** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
8737** holds temporary tables and indices.  If TF_Ephemeral is set
8738** then the table is stored in a file that is automatically deleted
8739** when the VDBE cursor to the table is closed.  In this case Table.tnum
8740** refers VDBE cursor number that holds the table open, not to the root
8741** page number.  Transient tables are used to hold the results of a
8742** sub-query that appears instead of a real table name in the FROM clause
8743** of a SELECT statement.
8744*/
8745struct Table {
8746  sqlite3 *dbMem;      /* DB connection used for lookaside allocations. */
8747  char *zName;         /* Name of the table or view */
8748  int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
8749  int nCol;            /* Number of columns in this table */
8750  Column *aCol;        /* Information about each column */
8751  Index *pIndex;       /* List of SQL indexes on this table. */
8752  int tnum;            /* Root BTree node for this table (see note above) */
8753  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
8754  u16 nRef;            /* Number of pointers to this Table */
8755  u8 tabFlags;         /* Mask of TF_* values */
8756  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
8757  FKey *pFKey;         /* Linked list of all foreign keys in this table */
8758  char *zColAff;       /* String defining the affinity of each column */
8759#ifndef SQLITE_OMIT_CHECK
8760  Expr *pCheck;        /* The AND of all CHECK constraints */
8761#endif
8762#ifndef SQLITE_OMIT_ALTERTABLE
8763  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
8764#endif
8765#ifndef SQLITE_OMIT_VIRTUALTABLE
8766  VTable *pVTable;     /* List of VTable objects. */
8767  int nModuleArg;      /* Number of arguments to the module */
8768  char **azModuleArg;  /* Text of all module args. [0] is module name */
8769#endif
8770  Trigger *pTrigger;   /* List of triggers stored in pSchema */
8771  Schema *pSchema;     /* Schema that contains this table */
8772  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
8773};
8774
8775/*
8776** Allowed values for Tabe.tabFlags.
8777*/
8778#define TF_Readonly        0x01    /* Read-only system table */
8779#define TF_Ephemeral       0x02    /* An ephemeral table */
8780#define TF_HasPrimaryKey   0x04    /* Table has a primary key */
8781#define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
8782#define TF_Virtual         0x10    /* Is a virtual table */
8783#define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
8784
8785
8786
8787/*
8788** Test to see whether or not a table is a virtual table.  This is
8789** done as a macro so that it will be optimized out when virtual
8790** table support is omitted from the build.
8791*/
8792#ifndef SQLITE_OMIT_VIRTUALTABLE
8793#  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
8794#  define IsHiddenColumn(X) ((X)->isHidden)
8795#else
8796#  define IsVirtual(X)      0
8797#  define IsHiddenColumn(X) 0
8798#endif
8799
8800/*
8801** Each foreign key constraint is an instance of the following structure.
8802**
8803** A foreign key is associated with two tables.  The "from" table is
8804** the table that contains the REFERENCES clause that creates the foreign
8805** key.  The "to" table is the table that is named in the REFERENCES clause.
8806** Consider this example:
8807**
8808**     CREATE TABLE ex1(
8809**       a INTEGER PRIMARY KEY,
8810**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
8811**     );
8812**
8813** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
8814**
8815** Each REFERENCES clause generates an instance of the following structure
8816** which is attached to the from-table.  The to-table need not exist when
8817** the from-table is created.  The existence of the to-table is not checked.
8818*/
8819struct FKey {
8820  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
8821  FKey *pNextFrom;  /* Next foreign key in pFrom */
8822  char *zTo;        /* Name of table that the key points to (aka: Parent) */
8823  FKey *pNextTo;    /* Next foreign key on table named zTo */
8824  FKey *pPrevTo;    /* Previous foreign key on table named zTo */
8825  int nCol;         /* Number of columns in this key */
8826  /* EV: R-30323-21917 */
8827  u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
8828  u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
8829  Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
8830  struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
8831    int iFrom;         /* Index of column in pFrom */
8832    char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
8833  } aCol[1];        /* One entry for each of nCol column s */
8834};
8835
8836/*
8837** SQLite supports many different ways to resolve a constraint
8838** error.  ROLLBACK processing means that a constraint violation
8839** causes the operation in process to fail and for the current transaction
8840** to be rolled back.  ABORT processing means the operation in process
8841** fails and any prior changes from that one operation are backed out,
8842** but the transaction is not rolled back.  FAIL processing means that
8843** the operation in progress stops and returns an error code.  But prior
8844** changes due to the same operation are not backed out and no rollback
8845** occurs.  IGNORE means that the particular row that caused the constraint
8846** error is not inserted or updated.  Processing continues and no error
8847** is returned.  REPLACE means that preexisting database rows that caused
8848** a UNIQUE constraint violation are removed so that the new insert or
8849** update can proceed.  Processing continues and no error is reported.
8850**
8851** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
8852** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
8853** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
8854** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
8855** referenced table row is propagated into the row that holds the
8856** foreign key.
8857**
8858** The following symbolic values are used to record which type
8859** of action to take.
8860*/
8861#define OE_None     0   /* There is no constraint to check */
8862#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
8863#define OE_Abort    2   /* Back out changes but do no rollback transaction */
8864#define OE_Fail     3   /* Stop the operation but leave all prior changes */
8865#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
8866#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
8867
8868#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
8869#define OE_SetNull  7   /* Set the foreign key value to NULL */
8870#define OE_SetDflt  8   /* Set the foreign key value to its default */
8871#define OE_Cascade  9   /* Cascade the changes */
8872
8873#define OE_Default  99  /* Do whatever the default action is */
8874
8875
8876/*
8877** An instance of the following structure is passed as the first
8878** argument to sqlite3VdbeKeyCompare and is used to control the
8879** comparison of the two index keys.
8880*/
8881struct KeyInfo {
8882  sqlite3 *db;        /* The database connection */
8883  u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
8884  u16 nField;         /* Number of entries in aColl[] */
8885  u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
8886  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
8887};
8888
8889/*
8890** An instance of the following structure holds information about a
8891** single index record that has already been parsed out into individual
8892** values.
8893**
8894** A record is an object that contains one or more fields of data.
8895** Records are used to store the content of a table row and to store
8896** the key of an index.  A blob encoding of a record is created by
8897** the OP_MakeRecord opcode of the VDBE and is disassembled by the
8898** OP_Column opcode.
8899**
8900** This structure holds a record that has already been disassembled
8901** into its constituent fields.
8902*/
8903struct UnpackedRecord {
8904  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
8905  u16 nField;         /* Number of entries in apMem[] */
8906  u16 flags;          /* Boolean settings.  UNPACKED_... below */
8907  i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
8908  Mem *aMem;          /* Values */
8909};
8910
8911/*
8912** Allowed values of UnpackedRecord.flags
8913*/
8914#define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
8915#define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
8916#define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
8917#define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
8918#define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
8919#define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
8920
8921/*
8922** Each SQL index is represented in memory by an
8923** instance of the following structure.
8924**
8925** The columns of the table that are to be indexed are described
8926** by the aiColumn[] field of this structure.  For example, suppose
8927** we have the following table and index:
8928**
8929**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
8930**     CREATE INDEX Ex2 ON Ex1(c3,c1);
8931**
8932** In the Table structure describing Ex1, nCol==3 because there are
8933** three columns in the table.  In the Index structure describing
8934** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
8935** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
8936** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
8937** The second column to be indexed (c1) has an index of 0 in
8938** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
8939**
8940** The Index.onError field determines whether or not the indexed columns
8941** must be unique and what to do if they are not.  When Index.onError=OE_None,
8942** it means this is not a unique index.  Otherwise it is a unique index
8943** and the value of Index.onError indicate the which conflict resolution
8944** algorithm to employ whenever an attempt is made to insert a non-unique
8945** element.
8946*/
8947struct Index {
8948  char *zName;     /* Name of this index */
8949  int nColumn;     /* Number of columns in the table used by this index */
8950  int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
8951  unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
8952  Table *pTable;   /* The SQL table being indexed */
8953  int tnum;        /* Page containing root of this index in database file */
8954  u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
8955  u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
8956  char *zColAff;   /* String defining the affinity of each column */
8957  Index *pNext;    /* The next index associated with the same table */
8958  Schema *pSchema; /* Schema containing this index */
8959  u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
8960  char **azColl;   /* Array of collation sequence names for index */
8961  IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
8962};
8963
8964/*
8965** Each sample stored in the sqlite_stat2 table is represented in memory
8966** using a structure of this type.
8967*/
8968struct IndexSample {
8969  union {
8970    char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
8971    double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
8972  } u;
8973  u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
8974  u8 nByte;         /* Size in byte of text or blob. */
8975};
8976
8977/*
8978** Each token coming out of the lexer is an instance of
8979** this structure.  Tokens are also used as part of an expression.
8980**
8981** Note if Token.z==0 then Token.dyn and Token.n are undefined and
8982** may contain random values.  Do not make any assumptions about Token.dyn
8983** and Token.n when Token.z==0.
8984*/
8985struct Token {
8986  const char *z;     /* Text of the token.  Not NULL-terminated! */
8987  unsigned int n;    /* Number of characters in this token */
8988};
8989
8990/*
8991** An instance of this structure contains information needed to generate
8992** code for a SELECT that contains aggregate functions.
8993**
8994** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
8995** pointer to this structure.  The Expr.iColumn field is the index in
8996** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
8997** code for that node.
8998**
8999** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9000** original Select structure that describes the SELECT statement.  These
9001** fields do not need to be freed when deallocating the AggInfo structure.
9002*/
9003struct AggInfo {
9004  u8 directMode;          /* Direct rendering mode means take data directly
9005                          ** from source tables rather than from accumulators */
9006  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9007                          ** than the source table */
9008  int sortingIdx;         /* Cursor number of the sorting index */
9009  ExprList *pGroupBy;     /* The group by clause */
9010  int nSortingColumn;     /* Number of columns in the sorting index */
9011  struct AggInfo_col {    /* For each column used in source tables */
9012    Table *pTab;             /* Source table */
9013    int iTable;              /* Cursor number of the source table */
9014    int iColumn;             /* Column number within the source table */
9015    int iSorterColumn;       /* Column number in the sorting index */
9016    int iMem;                /* Memory location that acts as accumulator */
9017    Expr *pExpr;             /* The original expression */
9018  } *aCol;
9019  int nColumn;            /* Number of used entries in aCol[] */
9020  int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9021  int nAccumulator;       /* Number of columns that show through to the output.
9022                          ** Additional columns are used only as parameters to
9023                          ** aggregate functions */
9024  struct AggInfo_func {   /* For each aggregate function */
9025    Expr *pExpr;             /* Expression encoding the function */
9026    FuncDef *pFunc;          /* The aggregate function implementation */
9027    int iMem;                /* Memory location that acts as accumulator */
9028    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
9029  } *aFunc;
9030  int nFunc;              /* Number of entries in aFunc[] */
9031  int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9032};
9033
9034/*
9035** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9036** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
9037** than 32767 we have to make it 32-bit.  16-bit is preferred because
9038** it uses less memory in the Expr object, which is a big memory user
9039** in systems with lots of prepared statements.  And few applications
9040** need more than about 10 or 20 variables.  But some extreme users want
9041** to have prepared statements with over 32767 variables, and for them
9042** the option is available (at compile-time).
9043*/
9044#if SQLITE_MAX_VARIABLE_NUMBER<=32767
9045typedef i16 ynVar;
9046#else
9047typedef int ynVar;
9048#endif
9049
9050/*
9051** Each node of an expression in the parse tree is an instance
9052** of this structure.
9053**
9054** Expr.op is the opcode. The integer parser token codes are reused
9055** as opcodes here. For example, the parser defines TK_GE to be an integer
9056** code representing the ">=" operator. This same integer code is reused
9057** to represent the greater-than-or-equal-to operator in the expression
9058** tree.
9059**
9060** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
9061** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9062** the expression is a variable (TK_VARIABLE), then Expr.token contains the
9063** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9064** then Expr.token contains the name of the function.
9065**
9066** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9067** binary operator. Either or both may be NULL.
9068**
9069** Expr.x.pList is a list of arguments if the expression is an SQL function,
9070** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9071** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9072** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9073** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
9074** valid.
9075**
9076** An expression of the form ID or ID.ID refers to a column in a table.
9077** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9078** the integer cursor number of a VDBE cursor pointing to that table and
9079** Expr.iColumn is the column number for the specific column.  If the
9080** expression is used as a result in an aggregate SELECT, then the
9081** value is also stored in the Expr.iAgg column in the aggregate so that
9082** it can be accessed after all aggregates are computed.
9083**
9084** If the expression is an unbound variable marker (a question mark
9085** character '?' in the original SQL) then the Expr.iTable holds the index
9086** number for that variable.
9087**
9088** If the expression is a subquery then Expr.iColumn holds an integer
9089** register number containing the result of the subquery.  If the
9090** subquery gives a constant result, then iTable is -1.  If the subquery
9091** gives a different answer at different times during statement processing
9092** then iTable is the address of a subroutine that computes the subquery.
9093**
9094** If the Expr is of type OP_Column, and the table it is selecting from
9095** is a disk table or the "old.*" pseudo-table, then pTab points to the
9096** corresponding table definition.
9097**
9098** ALLOCATION NOTES:
9099**
9100** Expr objects can use a lot of memory space in database schema.  To
9101** help reduce memory requirements, sometimes an Expr object will be
9102** truncated.  And to reduce the number of memory allocations, sometimes
9103** two or more Expr objects will be stored in a single memory allocation,
9104** together with Expr.zToken strings.
9105**
9106** If the EP_Reduced and EP_TokenOnly flags are set when
9107** an Expr object is truncated.  When EP_Reduced is set, then all
9108** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9109** are contained within the same memory allocation.  Note, however, that
9110** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9111** allocated, regardless of whether or not EP_Reduced is set.
9112*/
9113struct Expr {
9114  u8 op;                 /* Operation performed by this node */
9115  char affinity;         /* The affinity of the column or 0 if not a column */
9116  u16 flags;             /* Various flags.  EP_* See below */
9117  union {
9118    char *zToken;          /* Token value. Zero terminated and dequoted */
9119    int iValue;            /* Integer value if EP_IntValue */
9120  } u;
9121
9122  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9123  ** space is allocated for the fields below this point. An attempt to
9124  ** access them will result in a segfault or malfunction.
9125  *********************************************************************/
9126
9127  Expr *pLeft;           /* Left subnode */
9128  Expr *pRight;          /* Right subnode */
9129  union {
9130    ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
9131    Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
9132  } x;
9133  CollSeq *pColl;        /* The collation type of the column or 0 */
9134
9135  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
9136  ** space is allocated for the fields below this point. An attempt to
9137  ** access them will result in a segfault or malfunction.
9138  *********************************************************************/
9139
9140  int iTable;            /* TK_COLUMN: cursor number of table holding column
9141                         ** TK_REGISTER: register number
9142                         ** TK_TRIGGER: 1 -> new, 0 -> old */
9143  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
9144                         ** TK_VARIABLE: variable number (always >= 1). */
9145  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9146  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9147  u8 flags2;             /* Second set of flags.  EP2_... */
9148  u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
9149  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9150  Table *pTab;           /* Table for TK_COLUMN expressions. */
9151#if SQLITE_MAX_EXPR_DEPTH>0
9152  int nHeight;           /* Height of the tree headed by this node */
9153#endif
9154};
9155
9156/*
9157** The following are the meanings of bits in the Expr.flags field.
9158*/
9159#define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9160#define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9161#define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9162#define EP_Error      0x0008  /* Expression contains one or more errors */
9163#define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9164#define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9165#define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
9166#define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9167#define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9168#define EP_FixedDest  0x0200  /* Result needed in a specific register */
9169#define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
9170#define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
9171
9172#define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
9173#define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
9174#define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
9175
9176/*
9177** The following are the meanings of bits in the Expr.flags2 field.
9178*/
9179#define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
9180#define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
9181
9182/*
9183** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
9184** flag on an expression structure.  This flag is used for VV&A only.  The
9185** routine is implemented as a macro that only works when in debugging mode,
9186** so as not to burden production code.
9187*/
9188#ifdef SQLITE_DEBUG
9189# define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
9190#else
9191# define ExprSetIrreducible(X)
9192#endif
9193
9194/*
9195** These macros can be used to test, set, or clear bits in the
9196** Expr.flags field.
9197*/
9198#define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9199#define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9200#define ExprSetProperty(E,P)     (E)->flags|=(P)
9201#define ExprClearProperty(E,P)   (E)->flags&=~(P)
9202
9203/*
9204** Macros to determine the number of bytes required by a normal Expr
9205** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
9206** and an Expr struct with the EP_TokenOnly flag set.
9207*/
9208#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
9209#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
9210#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
9211
9212/*
9213** Flags passed to the sqlite3ExprDup() function. See the header comment
9214** above sqlite3ExprDup() for details.
9215*/
9216#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
9217
9218/*
9219** A list of expressions.  Each expression may optionally have a
9220** name.  An expr/name combination can be used in several ways, such
9221** as the list of "expr AS ID" fields following a "SELECT" or in the
9222** list of "ID = expr" items in an UPDATE.  A list of expressions can
9223** also be used as the argument to a function, in which case the a.zName
9224** field is not used.
9225*/
9226struct ExprList {
9227  int nExpr;             /* Number of expressions on the list */
9228  int nAlloc;            /* Number of entries allocated below */
9229  int iECursor;          /* VDBE Cursor associated with this ExprList */
9230  struct ExprList_item {
9231    Expr *pExpr;           /* The list of expressions */
9232    char *zName;           /* Token associated with this expression */
9233    char *zSpan;           /* Original text of the expression */
9234    u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9235    u8 done;               /* A flag to indicate when processing is finished */
9236    u16 iCol;              /* For ORDER BY, column number in result set */
9237    u16 iAlias;            /* Index into Parse.aAlias[] for zName */
9238  } *a;                  /* One entry for each expression */
9239};
9240
9241/*
9242** An instance of this structure is used by the parser to record both
9243** the parse tree for an expression and the span of input text for an
9244** expression.
9245*/
9246struct ExprSpan {
9247  Expr *pExpr;          /* The expression parse tree */
9248  const char *zStart;   /* First character of input text */
9249  const char *zEnd;     /* One character past the end of input text */
9250};
9251
9252/*
9253** An instance of this structure can hold a simple list of identifiers,
9254** such as the list "a,b,c" in the following statements:
9255**
9256**      INSERT INTO t(a,b,c) VALUES ...;
9257**      CREATE INDEX idx ON t(a,b,c);
9258**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9259**
9260** The IdList.a.idx field is used when the IdList represents the list of
9261** column names after a table name in an INSERT statement.  In the statement
9262**
9263**     INSERT INTO t(a,b,c) ...
9264**
9265** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9266*/
9267struct IdList {
9268  struct IdList_item {
9269    char *zName;      /* Name of the identifier */
9270    int idx;          /* Index in some Table.aCol[] of a column named zName */
9271  } *a;
9272  int nId;         /* Number of identifiers on the list */
9273  int nAlloc;      /* Number of entries allocated for a[] below */
9274};
9275
9276/*
9277** The bitmask datatype defined below is used for various optimizations.
9278**
9279** Changing this from a 64-bit to a 32-bit type limits the number of
9280** tables in a join to 32 instead of 64.  But it also reduces the size
9281** of the library by 738 bytes on ix86.
9282*/
9283typedef u64 Bitmask;
9284
9285/*
9286** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
9287*/
9288#define BMS  ((int)(sizeof(Bitmask)*8))
9289
9290/*
9291** The following structure describes the FROM clause of a SELECT statement.
9292** Each table or subquery in the FROM clause is a separate element of
9293** the SrcList.a[] array.
9294**
9295** With the addition of multiple database support, the following structure
9296** can also be used to describe a particular table such as the table that
9297** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
9298** such a table must be a simple name: ID.  But in SQLite, the table can
9299** now be identified by a database name, a dot, then the table name: ID.ID.
9300**
9301** The jointype starts out showing the join type between the current table
9302** and the next table on the list.  The parser builds the list this way.
9303** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9304** jointype expresses the join between the table and the previous table.
9305*/
9306struct SrcList {
9307  i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9308  i16 nAlloc;      /* Number of entries allocated in a[] below */
9309  struct SrcList_item {
9310    char *zDatabase;  /* Name of database holding this table */
9311    char *zName;      /* Name of the table */
9312    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
9313    Table *pTab;      /* An SQL table corresponding to zName */
9314    Select *pSelect;  /* A SELECT statement used in place of a table name */
9315    u8 isPopulated;   /* Temporary table associated with SELECT is populated */
9316    u8 jointype;      /* Type of join between this able and the previous */
9317    u8 notIndexed;    /* True if there is a NOT INDEXED clause */
9318    int iCursor;      /* The VDBE cursor number used to access this table */
9319    Expr *pOn;        /* The ON clause of a join */
9320    IdList *pUsing;   /* The USING clause of a join */
9321    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
9322    char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
9323    Index *pIndex;    /* Index structure corresponding to zIndex, if any */
9324  } a[1];             /* One entry for each identifier on the list */
9325};
9326
9327/*
9328** Permitted values of the SrcList.a.jointype field
9329*/
9330#define JT_INNER     0x0001    /* Any kind of inner or cross join */
9331#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
9332#define JT_NATURAL   0x0004    /* True for a "natural" join */
9333#define JT_LEFT      0x0008    /* Left outer join */
9334#define JT_RIGHT     0x0010    /* Right outer join */
9335#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
9336#define JT_ERROR     0x0040    /* unknown or unsupported join type */
9337
9338
9339/*
9340** A WherePlan object holds information that describes a lookup
9341** strategy.
9342**
9343** This object is intended to be opaque outside of the where.c module.
9344** It is included here only so that that compiler will know how big it
9345** is.  None of the fields in this object should be used outside of
9346** the where.c module.
9347**
9348** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
9349** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
9350** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
9351** case that more than one of these conditions is true.
9352*/
9353struct WherePlan {
9354  u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
9355  u32 nEq;                       /* Number of == constraints */
9356  union {
9357    Index *pIdx;                   /* Index when WHERE_INDEXED is true */
9358    struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
9359    sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
9360  } u;
9361};
9362
9363/*
9364** For each nested loop in a WHERE clause implementation, the WhereInfo
9365** structure contains a single instance of this structure.  This structure
9366** is intended to be private the the where.c module and should not be
9367** access or modified by other modules.
9368**
9369** The pIdxInfo field is used to help pick the best index on a
9370** virtual table.  The pIdxInfo pointer contains indexing
9371** information for the i-th table in the FROM clause before reordering.
9372** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
9373** All other information in the i-th WhereLevel object for the i-th table
9374** after FROM clause ordering.
9375*/
9376struct WhereLevel {
9377  WherePlan plan;       /* query plan for this element of the FROM clause */
9378  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
9379  int iTabCur;          /* The VDBE cursor used to access the table */
9380  int iIdxCur;          /* The VDBE cursor used to access pIdx */
9381  int addrBrk;          /* Jump here to break out of the loop */
9382  int addrNxt;          /* Jump here to start the next IN combination */
9383  int addrCont;         /* Jump here to continue with the next loop cycle */
9384  int addrFirst;        /* First instruction of interior of the loop */
9385  u8 iFrom;             /* Which entry in the FROM clause */
9386  u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
9387  int p1, p2;           /* Operands of the opcode used to ends the loop */
9388  union {               /* Information that depends on plan.wsFlags */
9389    struct {
9390      int nIn;              /* Number of entries in aInLoop[] */
9391      struct InLoop {
9392        int iCur;              /* The VDBE cursor used by this IN operator */
9393        int addrInTop;         /* Top of the IN loop */
9394      } *aInLoop;           /* Information about each nested IN operator */
9395    } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
9396  } u;
9397
9398  /* The following field is really not part of the current level.  But
9399  ** we need a place to cache virtual table index information for each
9400  ** virtual table in the FROM clause and the WhereLevel structure is
9401  ** a convenient place since there is one WhereLevel for each FROM clause
9402  ** element.
9403  */
9404  sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
9405};
9406
9407/*
9408** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
9409** and the WhereInfo.wctrlFlags member.
9410*/
9411#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
9412#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
9413#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
9414#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
9415#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
9416#define WHERE_OMIT_OPEN        0x0010 /* Table cursor are already open */
9417#define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
9418#define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
9419#define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
9420
9421/*
9422** The WHERE clause processing routine has two halves.  The
9423** first part does the start of the WHERE loop and the second
9424** half does the tail of the WHERE loop.  An instance of
9425** this structure is returned by the first half and passed
9426** into the second half to give some continuity.
9427*/
9428struct WhereInfo {
9429  Parse *pParse;       /* Parsing and code generating context */
9430  u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
9431  u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
9432  u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
9433  SrcList *pTabList;             /* List of tables in the join */
9434  int iTop;                      /* The very beginning of the WHERE loop */
9435  int iContinue;                 /* Jump here to continue with next record */
9436  int iBreak;                    /* Jump here to break out of the loop */
9437  int nLevel;                    /* Number of nested loop */
9438  struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
9439  WhereLevel a[1];               /* Information about each nest loop in WHERE */
9440};
9441
9442/*
9443** A NameContext defines a context in which to resolve table and column
9444** names.  The context consists of a list of tables (the pSrcList) field and
9445** a list of named expression (pEList).  The named expression list may
9446** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
9447** to the table being operated on by INSERT, UPDATE, or DELETE.  The
9448** pEList corresponds to the result set of a SELECT and is NULL for
9449** other statements.
9450**
9451** NameContexts can be nested.  When resolving names, the inner-most
9452** context is searched first.  If no match is found, the next outer
9453** context is checked.  If there is still no match, the next context
9454** is checked.  This process continues until either a match is found
9455** or all contexts are check.  When a match is found, the nRef member of
9456** the context containing the match is incremented.
9457**
9458** Each subquery gets a new NameContext.  The pNext field points to the
9459** NameContext in the parent query.  Thus the process of scanning the
9460** NameContext list corresponds to searching through successively outer
9461** subqueries looking for a match.
9462*/
9463struct NameContext {
9464  Parse *pParse;       /* The parser */
9465  SrcList *pSrcList;   /* One or more tables used to resolve names */
9466  ExprList *pEList;    /* Optional list of named expressions */
9467  int nRef;            /* Number of names resolved by this context */
9468  int nErr;            /* Number of errors encountered while resolving names */
9469  u8 allowAgg;         /* Aggregate functions allowed here */
9470  u8 hasAgg;           /* True if aggregates are seen */
9471  u8 isCheck;          /* True if resolving names in a CHECK constraint */
9472  int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
9473  AggInfo *pAggInfo;   /* Information about aggregates at this level */
9474  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
9475};
9476
9477/*
9478** An instance of the following structure contains all information
9479** needed to generate code for a single SELECT statement.
9480**
9481** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
9482** If there is a LIMIT clause, the parser sets nLimit to the value of the
9483** limit and nOffset to the value of the offset (or 0 if there is not
9484** offset).  But later on, nLimit and nOffset become the memory locations
9485** in the VDBE that record the limit and offset counters.
9486**
9487** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
9488** These addresses must be stored so that we can go back and fill in
9489** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
9490** the number of columns in P2 can be computed at the same time
9491** as the OP_OpenEphm instruction is coded because not
9492** enough information about the compound query is known at that point.
9493** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
9494** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
9495** sequences for the ORDER BY clause.
9496*/
9497struct Select {
9498  ExprList *pEList;      /* The fields of the result */
9499  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
9500  char affinity;         /* MakeRecord with this affinity for SRT_Set */
9501  u16 selFlags;          /* Various SF_* values */
9502  SrcList *pSrc;         /* The FROM clause */
9503  Expr *pWhere;          /* The WHERE clause */
9504  ExprList *pGroupBy;    /* The GROUP BY clause */
9505  Expr *pHaving;         /* The HAVING clause */
9506  ExprList *pOrderBy;    /* The ORDER BY clause */
9507  Select *pPrior;        /* Prior select in a compound select statement */
9508  Select *pNext;         /* Next select to the left in a compound */
9509  Select *pRightmost;    /* Right-most select in a compound select statement */
9510  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
9511  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
9512  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
9513  int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
9514};
9515
9516/*
9517** Allowed values for Select.selFlags.  The "SF" prefix stands for
9518** "Select Flag".
9519*/
9520#define SF_Distinct        0x0001  /* Output should be DISTINCT */
9521#define SF_Resolved        0x0002  /* Identifiers have been resolved */
9522#define SF_Aggregate       0x0004  /* Contains aggregate functions */
9523#define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
9524#define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
9525#define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
9526
9527
9528/*
9529** The results of a select can be distributed in several ways.  The
9530** "SRT" prefix means "SELECT Result Type".
9531*/
9532#define SRT_Union        1  /* Store result as keys in an index */
9533#define SRT_Except       2  /* Remove result from a UNION index */
9534#define SRT_Exists       3  /* Store 1 if the result is not empty */
9535#define SRT_Discard      4  /* Do not save the results anywhere */
9536
9537/* The ORDER BY clause is ignored for all of the above */
9538#define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
9539
9540#define SRT_Output       5  /* Output each row of result */
9541#define SRT_Mem          6  /* Store result in a memory cell */
9542#define SRT_Set          7  /* Store results as keys in an index */
9543#define SRT_Table        8  /* Store result as data with an automatic rowid */
9544#define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
9545#define SRT_Coroutine   10  /* Generate a single row of result */
9546
9547/*
9548** A structure used to customize the behavior of sqlite3Select(). See
9549** comments above sqlite3Select() for details.
9550*/
9551typedef struct SelectDest SelectDest;
9552struct SelectDest {
9553  u8 eDest;         /* How to dispose of the results */
9554  u8 affinity;      /* Affinity used when eDest==SRT_Set */
9555  int iParm;        /* A parameter used by the eDest disposal method */
9556  int iMem;         /* Base register where results are written */
9557  int nMem;         /* Number of registers allocated */
9558};
9559
9560/*
9561** During code generation of statements that do inserts into AUTOINCREMENT
9562** tables, the following information is attached to the Table.u.autoInc.p
9563** pointer of each autoincrement table to record some side information that
9564** the code generator needs.  We have to keep per-table autoincrement
9565** information in case inserts are down within triggers.  Triggers do not
9566** normally coordinate their activities, but we do need to coordinate the
9567** loading and saving of autoincrement information.
9568*/
9569struct AutoincInfo {
9570  AutoincInfo *pNext;   /* Next info block in a list of them all */
9571  Table *pTab;          /* Table this info block refers to */
9572  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
9573  int regCtr;           /* Memory register holding the rowid counter */
9574};
9575
9576/*
9577** Size of the column cache
9578*/
9579#ifndef SQLITE_N_COLCACHE
9580# define SQLITE_N_COLCACHE 10
9581#endif
9582
9583/*
9584** At least one instance of the following structure is created for each
9585** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
9586** statement. All such objects are stored in the linked list headed at
9587** Parse.pTriggerPrg and deleted once statement compilation has been
9588** completed.
9589**
9590** A Vdbe sub-program that implements the body and WHEN clause of trigger
9591** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
9592** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
9593** The Parse.pTriggerPrg list never contains two entries with the same
9594** values for both pTrigger and orconf.
9595**
9596** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
9597** accessed (or set to 0 for triggers fired as a result of INSERT
9598** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
9599** a mask of new.* columns used by the program.
9600*/
9601struct TriggerPrg {
9602  Trigger *pTrigger;      /* Trigger this program was coded from */
9603  int orconf;             /* Default ON CONFLICT policy */
9604  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
9605  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
9606  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
9607};
9608
9609/*
9610** An SQL parser context.  A copy of this structure is passed through
9611** the parser and down into all the parser action routine in order to
9612** carry around information that is global to the entire parse.
9613**
9614** The structure is divided into two parts.  When the parser and code
9615** generate call themselves recursively, the first part of the structure
9616** is constant but the second part is reset at the beginning and end of
9617** each recursion.
9618**
9619** The nTableLock and aTableLock variables are only used if the shared-cache
9620** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
9621** used to store the set of table-locks required by the statement being
9622** compiled. Function sqlite3TableLock() is used to add entries to the
9623** list.
9624*/
9625struct Parse {
9626  sqlite3 *db;         /* The main database structure */
9627  int rc;              /* Return code from execution */
9628  char *zErrMsg;       /* An error message */
9629  Vdbe *pVdbe;         /* An engine for executing database bytecode */
9630  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
9631  u8 nameClash;        /* A permanent table name clashes with temp table name */
9632  u8 checkSchema;      /* Causes schema cookie check after an error */
9633  u8 nested;           /* Number of nested calls to the parser/code generator */
9634  u8 parseError;       /* True after a parsing error.  Ticket #1794 */
9635  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
9636  u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
9637  int aTempReg[8];     /* Holding area for temporary registers */
9638  int nRangeReg;       /* Size of the temporary register block */
9639  int iRangeReg;       /* First register in temporary register block */
9640  int nErr;            /* Number of errors seen */
9641  int nTab;            /* Number of previously allocated VDBE cursors */
9642  int nMem;            /* Number of memory cells used so far */
9643  int nSet;            /* Number of sets used so far */
9644  int ckBase;          /* Base register of data during check constraints */
9645  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
9646  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
9647  u8 nColCache;        /* Number of entries in the column cache */
9648  u8 iColCache;        /* Next entry of the cache to replace */
9649  struct yColCache {
9650    int iTable;           /* Table cursor number */
9651    int iColumn;          /* Table column number */
9652    u8 tempReg;           /* iReg is a temp register that needs to be freed */
9653    int iLevel;           /* Nesting level */
9654    int iReg;             /* Reg with value of this column. 0 means none. */
9655    int lru;              /* Least recently used entry has the smallest value */
9656  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
9657  u32 writeMask;       /* Start a write transaction on these databases */
9658  u32 cookieMask;      /* Bitmask of schema verified databases */
9659  u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
9660  u8 mayAbort;         /* True if statement may throw an ABORT exception */
9661  int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
9662  int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
9663#ifndef SQLITE_OMIT_SHARED_CACHE
9664  int nTableLock;        /* Number of locks in aTableLock */
9665  TableLock *aTableLock; /* Required table locks for shared-cache mode */
9666#endif
9667  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
9668  int regRoot;         /* Register holding root page number for new objects */
9669  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
9670  int nMaxArg;         /* Max args passed to user function by sub-program */
9671
9672  /* Information used while coding trigger programs. */
9673  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
9674  Table *pTriggerTab;  /* Table triggers are being coded for */
9675  u32 oldmask;         /* Mask of old.* columns referenced */
9676  u32 newmask;         /* Mask of new.* columns referenced */
9677  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
9678  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
9679  u8 disableTriggers;  /* True to disable triggers */
9680
9681  /* Above is constant between recursions.  Below is reset before and after
9682  ** each recursion */
9683
9684  int nVar;            /* Number of '?' variables seen in the SQL so far */
9685  int nVarExpr;        /* Number of used slots in apVarExpr[] */
9686  int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
9687  Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
9688  Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
9689  int nAlias;          /* Number of aliased result set columns */
9690  int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
9691  int *aAlias;         /* Register used to hold aliased result */
9692  u8 explain;          /* True if the EXPLAIN flag is found on the query */
9693  Token sNameToken;    /* Token with unqualified schema object name */
9694  Token sLastToken;    /* The last token parsed */
9695  const char *zTail;   /* All SQL text past the last semicolon parsed */
9696  Table *pNewTable;    /* A table being constructed by CREATE TABLE */
9697  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
9698  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
9699#ifndef SQLITE_OMIT_VIRTUALTABLE
9700  Token sArg;                /* Complete text of a module argument */
9701  u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
9702  int nVtabLock;             /* Number of virtual tables to lock */
9703  Table **apVtabLock;        /* Pointer to virtual tables needing locking */
9704#endif
9705  int nHeight;            /* Expression tree height of current sub-select */
9706  Table *pZombieTab;      /* List of Table objects to delete after code gen */
9707  TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
9708};
9709
9710#ifdef SQLITE_OMIT_VIRTUALTABLE
9711  #define IN_DECLARE_VTAB 0
9712#else
9713  #define IN_DECLARE_VTAB (pParse->declareVtab)
9714#endif
9715
9716/*
9717** An instance of the following structure can be declared on a stack and used
9718** to save the Parse.zAuthContext value so that it can be restored later.
9719*/
9720struct AuthContext {
9721  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
9722  Parse *pParse;              /* The Parse structure */
9723};
9724
9725/*
9726** Bitfield flags for P5 value in OP_Insert and OP_Delete
9727*/
9728#define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
9729#define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
9730#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
9731#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
9732#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
9733#define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
9734
9735/*
9736 * Each trigger present in the database schema is stored as an instance of
9737 * struct Trigger.
9738 *
9739 * Pointers to instances of struct Trigger are stored in two ways.
9740 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
9741 *    database). This allows Trigger structures to be retrieved by name.
9742 * 2. All triggers associated with a single table form a linked list, using the
9743 *    pNext member of struct Trigger. A pointer to the first element of the
9744 *    linked list is stored as the "pTrigger" member of the associated
9745 *    struct Table.
9746 *
9747 * The "step_list" member points to the first element of a linked list
9748 * containing the SQL statements specified as the trigger program.
9749 */
9750struct Trigger {
9751  char *zName;            /* The name of the trigger                        */
9752  char *table;            /* The table or view to which the trigger applies */
9753  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
9754  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
9755  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
9756  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
9757                             the <column-list> is stored here */
9758  Schema *pSchema;        /* Schema containing the trigger */
9759  Schema *pTabSchema;     /* Schema containing the table */
9760  TriggerStep *step_list; /* Link list of trigger program steps             */
9761  Trigger *pNext;         /* Next trigger associated with the table */
9762};
9763
9764/*
9765** A trigger is either a BEFORE or an AFTER trigger.  The following constants
9766** determine which.
9767**
9768** If there are multiple triggers, you might of some BEFORE and some AFTER.
9769** In that cases, the constants below can be ORed together.
9770*/
9771#define TRIGGER_BEFORE  1
9772#define TRIGGER_AFTER   2
9773
9774/*
9775 * An instance of struct TriggerStep is used to store a single SQL statement
9776 * that is a part of a trigger-program.
9777 *
9778 * Instances of struct TriggerStep are stored in a singly linked list (linked
9779 * using the "pNext" member) referenced by the "step_list" member of the
9780 * associated struct Trigger instance. The first element of the linked list is
9781 * the first step of the trigger-program.
9782 *
9783 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
9784 * "SELECT" statement. The meanings of the other members is determined by the
9785 * value of "op" as follows:
9786 *
9787 * (op == TK_INSERT)
9788 * orconf    -> stores the ON CONFLICT algorithm
9789 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
9790 *              this stores a pointer to the SELECT statement. Otherwise NULL.
9791 * target    -> A token holding the quoted name of the table to insert into.
9792 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
9793 *              this stores values to be inserted. Otherwise NULL.
9794 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
9795 *              statement, then this stores the column-names to be
9796 *              inserted into.
9797 *
9798 * (op == TK_DELETE)
9799 * target    -> A token holding the quoted name of the table to delete from.
9800 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
9801 *              Otherwise NULL.
9802 *
9803 * (op == TK_UPDATE)
9804 * target    -> A token holding the quoted name of the table to update rows of.
9805 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
9806 *              Otherwise NULL.
9807 * pExprList -> A list of the columns to update and the expressions to update
9808 *              them to. See sqlite3Update() documentation of "pChanges"
9809 *              argument.
9810 *
9811 */
9812struct TriggerStep {
9813  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
9814  u8 orconf;           /* OE_Rollback etc. */
9815  Trigger *pTrig;      /* The trigger that this step is a part of */
9816  Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
9817  Token target;        /* Target table for DELETE, UPDATE, INSERT */
9818  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
9819  ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
9820  IdList *pIdList;     /* Column names for INSERT */
9821  TriggerStep *pNext;  /* Next in the link-list */
9822  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
9823};
9824
9825/*
9826** The following structure contains information used by the sqliteFix...
9827** routines as they walk the parse tree to make database references
9828** explicit.
9829*/
9830typedef struct DbFixer DbFixer;
9831struct DbFixer {
9832  Parse *pParse;      /* The parsing context.  Error messages written here */
9833  const char *zDb;    /* Make sure all objects are contained in this database */
9834  const char *zType;  /* Type of the container - used for error messages */
9835  const Token *pName; /* Name of the container - used for error messages */
9836};
9837
9838/*
9839** An objected used to accumulate the text of a string where we
9840** do not necessarily know how big the string will be in the end.
9841*/
9842struct StrAccum {
9843  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
9844  char *zBase;         /* A base allocation.  Not from malloc. */
9845  char *zText;         /* The string collected so far */
9846  int  nChar;          /* Length of the string so far */
9847  int  nAlloc;         /* Amount of space allocated in zText */
9848  int  mxAlloc;        /* Maximum allowed string length */
9849  u8   mallocFailed;   /* Becomes true if any memory allocation fails */
9850  u8   useMalloc;      /* True if zText is enlargeable using realloc */
9851  u8   tooBig;         /* Becomes true if string size exceeds limits */
9852};
9853
9854/*
9855** A pointer to this structure is used to communicate information
9856** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
9857*/
9858typedef struct {
9859  sqlite3 *db;        /* The database being initialized */
9860  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
9861  char **pzErrMsg;    /* Error message stored here */
9862  int rc;             /* Result code stored here */
9863} InitData;
9864
9865/*
9866** Structure containing global configuration data for the SQLite library.
9867**
9868** This structure also contains some state information.
9869*/
9870struct Sqlite3Config {
9871  int bMemstat;                     /* True to enable memory status */
9872  int bCoreMutex;                   /* True to enable core mutexing */
9873  int bFullMutex;                   /* True to enable full mutexing */
9874  int mxStrlen;                     /* Maximum string length */
9875  int szLookaside;                  /* Default lookaside buffer size */
9876  int nLookaside;                   /* Default lookaside buffer count */
9877  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
9878  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
9879  sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
9880  void *pHeap;                      /* Heap storage space */
9881  int nHeap;                        /* Size of pHeap[] */
9882  int mnReq, mxReq;                 /* Min and max heap requests sizes */
9883  void *pScratch;                   /* Scratch memory */
9884  int szScratch;                    /* Size of each scratch buffer */
9885  int nScratch;                     /* Number of scratch buffers */
9886  void *pPage;                      /* Page cache memory */
9887  int szPage;                       /* Size of each page in pPage[] */
9888  int nPage;                        /* Number of pages in pPage[] */
9889  int mxParserStack;                /* maximum depth of the parser stack */
9890  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
9891  /* The above might be initialized to non-zero.  The following need to always
9892  ** initially be zero, however. */
9893  int isInit;                       /* True after initialization has finished */
9894  int inProgress;                   /* True while initialization in progress */
9895  int isMutexInit;                  /* True after mutexes are initialized */
9896  int isMallocInit;                 /* True after malloc is initialized */
9897  int isPCacheInit;                 /* True after malloc is initialized */
9898  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
9899  int nRefInitMutex;                /* Number of users of pInitMutex */
9900  void (*xLog)(void*,int,const char*); /* Function for logging */
9901  void *pLogArg;                       /* First argument to xLog() */
9902};
9903
9904/*
9905** Context pointer passed down through the tree-walk.
9906*/
9907struct Walker {
9908  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
9909  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
9910  Parse *pParse;                            /* Parser context.  */
9911  union {                                   /* Extra data for callback */
9912    NameContext *pNC;                          /* Naming context */
9913    int i;                                     /* Integer value */
9914  } u;
9915};
9916
9917/* Forward declarations */
9918SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
9919SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
9920SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
9921SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
9922SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
9923
9924/*
9925** Return code from the parse-tree walking primitives and their
9926** callbacks.
9927*/
9928#define WRC_Continue    0   /* Continue down into children */
9929#define WRC_Prune       1   /* Omit children but continue walking siblings */
9930#define WRC_Abort       2   /* Abandon the tree walk */
9931
9932/*
9933** Assuming zIn points to the first byte of a UTF-8 character,
9934** advance zIn to point to the first byte of the next UTF-8 character.
9935*/
9936#define SQLITE_SKIP_UTF8(zIn) {                        \
9937  if( (*(zIn++))>=0xc0 ){                              \
9938    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
9939  }                                                    \
9940}
9941
9942/*
9943** The SQLITE_*_BKPT macros are substitutes for the error codes with
9944** the same name but without the _BKPT suffix.  These macros invoke
9945** routines that report the line-number on which the error originated
9946** using sqlite3_log().  The routines also provide a convenient place
9947** to set a debugger breakpoint.
9948*/
9949SQLITE_PRIVATE int sqlite3CorruptError(int);
9950SQLITE_PRIVATE int sqlite3MisuseError(int);
9951SQLITE_PRIVATE int sqlite3CantopenError(int);
9952#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
9953#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
9954#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
9955
9956
9957/*
9958** The ctype.h header is needed for non-ASCII systems.  It is also
9959** needed by FTS3 when FTS3 is included in the amalgamation.
9960*/
9961#if !defined(SQLITE_ASCII) || \
9962    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
9963# include <ctype.h>
9964#endif
9965
9966/*
9967** The following macros mimic the standard library functions toupper(),
9968** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
9969** sqlite versions only work for ASCII characters, regardless of locale.
9970*/
9971#ifdef SQLITE_ASCII
9972# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
9973# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
9974# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
9975# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
9976# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
9977# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
9978# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
9979#else
9980# define sqlite3Toupper(x)   toupper((unsigned char)(x))
9981# define sqlite3Isspace(x)   isspace((unsigned char)(x))
9982# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
9983# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
9984# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
9985# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
9986# define sqlite3Tolower(x)   tolower((unsigned char)(x))
9987#endif
9988
9989/*
9990** Internal function prototypes
9991*/
9992SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
9993SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
9994SQLITE_PRIVATE int sqlite3Strlen30(const char*);
9995#define sqlite3StrNICmp sqlite3_strnicmp
9996
9997SQLITE_PRIVATE int sqlite3MallocInit(void);
9998SQLITE_PRIVATE void sqlite3MallocEnd(void);
9999SQLITE_PRIVATE void *sqlite3Malloc(int);
10000SQLITE_PRIVATE void *sqlite3MallocZero(int);
10001SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10002SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10003SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10004SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10005SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10006SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10007SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10008SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10009SQLITE_PRIVATE int sqlite3MallocSize(void*);
10010SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10011SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10012SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10013SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10014SQLITE_PRIVATE void sqlite3PageFree(void*);
10015SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10016SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10017SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
10018
10019/*
10020** On systems with ample stack space and that support alloca(), make
10021** use of alloca() to obtain space for large automatic objects.  By default,
10022** obtain space from malloc().
10023**
10024** The alloca() routine never returns NULL.  This will cause code paths
10025** that deal with sqlite3StackAlloc() failures to be unreachable.
10026*/
10027#ifdef SQLITE_USE_ALLOCA
10028# define sqlite3StackAllocRaw(D,N)   alloca(N)
10029# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
10030# define sqlite3StackFree(D,P)
10031#else
10032# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
10033# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
10034# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
10035#endif
10036
10037#ifdef SQLITE_ENABLE_MEMSYS3
10038SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10039#endif
10040#ifdef SQLITE_ENABLE_MEMSYS5
10041SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10042#endif
10043
10044
10045#ifndef SQLITE_MUTEX_OMIT
10046SQLITE_PRIVATE   sqlite3_mutex_methods *sqlite3DefaultMutex(void);
10047SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10048SQLITE_PRIVATE   int sqlite3MutexInit(void);
10049SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10050#endif
10051
10052SQLITE_PRIVATE int sqlite3StatusValue(int);
10053SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10054SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10055
10056SQLITE_PRIVATE int sqlite3IsNaN(double);
10057
10058SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10059#ifndef SQLITE_OMIT_TRACE
10060SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10061#endif
10062SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10063SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10064SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10065#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10066SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10067#endif
10068#if defined(SQLITE_TEST)
10069SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10070#endif
10071SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10072SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10073SQLITE_PRIVATE int sqlite3Dequote(char*);
10074SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10075SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10076SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10077SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10078SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10079SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10080SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10081SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
10082SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
10083SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
10084SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10085SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10086SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10087SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10088SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10089SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
10090SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
10091SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
10092SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10093SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10094SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10095SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10096SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10097SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10098SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10099SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10100SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10101SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10102SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10103SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10104SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10105SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10106SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10107SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
10108SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10109SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10110
10111SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10112SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10113SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10114SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
10115SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10116SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
10117SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
10118
10119SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
10120SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
10121SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
10122SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
10123SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
10124
10125SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
10126
10127#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
10128SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
10129#else
10130# define sqlite3ViewGetColumnNames(A,B) 0
10131#endif
10132
10133SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10134SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
10135#ifndef SQLITE_OMIT_AUTOINCREMENT
10136SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
10137SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
10138#else
10139# define sqlite3AutoincrementBegin(X)
10140# define sqlite3AutoincrementEnd(X)
10141#endif
10142SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
10143SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
10144SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
10145SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
10146SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
10147SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
10148SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
10149                                      Token*, Select*, Expr*, IdList*);
10150SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
10151SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
10152SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
10153SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
10154SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
10155SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
10156SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
10157                        Token*, int, int);
10158SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
10159SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
10160SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
10161                         Expr*,ExprList*,int,Expr*,Expr*);
10162SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
10163SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
10164SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
10165SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
10166#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
10167SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
10168#endif
10169SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
10170SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
10171SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
10172SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10173SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
10174SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10175SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10176SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
10177SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
10178SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
10179SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
10180SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
10181SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10182SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
10183SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10184SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10185SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10186SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10187SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
10188SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
10189SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
10190SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
10191SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
10192SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
10193SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
10194SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
10195SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
10196SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
10197SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10198SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10199SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10200SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10201SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10202SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10203SQLITE_PRIVATE void sqlite3PrngSaveState(void);
10204SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
10205SQLITE_PRIVATE void sqlite3PrngResetState(void);
10206SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
10207SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
10208SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
10209SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
10210SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
10211SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
10212SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
10213SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
10214SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
10215SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
10216SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
10217SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
10218SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
10219SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
10220SQLITE_PRIVATE int sqlite3IsRowid(const char*);
10221SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
10222SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
10223SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
10224SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
10225                                     int*,int,int,int,int,int*);
10226SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
10227SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
10228SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
10229SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
10230SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
10231SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
10232SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
10233SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
10234SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
10235SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
10236SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
10237SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
10238SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
10239SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
10240SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
10241SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
10242SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
10243SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
10244SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
10245
10246#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
10247SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
10248#endif
10249
10250#ifndef SQLITE_OMIT_TRIGGER
10251SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
10252                           Expr*,int, int);
10253SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
10254SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
10255SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
10256SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
10257SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
10258SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
10259                            int, int, int);
10260SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
10261  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
10262SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
10263SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
10264SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
10265                                        ExprList*,Select*,u8);
10266SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
10267SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
10268SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
10269SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
10270SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
10271# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
10272#else
10273# define sqlite3TriggersExist(B,C,D,E,F) 0
10274# define sqlite3DeleteTrigger(A,B)
10275# define sqlite3DropTriggerPtr(A,B)
10276# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
10277# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
10278# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
10279# define sqlite3TriggerList(X, Y) 0
10280# define sqlite3ParseToplevel(p) p
10281# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
10282#endif
10283
10284SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
10285SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
10286SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
10287#ifndef SQLITE_OMIT_AUTHORIZATION
10288SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
10289SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
10290SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
10291SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
10292SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
10293#else
10294# define sqlite3AuthRead(a,b,c,d)
10295# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
10296# define sqlite3AuthContextPush(a,b,c)
10297# define sqlite3AuthContextPop(a)  ((void)(a))
10298#endif
10299SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10300SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10301SQLITE_PRIVATE int sqlite3BtreeFactory(sqlite3 *db, const char *zFilename,
10302                       int omitJournal, int nCache, int flags, Btree **ppBtree);
10303SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10304SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10305SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10306SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10307SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
10308SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
10309SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
10310SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
10311SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
10312SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
10313SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
10314SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
10315
10316/*
10317** Routines to read and write variable-length integers.  These used to
10318** be defined locally, but now we use the varint routines in the util.c
10319** file.  Code should use the MACRO forms below, as the Varint32 versions
10320** are coded to assume the single byte case is already handled (which
10321** the MACRO form does).
10322*/
10323SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
10324SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
10325SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
10326SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
10327SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
10328
10329/*
10330** The header of a record consists of a sequence variable-length integers.
10331** These integers are almost always small and are encoded as a single byte.
10332** The following macros take advantage this fact to provide a fast encode
10333** and decode of the integers in a record header.  It is faster for the common
10334** case where the integer is a single byte.  It is a little slower when the
10335** integer is two or more bytes.  But overall it is faster.
10336**
10337** The following expressions are equivalent:
10338**
10339**     x = sqlite3GetVarint32( A, &B );
10340**     x = sqlite3PutVarint32( A, B );
10341**
10342**     x = getVarint32( A, B );
10343**     x = putVarint32( A, B );
10344**
10345*/
10346#define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
10347#define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
10348#define getVarint    sqlite3GetVarint
10349#define putVarint    sqlite3PutVarint
10350
10351
10352SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
10353SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
10354SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
10355SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
10356SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
10357SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
10358SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
10359SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
10360SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
10361SQLITE_PRIVATE const char *sqlite3ErrStr(int);
10362SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
10363SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
10364SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
10365SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10366SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
10367SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10368SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10369SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
10370
10371SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
10372SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
10373SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
10374                        void(*)(void*));
10375SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
10376SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
10377SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
10378#ifdef SQLITE_ENABLE_STAT2
10379SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
10380#endif
10381SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
10382SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
10383#ifndef SQLITE_AMALGAMATION
10384SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
10385SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10386SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
10387SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
10388SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10389SQLITE_PRIVATE int sqlite3PendingByte;
10390#endif
10391SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10392SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10393SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
10394SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10395SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10396SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
10397SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
10398SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
10399SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
10400SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
10401SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
10402SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
10403SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
10404SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
10405SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
10406SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
10407SQLITE_PRIVATE char sqlite3AffinityType(const char*);
10408SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
10409SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
10410SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10411SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
10412SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
10413SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index*);
10414SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
10415SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
10416SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
10417SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
10418SQLITE_PRIVATE void sqlite3SchemaFree(void *);
10419SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
10420SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
10421SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
10422SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
10423  void (*)(sqlite3_context*,int,sqlite3_value **),
10424  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
10425SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
10426SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
10427
10428SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
10429SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
10430SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
10431SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
10432SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
10433SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
10434
10435SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
10436SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
10437
10438/*
10439** The interface to the LEMON-generated parser
10440*/
10441SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
10442SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
10443SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
10444#ifdef YYTRACKMAXSTACKDEPTH
10445SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
10446#endif
10447
10448SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
10449#ifndef SQLITE_OMIT_LOAD_EXTENSION
10450SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
10451#else
10452# define sqlite3CloseExtensions(X)
10453#endif
10454
10455#ifndef SQLITE_OMIT_SHARED_CACHE
10456SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
10457#else
10458  #define sqlite3TableLock(v,w,x,y,z)
10459#endif
10460
10461#ifdef SQLITE_TEST
10462SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
10463#endif
10464
10465#ifdef SQLITE_OMIT_VIRTUALTABLE
10466#  define sqlite3VtabClear(Y)
10467#  define sqlite3VtabSync(X,Y) SQLITE_OK
10468#  define sqlite3VtabRollback(X)
10469#  define sqlite3VtabCommit(X)
10470#  define sqlite3VtabInSync(db) 0
10471#  define sqlite3VtabLock(X)
10472#  define sqlite3VtabUnlock(X)
10473#  define sqlite3VtabUnlockList(X)
10474#else
10475SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
10476SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
10477SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
10478SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
10479SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
10480SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
10481SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
10482#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
10483#endif
10484SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
10485SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
10486SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
10487SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
10488SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
10489SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
10490SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
10491SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
10492SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
10493SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
10494SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
10495SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
10496SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
10497SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
10498SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
10499SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10500SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
10501SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
10502
10503/* Declarations for functions in fkey.c. All of these are replaced by
10504** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
10505** key functionality is available. If OMIT_TRIGGER is defined but
10506** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
10507** this case foreign keys are parsed, but no other functionality is
10508** provided (enforcement of FK constraints requires the triggers sub-system).
10509*/
10510#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
10511SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
10512SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
10513SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
10514SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
10515SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
10516SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
10517#else
10518  #define sqlite3FkActions(a,b,c,d)
10519  #define sqlite3FkCheck(a,b,c,d)
10520  #define sqlite3FkDropTable(a,b,c)
10521  #define sqlite3FkOldmask(a,b)      0
10522  #define sqlite3FkRequired(a,b,c,d) 0
10523#endif
10524#ifndef SQLITE_OMIT_FOREIGN_KEY
10525SQLITE_PRIVATE   void sqlite3FkDelete(Table*);
10526#else
10527  #define sqlite3FkDelete(a)
10528#endif
10529
10530
10531/*
10532** Available fault injectors.  Should be numbered beginning with 0.
10533*/
10534#define SQLITE_FAULTINJECTOR_MALLOC     0
10535#define SQLITE_FAULTINJECTOR_COUNT      1
10536
10537/*
10538** The interface to the code in fault.c used for identifying "benign"
10539** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
10540** is not defined.
10541*/
10542#ifndef SQLITE_OMIT_BUILTIN_TEST
10543SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
10544SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
10545#else
10546  #define sqlite3BeginBenignMalloc()
10547  #define sqlite3EndBenignMalloc()
10548#endif
10549
10550#define IN_INDEX_ROWID           1
10551#define IN_INDEX_EPH             2
10552#define IN_INDEX_INDEX           3
10553SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
10554
10555#ifdef SQLITE_ENABLE_ATOMIC_WRITE
10556SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
10557SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
10558SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
10559#else
10560  #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
10561#endif
10562
10563SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
10564SQLITE_PRIVATE int sqlite3MemJournalSize(void);
10565SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
10566
10567#if SQLITE_MAX_EXPR_DEPTH>0
10568SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
10569SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
10570SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
10571#else
10572  #define sqlite3ExprSetHeight(x,y)
10573  #define sqlite3SelectExprHeight(x) 0
10574  #define sqlite3ExprCheckHeight(x,y)
10575#endif
10576
10577SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
10578SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
10579
10580#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10581SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
10582SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
10583SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
10584#else
10585  #define sqlite3ConnectionBlocked(x,y)
10586  #define sqlite3ConnectionUnlocked(x)
10587  #define sqlite3ConnectionClosed(x)
10588#endif
10589
10590#ifdef SQLITE_DEBUG
10591SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
10592#endif
10593
10594/*
10595** If the SQLITE_ENABLE IOTRACE exists then the global variable
10596** sqlite3IoTrace is a pointer to a printf-like routine used to
10597** print I/O tracing messages.
10598*/
10599#ifdef SQLITE_ENABLE_IOTRACE
10600# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
10601SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
10602SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
10603#else
10604# define IOTRACE(A)
10605# define sqlite3VdbeIOTraceSql(X)
10606#endif
10607
10608#endif
10609
10610/************** End of sqliteInt.h *******************************************/
10611/************** Begin file global.c ******************************************/
10612/*
10613** 2008 June 13
10614**
10615** The author disclaims copyright to this source code.  In place of
10616** a legal notice, here is a blessing:
10617**
10618**    May you do good and not evil.
10619**    May you find forgiveness for yourself and forgive others.
10620**    May you share freely, never taking more than you give.
10621**
10622*************************************************************************
10623**
10624** This file contains definitions of global variables and contants.
10625*/
10626
10627/* An array to map all upper-case characters into their corresponding
10628** lower-case character.
10629**
10630** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
10631** handle case conversions for the UTF character set since the tables
10632** involved are nearly as big or bigger than SQLite itself.
10633*/
10634SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
10635#ifdef SQLITE_ASCII
10636      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
10637     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
10638     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
10639     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
10640    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
10641    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
10642    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
10643    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
10644    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
10645    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
10646    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
10647    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
10648    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
10649    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
10650    252,253,254,255
10651#endif
10652#ifdef SQLITE_EBCDIC
10653      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
10654     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
10655     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
10656     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
10657     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
10658     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
10659     96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
10660    112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
10661    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
10662    144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
10663    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
10664    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
10665    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
10666    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
10667    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
10668    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
10669#endif
10670};
10671
10672/*
10673** The following 256 byte lookup table is used to support SQLites built-in
10674** equivalents to the following standard library functions:
10675**
10676**   isspace()                        0x01
10677**   isalpha()                        0x02
10678**   isdigit()                        0x04
10679**   isalnum()                        0x06
10680**   isxdigit()                       0x08
10681**   toupper()                        0x20
10682**   SQLite identifier character      0x40
10683**
10684** Bit 0x20 is set if the mapped character requires translation to upper
10685** case. i.e. if the character is a lower-case ASCII character.
10686** If x is a lower-case ASCII character, then its upper-case equivalent
10687** is (x - 0x20). Therefore toupper() can be implemented as:
10688**
10689**   (x & ~(map[x]&0x20))
10690**
10691** Standard function tolower() is implemented using the sqlite3UpperToLower[]
10692** array. tolower() is used more often than toupper() by SQLite.
10693**
10694** Bit 0x40 is set if the character non-alphanumeric and can be used in an
10695** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
10696** non-ASCII UTF character. Hence the test for whether or not a character is
10697** part of an identifier is 0x46.
10698**
10699** SQLite's versions are identical to the standard versions assuming a
10700** locale of "C". They are implemented as macros in sqliteInt.h.
10701*/
10702#ifdef SQLITE_ASCII
10703SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
10704  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
10705  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
10706  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
10707  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
10708  0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
10709  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
10710  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
10711  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
10712
10713  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
10714  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
10715  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
10716  0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
10717  0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
10718  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
10719  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
10720  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
10721
10722  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
10723  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
10724  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
10725  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
10726  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
10727  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
10728  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
10729  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
10730
10731  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
10732  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
10733  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
10734  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
10735  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
10736  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
10737  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
10738  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
10739};
10740#endif
10741
10742
10743
10744/*
10745** The following singleton contains the global configuration for
10746** the SQLite library.
10747*/
10748SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
10749   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
10750   1,                         /* bCoreMutex */
10751   SQLITE_THREADSAFE==1,      /* bFullMutex */
10752   0x7ffffffe,                /* mxStrlen */
10753   100,                       /* szLookaside */
10754   500,                       /* nLookaside */
10755   {0,0,0,0,0,0,0,0},         /* m */
10756   {0,0,0,0,0,0,0,0,0},       /* mutex */
10757   {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
10758   (void*)0,                  /* pHeap */
10759   0,                         /* nHeap */
10760   0, 0,                      /* mnHeap, mxHeap */
10761   (void*)0,                  /* pScratch */
10762   0,                         /* szScratch */
10763   0,                         /* nScratch */
10764   (void*)0,                  /* pPage */
10765   0,                         /* szPage */
10766   0,                         /* nPage */
10767   0,                         /* mxParserStack */
10768   0,                         /* sharedCacheEnabled */
10769   /* All the rest should always be initialized to zero */
10770   0,                         /* isInit */
10771   0,                         /* inProgress */
10772   0,                         /* isMutexInit */
10773   0,                         /* isMallocInit */
10774   0,                         /* isPCacheInit */
10775   0,                         /* pInitMutex */
10776   0,                         /* nRefInitMutex */
10777   0,                         /* xLog */
10778   0,                         /* pLogArg */
10779};
10780
10781
10782/*
10783** Hash table for global functions - functions common to all
10784** database connections.  After initialization, this table is
10785** read-only.
10786*/
10787SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10788
10789/*
10790** The value of the "pending" byte must be 0x40000000 (1 byte past the
10791** 1-gibabyte boundary) in a compatible database.  SQLite never uses
10792** the database page that contains the pending byte.  It never attempts
10793** to read or write that page.  The pending byte page is set assign
10794** for use by the VFS layers as space for managing file locks.
10795**
10796** During testing, it is often desirable to move the pending byte to
10797** a different position in the file.  This allows code that has to
10798** deal with the pending byte to run on files that are much smaller
10799** than 1 GiB.  The sqlite3_test_control() interface can be used to
10800** move the pending byte.
10801**
10802** IMPORTANT:  Changing the pending byte to any value other than
10803** 0x40000000 results in an incompatible database file format!
10804** Changing the pending byte during operating results in undefined
10805** and dileterious behavior.
10806*/
10807SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
10808
10809/*
10810** Properties of opcodes.  The OPFLG_INITIALIZER macro is
10811** created by mkopcodeh.awk during compilation.  Data is obtained
10812** from the comments following the "case OP_xxxx:" statements in
10813** the vdbe.c file.
10814*/
10815SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
10816
10817/************** End of global.c **********************************************/
10818/************** Begin file status.c ******************************************/
10819/*
10820** 2008 June 18
10821**
10822** The author disclaims copyright to this source code.  In place of
10823** a legal notice, here is a blessing:
10824**
10825**    May you do good and not evil.
10826**    May you find forgiveness for yourself and forgive others.
10827**    May you share freely, never taking more than you give.
10828**
10829*************************************************************************
10830**
10831** This module implements the sqlite3_status() interface and related
10832** functionality.
10833*/
10834
10835/*
10836** Variables in which to record status information.
10837*/
10838typedef struct sqlite3StatType sqlite3StatType;
10839static SQLITE_WSD struct sqlite3StatType {
10840  int nowValue[9];         /* Current value */
10841  int mxValue[9];          /* Maximum value */
10842} sqlite3Stat = { {0,}, {0,} };
10843
10844
10845/* The "wsdStat" macro will resolve to the status information
10846** state vector.  If writable static data is unsupported on the target,
10847** we have to locate the state vector at run-time.  In the more common
10848** case where writable static data is supported, wsdStat can refer directly
10849** to the "sqlite3Stat" state vector declared above.
10850*/
10851#ifdef SQLITE_OMIT_WSD
10852# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
10853# define wsdStat x[0]
10854#else
10855# define wsdStatInit
10856# define wsdStat sqlite3Stat
10857#endif
10858
10859/*
10860** Return the current value of a status parameter.
10861*/
10862SQLITE_PRIVATE int sqlite3StatusValue(int op){
10863  wsdStatInit;
10864  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10865  return wsdStat.nowValue[op];
10866}
10867
10868/*
10869** Add N to the value of a status record.  It is assumed that the
10870** caller holds appropriate locks.
10871*/
10872SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
10873  wsdStatInit;
10874  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10875  wsdStat.nowValue[op] += N;
10876  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
10877    wsdStat.mxValue[op] = wsdStat.nowValue[op];
10878  }
10879}
10880
10881/*
10882** Set the value of a status to X.
10883*/
10884SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
10885  wsdStatInit;
10886  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10887  wsdStat.nowValue[op] = X;
10888  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
10889    wsdStat.mxValue[op] = wsdStat.nowValue[op];
10890  }
10891}
10892
10893/*
10894** Query status information.
10895**
10896** This implementation assumes that reading or writing an aligned
10897** 32-bit integer is an atomic operation.  If that assumption is not true,
10898** then this routine is not threadsafe.
10899*/
10900SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
10901  wsdStatInit;
10902  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
10903    return SQLITE_MISUSE_BKPT;
10904  }
10905  *pCurrent = wsdStat.nowValue[op];
10906  *pHighwater = wsdStat.mxValue[op];
10907  if( resetFlag ){
10908    wsdStat.mxValue[op] = wsdStat.nowValue[op];
10909  }
10910  return SQLITE_OK;
10911}
10912
10913/*
10914** Query status information for a single database connection
10915*/
10916SQLITE_API int sqlite3_db_status(
10917  sqlite3 *db,          /* The database connection whose status is desired */
10918  int op,               /* Status verb */
10919  int *pCurrent,        /* Write current value here */
10920  int *pHighwater,      /* Write high-water mark here */
10921  int resetFlag         /* Reset high-water mark if true */
10922){
10923  switch( op ){
10924    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
10925      *pCurrent = db->lookaside.nOut;
10926      *pHighwater = db->lookaside.mxOut;
10927      if( resetFlag ){
10928        db->lookaside.mxOut = db->lookaside.nOut;
10929      }
10930      break;
10931    }
10932    default: {
10933      return SQLITE_ERROR;
10934    }
10935  }
10936  return SQLITE_OK;
10937}
10938
10939/************** End of status.c **********************************************/
10940/************** Begin file date.c ********************************************/
10941/*
10942** 2003 October 31
10943**
10944** The author disclaims copyright to this source code.  In place of
10945** a legal notice, here is a blessing:
10946**
10947**    May you do good and not evil.
10948**    May you find forgiveness for yourself and forgive others.
10949**    May you share freely, never taking more than you give.
10950**
10951*************************************************************************
10952** This file contains the C functions that implement date and time
10953** functions for SQLite.
10954**
10955** There is only one exported symbol in this file - the function
10956** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
10957** All other code has file scope.
10958**
10959** SQLite processes all times and dates as Julian Day numbers.  The
10960** dates and times are stored as the number of days since noon
10961** in Greenwich on November 24, 4714 B.C. according to the Gregorian
10962** calendar system.
10963**
10964** 1970-01-01 00:00:00 is JD 2440587.5
10965** 2000-01-01 00:00:00 is JD 2451544.5
10966**
10967** This implemention requires years to be expressed as a 4-digit number
10968** which means that only dates between 0000-01-01 and 9999-12-31 can
10969** be represented, even though julian day numbers allow a much wider
10970** range of dates.
10971**
10972** The Gregorian calendar system is used for all dates and times,
10973** even those that predate the Gregorian calendar.  Historians usually
10974** use the Julian calendar for dates prior to 1582-10-15 and for some
10975** dates afterwards, depending on locale.  Beware of this difference.
10976**
10977** The conversion algorithms are implemented based on descriptions
10978** in the following text:
10979**
10980**      Jean Meeus
10981**      Astronomical Algorithms, 2nd Edition, 1998
10982**      ISBM 0-943396-61-1
10983**      Willmann-Bell, Inc
10984**      Richmond, Virginia (USA)
10985*/
10986#include <time.h>
10987
10988#ifndef SQLITE_OMIT_DATETIME_FUNCS
10989
10990/*
10991** On recent Windows platforms, the localtime_s() function is available
10992** as part of the "Secure CRT". It is essentially equivalent to
10993** localtime_r() available under most POSIX platforms, except that the
10994** order of the parameters is reversed.
10995**
10996** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
10997**
10998** If the user has not indicated to use localtime_r() or localtime_s()
10999** already, check for an MSVC build environment that provides
11000** localtime_s().
11001*/
11002#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
11003     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
11004#define HAVE_LOCALTIME_S 1
11005#endif
11006
11007/*
11008** A structure for holding a single date and time.
11009*/
11010typedef struct DateTime DateTime;
11011struct DateTime {
11012  sqlite3_int64 iJD; /* The julian day number times 86400000 */
11013  int Y, M, D;       /* Year, month, and day */
11014  int h, m;          /* Hour and minutes */
11015  int tz;            /* Timezone offset in minutes */
11016  double s;          /* Seconds */
11017  char validYMD;     /* True (1) if Y,M,D are valid */
11018  char validHMS;     /* True (1) if h,m,s are valid */
11019  char validJD;      /* True (1) if iJD is valid */
11020  char validTZ;      /* True (1) if tz is valid */
11021};
11022
11023
11024/*
11025** Convert zDate into one or more integers.  Additional arguments
11026** come in groups of 5 as follows:
11027**
11028**       N       number of digits in the integer
11029**       min     minimum allowed value of the integer
11030**       max     maximum allowed value of the integer
11031**       nextC   first character after the integer
11032**       pVal    where to write the integers value.
11033**
11034** Conversions continue until one with nextC==0 is encountered.
11035** The function returns the number of successful conversions.
11036*/
11037static int getDigits(const char *zDate, ...){
11038  va_list ap;
11039  int val;
11040  int N;
11041  int min;
11042  int max;
11043  int nextC;
11044  int *pVal;
11045  int cnt = 0;
11046  va_start(ap, zDate);
11047  do{
11048    N = va_arg(ap, int);
11049    min = va_arg(ap, int);
11050    max = va_arg(ap, int);
11051    nextC = va_arg(ap, int);
11052    pVal = va_arg(ap, int*);
11053    val = 0;
11054    while( N-- ){
11055      if( !sqlite3Isdigit(*zDate) ){
11056        goto end_getDigits;
11057      }
11058      val = val*10 + *zDate - '0';
11059      zDate++;
11060    }
11061    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
11062      goto end_getDigits;
11063    }
11064    *pVal = val;
11065    zDate++;
11066    cnt++;
11067  }while( nextC );
11068end_getDigits:
11069  va_end(ap);
11070  return cnt;
11071}
11072
11073/*
11074** Read text from z[] and convert into a floating point number.  Return
11075** the number of digits converted.
11076*/
11077#define getValue sqlite3AtoF
11078
11079/*
11080** Parse a timezone extension on the end of a date-time.
11081** The extension is of the form:
11082**
11083**        (+/-)HH:MM
11084**
11085** Or the "zulu" notation:
11086**
11087**        Z
11088**
11089** If the parse is successful, write the number of minutes
11090** of change in p->tz and return 0.  If a parser error occurs,
11091** return non-zero.
11092**
11093** A missing specifier is not considered an error.
11094*/
11095static int parseTimezone(const char *zDate, DateTime *p){
11096  int sgn = 0;
11097  int nHr, nMn;
11098  int c;
11099  while( sqlite3Isspace(*zDate) ){ zDate++; }
11100  p->tz = 0;
11101  c = *zDate;
11102  if( c=='-' ){
11103    sgn = -1;
11104  }else if( c=='+' ){
11105    sgn = +1;
11106  }else if( c=='Z' || c=='z' ){
11107    zDate++;
11108    goto zulu_time;
11109  }else{
11110    return c!=0;
11111  }
11112  zDate++;
11113  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
11114    return 1;
11115  }
11116  zDate += 5;
11117  p->tz = sgn*(nMn + nHr*60);
11118zulu_time:
11119  while( sqlite3Isspace(*zDate) ){ zDate++; }
11120  return *zDate!=0;
11121}
11122
11123/*
11124** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
11125** The HH, MM, and SS must each be exactly 2 digits.  The
11126** fractional seconds FFFF can be one or more digits.
11127**
11128** Return 1 if there is a parsing error and 0 on success.
11129*/
11130static int parseHhMmSs(const char *zDate, DateTime *p){
11131  int h, m, s;
11132  double ms = 0.0;
11133  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
11134    return 1;
11135  }
11136  zDate += 5;
11137  if( *zDate==':' ){
11138    zDate++;
11139    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
11140      return 1;
11141    }
11142    zDate += 2;
11143    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
11144      double rScale = 1.0;
11145      zDate++;
11146      while( sqlite3Isdigit(*zDate) ){
11147        ms = ms*10.0 + *zDate - '0';
11148        rScale *= 10.0;
11149        zDate++;
11150      }
11151      ms /= rScale;
11152    }
11153  }else{
11154    s = 0;
11155  }
11156  p->validJD = 0;
11157  p->validHMS = 1;
11158  p->h = h;
11159  p->m = m;
11160  p->s = s + ms;
11161  if( parseTimezone(zDate, p) ) return 1;
11162  p->validTZ = (p->tz!=0)?1:0;
11163  return 0;
11164}
11165
11166/*
11167** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
11168** that the YYYY-MM-DD is according to the Gregorian calendar.
11169**
11170** Reference:  Meeus page 61
11171*/
11172static void computeJD(DateTime *p){
11173  int Y, M, D, A, B, X1, X2;
11174
11175  if( p->validJD ) return;
11176  if( p->validYMD ){
11177    Y = p->Y;
11178    M = p->M;
11179    D = p->D;
11180  }else{
11181    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
11182    M = 1;
11183    D = 1;
11184  }
11185  if( M<=2 ){
11186    Y--;
11187    M += 12;
11188  }
11189  A = Y/100;
11190  B = 2 - A + (A/4);
11191  X1 = 36525*(Y+4716)/100;
11192  X2 = 306001*(M+1)/10000;
11193  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
11194  p->validJD = 1;
11195  if( p->validHMS ){
11196    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
11197    if( p->validTZ ){
11198      p->iJD -= p->tz*60000;
11199      p->validYMD = 0;
11200      p->validHMS = 0;
11201      p->validTZ = 0;
11202    }
11203  }
11204}
11205
11206/*
11207** Parse dates of the form
11208**
11209**     YYYY-MM-DD HH:MM:SS.FFF
11210**     YYYY-MM-DD HH:MM:SS
11211**     YYYY-MM-DD HH:MM
11212**     YYYY-MM-DD
11213**
11214** Write the result into the DateTime structure and return 0
11215** on success and 1 if the input string is not a well-formed
11216** date.
11217*/
11218static int parseYyyyMmDd(const char *zDate, DateTime *p){
11219  int Y, M, D, neg;
11220
11221  if( zDate[0]=='-' ){
11222    zDate++;
11223    neg = 1;
11224  }else{
11225    neg = 0;
11226  }
11227  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
11228    return 1;
11229  }
11230  zDate += 10;
11231  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
11232  if( parseHhMmSs(zDate, p)==0 ){
11233    /* We got the time */
11234  }else if( *zDate==0 ){
11235    p->validHMS = 0;
11236  }else{
11237    return 1;
11238  }
11239  p->validJD = 0;
11240  p->validYMD = 1;
11241  p->Y = neg ? -Y : Y;
11242  p->M = M;
11243  p->D = D;
11244  if( p->validTZ ){
11245    computeJD(p);
11246  }
11247  return 0;
11248}
11249
11250/*
11251** Set the time to the current time reported by the VFS
11252*/
11253static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
11254  double r;
11255  sqlite3 *db = sqlite3_context_db_handle(context);
11256  sqlite3OsCurrentTime(db->pVfs, &r);
11257  p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11258  p->validJD = 1;
11259}
11260
11261/*
11262** Attempt to parse the given string into a Julian Day Number.  Return
11263** the number of errors.
11264**
11265** The following are acceptable forms for the input string:
11266**
11267**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
11268**      DDDD.DD
11269**      now
11270**
11271** In the first form, the +/-HH:MM is always optional.  The fractional
11272** seconds extension (the ".FFF") is optional.  The seconds portion
11273** (":SS.FFF") is option.  The year and date can be omitted as long
11274** as there is a time string.  The time string can be omitted as long
11275** as there is a year and date.
11276*/
11277static int parseDateOrTime(
11278  sqlite3_context *context,
11279  const char *zDate,
11280  DateTime *p
11281){
11282  int isRealNum;    /* Return from sqlite3IsNumber().  Not used */
11283  if( parseYyyyMmDd(zDate,p)==0 ){
11284    return 0;
11285  }else if( parseHhMmSs(zDate, p)==0 ){
11286    return 0;
11287  }else if( sqlite3StrICmp(zDate,"now")==0){
11288    setDateTimeToCurrent(context, p);
11289    return 0;
11290  }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
11291    double r;
11292    getValue(zDate, &r);
11293    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11294    p->validJD = 1;
11295    return 0;
11296  }
11297  return 1;
11298}
11299
11300/*
11301** Compute the Year, Month, and Day from the julian day number.
11302*/
11303static void computeYMD(DateTime *p){
11304  int Z, A, B, C, D, E, X1;
11305  if( p->validYMD ) return;
11306  if( !p->validJD ){
11307    p->Y = 2000;
11308    p->M = 1;
11309    p->D = 1;
11310  }else{
11311    Z = (int)((p->iJD + 43200000)/86400000);
11312    A = (int)((Z - 1867216.25)/36524.25);
11313    A = Z + 1 + A - (A/4);
11314    B = A + 1524;
11315    C = (int)((B - 122.1)/365.25);
11316    D = (36525*C)/100;
11317    E = (int)((B-D)/30.6001);
11318    X1 = (int)(30.6001*E);
11319    p->D = B - D - X1;
11320    p->M = E<14 ? E-1 : E-13;
11321    p->Y = p->M>2 ? C - 4716 : C - 4715;
11322  }
11323  p->validYMD = 1;
11324}
11325
11326/*
11327** Compute the Hour, Minute, and Seconds from the julian day number.
11328*/
11329static void computeHMS(DateTime *p){
11330  int s;
11331  if( p->validHMS ) return;
11332  computeJD(p);
11333  s = (int)((p->iJD + 43200000) % 86400000);
11334  p->s = s/1000.0;
11335  s = (int)p->s;
11336  p->s -= s;
11337  p->h = s/3600;
11338  s -= p->h*3600;
11339  p->m = s/60;
11340  p->s += s - p->m*60;
11341  p->validHMS = 1;
11342}
11343
11344/*
11345** Compute both YMD and HMS
11346*/
11347static void computeYMD_HMS(DateTime *p){
11348  computeYMD(p);
11349  computeHMS(p);
11350}
11351
11352/*
11353** Clear the YMD and HMS and the TZ
11354*/
11355static void clearYMD_HMS_TZ(DateTime *p){
11356  p->validYMD = 0;
11357  p->validHMS = 0;
11358  p->validTZ = 0;
11359}
11360
11361#ifndef SQLITE_OMIT_LOCALTIME
11362/*
11363** Compute the difference (in milliseconds)
11364** between localtime and UTC (a.k.a. GMT)
11365** for the time value p where p is in UTC.
11366*/
11367static sqlite3_int64 localtimeOffset(DateTime *p){
11368  DateTime x, y;
11369  time_t t;
11370  x = *p;
11371  computeYMD_HMS(&x);
11372  if( x.Y<1971 || x.Y>=2038 ){
11373    x.Y = 2000;
11374    x.M = 1;
11375    x.D = 1;
11376    x.h = 0;
11377    x.m = 0;
11378    x.s = 0.0;
11379  } else {
11380    int s = (int)(x.s + 0.5);
11381    x.s = s;
11382  }
11383  x.tz = 0;
11384  x.validJD = 0;
11385  computeJD(&x);
11386  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
11387#ifdef HAVE_LOCALTIME_R
11388  {
11389    struct tm sLocal;
11390    localtime_r(&t, &sLocal);
11391    y.Y = sLocal.tm_year + 1900;
11392    y.M = sLocal.tm_mon + 1;
11393    y.D = sLocal.tm_mday;
11394    y.h = sLocal.tm_hour;
11395    y.m = sLocal.tm_min;
11396    y.s = sLocal.tm_sec;
11397  }
11398#elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
11399  {
11400    struct tm sLocal;
11401    localtime_s(&sLocal, &t);
11402    y.Y = sLocal.tm_year + 1900;
11403    y.M = sLocal.tm_mon + 1;
11404    y.D = sLocal.tm_mday;
11405    y.h = sLocal.tm_hour;
11406    y.m = sLocal.tm_min;
11407    y.s = sLocal.tm_sec;
11408  }
11409#else
11410  {
11411    struct tm *pTm;
11412    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11413    pTm = localtime(&t);
11414    y.Y = pTm->tm_year + 1900;
11415    y.M = pTm->tm_mon + 1;
11416    y.D = pTm->tm_mday;
11417    y.h = pTm->tm_hour;
11418    y.m = pTm->tm_min;
11419    y.s = pTm->tm_sec;
11420    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11421  }
11422#endif
11423  y.validYMD = 1;
11424  y.validHMS = 1;
11425  y.validJD = 0;
11426  y.validTZ = 0;
11427  computeJD(&y);
11428  return y.iJD - x.iJD;
11429}
11430#endif /* SQLITE_OMIT_LOCALTIME */
11431
11432/*
11433** Process a modifier to a date-time stamp.  The modifiers are
11434** as follows:
11435**
11436**     NNN days
11437**     NNN hours
11438**     NNN minutes
11439**     NNN.NNNN seconds
11440**     NNN months
11441**     NNN years
11442**     start of month
11443**     start of year
11444**     start of week
11445**     start of day
11446**     weekday N
11447**     unixepoch
11448**     localtime
11449**     utc
11450**
11451** Return 0 on success and 1 if there is any kind of error.
11452*/
11453static int parseModifier(const char *zMod, DateTime *p){
11454  int rc = 1;
11455  int n;
11456  double r;
11457  char *z, zBuf[30];
11458  z = zBuf;
11459  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
11460    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
11461  }
11462  z[n] = 0;
11463  switch( z[0] ){
11464#ifndef SQLITE_OMIT_LOCALTIME
11465    case 'l': {
11466      /*    localtime
11467      **
11468      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
11469      ** show local time.
11470      */
11471      if( strcmp(z, "localtime")==0 ){
11472        computeJD(p);
11473        p->iJD += localtimeOffset(p);
11474        clearYMD_HMS_TZ(p);
11475        rc = 0;
11476      }
11477      break;
11478    }
11479#endif
11480    case 'u': {
11481      /*
11482      **    unixepoch
11483      **
11484      ** Treat the current value of p->iJD as the number of
11485      ** seconds since 1970.  Convert to a real julian day number.
11486      */
11487      if( strcmp(z, "unixepoch")==0 && p->validJD ){
11488        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
11489        clearYMD_HMS_TZ(p);
11490        rc = 0;
11491      }
11492#ifndef SQLITE_OMIT_LOCALTIME
11493      else if( strcmp(z, "utc")==0 ){
11494        sqlite3_int64 c1;
11495        computeJD(p);
11496        c1 = localtimeOffset(p);
11497        p->iJD -= c1;
11498        clearYMD_HMS_TZ(p);
11499        p->iJD += c1 - localtimeOffset(p);
11500        rc = 0;
11501      }
11502#endif
11503      break;
11504    }
11505    case 'w': {
11506      /*
11507      **    weekday N
11508      **
11509      ** Move the date to the same time on the next occurrence of
11510      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
11511      ** date is already on the appropriate weekday, this is a no-op.
11512      */
11513      if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
11514                 && (n=(int)r)==r && n>=0 && r<7 ){
11515        sqlite3_int64 Z;
11516        computeYMD_HMS(p);
11517        p->validTZ = 0;
11518        p->validJD = 0;
11519        computeJD(p);
11520        Z = ((p->iJD + 129600000)/86400000) % 7;
11521        if( Z>n ) Z -= 7;
11522        p->iJD += (n - Z)*86400000;
11523        clearYMD_HMS_TZ(p);
11524        rc = 0;
11525      }
11526      break;
11527    }
11528    case 's': {
11529      /*
11530      **    start of TTTTT
11531      **
11532      ** Move the date backwards to the beginning of the current day,
11533      ** or month or year.
11534      */
11535      if( strncmp(z, "start of ", 9)!=0 ) break;
11536      z += 9;
11537      computeYMD(p);
11538      p->validHMS = 1;
11539      p->h = p->m = 0;
11540      p->s = 0.0;
11541      p->validTZ = 0;
11542      p->validJD = 0;
11543      if( strcmp(z,"month")==0 ){
11544        p->D = 1;
11545        rc = 0;
11546      }else if( strcmp(z,"year")==0 ){
11547        computeYMD(p);
11548        p->M = 1;
11549        p->D = 1;
11550        rc = 0;
11551      }else if( strcmp(z,"day")==0 ){
11552        rc = 0;
11553      }
11554      break;
11555    }
11556    case '+':
11557    case '-':
11558    case '0':
11559    case '1':
11560    case '2':
11561    case '3':
11562    case '4':
11563    case '5':
11564    case '6':
11565    case '7':
11566    case '8':
11567    case '9': {
11568      double rRounder;
11569      n = getValue(z, &r);
11570      assert( n>=1 );
11571      if( z[n]==':' ){
11572        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
11573        ** specified number of hours, minutes, seconds, and fractional seconds
11574        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
11575        ** omitted.
11576        */
11577        const char *z2 = z;
11578        DateTime tx;
11579        sqlite3_int64 day;
11580        if( !sqlite3Isdigit(*z2) ) z2++;
11581        memset(&tx, 0, sizeof(tx));
11582        if( parseHhMmSs(z2, &tx) ) break;
11583        computeJD(&tx);
11584        tx.iJD -= 43200000;
11585        day = tx.iJD/86400000;
11586        tx.iJD -= day*86400000;
11587        if( z[0]=='-' ) tx.iJD = -tx.iJD;
11588        computeJD(p);
11589        clearYMD_HMS_TZ(p);
11590        p->iJD += tx.iJD;
11591        rc = 0;
11592        break;
11593      }
11594      z += n;
11595      while( sqlite3Isspace(*z) ) z++;
11596      n = sqlite3Strlen30(z);
11597      if( n>10 || n<3 ) break;
11598      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
11599      computeJD(p);
11600      rc = 0;
11601      rRounder = r<0 ? -0.5 : +0.5;
11602      if( n==3 && strcmp(z,"day")==0 ){
11603        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
11604      }else if( n==4 && strcmp(z,"hour")==0 ){
11605        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
11606      }else if( n==6 && strcmp(z,"minute")==0 ){
11607        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
11608      }else if( n==6 && strcmp(z,"second")==0 ){
11609        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
11610      }else if( n==5 && strcmp(z,"month")==0 ){
11611        int x, y;
11612        computeYMD_HMS(p);
11613        p->M += (int)r;
11614        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
11615        p->Y += x;
11616        p->M -= x*12;
11617        p->validJD = 0;
11618        computeJD(p);
11619        y = (int)r;
11620        if( y!=r ){
11621          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
11622        }
11623      }else if( n==4 && strcmp(z,"year")==0 ){
11624        int y = (int)r;
11625        computeYMD_HMS(p);
11626        p->Y += y;
11627        p->validJD = 0;
11628        computeJD(p);
11629        if( y!=r ){
11630          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
11631        }
11632      }else{
11633        rc = 1;
11634      }
11635      clearYMD_HMS_TZ(p);
11636      break;
11637    }
11638    default: {
11639      break;
11640    }
11641  }
11642  return rc;
11643}
11644
11645/*
11646** Process time function arguments.  argv[0] is a date-time stamp.
11647** argv[1] and following are modifiers.  Parse them all and write
11648** the resulting time into the DateTime structure p.  Return 0
11649** on success and 1 if there are any errors.
11650**
11651** If there are zero parameters (if even argv[0] is undefined)
11652** then assume a default value of "now" for argv[0].
11653*/
11654static int isDate(
11655  sqlite3_context *context,
11656  int argc,
11657  sqlite3_value **argv,
11658  DateTime *p
11659){
11660  int i;
11661  const unsigned char *z;
11662  int eType;
11663  memset(p, 0, sizeof(*p));
11664  if( argc==0 ){
11665    setDateTimeToCurrent(context, p);
11666  }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
11667                   || eType==SQLITE_INTEGER ){
11668    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
11669    p->validJD = 1;
11670  }else{
11671    z = sqlite3_value_text(argv[0]);
11672    if( !z || parseDateOrTime(context, (char*)z, p) ){
11673      return 1;
11674    }
11675  }
11676  for(i=1; i<argc; i++){
11677    if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
11678      return 1;
11679    }
11680  }
11681  return 0;
11682}
11683
11684
11685/*
11686** The following routines implement the various date and time functions
11687** of SQLite.
11688*/
11689
11690/*
11691**    julianday( TIMESTRING, MOD, MOD, ...)
11692**
11693** Return the julian day number of the date specified in the arguments
11694*/
11695static void juliandayFunc(
11696  sqlite3_context *context,
11697  int argc,
11698  sqlite3_value **argv
11699){
11700  DateTime x;
11701  if( isDate(context, argc, argv, &x)==0 ){
11702    computeJD(&x);
11703    sqlite3_result_double(context, x.iJD/86400000.0);
11704  }
11705}
11706
11707/*
11708**    datetime( TIMESTRING, MOD, MOD, ...)
11709**
11710** Return YYYY-MM-DD HH:MM:SS
11711*/
11712static void datetimeFunc(
11713  sqlite3_context *context,
11714  int argc,
11715  sqlite3_value **argv
11716){
11717  DateTime x;
11718  if( isDate(context, argc, argv, &x)==0 ){
11719    char zBuf[100];
11720    computeYMD_HMS(&x);
11721    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
11722                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
11723    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11724  }
11725}
11726
11727/*
11728**    time( TIMESTRING, MOD, MOD, ...)
11729**
11730** Return HH:MM:SS
11731*/
11732static void timeFunc(
11733  sqlite3_context *context,
11734  int argc,
11735  sqlite3_value **argv
11736){
11737  DateTime x;
11738  if( isDate(context, argc, argv, &x)==0 ){
11739    char zBuf[100];
11740    computeHMS(&x);
11741    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
11742    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11743  }
11744}
11745
11746/*
11747**    date( TIMESTRING, MOD, MOD, ...)
11748**
11749** Return YYYY-MM-DD
11750*/
11751static void dateFunc(
11752  sqlite3_context *context,
11753  int argc,
11754  sqlite3_value **argv
11755){
11756  DateTime x;
11757  if( isDate(context, argc, argv, &x)==0 ){
11758    char zBuf[100];
11759    computeYMD(&x);
11760    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
11761    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11762  }
11763}
11764
11765/*
11766**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
11767**
11768** Return a string described by FORMAT.  Conversions as follows:
11769**
11770**   %d  day of month
11771**   %f  ** fractional seconds  SS.SSS
11772**   %H  hour 00-24
11773**   %j  day of year 000-366
11774**   %J  ** Julian day number
11775**   %m  month 01-12
11776**   %M  minute 00-59
11777**   %s  seconds since 1970-01-01
11778**   %S  seconds 00-59
11779**   %w  day of week 0-6  sunday==0
11780**   %W  week of year 00-53
11781**   %Y  year 0000-9999
11782**   %%  %
11783*/
11784static void strftimeFunc(
11785  sqlite3_context *context,
11786  int argc,
11787  sqlite3_value **argv
11788){
11789  DateTime x;
11790  u64 n;
11791  size_t i,j;
11792  char *z;
11793  sqlite3 *db;
11794  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
11795  char zBuf[100];
11796  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
11797  db = sqlite3_context_db_handle(context);
11798  for(i=0, n=1; zFmt[i]; i++, n++){
11799    if( zFmt[i]=='%' ){
11800      switch( zFmt[i+1] ){
11801        case 'd':
11802        case 'H':
11803        case 'm':
11804        case 'M':
11805        case 'S':
11806        case 'W':
11807          n++;
11808          /* fall thru */
11809        case 'w':
11810        case '%':
11811          break;
11812        case 'f':
11813          n += 8;
11814          break;
11815        case 'j':
11816          n += 3;
11817          break;
11818        case 'Y':
11819          n += 8;
11820          break;
11821        case 's':
11822        case 'J':
11823          n += 50;
11824          break;
11825        default:
11826          return;  /* ERROR.  return a NULL */
11827      }
11828      i++;
11829    }
11830  }
11831  testcase( n==sizeof(zBuf)-1 );
11832  testcase( n==sizeof(zBuf) );
11833  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
11834  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
11835  if( n<sizeof(zBuf) ){
11836    z = zBuf;
11837  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
11838    sqlite3_result_error_toobig(context);
11839    return;
11840  }else{
11841    z = sqlite3DbMallocRaw(db, (int)n);
11842    if( z==0 ){
11843      sqlite3_result_error_nomem(context);
11844      return;
11845    }
11846  }
11847  computeJD(&x);
11848  computeYMD_HMS(&x);
11849  for(i=j=0; zFmt[i]; i++){
11850    if( zFmt[i]!='%' ){
11851      z[j++] = zFmt[i];
11852    }else{
11853      i++;
11854      switch( zFmt[i] ){
11855        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
11856        case 'f': {
11857          double s = x.s;
11858          if( s>59.999 ) s = 59.999;
11859          sqlite3_snprintf(7, &z[j],"%06.3f", s);
11860          j += sqlite3Strlen30(&z[j]);
11861          break;
11862        }
11863        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
11864        case 'W': /* Fall thru */
11865        case 'j': {
11866          int nDay;             /* Number of days since 1st day of year */
11867          DateTime y = x;
11868          y.validJD = 0;
11869          y.M = 1;
11870          y.D = 1;
11871          computeJD(&y);
11872          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
11873          if( zFmt[i]=='W' ){
11874            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
11875            wd = (int)(((x.iJD+43200000)/86400000)%7);
11876            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
11877            j += 2;
11878          }else{
11879            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
11880            j += 3;
11881          }
11882          break;
11883        }
11884        case 'J': {
11885          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
11886          j+=sqlite3Strlen30(&z[j]);
11887          break;
11888        }
11889        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
11890        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
11891        case 's': {
11892          sqlite3_snprintf(30,&z[j],"%lld",
11893                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
11894          j += sqlite3Strlen30(&z[j]);
11895          break;
11896        }
11897        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
11898        case 'w': {
11899          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
11900          break;
11901        }
11902        case 'Y': {
11903          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
11904          break;
11905        }
11906        default:   z[j++] = '%'; break;
11907      }
11908    }
11909  }
11910  z[j] = 0;
11911  sqlite3_result_text(context, z, -1,
11912                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
11913}
11914
11915/*
11916** current_time()
11917**
11918** This function returns the same value as time('now').
11919*/
11920static void ctimeFunc(
11921  sqlite3_context *context,
11922  int NotUsed,
11923  sqlite3_value **NotUsed2
11924){
11925  UNUSED_PARAMETER2(NotUsed, NotUsed2);
11926  timeFunc(context, 0, 0);
11927}
11928
11929/*
11930** current_date()
11931**
11932** This function returns the same value as date('now').
11933*/
11934static void cdateFunc(
11935  sqlite3_context *context,
11936  int NotUsed,
11937  sqlite3_value **NotUsed2
11938){
11939  UNUSED_PARAMETER2(NotUsed, NotUsed2);
11940  dateFunc(context, 0, 0);
11941}
11942
11943/*
11944** current_timestamp()
11945**
11946** This function returns the same value as datetime('now').
11947*/
11948static void ctimestampFunc(
11949  sqlite3_context *context,
11950  int NotUsed,
11951  sqlite3_value **NotUsed2
11952){
11953  UNUSED_PARAMETER2(NotUsed, NotUsed2);
11954  datetimeFunc(context, 0, 0);
11955}
11956#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
11957
11958#ifdef SQLITE_OMIT_DATETIME_FUNCS
11959/*
11960** If the library is compiled to omit the full-scale date and time
11961** handling (to get a smaller binary), the following minimal version
11962** of the functions current_time(), current_date() and current_timestamp()
11963** are included instead. This is to support column declarations that
11964** include "DEFAULT CURRENT_TIME" etc.
11965**
11966** This function uses the C-library functions time(), gmtime()
11967** and strftime(). The format string to pass to strftime() is supplied
11968** as the user-data for the function.
11969*/
11970static void currentTimeFunc(
11971  sqlite3_context *context,
11972  int argc,
11973  sqlite3_value **argv
11974){
11975  time_t t;
11976  char *zFormat = (char *)sqlite3_user_data(context);
11977  sqlite3 *db;
11978  double rT;
11979  char zBuf[20];
11980
11981  UNUSED_PARAMETER(argc);
11982  UNUSED_PARAMETER(argv);
11983
11984  db = sqlite3_context_db_handle(context);
11985  sqlite3OsCurrentTime(db->pVfs, &rT);
11986#ifndef SQLITE_OMIT_FLOATING_POINT
11987  t = 86400.0*(rT - 2440587.5) + 0.5;
11988#else
11989  /* without floating point support, rT will have
11990  ** already lost fractional day precision.
11991  */
11992  t = 86400 * (rT - 2440587) - 43200;
11993#endif
11994#ifdef HAVE_GMTIME_R
11995  {
11996    struct tm sNow;
11997    gmtime_r(&t, &sNow);
11998    strftime(zBuf, 20, zFormat, &sNow);
11999  }
12000#else
12001  {
12002    struct tm *pTm;
12003    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12004    pTm = gmtime(&t);
12005    strftime(zBuf, 20, zFormat, pTm);
12006    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12007  }
12008#endif
12009
12010  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12011}
12012#endif
12013
12014/*
12015** This function registered all of the above C functions as SQL
12016** functions.  This should be the only routine in this file with
12017** external linkage.
12018*/
12019SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
12020  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
12021#ifndef SQLITE_OMIT_DATETIME_FUNCS
12022    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
12023    FUNCTION(date,             -1, 0, 0, dateFunc      ),
12024    FUNCTION(time,             -1, 0, 0, timeFunc      ),
12025    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
12026    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
12027    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
12028    FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
12029    FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
12030#else
12031    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
12032    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d",          0, currentTimeFunc),
12033    STR_FUNCTION(current_date,      0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
12034#endif
12035  };
12036  int i;
12037  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
12038  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
12039
12040  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
12041    sqlite3FuncDefInsert(pHash, &aFunc[i]);
12042  }
12043}
12044
12045/************** End of date.c ************************************************/
12046/************** Begin file os.c **********************************************/
12047/*
12048** 2005 November 29
12049**
12050** The author disclaims copyright to this source code.  In place of
12051** a legal notice, here is a blessing:
12052**
12053**    May you do good and not evil.
12054**    May you find forgiveness for yourself and forgive others.
12055**    May you share freely, never taking more than you give.
12056**
12057******************************************************************************
12058**
12059** This file contains OS interface code that is common to all
12060** architectures.
12061*/
12062#define _SQLITE_OS_C_ 1
12063#undef _SQLITE_OS_C_
12064
12065/*
12066** The default SQLite sqlite3_vfs implementations do not allocate
12067** memory (actually, os_unix.c allocates a small amount of memory
12068** from within OsOpen()), but some third-party implementations may.
12069** So we test the effects of a malloc() failing and the sqlite3OsXXX()
12070** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
12071**
12072** The following functions are instrumented for malloc() failure
12073** testing:
12074**
12075**     sqlite3OsOpen()
12076**     sqlite3OsRead()
12077**     sqlite3OsWrite()
12078**     sqlite3OsSync()
12079**     sqlite3OsLock()
12080**
12081*/
12082#if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0)
12083  #define DO_OS_MALLOC_TEST(x) if (!x || !sqlite3IsMemJournal(x)) {     \
12084    void *pTstAlloc = sqlite3Malloc(10);                             \
12085    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
12086    sqlite3_free(pTstAlloc);                                         \
12087  }
12088#else
12089  #define DO_OS_MALLOC_TEST(x)
12090#endif
12091
12092/*
12093** The following routines are convenience wrappers around methods
12094** of the sqlite3_file object.  This is mostly just syntactic sugar. All
12095** of this would be completely automatic if SQLite were coded using
12096** C++ instead of plain old C.
12097*/
12098SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
12099  int rc = SQLITE_OK;
12100  if( pId->pMethods ){
12101    rc = pId->pMethods->xClose(pId);
12102    pId->pMethods = 0;
12103  }
12104  return rc;
12105}
12106SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
12107  DO_OS_MALLOC_TEST(id);
12108  return id->pMethods->xRead(id, pBuf, amt, offset);
12109}
12110SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
12111  DO_OS_MALLOC_TEST(id);
12112  return id->pMethods->xWrite(id, pBuf, amt, offset);
12113}
12114SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
12115  return id->pMethods->xTruncate(id, size);
12116}
12117SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
12118  DO_OS_MALLOC_TEST(id);
12119  return id->pMethods->xSync(id, flags);
12120}
12121SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
12122  DO_OS_MALLOC_TEST(id);
12123  return id->pMethods->xFileSize(id, pSize);
12124}
12125SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
12126  DO_OS_MALLOC_TEST(id);
12127  return id->pMethods->xLock(id, lockType);
12128}
12129SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
12130  return id->pMethods->xUnlock(id, lockType);
12131}
12132SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
12133  DO_OS_MALLOC_TEST(id);
12134  return id->pMethods->xCheckReservedLock(id, pResOut);
12135}
12136SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
12137  return id->pMethods->xFileControl(id, op, pArg);
12138}
12139SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
12140  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
12141  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
12142}
12143SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
12144  return id->pMethods->xDeviceCharacteristics(id);
12145}
12146
12147/*
12148** The next group of routines are convenience wrappers around the
12149** VFS methods.
12150*/
12151SQLITE_PRIVATE int sqlite3OsOpen(
12152  sqlite3_vfs *pVfs,
12153  const char *zPath,
12154  sqlite3_file *pFile,
12155  int flags,
12156  int *pFlagsOut
12157){
12158  int rc;
12159  DO_OS_MALLOC_TEST(0);
12160  /* 0x7f1f is a mask of SQLITE_OPEN_ flags that are valid to be passed
12161  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
12162  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
12163  ** reaching the VFS. */
12164  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x7f1f, pFlagsOut);
12165  assert( rc==SQLITE_OK || pFile->pMethods==0 );
12166  return rc;
12167}
12168SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
12169  return pVfs->xDelete(pVfs, zPath, dirSync);
12170}
12171SQLITE_PRIVATE int sqlite3OsAccess(
12172  sqlite3_vfs *pVfs,
12173  const char *zPath,
12174  int flags,
12175  int *pResOut
12176){
12177  DO_OS_MALLOC_TEST(0);
12178  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
12179}
12180SQLITE_PRIVATE int sqlite3OsFullPathname(
12181  sqlite3_vfs *pVfs,
12182  const char *zPath,
12183  int nPathOut,
12184  char *zPathOut
12185){
12186  zPathOut[0] = 0;
12187  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
12188}
12189#ifndef SQLITE_OMIT_LOAD_EXTENSION
12190SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
12191  return pVfs->xDlOpen(pVfs, zPath);
12192}
12193SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12194  pVfs->xDlError(pVfs, nByte, zBufOut);
12195}
12196SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
12197  return pVfs->xDlSym(pVfs, pHdle, zSym);
12198}
12199SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
12200  pVfs->xDlClose(pVfs, pHandle);
12201}
12202#endif /* SQLITE_OMIT_LOAD_EXTENSION */
12203SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12204  return pVfs->xRandomness(pVfs, nByte, zBufOut);
12205}
12206SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
12207  return pVfs->xSleep(pVfs, nMicro);
12208}
12209SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
12210  return pVfs->xCurrentTime(pVfs, pTimeOut);
12211}
12212
12213SQLITE_PRIVATE int sqlite3OsOpenMalloc(
12214  sqlite3_vfs *pVfs,
12215  const char *zFile,
12216  sqlite3_file **ppFile,
12217  int flags,
12218  int *pOutFlags
12219){
12220  int rc = SQLITE_NOMEM;
12221  sqlite3_file *pFile;
12222  pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
12223  if( pFile ){
12224    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
12225    if( rc!=SQLITE_OK ){
12226      sqlite3_free(pFile);
12227    }else{
12228      *ppFile = pFile;
12229    }
12230  }
12231  return rc;
12232}
12233SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
12234  int rc = SQLITE_OK;
12235  assert( pFile );
12236  rc = sqlite3OsClose(pFile);
12237  sqlite3_free(pFile);
12238  return rc;
12239}
12240
12241/*
12242** This function is a wrapper around the OS specific implementation of
12243** sqlite3_os_init(). The purpose of the wrapper is to provide the
12244** ability to simulate a malloc failure, so that the handling of an
12245** error in sqlite3_os_init() by the upper layers can be tested.
12246*/
12247SQLITE_PRIVATE int sqlite3OsInit(void){
12248  void *p = sqlite3_malloc(10);
12249  if( p==0 ) return SQLITE_NOMEM;
12250  sqlite3_free(p);
12251  return sqlite3_os_init();
12252}
12253
12254/*
12255** The list of all registered VFS implementations.
12256*/
12257static sqlite3_vfs * SQLITE_WSD vfsList = 0;
12258#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
12259
12260/*
12261** Locate a VFS by name.  If no name is given, simply return the
12262** first VFS on the list.
12263*/
12264SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
12265  sqlite3_vfs *pVfs = 0;
12266#if SQLITE_THREADSAFE
12267  sqlite3_mutex *mutex;
12268#endif
12269#ifndef SQLITE_OMIT_AUTOINIT
12270  int rc = sqlite3_initialize();
12271  if( rc ) return 0;
12272#endif
12273#if SQLITE_THREADSAFE
12274  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12275#endif
12276  sqlite3_mutex_enter(mutex);
12277  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
12278    if( zVfs==0 ) break;
12279    if( strcmp(zVfs, pVfs->zName)==0 ) break;
12280  }
12281  sqlite3_mutex_leave(mutex);
12282  return pVfs;
12283}
12284
12285/*
12286** Unlink a VFS from the linked list
12287*/
12288static void vfsUnlink(sqlite3_vfs *pVfs){
12289  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
12290  if( pVfs==0 ){
12291    /* No-op */
12292  }else if( vfsList==pVfs ){
12293    vfsList = pVfs->pNext;
12294  }else if( vfsList ){
12295    sqlite3_vfs *p = vfsList;
12296    while( p->pNext && p->pNext!=pVfs ){
12297      p = p->pNext;
12298    }
12299    if( p->pNext==pVfs ){
12300      p->pNext = pVfs->pNext;
12301    }
12302  }
12303}
12304
12305/*
12306** Register a VFS with the system.  It is harmless to register the same
12307** VFS multiple times.  The new VFS becomes the default if makeDflt is
12308** true.
12309*/
12310SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
12311  sqlite3_mutex *mutex = 0;
12312#ifndef SQLITE_OMIT_AUTOINIT
12313  int rc = sqlite3_initialize();
12314  if( rc ) return rc;
12315#endif
12316  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12317  sqlite3_mutex_enter(mutex);
12318  vfsUnlink(pVfs);
12319  if( makeDflt || vfsList==0 ){
12320    pVfs->pNext = vfsList;
12321    vfsList = pVfs;
12322  }else{
12323    pVfs->pNext = vfsList->pNext;
12324    vfsList->pNext = pVfs;
12325  }
12326  assert(vfsList);
12327  sqlite3_mutex_leave(mutex);
12328  return SQLITE_OK;
12329}
12330
12331/*
12332** Unregister a VFS so that it is no longer accessible.
12333*/
12334SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
12335#if SQLITE_THREADSAFE
12336  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12337#endif
12338  sqlite3_mutex_enter(mutex);
12339  vfsUnlink(pVfs);
12340  sqlite3_mutex_leave(mutex);
12341  return SQLITE_OK;
12342}
12343
12344/************** End of os.c **************************************************/
12345/************** Begin file fault.c *******************************************/
12346/*
12347** 2008 Jan 22
12348**
12349** The author disclaims copyright to this source code.  In place of
12350** a legal notice, here is a blessing:
12351**
12352**    May you do good and not evil.
12353**    May you find forgiveness for yourself and forgive others.
12354**    May you share freely, never taking more than you give.
12355**
12356*************************************************************************
12357**
12358** This file contains code to support the concept of "benign"
12359** malloc failures (when the xMalloc() or xRealloc() method of the
12360** sqlite3_mem_methods structure fails to allocate a block of memory
12361** and returns 0).
12362**
12363** Most malloc failures are non-benign. After they occur, SQLite
12364** abandons the current operation and returns an error code (usually
12365** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
12366** fatal. For example, if a malloc fails while resizing a hash table, this
12367** is completely recoverable simply by not carrying out the resize. The
12368** hash table will continue to function normally.  So a malloc failure
12369** during a hash table resize is a benign fault.
12370*/
12371
12372
12373#ifndef SQLITE_OMIT_BUILTIN_TEST
12374
12375/*
12376** Global variables.
12377*/
12378typedef struct BenignMallocHooks BenignMallocHooks;
12379static SQLITE_WSD struct BenignMallocHooks {
12380  void (*xBenignBegin)(void);
12381  void (*xBenignEnd)(void);
12382} sqlite3Hooks = { 0, 0 };
12383
12384/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
12385** structure.  If writable static data is unsupported on the target,
12386** we have to locate the state vector at run-time.  In the more common
12387** case where writable static data is supported, wsdHooks can refer directly
12388** to the "sqlite3Hooks" state vector declared above.
12389*/
12390#ifdef SQLITE_OMIT_WSD
12391# define wsdHooksInit \
12392  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
12393# define wsdHooks x[0]
12394#else
12395# define wsdHooksInit
12396# define wsdHooks sqlite3Hooks
12397#endif
12398
12399
12400/*
12401** Register hooks to call when sqlite3BeginBenignMalloc() and
12402** sqlite3EndBenignMalloc() are called, respectively.
12403*/
12404SQLITE_PRIVATE void sqlite3BenignMallocHooks(
12405  void (*xBenignBegin)(void),
12406  void (*xBenignEnd)(void)
12407){
12408  wsdHooksInit;
12409  wsdHooks.xBenignBegin = xBenignBegin;
12410  wsdHooks.xBenignEnd = xBenignEnd;
12411}
12412
12413/*
12414** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
12415** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
12416** indicates that subsequent malloc failures are non-benign.
12417*/
12418SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
12419  wsdHooksInit;
12420  if( wsdHooks.xBenignBegin ){
12421    wsdHooks.xBenignBegin();
12422  }
12423}
12424SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
12425  wsdHooksInit;
12426  if( wsdHooks.xBenignEnd ){
12427    wsdHooks.xBenignEnd();
12428  }
12429}
12430
12431#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
12432
12433/************** End of fault.c ***********************************************/
12434/************** Begin file mem0.c ********************************************/
12435/*
12436** 2008 October 28
12437**
12438** The author disclaims copyright to this source code.  In place of
12439** a legal notice, here is a blessing:
12440**
12441**    May you do good and not evil.
12442**    May you find forgiveness for yourself and forgive others.
12443**    May you share freely, never taking more than you give.
12444**
12445*************************************************************************
12446**
12447** This file contains a no-op memory allocation drivers for use when
12448** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
12449** here always fail.  SQLite will not operate with these drivers.  These
12450** are merely placeholders.  Real drivers must be substituted using
12451** sqlite3_config() before SQLite will operate.
12452*/
12453
12454/*
12455** This version of the memory allocator is the default.  It is
12456** used when no other memory allocator is specified using compile-time
12457** macros.
12458*/
12459#ifdef SQLITE_ZERO_MALLOC
12460
12461/*
12462** No-op versions of all memory allocation routines
12463*/
12464static void *sqlite3MemMalloc(int nByte){ return 0; }
12465static void sqlite3MemFree(void *pPrior){ return; }
12466static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
12467static int sqlite3MemSize(void *pPrior){ return 0; }
12468static int sqlite3MemRoundup(int n){ return n; }
12469static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
12470static void sqlite3MemShutdown(void *NotUsed){ return; }
12471
12472/*
12473** This routine is the only routine in this file with external linkage.
12474**
12475** Populate the low-level memory allocation function pointers in
12476** sqlite3GlobalConfig.m with pointers to the routines in this file.
12477*/
12478SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12479  static const sqlite3_mem_methods defaultMethods = {
12480     sqlite3MemMalloc,
12481     sqlite3MemFree,
12482     sqlite3MemRealloc,
12483     sqlite3MemSize,
12484     sqlite3MemRoundup,
12485     sqlite3MemInit,
12486     sqlite3MemShutdown,
12487     0
12488  };
12489  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
12490}
12491
12492#endif /* SQLITE_ZERO_MALLOC */
12493
12494/************** End of mem0.c ************************************************/
12495/************** Begin file mem1.c ********************************************/
12496/*
12497** 2007 August 14
12498**
12499** The author disclaims copyright to this source code.  In place of
12500** a legal notice, here is a blessing:
12501**
12502**    May you do good and not evil.
12503**    May you find forgiveness for yourself and forgive others.
12504**    May you share freely, never taking more than you give.
12505**
12506*************************************************************************
12507**
12508** This file contains low-level memory allocation drivers for when
12509** SQLite will use the standard C-library malloc/realloc/free interface
12510** to obtain the memory it needs.
12511**
12512** This file contains implementations of the low-level memory allocation
12513** routines specified in the sqlite3_mem_methods object.
12514*/
12515
12516/*
12517** This version of the memory allocator is the default.  It is
12518** used when no other memory allocator is specified using compile-time
12519** macros.
12520*/
12521#ifdef SQLITE_SYSTEM_MALLOC
12522
12523/*
12524** Like malloc(), but remember the size of the allocation
12525** so that we can find it later using sqlite3MemSize().
12526**
12527** For this low-level routine, we are guaranteed that nByte>0 because
12528** cases of nByte<=0 will be intercepted and dealt with by higher level
12529** routines.
12530*/
12531static void *sqlite3MemMalloc(int nByte){
12532  sqlite3_int64 *p;
12533  assert( nByte>0 );
12534  nByte = ROUND8(nByte);
12535  p = malloc( nByte+8 );
12536  if( p ){
12537    p[0] = nByte;
12538    p++;
12539  }else{
12540    testcase( sqlite3GlobalConfig.xLog!=0 );
12541    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
12542  }
12543  return (void *)p;
12544}
12545
12546/*
12547** Like free() but works for allocations obtained from sqlite3MemMalloc()
12548** or sqlite3MemRealloc().
12549**
12550** For this low-level routine, we already know that pPrior!=0 since
12551** cases where pPrior==0 will have been intecepted and dealt with
12552** by higher-level routines.
12553*/
12554static void sqlite3MemFree(void *pPrior){
12555  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12556  assert( pPrior!=0 );
12557  p--;
12558  free(p);
12559}
12560
12561/*
12562** Report the allocated size of a prior return from xMalloc()
12563** or xRealloc().
12564*/
12565static int sqlite3MemSize(void *pPrior){
12566  sqlite3_int64 *p;
12567  if( pPrior==0 ) return 0;
12568  p = (sqlite3_int64*)pPrior;
12569  p--;
12570  return (int)p[0];
12571}
12572
12573/*
12574** Like realloc().  Resize an allocation previously obtained from
12575** sqlite3MemMalloc().
12576**
12577** For this low-level interface, we know that pPrior!=0.  Cases where
12578** pPrior==0 while have been intercepted by higher-level routine and
12579** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
12580** cases where nByte<=0 will have been intercepted by higher-level
12581** routines and redirected to xFree.
12582*/
12583static void *sqlite3MemRealloc(void *pPrior, int nByte){
12584  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12585  assert( pPrior!=0 && nByte>0 );
12586  nByte = ROUND8(nByte);
12587  p = (sqlite3_int64*)pPrior;
12588  p--;
12589  p = realloc(p, nByte+8 );
12590  if( p ){
12591    p[0] = nByte;
12592    p++;
12593  }else{
12594    testcase( sqlite3GlobalConfig.xLog!=0 );
12595    sqlite3_log(SQLITE_NOMEM,
12596      "failed memory resize %u to %u bytes",
12597      sqlite3MemSize(pPrior), nByte);
12598  }
12599  return (void*)p;
12600}
12601
12602/*
12603** Round up a request size to the next valid allocation size.
12604*/
12605static int sqlite3MemRoundup(int n){
12606  return ROUND8(n);
12607}
12608
12609/*
12610** Initialize this module.
12611*/
12612static int sqlite3MemInit(void *NotUsed){
12613  UNUSED_PARAMETER(NotUsed);
12614  return SQLITE_OK;
12615}
12616
12617/*
12618** Deinitialize this module.
12619*/
12620static void sqlite3MemShutdown(void *NotUsed){
12621  UNUSED_PARAMETER(NotUsed);
12622  return;
12623}
12624
12625/*
12626** This routine is the only routine in this file with external linkage.
12627**
12628** Populate the low-level memory allocation function pointers in
12629** sqlite3GlobalConfig.m with pointers to the routines in this file.
12630*/
12631SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12632  static const sqlite3_mem_methods defaultMethods = {
12633     sqlite3MemMalloc,
12634     sqlite3MemFree,
12635     sqlite3MemRealloc,
12636     sqlite3MemSize,
12637     sqlite3MemRoundup,
12638     sqlite3MemInit,
12639     sqlite3MemShutdown,
12640     0
12641  };
12642  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
12643}
12644
12645#endif /* SQLITE_SYSTEM_MALLOC */
12646
12647/************** End of mem1.c ************************************************/
12648/************** Begin file mem2.c ********************************************/
12649/*
12650** 2007 August 15
12651**
12652** The author disclaims copyright to this source code.  In place of
12653** a legal notice, here is a blessing:
12654**
12655**    May you do good and not evil.
12656**    May you find forgiveness for yourself and forgive others.
12657**    May you share freely, never taking more than you give.
12658**
12659*************************************************************************
12660**
12661** This file contains low-level memory allocation drivers for when
12662** SQLite will use the standard C-library malloc/realloc/free interface
12663** to obtain the memory it needs while adding lots of additional debugging
12664** information to each allocation in order to help detect and fix memory
12665** leaks and memory usage errors.
12666**
12667** This file contains implementations of the low-level memory allocation
12668** routines specified in the sqlite3_mem_methods object.
12669*/
12670
12671/*
12672** This version of the memory allocator is used only if the
12673** SQLITE_MEMDEBUG macro is defined
12674*/
12675#ifdef SQLITE_MEMDEBUG
12676
12677/*
12678** The backtrace functionality is only available with GLIBC
12679*/
12680#ifdef __GLIBC__
12681  extern int backtrace(void**,int);
12682  extern void backtrace_symbols_fd(void*const*,int,int);
12683#else
12684# define backtrace(A,B) 1
12685# define backtrace_symbols_fd(A,B,C)
12686#endif
12687
12688/*
12689** Each memory allocation looks like this:
12690**
12691**  ------------------------------------------------------------------------
12692**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
12693**  ------------------------------------------------------------------------
12694**
12695** The application code sees only a pointer to the allocation.  We have
12696** to back up from the allocation pointer to find the MemBlockHdr.  The
12697** MemBlockHdr tells us the size of the allocation and the number of
12698** backtrace pointers.  There is also a guard word at the end of the
12699** MemBlockHdr.
12700*/
12701struct MemBlockHdr {
12702  i64 iSize;                          /* Size of this allocation */
12703  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
12704  char nBacktrace;                    /* Number of backtraces on this alloc */
12705  char nBacktraceSlots;               /* Available backtrace slots */
12706  short nTitle;                       /* Bytes of title; includes '\0' */
12707  int iForeGuard;                     /* Guard word for sanity */
12708};
12709
12710/*
12711** Guard words
12712*/
12713#define FOREGUARD 0x80F5E153
12714#define REARGUARD 0xE4676B53
12715
12716/*
12717** Number of malloc size increments to track.
12718*/
12719#define NCSIZE  1000
12720
12721/*
12722** All of the static variables used by this module are collected
12723** into a single structure named "mem".  This is to keep the
12724** static variables organized and to reduce namespace pollution
12725** when this module is combined with other in the amalgamation.
12726*/
12727static struct {
12728
12729  /*
12730  ** Mutex to control access to the memory allocation subsystem.
12731  */
12732  sqlite3_mutex *mutex;
12733
12734  /*
12735  ** Head and tail of a linked list of all outstanding allocations
12736  */
12737  struct MemBlockHdr *pFirst;
12738  struct MemBlockHdr *pLast;
12739
12740  /*
12741  ** The number of levels of backtrace to save in new allocations.
12742  */
12743  int nBacktrace;
12744  void (*xBacktrace)(int, int, void **);
12745
12746  /*
12747  ** Title text to insert in front of each block
12748  */
12749  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
12750  char zTitle[100];  /* The title text */
12751
12752  /*
12753  ** sqlite3MallocDisallow() increments the following counter.
12754  ** sqlite3MallocAllow() decrements it.
12755  */
12756  int disallow; /* Do not allow memory allocation */
12757
12758  /*
12759  ** Gather statistics on the sizes of memory allocations.
12760  ** nAlloc[i] is the number of allocation attempts of i*8
12761  ** bytes.  i==NCSIZE is the number of allocation attempts for
12762  ** sizes more than NCSIZE*8 bytes.
12763  */
12764  int nAlloc[NCSIZE];      /* Total number of allocations */
12765  int nCurrent[NCSIZE];    /* Current number of allocations */
12766  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
12767
12768} mem;
12769
12770
12771/*
12772** Adjust memory usage statistics
12773*/
12774static void adjustStats(int iSize, int increment){
12775  int i = ROUND8(iSize)/8;
12776  if( i>NCSIZE-1 ){
12777    i = NCSIZE - 1;
12778  }
12779  if( increment>0 ){
12780    mem.nAlloc[i]++;
12781    mem.nCurrent[i]++;
12782    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
12783      mem.mxCurrent[i] = mem.nCurrent[i];
12784    }
12785  }else{
12786    mem.nCurrent[i]--;
12787    assert( mem.nCurrent[i]>=0 );
12788  }
12789}
12790
12791/*
12792** Given an allocation, find the MemBlockHdr for that allocation.
12793**
12794** This routine checks the guards at either end of the allocation and
12795** if they are incorrect it asserts.
12796*/
12797static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
12798  struct MemBlockHdr *p;
12799  int *pInt;
12800  u8 *pU8;
12801  int nReserve;
12802
12803  p = (struct MemBlockHdr*)pAllocation;
12804  p--;
12805  assert( p->iForeGuard==(int)FOREGUARD );
12806  nReserve = ROUND8(p->iSize);
12807  pInt = (int*)pAllocation;
12808  pU8 = (u8*)pAllocation;
12809  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
12810  /* This checks any of the "extra" bytes allocated due
12811  ** to rounding up to an 8 byte boundary to ensure
12812  ** they haven't been overwritten.
12813  */
12814  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
12815  return p;
12816}
12817
12818/*
12819** Return the number of bytes currently allocated at address p.
12820*/
12821static int sqlite3MemSize(void *p){
12822  struct MemBlockHdr *pHdr;
12823  if( !p ){
12824    return 0;
12825  }
12826  pHdr = sqlite3MemsysGetHeader(p);
12827  return pHdr->iSize;
12828}
12829
12830/*
12831** Initialize the memory allocation subsystem.
12832*/
12833static int sqlite3MemInit(void *NotUsed){
12834  UNUSED_PARAMETER(NotUsed);
12835  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
12836  if( !sqlite3GlobalConfig.bMemstat ){
12837    /* If memory status is enabled, then the malloc.c wrapper will already
12838    ** hold the STATIC_MEM mutex when the routines here are invoked. */
12839    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
12840  }
12841  return SQLITE_OK;
12842}
12843
12844/*
12845** Deinitialize the memory allocation subsystem.
12846*/
12847static void sqlite3MemShutdown(void *NotUsed){
12848  UNUSED_PARAMETER(NotUsed);
12849  mem.mutex = 0;
12850}
12851
12852/*
12853** Round up a request size to the next valid allocation size.
12854*/
12855static int sqlite3MemRoundup(int n){
12856  return ROUND8(n);
12857}
12858
12859/*
12860** Fill a buffer with pseudo-random bytes.  This is used to preset
12861** the content of a new memory allocation to unpredictable values and
12862** to clear the content of a freed allocation to unpredictable values.
12863*/
12864static void randomFill(char *pBuf, int nByte){
12865  unsigned int x, y, r;
12866  x = SQLITE_PTR_TO_INT(pBuf);
12867  y = nByte | 1;
12868  while( nByte >= 4 ){
12869    x = (x>>1) ^ (-(x&1) & 0xd0000001);
12870    y = y*1103515245 + 12345;
12871    r = x ^ y;
12872    *(int*)pBuf = r;
12873    pBuf += 4;
12874    nByte -= 4;
12875  }
12876  while( nByte-- > 0 ){
12877    x = (x>>1) ^ (-(x&1) & 0xd0000001);
12878    y = y*1103515245 + 12345;
12879    r = x ^ y;
12880    *(pBuf++) = r & 0xff;
12881  }
12882}
12883
12884/*
12885** Allocate nByte bytes of memory.
12886*/
12887static void *sqlite3MemMalloc(int nByte){
12888  struct MemBlockHdr *pHdr;
12889  void **pBt;
12890  char *z;
12891  int *pInt;
12892  void *p = 0;
12893  int totalSize;
12894  int nReserve;
12895  sqlite3_mutex_enter(mem.mutex);
12896  assert( mem.disallow==0 );
12897  nReserve = ROUND8(nByte);
12898  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
12899               mem.nBacktrace*sizeof(void*) + mem.nTitle;
12900  p = malloc(totalSize);
12901  if( p ){
12902    z = p;
12903    pBt = (void**)&z[mem.nTitle];
12904    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
12905    pHdr->pNext = 0;
12906    pHdr->pPrev = mem.pLast;
12907    if( mem.pLast ){
12908      mem.pLast->pNext = pHdr;
12909    }else{
12910      mem.pFirst = pHdr;
12911    }
12912    mem.pLast = pHdr;
12913    pHdr->iForeGuard = FOREGUARD;
12914    pHdr->nBacktraceSlots = mem.nBacktrace;
12915    pHdr->nTitle = mem.nTitle;
12916    if( mem.nBacktrace ){
12917      void *aAddr[40];
12918      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
12919      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
12920      assert(pBt[0]);
12921      if( mem.xBacktrace ){
12922        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
12923      }
12924    }else{
12925      pHdr->nBacktrace = 0;
12926    }
12927    if( mem.nTitle ){
12928      memcpy(z, mem.zTitle, mem.nTitle);
12929    }
12930    pHdr->iSize = nByte;
12931    adjustStats(nByte, +1);
12932    pInt = (int*)&pHdr[1];
12933    pInt[nReserve/sizeof(int)] = REARGUARD;
12934    randomFill((char*)pInt, nByte);
12935    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
12936    p = (void*)pInt;
12937  }
12938  sqlite3_mutex_leave(mem.mutex);
12939  return p;
12940}
12941
12942/*
12943** Free memory.
12944*/
12945static void sqlite3MemFree(void *pPrior){
12946  struct MemBlockHdr *pHdr;
12947  void **pBt;
12948  char *z;
12949  assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 );
12950  pHdr = sqlite3MemsysGetHeader(pPrior);
12951  pBt = (void**)pHdr;
12952  pBt -= pHdr->nBacktraceSlots;
12953  sqlite3_mutex_enter(mem.mutex);
12954  if( pHdr->pPrev ){
12955    assert( pHdr->pPrev->pNext==pHdr );
12956    pHdr->pPrev->pNext = pHdr->pNext;
12957  }else{
12958    assert( mem.pFirst==pHdr );
12959    mem.pFirst = pHdr->pNext;
12960  }
12961  if( pHdr->pNext ){
12962    assert( pHdr->pNext->pPrev==pHdr );
12963    pHdr->pNext->pPrev = pHdr->pPrev;
12964  }else{
12965    assert( mem.pLast==pHdr );
12966    mem.pLast = pHdr->pPrev;
12967  }
12968  z = (char*)pBt;
12969  z -= pHdr->nTitle;
12970  adjustStats(pHdr->iSize, -1);
12971  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
12972                pHdr->iSize + sizeof(int) + pHdr->nTitle);
12973  free(z);
12974  sqlite3_mutex_leave(mem.mutex);
12975}
12976
12977/*
12978** Change the size of an existing memory allocation.
12979**
12980** For this debugging implementation, we *always* make a copy of the
12981** allocation into a new place in memory.  In this way, if the
12982** higher level code is using pointer to the old allocation, it is
12983** much more likely to break and we are much more liking to find
12984** the error.
12985*/
12986static void *sqlite3MemRealloc(void *pPrior, int nByte){
12987  struct MemBlockHdr *pOldHdr;
12988  void *pNew;
12989  assert( mem.disallow==0 );
12990  pOldHdr = sqlite3MemsysGetHeader(pPrior);
12991  pNew = sqlite3MemMalloc(nByte);
12992  if( pNew ){
12993    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
12994    if( nByte>pOldHdr->iSize ){
12995      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
12996    }
12997    sqlite3MemFree(pPrior);
12998  }
12999  return pNew;
13000}
13001
13002/*
13003** Populate the low-level memory allocation function pointers in
13004** sqlite3GlobalConfig.m with pointers to the routines in this file.
13005*/
13006SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13007  static const sqlite3_mem_methods defaultMethods = {
13008     sqlite3MemMalloc,
13009     sqlite3MemFree,
13010     sqlite3MemRealloc,
13011     sqlite3MemSize,
13012     sqlite3MemRoundup,
13013     sqlite3MemInit,
13014     sqlite3MemShutdown,
13015     0
13016  };
13017  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13018}
13019
13020/*
13021** Set the number of backtrace levels kept for each allocation.
13022** A value of zero turns off backtracing.  The number is always rounded
13023** up to a multiple of 2.
13024*/
13025SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
13026  if( depth<0 ){ depth = 0; }
13027  if( depth>20 ){ depth = 20; }
13028  depth = (depth+1)&0xfe;
13029  mem.nBacktrace = depth;
13030}
13031
13032SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
13033  mem.xBacktrace = xBacktrace;
13034}
13035
13036/*
13037** Set the title string for subsequent allocations.
13038*/
13039SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
13040  unsigned int n = sqlite3Strlen30(zTitle) + 1;
13041  sqlite3_mutex_enter(mem.mutex);
13042  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
13043  memcpy(mem.zTitle, zTitle, n);
13044  mem.zTitle[n] = 0;
13045  mem.nTitle = ROUND8(n);
13046  sqlite3_mutex_leave(mem.mutex);
13047}
13048
13049SQLITE_PRIVATE void sqlite3MemdebugSync(){
13050  struct MemBlockHdr *pHdr;
13051  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13052    void **pBt = (void**)pHdr;
13053    pBt -= pHdr->nBacktraceSlots;
13054    mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
13055  }
13056}
13057
13058/*
13059** Open the file indicated and write a log of all unfreed memory
13060** allocations into that log.
13061*/
13062SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
13063  FILE *out;
13064  struct MemBlockHdr *pHdr;
13065  void **pBt;
13066  int i;
13067  out = fopen(zFilename, "w");
13068  if( out==0 ){
13069    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13070                    zFilename);
13071    return;
13072  }
13073  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13074    char *z = (char*)pHdr;
13075    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
13076    fprintf(out, "**** %lld bytes at %p from %s ****\n",
13077            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
13078    if( pHdr->nBacktrace ){
13079      fflush(out);
13080      pBt = (void**)pHdr;
13081      pBt -= pHdr->nBacktraceSlots;
13082      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
13083      fprintf(out, "\n");
13084    }
13085  }
13086  fprintf(out, "COUNTS:\n");
13087  for(i=0; i<NCSIZE-1; i++){
13088    if( mem.nAlloc[i] ){
13089      fprintf(out, "   %5d: %10d %10d %10d\n",
13090            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
13091    }
13092  }
13093  if( mem.nAlloc[NCSIZE-1] ){
13094    fprintf(out, "   %5d: %10d %10d %10d\n",
13095             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
13096             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
13097  }
13098  fclose(out);
13099}
13100
13101/*
13102** Return the number of times sqlite3MemMalloc() has been called.
13103*/
13104SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
13105  int i;
13106  int nTotal = 0;
13107  for(i=0; i<NCSIZE; i++){
13108    nTotal += mem.nAlloc[i];
13109  }
13110  return nTotal;
13111}
13112
13113
13114#endif /* SQLITE_MEMDEBUG */
13115
13116/************** End of mem2.c ************************************************/
13117/************** Begin file mem3.c ********************************************/
13118/*
13119** 2007 October 14
13120**
13121** The author disclaims copyright to this source code.  In place of
13122** a legal notice, here is a blessing:
13123**
13124**    May you do good and not evil.
13125**    May you find forgiveness for yourself and forgive others.
13126**    May you share freely, never taking more than you give.
13127**
13128*************************************************************************
13129** This file contains the C functions that implement a memory
13130** allocation subsystem for use by SQLite.
13131**
13132** This version of the memory allocation subsystem omits all
13133** use of malloc(). The SQLite user supplies a block of memory
13134** before calling sqlite3_initialize() from which allocations
13135** are made and returned by the xMalloc() and xRealloc()
13136** implementations. Once sqlite3_initialize() has been called,
13137** the amount of memory available to SQLite is fixed and cannot
13138** be changed.
13139**
13140** This version of the memory allocation subsystem is included
13141** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
13142*/
13143
13144/*
13145** This version of the memory allocator is only built into the library
13146** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
13147** mean that the library will use a memory-pool by default, just that
13148** it is available. The mempool allocator is activated by calling
13149** sqlite3_config().
13150*/
13151#ifdef SQLITE_ENABLE_MEMSYS3
13152
13153/*
13154** Maximum size (in Mem3Blocks) of a "small" chunk.
13155*/
13156#define MX_SMALL 10
13157
13158
13159/*
13160** Number of freelist hash slots
13161*/
13162#define N_HASH  61
13163
13164/*
13165** A memory allocation (also called a "chunk") consists of two or
13166** more blocks where each block is 8 bytes.  The first 8 bytes are
13167** a header that is not returned to the user.
13168**
13169** A chunk is two or more blocks that is either checked out or
13170** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
13171** size of the allocation in blocks if the allocation is free.
13172** The u.hdr.size4x&1 bit is true if the chunk is checked out and
13173** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
13174** is true if the previous chunk is checked out and false if the
13175** previous chunk is free.  The u.hdr.prevSize field is the size of
13176** the previous chunk in blocks if the previous chunk is on the
13177** freelist. If the previous chunk is checked out, then
13178** u.hdr.prevSize can be part of the data for that chunk and should
13179** not be read or written.
13180**
13181** We often identify a chunk by its index in mem3.aPool[].  When
13182** this is done, the chunk index refers to the second block of
13183** the chunk.  In this way, the first chunk has an index of 1.
13184** A chunk index of 0 means "no such chunk" and is the equivalent
13185** of a NULL pointer.
13186**
13187** The second block of free chunks is of the form u.list.  The
13188** two fields form a double-linked list of chunks of related sizes.
13189** Pointers to the head of the list are stored in mem3.aiSmall[]
13190** for smaller chunks and mem3.aiHash[] for larger chunks.
13191**
13192** The second block of a chunk is user data if the chunk is checked
13193** out.  If a chunk is checked out, the user data may extend into
13194** the u.hdr.prevSize value of the following chunk.
13195*/
13196typedef struct Mem3Block Mem3Block;
13197struct Mem3Block {
13198  union {
13199    struct {
13200      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
13201      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
13202    } hdr;
13203    struct {
13204      u32 next;       /* Index in mem3.aPool[] of next free chunk */
13205      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
13206    } list;
13207  } u;
13208};
13209
13210/*
13211** All of the static variables used by this module are collected
13212** into a single structure named "mem3".  This is to keep the
13213** static variables organized and to reduce namespace pollution
13214** when this module is combined with other in the amalgamation.
13215*/
13216static SQLITE_WSD struct Mem3Global {
13217  /*
13218  ** Memory available for allocation. nPool is the size of the array
13219  ** (in Mem3Blocks) pointed to by aPool less 2.
13220  */
13221  u32 nPool;
13222  Mem3Block *aPool;
13223
13224  /*
13225  ** True if we are evaluating an out-of-memory callback.
13226  */
13227  int alarmBusy;
13228
13229  /*
13230  ** Mutex to control access to the memory allocation subsystem.
13231  */
13232  sqlite3_mutex *mutex;
13233
13234  /*
13235  ** The minimum amount of free space that we have seen.
13236  */
13237  u32 mnMaster;
13238
13239  /*
13240  ** iMaster is the index of the master chunk.  Most new allocations
13241  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
13242  ** of the current master.  iMaster is 0 if there is not master chunk.
13243  ** The master chunk is not in either the aiHash[] or aiSmall[].
13244  */
13245  u32 iMaster;
13246  u32 szMaster;
13247
13248  /*
13249  ** Array of lists of free blocks according to the block size
13250  ** for smaller chunks, or a hash on the block size for larger
13251  ** chunks.
13252  */
13253  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
13254  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
13255} mem3 = { 97535575 };
13256
13257#define mem3 GLOBAL(struct Mem3Global, mem3)
13258
13259/*
13260** Unlink the chunk at mem3.aPool[i] from list it is currently
13261** on.  *pRoot is the list that i is a member of.
13262*/
13263static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
13264  u32 next = mem3.aPool[i].u.list.next;
13265  u32 prev = mem3.aPool[i].u.list.prev;
13266  assert( sqlite3_mutex_held(mem3.mutex) );
13267  if( prev==0 ){
13268    *pRoot = next;
13269  }else{
13270    mem3.aPool[prev].u.list.next = next;
13271  }
13272  if( next ){
13273    mem3.aPool[next].u.list.prev = prev;
13274  }
13275  mem3.aPool[i].u.list.next = 0;
13276  mem3.aPool[i].u.list.prev = 0;
13277}
13278
13279/*
13280** Unlink the chunk at index i from
13281** whatever list is currently a member of.
13282*/
13283static void memsys3Unlink(u32 i){
13284  u32 size, hash;
13285  assert( sqlite3_mutex_held(mem3.mutex) );
13286  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13287  assert( i>=1 );
13288  size = mem3.aPool[i-1].u.hdr.size4x/4;
13289  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13290  assert( size>=2 );
13291  if( size <= MX_SMALL ){
13292    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
13293  }else{
13294    hash = size % N_HASH;
13295    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13296  }
13297}
13298
13299/*
13300** Link the chunk at mem3.aPool[i] so that is on the list rooted
13301** at *pRoot.
13302*/
13303static void memsys3LinkIntoList(u32 i, u32 *pRoot){
13304  assert( sqlite3_mutex_held(mem3.mutex) );
13305  mem3.aPool[i].u.list.next = *pRoot;
13306  mem3.aPool[i].u.list.prev = 0;
13307  if( *pRoot ){
13308    mem3.aPool[*pRoot].u.list.prev = i;
13309  }
13310  *pRoot = i;
13311}
13312
13313/*
13314** Link the chunk at index i into either the appropriate
13315** small chunk list, or into the large chunk hash table.
13316*/
13317static void memsys3Link(u32 i){
13318  u32 size, hash;
13319  assert( sqlite3_mutex_held(mem3.mutex) );
13320  assert( i>=1 );
13321  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13322  size = mem3.aPool[i-1].u.hdr.size4x/4;
13323  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13324  assert( size>=2 );
13325  if( size <= MX_SMALL ){
13326    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
13327  }else{
13328    hash = size % N_HASH;
13329    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
13330  }
13331}
13332
13333/*
13334** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13335** will already be held (obtained by code in malloc.c) if
13336** sqlite3GlobalConfig.bMemStat is true.
13337*/
13338static void memsys3Enter(void){
13339  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
13340    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13341  }
13342  sqlite3_mutex_enter(mem3.mutex);
13343}
13344static void memsys3Leave(void){
13345  sqlite3_mutex_leave(mem3.mutex);
13346}
13347
13348/*
13349** Called when we are unable to satisfy an allocation of nBytes.
13350*/
13351static void memsys3OutOfMemory(int nByte){
13352  if( !mem3.alarmBusy ){
13353    mem3.alarmBusy = 1;
13354    assert( sqlite3_mutex_held(mem3.mutex) );
13355    sqlite3_mutex_leave(mem3.mutex);
13356    sqlite3_release_memory(nByte);
13357    sqlite3_mutex_enter(mem3.mutex);
13358    mem3.alarmBusy = 0;
13359  }
13360}
13361
13362
13363/*
13364** Chunk i is a free chunk that has been unlinked.  Adjust its
13365** size parameters for check-out and return a pointer to the
13366** user portion of the chunk.
13367*/
13368static void *memsys3Checkout(u32 i, u32 nBlock){
13369  u32 x;
13370  assert( sqlite3_mutex_held(mem3.mutex) );
13371  assert( i>=1 );
13372  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
13373  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
13374  x = mem3.aPool[i-1].u.hdr.size4x;
13375  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
13376  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
13377  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
13378  return &mem3.aPool[i];
13379}
13380
13381/*
13382** Carve a piece off of the end of the mem3.iMaster free chunk.
13383** Return a pointer to the new allocation.  Or, if the master chunk
13384** is not large enough, return 0.
13385*/
13386static void *memsys3FromMaster(u32 nBlock){
13387  assert( sqlite3_mutex_held(mem3.mutex) );
13388  assert( mem3.szMaster>=nBlock );
13389  if( nBlock>=mem3.szMaster-1 ){
13390    /* Use the entire master */
13391    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
13392    mem3.iMaster = 0;
13393    mem3.szMaster = 0;
13394    mem3.mnMaster = 0;
13395    return p;
13396  }else{
13397    /* Split the master block.  Return the tail. */
13398    u32 newi, x;
13399    newi = mem3.iMaster + mem3.szMaster - nBlock;
13400    assert( newi > mem3.iMaster+1 );
13401    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
13402    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
13403    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
13404    mem3.szMaster -= nBlock;
13405    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
13406    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13407    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13408    if( mem3.szMaster < mem3.mnMaster ){
13409      mem3.mnMaster = mem3.szMaster;
13410    }
13411    return (void*)&mem3.aPool[newi];
13412  }
13413}
13414
13415/*
13416** *pRoot is the head of a list of free chunks of the same size
13417** or same size hash.  In other words, *pRoot is an entry in either
13418** mem3.aiSmall[] or mem3.aiHash[].
13419**
13420** This routine examines all entries on the given list and tries
13421** to coalesce each entries with adjacent free chunks.
13422**
13423** If it sees a chunk that is larger than mem3.iMaster, it replaces
13424** the current mem3.iMaster with the new larger chunk.  In order for
13425** this mem3.iMaster replacement to work, the master chunk must be
13426** linked into the hash tables.  That is not the normal state of
13427** affairs, of course.  The calling routine must link the master
13428** chunk before invoking this routine, then must unlink the (possibly
13429** changed) master chunk once this routine has finished.
13430*/
13431static void memsys3Merge(u32 *pRoot){
13432  u32 iNext, prev, size, i, x;
13433
13434  assert( sqlite3_mutex_held(mem3.mutex) );
13435  for(i=*pRoot; i>0; i=iNext){
13436    iNext = mem3.aPool[i].u.list.next;
13437    size = mem3.aPool[i-1].u.hdr.size4x;
13438    assert( (size&1)==0 );
13439    if( (size&2)==0 ){
13440      memsys3UnlinkFromList(i, pRoot);
13441      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
13442      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
13443      if( prev==iNext ){
13444        iNext = mem3.aPool[prev].u.list.next;
13445      }
13446      memsys3Unlink(prev);
13447      size = i + size/4 - prev;
13448      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
13449      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
13450      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
13451      memsys3Link(prev);
13452      i = prev;
13453    }else{
13454      size /= 4;
13455    }
13456    if( size>mem3.szMaster ){
13457      mem3.iMaster = i;
13458      mem3.szMaster = size;
13459    }
13460  }
13461}
13462
13463/*
13464** Return a block of memory of at least nBytes in size.
13465** Return NULL if unable.
13466**
13467** This function assumes that the necessary mutexes, if any, are
13468** already held by the caller. Hence "Unsafe".
13469*/
13470static void *memsys3MallocUnsafe(int nByte){
13471  u32 i;
13472  u32 nBlock;
13473  u32 toFree;
13474
13475  assert( sqlite3_mutex_held(mem3.mutex) );
13476  assert( sizeof(Mem3Block)==8 );
13477  if( nByte<=12 ){
13478    nBlock = 2;
13479  }else{
13480    nBlock = (nByte + 11)/8;
13481  }
13482  assert( nBlock>=2 );
13483
13484  /* STEP 1:
13485  ** Look for an entry of the correct size in either the small
13486  ** chunk table or in the large chunk hash table.  This is
13487  ** successful most of the time (about 9 times out of 10).
13488  */
13489  if( nBlock <= MX_SMALL ){
13490    i = mem3.aiSmall[nBlock-2];
13491    if( i>0 ){
13492      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
13493      return memsys3Checkout(i, nBlock);
13494    }
13495  }else{
13496    int hash = nBlock % N_HASH;
13497    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
13498      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
13499        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13500        return memsys3Checkout(i, nBlock);
13501      }
13502    }
13503  }
13504
13505  /* STEP 2:
13506  ** Try to satisfy the allocation by carving a piece off of the end
13507  ** of the master chunk.  This step usually works if step 1 fails.
13508  */
13509  if( mem3.szMaster>=nBlock ){
13510    return memsys3FromMaster(nBlock);
13511  }
13512
13513
13514  /* STEP 3:
13515  ** Loop through the entire memory pool.  Coalesce adjacent free
13516  ** chunks.  Recompute the master chunk as the largest free chunk.
13517  ** Then try again to satisfy the allocation by carving a piece off
13518  ** of the end of the master chunk.  This step happens very
13519  ** rarely (we hope!)
13520  */
13521  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
13522    memsys3OutOfMemory(toFree);
13523    if( mem3.iMaster ){
13524      memsys3Link(mem3.iMaster);
13525      mem3.iMaster = 0;
13526      mem3.szMaster = 0;
13527    }
13528    for(i=0; i<N_HASH; i++){
13529      memsys3Merge(&mem3.aiHash[i]);
13530    }
13531    for(i=0; i<MX_SMALL-1; i++){
13532      memsys3Merge(&mem3.aiSmall[i]);
13533    }
13534    if( mem3.szMaster ){
13535      memsys3Unlink(mem3.iMaster);
13536      if( mem3.szMaster>=nBlock ){
13537        return memsys3FromMaster(nBlock);
13538      }
13539    }
13540  }
13541
13542  /* If none of the above worked, then we fail. */
13543  return 0;
13544}
13545
13546/*
13547** Free an outstanding memory allocation.
13548**
13549** This function assumes that the necessary mutexes, if any, are
13550** already held by the caller. Hence "Unsafe".
13551*/
13552void memsys3FreeUnsafe(void *pOld){
13553  Mem3Block *p = (Mem3Block*)pOld;
13554  int i;
13555  u32 size, x;
13556  assert( sqlite3_mutex_held(mem3.mutex) );
13557  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
13558  i = p - mem3.aPool;
13559  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
13560  size = mem3.aPool[i-1].u.hdr.size4x/4;
13561  assert( i+size<=mem3.nPool+1 );
13562  mem3.aPool[i-1].u.hdr.size4x &= ~1;
13563  mem3.aPool[i+size-1].u.hdr.prevSize = size;
13564  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
13565  memsys3Link(i);
13566
13567  /* Try to expand the master using the newly freed chunk */
13568  if( mem3.iMaster ){
13569    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
13570      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
13571      mem3.iMaster -= size;
13572      mem3.szMaster += size;
13573      memsys3Unlink(mem3.iMaster);
13574      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13575      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13576      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
13577    }
13578    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13579    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
13580      memsys3Unlink(mem3.iMaster+mem3.szMaster);
13581      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
13582      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13583      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
13584    }
13585  }
13586}
13587
13588/*
13589** Return the size of an outstanding allocation, in bytes.  The
13590** size returned omits the 8-byte header overhead.  This only
13591** works for chunks that are currently checked out.
13592*/
13593static int memsys3Size(void *p){
13594  Mem3Block *pBlock;
13595  if( p==0 ) return 0;
13596  pBlock = (Mem3Block*)p;
13597  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
13598  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
13599}
13600
13601/*
13602** Round up a request size to the next valid allocation size.
13603*/
13604static int memsys3Roundup(int n){
13605  if( n<=12 ){
13606    return 12;
13607  }else{
13608    return ((n+11)&~7) - 4;
13609  }
13610}
13611
13612/*
13613** Allocate nBytes of memory.
13614*/
13615static void *memsys3Malloc(int nBytes){
13616  sqlite3_int64 *p;
13617  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
13618  memsys3Enter();
13619  p = memsys3MallocUnsafe(nBytes);
13620  memsys3Leave();
13621  return (void*)p;
13622}
13623
13624/*
13625** Free memory.
13626*/
13627void memsys3Free(void *pPrior){
13628  assert( pPrior );
13629  memsys3Enter();
13630  memsys3FreeUnsafe(pPrior);
13631  memsys3Leave();
13632}
13633
13634/*
13635** Change the size of an existing memory allocation
13636*/
13637void *memsys3Realloc(void *pPrior, int nBytes){
13638  int nOld;
13639  void *p;
13640  if( pPrior==0 ){
13641    return sqlite3_malloc(nBytes);
13642  }
13643  if( nBytes<=0 ){
13644    sqlite3_free(pPrior);
13645    return 0;
13646  }
13647  nOld = memsys3Size(pPrior);
13648  if( nBytes<=nOld && nBytes>=nOld-128 ){
13649    return pPrior;
13650  }
13651  memsys3Enter();
13652  p = memsys3MallocUnsafe(nBytes);
13653  if( p ){
13654    if( nOld<nBytes ){
13655      memcpy(p, pPrior, nOld);
13656    }else{
13657      memcpy(p, pPrior, nBytes);
13658    }
13659    memsys3FreeUnsafe(pPrior);
13660  }
13661  memsys3Leave();
13662  return p;
13663}
13664
13665/*
13666** Initialize this module.
13667*/
13668static int memsys3Init(void *NotUsed){
13669  UNUSED_PARAMETER(NotUsed);
13670  if( !sqlite3GlobalConfig.pHeap ){
13671    return SQLITE_ERROR;
13672  }
13673
13674  /* Store a pointer to the memory block in global structure mem3. */
13675  assert( sizeof(Mem3Block)==8 );
13676  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
13677  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
13678
13679  /* Initialize the master block. */
13680  mem3.szMaster = mem3.nPool;
13681  mem3.mnMaster = mem3.szMaster;
13682  mem3.iMaster = 1;
13683  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
13684  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
13685  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
13686
13687  return SQLITE_OK;
13688}
13689
13690/*
13691** Deinitialize this module.
13692*/
13693static void memsys3Shutdown(void *NotUsed){
13694  UNUSED_PARAMETER(NotUsed);
13695  mem3.mutex = 0;
13696  return;
13697}
13698
13699
13700
13701/*
13702** Open the file indicated and write a log of all unfreed memory
13703** allocations into that log.
13704*/
13705SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
13706#ifdef SQLITE_DEBUG
13707  FILE *out;
13708  u32 i, j;
13709  u32 size;
13710  if( zFilename==0 || zFilename[0]==0 ){
13711    out = stdout;
13712  }else{
13713    out = fopen(zFilename, "w");
13714    if( out==0 ){
13715      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13716                      zFilename);
13717      return;
13718    }
13719  }
13720  memsys3Enter();
13721  fprintf(out, "CHUNKS:\n");
13722  for(i=1; i<=mem3.nPool; i+=size/4){
13723    size = mem3.aPool[i-1].u.hdr.size4x;
13724    if( size/4<=1 ){
13725      fprintf(out, "%p size error\n", &mem3.aPool[i]);
13726      assert( 0 );
13727      break;
13728    }
13729    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
13730      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
13731      assert( 0 );
13732      break;
13733    }
13734    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
13735      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
13736      assert( 0 );
13737      break;
13738    }
13739    if( size&1 ){
13740      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
13741    }else{
13742      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
13743                  i==mem3.iMaster ? " **master**" : "");
13744    }
13745  }
13746  for(i=0; i<MX_SMALL-1; i++){
13747    if( mem3.aiSmall[i]==0 ) continue;
13748    fprintf(out, "small(%2d):", i);
13749    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
13750      fprintf(out, " %p(%d)", &mem3.aPool[j],
13751              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
13752    }
13753    fprintf(out, "\n");
13754  }
13755  for(i=0; i<N_HASH; i++){
13756    if( mem3.aiHash[i]==0 ) continue;
13757    fprintf(out, "hash(%2d):", i);
13758    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
13759      fprintf(out, " %p(%d)", &mem3.aPool[j],
13760              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
13761    }
13762    fprintf(out, "\n");
13763  }
13764  fprintf(out, "master=%d\n", mem3.iMaster);
13765  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
13766  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
13767  sqlite3_mutex_leave(mem3.mutex);
13768  if( out==stdout ){
13769    fflush(stdout);
13770  }else{
13771    fclose(out);
13772  }
13773#else
13774  UNUSED_PARAMETER(zFilename);
13775#endif
13776}
13777
13778/*
13779** This routine is the only routine in this file with external
13780** linkage.
13781**
13782** Populate the low-level memory allocation function pointers in
13783** sqlite3GlobalConfig.m with pointers to the routines in this file. The
13784** arguments specify the block of memory to manage.
13785**
13786** This routine is only called by sqlite3_config(), and therefore
13787** is not required to be threadsafe (it is not).
13788*/
13789SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
13790  static const sqlite3_mem_methods mempoolMethods = {
13791     memsys3Malloc,
13792     memsys3Free,
13793     memsys3Realloc,
13794     memsys3Size,
13795     memsys3Roundup,
13796     memsys3Init,
13797     memsys3Shutdown,
13798     0
13799  };
13800  return &mempoolMethods;
13801}
13802
13803#endif /* SQLITE_ENABLE_MEMSYS3 */
13804
13805/************** End of mem3.c ************************************************/
13806/************** Begin file mem5.c ********************************************/
13807/*
13808** 2007 October 14
13809**
13810** The author disclaims copyright to this source code.  In place of
13811** a legal notice, here is a blessing:
13812**
13813**    May you do good and not evil.
13814**    May you find forgiveness for yourself and forgive others.
13815**    May you share freely, never taking more than you give.
13816**
13817*************************************************************************
13818** This file contains the C functions that implement a memory
13819** allocation subsystem for use by SQLite.
13820**
13821** This version of the memory allocation subsystem omits all
13822** use of malloc(). The application gives SQLite a block of memory
13823** before calling sqlite3_initialize() from which allocations
13824** are made and returned by the xMalloc() and xRealloc()
13825** implementations. Once sqlite3_initialize() has been called,
13826** the amount of memory available to SQLite is fixed and cannot
13827** be changed.
13828**
13829** This version of the memory allocation subsystem is included
13830** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
13831**
13832** This memory allocator uses the following algorithm:
13833**
13834**   1.  All memory allocations sizes are rounded up to a power of 2.
13835**
13836**   2.  If two adjacent free blocks are the halves of a larger block,
13837**       then the two blocks are coalesed into the single larger block.
13838**
13839**   3.  New memory is allocated from the first available free block.
13840**
13841** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
13842** Concerning Dynamic Storage Allocation". Journal of the Association for
13843** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
13844**
13845** Let n be the size of the largest allocation divided by the minimum
13846** allocation size (after rounding all sizes up to a power of 2.)  Let M
13847** be the maximum amount of memory ever outstanding at one time.  Let
13848** N be the total amount of memory available for allocation.  Robson
13849** proved that this memory allocator will never breakdown due to
13850** fragmentation as long as the following constraint holds:
13851**
13852**      N >=  M*(1 + log2(n)/2) - n + 1
13853**
13854** The sqlite3_status() logic tracks the maximum values of n and M so
13855** that an application can, at any time, verify this constraint.
13856*/
13857
13858/*
13859** This version of the memory allocator is used only when
13860** SQLITE_ENABLE_MEMSYS5 is defined.
13861*/
13862#ifdef SQLITE_ENABLE_MEMSYS5
13863
13864/*
13865** A minimum allocation is an instance of the following structure.
13866** Larger allocations are an array of these structures where the
13867** size of the array is a power of 2.
13868**
13869** The size of this object must be a power of two.  That fact is
13870** verified in memsys5Init().
13871*/
13872typedef struct Mem5Link Mem5Link;
13873struct Mem5Link {
13874  int next;       /* Index of next free chunk */
13875  int prev;       /* Index of previous free chunk */
13876};
13877
13878/*
13879** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
13880** mem5.szAtom is always at least 8 and 32-bit integers are used,
13881** it is not actually possible to reach this limit.
13882*/
13883#define LOGMAX 30
13884
13885/*
13886** Masks used for mem5.aCtrl[] elements.
13887*/
13888#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
13889#define CTRL_FREE     0x20    /* True if not checked out */
13890
13891/*
13892** All of the static variables used by this module are collected
13893** into a single structure named "mem5".  This is to keep the
13894** static variables organized and to reduce namespace pollution
13895** when this module is combined with other in the amalgamation.
13896*/
13897static SQLITE_WSD struct Mem5Global {
13898  /*
13899  ** Memory available for allocation
13900  */
13901  int szAtom;      /* Smallest possible allocation in bytes */
13902  int nBlock;      /* Number of szAtom sized blocks in zPool */
13903  u8 *zPool;       /* Memory available to be allocated */
13904
13905  /*
13906  ** Mutex to control access to the memory allocation subsystem.
13907  */
13908  sqlite3_mutex *mutex;
13909
13910  /*
13911  ** Performance statistics
13912  */
13913  u64 nAlloc;         /* Total number of calls to malloc */
13914  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
13915  u64 totalExcess;    /* Total internal fragmentation */
13916  u32 currentOut;     /* Current checkout, including internal fragmentation */
13917  u32 currentCount;   /* Current number of distinct checkouts */
13918  u32 maxOut;         /* Maximum instantaneous currentOut */
13919  u32 maxCount;       /* Maximum instantaneous currentCount */
13920  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
13921
13922  /*
13923  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
13924  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
13925  ** and so forth.
13926  */
13927  int aiFreelist[LOGMAX+1];
13928
13929  /*
13930  ** Space for tracking which blocks are checked out and the size
13931  ** of each block.  One byte per block.
13932  */
13933  u8 *aCtrl;
13934
13935} mem5 = { 0 };
13936
13937/*
13938** Access the static variable through a macro for SQLITE_OMIT_WSD
13939*/
13940#define mem5 GLOBAL(struct Mem5Global, mem5)
13941
13942/*
13943** Assuming mem5.zPool is divided up into an array of Mem5Link
13944** structures, return a pointer to the idx-th such lik.
13945*/
13946#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
13947
13948/*
13949** Unlink the chunk at mem5.aPool[i] from list it is currently
13950** on.  It should be found on mem5.aiFreelist[iLogsize].
13951*/
13952static void memsys5Unlink(int i, int iLogsize){
13953  int next, prev;
13954  assert( i>=0 && i<mem5.nBlock );
13955  assert( iLogsize>=0 && iLogsize<=LOGMAX );
13956  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
13957
13958  next = MEM5LINK(i)->next;
13959  prev = MEM5LINK(i)->prev;
13960  if( prev<0 ){
13961    mem5.aiFreelist[iLogsize] = next;
13962  }else{
13963    MEM5LINK(prev)->next = next;
13964  }
13965  if( next>=0 ){
13966    MEM5LINK(next)->prev = prev;
13967  }
13968}
13969
13970/*
13971** Link the chunk at mem5.aPool[i] so that is on the iLogsize
13972** free list.
13973*/
13974static void memsys5Link(int i, int iLogsize){
13975  int x;
13976  assert( sqlite3_mutex_held(mem5.mutex) );
13977  assert( i>=0 && i<mem5.nBlock );
13978  assert( iLogsize>=0 && iLogsize<=LOGMAX );
13979  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
13980
13981  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
13982  MEM5LINK(i)->prev = -1;
13983  if( x>=0 ){
13984    assert( x<mem5.nBlock );
13985    MEM5LINK(x)->prev = i;
13986  }
13987  mem5.aiFreelist[iLogsize] = i;
13988}
13989
13990/*
13991** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13992** will already be held (obtained by code in malloc.c) if
13993** sqlite3GlobalConfig.bMemStat is true.
13994*/
13995static void memsys5Enter(void){
13996  sqlite3_mutex_enter(mem5.mutex);
13997}
13998static void memsys5Leave(void){
13999  sqlite3_mutex_leave(mem5.mutex);
14000}
14001
14002/*
14003** Return the size of an outstanding allocation, in bytes.  The
14004** size returned omits the 8-byte header overhead.  This only
14005** works for chunks that are currently checked out.
14006*/
14007static int memsys5Size(void *p){
14008  int iSize = 0;
14009  if( p ){
14010    int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
14011    assert( i>=0 && i<mem5.nBlock );
14012    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
14013  }
14014  return iSize;
14015}
14016
14017/*
14018** Find the first entry on the freelist iLogsize.  Unlink that
14019** entry and return its index.
14020*/
14021static int memsys5UnlinkFirst(int iLogsize){
14022  int i;
14023  int iFirst;
14024
14025  assert( iLogsize>=0 && iLogsize<=LOGMAX );
14026  i = iFirst = mem5.aiFreelist[iLogsize];
14027  assert( iFirst>=0 );
14028  while( i>0 ){
14029    if( i<iFirst ) iFirst = i;
14030    i = MEM5LINK(i)->next;
14031  }
14032  memsys5Unlink(iFirst, iLogsize);
14033  return iFirst;
14034}
14035
14036/*
14037** Return a block of memory of at least nBytes in size.
14038** Return NULL if unable.  Return NULL if nBytes==0.
14039**
14040** The caller guarantees that nByte positive.
14041**
14042** The caller has obtained a mutex prior to invoking this
14043** routine so there is never any chance that two or more
14044** threads can be in this routine at the same time.
14045*/
14046static void *memsys5MallocUnsafe(int nByte){
14047  int i;           /* Index of a mem5.aPool[] slot */
14048  int iBin;        /* Index into mem5.aiFreelist[] */
14049  int iFullSz;     /* Size of allocation rounded up to power of 2 */
14050  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
14051
14052  /* nByte must be a positive */
14053  assert( nByte>0 );
14054
14055  /* Keep track of the maximum allocation request.  Even unfulfilled
14056  ** requests are counted */
14057  if( (u32)nByte>mem5.maxRequest ){
14058    mem5.maxRequest = nByte;
14059  }
14060
14061  /* Abort if the requested allocation size is larger than the largest
14062  ** power of two that we can represent using 32-bit signed integers.
14063  */
14064  if( nByte > 0x40000000 ){
14065    return 0;
14066  }
14067
14068  /* Round nByte up to the next valid power of two */
14069  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
14070
14071  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
14072  ** block.  If not, then split a block of the next larger power of
14073  ** two in order to create a new free block of size iLogsize.
14074  */
14075  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
14076  if( iBin>LOGMAX ){
14077    testcase( sqlite3GlobalConfig.xLog!=0 );
14078    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
14079    return 0;
14080  }
14081  i = memsys5UnlinkFirst(iBin);
14082  while( iBin>iLogsize ){
14083    int newSize;
14084
14085    iBin--;
14086    newSize = 1 << iBin;
14087    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
14088    memsys5Link(i+newSize, iBin);
14089  }
14090  mem5.aCtrl[i] = iLogsize;
14091
14092  /* Update allocator performance statistics. */
14093  mem5.nAlloc++;
14094  mem5.totalAlloc += iFullSz;
14095  mem5.totalExcess += iFullSz - nByte;
14096  mem5.currentCount++;
14097  mem5.currentOut += iFullSz;
14098  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
14099  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
14100
14101  /* Return a pointer to the allocated memory. */
14102  return (void*)&mem5.zPool[i*mem5.szAtom];
14103}
14104
14105/*
14106** Free an outstanding memory allocation.
14107*/
14108static void memsys5FreeUnsafe(void *pOld){
14109  u32 size, iLogsize;
14110  int iBlock;
14111
14112  /* Set iBlock to the index of the block pointed to by pOld in
14113  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
14114  */
14115  iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
14116
14117  /* Check that the pointer pOld points to a valid, non-free block. */
14118  assert( iBlock>=0 && iBlock<mem5.nBlock );
14119  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
14120  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
14121
14122  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
14123  size = 1<<iLogsize;
14124  assert( iBlock+size-1<(u32)mem5.nBlock );
14125
14126  mem5.aCtrl[iBlock] |= CTRL_FREE;
14127  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
14128  assert( mem5.currentCount>0 );
14129  assert( mem5.currentOut>=(size*mem5.szAtom) );
14130  mem5.currentCount--;
14131  mem5.currentOut -= size*mem5.szAtom;
14132  assert( mem5.currentOut>0 || mem5.currentCount==0 );
14133  assert( mem5.currentCount>0 || mem5.currentOut==0 );
14134
14135  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14136  while( ALWAYS(iLogsize<LOGMAX) ){
14137    int iBuddy;
14138    if( (iBlock>>iLogsize) & 1 ){
14139      iBuddy = iBlock - size;
14140    }else{
14141      iBuddy = iBlock + size;
14142    }
14143    assert( iBuddy>=0 );
14144    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
14145    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
14146    memsys5Unlink(iBuddy, iLogsize);
14147    iLogsize++;
14148    if( iBuddy<iBlock ){
14149      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
14150      mem5.aCtrl[iBlock] = 0;
14151      iBlock = iBuddy;
14152    }else{
14153      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14154      mem5.aCtrl[iBuddy] = 0;
14155    }
14156    size *= 2;
14157  }
14158  memsys5Link(iBlock, iLogsize);
14159}
14160
14161/*
14162** Allocate nBytes of memory
14163*/
14164static void *memsys5Malloc(int nBytes){
14165  sqlite3_int64 *p = 0;
14166  if( nBytes>0 ){
14167    memsys5Enter();
14168    p = memsys5MallocUnsafe(nBytes);
14169    memsys5Leave();
14170  }
14171  return (void*)p;
14172}
14173
14174/*
14175** Free memory.
14176**
14177** The outer layer memory allocator prevents this routine from
14178** being called with pPrior==0.
14179*/
14180static void memsys5Free(void *pPrior){
14181  assert( pPrior!=0 );
14182  memsys5Enter();
14183  memsys5FreeUnsafe(pPrior);
14184  memsys5Leave();
14185}
14186
14187/*
14188** Change the size of an existing memory allocation.
14189**
14190** The outer layer memory allocator prevents this routine from
14191** being called with pPrior==0.
14192**
14193** nBytes is always a value obtained from a prior call to
14194** memsys5Round().  Hence nBytes is always a non-negative power
14195** of two.  If nBytes==0 that means that an oversize allocation
14196** (an allocation larger than 0x40000000) was requested and this
14197** routine should return 0 without freeing pPrior.
14198*/
14199static void *memsys5Realloc(void *pPrior, int nBytes){
14200  int nOld;
14201  void *p;
14202  assert( pPrior!=0 );
14203  assert( (nBytes&(nBytes-1))==0 );
14204  assert( nBytes>=0 );
14205  if( nBytes==0 ){
14206    return 0;
14207  }
14208  nOld = memsys5Size(pPrior);
14209  if( nBytes<=nOld ){
14210    return pPrior;
14211  }
14212  memsys5Enter();
14213  p = memsys5MallocUnsafe(nBytes);
14214  if( p ){
14215    memcpy(p, pPrior, nOld);
14216    memsys5FreeUnsafe(pPrior);
14217  }
14218  memsys5Leave();
14219  return p;
14220}
14221
14222/*
14223** Round up a request size to the next valid allocation size.  If
14224** the allocation is too large to be handled by this allocation system,
14225** return 0.
14226**
14227** All allocations must be a power of two and must be expressed by a
14228** 32-bit signed integer.  Hence the largest allocation is 0x40000000
14229** or 1073741824 bytes.
14230*/
14231static int memsys5Roundup(int n){
14232  int iFullSz;
14233  if( n > 0x40000000 ) return 0;
14234  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
14235  return iFullSz;
14236}
14237
14238/*
14239** Return the ceiling of the logarithm base 2 of iValue.
14240**
14241** Examples:   memsys5Log(1) -> 0
14242**             memsys5Log(2) -> 1
14243**             memsys5Log(4) -> 2
14244**             memsys5Log(5) -> 3
14245**             memsys5Log(8) -> 3
14246**             memsys5Log(9) -> 4
14247*/
14248static int memsys5Log(int iValue){
14249  int iLog;
14250  for(iLog=0; (1<<iLog)<iValue; iLog++);
14251  return iLog;
14252}
14253
14254/*
14255** Initialize the memory allocator.
14256**
14257** This routine is not threadsafe.  The caller must be holding a mutex
14258** to prevent multiple threads from entering at the same time.
14259*/
14260static int memsys5Init(void *NotUsed){
14261  int ii;            /* Loop counter */
14262  int nByte;         /* Number of bytes of memory available to this allocator */
14263  u8 *zByte;         /* Memory usable by this allocator */
14264  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
14265  int iOffset;       /* An offset into mem5.aCtrl[] */
14266
14267  UNUSED_PARAMETER(NotUsed);
14268
14269  /* For the purposes of this routine, disable the mutex */
14270  mem5.mutex = 0;
14271
14272  /* The size of a Mem5Link object must be a power of two.  Verify that
14273  ** this is case.
14274  */
14275  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
14276
14277  nByte = sqlite3GlobalConfig.nHeap;
14278  zByte = (u8*)sqlite3GlobalConfig.pHeap;
14279  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
14280
14281  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
14282  mem5.szAtom = (1<<nMinLog);
14283  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
14284    mem5.szAtom = mem5.szAtom << 1;
14285  }
14286
14287  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
14288  mem5.zPool = zByte;
14289  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
14290
14291  for(ii=0; ii<=LOGMAX; ii++){
14292    mem5.aiFreelist[ii] = -1;
14293  }
14294
14295  iOffset = 0;
14296  for(ii=LOGMAX; ii>=0; ii--){
14297    int nAlloc = (1<<ii);
14298    if( (iOffset+nAlloc)<=mem5.nBlock ){
14299      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
14300      memsys5Link(iOffset, ii);
14301      iOffset += nAlloc;
14302    }
14303    assert((iOffset+nAlloc)>mem5.nBlock);
14304  }
14305
14306  /* If a mutex is required for normal operation, allocate one */
14307  if( sqlite3GlobalConfig.bMemstat==0 ){
14308    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14309  }
14310
14311  return SQLITE_OK;
14312}
14313
14314/*
14315** Deinitialize this module.
14316*/
14317static void memsys5Shutdown(void *NotUsed){
14318  UNUSED_PARAMETER(NotUsed);
14319  mem5.mutex = 0;
14320  return;
14321}
14322
14323#ifdef SQLITE_TEST
14324/*
14325** Open the file indicated and write a log of all unfreed memory
14326** allocations into that log.
14327*/
14328SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
14329  FILE *out;
14330  int i, j, n;
14331  int nMinLog;
14332
14333  if( zFilename==0 || zFilename[0]==0 ){
14334    out = stdout;
14335  }else{
14336    out = fopen(zFilename, "w");
14337    if( out==0 ){
14338      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14339                      zFilename);
14340      return;
14341    }
14342  }
14343  memsys5Enter();
14344  nMinLog = memsys5Log(mem5.szAtom);
14345  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
14346    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
14347    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
14348  }
14349  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
14350  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
14351  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
14352  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
14353  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
14354  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
14355  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
14356  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
14357  memsys5Leave();
14358  if( out==stdout ){
14359    fflush(stdout);
14360  }else{
14361    fclose(out);
14362  }
14363}
14364#endif
14365
14366/*
14367** This routine is the only routine in this file with external
14368** linkage. It returns a pointer to a static sqlite3_mem_methods
14369** struct populated with the memsys5 methods.
14370*/
14371SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
14372  static const sqlite3_mem_methods memsys5Methods = {
14373     memsys5Malloc,
14374     memsys5Free,
14375     memsys5Realloc,
14376     memsys5Size,
14377     memsys5Roundup,
14378     memsys5Init,
14379     memsys5Shutdown,
14380     0
14381  };
14382  return &memsys5Methods;
14383}
14384
14385#endif /* SQLITE_ENABLE_MEMSYS5 */
14386
14387/************** End of mem5.c ************************************************/
14388/************** Begin file mutex.c *******************************************/
14389/*
14390** 2007 August 14
14391**
14392** The author disclaims copyright to this source code.  In place of
14393** a legal notice, here is a blessing:
14394**
14395**    May you do good and not evil.
14396**    May you find forgiveness for yourself and forgive others.
14397**    May you share freely, never taking more than you give.
14398**
14399*************************************************************************
14400** This file contains the C functions that implement mutexes.
14401**
14402** This file contains code that is common across all mutex implementations.
14403*/
14404
14405#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
14406/*
14407** For debugging purposes, record when the mutex subsystem is initialized
14408** and uninitialized so that we can assert() if there is an attempt to
14409** allocate a mutex while the system is uninitialized.
14410*/
14411static SQLITE_WSD int mutexIsInit = 0;
14412#endif /* SQLITE_DEBUG */
14413
14414
14415#ifndef SQLITE_MUTEX_OMIT
14416/*
14417** Initialize the mutex system.
14418*/
14419SQLITE_PRIVATE int sqlite3MutexInit(void){
14420  int rc = SQLITE_OK;
14421  if( sqlite3GlobalConfig.bCoreMutex ){
14422    if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
14423      /* If the xMutexAlloc method has not been set, then the user did not
14424      ** install a mutex implementation via sqlite3_config() prior to
14425      ** sqlite3_initialize() being called. This block copies pointers to
14426      ** the default implementation into the sqlite3GlobalConfig structure.
14427      */
14428      sqlite3_mutex_methods *pFrom = sqlite3DefaultMutex();
14429      sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
14430
14431      memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
14432      memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
14433             sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
14434      pTo->xMutexAlloc = pFrom->xMutexAlloc;
14435    }
14436    rc = sqlite3GlobalConfig.mutex.xMutexInit();
14437  }
14438
14439#ifdef SQLITE_DEBUG
14440  GLOBAL(int, mutexIsInit) = 1;
14441#endif
14442
14443  return rc;
14444}
14445
14446/*
14447** Shutdown the mutex system. This call frees resources allocated by
14448** sqlite3MutexInit().
14449*/
14450SQLITE_PRIVATE int sqlite3MutexEnd(void){
14451  int rc = SQLITE_OK;
14452  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
14453    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
14454  }
14455
14456#ifdef SQLITE_DEBUG
14457  GLOBAL(int, mutexIsInit) = 0;
14458#endif
14459
14460  return rc;
14461}
14462
14463/*
14464** Retrieve a pointer to a static mutex or allocate a new dynamic one.
14465*/
14466SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
14467#ifndef SQLITE_OMIT_AUTOINIT
14468  if( sqlite3_initialize() ) return 0;
14469#endif
14470  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14471}
14472
14473SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
14474  if( !sqlite3GlobalConfig.bCoreMutex ){
14475    return 0;
14476  }
14477  assert( GLOBAL(int, mutexIsInit) );
14478  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14479}
14480
14481/*
14482** Free a dynamic mutex.
14483*/
14484SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
14485  if( p ){
14486    sqlite3GlobalConfig.mutex.xMutexFree(p);
14487  }
14488}
14489
14490/*
14491** Obtain the mutex p. If some other thread already has the mutex, block
14492** until it can be obtained.
14493*/
14494SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
14495  if( p ){
14496    sqlite3GlobalConfig.mutex.xMutexEnter(p);
14497  }
14498}
14499
14500/*
14501** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
14502** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
14503*/
14504SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
14505  int rc = SQLITE_OK;
14506  if( p ){
14507    return sqlite3GlobalConfig.mutex.xMutexTry(p);
14508  }
14509  return rc;
14510}
14511
14512/*
14513** The sqlite3_mutex_leave() routine exits a mutex that was previously
14514** entered by the same thread.  The behavior is undefined if the mutex
14515** is not currently entered. If a NULL pointer is passed as an argument
14516** this function is a no-op.
14517*/
14518SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
14519  if( p ){
14520    sqlite3GlobalConfig.mutex.xMutexLeave(p);
14521  }
14522}
14523
14524#ifndef NDEBUG
14525/*
14526** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14527** intended for use inside assert() statements.
14528*/
14529SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
14530  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
14531}
14532SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
14533  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
14534}
14535#endif
14536
14537#endif /* SQLITE_MUTEX_OMIT */
14538
14539/************** End of mutex.c ***********************************************/
14540/************** Begin file mutex_noop.c **************************************/
14541/*
14542** 2008 October 07
14543**
14544** The author disclaims copyright to this source code.  In place of
14545** a legal notice, here is a blessing:
14546**
14547**    May you do good and not evil.
14548**    May you find forgiveness for yourself and forgive others.
14549**    May you share freely, never taking more than you give.
14550**
14551*************************************************************************
14552** This file contains the C functions that implement mutexes.
14553**
14554** This implementation in this file does not provide any mutual
14555** exclusion and is thus suitable for use only in applications
14556** that use SQLite in a single thread.  The routines defined
14557** here are place-holders.  Applications can substitute working
14558** mutex routines at start-time using the
14559**
14560**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
14561**
14562** interface.
14563**
14564** If compiled with SQLITE_DEBUG, then additional logic is inserted
14565** that does error checking on mutexes to make sure they are being
14566** called correctly.
14567*/
14568
14569
14570#if defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG)
14571/*
14572** Stub routines for all mutex methods.
14573**
14574** This routines provide no mutual exclusion or error checking.
14575*/
14576static int noopMutexHeld(sqlite3_mutex *p){ return 1; }
14577static int noopMutexNotheld(sqlite3_mutex *p){ return 1; }
14578static int noopMutexInit(void){ return SQLITE_OK; }
14579static int noopMutexEnd(void){ return SQLITE_OK; }
14580static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; }
14581static void noopMutexFree(sqlite3_mutex *p){ return; }
14582static void noopMutexEnter(sqlite3_mutex *p){ return; }
14583static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; }
14584static void noopMutexLeave(sqlite3_mutex *p){ return; }
14585
14586SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14587  static sqlite3_mutex_methods sMutex = {
14588    noopMutexInit,
14589    noopMutexEnd,
14590    noopMutexAlloc,
14591    noopMutexFree,
14592    noopMutexEnter,
14593    noopMutexTry,
14594    noopMutexLeave,
14595
14596    noopMutexHeld,
14597    noopMutexNotheld
14598  };
14599
14600  return &sMutex;
14601}
14602#endif /* defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG) */
14603
14604#if defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG)
14605/*
14606** In this implementation, error checking is provided for testing
14607** and debugging purposes.  The mutexes still do not provide any
14608** mutual exclusion.
14609*/
14610
14611/*
14612** The mutex object
14613*/
14614struct sqlite3_mutex {
14615  int id;     /* The mutex type */
14616  int cnt;    /* Number of entries without a matching leave */
14617};
14618
14619/*
14620** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14621** intended for use inside assert() statements.
14622*/
14623static int debugMutexHeld(sqlite3_mutex *p){
14624  return p==0 || p->cnt>0;
14625}
14626static int debugMutexNotheld(sqlite3_mutex *p){
14627  return p==0 || p->cnt==0;
14628}
14629
14630/*
14631** Initialize and deinitialize the mutex subsystem.
14632*/
14633static int debugMutexInit(void){ return SQLITE_OK; }
14634static int debugMutexEnd(void){ return SQLITE_OK; }
14635
14636/*
14637** The sqlite3_mutex_alloc() routine allocates a new
14638** mutex and returns a pointer to it.  If it returns NULL
14639** that means that a mutex could not be allocated.
14640*/
14641static sqlite3_mutex *debugMutexAlloc(int id){
14642  static sqlite3_mutex aStatic[6];
14643  sqlite3_mutex *pNew = 0;
14644  switch( id ){
14645    case SQLITE_MUTEX_FAST:
14646    case SQLITE_MUTEX_RECURSIVE: {
14647      pNew = sqlite3Malloc(sizeof(*pNew));
14648      if( pNew ){
14649        pNew->id = id;
14650        pNew->cnt = 0;
14651      }
14652      break;
14653    }
14654    default: {
14655      assert( id-2 >= 0 );
14656      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
14657      pNew = &aStatic[id-2];
14658      pNew->id = id;
14659      break;
14660    }
14661  }
14662  return pNew;
14663}
14664
14665/*
14666** This routine deallocates a previously allocated mutex.
14667*/
14668static void debugMutexFree(sqlite3_mutex *p){
14669  assert( p->cnt==0 );
14670  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
14671  sqlite3_free(p);
14672}
14673
14674/*
14675** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
14676** to enter a mutex.  If another thread is already within the mutex,
14677** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
14678** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
14679** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
14680** be entered multiple times by the same thread.  In such cases the,
14681** mutex must be exited an equal number of times before another thread
14682** can enter.  If the same thread tries to enter any other kind of mutex
14683** more than once, the behavior is undefined.
14684*/
14685static void debugMutexEnter(sqlite3_mutex *p){
14686  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14687  p->cnt++;
14688}
14689static int debugMutexTry(sqlite3_mutex *p){
14690  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14691  p->cnt++;
14692  return SQLITE_OK;
14693}
14694
14695/*
14696** The sqlite3_mutex_leave() routine exits a mutex that was
14697** previously entered by the same thread.  The behavior
14698** is undefined if the mutex is not currently entered or
14699** is not currently allocated.  SQLite will never do either.
14700*/
14701static void debugMutexLeave(sqlite3_mutex *p){
14702  assert( debugMutexHeld(p) );
14703  p->cnt--;
14704  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14705}
14706
14707SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14708  static sqlite3_mutex_methods sMutex = {
14709    debugMutexInit,
14710    debugMutexEnd,
14711    debugMutexAlloc,
14712    debugMutexFree,
14713    debugMutexEnter,
14714    debugMutexTry,
14715    debugMutexLeave,
14716
14717    debugMutexHeld,
14718    debugMutexNotheld
14719  };
14720
14721  return &sMutex;
14722}
14723#endif /* defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG) */
14724
14725/************** End of mutex_noop.c ******************************************/
14726/************** Begin file mutex_os2.c ***************************************/
14727/*
14728** 2007 August 28
14729**
14730** The author disclaims copyright to this source code.  In place of
14731** a legal notice, here is a blessing:
14732**
14733**    May you do good and not evil.
14734**    May you find forgiveness for yourself and forgive others.
14735**    May you share freely, never taking more than you give.
14736**
14737*************************************************************************
14738** This file contains the C functions that implement mutexes for OS/2
14739*/
14740
14741/*
14742** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
14743** See the mutex.h file for details.
14744*/
14745#ifdef SQLITE_MUTEX_OS2
14746
14747/********************** OS/2 Mutex Implementation **********************
14748**
14749** This implementation of mutexes is built using the OS/2 API.
14750*/
14751
14752/*
14753** The mutex object
14754** Each recursive mutex is an instance of the following structure.
14755*/
14756struct sqlite3_mutex {
14757  HMTX mutex;       /* Mutex controlling the lock */
14758  int  id;          /* Mutex type */
14759  int  nRef;        /* Number of references */
14760  TID  owner;       /* Thread holding this mutex */
14761};
14762
14763#define OS2_MUTEX_INITIALIZER   0,0,0,0
14764
14765/*
14766** Initialize and deinitialize the mutex subsystem.
14767*/
14768static int os2MutexInit(void){ return SQLITE_OK; }
14769static int os2MutexEnd(void){ return SQLITE_OK; }
14770
14771/*
14772** The sqlite3_mutex_alloc() routine allocates a new
14773** mutex and returns a pointer to it.  If it returns NULL
14774** that means that a mutex could not be allocated.
14775** SQLite will unwind its stack and return an error.  The argument
14776** to sqlite3_mutex_alloc() is one of these integer constants:
14777**
14778** <ul>
14779** <li>  SQLITE_MUTEX_FAST               0
14780** <li>  SQLITE_MUTEX_RECURSIVE          1
14781** <li>  SQLITE_MUTEX_STATIC_MASTER      2
14782** <li>  SQLITE_MUTEX_STATIC_MEM         3
14783** <li>  SQLITE_MUTEX_STATIC_PRNG        4
14784** </ul>
14785**
14786** The first two constants cause sqlite3_mutex_alloc() to create
14787** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
14788** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
14789** The mutex implementation does not need to make a distinction
14790** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
14791** not want to.  But SQLite will only request a recursive mutex in
14792** cases where it really needs one.  If a faster non-recursive mutex
14793** implementation is available on the host platform, the mutex subsystem
14794** might return such a mutex in response to SQLITE_MUTEX_FAST.
14795**
14796** The other allowed parameters to sqlite3_mutex_alloc() each return
14797** a pointer to a static preexisting mutex.  Three static mutexes are
14798** used by the current version of SQLite.  Future versions of SQLite
14799** may add additional static mutexes.  Static mutexes are for internal
14800** use by SQLite only.  Applications that use SQLite mutexes should
14801** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
14802** SQLITE_MUTEX_RECURSIVE.
14803**
14804** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
14805** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
14806** returns a different mutex on every call.  But for the static
14807** mutex types, the same mutex is returned on every call that has
14808** the same type number.
14809*/
14810static sqlite3_mutex *os2MutexAlloc(int iType){
14811  sqlite3_mutex *p = NULL;
14812  switch( iType ){
14813    case SQLITE_MUTEX_FAST:
14814    case SQLITE_MUTEX_RECURSIVE: {
14815      p = sqlite3MallocZero( sizeof(*p) );
14816      if( p ){
14817        p->id = iType;
14818        if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
14819          sqlite3_free( p );
14820          p = NULL;
14821        }
14822      }
14823      break;
14824    }
14825    default: {
14826      static volatile int isInit = 0;
14827      static sqlite3_mutex staticMutexes[] = {
14828        { OS2_MUTEX_INITIALIZER, },
14829        { OS2_MUTEX_INITIALIZER, },
14830        { OS2_MUTEX_INITIALIZER, },
14831        { OS2_MUTEX_INITIALIZER, },
14832        { OS2_MUTEX_INITIALIZER, },
14833        { OS2_MUTEX_INITIALIZER, },
14834      };
14835      if ( !isInit ){
14836        APIRET rc;
14837        PTIB ptib;
14838        PPIB ppib;
14839        HMTX mutex;
14840        char name[32];
14841        DosGetInfoBlocks( &ptib, &ppib );
14842        sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
14843                          ppib->pib_ulpid );
14844        while( !isInit ){
14845          mutex = 0;
14846          rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
14847          if( rc == NO_ERROR ){
14848            unsigned int i;
14849            if( !isInit ){
14850              for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
14851                DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
14852              }
14853              isInit = 1;
14854            }
14855            DosCloseMutexSem( mutex );
14856          }else if( rc == ERROR_DUPLICATE_NAME ){
14857            DosSleep( 1 );
14858          }else{
14859            return p;
14860          }
14861        }
14862      }
14863      assert( iType-2 >= 0 );
14864      assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
14865      p = &staticMutexes[iType-2];
14866      p->id = iType;
14867      break;
14868    }
14869  }
14870  return p;
14871}
14872
14873
14874/*
14875** This routine deallocates a previously allocated mutex.
14876** SQLite is careful to deallocate every mutex that it allocates.
14877*/
14878static void os2MutexFree(sqlite3_mutex *p){
14879  if( p==0 ) return;
14880  assert( p->nRef==0 );
14881  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
14882  DosCloseMutexSem( p->mutex );
14883  sqlite3_free( p );
14884}
14885
14886#ifdef SQLITE_DEBUG
14887/*
14888** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14889** intended for use inside assert() statements.
14890*/
14891static int os2MutexHeld(sqlite3_mutex *p){
14892  TID tid;
14893  PID pid;
14894  ULONG ulCount;
14895  PTIB ptib;
14896  if( p!=0 ) {
14897    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
14898  } else {
14899    DosGetInfoBlocks(&ptib, NULL);
14900    tid = ptib->tib_ptib2->tib2_ultid;
14901  }
14902  return p==0 || (p->nRef!=0 && p->owner==tid);
14903}
14904static int os2MutexNotheld(sqlite3_mutex *p){
14905  TID tid;
14906  PID pid;
14907  ULONG ulCount;
14908  PTIB ptib;
14909  if( p!= 0 ) {
14910    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
14911  } else {
14912    DosGetInfoBlocks(&ptib, NULL);
14913    tid = ptib->tib_ptib2->tib2_ultid;
14914  }
14915  return p==0 || p->nRef==0 || p->owner!=tid;
14916}
14917#endif
14918
14919/*
14920** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
14921** to enter a mutex.  If another thread is already within the mutex,
14922** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
14923** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
14924** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
14925** be entered multiple times by the same thread.  In such cases the,
14926** mutex must be exited an equal number of times before another thread
14927** can enter.  If the same thread tries to enter any other kind of mutex
14928** more than once, the behavior is undefined.
14929*/
14930static void os2MutexEnter(sqlite3_mutex *p){
14931  TID tid;
14932  PID holder1;
14933  ULONG holder2;
14934  if( p==0 ) return;
14935  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
14936  DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
14937  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14938  p->owner = tid;
14939  p->nRef++;
14940}
14941static int os2MutexTry(sqlite3_mutex *p){
14942  int rc;
14943  TID tid;
14944  PID holder1;
14945  ULONG holder2;
14946  if( p==0 ) return SQLITE_OK;
14947  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
14948  if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
14949    DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14950    p->owner = tid;
14951    p->nRef++;
14952    rc = SQLITE_OK;
14953  } else {
14954    rc = SQLITE_BUSY;
14955  }
14956
14957  return rc;
14958}
14959
14960/*
14961** The sqlite3_mutex_leave() routine exits a mutex that was
14962** previously entered by the same thread.  The behavior
14963** is undefined if the mutex is not currently entered or
14964** is not currently allocated.  SQLite will never do either.
14965*/
14966static void os2MutexLeave(sqlite3_mutex *p){
14967  TID tid;
14968  PID holder1;
14969  ULONG holder2;
14970  if( p==0 ) return;
14971  assert( p->nRef>0 );
14972  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14973  assert( p->owner==tid );
14974  p->nRef--;
14975  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
14976  DosReleaseMutexSem(p->mutex);
14977}
14978
14979SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14980  static sqlite3_mutex_methods sMutex = {
14981    os2MutexInit,
14982    os2MutexEnd,
14983    os2MutexAlloc,
14984    os2MutexFree,
14985    os2MutexEnter,
14986    os2MutexTry,
14987    os2MutexLeave,
14988#ifdef SQLITE_DEBUG
14989    os2MutexHeld,
14990    os2MutexNotheld
14991#endif
14992  };
14993
14994  return &sMutex;
14995}
14996#endif /* SQLITE_MUTEX_OS2 */
14997
14998/************** End of mutex_os2.c *******************************************/
14999/************** Begin file mutex_unix.c **************************************/
15000/*
15001** 2007 August 28
15002**
15003** The author disclaims copyright to this source code.  In place of
15004** a legal notice, here is a blessing:
15005**
15006**    May you do good and not evil.
15007**    May you find forgiveness for yourself and forgive others.
15008**    May you share freely, never taking more than you give.
15009**
15010*************************************************************************
15011** This file contains the C functions that implement mutexes for pthreads
15012*/
15013
15014/*
15015** The code in this file is only used if we are compiling threadsafe
15016** under unix with pthreads.
15017**
15018** Note that this implementation requires a version of pthreads that
15019** supports recursive mutexes.
15020*/
15021#ifdef SQLITE_MUTEX_PTHREADS
15022
15023#include <pthread.h>
15024
15025
15026/*
15027** Each recursive mutex is an instance of the following structure.
15028*/
15029struct sqlite3_mutex {
15030  pthread_mutex_t mutex;     /* Mutex controlling the lock */
15031  int id;                    /* Mutex type */
15032  int nRef;                  /* Number of entrances */
15033  pthread_t owner;           /* Thread that is within this mutex */
15034#ifdef SQLITE_DEBUG
15035  int trace;                 /* True to trace changes */
15036#endif
15037};
15038#ifdef SQLITE_DEBUG
15039#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
15040#else
15041#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
15042#endif
15043
15044/*
15045** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15046** intended for use only inside assert() statements.  On some platforms,
15047** there might be race conditions that can cause these routines to
15048** deliver incorrect results.  In particular, if pthread_equal() is
15049** not an atomic operation, then these routines might delivery
15050** incorrect results.  On most platforms, pthread_equal() is a
15051** comparison of two integers and is therefore atomic.  But we are
15052** told that HPUX is not such a platform.  If so, then these routines
15053** will not always work correctly on HPUX.
15054**
15055** On those platforms where pthread_equal() is not atomic, SQLite
15056** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
15057** make sure no assert() statements are evaluated and hence these
15058** routines are never called.
15059*/
15060#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
15061static int pthreadMutexHeld(sqlite3_mutex *p){
15062  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
15063}
15064static int pthreadMutexNotheld(sqlite3_mutex *p){
15065  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
15066}
15067#endif
15068
15069/*
15070** Initialize and deinitialize the mutex subsystem.
15071*/
15072static int pthreadMutexInit(void){ return SQLITE_OK; }
15073static int pthreadMutexEnd(void){ return SQLITE_OK; }
15074
15075/*
15076** The sqlite3_mutex_alloc() routine allocates a new
15077** mutex and returns a pointer to it.  If it returns NULL
15078** that means that a mutex could not be allocated.  SQLite
15079** will unwind its stack and return an error.  The argument
15080** to sqlite3_mutex_alloc() is one of these integer constants:
15081**
15082** <ul>
15083** <li>  SQLITE_MUTEX_FAST
15084** <li>  SQLITE_MUTEX_RECURSIVE
15085** <li>  SQLITE_MUTEX_STATIC_MASTER
15086** <li>  SQLITE_MUTEX_STATIC_MEM
15087** <li>  SQLITE_MUTEX_STATIC_MEM2
15088** <li>  SQLITE_MUTEX_STATIC_PRNG
15089** <li>  SQLITE_MUTEX_STATIC_LRU
15090** <li>  SQLITE_MUTEX_STATIC_LRU2
15091** </ul>
15092**
15093** The first two constants cause sqlite3_mutex_alloc() to create
15094** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15095** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15096** The mutex implementation does not need to make a distinction
15097** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15098** not want to.  But SQLite will only request a recursive mutex in
15099** cases where it really needs one.  If a faster non-recursive mutex
15100** implementation is available on the host platform, the mutex subsystem
15101** might return such a mutex in response to SQLITE_MUTEX_FAST.
15102**
15103** The other allowed parameters to sqlite3_mutex_alloc() each return
15104** a pointer to a static preexisting mutex.  Six static mutexes are
15105** used by the current version of SQLite.  Future versions of SQLite
15106** may add additional static mutexes.  Static mutexes are for internal
15107** use by SQLite only.  Applications that use SQLite mutexes should
15108** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15109** SQLITE_MUTEX_RECURSIVE.
15110**
15111** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15112** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15113** returns a different mutex on every call.  But for the static
15114** mutex types, the same mutex is returned on every call that has
15115** the same type number.
15116*/
15117static sqlite3_mutex *pthreadMutexAlloc(int iType){
15118  static sqlite3_mutex staticMutexes[] = {
15119    SQLITE3_MUTEX_INITIALIZER,
15120    SQLITE3_MUTEX_INITIALIZER,
15121    SQLITE3_MUTEX_INITIALIZER,
15122    SQLITE3_MUTEX_INITIALIZER,
15123    SQLITE3_MUTEX_INITIALIZER,
15124    SQLITE3_MUTEX_INITIALIZER
15125  };
15126  sqlite3_mutex *p;
15127  switch( iType ){
15128    case SQLITE_MUTEX_RECURSIVE: {
15129      p = sqlite3MallocZero( sizeof(*p) );
15130      if( p ){
15131#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15132        /* If recursive mutexes are not available, we will have to
15133        ** build our own.  See below. */
15134        pthread_mutex_init(&p->mutex, 0);
15135#else
15136        /* Use a recursive mutex if it is available */
15137        pthread_mutexattr_t recursiveAttr;
15138        pthread_mutexattr_init(&recursiveAttr);
15139        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
15140        pthread_mutex_init(&p->mutex, &recursiveAttr);
15141        pthread_mutexattr_destroy(&recursiveAttr);
15142#endif
15143        p->id = iType;
15144      }
15145      break;
15146    }
15147    case SQLITE_MUTEX_FAST: {
15148      p = sqlite3MallocZero( sizeof(*p) );
15149      if( p ){
15150        p->id = iType;
15151        pthread_mutex_init(&p->mutex, 0);
15152      }
15153      break;
15154    }
15155    default: {
15156      assert( iType-2 >= 0 );
15157      assert( iType-2 < ArraySize(staticMutexes) );
15158      p = &staticMutexes[iType-2];
15159      p->id = iType;
15160      break;
15161    }
15162  }
15163  return p;
15164}
15165
15166
15167/*
15168** This routine deallocates a previously
15169** allocated mutex.  SQLite is careful to deallocate every
15170** mutex that it allocates.
15171*/
15172static void pthreadMutexFree(sqlite3_mutex *p){
15173  assert( p->nRef==0 );
15174  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15175  pthread_mutex_destroy(&p->mutex);
15176  sqlite3_free(p);
15177}
15178
15179/*
15180** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15181** to enter a mutex.  If another thread is already within the mutex,
15182** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15183** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15184** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15185** be entered multiple times by the same thread.  In such cases the,
15186** mutex must be exited an equal number of times before another thread
15187** can enter.  If the same thread tries to enter any other kind of mutex
15188** more than once, the behavior is undefined.
15189*/
15190static void pthreadMutexEnter(sqlite3_mutex *p){
15191  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15192
15193#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15194  /* If recursive mutexes are not available, then we have to grow
15195  ** our own.  This implementation assumes that pthread_equal()
15196  ** is atomic - that it cannot be deceived into thinking self
15197  ** and p->owner are equal if p->owner changes between two values
15198  ** that are not equal to self while the comparison is taking place.
15199  ** This implementation also assumes a coherent cache - that
15200  ** separate processes cannot read different values from the same
15201  ** address at the same time.  If either of these two conditions
15202  ** are not met, then the mutexes will fail and problems will result.
15203  */
15204  {
15205    pthread_t self = pthread_self();
15206    if( p->nRef>0 && pthread_equal(p->owner, self) ){
15207      p->nRef++;
15208    }else{
15209      pthread_mutex_lock(&p->mutex);
15210      assert( p->nRef==0 );
15211      p->owner = self;
15212      p->nRef = 1;
15213    }
15214  }
15215#else
15216  /* Use the built-in recursive mutexes if they are available.
15217  */
15218  pthread_mutex_lock(&p->mutex);
15219  p->owner = pthread_self();
15220  p->nRef++;
15221#endif
15222
15223#ifdef SQLITE_DEBUG
15224  if( p->trace ){
15225    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15226  }
15227#endif
15228}
15229static int pthreadMutexTry(sqlite3_mutex *p){
15230  int rc;
15231  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15232
15233#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15234  /* If recursive mutexes are not available, then we have to grow
15235  ** our own.  This implementation assumes that pthread_equal()
15236  ** is atomic - that it cannot be deceived into thinking self
15237  ** and p->owner are equal if p->owner changes between two values
15238  ** that are not equal to self while the comparison is taking place.
15239  ** This implementation also assumes a coherent cache - that
15240  ** separate processes cannot read different values from the same
15241  ** address at the same time.  If either of these two conditions
15242  ** are not met, then the mutexes will fail and problems will result.
15243  */
15244  {
15245    pthread_t self = pthread_self();
15246    if( p->nRef>0 && pthread_equal(p->owner, self) ){
15247      p->nRef++;
15248      rc = SQLITE_OK;
15249    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
15250      assert( p->nRef==0 );
15251      p->owner = self;
15252      p->nRef = 1;
15253      rc = SQLITE_OK;
15254    }else{
15255      rc = SQLITE_BUSY;
15256    }
15257  }
15258#else
15259  /* Use the built-in recursive mutexes if they are available.
15260  */
15261  if( pthread_mutex_trylock(&p->mutex)==0 ){
15262    p->owner = pthread_self();
15263    p->nRef++;
15264    rc = SQLITE_OK;
15265  }else{
15266    rc = SQLITE_BUSY;
15267  }
15268#endif
15269
15270#ifdef SQLITE_DEBUG
15271  if( rc==SQLITE_OK && p->trace ){
15272    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15273  }
15274#endif
15275  return rc;
15276}
15277
15278/*
15279** The sqlite3_mutex_leave() routine exits a mutex that was
15280** previously entered by the same thread.  The behavior
15281** is undefined if the mutex is not currently entered or
15282** is not currently allocated.  SQLite will never do either.
15283*/
15284static void pthreadMutexLeave(sqlite3_mutex *p){
15285  assert( pthreadMutexHeld(p) );
15286  p->nRef--;
15287  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15288
15289#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15290  if( p->nRef==0 ){
15291    pthread_mutex_unlock(&p->mutex);
15292  }
15293#else
15294  pthread_mutex_unlock(&p->mutex);
15295#endif
15296
15297#ifdef SQLITE_DEBUG
15298  if( p->trace ){
15299    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15300  }
15301#endif
15302}
15303
15304SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15305  static sqlite3_mutex_methods sMutex = {
15306    pthreadMutexInit,
15307    pthreadMutexEnd,
15308    pthreadMutexAlloc,
15309    pthreadMutexFree,
15310    pthreadMutexEnter,
15311    pthreadMutexTry,
15312    pthreadMutexLeave,
15313#ifdef SQLITE_DEBUG
15314    pthreadMutexHeld,
15315    pthreadMutexNotheld
15316#else
15317    0,
15318    0
15319#endif
15320  };
15321
15322  return &sMutex;
15323}
15324
15325#endif /* SQLITE_MUTEX_PTHREAD */
15326
15327/************** End of mutex_unix.c ******************************************/
15328/************** Begin file mutex_w32.c ***************************************/
15329/*
15330** 2007 August 14
15331**
15332** The author disclaims copyright to this source code.  In place of
15333** a legal notice, here is a blessing:
15334**
15335**    May you do good and not evil.
15336**    May you find forgiveness for yourself and forgive others.
15337**    May you share freely, never taking more than you give.
15338**
15339*************************************************************************
15340** This file contains the C functions that implement mutexes for win32
15341*/
15342
15343/*
15344** The code in this file is only used if we are compiling multithreaded
15345** on a win32 system.
15346*/
15347#ifdef SQLITE_MUTEX_W32
15348
15349/*
15350** Each recursive mutex is an instance of the following structure.
15351*/
15352struct sqlite3_mutex {
15353  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
15354  int id;                    /* Mutex type */
15355  int nRef;                  /* Number of enterances */
15356  DWORD owner;               /* Thread holding this mutex */
15357};
15358
15359/*
15360** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
15361** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
15362**
15363** Here is an interesting observation:  Win95, Win98, and WinME lack
15364** the LockFileEx() API.  But we can still statically link against that
15365** API as long as we don't call it win running Win95/98/ME.  A call to
15366** this routine is used to determine if the host is Win95/98/ME or
15367** WinNT/2K/XP so that we will know whether or not we can safely call
15368** the LockFileEx() API.
15369**
15370** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
15371** which is only available if your application was compiled with
15372** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
15373** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
15374** this out as well.
15375*/
15376#if 0
15377#if SQLITE_OS_WINCE
15378# define mutexIsNT()  (1)
15379#else
15380  static int mutexIsNT(void){
15381    static int osType = 0;
15382    if( osType==0 ){
15383      OSVERSIONINFO sInfo;
15384      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
15385      GetVersionEx(&sInfo);
15386      osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
15387    }
15388    return osType==2;
15389  }
15390#endif /* SQLITE_OS_WINCE */
15391#endif
15392
15393#ifdef SQLITE_DEBUG
15394/*
15395** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15396** intended for use only inside assert() statements.
15397*/
15398static int winMutexHeld(sqlite3_mutex *p){
15399  return p->nRef!=0 && p->owner==GetCurrentThreadId();
15400}
15401static int winMutexNotheld(sqlite3_mutex *p){
15402  return p->nRef==0 || p->owner!=GetCurrentThreadId();
15403}
15404#endif
15405
15406
15407/*
15408** Initialize and deinitialize the mutex subsystem.
15409*/
15410static sqlite3_mutex winMutex_staticMutexes[6];
15411static int winMutex_isInit = 0;
15412/* As winMutexInit() and winMutexEnd() are called as part
15413** of the sqlite3_initialize and sqlite3_shutdown()
15414** processing, the "interlocked" magic is probably not
15415** strictly necessary.
15416*/
15417static long winMutex_lock = 0;
15418
15419static int winMutexInit(void){
15420  /* The first to increment to 1 does actual initialization */
15421  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
15422    int i;
15423    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
15424      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
15425    }
15426    winMutex_isInit = 1;
15427  }else{
15428    /* Someone else is in the process of initing the static mutexes */
15429    while( !winMutex_isInit ){
15430      Sleep(1);
15431    }
15432  }
15433  return SQLITE_OK;
15434}
15435
15436static int winMutexEnd(void){
15437  /* The first to decrement to 0 does actual shutdown
15438  ** (which should be the last to shutdown.) */
15439  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
15440    if( winMutex_isInit==1 ){
15441      int i;
15442      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
15443        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
15444      }
15445      winMutex_isInit = 0;
15446    }
15447  }
15448  return SQLITE_OK;
15449}
15450
15451/*
15452** The sqlite3_mutex_alloc() routine allocates a new
15453** mutex and returns a pointer to it.  If it returns NULL
15454** that means that a mutex could not be allocated.  SQLite
15455** will unwind its stack and return an error.  The argument
15456** to sqlite3_mutex_alloc() is one of these integer constants:
15457**
15458** <ul>
15459** <li>  SQLITE_MUTEX_FAST
15460** <li>  SQLITE_MUTEX_RECURSIVE
15461** <li>  SQLITE_MUTEX_STATIC_MASTER
15462** <li>  SQLITE_MUTEX_STATIC_MEM
15463** <li>  SQLITE_MUTEX_STATIC_MEM2
15464** <li>  SQLITE_MUTEX_STATIC_PRNG
15465** <li>  SQLITE_MUTEX_STATIC_LRU
15466** <li>  SQLITE_MUTEX_STATIC_LRU2
15467** </ul>
15468**
15469** The first two constants cause sqlite3_mutex_alloc() to create
15470** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15471** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15472** The mutex implementation does not need to make a distinction
15473** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15474** not want to.  But SQLite will only request a recursive mutex in
15475** cases where it really needs one.  If a faster non-recursive mutex
15476** implementation is available on the host platform, the mutex subsystem
15477** might return such a mutex in response to SQLITE_MUTEX_FAST.
15478**
15479** The other allowed parameters to sqlite3_mutex_alloc() each return
15480** a pointer to a static preexisting mutex.  Six static mutexes are
15481** used by the current version of SQLite.  Future versions of SQLite
15482** may add additional static mutexes.  Static mutexes are for internal
15483** use by SQLite only.  Applications that use SQLite mutexes should
15484** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15485** SQLITE_MUTEX_RECURSIVE.
15486**
15487** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15488** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15489** returns a different mutex on every call.  But for the static
15490** mutex types, the same mutex is returned on every call that has
15491** the same type number.
15492*/
15493static sqlite3_mutex *winMutexAlloc(int iType){
15494  sqlite3_mutex *p;
15495
15496  switch( iType ){
15497    case SQLITE_MUTEX_FAST:
15498    case SQLITE_MUTEX_RECURSIVE: {
15499      p = sqlite3MallocZero( sizeof(*p) );
15500      if( p ){
15501        p->id = iType;
15502        InitializeCriticalSection(&p->mutex);
15503      }
15504      break;
15505    }
15506    default: {
15507      assert( winMutex_isInit==1 );
15508      assert( iType-2 >= 0 );
15509      assert( iType-2 < ArraySize(winMutex_staticMutexes) );
15510      p = &winMutex_staticMutexes[iType-2];
15511      p->id = iType;
15512      break;
15513    }
15514  }
15515  return p;
15516}
15517
15518
15519/*
15520** This routine deallocates a previously
15521** allocated mutex.  SQLite is careful to deallocate every
15522** mutex that it allocates.
15523*/
15524static void winMutexFree(sqlite3_mutex *p){
15525  assert( p );
15526  assert( p->nRef==0 );
15527  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15528  DeleteCriticalSection(&p->mutex);
15529  sqlite3_free(p);
15530}
15531
15532/*
15533** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15534** to enter a mutex.  If another thread is already within the mutex,
15535** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15536** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15537** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15538** be entered multiple times by the same thread.  In such cases the,
15539** mutex must be exited an equal number of times before another thread
15540** can enter.  If the same thread tries to enter any other kind of mutex
15541** more than once, the behavior is undefined.
15542*/
15543static void winMutexEnter(sqlite3_mutex *p){
15544  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15545  EnterCriticalSection(&p->mutex);
15546  p->owner = GetCurrentThreadId();
15547  p->nRef++;
15548}
15549static int winMutexTry(sqlite3_mutex *p){
15550  int rc = SQLITE_BUSY;
15551  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15552  /*
15553  ** The sqlite3_mutex_try() routine is very rarely used, and when it
15554  ** is used it is merely an optimization.  So it is OK for it to always
15555  ** fail.
15556  **
15557  ** The TryEnterCriticalSection() interface is only available on WinNT.
15558  ** And some windows compilers complain if you try to use it without
15559  ** first doing some #defines that prevent SQLite from building on Win98.
15560  ** For that reason, we will omit this optimization for now.  See
15561  ** ticket #2685.
15562  */
15563#if 0
15564  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
15565    p->owner = GetCurrentThreadId();
15566    p->nRef++;
15567    rc = SQLITE_OK;
15568  }
15569#else
15570  UNUSED_PARAMETER(p);
15571#endif
15572  return rc;
15573}
15574
15575/*
15576** The sqlite3_mutex_leave() routine exits a mutex that was
15577** previously entered by the same thread.  The behavior
15578** is undefined if the mutex is not currently entered or
15579** is not currently allocated.  SQLite will never do either.
15580*/
15581static void winMutexLeave(sqlite3_mutex *p){
15582  assert( p->nRef>0 );
15583  assert( p->owner==GetCurrentThreadId() );
15584  p->nRef--;
15585  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15586  LeaveCriticalSection(&p->mutex);
15587}
15588
15589SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15590  static sqlite3_mutex_methods sMutex = {
15591    winMutexInit,
15592    winMutexEnd,
15593    winMutexAlloc,
15594    winMutexFree,
15595    winMutexEnter,
15596    winMutexTry,
15597    winMutexLeave,
15598#ifdef SQLITE_DEBUG
15599    winMutexHeld,
15600    winMutexNotheld
15601#else
15602    0,
15603    0
15604#endif
15605  };
15606
15607  return &sMutex;
15608}
15609#endif /* SQLITE_MUTEX_W32 */
15610
15611/************** End of mutex_w32.c *******************************************/
15612/************** Begin file malloc.c ******************************************/
15613/*
15614** 2001 September 15
15615**
15616** The author disclaims copyright to this source code.  In place of
15617** a legal notice, here is a blessing:
15618**
15619**    May you do good and not evil.
15620**    May you find forgiveness for yourself and forgive others.
15621**    May you share freely, never taking more than you give.
15622**
15623*************************************************************************
15624**
15625** Memory allocation functions used throughout sqlite.
15626*/
15627
15628/*
15629** This routine runs when the memory allocator sees that the
15630** total memory allocation is about to exceed the soft heap
15631** limit.
15632*/
15633static void softHeapLimitEnforcer(
15634  void *NotUsed,
15635  sqlite3_int64 NotUsed2,
15636  int allocSize
15637){
15638  UNUSED_PARAMETER2(NotUsed, NotUsed2);
15639  sqlite3_release_memory(allocSize);
15640}
15641
15642/*
15643** Set the soft heap-size limit for the library. Passing a zero or
15644** negative value indicates no limit.
15645*/
15646SQLITE_API void sqlite3_soft_heap_limit(int n){
15647  sqlite3_uint64 iLimit;
15648  int overage;
15649  if( n<0 ){
15650    iLimit = 0;
15651  }else{
15652    iLimit = n;
15653  }
15654#ifndef SQLITE_OMIT_AUTOINIT
15655  sqlite3_initialize();
15656#endif
15657  if( iLimit>0 ){
15658    sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
15659  }else{
15660    sqlite3MemoryAlarm(0, 0, 0);
15661  }
15662  overage = (int)(sqlite3_memory_used() - (i64)n);
15663  if( overage>0 ){
15664    sqlite3_release_memory(overage);
15665  }
15666}
15667
15668/*
15669** Attempt to release up to n bytes of non-essential memory currently
15670** held by SQLite. An example of non-essential memory is memory used to
15671** cache database pages that are not currently in use.
15672*/
15673SQLITE_API int sqlite3_release_memory(int n){
15674#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
15675  int nRet = 0;
15676  nRet += sqlite3PcacheReleaseMemory(n-nRet);
15677  return nRet;
15678#else
15679  UNUSED_PARAMETER(n);
15680  return SQLITE_OK;
15681#endif
15682}
15683
15684/*
15685** State information local to the memory allocation subsystem.
15686*/
15687static SQLITE_WSD struct Mem0Global {
15688  /* Number of free pages for scratch and page-cache memory */
15689  u32 nScratchFree;
15690  u32 nPageFree;
15691
15692  sqlite3_mutex *mutex;         /* Mutex to serialize access */
15693
15694  /*
15695  ** The alarm callback and its arguments.  The mem0.mutex lock will
15696  ** be held while the callback is running.  Recursive calls into
15697  ** the memory subsystem are allowed, but no new callbacks will be
15698  ** issued.
15699  */
15700  sqlite3_int64 alarmThreshold;
15701  void (*alarmCallback)(void*, sqlite3_int64,int);
15702  void *alarmArg;
15703
15704  /*
15705  ** Pointers to the end of sqlite3GlobalConfig.pScratch and
15706  ** sqlite3GlobalConfig.pPage to a block of memory that records
15707  ** which pages are available.
15708  */
15709  u32 *aScratchFree;
15710  u32 *aPageFree;
15711} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
15712
15713#define mem0 GLOBAL(struct Mem0Global, mem0)
15714
15715/*
15716** Initialize the memory allocation subsystem.
15717*/
15718SQLITE_PRIVATE int sqlite3MallocInit(void){
15719  if( sqlite3GlobalConfig.m.xMalloc==0 ){
15720    sqlite3MemSetDefault();
15721  }
15722  memset(&mem0, 0, sizeof(mem0));
15723  if( sqlite3GlobalConfig.bCoreMutex ){
15724    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15725  }
15726  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
15727      && sqlite3GlobalConfig.nScratch>=0 ){
15728    int i;
15729    sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
15730    mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
15731                  [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
15732    for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
15733    mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
15734  }else{
15735    sqlite3GlobalConfig.pScratch = 0;
15736    sqlite3GlobalConfig.szScratch = 0;
15737  }
15738  if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
15739      && sqlite3GlobalConfig.nPage>=1 ){
15740    int i;
15741    int overhead;
15742    int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
15743    int n = sqlite3GlobalConfig.nPage;
15744    overhead = (4*n + sz - 1)/sz;
15745    sqlite3GlobalConfig.nPage -= overhead;
15746    mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
15747                  [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
15748    for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
15749    mem0.nPageFree = sqlite3GlobalConfig.nPage;
15750  }else{
15751    sqlite3GlobalConfig.pPage = 0;
15752    sqlite3GlobalConfig.szPage = 0;
15753  }
15754  return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
15755}
15756
15757/*
15758** Deinitialize the memory allocation subsystem.
15759*/
15760SQLITE_PRIVATE void sqlite3MallocEnd(void){
15761  if( sqlite3GlobalConfig.m.xShutdown ){
15762    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
15763  }
15764  memset(&mem0, 0, sizeof(mem0));
15765}
15766
15767/*
15768** Return the amount of memory currently checked out.
15769*/
15770SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
15771  int n, mx;
15772  sqlite3_int64 res;
15773  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
15774  res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
15775  return res;
15776}
15777
15778/*
15779** Return the maximum amount of memory that has ever been
15780** checked out since either the beginning of this process
15781** or since the most recent reset.
15782*/
15783SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
15784  int n, mx;
15785  sqlite3_int64 res;
15786  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
15787  res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
15788  return res;
15789}
15790
15791/*
15792** Change the alarm callback
15793*/
15794SQLITE_PRIVATE int sqlite3MemoryAlarm(
15795  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
15796  void *pArg,
15797  sqlite3_int64 iThreshold
15798){
15799  sqlite3_mutex_enter(mem0.mutex);
15800  mem0.alarmCallback = xCallback;
15801  mem0.alarmArg = pArg;
15802  mem0.alarmThreshold = iThreshold;
15803  sqlite3_mutex_leave(mem0.mutex);
15804  return SQLITE_OK;
15805}
15806
15807#ifndef SQLITE_OMIT_DEPRECATED
15808/*
15809** Deprecated external interface.  Internal/core SQLite code
15810** should call sqlite3MemoryAlarm.
15811*/
15812SQLITE_API int sqlite3_memory_alarm(
15813  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
15814  void *pArg,
15815  sqlite3_int64 iThreshold
15816){
15817  return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
15818}
15819#endif
15820
15821/*
15822** Trigger the alarm
15823*/
15824static void sqlite3MallocAlarm(int nByte){
15825  void (*xCallback)(void*,sqlite3_int64,int);
15826  sqlite3_int64 nowUsed;
15827  void *pArg;
15828  if( mem0.alarmCallback==0 ) return;
15829  xCallback = mem0.alarmCallback;
15830  nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
15831  pArg = mem0.alarmArg;
15832  mem0.alarmCallback = 0;
15833  sqlite3_mutex_leave(mem0.mutex);
15834  xCallback(pArg, nowUsed, nByte);
15835  sqlite3_mutex_enter(mem0.mutex);
15836  mem0.alarmCallback = xCallback;
15837  mem0.alarmArg = pArg;
15838}
15839
15840/*
15841** Do a memory allocation with statistics and alarms.  Assume the
15842** lock is already held.
15843*/
15844static int mallocWithAlarm(int n, void **pp){
15845  int nFull;
15846  void *p;
15847  assert( sqlite3_mutex_held(mem0.mutex) );
15848  nFull = sqlite3GlobalConfig.m.xRoundup(n);
15849  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
15850  if( mem0.alarmCallback!=0 ){
15851    int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
15852    if( nUsed+nFull >= mem0.alarmThreshold ){
15853      sqlite3MallocAlarm(nFull);
15854    }
15855  }
15856  p = sqlite3GlobalConfig.m.xMalloc(nFull);
15857  if( p==0 && mem0.alarmCallback ){
15858    sqlite3MallocAlarm(nFull);
15859    p = sqlite3GlobalConfig.m.xMalloc(nFull);
15860  }
15861  if( p ){
15862    nFull = sqlite3MallocSize(p);
15863    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
15864  }
15865  *pp = p;
15866  return nFull;
15867}
15868
15869/*
15870** Allocate memory.  This routine is like sqlite3_malloc() except that it
15871** assumes the memory subsystem has already been initialized.
15872*/
15873SQLITE_PRIVATE void *sqlite3Malloc(int n){
15874  void *p;
15875  if( n<=0 || n>=0x7fffff00 ){
15876    /* A memory allocation of a number of bytes which is near the maximum
15877    ** signed integer value might cause an integer overflow inside of the
15878    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
15879    ** 255 bytes of overhead.  SQLite itself will never use anything near
15880    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
15881    p = 0;
15882  }else if( sqlite3GlobalConfig.bMemstat ){
15883    sqlite3_mutex_enter(mem0.mutex);
15884    mallocWithAlarm(n, &p);
15885    sqlite3_mutex_leave(mem0.mutex);
15886  }else{
15887    p = sqlite3GlobalConfig.m.xMalloc(n);
15888  }
15889  return p;
15890}
15891
15892/*
15893** This version of the memory allocation is for use by the application.
15894** First make sure the memory subsystem is initialized, then do the
15895** allocation.
15896*/
15897SQLITE_API void *sqlite3_malloc(int n){
15898#ifndef SQLITE_OMIT_AUTOINIT
15899  if( sqlite3_initialize() ) return 0;
15900#endif
15901  return sqlite3Malloc(n);
15902}
15903
15904/*
15905** Each thread may only have a single outstanding allocation from
15906** xScratchMalloc().  We verify this constraint in the single-threaded
15907** case by setting scratchAllocOut to 1 when an allocation
15908** is outstanding clearing it when the allocation is freed.
15909*/
15910#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15911static int scratchAllocOut = 0;
15912#endif
15913
15914
15915/*
15916** Allocate memory that is to be used and released right away.
15917** This routine is similar to alloca() in that it is not intended
15918** for situations where the memory might be held long-term.  This
15919** routine is intended to get memory to old large transient data
15920** structures that would not normally fit on the stack of an
15921** embedded processor.
15922*/
15923SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
15924  void *p;
15925  assert( n>0 );
15926
15927#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15928  /* Verify that no more than one scratch allocation per thread
15929  ** is outstanding at one time.  (This is only checked in the
15930  ** single-threaded case since checking in the multi-threaded case
15931  ** would be much more complicated.) */
15932  assert( scratchAllocOut==0 );
15933#endif
15934
15935  if( sqlite3GlobalConfig.szScratch<n ){
15936    goto scratch_overflow;
15937  }else{
15938    sqlite3_mutex_enter(mem0.mutex);
15939    if( mem0.nScratchFree==0 ){
15940      sqlite3_mutex_leave(mem0.mutex);
15941      goto scratch_overflow;
15942    }else{
15943      int i;
15944      i = mem0.aScratchFree[--mem0.nScratchFree];
15945      i *= sqlite3GlobalConfig.szScratch;
15946      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
15947      sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
15948      sqlite3_mutex_leave(mem0.mutex);
15949      p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
15950      assert(  (((u8*)p - (u8*)0) & 7)==0 );
15951    }
15952  }
15953#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15954  scratchAllocOut = p!=0;
15955#endif
15956
15957  return p;
15958
15959scratch_overflow:
15960  if( sqlite3GlobalConfig.bMemstat ){
15961    sqlite3_mutex_enter(mem0.mutex);
15962    sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
15963    n = mallocWithAlarm(n, &p);
15964    if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
15965    sqlite3_mutex_leave(mem0.mutex);
15966  }else{
15967    p = sqlite3GlobalConfig.m.xMalloc(n);
15968  }
15969#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15970  scratchAllocOut = p!=0;
15971#endif
15972  return p;
15973}
15974SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
15975  if( p ){
15976
15977#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15978    /* Verify that no more than one scratch allocation per thread
15979    ** is outstanding at one time.  (This is only checked in the
15980    ** single-threaded case since checking in the multi-threaded case
15981    ** would be much more complicated.) */
15982    assert( scratchAllocOut==1 );
15983    scratchAllocOut = 0;
15984#endif
15985
15986    if( sqlite3GlobalConfig.pScratch==0
15987           || p<sqlite3GlobalConfig.pScratch
15988           || p>=(void*)mem0.aScratchFree ){
15989      if( sqlite3GlobalConfig.bMemstat ){
15990        int iSize = sqlite3MallocSize(p);
15991        sqlite3_mutex_enter(mem0.mutex);
15992        sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
15993        sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
15994        sqlite3GlobalConfig.m.xFree(p);
15995        sqlite3_mutex_leave(mem0.mutex);
15996      }else{
15997        sqlite3GlobalConfig.m.xFree(p);
15998      }
15999    }else{
16000      int i;
16001      i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
16002      i /= sqlite3GlobalConfig.szScratch;
16003      assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
16004      sqlite3_mutex_enter(mem0.mutex);
16005      assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
16006      mem0.aScratchFree[mem0.nScratchFree++] = i;
16007      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
16008      sqlite3_mutex_leave(mem0.mutex);
16009    }
16010  }
16011}
16012
16013/*
16014** TRUE if p is a lookaside memory allocation from db
16015*/
16016#ifndef SQLITE_OMIT_LOOKASIDE
16017static int isLookaside(sqlite3 *db, void *p){
16018  return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
16019}
16020#else
16021#define isLookaside(A,B) 0
16022#endif
16023
16024/*
16025** Return the size of a memory allocation previously obtained from
16026** sqlite3Malloc() or sqlite3_malloc().
16027*/
16028SQLITE_PRIVATE int sqlite3MallocSize(void *p){
16029  return sqlite3GlobalConfig.m.xSize(p);
16030}
16031SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
16032  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16033  if( isLookaside(db, p) ){
16034    return db->lookaside.sz;
16035  }else{
16036    return sqlite3GlobalConfig.m.xSize(p);
16037  }
16038}
16039
16040/*
16041** Free memory previously obtained from sqlite3Malloc().
16042*/
16043SQLITE_API void sqlite3_free(void *p){
16044  if( p==0 ) return;
16045  if( sqlite3GlobalConfig.bMemstat ){
16046    sqlite3_mutex_enter(mem0.mutex);
16047    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
16048    sqlite3GlobalConfig.m.xFree(p);
16049    sqlite3_mutex_leave(mem0.mutex);
16050  }else{
16051    sqlite3GlobalConfig.m.xFree(p);
16052  }
16053}
16054
16055/*
16056** Free memory that might be associated with a particular database
16057** connection.
16058*/
16059SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
16060  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16061  if( isLookaside(db, p) ){
16062    LookasideSlot *pBuf = (LookasideSlot*)p;
16063    pBuf->pNext = db->lookaside.pFree;
16064    db->lookaside.pFree = pBuf;
16065    db->lookaside.nOut--;
16066  }else{
16067    sqlite3_free(p);
16068  }
16069}
16070
16071/*
16072** Change the size of an existing memory allocation
16073*/
16074SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
16075  int nOld, nNew;
16076  void *pNew;
16077  if( pOld==0 ){
16078    return sqlite3Malloc(nBytes);
16079  }
16080  if( nBytes<=0 ){
16081    sqlite3_free(pOld);
16082    return 0;
16083  }
16084  if( nBytes>=0x7fffff00 ){
16085    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
16086    return 0;
16087  }
16088  nOld = sqlite3MallocSize(pOld);
16089  nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
16090  if( nOld==nNew ){
16091    pNew = pOld;
16092  }else if( sqlite3GlobalConfig.bMemstat ){
16093    sqlite3_mutex_enter(mem0.mutex);
16094    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
16095    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
16096          mem0.alarmThreshold ){
16097      sqlite3MallocAlarm(nNew-nOld);
16098    }
16099    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16100    if( pNew==0 && mem0.alarmCallback ){
16101      sqlite3MallocAlarm(nBytes);
16102      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16103    }
16104    if( pNew ){
16105      nNew = sqlite3MallocSize(pNew);
16106      sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
16107    }
16108    sqlite3_mutex_leave(mem0.mutex);
16109  }else{
16110    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16111  }
16112  return pNew;
16113}
16114
16115/*
16116** The public interface to sqlite3Realloc.  Make sure that the memory
16117** subsystem is initialized prior to invoking sqliteRealloc.
16118*/
16119SQLITE_API void *sqlite3_realloc(void *pOld, int n){
16120#ifndef SQLITE_OMIT_AUTOINIT
16121  if( sqlite3_initialize() ) return 0;
16122#endif
16123  return sqlite3Realloc(pOld, n);
16124}
16125
16126
16127/*
16128** Allocate and zero memory.
16129*/
16130SQLITE_PRIVATE void *sqlite3MallocZero(int n){
16131  void *p = sqlite3Malloc(n);
16132  if( p ){
16133    memset(p, 0, n);
16134  }
16135  return p;
16136}
16137
16138/*
16139** Allocate and zero memory.  If the allocation fails, make
16140** the mallocFailed flag in the connection pointer.
16141*/
16142SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
16143  void *p = sqlite3DbMallocRaw(db, n);
16144  if( p ){
16145    memset(p, 0, n);
16146  }
16147  return p;
16148}
16149
16150/*
16151** Allocate and zero memory.  If the allocation fails, make
16152** the mallocFailed flag in the connection pointer.
16153**
16154** If db!=0 and db->mallocFailed is true (indicating a prior malloc
16155** failure on the same database connection) then always return 0.
16156** Hence for a particular database connection, once malloc starts
16157** failing, it fails consistently until mallocFailed is reset.
16158** This is an important assumption.  There are many places in the
16159** code that do things like this:
16160**
16161**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
16162**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
16163**         if( b ) a[10] = 9;
16164**
16165** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
16166** that all prior mallocs (ex: "a") worked too.
16167*/
16168SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
16169  void *p;
16170  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16171#ifndef SQLITE_OMIT_LOOKASIDE
16172  if( db ){
16173    LookasideSlot *pBuf;
16174    if( db->mallocFailed ){
16175      return 0;
16176    }
16177    if( db->lookaside.bEnabled && n<=db->lookaside.sz
16178         && (pBuf = db->lookaside.pFree)!=0 ){
16179      db->lookaside.pFree = pBuf->pNext;
16180      db->lookaside.nOut++;
16181      if( db->lookaside.nOut>db->lookaside.mxOut ){
16182        db->lookaside.mxOut = db->lookaside.nOut;
16183      }
16184      return (void*)pBuf;
16185    }
16186  }
16187#else
16188  if( db && db->mallocFailed ){
16189    return 0;
16190  }
16191#endif
16192  p = sqlite3Malloc(n);
16193  if( !p && db ){
16194    db->mallocFailed = 1;
16195  }
16196  return p;
16197}
16198
16199/*
16200** Resize the block of memory pointed to by p to n bytes. If the
16201** resize fails, set the mallocFailed flag in the connection object.
16202*/
16203SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
16204  void *pNew = 0;
16205  assert( db!=0 );
16206  assert( sqlite3_mutex_held(db->mutex) );
16207  if( db->mallocFailed==0 ){
16208    if( p==0 ){
16209      return sqlite3DbMallocRaw(db, n);
16210    }
16211    if( isLookaside(db, p) ){
16212      if( n<=db->lookaside.sz ){
16213        return p;
16214      }
16215      pNew = sqlite3DbMallocRaw(db, n);
16216      if( pNew ){
16217        memcpy(pNew, p, db->lookaside.sz);
16218        sqlite3DbFree(db, p);
16219      }
16220    }else{
16221      pNew = sqlite3_realloc(p, n);
16222      if( !pNew ){
16223        db->mallocFailed = 1;
16224      }
16225    }
16226  }
16227  return pNew;
16228}
16229
16230/*
16231** Attempt to reallocate p.  If the reallocation fails, then free p
16232** and set the mallocFailed flag in the database connection.
16233*/
16234SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
16235  void *pNew;
16236  pNew = sqlite3DbRealloc(db, p, n);
16237  if( !pNew ){
16238    sqlite3DbFree(db, p);
16239  }
16240  return pNew;
16241}
16242
16243/*
16244** Make a copy of a string in memory obtained from sqliteMalloc(). These
16245** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
16246** is because when memory debugging is turned on, these two functions are
16247** called via macros that record the current file and line number in the
16248** ThreadData structure.
16249*/
16250SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
16251  char *zNew;
16252  size_t n;
16253  if( z==0 ){
16254    return 0;
16255  }
16256  n = sqlite3Strlen30(z) + 1;
16257  assert( (n&0x7fffffff)==n );
16258  zNew = sqlite3DbMallocRaw(db, (int)n);
16259  if( zNew ){
16260    memcpy(zNew, z, n);
16261  }
16262  return zNew;
16263}
16264SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
16265  char *zNew;
16266  if( z==0 ){
16267    return 0;
16268  }
16269  assert( (n&0x7fffffff)==n );
16270  zNew = sqlite3DbMallocRaw(db, n+1);
16271  if( zNew ){
16272    memcpy(zNew, z, n);
16273    zNew[n] = 0;
16274  }
16275  return zNew;
16276}
16277
16278/*
16279** Create a string from the zFromat argument and the va_list that follows.
16280** Store the string in memory obtained from sqliteMalloc() and make *pz
16281** point to that string.
16282*/
16283SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
16284  va_list ap;
16285  char *z;
16286
16287  va_start(ap, zFormat);
16288  z = sqlite3VMPrintf(db, zFormat, ap);
16289  va_end(ap);
16290  sqlite3DbFree(db, *pz);
16291  *pz = z;
16292}
16293
16294
16295/*
16296** This function must be called before exiting any API function (i.e.
16297** returning control to the user) that has called sqlite3_malloc or
16298** sqlite3_realloc.
16299**
16300** The returned value is normally a copy of the second argument to this
16301** function. However, if a malloc() failure has occurred since the previous
16302** invocation SQLITE_NOMEM is returned instead.
16303**
16304** If the first argument, db, is not NULL and a malloc() error has occurred,
16305** then the connection error-code (the value returned by sqlite3_errcode())
16306** is set to SQLITE_NOMEM.
16307*/
16308SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
16309  /* If the db handle is not NULL, then we must hold the connection handle
16310  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
16311  ** is unsafe, as is the call to sqlite3Error().
16312  */
16313  assert( !db || sqlite3_mutex_held(db->mutex) );
16314  if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
16315    sqlite3Error(db, SQLITE_NOMEM, 0);
16316    db->mallocFailed = 0;
16317    rc = SQLITE_NOMEM;
16318  }
16319  return rc & (db ? db->errMask : 0xff);
16320}
16321
16322/************** End of malloc.c **********************************************/
16323/************** Begin file printf.c ******************************************/
16324/*
16325** The "printf" code that follows dates from the 1980's.  It is in
16326** the public domain.  The original comments are included here for
16327** completeness.  They are very out-of-date but might be useful as
16328** an historical reference.  Most of the "enhancements" have been backed
16329** out so that the functionality is now the same as standard printf().
16330**
16331**************************************************************************
16332**
16333** The following modules is an enhanced replacement for the "printf" subroutines
16334** found in the standard C library.  The following enhancements are
16335** supported:
16336**
16337**      +  Additional functions.  The standard set of "printf" functions
16338**         includes printf, fprintf, sprintf, vprintf, vfprintf, and
16339**         vsprintf.  This module adds the following:
16340**
16341**           *  snprintf -- Works like sprintf, but has an extra argument
16342**                          which is the size of the buffer written to.
16343**
16344**           *  mprintf --  Similar to sprintf.  Writes output to memory
16345**                          obtained from malloc.
16346**
16347**           *  xprintf --  Calls a function to dispose of output.
16348**
16349**           *  nprintf --  No output, but returns the number of characters
16350**                          that would have been output by printf.
16351**
16352**           *  A v- version (ex: vsnprintf) of every function is also
16353**              supplied.
16354**
16355**      +  A few extensions to the formatting notation are supported:
16356**
16357**           *  The "=" flag (similar to "-") causes the output to be
16358**              be centered in the appropriately sized field.
16359**
16360**           *  The %b field outputs an integer in binary notation.
16361**
16362**           *  The %c field now accepts a precision.  The character output
16363**              is repeated by the number of times the precision specifies.
16364**
16365**           *  The %' field works like %c, but takes as its character the
16366**              next character of the format string, instead of the next
16367**              argument.  For example,  printf("%.78'-")  prints 78 minus
16368**              signs, the same as  printf("%.78c",'-').
16369**
16370**      +  When compiled using GCC on a SPARC, this version of printf is
16371**         faster than the library printf for SUN OS 4.1.
16372**
16373**      +  All functions are fully reentrant.
16374**
16375*/
16376
16377/*
16378** Conversion types fall into various categories as defined by the
16379** following enumeration.
16380*/
16381#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
16382#define etFLOAT       2 /* Floating point.  %f */
16383#define etEXP         3 /* Exponentional notation. %e and %E */
16384#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
16385#define etSIZE        5 /* Return number of characters processed so far. %n */
16386#define etSTRING      6 /* Strings. %s */
16387#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
16388#define etPERCENT     8 /* Percent symbol. %% */
16389#define etCHARX       9 /* Characters. %c */
16390/* The rest are extensions, not normally found in printf() */
16391#define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
16392#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
16393                          NULL pointers replaced by SQL NULL.  %Q */
16394#define etTOKEN      12 /* a pointer to a Token structure */
16395#define etSRCLIST    13 /* a pointer to a SrcList */
16396#define etPOINTER    14 /* The %p conversion */
16397#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
16398#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
16399
16400#define etINVALID     0 /* Any unrecognized conversion type */
16401
16402
16403/*
16404** An "etByte" is an 8-bit unsigned value.
16405*/
16406typedef unsigned char etByte;
16407
16408/*
16409** Each builtin conversion character (ex: the 'd' in "%d") is described
16410** by an instance of the following structure
16411*/
16412typedef struct et_info {   /* Information about each format field */
16413  char fmttype;            /* The format field code letter */
16414  etByte base;             /* The base for radix conversion */
16415  etByte flags;            /* One or more of FLAG_ constants below */
16416  etByte type;             /* Conversion paradigm */
16417  etByte charset;          /* Offset into aDigits[] of the digits string */
16418  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
16419} et_info;
16420
16421/*
16422** Allowed values for et_info.flags
16423*/
16424#define FLAG_SIGNED  1     /* True if the value to convert is signed */
16425#define FLAG_INTERN  2     /* True if for internal use only */
16426#define FLAG_STRING  4     /* Allow infinity precision */
16427
16428
16429/*
16430** The following table is searched linearly, so it is good to put the
16431** most frequently used conversion types first.
16432*/
16433static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
16434static const char aPrefix[] = "-x0\000X0";
16435static const et_info fmtinfo[] = {
16436  {  'd', 10, 1, etRADIX,      0,  0 },
16437  {  's',  0, 4, etSTRING,     0,  0 },
16438  {  'g',  0, 1, etGENERIC,    30, 0 },
16439  {  'z',  0, 4, etDYNSTRING,  0,  0 },
16440  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
16441  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
16442  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
16443  {  'c',  0, 0, etCHARX,      0,  0 },
16444  {  'o',  8, 0, etRADIX,      0,  2 },
16445  {  'u', 10, 0, etRADIX,      0,  0 },
16446  {  'x', 16, 0, etRADIX,      16, 1 },
16447  {  'X', 16, 0, etRADIX,      0,  4 },
16448#ifndef SQLITE_OMIT_FLOATING_POINT
16449  {  'f',  0, 1, etFLOAT,      0,  0 },
16450  {  'e',  0, 1, etEXP,        30, 0 },
16451  {  'E',  0, 1, etEXP,        14, 0 },
16452  {  'G',  0, 1, etGENERIC,    14, 0 },
16453#endif
16454  {  'i', 10, 1, etRADIX,      0,  0 },
16455  {  'n',  0, 0, etSIZE,       0,  0 },
16456  {  '%',  0, 0, etPERCENT,    0,  0 },
16457  {  'p', 16, 0, etPOINTER,    0,  1 },
16458
16459/* All the rest have the FLAG_INTERN bit set and are thus for internal
16460** use only */
16461  {  'T',  0, 2, etTOKEN,      0,  0 },
16462  {  'S',  0, 2, etSRCLIST,    0,  0 },
16463  {  'r', 10, 3, etORDINAL,    0,  0 },
16464};
16465
16466/*
16467** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
16468** conversions will work.
16469*/
16470#ifndef SQLITE_OMIT_FLOATING_POINT
16471/*
16472** "*val" is a double such that 0.1 <= *val < 10.0
16473** Return the ascii code for the leading digit of *val, then
16474** multiply "*val" by 10.0 to renormalize.
16475**
16476** Example:
16477**     input:     *val = 3.14159
16478**     output:    *val = 1.4159    function return = '3'
16479**
16480** The counter *cnt is incremented each time.  After counter exceeds
16481** 16 (the number of significant digits in a 64-bit float) '0' is
16482** always returned.
16483*/
16484static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
16485  int digit;
16486  LONGDOUBLE_TYPE d;
16487  if( (*cnt)++ >= 16 ) return '0';
16488  digit = (int)*val;
16489  d = digit;
16490  digit += '0';
16491  *val = (*val - d)*10.0;
16492  return (char)digit;
16493}
16494#endif /* SQLITE_OMIT_FLOATING_POINT */
16495
16496/*
16497** Append N space characters to the given string buffer.
16498*/
16499static void appendSpace(StrAccum *pAccum, int N){
16500  static const char zSpaces[] = "                             ";
16501  while( N>=(int)sizeof(zSpaces)-1 ){
16502    sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
16503    N -= sizeof(zSpaces)-1;
16504  }
16505  if( N>0 ){
16506    sqlite3StrAccumAppend(pAccum, zSpaces, N);
16507  }
16508}
16509
16510/*
16511** On machines with a small stack size, you can redefine the
16512** SQLITE_PRINT_BUF_SIZE to be less than 350.
16513*/
16514#ifndef SQLITE_PRINT_BUF_SIZE
16515# if defined(SQLITE_SMALL_STACK)
16516#   define SQLITE_PRINT_BUF_SIZE 50
16517# else
16518#   define SQLITE_PRINT_BUF_SIZE 350
16519# endif
16520#endif
16521#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
16522
16523/*
16524** The root program.  All variations call this core.
16525**
16526** INPUTS:
16527**   func   This is a pointer to a function taking three arguments
16528**            1. A pointer to anything.  Same as the "arg" parameter.
16529**            2. A pointer to the list of characters to be output
16530**               (Note, this list is NOT null terminated.)
16531**            3. An integer number of characters to be output.
16532**               (Note: This number might be zero.)
16533**
16534**   arg    This is the pointer to anything which will be passed as the
16535**          first argument to "func".  Use it for whatever you like.
16536**
16537**   fmt    This is the format string, as in the usual print.
16538**
16539**   ap     This is a pointer to a list of arguments.  Same as in
16540**          vfprint.
16541**
16542** OUTPUTS:
16543**          The return value is the total number of characters sent to
16544**          the function "func".  Returns -1 on a error.
16545**
16546** Note that the order in which automatic variables are declared below
16547** seems to make a big difference in determining how fast this beast
16548** will run.
16549*/
16550SQLITE_PRIVATE void sqlite3VXPrintf(
16551  StrAccum *pAccum,                  /* Accumulate results here */
16552  int useExtended,                   /* Allow extended %-conversions */
16553  const char *fmt,                   /* Format string */
16554  va_list ap                         /* arguments */
16555){
16556  int c;                     /* Next character in the format string */
16557  char *bufpt;               /* Pointer to the conversion buffer */
16558  int precision;             /* Precision of the current field */
16559  int length;                /* Length of the field */
16560  int idx;                   /* A general purpose loop counter */
16561  int width;                 /* Width of the current field */
16562  etByte flag_leftjustify;   /* True if "-" flag is present */
16563  etByte flag_plussign;      /* True if "+" flag is present */
16564  etByte flag_blanksign;     /* True if " " flag is present */
16565  etByte flag_alternateform; /* True if "#" flag is present */
16566  etByte flag_altform2;      /* True if "!" flag is present */
16567  etByte flag_zeropad;       /* True if field width constant starts with zero */
16568  etByte flag_long;          /* True if "l" flag is present */
16569  etByte flag_longlong;      /* True if the "ll" flag is present */
16570  etByte done;               /* Loop termination flag */
16571  sqlite_uint64 longvalue;   /* Value for integer types */
16572  LONGDOUBLE_TYPE realvalue; /* Value for real types */
16573  const et_info *infop;      /* Pointer to the appropriate info structure */
16574  char buf[etBUFSIZE];       /* Conversion buffer */
16575  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
16576  etByte xtype = 0;          /* Conversion paradigm */
16577  char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
16578#ifndef SQLITE_OMIT_FLOATING_POINT
16579  int  exp, e2;              /* exponent of real numbers */
16580  double rounder;            /* Used for rounding floating point values */
16581  etByte flag_dp;            /* True if decimal point should be shown */
16582  etByte flag_rtz;           /* True if trailing zeros should be removed */
16583  etByte flag_exp;           /* True to force display of the exponent */
16584  int nsd;                   /* Number of significant digits returned */
16585#endif
16586
16587  length = 0;
16588  bufpt = 0;
16589  for(; (c=(*fmt))!=0; ++fmt){
16590    if( c!='%' ){
16591      int amt;
16592      bufpt = (char *)fmt;
16593      amt = 1;
16594      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
16595      sqlite3StrAccumAppend(pAccum, bufpt, amt);
16596      if( c==0 ) break;
16597    }
16598    if( (c=(*++fmt))==0 ){
16599      sqlite3StrAccumAppend(pAccum, "%", 1);
16600      break;
16601    }
16602    /* Find out what flags are present */
16603    flag_leftjustify = flag_plussign = flag_blanksign =
16604     flag_alternateform = flag_altform2 = flag_zeropad = 0;
16605    done = 0;
16606    do{
16607      switch( c ){
16608        case '-':   flag_leftjustify = 1;     break;
16609        case '+':   flag_plussign = 1;        break;
16610        case ' ':   flag_blanksign = 1;       break;
16611        case '#':   flag_alternateform = 1;   break;
16612        case '!':   flag_altform2 = 1;        break;
16613        case '0':   flag_zeropad = 1;         break;
16614        default:    done = 1;                 break;
16615      }
16616    }while( !done && (c=(*++fmt))!=0 );
16617    /* Get the field width */
16618    width = 0;
16619    if( c=='*' ){
16620      width = va_arg(ap,int);
16621      if( width<0 ){
16622        flag_leftjustify = 1;
16623        width = -width;
16624      }
16625      c = *++fmt;
16626    }else{
16627      while( c>='0' && c<='9' ){
16628        width = width*10 + c - '0';
16629        c = *++fmt;
16630      }
16631    }
16632    if( width > etBUFSIZE-10 ){
16633      width = etBUFSIZE-10;
16634    }
16635    /* Get the precision */
16636    if( c=='.' ){
16637      precision = 0;
16638      c = *++fmt;
16639      if( c=='*' ){
16640        precision = va_arg(ap,int);
16641        if( precision<0 ) precision = -precision;
16642        c = *++fmt;
16643      }else{
16644        while( c>='0' && c<='9' ){
16645          precision = precision*10 + c - '0';
16646          c = *++fmt;
16647        }
16648      }
16649    }else{
16650      precision = -1;
16651    }
16652    /* Get the conversion type modifier */
16653    if( c=='l' ){
16654      flag_long = 1;
16655      c = *++fmt;
16656      if( c=='l' ){
16657        flag_longlong = 1;
16658        c = *++fmt;
16659      }else{
16660        flag_longlong = 0;
16661      }
16662    }else{
16663      flag_long = flag_longlong = 0;
16664    }
16665    /* Fetch the info entry for the field */
16666    infop = &fmtinfo[0];
16667    xtype = etINVALID;
16668    for(idx=0; idx<ArraySize(fmtinfo); idx++){
16669      if( c==fmtinfo[idx].fmttype ){
16670        infop = &fmtinfo[idx];
16671        if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
16672          xtype = infop->type;
16673        }else{
16674          return;
16675        }
16676        break;
16677      }
16678    }
16679    zExtra = 0;
16680
16681
16682    /* Limit the precision to prevent overflowing buf[] during conversion */
16683    if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
16684      precision = etBUFSIZE-40;
16685    }
16686
16687    /*
16688    ** At this point, variables are initialized as follows:
16689    **
16690    **   flag_alternateform          TRUE if a '#' is present.
16691    **   flag_altform2               TRUE if a '!' is present.
16692    **   flag_plussign               TRUE if a '+' is present.
16693    **   flag_leftjustify            TRUE if a '-' is present or if the
16694    **                               field width was negative.
16695    **   flag_zeropad                TRUE if the width began with 0.
16696    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
16697    **                               the conversion character.
16698    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
16699    **                               the conversion character.
16700    **   flag_blanksign              TRUE if a ' ' is present.
16701    **   width                       The specified field width.  This is
16702    **                               always non-negative.  Zero is the default.
16703    **   precision                   The specified precision.  The default
16704    **                               is -1.
16705    **   xtype                       The class of the conversion.
16706    **   infop                       Pointer to the appropriate info struct.
16707    */
16708    switch( xtype ){
16709      case etPOINTER:
16710        flag_longlong = sizeof(char*)==sizeof(i64);
16711        flag_long = sizeof(char*)==sizeof(long int);
16712        /* Fall through into the next case */
16713      case etORDINAL:
16714      case etRADIX:
16715        if( infop->flags & FLAG_SIGNED ){
16716          i64 v;
16717          if( flag_longlong ){
16718            v = va_arg(ap,i64);
16719          }else if( flag_long ){
16720            v = va_arg(ap,long int);
16721          }else{
16722            v = va_arg(ap,int);
16723          }
16724          if( v<0 ){
16725            longvalue = -v;
16726            prefix = '-';
16727          }else{
16728            longvalue = v;
16729            if( flag_plussign )        prefix = '+';
16730            else if( flag_blanksign )  prefix = ' ';
16731            else                       prefix = 0;
16732          }
16733        }else{
16734          if( flag_longlong ){
16735            longvalue = va_arg(ap,u64);
16736          }else if( flag_long ){
16737            longvalue = va_arg(ap,unsigned long int);
16738          }else{
16739            longvalue = va_arg(ap,unsigned int);
16740          }
16741          prefix = 0;
16742        }
16743        if( longvalue==0 ) flag_alternateform = 0;
16744        if( flag_zeropad && precision<width-(prefix!=0) ){
16745          precision = width-(prefix!=0);
16746        }
16747        bufpt = &buf[etBUFSIZE-1];
16748        if( xtype==etORDINAL ){
16749          static const char zOrd[] = "thstndrd";
16750          int x = (int)(longvalue % 10);
16751          if( x>=4 || (longvalue/10)%10==1 ){
16752            x = 0;
16753          }
16754          buf[etBUFSIZE-3] = zOrd[x*2];
16755          buf[etBUFSIZE-2] = zOrd[x*2+1];
16756          bufpt -= 2;
16757        }
16758        {
16759          register const char *cset;      /* Use registers for speed */
16760          register int base;
16761          cset = &aDigits[infop->charset];
16762          base = infop->base;
16763          do{                                           /* Convert to ascii */
16764            *(--bufpt) = cset[longvalue%base];
16765            longvalue = longvalue/base;
16766          }while( longvalue>0 );
16767        }
16768        length = (int)(&buf[etBUFSIZE-1]-bufpt);
16769        for(idx=precision-length; idx>0; idx--){
16770          *(--bufpt) = '0';                             /* Zero pad */
16771        }
16772        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
16773        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
16774          const char *pre;
16775          char x;
16776          pre = &aPrefix[infop->prefix];
16777          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
16778        }
16779        length = (int)(&buf[etBUFSIZE-1]-bufpt);
16780        break;
16781      case etFLOAT:
16782      case etEXP:
16783      case etGENERIC:
16784        realvalue = va_arg(ap,double);
16785#ifndef SQLITE_OMIT_FLOATING_POINT
16786        if( precision<0 ) precision = 6;         /* Set default precision */
16787        if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
16788        if( realvalue<0.0 ){
16789          realvalue = -realvalue;
16790          prefix = '-';
16791        }else{
16792          if( flag_plussign )          prefix = '+';
16793          else if( flag_blanksign )    prefix = ' ';
16794          else                         prefix = 0;
16795        }
16796        if( xtype==etGENERIC && precision>0 ) precision--;
16797#if 0
16798        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
16799        for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
16800#else
16801        /* It makes more sense to use 0.5 */
16802        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
16803#endif
16804        if( xtype==etFLOAT ) realvalue += rounder;
16805        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
16806        exp = 0;
16807        if( sqlite3IsNaN((double)realvalue) ){
16808          bufpt = "NaN";
16809          length = 3;
16810          break;
16811        }
16812        if( realvalue>0.0 ){
16813          while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
16814          while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
16815          while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
16816          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
16817          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
16818          if( exp>350 ){
16819            if( prefix=='-' ){
16820              bufpt = "-Inf";
16821            }else if( prefix=='+' ){
16822              bufpt = "+Inf";
16823            }else{
16824              bufpt = "Inf";
16825            }
16826            length = sqlite3Strlen30(bufpt);
16827            break;
16828          }
16829        }
16830        bufpt = buf;
16831        /*
16832        ** If the field type is etGENERIC, then convert to either etEXP
16833        ** or etFLOAT, as appropriate.
16834        */
16835        flag_exp = xtype==etEXP;
16836        if( xtype!=etFLOAT ){
16837          realvalue += rounder;
16838          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
16839        }
16840        if( xtype==etGENERIC ){
16841          flag_rtz = !flag_alternateform;
16842          if( exp<-4 || exp>precision ){
16843            xtype = etEXP;
16844          }else{
16845            precision = precision - exp;
16846            xtype = etFLOAT;
16847          }
16848        }else{
16849          flag_rtz = 0;
16850        }
16851        if( xtype==etEXP ){
16852          e2 = 0;
16853        }else{
16854          e2 = exp;
16855        }
16856        nsd = 0;
16857        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
16858        /* The sign in front of the number */
16859        if( prefix ){
16860          *(bufpt++) = prefix;
16861        }
16862        /* Digits prior to the decimal point */
16863        if( e2<0 ){
16864          *(bufpt++) = '0';
16865        }else{
16866          for(; e2>=0; e2--){
16867            *(bufpt++) = et_getdigit(&realvalue,&nsd);
16868          }
16869        }
16870        /* The decimal point */
16871        if( flag_dp ){
16872          *(bufpt++) = '.';
16873        }
16874        /* "0" digits after the decimal point but before the first
16875        ** significant digit of the number */
16876        for(e2++; e2<0; precision--, e2++){
16877          assert( precision>0 );
16878          *(bufpt++) = '0';
16879        }
16880        /* Significant digits after the decimal point */
16881        while( (precision--)>0 ){
16882          *(bufpt++) = et_getdigit(&realvalue,&nsd);
16883        }
16884        /* Remove trailing zeros and the "." if no digits follow the "." */
16885        if( flag_rtz && flag_dp ){
16886          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
16887          assert( bufpt>buf );
16888          if( bufpt[-1]=='.' ){
16889            if( flag_altform2 ){
16890              *(bufpt++) = '0';
16891            }else{
16892              *(--bufpt) = 0;
16893            }
16894          }
16895        }
16896        /* Add the "eNNN" suffix */
16897        if( flag_exp || xtype==etEXP ){
16898          *(bufpt++) = aDigits[infop->charset];
16899          if( exp<0 ){
16900            *(bufpt++) = '-'; exp = -exp;
16901          }else{
16902            *(bufpt++) = '+';
16903          }
16904          if( exp>=100 ){
16905            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
16906            exp %= 100;
16907          }
16908          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
16909          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
16910        }
16911        *bufpt = 0;
16912
16913        /* The converted number is in buf[] and zero terminated. Output it.
16914        ** Note that the number is in the usual order, not reversed as with
16915        ** integer conversions. */
16916        length = (int)(bufpt-buf);
16917        bufpt = buf;
16918
16919        /* Special case:  Add leading zeros if the flag_zeropad flag is
16920        ** set and we are not left justified */
16921        if( flag_zeropad && !flag_leftjustify && length < width){
16922          int i;
16923          int nPad = width - length;
16924          for(i=width; i>=nPad; i--){
16925            bufpt[i] = bufpt[i-nPad];
16926          }
16927          i = prefix!=0;
16928          while( nPad-- ) bufpt[i++] = '0';
16929          length = width;
16930        }
16931#endif
16932        break;
16933      case etSIZE:
16934        *(va_arg(ap,int*)) = pAccum->nChar;
16935        length = width = 0;
16936        break;
16937      case etPERCENT:
16938        buf[0] = '%';
16939        bufpt = buf;
16940        length = 1;
16941        break;
16942      case etCHARX:
16943        c = va_arg(ap,int);
16944        buf[0] = (char)c;
16945        if( precision>=0 ){
16946          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
16947          length = precision;
16948        }else{
16949          length =1;
16950        }
16951        bufpt = buf;
16952        break;
16953      case etSTRING:
16954      case etDYNSTRING:
16955        bufpt = va_arg(ap,char*);
16956        if( bufpt==0 ){
16957          bufpt = "";
16958        }else if( xtype==etDYNSTRING ){
16959          zExtra = bufpt;
16960        }
16961        if( precision>=0 ){
16962          for(length=0; length<precision && bufpt[length]; length++){}
16963        }else{
16964          length = sqlite3Strlen30(bufpt);
16965        }
16966        break;
16967      case etSQLESCAPE:
16968      case etSQLESCAPE2:
16969      case etSQLESCAPE3: {
16970        int i, j, k, n, isnull;
16971        int needQuote;
16972        char ch;
16973        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
16974        char *escarg = va_arg(ap,char*);
16975        isnull = escarg==0;
16976        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
16977        k = precision;
16978        for(i=n=0; (ch=escarg[i])!=0 && k!=0; i++, k--){
16979          if( ch==q )  n++;
16980        }
16981        needQuote = !isnull && xtype==etSQLESCAPE2;
16982        n += i + 1 + needQuote*2;
16983        if( n>etBUFSIZE ){
16984          bufpt = zExtra = sqlite3Malloc( n );
16985          if( bufpt==0 ){
16986            pAccum->mallocFailed = 1;
16987            return;
16988          }
16989        }else{
16990          bufpt = buf;
16991        }
16992        j = 0;
16993        if( needQuote ) bufpt[j++] = q;
16994        k = i;
16995        for(i=0; i<k; i++){
16996          bufpt[j++] = ch = escarg[i];
16997          if( ch==q ) bufpt[j++] = ch;
16998        }
16999        if( needQuote ) bufpt[j++] = q;
17000        bufpt[j] = 0;
17001        length = j;
17002        /* The precision in %q and %Q means how many input characters to
17003        ** consume, not the length of the output...
17004        ** if( precision>=0 && precision<length ) length = precision; */
17005        break;
17006      }
17007      case etTOKEN: {
17008        Token *pToken = va_arg(ap, Token*);
17009        if( pToken ){
17010          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
17011        }
17012        length = width = 0;
17013        break;
17014      }
17015      case etSRCLIST: {
17016        SrcList *pSrc = va_arg(ap, SrcList*);
17017        int k = va_arg(ap, int);
17018        struct SrcList_item *pItem = &pSrc->a[k];
17019        assert( k>=0 && k<pSrc->nSrc );
17020        if( pItem->zDatabase ){
17021          sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
17022          sqlite3StrAccumAppend(pAccum, ".", 1);
17023        }
17024        sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
17025        length = width = 0;
17026        break;
17027      }
17028      default: {
17029        assert( xtype==etINVALID );
17030        return;
17031      }
17032    }/* End switch over the format type */
17033    /*
17034    ** The text of the conversion is pointed to by "bufpt" and is
17035    ** "length" characters long.  The field width is "width".  Do
17036    ** the output.
17037    */
17038    if( !flag_leftjustify ){
17039      register int nspace;
17040      nspace = width-length;
17041      if( nspace>0 ){
17042        appendSpace(pAccum, nspace);
17043      }
17044    }
17045    if( length>0 ){
17046      sqlite3StrAccumAppend(pAccum, bufpt, length);
17047    }
17048    if( flag_leftjustify ){
17049      register int nspace;
17050      nspace = width-length;
17051      if( nspace>0 ){
17052        appendSpace(pAccum, nspace);
17053      }
17054    }
17055    if( zExtra ){
17056      sqlite3_free(zExtra);
17057    }
17058  }/* End for loop over the format string */
17059} /* End of function */
17060
17061/*
17062** Append N bytes of text from z to the StrAccum object.
17063*/
17064SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
17065  assert( z!=0 || N==0 );
17066  if( p->tooBig | p->mallocFailed ){
17067    testcase(p->tooBig);
17068    testcase(p->mallocFailed);
17069    return;
17070  }
17071  if( N<0 ){
17072    N = sqlite3Strlen30(z);
17073  }
17074  if( N==0 || NEVER(z==0) ){
17075    return;
17076  }
17077  if( p->nChar+N >= p->nAlloc ){
17078    char *zNew;
17079    if( !p->useMalloc ){
17080      p->tooBig = 1;
17081      N = p->nAlloc - p->nChar - 1;
17082      if( N<=0 ){
17083        return;
17084      }
17085    }else{
17086      i64 szNew = p->nChar;
17087      szNew += N + 1;
17088      if( szNew > p->mxAlloc ){
17089        sqlite3StrAccumReset(p);
17090        p->tooBig = 1;
17091        return;
17092      }else{
17093        p->nAlloc = (int)szNew;
17094      }
17095      zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
17096      if( zNew ){
17097        memcpy(zNew, p->zText, p->nChar);
17098        sqlite3StrAccumReset(p);
17099        p->zText = zNew;
17100      }else{
17101        p->mallocFailed = 1;
17102        sqlite3StrAccumReset(p);
17103        return;
17104      }
17105    }
17106  }
17107  memcpy(&p->zText[p->nChar], z, N);
17108  p->nChar += N;
17109}
17110
17111/*
17112** Finish off a string by making sure it is zero-terminated.
17113** Return a pointer to the resulting string.  Return a NULL
17114** pointer if any kind of error was encountered.
17115*/
17116SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
17117  if( p->zText ){
17118    p->zText[p->nChar] = 0;
17119    if( p->useMalloc && p->zText==p->zBase ){
17120      p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
17121      if( p->zText ){
17122        memcpy(p->zText, p->zBase, p->nChar+1);
17123      }else{
17124        p->mallocFailed = 1;
17125      }
17126    }
17127  }
17128  return p->zText;
17129}
17130
17131/*
17132** Reset an StrAccum string.  Reclaim all malloced memory.
17133*/
17134SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
17135  if( p->zText!=p->zBase ){
17136    sqlite3DbFree(p->db, p->zText);
17137  }
17138  p->zText = 0;
17139}
17140
17141/*
17142** Initialize a string accumulator
17143*/
17144SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
17145  p->zText = p->zBase = zBase;
17146  p->db = 0;
17147  p->nChar = 0;
17148  p->nAlloc = n;
17149  p->mxAlloc = mx;
17150  p->useMalloc = 1;
17151  p->tooBig = 0;
17152  p->mallocFailed = 0;
17153}
17154
17155/*
17156** Print into memory obtained from sqliteMalloc().  Use the internal
17157** %-conversion extensions.
17158*/
17159SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
17160  char *z;
17161  char zBase[SQLITE_PRINT_BUF_SIZE];
17162  StrAccum acc;
17163  assert( db!=0 );
17164  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
17165                      db->aLimit[SQLITE_LIMIT_LENGTH]);
17166  acc.db = db;
17167  sqlite3VXPrintf(&acc, 1, zFormat, ap);
17168  z = sqlite3StrAccumFinish(&acc);
17169  if( acc.mallocFailed ){
17170    db->mallocFailed = 1;
17171  }
17172  return z;
17173}
17174
17175/*
17176** Print into memory obtained from sqliteMalloc().  Use the internal
17177** %-conversion extensions.
17178*/
17179SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
17180  va_list ap;
17181  char *z;
17182  va_start(ap, zFormat);
17183  z = sqlite3VMPrintf(db, zFormat, ap);
17184  va_end(ap);
17185  return z;
17186}
17187
17188/*
17189** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
17190** the string and before returnning.  This routine is intended to be used
17191** to modify an existing string.  For example:
17192**
17193**       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
17194**
17195*/
17196SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
17197  va_list ap;
17198  char *z;
17199  va_start(ap, zFormat);
17200  z = sqlite3VMPrintf(db, zFormat, ap);
17201  va_end(ap);
17202  sqlite3DbFree(db, zStr);
17203  return z;
17204}
17205
17206/*
17207** Print into memory obtained from sqlite3_malloc().  Omit the internal
17208** %-conversion extensions.
17209*/
17210SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
17211  char *z;
17212  char zBase[SQLITE_PRINT_BUF_SIZE];
17213  StrAccum acc;
17214#ifndef SQLITE_OMIT_AUTOINIT
17215  if( sqlite3_initialize() ) return 0;
17216#endif
17217  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
17218  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17219  z = sqlite3StrAccumFinish(&acc);
17220  return z;
17221}
17222
17223/*
17224** Print into memory obtained from sqlite3_malloc()().  Omit the internal
17225** %-conversion extensions.
17226*/
17227SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
17228  va_list ap;
17229  char *z;
17230#ifndef SQLITE_OMIT_AUTOINIT
17231  if( sqlite3_initialize() ) return 0;
17232#endif
17233  va_start(ap, zFormat);
17234  z = sqlite3_vmprintf(zFormat, ap);
17235  va_end(ap);
17236  return z;
17237}
17238
17239/*
17240** sqlite3_snprintf() works like snprintf() except that it ignores the
17241** current locale settings.  This is important for SQLite because we
17242** are not able to use a "," as the decimal point in place of "." as
17243** specified by some locales.
17244*/
17245SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
17246  char *z;
17247  va_list ap;
17248  StrAccum acc;
17249
17250  if( n<=0 ){
17251    return zBuf;
17252  }
17253  sqlite3StrAccumInit(&acc, zBuf, n, 0);
17254  acc.useMalloc = 0;
17255  va_start(ap,zFormat);
17256  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17257  va_end(ap);
17258  z = sqlite3StrAccumFinish(&acc);
17259  return z;
17260}
17261
17262/*
17263** This is the routine that actually formats the sqlite3_log() message.
17264** We house it in a separate routine from sqlite3_log() to avoid using
17265** stack space on small-stack systems when logging is disabled.
17266**
17267** sqlite3_log() must render into a static buffer.  It cannot dynamically
17268** allocate memory because it might be called while the memory allocator
17269** mutex is held.
17270*/
17271static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
17272  StrAccum acc;                           /* String accumulator */
17273#ifdef SQLITE_SMALL_STACK
17274  char zMsg[150];                         /* Complete log message */
17275#else
17276  char zMsg[400];                         /* Complete log message */
17277#endif
17278
17279  sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
17280  acc.useMalloc = 0;
17281  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17282  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
17283                           sqlite3StrAccumFinish(&acc));
17284}
17285
17286/*
17287** Format and write a message to the log if logging is enabled.
17288*/
17289SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
17290  va_list ap;                             /* Vararg list */
17291  if( sqlite3GlobalConfig.xLog ){
17292    va_start(ap, zFormat);
17293    renderLogMsg(iErrCode, zFormat, ap);
17294    va_end(ap);
17295  }
17296}
17297
17298#if defined(SQLITE_DEBUG)
17299/*
17300** A version of printf() that understands %lld.  Used for debugging.
17301** The printf() built into some versions of windows does not understand %lld
17302** and segfaults if you give it a long long int.
17303*/
17304SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
17305  va_list ap;
17306  StrAccum acc;
17307  char zBuf[500];
17308  sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
17309  acc.useMalloc = 0;
17310  va_start(ap,zFormat);
17311  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17312  va_end(ap);
17313  sqlite3StrAccumFinish(&acc);
17314  fprintf(stdout,"%s", zBuf);
17315  fflush(stdout);
17316}
17317#endif
17318
17319#ifndef SQLITE_OMIT_TRACE
17320/*
17321** variable-argument wrapper around sqlite3VXPrintf().
17322*/
17323SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
17324  va_list ap;
17325  va_start(ap,zFormat);
17326  sqlite3VXPrintf(p, 1, zFormat, ap);
17327  va_end(ap);
17328}
17329#endif
17330
17331/************** End of printf.c **********************************************/
17332/************** Begin file random.c ******************************************/
17333/*
17334** 2001 September 15
17335**
17336** The author disclaims copyright to this source code.  In place of
17337** a legal notice, here is a blessing:
17338**
17339**    May you do good and not evil.
17340**    May you find forgiveness for yourself and forgive others.
17341**    May you share freely, never taking more than you give.
17342**
17343*************************************************************************
17344** This file contains code to implement a pseudo-random number
17345** generator (PRNG) for SQLite.
17346**
17347** Random numbers are used by some of the database backends in order
17348** to generate random integer keys for tables or random filenames.
17349*/
17350
17351
17352/* All threads share a single random number generator.
17353** This structure is the current state of the generator.
17354*/
17355static SQLITE_WSD struct sqlite3PrngType {
17356  unsigned char isInit;          /* True if initialized */
17357  unsigned char i, j;            /* State variables */
17358  unsigned char s[256];          /* State variables */
17359} sqlite3Prng;
17360
17361/*
17362** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
17363** must be held while executing this routine.
17364**
17365** Why not just use a library random generator like lrand48() for this?
17366** Because the OP_NewRowid opcode in the VDBE depends on having a very
17367** good source of random numbers.  The lrand48() library function may
17368** well be good enough.  But maybe not.  Or maybe lrand48() has some
17369** subtle problems on some systems that could cause problems.  It is hard
17370** to know.  To minimize the risk of problems due to bad lrand48()
17371** implementations, SQLite uses this random number generator based
17372** on RC4, which we know works very well.
17373**
17374** (Later):  Actually, OP_NewRowid does not depend on a good source of
17375** randomness any more.  But we will leave this code in all the same.
17376*/
17377static u8 randomByte(void){
17378  unsigned char t;
17379
17380
17381  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
17382  ** state vector.  If writable static data is unsupported on the target,
17383  ** we have to locate the state vector at run-time.  In the more common
17384  ** case where writable static data is supported, wsdPrng can refer directly
17385  ** to the "sqlite3Prng" state vector declared above.
17386  */
17387#ifdef SQLITE_OMIT_WSD
17388  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
17389# define wsdPrng p[0]
17390#else
17391# define wsdPrng sqlite3Prng
17392#endif
17393
17394
17395  /* Initialize the state of the random number generator once,
17396  ** the first time this routine is called.  The seed value does
17397  ** not need to contain a lot of randomness since we are not
17398  ** trying to do secure encryption or anything like that...
17399  **
17400  ** Nothing in this file or anywhere else in SQLite does any kind of
17401  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
17402  ** number generator) not as an encryption device.
17403  */
17404  if( !wsdPrng.isInit ){
17405    int i;
17406    char k[256];
17407    wsdPrng.j = 0;
17408    wsdPrng.i = 0;
17409    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
17410    for(i=0; i<256; i++){
17411      wsdPrng.s[i] = (u8)i;
17412    }
17413    for(i=0; i<256; i++){
17414      wsdPrng.j += wsdPrng.s[i] + k[i];
17415      t = wsdPrng.s[wsdPrng.j];
17416      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
17417      wsdPrng.s[i] = t;
17418    }
17419    wsdPrng.isInit = 1;
17420  }
17421
17422  /* Generate and return single random byte
17423  */
17424  wsdPrng.i++;
17425  t = wsdPrng.s[wsdPrng.i];
17426  wsdPrng.j += t;
17427  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
17428  wsdPrng.s[wsdPrng.j] = t;
17429  t += wsdPrng.s[wsdPrng.i];
17430  return wsdPrng.s[t];
17431}
17432
17433/*
17434** Return N random bytes.
17435*/
17436SQLITE_API void sqlite3_randomness(int N, void *pBuf){
17437  unsigned char *zBuf = pBuf;
17438#if SQLITE_THREADSAFE
17439  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
17440#endif
17441  sqlite3_mutex_enter(mutex);
17442  while( N-- ){
17443    *(zBuf++) = randomByte();
17444  }
17445  sqlite3_mutex_leave(mutex);
17446}
17447
17448#ifndef SQLITE_OMIT_BUILTIN_TEST
17449/*
17450** For testing purposes, we sometimes want to preserve the state of
17451** PRNG and restore the PRNG to its saved state at a later time, or
17452** to reset the PRNG to its initial state.  These routines accomplish
17453** those tasks.
17454**
17455** The sqlite3_test_control() interface calls these routines to
17456** control the PRNG.
17457*/
17458static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
17459SQLITE_PRIVATE void sqlite3PrngSaveState(void){
17460  memcpy(
17461    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17462    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17463    sizeof(sqlite3Prng)
17464  );
17465}
17466SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
17467  memcpy(
17468    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17469    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17470    sizeof(sqlite3Prng)
17471  );
17472}
17473SQLITE_PRIVATE void sqlite3PrngResetState(void){
17474  GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
17475}
17476#endif /* SQLITE_OMIT_BUILTIN_TEST */
17477
17478/************** End of random.c **********************************************/
17479/************** Begin file utf.c *********************************************/
17480/*
17481** 2004 April 13
17482**
17483** The author disclaims copyright to this source code.  In place of
17484** a legal notice, here is a blessing:
17485**
17486**    May you do good and not evil.
17487**    May you find forgiveness for yourself and forgive others.
17488**    May you share freely, never taking more than you give.
17489**
17490*************************************************************************
17491** This file contains routines used to translate between UTF-8,
17492** UTF-16, UTF-16BE, and UTF-16LE.
17493**
17494** Notes on UTF-8:
17495**
17496**   Byte-0    Byte-1    Byte-2    Byte-3    Value
17497**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
17498**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
17499**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
17500**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
17501**
17502**
17503** Notes on UTF-16:  (with wwww+1==uuuuu)
17504**
17505**      Word-0               Word-1          Value
17506**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
17507**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
17508**
17509**
17510** BOM or Byte Order Mark:
17511**     0xff 0xfe   little-endian utf-16 follows
17512**     0xfe 0xff   big-endian utf-16 follows
17513**
17514*/
17515/************** Include vdbeInt.h in the middle of utf.c *********************/
17516/************** Begin file vdbeInt.h *****************************************/
17517/*
17518** 2003 September 6
17519**
17520** The author disclaims copyright to this source code.  In place of
17521** a legal notice, here is a blessing:
17522**
17523**    May you do good and not evil.
17524**    May you find forgiveness for yourself and forgive others.
17525**    May you share freely, never taking more than you give.
17526**
17527*************************************************************************
17528** This is the header file for information that is private to the
17529** VDBE.  This information used to all be at the top of the single
17530** source code file "vdbe.c".  When that file became too big (over
17531** 6000 lines long) it was split up into several smaller files and
17532** this header information was factored out.
17533*/
17534#ifndef _VDBEINT_H_
17535#define _VDBEINT_H_
17536
17537/*
17538** SQL is translated into a sequence of instructions to be
17539** executed by a virtual machine.  Each instruction is an instance
17540** of the following structure.
17541*/
17542typedef struct VdbeOp Op;
17543
17544/*
17545** Boolean values
17546*/
17547typedef unsigned char Bool;
17548
17549/*
17550** A cursor is a pointer into a single BTree within a database file.
17551** The cursor can seek to a BTree entry with a particular key, or
17552** loop over all entries of the Btree.  You can also insert new BTree
17553** entries or retrieve the key or data from the entry that the cursor
17554** is currently pointing to.
17555**
17556** Every cursor that the virtual machine has open is represented by an
17557** instance of the following structure.
17558**
17559** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
17560** really a single row that represents the NEW or OLD pseudo-table of
17561** a row trigger.  The data for the row is stored in VdbeCursor.pData and
17562** the rowid is in VdbeCursor.iKey.
17563*/
17564struct VdbeCursor {
17565  BtCursor *pCursor;    /* The cursor structure of the backend */
17566  int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
17567  i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
17568  Bool zeroed;          /* True if zeroed out and ready for reuse */
17569  Bool rowidIsValid;    /* True if lastRowid is valid */
17570  Bool atFirst;         /* True if pointing to first entry */
17571  Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
17572  Bool nullRow;         /* True if pointing to a row with no data */
17573  Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
17574  Bool isTable;         /* True if a table requiring integer keys */
17575  Bool isIndex;         /* True if an index containing keys only - no data */
17576  i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
17577  Btree *pBt;           /* Separate file holding temporary table */
17578  int pseudoTableReg;   /* Register holding pseudotable content. */
17579  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
17580  int nField;           /* Number of fields in the header */
17581  i64 seqCount;         /* Sequence counter */
17582  sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
17583  const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
17584
17585  /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
17586  ** OP_IsUnique opcode on this cursor. */
17587  int seekResult;
17588
17589  /* Cached information about the header for the data record that the
17590  ** cursor is currently pointing to.  Only valid if cacheStatus matches
17591  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
17592  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
17593  ** the cache is out of date.
17594  **
17595  ** aRow might point to (ephemeral) data for the current row, or it might
17596  ** be NULL.
17597  */
17598  u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
17599  int payloadSize;      /* Total number of bytes in the record */
17600  u32 *aType;           /* Type values for all entries in the record */
17601  u32 *aOffset;         /* Cached offsets to the start of each columns data */
17602  u8 *aRow;             /* Data for the current row, if all on one page */
17603};
17604typedef struct VdbeCursor VdbeCursor;
17605
17606/*
17607** When a sub-program is executed (OP_Program), a structure of this type
17608** is allocated to store the current value of the program counter, as
17609** well as the current memory cell array and various other frame specific
17610** values stored in the Vdbe struct. When the sub-program is finished,
17611** these values are copied back to the Vdbe from the VdbeFrame structure,
17612** restoring the state of the VM to as it was before the sub-program
17613** began executing.
17614**
17615** Frames are stored in a linked list headed at Vdbe.pParent. Vdbe.pParent
17616** is the parent of the current frame, or zero if the current frame
17617** is the main Vdbe program.
17618*/
17619typedef struct VdbeFrame VdbeFrame;
17620struct VdbeFrame {
17621  Vdbe *v;                /* VM this frame belongs to */
17622  int pc;                 /* Program Counter */
17623  Op *aOp;                /* Program instructions */
17624  int nOp;                /* Size of aOp array */
17625  Mem *aMem;              /* Array of memory cells */
17626  int nMem;               /* Number of entries in aMem */
17627  VdbeCursor **apCsr;     /* Element of Vdbe cursors */
17628  u16 nCursor;            /* Number of entries in apCsr */
17629  void *token;            /* Copy of SubProgram.token */
17630  int nChildMem;          /* Number of memory cells for child frame */
17631  int nChildCsr;          /* Number of cursors for child frame */
17632  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
17633  int nChange;            /* Statement changes (Vdbe.nChanges)     */
17634  VdbeFrame *pParent;     /* Parent of this frame */
17635};
17636
17637#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
17638
17639/*
17640** A value for VdbeCursor.cacheValid that means the cache is always invalid.
17641*/
17642#define CACHE_STALE 0
17643
17644/*
17645** Internally, the vdbe manipulates nearly all SQL values as Mem
17646** structures. Each Mem struct may cache multiple representations (string,
17647** integer etc.) of the same value.  A value (and therefore Mem structure)
17648** has the following properties:
17649**
17650** Each value has a manifest type. The manifest type of the value stored
17651** in a Mem struct is returned by the MemType(Mem*) macro. The type is
17652** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
17653** SQLITE_BLOB.
17654*/
17655struct Mem {
17656  union {
17657    i64 i;              /* Integer value. */
17658    int nZero;          /* Used when bit MEM_Zero is set in flags */
17659    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
17660    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
17661    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
17662  } u;
17663  double r;           /* Real value */
17664  sqlite3 *db;        /* The associated database connection */
17665  char *z;            /* String or BLOB value */
17666  int n;              /* Number of characters in string value, excluding '\0' */
17667  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
17668  u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
17669  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
17670  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
17671  char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
17672};
17673
17674/* One or more of the following flags are set to indicate the validOK
17675** representations of the value stored in the Mem struct.
17676**
17677** If the MEM_Null flag is set, then the value is an SQL NULL value.
17678** No other flags may be set in this case.
17679**
17680** If the MEM_Str flag is set then Mem.z points at a string representation.
17681** Usually this is encoded in the same unicode encoding as the main
17682** database (see below for exceptions). If the MEM_Term flag is also
17683** set, then the string is nul terminated. The MEM_Int and MEM_Real
17684** flags may coexist with the MEM_Str flag.
17685**
17686** Multiple of these values can appear in Mem.flags.  But only one
17687** at a time can appear in Mem.type.
17688*/
17689#define MEM_Null      0x0001   /* Value is NULL */
17690#define MEM_Str       0x0002   /* Value is a string */
17691#define MEM_Int       0x0004   /* Value is an integer */
17692#define MEM_Real      0x0008   /* Value is a real number */
17693#define MEM_Blob      0x0010   /* Value is a BLOB */
17694#define MEM_RowSet    0x0020   /* Value is a RowSet object */
17695#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
17696#define MEM_TypeMask  0x00ff   /* Mask of type bits */
17697
17698/* Whenever Mem contains a valid string or blob representation, one of
17699** the following flags must be set to determine the memory management
17700** policy for Mem.z.  The MEM_Term flag tells us whether or not the
17701** string is \000 or \u0000 terminated
17702*/
17703#define MEM_Term      0x0200   /* String rep is nul terminated */
17704#define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
17705#define MEM_Static    0x0800   /* Mem.z points to a static string */
17706#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
17707#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
17708#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
17709
17710#ifdef SQLITE_OMIT_INCRBLOB
17711  #undef MEM_Zero
17712  #define MEM_Zero 0x0000
17713#endif
17714
17715
17716/*
17717** Clear any existing type flags from a Mem and replace them with f
17718*/
17719#define MemSetTypeFlag(p, f) \
17720   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
17721
17722
17723/* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
17724** additional information about auxiliary information bound to arguments
17725** of the function.  This is used to implement the sqlite3_get_auxdata()
17726** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
17727** that can be associated with a constant argument to a function.  This
17728** allows functions such as "regexp" to compile their constant regular
17729** expression argument once and reused the compiled code for multiple
17730** invocations.
17731*/
17732struct VdbeFunc {
17733  FuncDef *pFunc;               /* The definition of the function */
17734  int nAux;                     /* Number of entries allocated for apAux[] */
17735  struct AuxData {
17736    void *pAux;                   /* Aux data for the i-th argument */
17737    void (*xDelete)(void *);      /* Destructor for the aux data */
17738  } apAux[1];                   /* One slot for each function argument */
17739};
17740
17741/*
17742** The "context" argument for a installable function.  A pointer to an
17743** instance of this structure is the first argument to the routines used
17744** implement the SQL functions.
17745**
17746** There is a typedef for this structure in sqlite.h.  So all routines,
17747** even the public interface to SQLite, can use a pointer to this structure.
17748** But this file is the only place where the internal details of this
17749** structure are known.
17750**
17751** This structure is defined inside of vdbeInt.h because it uses substructures
17752** (Mem) which are only defined there.
17753*/
17754struct sqlite3_context {
17755  FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
17756  VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
17757  Mem s;                /* The return value is stored here */
17758  Mem *pMem;            /* Memory cell used to store aggregate context */
17759  int isError;          /* Error code returned by the function. */
17760  CollSeq *pColl;       /* Collating sequence */
17761};
17762
17763/*
17764** A Set structure is used for quick testing to see if a value
17765** is part of a small set.  Sets are used to implement code like
17766** this:
17767**            x.y IN ('hi','hoo','hum')
17768*/
17769typedef struct Set Set;
17770struct Set {
17771  Hash hash;             /* A set is just a hash table */
17772  HashElem *prev;        /* Previously accessed hash elemen */
17773};
17774
17775/*
17776** An instance of the virtual machine.  This structure contains the complete
17777** state of the virtual machine.
17778**
17779** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
17780** is really a pointer to an instance of this structure.
17781**
17782** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
17783** any virtual table method invocations made by the vdbe program. It is
17784** set to 2 for xDestroy method calls and 1 for all other methods. This
17785** variable is used for two purposes: to allow xDestroy methods to execute
17786** "DROP TABLE" statements and to prevent some nasty side effects of
17787** malloc failure when SQLite is invoked recursively by a virtual table
17788** method function.
17789*/
17790struct Vdbe {
17791  sqlite3 *db;            /* The database connection that owns this statement */
17792  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
17793  int nOp;                /* Number of instructions in the program */
17794  int nOpAlloc;           /* Number of slots allocated for aOp[] */
17795  Op *aOp;                /* Space to hold the virtual machine's program */
17796  int nLabel;             /* Number of labels used */
17797  int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
17798  int *aLabel;            /* Space to hold the labels */
17799  Mem **apArg;            /* Arguments to currently executing user function */
17800  Mem *aColName;          /* Column names to return */
17801  Mem *pResultSet;        /* Pointer to an array of results */
17802  u16 nResColumn;         /* Number of columns in one row of the result set */
17803  u16 nCursor;            /* Number of slots in apCsr[] */
17804  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
17805  u8 errorAction;         /* Recovery action to do in case of an error */
17806  u8 okVar;               /* True if azVar[] has been initialized */
17807  ynVar nVar;             /* Number of entries in aVar[] */
17808  Mem *aVar;              /* Values for the OP_Variable opcode. */
17809  char **azVar;           /* Name of variables */
17810  u32 magic;              /* Magic number for sanity checking */
17811  int nMem;               /* Number of memory locations currently allocated */
17812  Mem *aMem;              /* The memory locations */
17813  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
17814  int pc;                 /* The program counter */
17815  int rc;                 /* Value to return */
17816  char *zErrMsg;          /* Error message written here */
17817  u8 explain;             /* True if EXPLAIN present on SQL command */
17818  u8 changeCntOn;         /* True to update the change-counter */
17819  u8 expired;             /* True if the VM needs to be recompiled */
17820  u8 runOnlyOnce;         /* Automatically expire on reset */
17821  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
17822  u8 inVtabMethod;        /* See comments above */
17823  u8 usesStmtJournal;     /* True if uses a statement journal */
17824  u8 readOnly;            /* True for read-only statements */
17825  u8 isPrepareV2;         /* True if prepared with prepare_v2() */
17826  int nChange;            /* Number of db changes made since last reset */
17827  int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
17828  i64 startTime;          /* Time when query started - used for profiling */
17829  BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
17830  int aCounter[2];        /* Counters used by sqlite3_stmt_status() */
17831  char *zSql;             /* Text of the SQL statement that generated this */
17832  void *pFree;            /* Free this when deleting the vdbe */
17833  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
17834  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
17835  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
17836#ifdef SQLITE_DEBUG
17837  FILE *trace;            /* Write an execution trace here, if not NULL */
17838#endif
17839  VdbeFrame *pFrame;      /* Parent frame */
17840  int nFrame;             /* Number of frames in pFrame list */
17841  u32 expmask;            /* Binding to these vars invalidates VM */
17842};
17843
17844/*
17845** The following are allowed values for Vdbe.magic
17846*/
17847#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
17848#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
17849#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
17850#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
17851
17852/*
17853** Function prototypes
17854*/
17855SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
17856void sqliteVdbePopStack(Vdbe*,int);
17857SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
17858#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
17859SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
17860#endif
17861SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
17862SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
17863SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
17864SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
17865SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
17866
17867int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
17868SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
17869SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
17870SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
17871SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
17872SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
17873SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
17874SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
17875SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
17876SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
17877SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
17878SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
17879SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
17880SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
17881SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
17882SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
17883SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
17884SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
17885SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
17886SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
17887SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
17888SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
17889SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
17890SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
17891SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
17892SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
17893SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
17894SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
17895SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
17896SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
17897SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
17898SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
17899SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
17900SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
17901SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
17902SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
17903SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
17904
17905#ifndef SQLITE_OMIT_FOREIGN_KEY
17906SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
17907#else
17908# define sqlite3VdbeCheckFk(p,i) 0
17909#endif
17910
17911#ifndef SQLITE_OMIT_SHARED_CACHE
17912SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p);
17913#else
17914# define sqlite3VdbeMutexArrayEnter(p)
17915#endif
17916
17917SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
17918#ifdef SQLITE_DEBUG
17919SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
17920SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
17921#endif
17922SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
17923
17924#ifndef SQLITE_OMIT_INCRBLOB
17925SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
17926#else
17927  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
17928#endif
17929
17930#endif /* !defined(_VDBEINT_H_) */
17931
17932/************** End of vdbeInt.h *********************************************/
17933/************** Continuing where we left off in utf.c ************************/
17934
17935#ifndef SQLITE_AMALGAMATION
17936/*
17937** The following constant value is used by the SQLITE_BIGENDIAN and
17938** SQLITE_LITTLEENDIAN macros.
17939*/
17940SQLITE_PRIVATE const int sqlite3one = 1;
17941#endif /* SQLITE_AMALGAMATION */
17942
17943/*
17944** This lookup table is used to help decode the first byte of
17945** a multi-byte UTF8 character.
17946*/
17947static const unsigned char sqlite3Utf8Trans1[] = {
17948  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17949  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
17950  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
17951  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
17952  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17953  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
17954  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17955  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
17956};
17957
17958
17959#define WRITE_UTF8(zOut, c) {                          \
17960  if( c<0x00080 ){                                     \
17961    *zOut++ = (u8)(c&0xFF);                            \
17962  }                                                    \
17963  else if( c<0x00800 ){                                \
17964    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
17965    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
17966  }                                                    \
17967  else if( c<0x10000 ){                                \
17968    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
17969    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
17970    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
17971  }else{                                               \
17972    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
17973    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
17974    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
17975    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
17976  }                                                    \
17977}
17978
17979#define WRITE_UTF16LE(zOut, c) {                                    \
17980  if( c<=0xFFFF ){                                                  \
17981    *zOut++ = (u8)(c&0x00FF);                                       \
17982    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
17983  }else{                                                            \
17984    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
17985    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
17986    *zOut++ = (u8)(c&0x00FF);                                       \
17987    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
17988  }                                                                 \
17989}
17990
17991#define WRITE_UTF16BE(zOut, c) {                                    \
17992  if( c<=0xFFFF ){                                                  \
17993    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
17994    *zOut++ = (u8)(c&0x00FF);                                       \
17995  }else{                                                            \
17996    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
17997    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
17998    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
17999    *zOut++ = (u8)(c&0x00FF);                                       \
18000  }                                                                 \
18001}
18002
18003#define READ_UTF16LE(zIn, TERM, c){                                   \
18004  c = (*zIn++);                                                       \
18005  c += ((*zIn++)<<8);                                                 \
18006  if( c>=0xD800 && c<0xE000 && TERM ){                                \
18007    int c2 = (*zIn++);                                                \
18008    c2 += ((*zIn++)<<8);                                              \
18009    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18010  }                                                                   \
18011}
18012
18013#define READ_UTF16BE(zIn, TERM, c){                                   \
18014  c = ((*zIn++)<<8);                                                  \
18015  c += (*zIn++);                                                      \
18016  if( c>=0xD800 && c<0xE000 && TERM ){                                \
18017    int c2 = ((*zIn++)<<8);                                           \
18018    c2 += (*zIn++);                                                   \
18019    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18020  }                                                                   \
18021}
18022
18023/*
18024** Translate a single UTF-8 character.  Return the unicode value.
18025**
18026** During translation, assume that the byte that zTerm points
18027** is a 0x00.
18028**
18029** Write a pointer to the next unread byte back into *pzNext.
18030**
18031** Notes On Invalid UTF-8:
18032**
18033**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
18034**     be encoded as a multi-byte character.  Any multi-byte character that
18035**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
18036**
18037**  *  This routine never allows a UTF16 surrogate value to be encoded.
18038**     If a multi-byte character attempts to encode a value between
18039**     0xd800 and 0xe000 then it is rendered as 0xfffd.
18040**
18041**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
18042**     byte of a character are interpreted as single-byte characters
18043**     and rendered as themselves even though they are technically
18044**     invalid characters.
18045**
18046**  *  This routine accepts an infinite number of different UTF8 encodings
18047**     for unicode values 0x80 and greater.  It do not change over-length
18048**     encodings to 0xfffd as some systems recommend.
18049*/
18050#define READ_UTF8(zIn, zTerm, c)                           \
18051  c = *(zIn++);                                            \
18052  if( c>=0xc0 ){                                           \
18053    c = sqlite3Utf8Trans1[c-0xc0];                         \
18054    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
18055      c = (c<<6) + (0x3f & *(zIn++));                      \
18056    }                                                      \
18057    if( c<0x80                                             \
18058        || (c&0xFFFFF800)==0xD800                          \
18059        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
18060  }
18061SQLITE_PRIVATE int sqlite3Utf8Read(
18062  const unsigned char *zIn,       /* First byte of UTF-8 character */
18063  const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
18064){
18065  int c;
18066
18067  /* Same as READ_UTF8() above but without the zTerm parameter.
18068  ** For this routine, we assume the UTF8 string is always zero-terminated.
18069  */
18070  c = *(zIn++);
18071  if( c>=0xc0 ){
18072    c = sqlite3Utf8Trans1[c-0xc0];
18073    while( (*zIn & 0xc0)==0x80 ){
18074      c = (c<<6) + (0x3f & *(zIn++));
18075    }
18076    if( c<0x80
18077        || (c&0xFFFFF800)==0xD800
18078        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
18079  }
18080  *pzNext = zIn;
18081  return c;
18082}
18083
18084
18085
18086
18087/*
18088** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
18089** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
18090*/
18091/* #define TRANSLATE_TRACE 1 */
18092
18093#ifndef SQLITE_OMIT_UTF16
18094/*
18095** This routine transforms the internal text encoding used by pMem to
18096** desiredEnc. It is an error if the string is already of the desired
18097** encoding, or if *pMem does not contain a string value.
18098*/
18099SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
18100  int len;                    /* Maximum length of output string in bytes */
18101  unsigned char *zOut;                  /* Output buffer */
18102  unsigned char *zIn;                   /* Input iterator */
18103  unsigned char *zTerm;                 /* End of input */
18104  unsigned char *z;                     /* Output iterator */
18105  unsigned int c;
18106
18107  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
18108  assert( pMem->flags&MEM_Str );
18109  assert( pMem->enc!=desiredEnc );
18110  assert( pMem->enc!=0 );
18111  assert( pMem->n>=0 );
18112
18113#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18114  {
18115    char zBuf[100];
18116    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18117    fprintf(stderr, "INPUT:  %s\n", zBuf);
18118  }
18119#endif
18120
18121  /* If the translation is between UTF-16 little and big endian, then
18122  ** all that is required is to swap the byte order. This case is handled
18123  ** differently from the others.
18124  */
18125  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
18126    u8 temp;
18127    int rc;
18128    rc = sqlite3VdbeMemMakeWriteable(pMem);
18129    if( rc!=SQLITE_OK ){
18130      assert( rc==SQLITE_NOMEM );
18131      return SQLITE_NOMEM;
18132    }
18133    zIn = (u8*)pMem->z;
18134    zTerm = &zIn[pMem->n&~1];
18135    while( zIn<zTerm ){
18136      temp = *zIn;
18137      *zIn = *(zIn+1);
18138      zIn++;
18139      *zIn++ = temp;
18140    }
18141    pMem->enc = desiredEnc;
18142    goto translate_out;
18143  }
18144
18145  /* Set len to the maximum number of bytes required in the output buffer. */
18146  if( desiredEnc==SQLITE_UTF8 ){
18147    /* When converting from UTF-16, the maximum growth results from
18148    ** translating a 2-byte character to a 4-byte UTF-8 character.
18149    ** A single byte is required for the output string
18150    ** nul-terminator.
18151    */
18152    pMem->n &= ~1;
18153    len = pMem->n * 2 + 1;
18154  }else{
18155    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
18156    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
18157    ** character. Two bytes are required in the output buffer for the
18158    ** nul-terminator.
18159    */
18160    len = pMem->n * 2 + 2;
18161  }
18162
18163  /* Set zIn to point at the start of the input buffer and zTerm to point 1
18164  ** byte past the end.
18165  **
18166  ** Variable zOut is set to point at the output buffer, space obtained
18167  ** from sqlite3_malloc().
18168  */
18169  zIn = (u8*)pMem->z;
18170  zTerm = &zIn[pMem->n];
18171  zOut = sqlite3DbMallocRaw(pMem->db, len);
18172  if( !zOut ){
18173    return SQLITE_NOMEM;
18174  }
18175  z = zOut;
18176
18177  if( pMem->enc==SQLITE_UTF8 ){
18178    if( desiredEnc==SQLITE_UTF16LE ){
18179      /* UTF-8 -> UTF-16 Little-endian */
18180      while( zIn<zTerm ){
18181        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18182        READ_UTF8(zIn, zTerm, c);
18183        WRITE_UTF16LE(z, c);
18184      }
18185    }else{
18186      assert( desiredEnc==SQLITE_UTF16BE );
18187      /* UTF-8 -> UTF-16 Big-endian */
18188      while( zIn<zTerm ){
18189        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18190        READ_UTF8(zIn, zTerm, c);
18191        WRITE_UTF16BE(z, c);
18192      }
18193    }
18194    pMem->n = (int)(z - zOut);
18195    *z++ = 0;
18196  }else{
18197    assert( desiredEnc==SQLITE_UTF8 );
18198    if( pMem->enc==SQLITE_UTF16LE ){
18199      /* UTF-16 Little-endian -> UTF-8 */
18200      while( zIn<zTerm ){
18201        READ_UTF16LE(zIn, zIn<zTerm, c);
18202        WRITE_UTF8(z, c);
18203      }
18204    }else{
18205      /* UTF-16 Big-endian -> UTF-8 */
18206      while( zIn<zTerm ){
18207        READ_UTF16BE(zIn, zIn<zTerm, c);
18208        WRITE_UTF8(z, c);
18209      }
18210    }
18211    pMem->n = (int)(z - zOut);
18212  }
18213  *z = 0;
18214  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
18215
18216  sqlite3VdbeMemRelease(pMem);
18217  pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
18218  pMem->enc = desiredEnc;
18219  pMem->flags |= (MEM_Term|MEM_Dyn);
18220  pMem->z = (char*)zOut;
18221  pMem->zMalloc = pMem->z;
18222
18223translate_out:
18224#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18225  {
18226    char zBuf[100];
18227    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18228    fprintf(stderr, "OUTPUT: %s\n", zBuf);
18229  }
18230#endif
18231  return SQLITE_OK;
18232}
18233
18234/*
18235** This routine checks for a byte-order mark at the beginning of the
18236** UTF-16 string stored in *pMem. If one is present, it is removed and
18237** the encoding of the Mem adjusted. This routine does not do any
18238** byte-swapping, it just sets Mem.enc appropriately.
18239**
18240** The allocation (static, dynamic etc.) and encoding of the Mem may be
18241** changed by this function.
18242*/
18243SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
18244  int rc = SQLITE_OK;
18245  u8 bom = 0;
18246
18247  assert( pMem->n>=0 );
18248  if( pMem->n>1 ){
18249    u8 b1 = *(u8 *)pMem->z;
18250    u8 b2 = *(((u8 *)pMem->z) + 1);
18251    if( b1==0xFE && b2==0xFF ){
18252      bom = SQLITE_UTF16BE;
18253    }
18254    if( b1==0xFF && b2==0xFE ){
18255      bom = SQLITE_UTF16LE;
18256    }
18257  }
18258
18259  if( bom ){
18260    rc = sqlite3VdbeMemMakeWriteable(pMem);
18261    if( rc==SQLITE_OK ){
18262      pMem->n -= 2;
18263      memmove(pMem->z, &pMem->z[2], pMem->n);
18264      pMem->z[pMem->n] = '\0';
18265      pMem->z[pMem->n+1] = '\0';
18266      pMem->flags |= MEM_Term;
18267      pMem->enc = bom;
18268    }
18269  }
18270  return rc;
18271}
18272#endif /* SQLITE_OMIT_UTF16 */
18273
18274/*
18275** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
18276** return the number of unicode characters in pZ up to (but not including)
18277** the first 0x00 byte. If nByte is not less than zero, return the
18278** number of unicode characters in the first nByte of pZ (or up to
18279** the first 0x00, whichever comes first).
18280*/
18281SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
18282  int r = 0;
18283  const u8 *z = (const u8*)zIn;
18284  const u8 *zTerm;
18285  if( nByte>=0 ){
18286    zTerm = &z[nByte];
18287  }else{
18288    zTerm = (const u8*)(-1);
18289  }
18290  assert( z<=zTerm );
18291  while( *z!=0 && z<zTerm ){
18292    SQLITE_SKIP_UTF8(z);
18293    r++;
18294  }
18295  return r;
18296}
18297
18298/* This test function is not currently used by the automated test-suite.
18299** Hence it is only available in debug builds.
18300*/
18301#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
18302/*
18303** Translate UTF-8 to UTF-8.
18304**
18305** This has the effect of making sure that the string is well-formed
18306** UTF-8.  Miscoded characters are removed.
18307**
18308** The translation is done in-place (since it is impossible for the
18309** correct UTF-8 encoding to be longer than a malformed encoding).
18310*/
18311SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
18312  unsigned char *zOut = zIn;
18313  unsigned char *zStart = zIn;
18314  u32 c;
18315
18316  while( zIn[0] ){
18317    c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
18318    if( c!=0xfffd ){
18319      WRITE_UTF8(zOut, c);
18320    }
18321  }
18322  *zOut = 0;
18323  return (int)(zOut - zStart);
18324}
18325#endif
18326
18327#ifndef SQLITE_OMIT_UTF16
18328/*
18329** Convert a UTF-16 string in the native encoding into a UTF-8 string.
18330** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
18331** be freed by the calling function.
18332**
18333** NULL is returned if there is an allocation error.
18334*/
18335SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
18336  Mem m;
18337  memset(&m, 0, sizeof(m));
18338  m.db = db;
18339  sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
18340  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
18341  if( db->mallocFailed ){
18342    sqlite3VdbeMemRelease(&m);
18343    m.z = 0;
18344  }
18345  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
18346  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
18347  return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
18348}
18349
18350/*
18351** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
18352** enc. A pointer to the new string is returned, and the value of *pnOut
18353** is set to the length of the returned string in bytes. The call should
18354** arrange to call sqlite3DbFree() on the returned pointer when it is
18355** no longer required.
18356**
18357** If a malloc failure occurs, NULL is returned and the db.mallocFailed
18358** flag set.
18359*/
18360#ifdef SQLITE_ENABLE_STAT2
18361SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
18362  Mem m;
18363  memset(&m, 0, sizeof(m));
18364  m.db = db;
18365  sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
18366  if( sqlite3VdbeMemTranslate(&m, enc) ){
18367    assert( db->mallocFailed );
18368    return 0;
18369  }
18370  assert( m.z==m.zMalloc );
18371  *pnOut = m.n;
18372  return m.z;
18373}
18374#endif
18375
18376/*
18377** zIn is a UTF-16 encoded unicode string at least nChar characters long.
18378** Return the number of bytes in the first nChar unicode characters
18379** in pZ.  nChar must be non-negative.
18380*/
18381SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
18382  int c;
18383  unsigned char const *z = zIn;
18384  int n = 0;
18385
18386  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
18387    while( n<nChar ){
18388      READ_UTF16BE(z, 1, c);
18389      n++;
18390    }
18391  }else{
18392    while( n<nChar ){
18393      READ_UTF16LE(z, 1, c);
18394      n++;
18395    }
18396  }
18397  return (int)(z-(unsigned char const *)zIn);
18398}
18399
18400#if defined(SQLITE_TEST)
18401/*
18402** This routine is called from the TCL test function "translate_selftest".
18403** It checks that the primitives for serializing and deserializing
18404** characters in each encoding are inverses of each other.
18405*/
18406SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
18407  unsigned int i, t;
18408  unsigned char zBuf[20];
18409  unsigned char *z;
18410  int n;
18411  unsigned int c;
18412
18413  for(i=0; i<0x00110000; i++){
18414    z = zBuf;
18415    WRITE_UTF8(z, i);
18416    n = (int)(z-zBuf);
18417    assert( n>0 && n<=4 );
18418    z[0] = 0;
18419    z = zBuf;
18420    c = sqlite3Utf8Read(z, (const u8**)&z);
18421    t = i;
18422    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
18423    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
18424    assert( c==t );
18425    assert( (z-zBuf)==n );
18426  }
18427  for(i=0; i<0x00110000; i++){
18428    if( i>=0xD800 && i<0xE000 ) continue;
18429    z = zBuf;
18430    WRITE_UTF16LE(z, i);
18431    n = (int)(z-zBuf);
18432    assert( n>0 && n<=4 );
18433    z[0] = 0;
18434    z = zBuf;
18435    READ_UTF16LE(z, 1, c);
18436    assert( c==i );
18437    assert( (z-zBuf)==n );
18438  }
18439  for(i=0; i<0x00110000; i++){
18440    if( i>=0xD800 && i<0xE000 ) continue;
18441    z = zBuf;
18442    WRITE_UTF16BE(z, i);
18443    n = (int)(z-zBuf);
18444    assert( n>0 && n<=4 );
18445    z[0] = 0;
18446    z = zBuf;
18447    READ_UTF16BE(z, 1, c);
18448    assert( c==i );
18449    assert( (z-zBuf)==n );
18450  }
18451}
18452#endif /* SQLITE_TEST */
18453#endif /* SQLITE_OMIT_UTF16 */
18454
18455/************** End of utf.c *************************************************/
18456/************** Begin file util.c ********************************************/
18457/*
18458** 2001 September 15
18459**
18460** The author disclaims copyright to this source code.  In place of
18461** a legal notice, here is a blessing:
18462**
18463**    May you do good and not evil.
18464**    May you find forgiveness for yourself and forgive others.
18465**    May you share freely, never taking more than you give.
18466**
18467*************************************************************************
18468** Utility functions used throughout sqlite.
18469**
18470** This file contains functions for allocating memory, comparing
18471** strings, and stuff like that.
18472**
18473*/
18474#ifdef SQLITE_HAVE_ISNAN
18475# include <math.h>
18476#endif
18477
18478/*
18479** Routine needed to support the testcase() macro.
18480*/
18481#ifdef SQLITE_COVERAGE_TEST
18482SQLITE_PRIVATE void sqlite3Coverage(int x){
18483  static int dummy = 0;
18484  dummy += x;
18485}
18486#endif
18487
18488/*
18489** Return true if the floating point value is Not a Number (NaN).
18490**
18491** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
18492** Otherwise, we have our own implementation that works on most systems.
18493*/
18494SQLITE_PRIVATE int sqlite3IsNaN(double x){
18495  int rc;   /* The value return */
18496#if !defined(SQLITE_HAVE_ISNAN)
18497  /*
18498  ** Systems that support the isnan() library function should probably
18499  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
18500  ** found that many systems do not have a working isnan() function so
18501  ** this implementation is provided as an alternative.
18502  **
18503  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
18504  ** On the other hand, the use of -ffast-math comes with the following
18505  ** warning:
18506  **
18507  **      This option [-ffast-math] should never be turned on by any
18508  **      -O option since it can result in incorrect output for programs
18509  **      which depend on an exact implementation of IEEE or ISO
18510  **      rules/specifications for math functions.
18511  **
18512  ** Under MSVC, this NaN test may fail if compiled with a floating-
18513  ** point precision mode other than /fp:precise.  From the MSDN
18514  ** documentation:
18515  **
18516  **      The compiler [with /fp:precise] will properly handle comparisons
18517  **      involving NaN. For example, x != x evaluates to true if x is NaN
18518  **      ...
18519  */
18520#ifdef __FAST_MATH__
18521# error SQLite will not work correctly with the -ffast-math option of GCC.
18522#endif
18523  volatile double y = x;
18524  volatile double z = y;
18525  rc = (y!=z);
18526#else  /* if defined(SQLITE_HAVE_ISNAN) */
18527  rc = isnan(x);
18528#endif /* SQLITE_HAVE_ISNAN */
18529  testcase( rc );
18530  return rc;
18531}
18532
18533/*
18534** Compute a string length that is limited to what can be stored in
18535** lower 30 bits of a 32-bit signed integer.
18536**
18537** The value returned will never be negative.  Nor will it ever be greater
18538** than the actual length of the string.  For very long strings (greater
18539** than 1GiB) the value returned might be less than the true string length.
18540*/
18541SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
18542  const char *z2 = z;
18543  if( z==0 ) return 0;
18544  while( *z2 ){ z2++; }
18545  return 0x3fffffff & (int)(z2 - z);
18546}
18547
18548/*
18549** Set the most recent error code and error string for the sqlite
18550** handle "db". The error code is set to "err_code".
18551**
18552** If it is not NULL, string zFormat specifies the format of the
18553** error string in the style of the printf functions: The following
18554** format characters are allowed:
18555**
18556**      %s      Insert a string
18557**      %z      A string that should be freed after use
18558**      %d      Insert an integer
18559**      %T      Insert a token
18560**      %S      Insert the first element of a SrcList
18561**
18562** zFormat and any string tokens that follow it are assumed to be
18563** encoded in UTF-8.
18564**
18565** To clear the most recent error for sqlite handle "db", sqlite3Error
18566** should be called with err_code set to SQLITE_OK and zFormat set
18567** to NULL.
18568*/
18569SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
18570  if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
18571    db->errCode = err_code;
18572    if( zFormat ){
18573      char *z;
18574      va_list ap;
18575      va_start(ap, zFormat);
18576      z = sqlite3VMPrintf(db, zFormat, ap);
18577      va_end(ap);
18578      sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
18579    }else{
18580      sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
18581    }
18582  }
18583}
18584
18585/*
18586** Add an error message to pParse->zErrMsg and increment pParse->nErr.
18587** The following formatting characters are allowed:
18588**
18589**      %s      Insert a string
18590**      %z      A string that should be freed after use
18591**      %d      Insert an integer
18592**      %T      Insert a token
18593**      %S      Insert the first element of a SrcList
18594**
18595** This function should be used to report any error that occurs whilst
18596** compiling an SQL statement (i.e. within sqlite3_prepare()). The
18597** last thing the sqlite3_prepare() function does is copy the error
18598** stored by this function into the database handle using sqlite3Error().
18599** Function sqlite3Error() should be used during statement execution
18600** (sqlite3_step() etc.).
18601*/
18602SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
18603  char *zMsg;
18604  va_list ap;
18605  sqlite3 *db = pParse->db;
18606  va_start(ap, zFormat);
18607  zMsg = sqlite3VMPrintf(db, zFormat, ap);
18608  va_end(ap);
18609  if( db->suppressErr ){
18610    sqlite3DbFree(db, zMsg);
18611  }else{
18612    pParse->nErr++;
18613    sqlite3DbFree(db, pParse->zErrMsg);
18614    pParse->zErrMsg = zMsg;
18615    pParse->rc = SQLITE_ERROR;
18616  }
18617}
18618
18619/*
18620** Convert an SQL-style quoted string into a normal string by removing
18621** the quote characters.  The conversion is done in-place.  If the
18622** input does not begin with a quote character, then this routine
18623** is a no-op.
18624**
18625** The input string must be zero-terminated.  A new zero-terminator
18626** is added to the dequoted string.
18627**
18628** The return value is -1 if no dequoting occurs or the length of the
18629** dequoted string, exclusive of the zero terminator, if dequoting does
18630** occur.
18631**
18632** 2002-Feb-14: This routine is extended to remove MS-Access style
18633** brackets from around identifers.  For example:  "[a-b-c]" becomes
18634** "a-b-c".
18635*/
18636SQLITE_PRIVATE int sqlite3Dequote(char *z){
18637  char quote;
18638  int i, j;
18639  if( z==0 ) return -1;
18640  quote = z[0];
18641  switch( quote ){
18642    case '\'':  break;
18643    case '"':   break;
18644    case '`':   break;                /* For MySQL compatibility */
18645    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
18646    default:    return -1;
18647  }
18648  for(i=1, j=0; ALWAYS(z[i]); i++){
18649    if( z[i]==quote ){
18650      if( z[i+1]==quote ){
18651        z[j++] = quote;
18652        i++;
18653      }else{
18654        break;
18655      }
18656    }else{
18657      z[j++] = z[i];
18658    }
18659  }
18660  z[j] = 0;
18661  return j;
18662}
18663
18664/* Convenient short-hand */
18665#define UpperToLower sqlite3UpperToLower
18666
18667/*
18668** Some systems have stricmp().  Others have strcasecmp().  Because
18669** there is no consistency, we will define our own.
18670*/
18671SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
18672  register unsigned char *a, *b;
18673  a = (unsigned char *)zLeft;
18674  b = (unsigned char *)zRight;
18675  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18676  return UpperToLower[*a] - UpperToLower[*b];
18677}
18678SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
18679  register unsigned char *a, *b;
18680  a = (unsigned char *)zLeft;
18681  b = (unsigned char *)zRight;
18682  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18683  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
18684}
18685
18686/*
18687** Return TRUE if z is a pure numeric string.  Return FALSE and leave
18688** *realnum unchanged if the string contains any character which is not
18689** part of a number.
18690**
18691** If the string is pure numeric, set *realnum to TRUE if the string
18692** contains the '.' character or an "E+000" style exponentiation suffix.
18693** Otherwise set *realnum to FALSE.  Note that just becaue *realnum is
18694** false does not mean that the number can be successfully converted into
18695** an integer - it might be too big.
18696**
18697** An empty string is considered non-numeric.
18698*/
18699SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
18700  int incr = (enc==SQLITE_UTF8?1:2);
18701  if( enc==SQLITE_UTF16BE ) z++;
18702  if( *z=='-' || *z=='+' ) z += incr;
18703  if( !sqlite3Isdigit(*z) ){
18704    return 0;
18705  }
18706  z += incr;
18707  *realnum = 0;
18708  while( sqlite3Isdigit(*z) ){ z += incr; }
18709  if( *z=='.' ){
18710    z += incr;
18711    if( !sqlite3Isdigit(*z) ) return 0;
18712    while( sqlite3Isdigit(*z) ){ z += incr; }
18713    *realnum = 1;
18714  }
18715  if( *z=='e' || *z=='E' ){
18716    z += incr;
18717    if( *z=='+' || *z=='-' ) z += incr;
18718    if( !sqlite3Isdigit(*z) ) return 0;
18719    while( sqlite3Isdigit(*z) ){ z += incr; }
18720    *realnum = 1;
18721  }
18722  return *z==0;
18723}
18724
18725/*
18726** The string z[] is an ASCII representation of a real number.
18727** Convert this string to a double.
18728**
18729** This routine assumes that z[] really is a valid number.  If it
18730** is not, the result is undefined.
18731**
18732** This routine is used instead of the library atof() function because
18733** the library atof() might want to use "," as the decimal point instead
18734** of "." depending on how locale is set.  But that would cause problems
18735** for SQL.  So this routine always uses "." regardless of locale.
18736*/
18737SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
18738#ifndef SQLITE_OMIT_FLOATING_POINT
18739  const char *zBegin = z;
18740  /* sign * significand * (10 ^ (esign * exponent)) */
18741  int sign = 1;   /* sign of significand */
18742  i64 s = 0;      /* significand */
18743  int d = 0;      /* adjust exponent for shifting decimal point */
18744  int esign = 1;  /* sign of exponent */
18745  int e = 0;      /* exponent */
18746  double result;
18747  int nDigits = 0;
18748
18749  /* skip leading spaces */
18750  while( sqlite3Isspace(*z) ) z++;
18751  /* get sign of significand */
18752  if( *z=='-' ){
18753    sign = -1;
18754    z++;
18755  }else if( *z=='+' ){
18756    z++;
18757  }
18758  /* skip leading zeroes */
18759  while( z[0]=='0' ) z++, nDigits++;
18760
18761  /* copy max significant digits to significand */
18762  while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
18763    s = s*10 + (*z - '0');
18764    z++, nDigits++;
18765  }
18766  /* skip non-significant significand digits
18767  ** (increase exponent by d to shift decimal left) */
18768  while( sqlite3Isdigit(*z) ) z++, nDigits++, d++;
18769
18770  /* if decimal point is present */
18771  if( *z=='.' ){
18772    z++;
18773    /* copy digits from after decimal to significand
18774    ** (decrease exponent by d to shift decimal right) */
18775    while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
18776      s = s*10 + (*z - '0');
18777      z++, nDigits++, d--;
18778    }
18779    /* skip non-significant digits */
18780    while( sqlite3Isdigit(*z) ) z++, nDigits++;
18781  }
18782
18783  /* if exponent is present */
18784  if( *z=='e' || *z=='E' ){
18785    z++;
18786    /* get sign of exponent */
18787    if( *z=='-' ){
18788      esign = -1;
18789      z++;
18790    }else if( *z=='+' ){
18791      z++;
18792    }
18793    /* copy digits to exponent */
18794    while( sqlite3Isdigit(*z) ){
18795      e = e*10 + (*z - '0');
18796      z++;
18797    }
18798  }
18799
18800  /* adjust exponent by d, and update sign */
18801  e = (e*esign) + d;
18802  if( e<0 ) {
18803    esign = -1;
18804    e *= -1;
18805  } else {
18806    esign = 1;
18807  }
18808
18809  /* if 0 significand */
18810  if( !s ) {
18811    /* In the IEEE 754 standard, zero is signed.
18812    ** Add the sign if we've seen at least one digit */
18813    result = (sign<0 && nDigits) ? -(double)0 : (double)0;
18814  } else {
18815    /* attempt to reduce exponent */
18816    if( esign>0 ){
18817      while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
18818    }else{
18819      while( !(s%10) && e>0 ) e--,s/=10;
18820    }
18821
18822    /* adjust the sign of significand */
18823    s = sign<0 ? -s : s;
18824
18825    /* if exponent, scale significand as appropriate
18826    ** and store in result. */
18827    if( e ){
18828      double scale = 1.0;
18829      /* attempt to handle extremely small/large numbers better */
18830      if( e>307 && e<342 ){
18831        while( e%308 ) { scale *= 1.0e+1; e -= 1; }
18832        if( esign<0 ){
18833          result = s / scale;
18834          result /= 1.0e+308;
18835        }else{
18836          result = s * scale;
18837          result *= 1.0e+308;
18838        }
18839      }else{
18840        /* 1.0e+22 is the largest power of 10 than can be
18841        ** represented exactly. */
18842        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
18843        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
18844        if( esign<0 ){
18845          result = s / scale;
18846        }else{
18847          result = s * scale;
18848        }
18849      }
18850    } else {
18851      result = (double)s;
18852    }
18853  }
18854
18855  /* store the result */
18856  *pResult = result;
18857
18858  /* return number of characters used */
18859  return (int)(z - zBegin);
18860#else
18861  return sqlite3Atoi64(z, pResult);
18862#endif /* SQLITE_OMIT_FLOATING_POINT */
18863}
18864
18865/*
18866** Compare the 19-character string zNum against the text representation
18867** value 2^63:  9223372036854775808.  Return negative, zero, or positive
18868** if zNum is less than, equal to, or greater than the string.
18869**
18870** Unlike memcmp() this routine is guaranteed to return the difference
18871** in the values of the last digit if the only difference is in the
18872** last digit.  So, for example,
18873**
18874**      compare2pow63("9223372036854775800")
18875**
18876** will return -8.
18877*/
18878static int compare2pow63(const char *zNum){
18879  int c;
18880  c = memcmp(zNum,"922337203685477580",18)*10;
18881  if( c==0 ){
18882    c = zNum[18] - '8';
18883  }
18884  return c;
18885}
18886
18887
18888/*
18889** Return TRUE if zNum is a 64-bit signed integer and write
18890** the value of the integer into *pNum.  If zNum is not an integer
18891** or is an integer that is too large to be expressed with 64 bits,
18892** then return false.
18893**
18894** When this routine was originally written it dealt with only
18895** 32-bit numbers.  At that time, it was much faster than the
18896** atoi() library routine in RedHat 7.2.
18897*/
18898SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
18899  i64 v = 0;
18900  int neg;
18901  int i, c;
18902  const char *zStart;
18903  while( sqlite3Isspace(*zNum) ) zNum++;
18904  if( *zNum=='-' ){
18905    neg = 1;
18906    zNum++;
18907  }else if( *zNum=='+' ){
18908    neg = 0;
18909    zNum++;
18910  }else{
18911    neg = 0;
18912  }
18913  zStart = zNum;
18914  while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
18915  for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
18916    v = v*10 + c - '0';
18917  }
18918  *pNum = neg ? -v : v;
18919  if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
18920    /* zNum is empty or contains non-numeric text or is longer
18921    ** than 19 digits (thus guaranting that it is too large) */
18922    return 0;
18923  }else if( i<19 ){
18924    /* Less than 19 digits, so we know that it fits in 64 bits */
18925    return 1;
18926  }else{
18927    /* 19-digit numbers must be no larger than 9223372036854775807 if positive
18928    ** or 9223372036854775808 if negative.  Note that 9223372036854665808
18929    ** is 2^63. */
18930    return compare2pow63(zNum)<neg;
18931  }
18932}
18933
18934/*
18935** The string zNum represents an unsigned integer.  The zNum string
18936** consists of one or more digit characters and is terminated by
18937** a zero character.  Any stray characters in zNum result in undefined
18938** behavior.
18939**
18940** If the unsigned integer that zNum represents will fit in a
18941** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
18942**
18943** If the negFlag parameter is true, that means that zNum really represents
18944** a negative number.  (The leading "-" is omitted from zNum.)  This
18945** parameter is needed to determine a boundary case.  A string
18946** of "9223373036854775808" returns false if negFlag is false or true
18947** if negFlag is true.
18948**
18949** Leading zeros are ignored.
18950*/
18951SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
18952  int i;
18953  int neg = 0;
18954
18955  assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */
18956
18957  if( negFlag ) neg = 1-neg;
18958  while( *zNum=='0' ){
18959    zNum++;   /* Skip leading zeros.  Ticket #2454 */
18960  }
18961  for(i=0; zNum[i]; i++){ assert( zNum[i]>='0' && zNum[i]<='9' ); }
18962  if( i<19 ){
18963    /* Guaranteed to fit if less than 19 digits */
18964    return 1;
18965  }else if( i>19 ){
18966    /* Guaranteed to be too big if greater than 19 digits */
18967    return 0;
18968  }else{
18969    /* Compare against 2^63. */
18970    return compare2pow63(zNum)<neg;
18971  }
18972}
18973
18974/*
18975** If zNum represents an integer that will fit in 32-bits, then set
18976** *pValue to that integer and return true.  Otherwise return false.
18977**
18978** Any non-numeric characters that following zNum are ignored.
18979** This is different from sqlite3Atoi64() which requires the
18980** input number to be zero-terminated.
18981*/
18982SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
18983  sqlite_int64 v = 0;
18984  int i, c;
18985  int neg = 0;
18986  if( zNum[0]=='-' ){
18987    neg = 1;
18988    zNum++;
18989  }else if( zNum[0]=='+' ){
18990    zNum++;
18991  }
18992  while( zNum[0]=='0' ) zNum++;
18993  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
18994    v = v*10 + c;
18995  }
18996
18997  /* The longest decimal representation of a 32 bit integer is 10 digits:
18998  **
18999  **             1234567890
19000  **     2^31 -> 2147483648
19001  */
19002  if( i>10 ){
19003    return 0;
19004  }
19005  if( v-neg>2147483647 ){
19006    return 0;
19007  }
19008  if( neg ){
19009    v = -v;
19010  }
19011  *pValue = (int)v;
19012  return 1;
19013}
19014
19015/*
19016** The variable-length integer encoding is as follows:
19017**
19018** KEY:
19019**         A = 0xxxxxxx    7 bits of data and one flag bit
19020**         B = 1xxxxxxx    7 bits of data and one flag bit
19021**         C = xxxxxxxx    8 bits of data
19022**
19023**  7 bits - A
19024** 14 bits - BA
19025** 21 bits - BBA
19026** 28 bits - BBBA
19027** 35 bits - BBBBA
19028** 42 bits - BBBBBA
19029** 49 bits - BBBBBBA
19030** 56 bits - BBBBBBBA
19031** 64 bits - BBBBBBBBC
19032*/
19033
19034/*
19035** Write a 64-bit variable-length integer to memory starting at p[0].
19036** The length of data write will be between 1 and 9 bytes.  The number
19037** of bytes written is returned.
19038**
19039** A variable-length integer consists of the lower 7 bits of each byte
19040** for all bytes that have the 8th bit set and one byte with the 8th
19041** bit clear.  Except, if we get to the 9th byte, it stores the full
19042** 8 bits and is the last byte.
19043*/
19044SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
19045  int i, j, n;
19046  u8 buf[10];
19047  if( v & (((u64)0xff000000)<<32) ){
19048    p[8] = (u8)v;
19049    v >>= 8;
19050    for(i=7; i>=0; i--){
19051      p[i] = (u8)((v & 0x7f) | 0x80);
19052      v >>= 7;
19053    }
19054    return 9;
19055  }
19056  n = 0;
19057  do{
19058    buf[n++] = (u8)((v & 0x7f) | 0x80);
19059    v >>= 7;
19060  }while( v!=0 );
19061  buf[0] &= 0x7f;
19062  assert( n<=9 );
19063  for(i=0, j=n-1; j>=0; j--, i++){
19064    p[i] = buf[j];
19065  }
19066  return n;
19067}
19068
19069/*
19070** This routine is a faster version of sqlite3PutVarint() that only
19071** works for 32-bit positive integers and which is optimized for
19072** the common case of small integers.  A MACRO version, putVarint32,
19073** is provided which inlines the single-byte case.  All code should use
19074** the MACRO version as this function assumes the single-byte case has
19075** already been handled.
19076*/
19077SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
19078#ifndef putVarint32
19079  if( (v & ~0x7f)==0 ){
19080    p[0] = v;
19081    return 1;
19082  }
19083#endif
19084  if( (v & ~0x3fff)==0 ){
19085    p[0] = (u8)((v>>7) | 0x80);
19086    p[1] = (u8)(v & 0x7f);
19087    return 2;
19088  }
19089  return sqlite3PutVarint(p, v);
19090}
19091
19092/*
19093** Read a 64-bit variable-length integer from memory starting at p[0].
19094** Return the number of bytes read.  The value is stored in *v.
19095*/
19096SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
19097  u32 a,b,s;
19098
19099  a = *p;
19100  /* a: p0 (unmasked) */
19101  if (!(a&0x80))
19102  {
19103    *v = a;
19104    return 1;
19105  }
19106
19107  p++;
19108  b = *p;
19109  /* b: p1 (unmasked) */
19110  if (!(b&0x80))
19111  {
19112    a &= 0x7f;
19113    a = a<<7;
19114    a |= b;
19115    *v = a;
19116    return 2;
19117  }
19118
19119  p++;
19120  a = a<<14;
19121  a |= *p;
19122  /* a: p0<<14 | p2 (unmasked) */
19123  if (!(a&0x80))
19124  {
19125    a &= (0x7f<<14)|(0x7f);
19126    b &= 0x7f;
19127    b = b<<7;
19128    a |= b;
19129    *v = a;
19130    return 3;
19131  }
19132
19133  /* CSE1 from below */
19134  a &= (0x7f<<14)|(0x7f);
19135  p++;
19136  b = b<<14;
19137  b |= *p;
19138  /* b: p1<<14 | p3 (unmasked) */
19139  if (!(b&0x80))
19140  {
19141    b &= (0x7f<<14)|(0x7f);
19142    /* moved CSE1 up */
19143    /* a &= (0x7f<<14)|(0x7f); */
19144    a = a<<7;
19145    a |= b;
19146    *v = a;
19147    return 4;
19148  }
19149
19150  /* a: p0<<14 | p2 (masked) */
19151  /* b: p1<<14 | p3 (unmasked) */
19152  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19153  /* moved CSE1 up */
19154  /* a &= (0x7f<<14)|(0x7f); */
19155  b &= (0x7f<<14)|(0x7f);
19156  s = a;
19157  /* s: p0<<14 | p2 (masked) */
19158
19159  p++;
19160  a = a<<14;
19161  a |= *p;
19162  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19163  if (!(a&0x80))
19164  {
19165    /* we can skip these cause they were (effectively) done above in calc'ing s */
19166    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19167    /* b &= (0x7f<<14)|(0x7f); */
19168    b = b<<7;
19169    a |= b;
19170    s = s>>18;
19171    *v = ((u64)s)<<32 | a;
19172    return 5;
19173  }
19174
19175  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19176  s = s<<7;
19177  s |= b;
19178  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19179
19180  p++;
19181  b = b<<14;
19182  b |= *p;
19183  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
19184  if (!(b&0x80))
19185  {
19186    /* we can skip this cause it was (effectively) done above in calc'ing s */
19187    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19188    a &= (0x7f<<14)|(0x7f);
19189    a = a<<7;
19190    a |= b;
19191    s = s>>18;
19192    *v = ((u64)s)<<32 | a;
19193    return 6;
19194  }
19195
19196  p++;
19197  a = a<<14;
19198  a |= *p;
19199  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
19200  if (!(a&0x80))
19201  {
19202    a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19203    b &= (0x7f<<14)|(0x7f);
19204    b = b<<7;
19205    a |= b;
19206    s = s>>11;
19207    *v = ((u64)s)<<32 | a;
19208    return 7;
19209  }
19210
19211  /* CSE2 from below */
19212  a &= (0x7f<<14)|(0x7f);
19213  p++;
19214  b = b<<14;
19215  b |= *p;
19216  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
19217  if (!(b&0x80))
19218  {
19219    b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19220    /* moved CSE2 up */
19221    /* a &= (0x7f<<14)|(0x7f); */
19222    a = a<<7;
19223    a |= b;
19224    s = s>>4;
19225    *v = ((u64)s)<<32 | a;
19226    return 8;
19227  }
19228
19229  p++;
19230  a = a<<15;
19231  a |= *p;
19232  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
19233
19234  /* moved CSE2 up */
19235  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
19236  b &= (0x7f<<14)|(0x7f);
19237  b = b<<8;
19238  a |= b;
19239
19240  s = s<<4;
19241  b = p[-4];
19242  b &= 0x7f;
19243  b = b>>3;
19244  s |= b;
19245
19246  *v = ((u64)s)<<32 | a;
19247
19248  return 9;
19249}
19250
19251/*
19252** Read a 32-bit variable-length integer from memory starting at p[0].
19253** Return the number of bytes read.  The value is stored in *v.
19254**
19255** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
19256** integer, then set *v to 0xffffffff.
19257**
19258** A MACRO version, getVarint32, is provided which inlines the
19259** single-byte case.  All code should use the MACRO version as
19260** this function assumes the single-byte case has already been handled.
19261*/
19262SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
19263  u32 a,b;
19264
19265  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
19266  ** by the getVarin32() macro */
19267  a = *p;
19268  /* a: p0 (unmasked) */
19269#ifndef getVarint32
19270  if (!(a&0x80))
19271  {
19272    /* Values between 0 and 127 */
19273    *v = a;
19274    return 1;
19275  }
19276#endif
19277
19278  /* The 2-byte case */
19279  p++;
19280  b = *p;
19281  /* b: p1 (unmasked) */
19282  if (!(b&0x80))
19283  {
19284    /* Values between 128 and 16383 */
19285    a &= 0x7f;
19286    a = a<<7;
19287    *v = a | b;
19288    return 2;
19289  }
19290
19291  /* The 3-byte case */
19292  p++;
19293  a = a<<14;
19294  a |= *p;
19295  /* a: p0<<14 | p2 (unmasked) */
19296  if (!(a&0x80))
19297  {
19298    /* Values between 16384 and 2097151 */
19299    a &= (0x7f<<14)|(0x7f);
19300    b &= 0x7f;
19301    b = b<<7;
19302    *v = a | b;
19303    return 3;
19304  }
19305
19306  /* A 32-bit varint is used to store size information in btrees.
19307  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
19308  ** A 3-byte varint is sufficient, for example, to record the size
19309  ** of a 1048569-byte BLOB or string.
19310  **
19311  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
19312  ** rare larger cases can be handled by the slower 64-bit varint
19313  ** routine.
19314  */
19315#if 1
19316  {
19317    u64 v64;
19318    u8 n;
19319
19320    p -= 2;
19321    n = sqlite3GetVarint(p, &v64);
19322    assert( n>3 && n<=9 );
19323    if( (v64 & SQLITE_MAX_U32)!=v64 ){
19324      *v = 0xffffffff;
19325    }else{
19326      *v = (u32)v64;
19327    }
19328    return n;
19329  }
19330
19331#else
19332  /* For following code (kept for historical record only) shows an
19333  ** unrolling for the 3- and 4-byte varint cases.  This code is
19334  ** slightly faster, but it is also larger and much harder to test.
19335  */
19336  p++;
19337  b = b<<14;
19338  b |= *p;
19339  /* b: p1<<14 | p3 (unmasked) */
19340  if (!(b&0x80))
19341  {
19342    /* Values between 2097152 and 268435455 */
19343    b &= (0x7f<<14)|(0x7f);
19344    a &= (0x7f<<14)|(0x7f);
19345    a = a<<7;
19346    *v = a | b;
19347    return 4;
19348  }
19349
19350  p++;
19351  a = a<<14;
19352  a |= *p;
19353  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19354  if (!(a&0x80))
19355  {
19356    /* Walues  between 268435456 and 34359738367 */
19357    a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19358    b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19359    b = b<<7;
19360    *v = a | b;
19361    return 5;
19362  }
19363
19364  /* We can only reach this point when reading a corrupt database
19365  ** file.  In that case we are not in any hurry.  Use the (relatively
19366  ** slow) general-purpose sqlite3GetVarint() routine to extract the
19367  ** value. */
19368  {
19369    u64 v64;
19370    u8 n;
19371
19372    p -= 4;
19373    n = sqlite3GetVarint(p, &v64);
19374    assert( n>5 && n<=9 );
19375    *v = (u32)v64;
19376    return n;
19377  }
19378#endif
19379}
19380
19381/*
19382** Return the number of bytes that will be needed to store the given
19383** 64-bit integer.
19384*/
19385SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
19386  int i = 0;
19387  do{
19388    i++;
19389    v >>= 7;
19390  }while( v!=0 && ALWAYS(i<9) );
19391  return i;
19392}
19393
19394
19395/*
19396** Read or write a four-byte big-endian integer value.
19397*/
19398SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
19399  return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
19400}
19401SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
19402  p[0] = (u8)(v>>24);
19403  p[1] = (u8)(v>>16);
19404  p[2] = (u8)(v>>8);
19405  p[3] = (u8)v;
19406}
19407
19408
19409
19410#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19411/*
19412** Translate a single byte of Hex into an integer.
19413** This routine only works if h really is a valid hexadecimal
19414** character:  0..9a..fA..F
19415*/
19416static u8 hexToInt(int h){
19417  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
19418#ifdef SQLITE_ASCII
19419  h += 9*(1&(h>>6));
19420#endif
19421#ifdef SQLITE_EBCDIC
19422  h += 9*(1&~(h>>4));
19423#endif
19424  return (u8)(h & 0xf);
19425}
19426#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19427
19428#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19429/*
19430** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
19431** value.  Return a pointer to its binary value.  Space to hold the
19432** binary value has been obtained from malloc and must be freed by
19433** the calling routine.
19434*/
19435SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
19436  char *zBlob;
19437  int i;
19438
19439  zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
19440  n--;
19441  if( zBlob ){
19442    for(i=0; i<n; i+=2){
19443      zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
19444    }
19445    zBlob[i/2] = 0;
19446  }
19447  return zBlob;
19448}
19449#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19450
19451/*
19452** Log an error that is an API call on a connection pointer that should
19453** not have been used.  The "type" of connection pointer is given as the
19454** argument.  The zType is a word like "NULL" or "closed" or "invalid".
19455*/
19456static void logBadConnection(const char *zType){
19457  sqlite3_log(SQLITE_MISUSE,
19458     "API call with %s database connection pointer",
19459     zType
19460  );
19461}
19462
19463/*
19464** Check to make sure we have a valid db pointer.  This test is not
19465** foolproof but it does provide some measure of protection against
19466** misuse of the interface such as passing in db pointers that are
19467** NULL or which have been previously closed.  If this routine returns
19468** 1 it means that the db pointer is valid and 0 if it should not be
19469** dereferenced for any reason.  The calling function should invoke
19470** SQLITE_MISUSE immediately.
19471**
19472** sqlite3SafetyCheckOk() requires that the db pointer be valid for
19473** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
19474** open properly and is not fit for general use but which can be
19475** used as an argument to sqlite3_errmsg() or sqlite3_close().
19476*/
19477SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
19478  u32 magic;
19479  if( db==0 ){
19480    logBadConnection("NULL");
19481    return 0;
19482  }
19483  magic = db->magic;
19484  if( magic!=SQLITE_MAGIC_OPEN ){
19485    if( !sqlite3SafetyCheckSickOrOk(db) ){
19486      logBadConnection("unopened");
19487    }
19488    return 0;
19489  }else{
19490    return 1;
19491  }
19492}
19493SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
19494  u32 magic;
19495  magic = db->magic;
19496  if( magic!=SQLITE_MAGIC_SICK &&
19497      magic!=SQLITE_MAGIC_OPEN &&
19498      magic!=SQLITE_MAGIC_BUSY ){
19499    logBadConnection("invalid");
19500    return 0;
19501  }else{
19502    return 1;
19503  }
19504}
19505
19506/************** End of util.c ************************************************/
19507/************** Begin file hash.c ********************************************/
19508/*
19509** 2001 September 22
19510**
19511** The author disclaims copyright to this source code.  In place of
19512** a legal notice, here is a blessing:
19513**
19514**    May you do good and not evil.
19515**    May you find forgiveness for yourself and forgive others.
19516**    May you share freely, never taking more than you give.
19517**
19518*************************************************************************
19519** This is the implementation of generic hash-tables
19520** used in SQLite.
19521*/
19522
19523/* Turn bulk memory into a hash table object by initializing the
19524** fields of the Hash structure.
19525**
19526** "pNew" is a pointer to the hash table that is to be initialized.
19527*/
19528SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
19529  assert( pNew!=0 );
19530  pNew->first = 0;
19531  pNew->count = 0;
19532  pNew->htsize = 0;
19533  pNew->ht = 0;
19534}
19535
19536/* Remove all entries from a hash table.  Reclaim all memory.
19537** Call this routine to delete a hash table or to reset a hash table
19538** to the empty state.
19539*/
19540SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
19541  HashElem *elem;         /* For looping over all elements of the table */
19542
19543  assert( pH!=0 );
19544  elem = pH->first;
19545  pH->first = 0;
19546  sqlite3_free(pH->ht);
19547  pH->ht = 0;
19548  pH->htsize = 0;
19549  while( elem ){
19550    HashElem *next_elem = elem->next;
19551    sqlite3_free(elem);
19552    elem = next_elem;
19553  }
19554  pH->count = 0;
19555}
19556
19557/*
19558** The hashing function.
19559*/
19560static unsigned int strHash(const char *z, int nKey){
19561  int h = 0;
19562  assert( nKey>=0 );
19563  while( nKey > 0  ){
19564    h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
19565    nKey--;
19566  }
19567  return h;
19568}
19569
19570
19571/* Link pNew element into the hash table pH.  If pEntry!=0 then also
19572** insert pNew into the pEntry hash bucket.
19573*/
19574static void insertElement(
19575  Hash *pH,              /* The complete hash table */
19576  struct _ht *pEntry,    /* The entry into which pNew is inserted */
19577  HashElem *pNew         /* The element to be inserted */
19578){
19579  HashElem *pHead;       /* First element already in pEntry */
19580  if( pEntry ){
19581    pHead = pEntry->count ? pEntry->chain : 0;
19582    pEntry->count++;
19583    pEntry->chain = pNew;
19584  }else{
19585    pHead = 0;
19586  }
19587  if( pHead ){
19588    pNew->next = pHead;
19589    pNew->prev = pHead->prev;
19590    if( pHead->prev ){ pHead->prev->next = pNew; }
19591    else             { pH->first = pNew; }
19592    pHead->prev = pNew;
19593  }else{
19594    pNew->next = pH->first;
19595    if( pH->first ){ pH->first->prev = pNew; }
19596    pNew->prev = 0;
19597    pH->first = pNew;
19598  }
19599}
19600
19601
19602/* Resize the hash table so that it cantains "new_size" buckets.
19603**
19604** The hash table might fail to resize if sqlite3_malloc() fails or
19605** if the new size is the same as the prior size.
19606** Return TRUE if the resize occurs and false if not.
19607*/
19608static int rehash(Hash *pH, unsigned int new_size){
19609  struct _ht *new_ht;            /* The new hash table */
19610  HashElem *elem, *next_elem;    /* For looping over existing elements */
19611
19612#if SQLITE_MALLOC_SOFT_LIMIT>0
19613  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
19614    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
19615  }
19616  if( new_size==pH->htsize ) return 0;
19617#endif
19618
19619  /* The inability to allocates space for a larger hash table is
19620  ** a performance hit but it is not a fatal error.  So mark the
19621  ** allocation as a benign.
19622  */
19623  sqlite3BeginBenignMalloc();
19624  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
19625  sqlite3EndBenignMalloc();
19626
19627  if( new_ht==0 ) return 0;
19628  sqlite3_free(pH->ht);
19629  pH->ht = new_ht;
19630  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
19631  memset(new_ht, 0, new_size*sizeof(struct _ht));
19632  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
19633    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
19634    next_elem = elem->next;
19635    insertElement(pH, &new_ht[h], elem);
19636  }
19637  return 1;
19638}
19639
19640/* This function (for internal use only) locates an element in an
19641** hash table that matches the given key.  The hash for this key has
19642** already been computed and is passed as the 4th parameter.
19643*/
19644static HashElem *findElementGivenHash(
19645  const Hash *pH,     /* The pH to be searched */
19646  const char *pKey,   /* The key we are searching for */
19647  int nKey,           /* Bytes in key (not counting zero terminator) */
19648  unsigned int h      /* The hash for this key. */
19649){
19650  HashElem *elem;                /* Used to loop thru the element list */
19651  int count;                     /* Number of elements left to test */
19652
19653  if( pH->ht ){
19654    struct _ht *pEntry = &pH->ht[h];
19655    elem = pEntry->chain;
19656    count = pEntry->count;
19657  }else{
19658    elem = pH->first;
19659    count = pH->count;
19660  }
19661  while( count-- && ALWAYS(elem) ){
19662    if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
19663      return elem;
19664    }
19665    elem = elem->next;
19666  }
19667  return 0;
19668}
19669
19670/* Remove a single entry from the hash table given a pointer to that
19671** element and a hash on the element's key.
19672*/
19673static void removeElementGivenHash(
19674  Hash *pH,         /* The pH containing "elem" */
19675  HashElem* elem,   /* The element to be removed from the pH */
19676  unsigned int h    /* Hash value for the element */
19677){
19678  struct _ht *pEntry;
19679  if( elem->prev ){
19680    elem->prev->next = elem->next;
19681  }else{
19682    pH->first = elem->next;
19683  }
19684  if( elem->next ){
19685    elem->next->prev = elem->prev;
19686  }
19687  if( pH->ht ){
19688    pEntry = &pH->ht[h];
19689    if( pEntry->chain==elem ){
19690      pEntry->chain = elem->next;
19691    }
19692    pEntry->count--;
19693    assert( pEntry->count>=0 );
19694  }
19695  sqlite3_free( elem );
19696  pH->count--;
19697  if( pH->count<=0 ){
19698    assert( pH->first==0 );
19699    assert( pH->count==0 );
19700    sqlite3HashClear(pH);
19701  }
19702}
19703
19704/* Attempt to locate an element of the hash table pH with a key
19705** that matches pKey,nKey.  Return the data for this element if it is
19706** found, or NULL if there is no match.
19707*/
19708SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
19709  HashElem *elem;    /* The element that matches key */
19710  unsigned int h;    /* A hash on key */
19711
19712  assert( pH!=0 );
19713  assert( pKey!=0 );
19714  assert( nKey>=0 );
19715  if( pH->ht ){
19716    h = strHash(pKey, nKey) % pH->htsize;
19717  }else{
19718    h = 0;
19719  }
19720  elem = findElementGivenHash(pH, pKey, nKey, h);
19721  return elem ? elem->data : 0;
19722}
19723
19724/* Insert an element into the hash table pH.  The key is pKey,nKey
19725** and the data is "data".
19726**
19727** If no element exists with a matching key, then a new
19728** element is created and NULL is returned.
19729**
19730** If another element already exists with the same key, then the
19731** new data replaces the old data and the old data is returned.
19732** The key is not copied in this instance.  If a malloc fails, then
19733** the new data is returned and the hash table is unchanged.
19734**
19735** If the "data" parameter to this function is NULL, then the
19736** element corresponding to "key" is removed from the hash table.
19737*/
19738SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
19739  unsigned int h;       /* the hash of the key modulo hash table size */
19740  HashElem *elem;       /* Used to loop thru the element list */
19741  HashElem *new_elem;   /* New element added to the pH */
19742
19743  assert( pH!=0 );
19744  assert( pKey!=0 );
19745  assert( nKey>=0 );
19746  if( pH->htsize ){
19747    h = strHash(pKey, nKey) % pH->htsize;
19748  }else{
19749    h = 0;
19750  }
19751  elem = findElementGivenHash(pH,pKey,nKey,h);
19752  if( elem ){
19753    void *old_data = elem->data;
19754    if( data==0 ){
19755      removeElementGivenHash(pH,elem,h);
19756    }else{
19757      elem->data = data;
19758      elem->pKey = pKey;
19759      assert(nKey==elem->nKey);
19760    }
19761    return old_data;
19762  }
19763  if( data==0 ) return 0;
19764  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
19765  if( new_elem==0 ) return data;
19766  new_elem->pKey = pKey;
19767  new_elem->nKey = nKey;
19768  new_elem->data = data;
19769  pH->count++;
19770  if( pH->count>=10 && pH->count > 2*pH->htsize ){
19771    if( rehash(pH, pH->count*2) ){
19772      assert( pH->htsize>0 );
19773      h = strHash(pKey, nKey) % pH->htsize;
19774    }
19775  }
19776  if( pH->ht ){
19777    insertElement(pH, &pH->ht[h], new_elem);
19778  }else{
19779    insertElement(pH, 0, new_elem);
19780  }
19781  return 0;
19782}
19783
19784/************** End of hash.c ************************************************/
19785/************** Begin file opcodes.c *****************************************/
19786/* Automatically generated.  Do not edit */
19787/* See the mkopcodec.awk script for details. */
19788#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
19789SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
19790 static const char *const azName[] = { "?",
19791     /*   1 */ "Goto",
19792     /*   2 */ "Gosub",
19793     /*   3 */ "Return",
19794     /*   4 */ "Yield",
19795     /*   5 */ "HaltIfNull",
19796     /*   6 */ "Halt",
19797     /*   7 */ "Integer",
19798     /*   8 */ "Int64",
19799     /*   9 */ "String",
19800     /*  10 */ "Null",
19801     /*  11 */ "Blob",
19802     /*  12 */ "Variable",
19803     /*  13 */ "Move",
19804     /*  14 */ "Copy",
19805     /*  15 */ "SCopy",
19806     /*  16 */ "ResultRow",
19807     /*  17 */ "CollSeq",
19808     /*  18 */ "Function",
19809     /*  19 */ "Not",
19810     /*  20 */ "AddImm",
19811     /*  21 */ "MustBeInt",
19812     /*  22 */ "RealAffinity",
19813     /*  23 */ "Permutation",
19814     /*  24 */ "Compare",
19815     /*  25 */ "Jump",
19816     /*  26 */ "If",
19817     /*  27 */ "IfNot",
19818     /*  28 */ "Column",
19819     /*  29 */ "Affinity",
19820     /*  30 */ "MakeRecord",
19821     /*  31 */ "Count",
19822     /*  32 */ "Savepoint",
19823     /*  33 */ "AutoCommit",
19824     /*  34 */ "Transaction",
19825     /*  35 */ "ReadCookie",
19826     /*  36 */ "SetCookie",
19827     /*  37 */ "VerifyCookie",
19828     /*  38 */ "OpenRead",
19829     /*  39 */ "OpenWrite",
19830     /*  40 */ "OpenEphemeral",
19831     /*  41 */ "OpenPseudo",
19832     /*  42 */ "Close",
19833     /*  43 */ "SeekLt",
19834     /*  44 */ "SeekLe",
19835     /*  45 */ "SeekGe",
19836     /*  46 */ "SeekGt",
19837     /*  47 */ "Seek",
19838     /*  48 */ "NotFound",
19839     /*  49 */ "Found",
19840     /*  50 */ "IsUnique",
19841     /*  51 */ "NotExists",
19842     /*  52 */ "Sequence",
19843     /*  53 */ "NewRowid",
19844     /*  54 */ "Insert",
19845     /*  55 */ "InsertInt",
19846     /*  56 */ "Delete",
19847     /*  57 */ "ResetCount",
19848     /*  58 */ "RowKey",
19849     /*  59 */ "RowData",
19850     /*  60 */ "Rowid",
19851     /*  61 */ "NullRow",
19852     /*  62 */ "Last",
19853     /*  63 */ "Sort",
19854     /*  64 */ "Rewind",
19855     /*  65 */ "Prev",
19856     /*  66 */ "Next",
19857     /*  67 */ "IdxInsert",
19858     /*  68 */ "Or",
19859     /*  69 */ "And",
19860     /*  70 */ "IdxDelete",
19861     /*  71 */ "IdxRowid",
19862     /*  72 */ "IdxLT",
19863     /*  73 */ "IsNull",
19864     /*  74 */ "NotNull",
19865     /*  75 */ "Ne",
19866     /*  76 */ "Eq",
19867     /*  77 */ "Gt",
19868     /*  78 */ "Le",
19869     /*  79 */ "Lt",
19870     /*  80 */ "Ge",
19871     /*  81 */ "IdxGE",
19872     /*  82 */ "BitAnd",
19873     /*  83 */ "BitOr",
19874     /*  84 */ "ShiftLeft",
19875     /*  85 */ "ShiftRight",
19876     /*  86 */ "Add",
19877     /*  87 */ "Subtract",
19878     /*  88 */ "Multiply",
19879     /*  89 */ "Divide",
19880     /*  90 */ "Remainder",
19881     /*  91 */ "Concat",
19882     /*  92 */ "Destroy",
19883     /*  93 */ "BitNot",
19884     /*  94 */ "String8",
19885     /*  95 */ "Clear",
19886     /*  96 */ "CreateIndex",
19887     /*  97 */ "CreateTable",
19888     /*  98 */ "ParseSchema",
19889     /*  99 */ "LoadAnalysis",
19890     /* 100 */ "DropTable",
19891     /* 101 */ "DropIndex",
19892     /* 102 */ "DropTrigger",
19893     /* 103 */ "IntegrityCk",
19894     /* 104 */ "RowSetAdd",
19895     /* 105 */ "RowSetRead",
19896     /* 106 */ "RowSetTest",
19897     /* 107 */ "Program",
19898     /* 108 */ "Param",
19899     /* 109 */ "FkCounter",
19900     /* 110 */ "FkIfZero",
19901     /* 111 */ "MemMax",
19902     /* 112 */ "IfPos",
19903     /* 113 */ "IfNeg",
19904     /* 114 */ "IfZero",
19905     /* 115 */ "AggStep",
19906     /* 116 */ "AggFinal",
19907     /* 117 */ "Vacuum",
19908     /* 118 */ "IncrVacuum",
19909     /* 119 */ "Expire",
19910     /* 120 */ "TableLock",
19911     /* 121 */ "VBegin",
19912     /* 122 */ "VCreate",
19913     /* 123 */ "VDestroy",
19914     /* 124 */ "VOpen",
19915     /* 125 */ "VFilter",
19916     /* 126 */ "VColumn",
19917     /* 127 */ "VNext",
19918     /* 128 */ "VRename",
19919     /* 129 */ "VUpdate",
19920     /* 130 */ "Real",
19921     /* 131 */ "Pagecount",
19922     /* 132 */ "Trace",
19923     /* 133 */ "Noop",
19924     /* 134 */ "Explain",
19925     /* 135 */ "NotUsed_135",
19926     /* 136 */ "NotUsed_136",
19927     /* 137 */ "NotUsed_137",
19928     /* 138 */ "NotUsed_138",
19929     /* 139 */ "NotUsed_139",
19930     /* 140 */ "NotUsed_140",
19931     /* 141 */ "ToText",
19932     /* 142 */ "ToBlob",
19933     /* 143 */ "ToNumeric",
19934     /* 144 */ "ToInt",
19935     /* 145 */ "ToReal",
19936  };
19937  return azName[i];
19938}
19939#endif
19940
19941/************** End of opcodes.c *********************************************/
19942/************** Begin file os_os2.c ******************************************/
19943/*
19944** 2006 Feb 14
19945**
19946** The author disclaims copyright to this source code.  In place of
19947** a legal notice, here is a blessing:
19948**
19949**    May you do good and not evil.
19950**    May you find forgiveness for yourself and forgive others.
19951**    May you share freely, never taking more than you give.
19952**
19953******************************************************************************
19954**
19955** This file contains code that is specific to OS/2.
19956*/
19957
19958
19959#if SQLITE_OS_OS2
19960
19961/*
19962** A Note About Memory Allocation:
19963**
19964** This driver uses malloc()/free() directly rather than going through
19965** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
19966** are designed for use on embedded systems where memory is scarce and
19967** malloc failures happen frequently.  OS/2 does not typically run on
19968** embedded systems, and when it does the developers normally have bigger
19969** problems to worry about than running out of memory.  So there is not
19970** a compelling need to use the wrappers.
19971**
19972** But there is a good reason to not use the wrappers.  If we use the
19973** wrappers then we will get simulated malloc() failures within this
19974** driver.  And that causes all kinds of problems for our tests.  We
19975** could enhance SQLite to deal with simulated malloc failures within
19976** the OS driver, but the code to deal with those failure would not
19977** be exercised on Linux (which does not need to malloc() in the driver)
19978** and so we would have difficulty writing coverage tests for that
19979** code.  Better to leave the code out, we think.
19980**
19981** The point of this discussion is as follows:  When creating a new
19982** OS layer for an embedded system, if you use this file as an example,
19983** avoid the use of malloc()/free().  Those routines work ok on OS/2
19984** desktops but not so well in embedded systems.
19985*/
19986
19987/*
19988** Macros used to determine whether or not to use threads.
19989*/
19990#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
19991# define SQLITE_OS2_THREADS 1
19992#endif
19993
19994/*
19995** Include code that is common to all os_*.c files
19996*/
19997/************** Include os_common.h in the middle of os_os2.c ****************/
19998/************** Begin file os_common.h ***************************************/
19999/*
20000** 2004 May 22
20001**
20002** The author disclaims copyright to this source code.  In place of
20003** a legal notice, here is a blessing:
20004**
20005**    May you do good and not evil.
20006**    May you find forgiveness for yourself and forgive others.
20007**    May you share freely, never taking more than you give.
20008**
20009******************************************************************************
20010**
20011** This file contains macros and a little bit of code that is common to
20012** all of the platform-specific files (os_*.c) and is #included into those
20013** files.
20014**
20015** This file should be #included by the os_*.c files only.  It is not a
20016** general purpose header file.
20017*/
20018#ifndef _OS_COMMON_H_
20019#define _OS_COMMON_H_
20020
20021/*
20022** At least two bugs have slipped in because we changed the MEMORY_DEBUG
20023** macro to SQLITE_DEBUG and some older makefiles have not yet made the
20024** switch.  The following code should catch this problem at compile-time.
20025*/
20026#ifdef MEMORY_DEBUG
20027# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
20028#endif
20029
20030#ifdef SQLITE_DEBUG
20031SQLITE_PRIVATE int sqlite3OSTrace = 0;
20032#define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
20033#define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
20034#define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
20035#define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
20036#define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
20037#define OSTRACE6(X,Y,Z,A,B,C) \
20038    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
20039#define OSTRACE7(X,Y,Z,A,B,C,D) \
20040    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
20041#else
20042#define OSTRACE1(X)
20043#define OSTRACE2(X,Y)
20044#define OSTRACE3(X,Y,Z)
20045#define OSTRACE4(X,Y,Z,A)
20046#define OSTRACE5(X,Y,Z,A,B)
20047#define OSTRACE6(X,Y,Z,A,B,C)
20048#define OSTRACE7(X,Y,Z,A,B,C,D)
20049#endif
20050
20051/*
20052** Macros for performance tracing.  Normally turned off.  Only works
20053** on i486 hardware.
20054*/
20055#ifdef SQLITE_PERFORMANCE_TRACE
20056
20057/*
20058** hwtime.h contains inline assembler code for implementing
20059** high-performance timing routines.
20060*/
20061/************** Include hwtime.h in the middle of os_common.h ****************/
20062/************** Begin file hwtime.h ******************************************/
20063/*
20064** 2008 May 27
20065**
20066** The author disclaims copyright to this source code.  In place of
20067** a legal notice, here is a blessing:
20068**
20069**    May you do good and not evil.
20070**    May you find forgiveness for yourself and forgive others.
20071**    May you share freely, never taking more than you give.
20072**
20073******************************************************************************
20074**
20075** This file contains inline asm code for retrieving "high-performance"
20076** counters for x86 class CPUs.
20077*/
20078#ifndef _HWTIME_H_
20079#define _HWTIME_H_
20080
20081/*
20082** The following routine only works on pentium-class (or newer) processors.
20083** It uses the RDTSC opcode to read the cycle count value out of the
20084** processor and returns that value.  This can be used for high-res
20085** profiling.
20086*/
20087#if (defined(__GNUC__) || defined(_MSC_VER)) && \
20088      (defined(i386) || defined(__i386__) || defined(_M_IX86))
20089
20090  #if defined(__GNUC__)
20091
20092  __inline__ sqlite_uint64 sqlite3Hwtime(void){
20093     unsigned int lo, hi;
20094     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
20095     return (sqlite_uint64)hi << 32 | lo;
20096  }
20097
20098  #elif defined(_MSC_VER)
20099
20100  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
20101     __asm {
20102        rdtsc
20103        ret       ; return value at EDX:EAX
20104     }
20105  }
20106
20107  #endif
20108
20109#elif (defined(__GNUC__) && defined(__x86_64__))
20110
20111  __inline__ sqlite_uint64 sqlite3Hwtime(void){
20112      unsigned long val;
20113      __asm__ __volatile__ ("rdtsc" : "=A" (val));
20114      return val;
20115  }
20116
20117#elif (defined(__GNUC__) && defined(__ppc__))
20118
20119  __inline__ sqlite_uint64 sqlite3Hwtime(void){
20120      unsigned long long retval;
20121      unsigned long junk;
20122      __asm__ __volatile__ ("\n\
20123          1:      mftbu   %1\n\
20124                  mftb    %L0\n\
20125                  mftbu   %0\n\
20126                  cmpw    %0,%1\n\
20127                  bne     1b"
20128                  : "=r" (retval), "=r" (junk));
20129      return retval;
20130  }
20131
20132#else
20133
20134  #error Need implementation of sqlite3Hwtime() for your platform.
20135
20136  /*
20137  ** To compile without implementing sqlite3Hwtime() for your platform,
20138  ** you can remove the above #error and use the following
20139  ** stub function.  You will lose timing support for many
20140  ** of the debugging and testing utilities, but it should at
20141  ** least compile and run.
20142  */
20143SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
20144
20145#endif
20146
20147#endif /* !defined(_HWTIME_H_) */
20148
20149/************** End of hwtime.h **********************************************/
20150/************** Continuing where we left off in os_common.h ******************/
20151
20152static sqlite_uint64 g_start;
20153static sqlite_uint64 g_elapsed;
20154#define TIMER_START       g_start=sqlite3Hwtime()
20155#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
20156#define TIMER_ELAPSED     g_elapsed
20157#else
20158#define TIMER_START
20159#define TIMER_END
20160#define TIMER_ELAPSED     ((sqlite_uint64)0)
20161#endif
20162
20163/*
20164** If we compile with the SQLITE_TEST macro set, then the following block
20165** of code will give us the ability to simulate a disk I/O error.  This
20166** is used for testing the I/O recovery logic.
20167*/
20168#ifdef SQLITE_TEST
20169SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
20170SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
20171SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
20172SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
20173SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
20174SQLITE_API int sqlite3_diskfull_pending = 0;
20175SQLITE_API int sqlite3_diskfull = 0;
20176#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
20177#define SimulateIOError(CODE)  \
20178  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
20179       || sqlite3_io_error_pending-- == 1 )  \
20180              { local_ioerr(); CODE; }
20181static void local_ioerr(){
20182  IOTRACE(("IOERR\n"));
20183  sqlite3_io_error_hit++;
20184  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
20185}
20186#define SimulateDiskfullError(CODE) \
20187   if( sqlite3_diskfull_pending ){ \
20188     if( sqlite3_diskfull_pending == 1 ){ \
20189       local_ioerr(); \
20190       sqlite3_diskfull = 1; \
20191       sqlite3_io_error_hit = 1; \
20192       CODE; \
20193     }else{ \
20194       sqlite3_diskfull_pending--; \
20195     } \
20196   }
20197#else
20198#define SimulateIOErrorBenign(X)
20199#define SimulateIOError(A)
20200#define SimulateDiskfullError(A)
20201#endif
20202
20203/*
20204** When testing, keep a count of the number of open files.
20205*/
20206#ifdef SQLITE_TEST
20207SQLITE_API int sqlite3_open_file_count = 0;
20208#define OpenCounter(X)  sqlite3_open_file_count+=(X)
20209#else
20210#define OpenCounter(X)
20211#endif
20212
20213#endif /* !defined(_OS_COMMON_H_) */
20214
20215/************** End of os_common.h *******************************************/
20216/************** Continuing where we left off in os_os2.c *********************/
20217
20218/*
20219** The os2File structure is subclass of sqlite3_file specific for the OS/2
20220** protability layer.
20221*/
20222typedef struct os2File os2File;
20223struct os2File {
20224  const sqlite3_io_methods *pMethod;  /* Always the first entry */
20225  HFILE h;                  /* Handle for accessing the file */
20226  char* pathToDel;          /* Name of file to delete on close, NULL if not */
20227  unsigned char locktype;   /* Type of lock currently held on this file */
20228};
20229
20230#define LOCK_TIMEOUT 10L /* the default locking timeout */
20231
20232/*****************************************************************************
20233** The next group of routines implement the I/O methods specified
20234** by the sqlite3_io_methods object.
20235******************************************************************************/
20236
20237/*
20238** Close a file.
20239*/
20240static int os2Close( sqlite3_file *id ){
20241  APIRET rc = NO_ERROR;
20242  os2File *pFile;
20243  if( id && (pFile = (os2File*)id) != 0 ){
20244    OSTRACE2( "CLOSE %d\n", pFile->h );
20245    rc = DosClose( pFile->h );
20246    pFile->locktype = NO_LOCK;
20247    if( pFile->pathToDel != NULL ){
20248      rc = DosForceDelete( (PSZ)pFile->pathToDel );
20249      free( pFile->pathToDel );
20250      pFile->pathToDel = NULL;
20251    }
20252    id = 0;
20253    OpenCounter( -1 );
20254  }
20255
20256  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20257}
20258
20259/*
20260** Read data from a file into a buffer.  Return SQLITE_OK if all
20261** bytes were read successfully and SQLITE_IOERR if anything goes
20262** wrong.
20263*/
20264static int os2Read(
20265  sqlite3_file *id,               /* File to read from */
20266  void *pBuf,                     /* Write content into this buffer */
20267  int amt,                        /* Number of bytes to read */
20268  sqlite3_int64 offset            /* Begin reading at this offset */
20269){
20270  ULONG fileLocation = 0L;
20271  ULONG got;
20272  os2File *pFile = (os2File*)id;
20273  assert( id!=0 );
20274  SimulateIOError( return SQLITE_IOERR_READ );
20275  OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
20276  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20277    return SQLITE_IOERR;
20278  }
20279  if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
20280    return SQLITE_IOERR_READ;
20281  }
20282  if( got == (ULONG)amt )
20283    return SQLITE_OK;
20284  else {
20285    /* Unread portions of the input buffer must be zero-filled */
20286    memset(&((char*)pBuf)[got], 0, amt-got);
20287    return SQLITE_IOERR_SHORT_READ;
20288  }
20289}
20290
20291/*
20292** Write data from a buffer into a file.  Return SQLITE_OK on success
20293** or some other error code on failure.
20294*/
20295static int os2Write(
20296  sqlite3_file *id,               /* File to write into */
20297  const void *pBuf,               /* The bytes to be written */
20298  int amt,                        /* Number of bytes to write */
20299  sqlite3_int64 offset            /* Offset into the file to begin writing at */
20300){
20301  ULONG fileLocation = 0L;
20302  APIRET rc = NO_ERROR;
20303  ULONG wrote;
20304  os2File *pFile = (os2File*)id;
20305  assert( id!=0 );
20306  SimulateIOError( return SQLITE_IOERR_WRITE );
20307  SimulateDiskfullError( return SQLITE_FULL );
20308  OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
20309  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20310    return SQLITE_IOERR;
20311  }
20312  assert( amt>0 );
20313  while( amt > 0 &&
20314         ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
20315         wrote > 0
20316  ){
20317    amt -= wrote;
20318    pBuf = &((char*)pBuf)[wrote];
20319  }
20320
20321  return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
20322}
20323
20324/*
20325** Truncate an open file to a specified size
20326*/
20327static int os2Truncate( sqlite3_file *id, i64 nByte ){
20328  APIRET rc = NO_ERROR;
20329  os2File *pFile = (os2File*)id;
20330  OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
20331  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
20332  rc = DosSetFileSize( pFile->h, nByte );
20333  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
20334}
20335
20336#ifdef SQLITE_TEST
20337/*
20338** Count the number of fullsyncs and normal syncs.  This is used to test
20339** that syncs and fullsyncs are occuring at the right times.
20340*/
20341SQLITE_API int sqlite3_sync_count = 0;
20342SQLITE_API int sqlite3_fullsync_count = 0;
20343#endif
20344
20345/*
20346** Make sure all writes to a particular file are committed to disk.
20347*/
20348static int os2Sync( sqlite3_file *id, int flags ){
20349  os2File *pFile = (os2File*)id;
20350  OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
20351#ifdef SQLITE_TEST
20352  if( flags & SQLITE_SYNC_FULL){
20353    sqlite3_fullsync_count++;
20354  }
20355  sqlite3_sync_count++;
20356#endif
20357  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
20358  ** no-op
20359  */
20360#ifdef SQLITE_NO_SYNC
20361  UNUSED_PARAMETER(pFile);
20362  return SQLITE_OK;
20363#else
20364  return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20365#endif
20366}
20367
20368/*
20369** Determine the current size of a file in bytes
20370*/
20371static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
20372  APIRET rc = NO_ERROR;
20373  FILESTATUS3 fsts3FileInfo;
20374  memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
20375  assert( id!=0 );
20376  SimulateIOError( return SQLITE_IOERR_FSTAT );
20377  rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
20378  if( rc == NO_ERROR ){
20379    *pSize = fsts3FileInfo.cbFile;
20380    return SQLITE_OK;
20381  }else{
20382    return SQLITE_IOERR_FSTAT;
20383  }
20384}
20385
20386/*
20387** Acquire a reader lock.
20388*/
20389static int getReadLock( os2File *pFile ){
20390  FILELOCK  LockArea,
20391            UnlockArea;
20392  APIRET res;
20393  memset(&LockArea, 0, sizeof(LockArea));
20394  memset(&UnlockArea, 0, sizeof(UnlockArea));
20395  LockArea.lOffset = SHARED_FIRST;
20396  LockArea.lRange = SHARED_SIZE;
20397  UnlockArea.lOffset = 0L;
20398  UnlockArea.lRange = 0L;
20399  res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20400  OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
20401  return res;
20402}
20403
20404/*
20405** Undo a readlock
20406*/
20407static int unlockReadLock( os2File *id ){
20408  FILELOCK  LockArea,
20409            UnlockArea;
20410  APIRET res;
20411  memset(&LockArea, 0, sizeof(LockArea));
20412  memset(&UnlockArea, 0, sizeof(UnlockArea));
20413  LockArea.lOffset = 0L;
20414  LockArea.lRange = 0L;
20415  UnlockArea.lOffset = SHARED_FIRST;
20416  UnlockArea.lRange = SHARED_SIZE;
20417  res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20418  OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
20419  return res;
20420}
20421
20422/*
20423** Lock the file with the lock specified by parameter locktype - one
20424** of the following:
20425**
20426**     (1) SHARED_LOCK
20427**     (2) RESERVED_LOCK
20428**     (3) PENDING_LOCK
20429**     (4) EXCLUSIVE_LOCK
20430**
20431** Sometimes when requesting one lock state, additional lock states
20432** are inserted in between.  The locking might fail on one of the later
20433** transitions leaving the lock state different from what it started but
20434** still short of its goal.  The following chart shows the allowed
20435** transitions and the inserted intermediate states:
20436**
20437**    UNLOCKED -> SHARED
20438**    SHARED -> RESERVED
20439**    SHARED -> (PENDING) -> EXCLUSIVE
20440**    RESERVED -> (PENDING) -> EXCLUSIVE
20441**    PENDING -> EXCLUSIVE
20442**
20443** This routine will only increase a lock.  The os2Unlock() routine
20444** erases all locks at once and returns us immediately to locking level 0.
20445** It is not possible to lower the locking level one step at a time.  You
20446** must go straight to locking level 0.
20447*/
20448static int os2Lock( sqlite3_file *id, int locktype ){
20449  int rc = SQLITE_OK;       /* Return code from subroutines */
20450  APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
20451  int newLocktype;       /* Set pFile->locktype to this value before exiting */
20452  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
20453  FILELOCK  LockArea,
20454            UnlockArea;
20455  os2File *pFile = (os2File*)id;
20456  memset(&LockArea, 0, sizeof(LockArea));
20457  memset(&UnlockArea, 0, sizeof(UnlockArea));
20458  assert( pFile!=0 );
20459  OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
20460
20461  /* If there is already a lock of this type or more restrictive on the
20462  ** os2File, do nothing. Don't use the end_lock: exit path, as
20463  ** sqlite3_mutex_enter() hasn't been called yet.
20464  */
20465  if( pFile->locktype>=locktype ){
20466    OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
20467    return SQLITE_OK;
20468  }
20469
20470  /* Make sure the locking sequence is correct
20471  */
20472  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
20473  assert( locktype!=PENDING_LOCK );
20474  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
20475
20476  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
20477  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
20478  ** the PENDING_LOCK byte is temporary.
20479  */
20480  newLocktype = pFile->locktype;
20481  if( pFile->locktype==NO_LOCK
20482      || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
20483  ){
20484    LockArea.lOffset = PENDING_BYTE;
20485    LockArea.lRange = 1L;
20486    UnlockArea.lOffset = 0L;
20487    UnlockArea.lRange = 0L;
20488
20489    /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
20490    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
20491    if( res == NO_ERROR ){
20492      gotPendingLock = 1;
20493      OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
20494    }
20495  }
20496
20497  /* Acquire a shared lock
20498  */
20499  if( locktype==SHARED_LOCK && res == NO_ERROR ){
20500    assert( pFile->locktype==NO_LOCK );
20501    res = getReadLock(pFile);
20502    if( res == NO_ERROR ){
20503      newLocktype = SHARED_LOCK;
20504    }
20505    OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
20506  }
20507
20508  /* Acquire a RESERVED lock
20509  */
20510  if( locktype==RESERVED_LOCK && res == NO_ERROR ){
20511    assert( pFile->locktype==SHARED_LOCK );
20512    LockArea.lOffset = RESERVED_BYTE;
20513    LockArea.lRange = 1L;
20514    UnlockArea.lOffset = 0L;
20515    UnlockArea.lRange = 0L;
20516    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20517    if( res == NO_ERROR ){
20518      newLocktype = RESERVED_LOCK;
20519    }
20520    OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
20521  }
20522
20523  /* Acquire a PENDING lock
20524  */
20525  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20526    newLocktype = PENDING_LOCK;
20527    gotPendingLock = 0;
20528    OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
20529  }
20530
20531  /* Acquire an EXCLUSIVE lock
20532  */
20533  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20534    assert( pFile->locktype>=SHARED_LOCK );
20535    res = unlockReadLock(pFile);
20536    OSTRACE2( "unreadlock = %d\n", res );
20537    LockArea.lOffset = SHARED_FIRST;
20538    LockArea.lRange = SHARED_SIZE;
20539    UnlockArea.lOffset = 0L;
20540    UnlockArea.lRange = 0L;
20541    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20542    if( res == NO_ERROR ){
20543      newLocktype = EXCLUSIVE_LOCK;
20544    }else{
20545      OSTRACE2( "OS/2 error-code = %d\n", res );
20546      getReadLock(pFile);
20547    }
20548    OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
20549  }
20550
20551  /* If we are holding a PENDING lock that ought to be released, then
20552  ** release it now.
20553  */
20554  if( gotPendingLock && locktype==SHARED_LOCK ){
20555    int r;
20556    LockArea.lOffset = 0L;
20557    LockArea.lRange = 0L;
20558    UnlockArea.lOffset = PENDING_BYTE;
20559    UnlockArea.lRange = 1L;
20560    r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20561    OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
20562  }
20563
20564  /* Update the state of the lock has held in the file descriptor then
20565  ** return the appropriate result code.
20566  */
20567  if( res == NO_ERROR ){
20568    rc = SQLITE_OK;
20569  }else{
20570    OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
20571              locktype, newLocktype );
20572    rc = SQLITE_BUSY;
20573  }
20574  pFile->locktype = newLocktype;
20575  OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
20576  return rc;
20577}
20578
20579/*
20580** This routine checks if there is a RESERVED lock held on the specified
20581** file by this or any other process. If such a lock is held, return
20582** non-zero, otherwise zero.
20583*/
20584static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
20585  int r = 0;
20586  os2File *pFile = (os2File*)id;
20587  assert( pFile!=0 );
20588  if( pFile->locktype>=RESERVED_LOCK ){
20589    r = 1;
20590    OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
20591  }else{
20592    FILELOCK  LockArea,
20593              UnlockArea;
20594    APIRET rc = NO_ERROR;
20595    memset(&LockArea, 0, sizeof(LockArea));
20596    memset(&UnlockArea, 0, sizeof(UnlockArea));
20597    LockArea.lOffset = RESERVED_BYTE;
20598    LockArea.lRange = 1L;
20599    UnlockArea.lOffset = 0L;
20600    UnlockArea.lRange = 0L;
20601    rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20602    OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
20603    if( rc == NO_ERROR ){
20604      APIRET rcu = NO_ERROR; /* return code for unlocking */
20605      LockArea.lOffset = 0L;
20606      LockArea.lRange = 0L;
20607      UnlockArea.lOffset = RESERVED_BYTE;
20608      UnlockArea.lRange = 1L;
20609      rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20610      OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
20611    }
20612    r = !(rc == NO_ERROR);
20613    OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
20614  }
20615  *pOut = r;
20616  return SQLITE_OK;
20617}
20618
20619/*
20620** Lower the locking level on file descriptor id to locktype.  locktype
20621** must be either NO_LOCK or SHARED_LOCK.
20622**
20623** If the locking level of the file descriptor is already at or below
20624** the requested locking level, this routine is a no-op.
20625**
20626** It is not possible for this routine to fail if the second argument
20627** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
20628** might return SQLITE_IOERR;
20629*/
20630static int os2Unlock( sqlite3_file *id, int locktype ){
20631  int type;
20632  os2File *pFile = (os2File*)id;
20633  APIRET rc = SQLITE_OK;
20634  APIRET res = NO_ERROR;
20635  FILELOCK  LockArea,
20636            UnlockArea;
20637  memset(&LockArea, 0, sizeof(LockArea));
20638  memset(&UnlockArea, 0, sizeof(UnlockArea));
20639  assert( pFile!=0 );
20640  assert( locktype<=SHARED_LOCK );
20641  OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
20642  type = pFile->locktype;
20643  if( type>=EXCLUSIVE_LOCK ){
20644    LockArea.lOffset = 0L;
20645    LockArea.lRange = 0L;
20646    UnlockArea.lOffset = SHARED_FIRST;
20647    UnlockArea.lRange = SHARED_SIZE;
20648    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20649    OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
20650    if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
20651      /* This should never happen.  We should always be able to
20652      ** reacquire the read lock */
20653      OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
20654      rc = SQLITE_IOERR_UNLOCK;
20655    }
20656  }
20657  if( type>=RESERVED_LOCK ){
20658    LockArea.lOffset = 0L;
20659    LockArea.lRange = 0L;
20660    UnlockArea.lOffset = RESERVED_BYTE;
20661    UnlockArea.lRange = 1L;
20662    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20663    OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
20664  }
20665  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
20666    res = unlockReadLock(pFile);
20667    OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
20668  }
20669  if( type>=PENDING_LOCK ){
20670    LockArea.lOffset = 0L;
20671    LockArea.lRange = 0L;
20672    UnlockArea.lOffset = PENDING_BYTE;
20673    UnlockArea.lRange = 1L;
20674    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20675    OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
20676  }
20677  pFile->locktype = locktype;
20678  OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
20679  return rc;
20680}
20681
20682/*
20683** Control and query of the open file handle.
20684*/
20685static int os2FileControl(sqlite3_file *id, int op, void *pArg){
20686  switch( op ){
20687    case SQLITE_FCNTL_LOCKSTATE: {
20688      *(int*)pArg = ((os2File*)id)->locktype;
20689      OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
20690      return SQLITE_OK;
20691    }
20692  }
20693  return SQLITE_ERROR;
20694}
20695
20696/*
20697** Return the sector size in bytes of the underlying block device for
20698** the specified file. This is almost always 512 bytes, but may be
20699** larger for some devices.
20700**
20701** SQLite code assumes this function cannot fail. It also assumes that
20702** if two files are created in the same file-system directory (i.e.
20703** a database and its journal file) that the sector size will be the
20704** same for both.
20705*/
20706static int os2SectorSize(sqlite3_file *id){
20707  return SQLITE_DEFAULT_SECTOR_SIZE;
20708}
20709
20710/*
20711** Return a vector of device characteristics.
20712*/
20713static int os2DeviceCharacteristics(sqlite3_file *id){
20714  return 0;
20715}
20716
20717
20718/*
20719** Character set conversion objects used by conversion routines.
20720*/
20721static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
20722static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
20723
20724/*
20725** Helper function to initialize the conversion objects from and to UTF-8.
20726*/
20727static void initUconvObjects( void ){
20728  if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
20729    ucUtf8 = NULL;
20730  if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
20731    uclCp = NULL;
20732}
20733
20734/*
20735** Helper function to free the conversion objects from and to UTF-8.
20736*/
20737static void freeUconvObjects( void ){
20738  if ( ucUtf8 )
20739    UniFreeUconvObject( ucUtf8 );
20740  if ( uclCp )
20741    UniFreeUconvObject( uclCp );
20742  ucUtf8 = NULL;
20743  uclCp = NULL;
20744}
20745
20746/*
20747** Helper function to convert UTF-8 filenames to local OS/2 codepage.
20748** The two-step process: first convert the incoming UTF-8 string
20749** into UCS-2 and then from UCS-2 to the current codepage.
20750** The returned char pointer has to be freed.
20751*/
20752static char *convertUtf8PathToCp( const char *in ){
20753  UniChar tempPath[CCHMAXPATH];
20754  char *out = (char *)calloc( CCHMAXPATH, 1 );
20755
20756  if( !out )
20757    return NULL;
20758
20759  if( !ucUtf8 || !uclCp )
20760    initUconvObjects();
20761
20762  /* determine string for the conversion of UTF-8 which is CP1208 */
20763  if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
20764    return out; /* if conversion fails, return the empty string */
20765
20766  /* conversion for current codepage which can be used for paths */
20767  UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
20768
20769  return out;
20770}
20771
20772/*
20773** Helper function to convert filenames from local codepage to UTF-8.
20774** The two-step process: first convert the incoming codepage-specific
20775** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
20776** The returned char pointer has to be freed.
20777**
20778** This function is non-static to be able to use this in shell.c and
20779** similar applications that take command line arguments.
20780*/
20781char *convertCpPathToUtf8( const char *in ){
20782  UniChar tempPath[CCHMAXPATH];
20783  char *out = (char *)calloc( CCHMAXPATH, 1 );
20784
20785  if( !out )
20786    return NULL;
20787
20788  if( !ucUtf8 || !uclCp )
20789    initUconvObjects();
20790
20791  /* conversion for current codepage which can be used for paths */
20792  if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
20793    return out; /* if conversion fails, return the empty string */
20794
20795  /* determine string for the conversion of UTF-8 which is CP1208 */
20796  UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
20797
20798  return out;
20799}
20800
20801/*
20802** This vector defines all the methods that can operate on an
20803** sqlite3_file for os2.
20804*/
20805static const sqlite3_io_methods os2IoMethod = {
20806  1,                        /* iVersion */
20807  os2Close,
20808  os2Read,
20809  os2Write,
20810  os2Truncate,
20811  os2Sync,
20812  os2FileSize,
20813  os2Lock,
20814  os2Unlock,
20815  os2CheckReservedLock,
20816  os2FileControl,
20817  os2SectorSize,
20818  os2DeviceCharacteristics
20819};
20820
20821/***************************************************************************
20822** Here ends the I/O methods that form the sqlite3_io_methods object.
20823**
20824** The next block of code implements the VFS methods.
20825****************************************************************************/
20826
20827/*
20828** Create a temporary file name in zBuf.  zBuf must be big enough to
20829** hold at pVfs->mxPathname characters.
20830*/
20831static int getTempname(int nBuf, char *zBuf ){
20832  static const unsigned char zChars[] =
20833    "abcdefghijklmnopqrstuvwxyz"
20834    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
20835    "0123456789";
20836  int i, j;
20837  char zTempPathBuf[3];
20838  PSZ zTempPath = (PSZ)&zTempPathBuf;
20839  if( sqlite3_temp_directory ){
20840    zTempPath = sqlite3_temp_directory;
20841  }else{
20842    if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
20843      if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
20844        if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
20845           ULONG ulDriveNum = 0, ulDriveMap = 0;
20846           DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
20847           sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
20848        }
20849      }
20850    }
20851  }
20852  /* Strip off a trailing slashes or backslashes, otherwise we would get *
20853   * multiple (back)slashes which causes DosOpen() to fail.              *
20854   * Trailing spaces are not allowed, either.                            */
20855  j = sqlite3Strlen30(zTempPath);
20856  while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
20857                    || zTempPath[j-1] == ' ' ) ){
20858    j--;
20859  }
20860  zTempPath[j] = '\0';
20861  if( !sqlite3_temp_directory ){
20862    char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
20863    sqlite3_snprintf( nBuf-30, zBuf,
20864                      "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
20865    free( zTempPathUTF );
20866  }else{
20867    sqlite3_snprintf( nBuf-30, zBuf,
20868                      "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
20869  }
20870  j = sqlite3Strlen30( zBuf );
20871  sqlite3_randomness( 20, &zBuf[j] );
20872  for( i = 0; i < 20; i++, j++ ){
20873    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
20874  }
20875  zBuf[j] = 0;
20876  OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
20877  return SQLITE_OK;
20878}
20879
20880
20881/*
20882** Turn a relative pathname into a full pathname.  Write the full
20883** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
20884** bytes in size.
20885*/
20886static int os2FullPathname(
20887  sqlite3_vfs *pVfs,          /* Pointer to vfs object */
20888  const char *zRelative,      /* Possibly relative input path */
20889  int nFull,                  /* Size of output buffer in bytes */
20890  char *zFull                 /* Output buffer */
20891){
20892  char *zRelativeCp = convertUtf8PathToCp( zRelative );
20893  char zFullCp[CCHMAXPATH] = "\0";
20894  char *zFullUTF;
20895  APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
20896                                CCHMAXPATH );
20897  free( zRelativeCp );
20898  zFullUTF = convertCpPathToUtf8( zFullCp );
20899  sqlite3_snprintf( nFull, zFull, zFullUTF );
20900  free( zFullUTF );
20901  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20902}
20903
20904
20905/*
20906** Open a file.
20907*/
20908static int os2Open(
20909  sqlite3_vfs *pVfs,            /* Not used */
20910  const char *zName,            /* Name of the file */
20911  sqlite3_file *id,             /* Write the SQLite file handle here */
20912  int flags,                    /* Open mode flags */
20913  int *pOutFlags                /* Status return flags */
20914){
20915  HFILE h;
20916  ULONG ulFileAttribute = FILE_NORMAL;
20917  ULONG ulOpenFlags = 0;
20918  ULONG ulOpenMode = 0;
20919  os2File *pFile = (os2File*)id;
20920  APIRET rc = NO_ERROR;
20921  ULONG ulAction;
20922  char *zNameCp;
20923  char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
20924
20925  /* If the second argument to this function is NULL, generate a
20926  ** temporary file name to use
20927  */
20928  if( !zName ){
20929    int rc = getTempname(CCHMAXPATH+1, zTmpname);
20930    if( rc!=SQLITE_OK ){
20931      return rc;
20932    }
20933    zName = zTmpname;
20934  }
20935
20936
20937  memset( pFile, 0, sizeof(*pFile) );
20938
20939  OSTRACE2( "OPEN want %d\n", flags );
20940
20941  if( flags & SQLITE_OPEN_READWRITE ){
20942    ulOpenMode |= OPEN_ACCESS_READWRITE;
20943    OSTRACE1( "OPEN read/write\n" );
20944  }else{
20945    ulOpenMode |= OPEN_ACCESS_READONLY;
20946    OSTRACE1( "OPEN read only\n" );
20947  }
20948
20949  if( flags & SQLITE_OPEN_CREATE ){
20950    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
20951    OSTRACE1( "OPEN open new/create\n" );
20952  }else{
20953    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
20954    OSTRACE1( "OPEN open existing\n" );
20955  }
20956
20957  if( flags & SQLITE_OPEN_MAIN_DB ){
20958    ulOpenMode |= OPEN_SHARE_DENYNONE;
20959    OSTRACE1( "OPEN share read/write\n" );
20960  }else{
20961    ulOpenMode |= OPEN_SHARE_DENYWRITE;
20962    OSTRACE1( "OPEN share read only\n" );
20963  }
20964
20965  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
20966    char pathUtf8[CCHMAXPATH];
20967#ifdef NDEBUG /* when debugging we want to make sure it is deleted */
20968    ulFileAttribute = FILE_HIDDEN;
20969#endif
20970    os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
20971    pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
20972    OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
20973  }else{
20974    pFile->pathToDel = NULL;
20975    OSTRACE1( "OPEN normal file attribute\n" );
20976  }
20977
20978  /* always open in random access mode for possibly better speed */
20979  ulOpenMode |= OPEN_FLAGS_RANDOM;
20980  ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
20981  ulOpenMode |= OPEN_FLAGS_NOINHERIT;
20982
20983  zNameCp = convertUtf8PathToCp( zName );
20984  rc = DosOpen( (PSZ)zNameCp,
20985                &h,
20986                &ulAction,
20987                0L,
20988                ulFileAttribute,
20989                ulOpenFlags,
20990                ulOpenMode,
20991                (PEAOP2)NULL );
20992  free( zNameCp );
20993  if( rc != NO_ERROR ){
20994    OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
20995              rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
20996    if( pFile->pathToDel )
20997      free( pFile->pathToDel );
20998    pFile->pathToDel = NULL;
20999    if( flags & SQLITE_OPEN_READWRITE ){
21000      OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
21001      return os2Open( pVfs, zName, id,
21002                      ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
21003                      pOutFlags );
21004    }else{
21005      return SQLITE_CANTOPEN;
21006    }
21007  }
21008
21009  if( pOutFlags ){
21010    *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
21011  }
21012
21013  pFile->pMethod = &os2IoMethod;
21014  pFile->h = h;
21015  OpenCounter(+1);
21016  OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
21017  return SQLITE_OK;
21018}
21019
21020/*
21021** Delete the named file.
21022*/
21023static int os2Delete(
21024  sqlite3_vfs *pVfs,                     /* Not used on os2 */
21025  const char *zFilename,                 /* Name of file to delete */
21026  int syncDir                            /* Not used on os2 */
21027){
21028  APIRET rc = NO_ERROR;
21029  char *zFilenameCp = convertUtf8PathToCp( zFilename );
21030  SimulateIOError( return SQLITE_IOERR_DELETE );
21031  rc = DosDelete( (PSZ)zFilenameCp );
21032  free( zFilenameCp );
21033  OSTRACE2( "DELETE \"%s\"\n", zFilename );
21034  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
21035}
21036
21037/*
21038** Check the existance and status of a file.
21039*/
21040static int os2Access(
21041  sqlite3_vfs *pVfs,        /* Not used on os2 */
21042  const char *zFilename,    /* Name of file to check */
21043  int flags,                /* Type of test to make on this file */
21044  int *pOut                 /* Write results here */
21045){
21046  FILESTATUS3 fsts3ConfigInfo;
21047  APIRET rc = NO_ERROR;
21048  char *zFilenameCp = convertUtf8PathToCp( zFilename );
21049
21050  memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
21051  rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
21052                         &fsts3ConfigInfo, sizeof(FILESTATUS3) );
21053  free( zFilenameCp );
21054  OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
21055            fsts3ConfigInfo.attrFile, flags, rc );
21056  switch( flags ){
21057    case SQLITE_ACCESS_READ:
21058    case SQLITE_ACCESS_EXISTS:
21059      rc = (rc == NO_ERROR);
21060      OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
21061      break;
21062    case SQLITE_ACCESS_READWRITE:
21063      rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
21064      OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
21065      break;
21066    default:
21067      assert( !"Invalid flags argument" );
21068  }
21069  *pOut = rc;
21070  return SQLITE_OK;
21071}
21072
21073
21074#ifndef SQLITE_OMIT_LOAD_EXTENSION
21075/*
21076** Interfaces for opening a shared library, finding entry points
21077** within the shared library, and closing the shared library.
21078*/
21079/*
21080** Interfaces for opening a shared library, finding entry points
21081** within the shared library, and closing the shared library.
21082*/
21083static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
21084  UCHAR loadErr[256];
21085  HMODULE hmod;
21086  APIRET rc;
21087  char *zFilenameCp = convertUtf8PathToCp(zFilename);
21088  rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
21089  free(zFilenameCp);
21090  return rc != NO_ERROR ? 0 : (void*)hmod;
21091}
21092/*
21093** A no-op since the error code is returned on the DosLoadModule call.
21094** os2Dlopen returns zero if DosLoadModule is not successful.
21095*/
21096static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
21097/* no-op */
21098}
21099static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
21100  PFN pfn;
21101  APIRET rc;
21102  rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
21103  if( rc != NO_ERROR ){
21104    /* if the symbol itself was not found, search again for the same
21105     * symbol with an extra underscore, that might be needed depending
21106     * on the calling convention */
21107    char _zSymbol[256] = "_";
21108    strncat(_zSymbol, zSymbol, 255);
21109    rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
21110  }
21111  return rc != NO_ERROR ? 0 : (void*)pfn;
21112}
21113static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
21114  DosFreeModule((HMODULE)pHandle);
21115}
21116#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
21117  #define os2DlOpen 0
21118  #define os2DlError 0
21119  #define os2DlSym 0
21120  #define os2DlClose 0
21121#endif
21122
21123
21124/*
21125** Write up to nBuf bytes of randomness into zBuf.
21126*/
21127static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
21128  int n = 0;
21129#if defined(SQLITE_TEST)
21130  n = nBuf;
21131  memset(zBuf, 0, nBuf);
21132#else
21133  int sizeofULong = sizeof(ULONG);
21134  if( (int)sizeof(DATETIME) <= nBuf - n ){
21135    DATETIME x;
21136    DosGetDateTime(&x);
21137    memcpy(&zBuf[n], &x, sizeof(x));
21138    n += sizeof(x);
21139  }
21140
21141  if( sizeofULong <= nBuf - n ){
21142    PPIB ppib;
21143    DosGetInfoBlocks(NULL, &ppib);
21144    memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
21145    n += sizeofULong;
21146  }
21147
21148  if( sizeofULong <= nBuf - n ){
21149    PTIB ptib;
21150    DosGetInfoBlocks(&ptib, NULL);
21151    memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
21152    n += sizeofULong;
21153  }
21154
21155  /* if we still haven't filled the buffer yet the following will */
21156  /* grab everything once instead of making several calls for a single item */
21157  if( sizeofULong <= nBuf - n ){
21158    ULONG ulSysInfo[QSV_MAX];
21159    DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
21160
21161    memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
21162    n += sizeofULong;
21163
21164    if( sizeofULong <= nBuf - n ){
21165      memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
21166      n += sizeofULong;
21167    }
21168    if( sizeofULong <= nBuf - n ){
21169      memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
21170      n += sizeofULong;
21171    }
21172    if( sizeofULong <= nBuf - n ){
21173      memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
21174      n += sizeofULong;
21175    }
21176    if( sizeofULong <= nBuf - n ){
21177      memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
21178      n += sizeofULong;
21179    }
21180  }
21181#endif
21182
21183  return n;
21184}
21185
21186/*
21187** Sleep for a little while.  Return the amount of time slept.
21188** The argument is the number of microseconds we want to sleep.
21189** The return value is the number of microseconds of sleep actually
21190** requested from the underlying operating system, a number which
21191** might be greater than or equal to the argument, but not less
21192** than the argument.
21193*/
21194static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
21195  DosSleep( (microsec/1000) );
21196  return microsec;
21197}
21198
21199/*
21200** The following variable, if set to a non-zero value, becomes the result
21201** returned from sqlite3OsCurrentTime().  This is used for testing.
21202*/
21203#ifdef SQLITE_TEST
21204SQLITE_API int sqlite3_current_time = 0;
21205#endif
21206
21207/*
21208** Find the current time (in Universal Coordinated Time).  Write the
21209** current time and date as a Julian Day number into *prNow and
21210** return 0.  Return 1 if the time and date cannot be found.
21211*/
21212int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
21213  double now;
21214  SHORT minute; /* needs to be able to cope with negative timezone offset */
21215  USHORT second, hour,
21216         day, month, year;
21217  DATETIME dt;
21218  DosGetDateTime( &dt );
21219  second = (USHORT)dt.seconds;
21220  minute = (SHORT)dt.minutes + dt.timezone;
21221  hour = (USHORT)dt.hours;
21222  day = (USHORT)dt.day;
21223  month = (USHORT)dt.month;
21224  year = (USHORT)dt.year;
21225
21226  /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
21227     http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
21228  /* Calculate the Julian days */
21229  now = day - 32076 +
21230    1461*(year + 4800 + (month - 14)/12)/4 +
21231    367*(month - 2 - (month - 14)/12*12)/12 -
21232    3*((year + 4900 + (month - 14)/12)/100)/4;
21233
21234  /* Add the fractional hours, mins and seconds */
21235  now += (hour + 12.0)/24.0;
21236  now += minute/1440.0;
21237  now += second/86400.0;
21238  *prNow = now;
21239#ifdef SQLITE_TEST
21240  if( sqlite3_current_time ){
21241    *prNow = sqlite3_current_time/86400.0 + 2440587.5;
21242  }
21243#endif
21244  return 0;
21245}
21246
21247static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
21248  return 0;
21249}
21250
21251/*
21252** Initialize and deinitialize the operating system interface.
21253*/
21254SQLITE_API int sqlite3_os_init(void){
21255  static sqlite3_vfs os2Vfs = {
21256    1,                 /* iVersion */
21257    sizeof(os2File),   /* szOsFile */
21258    CCHMAXPATH,        /* mxPathname */
21259    0,                 /* pNext */
21260    "os2",             /* zName */
21261    0,                 /* pAppData */
21262
21263    os2Open,           /* xOpen */
21264    os2Delete,         /* xDelete */
21265    os2Access,         /* xAccess */
21266    os2FullPathname,   /* xFullPathname */
21267    os2DlOpen,         /* xDlOpen */
21268    os2DlError,        /* xDlError */
21269    os2DlSym,          /* xDlSym */
21270    os2DlClose,        /* xDlClose */
21271    os2Randomness,     /* xRandomness */
21272    os2Sleep,          /* xSleep */
21273    os2CurrentTime,    /* xCurrentTime */
21274    os2GetLastError    /* xGetLastError */
21275  };
21276  sqlite3_vfs_register(&os2Vfs, 1);
21277  initUconvObjects();
21278  return SQLITE_OK;
21279}
21280SQLITE_API int sqlite3_os_end(void){
21281  freeUconvObjects();
21282  return SQLITE_OK;
21283}
21284
21285#endif /* SQLITE_OS_OS2 */
21286
21287/************** End of os_os2.c **********************************************/
21288/************** Begin file os_unix.c *****************************************/
21289/*
21290** 2004 May 22
21291**
21292** The author disclaims copyright to this source code.  In place of
21293** a legal notice, here is a blessing:
21294**
21295**    May you do good and not evil.
21296**    May you find forgiveness for yourself and forgive others.
21297**    May you share freely, never taking more than you give.
21298**
21299******************************************************************************
21300**
21301** This file contains the VFS implementation for unix-like operating systems
21302** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
21303**
21304** There are actually several different VFS implementations in this file.
21305** The differences are in the way that file locking is done.  The default
21306** implementation uses Posix Advisory Locks.  Alternative implementations
21307** use flock(), dot-files, various proprietary locking schemas, or simply
21308** skip locking all together.
21309**
21310** This source file is organized into divisions where the logic for various
21311** subfunctions is contained within the appropriate division.  PLEASE
21312** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
21313** in the correct division and should be clearly labeled.
21314**
21315** The layout of divisions is as follows:
21316**
21317**   *  General-purpose declarations and utility functions.
21318**   *  Unique file ID logic used by VxWorks.
21319**   *  Various locking primitive implementations (all except proxy locking):
21320**      + for Posix Advisory Locks
21321**      + for no-op locks
21322**      + for dot-file locks
21323**      + for flock() locking
21324**      + for named semaphore locks (VxWorks only)
21325**      + for AFP filesystem locks (MacOSX only)
21326**   *  sqlite3_file methods not associated with locking.
21327**   *  Definitions of sqlite3_io_methods objects for all locking
21328**      methods plus "finder" functions for each locking method.
21329**   *  sqlite3_vfs method implementations.
21330**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
21331**   *  Definitions of sqlite3_vfs objects for all locking methods
21332**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
21333*/
21334#if SQLITE_OS_UNIX              /* This file is used on unix only */
21335
21336/*
21337** There are various methods for file locking used for concurrency
21338** control:
21339**
21340**   1. POSIX locking (the default),
21341**   2. No locking,
21342**   3. Dot-file locking,
21343**   4. flock() locking,
21344**   5. AFP locking (OSX only),
21345**   6. Named POSIX semaphores (VXWorks only),
21346**   7. proxy locking. (OSX only)
21347**
21348** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
21349** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
21350** selection of the appropriate locking style based on the filesystem
21351** where the database is located.
21352*/
21353#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
21354#  if defined(__APPLE__)
21355#    define SQLITE_ENABLE_LOCKING_STYLE 1
21356#  else
21357#    define SQLITE_ENABLE_LOCKING_STYLE 0
21358#  endif
21359#endif
21360
21361/*
21362** Define the OS_VXWORKS pre-processor macro to 1 if building on
21363** vxworks, or 0 otherwise.
21364*/
21365#ifndef OS_VXWORKS
21366#  if defined(__RTP__) || defined(_WRS_KERNEL)
21367#    define OS_VXWORKS 1
21368#  else
21369#    define OS_VXWORKS 0
21370#  endif
21371#endif
21372
21373/*
21374** These #defines should enable >2GB file support on Posix if the
21375** underlying operating system supports it.  If the OS lacks
21376** large file support, these should be no-ops.
21377**
21378** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
21379** on the compiler command line.  This is necessary if you are compiling
21380** on a recent machine (ex: RedHat 7.2) but you want your code to work
21381** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
21382** without this option, LFS is enable.  But LFS does not exist in the kernel
21383** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
21384** portability you should omit LFS.
21385**
21386** The previous paragraph was written in 2005.  (This paragraph is written
21387** on 2008-11-28.) These days, all Linux kernels support large files, so
21388** you should probably leave LFS enabled.  But some embedded platforms might
21389** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
21390*/
21391#ifndef SQLITE_DISABLE_LFS
21392# define _LARGE_FILE       1
21393# ifndef _FILE_OFFSET_BITS
21394#   define _FILE_OFFSET_BITS 64
21395# endif
21396# define _LARGEFILE_SOURCE 1
21397#endif
21398
21399/*
21400** standard include files.
21401*/
21402#include <sys/types.h>
21403#include <sys/stat.h>
21404#include <fcntl.h>
21405#include <unistd.h>
21406#include <sys/time.h>
21407#include <errno.h>
21408
21409#if SQLITE_ENABLE_LOCKING_STYLE
21410# include <sys/ioctl.h>
21411# if OS_VXWORKS
21412#  include <semaphore.h>
21413#  include <limits.h>
21414# else
21415#  include <sys/file.h>
21416#  include <sys/param.h>
21417#  include <sys/mount.h>
21418# endif
21419#endif /* SQLITE_ENABLE_LOCKING_STYLE */
21420
21421/*
21422** If we are to be thread-safe, include the pthreads header and define
21423** the SQLITE_UNIX_THREADS macro.
21424*/
21425#if SQLITE_THREADSAFE
21426# define SQLITE_UNIX_THREADS 1
21427#endif
21428
21429/*
21430** Default permissions when creating a new file
21431*/
21432#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
21433# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
21434#endif
21435
21436/*
21437 ** Default permissions when creating auto proxy dir
21438 */
21439#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
21440# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
21441#endif
21442
21443/*
21444** Maximum supported path-length.
21445*/
21446#define MAX_PATHNAME 512
21447
21448/*
21449** Only set the lastErrno if the error code is a real error and not
21450** a normal expected return code of SQLITE_BUSY or SQLITE_OK
21451*/
21452#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
21453
21454
21455/*
21456** Sometimes, after a file handle is closed by SQLite, the file descriptor
21457** cannot be closed immediately. In these cases, instances of the following
21458** structure are used to store the file descriptor while waiting for an
21459** opportunity to either close or reuse it.
21460*/
21461typedef struct UnixUnusedFd UnixUnusedFd;
21462struct UnixUnusedFd {
21463  int fd;                   /* File descriptor to close */
21464  int flags;                /* Flags this file descriptor was opened with */
21465  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
21466};
21467
21468/*
21469** The unixFile structure is subclass of sqlite3_file specific to the unix
21470** VFS implementations.
21471*/
21472typedef struct unixFile unixFile;
21473struct unixFile {
21474  sqlite3_io_methods const *pMethod;  /* Always the first entry */
21475  struct unixOpenCnt *pOpen;       /* Info about all open fd's on this inode */
21476  struct unixLockInfo *pLock;      /* Info about locks on this inode */
21477  int h;                           /* The file descriptor */
21478  int dirfd;                       /* File descriptor for the directory */
21479  unsigned char locktype;          /* The type of lock held on this fd */
21480  int lastErrno;                   /* The unix errno from the last I/O error */
21481  void *lockingContext;            /* Locking style specific state */
21482  UnixUnusedFd *pUnused;           /* Pre-allocated UnixUnusedFd */
21483  int fileFlags;                   /* Miscellanous flags */
21484#if SQLITE_ENABLE_LOCKING_STYLE
21485  int openFlags;                   /* The flags specified at open() */
21486#endif
21487#if SQLITE_THREADSAFE && defined(__linux__)
21488  pthread_t tid;                   /* The thread that "owns" this unixFile */
21489#endif
21490#if OS_VXWORKS
21491  int isDelete;                    /* Delete on close if true */
21492  struct vxworksFileId *pId;       /* Unique file ID */
21493#endif
21494#ifndef NDEBUG
21495  /* The next group of variables are used to track whether or not the
21496  ** transaction counter in bytes 24-27 of database files are updated
21497  ** whenever any part of the database changes.  An assertion fault will
21498  ** occur if a file is updated without also updating the transaction
21499  ** counter.  This test is made to avoid new problems similar to the
21500  ** one described by ticket #3584.
21501  */
21502  unsigned char transCntrChng;   /* True if the transaction counter changed */
21503  unsigned char dbUpdate;        /* True if any part of database file changed */
21504  unsigned char inNormalWrite;   /* True if in a normal write operation */
21505#endif
21506#ifdef SQLITE_TEST
21507  /* In test mode, increase the size of this structure a bit so that
21508  ** it is larger than the struct CrashFile defined in test6.c.
21509  */
21510  char aPadding[32];
21511#endif
21512};
21513
21514/*
21515** The following macros define bits in unixFile.fileFlags
21516*/
21517#define SQLITE_WHOLE_FILE_LOCKING  0x0001   /* Use whole-file locking */
21518
21519/*
21520** Include code that is common to all os_*.c files
21521*/
21522/************** Include os_common.h in the middle of os_unix.c ***************/
21523/************** Begin file os_common.h ***************************************/
21524/*
21525** 2004 May 22
21526**
21527** The author disclaims copyright to this source code.  In place of
21528** a legal notice, here is a blessing:
21529**
21530**    May you do good and not evil.
21531**    May you find forgiveness for yourself and forgive others.
21532**    May you share freely, never taking more than you give.
21533**
21534******************************************************************************
21535**
21536** This file contains macros and a little bit of code that is common to
21537** all of the platform-specific files (os_*.c) and is #included into those
21538** files.
21539**
21540** This file should be #included by the os_*.c files only.  It is not a
21541** general purpose header file.
21542*/
21543#ifndef _OS_COMMON_H_
21544#define _OS_COMMON_H_
21545
21546/*
21547** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21548** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21549** switch.  The following code should catch this problem at compile-time.
21550*/
21551#ifdef MEMORY_DEBUG
21552# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21553#endif
21554
21555#ifdef SQLITE_DEBUG
21556SQLITE_PRIVATE int sqlite3OSTrace = 0;
21557#define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
21558#define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
21559#define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
21560#define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
21561#define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
21562#define OSTRACE6(X,Y,Z,A,B,C) \
21563    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
21564#define OSTRACE7(X,Y,Z,A,B,C,D) \
21565    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
21566#else
21567#define OSTRACE1(X)
21568#define OSTRACE2(X,Y)
21569#define OSTRACE3(X,Y,Z)
21570#define OSTRACE4(X,Y,Z,A)
21571#define OSTRACE5(X,Y,Z,A,B)
21572#define OSTRACE6(X,Y,Z,A,B,C)
21573#define OSTRACE7(X,Y,Z,A,B,C,D)
21574#endif
21575
21576/*
21577** Macros for performance tracing.  Normally turned off.  Only works
21578** on i486 hardware.
21579*/
21580#ifdef SQLITE_PERFORMANCE_TRACE
21581
21582/*
21583** hwtime.h contains inline assembler code for implementing
21584** high-performance timing routines.
21585*/
21586/************** Include hwtime.h in the middle of os_common.h ****************/
21587/************** Begin file hwtime.h ******************************************/
21588/*
21589** 2008 May 27
21590**
21591** The author disclaims copyright to this source code.  In place of
21592** a legal notice, here is a blessing:
21593**
21594**    May you do good and not evil.
21595**    May you find forgiveness for yourself and forgive others.
21596**    May you share freely, never taking more than you give.
21597**
21598******************************************************************************
21599**
21600** This file contains inline asm code for retrieving "high-performance"
21601** counters for x86 class CPUs.
21602*/
21603#ifndef _HWTIME_H_
21604#define _HWTIME_H_
21605
21606/*
21607** The following routine only works on pentium-class (or newer) processors.
21608** It uses the RDTSC opcode to read the cycle count value out of the
21609** processor and returns that value.  This can be used for high-res
21610** profiling.
21611*/
21612#if (defined(__GNUC__) || defined(_MSC_VER)) && \
21613      (defined(i386) || defined(__i386__) || defined(_M_IX86))
21614
21615  #if defined(__GNUC__)
21616
21617  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21618     unsigned int lo, hi;
21619     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21620     return (sqlite_uint64)hi << 32 | lo;
21621  }
21622
21623  #elif defined(_MSC_VER)
21624
21625  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21626     __asm {
21627        rdtsc
21628        ret       ; return value at EDX:EAX
21629     }
21630  }
21631
21632  #endif
21633
21634#elif (defined(__GNUC__) && defined(__x86_64__))
21635
21636  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21637      unsigned long val;
21638      __asm__ __volatile__ ("rdtsc" : "=A" (val));
21639      return val;
21640  }
21641
21642#elif (defined(__GNUC__) && defined(__ppc__))
21643
21644  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21645      unsigned long long retval;
21646      unsigned long junk;
21647      __asm__ __volatile__ ("\n\
21648          1:      mftbu   %1\n\
21649                  mftb    %L0\n\
21650                  mftbu   %0\n\
21651                  cmpw    %0,%1\n\
21652                  bne     1b"
21653                  : "=r" (retval), "=r" (junk));
21654      return retval;
21655  }
21656
21657#else
21658
21659  #error Need implementation of sqlite3Hwtime() for your platform.
21660
21661  /*
21662  ** To compile without implementing sqlite3Hwtime() for your platform,
21663  ** you can remove the above #error and use the following
21664  ** stub function.  You will lose timing support for many
21665  ** of the debugging and testing utilities, but it should at
21666  ** least compile and run.
21667  */
21668SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21669
21670#endif
21671
21672#endif /* !defined(_HWTIME_H_) */
21673
21674/************** End of hwtime.h **********************************************/
21675/************** Continuing where we left off in os_common.h ******************/
21676
21677static sqlite_uint64 g_start;
21678static sqlite_uint64 g_elapsed;
21679#define TIMER_START       g_start=sqlite3Hwtime()
21680#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21681#define TIMER_ELAPSED     g_elapsed
21682#else
21683#define TIMER_START
21684#define TIMER_END
21685#define TIMER_ELAPSED     ((sqlite_uint64)0)
21686#endif
21687
21688/*
21689** If we compile with the SQLITE_TEST macro set, then the following block
21690** of code will give us the ability to simulate a disk I/O error.  This
21691** is used for testing the I/O recovery logic.
21692*/
21693#ifdef SQLITE_TEST
21694SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21695SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21696SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21697SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21698SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21699SQLITE_API int sqlite3_diskfull_pending = 0;
21700SQLITE_API int sqlite3_diskfull = 0;
21701#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21702#define SimulateIOError(CODE)  \
21703  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21704       || sqlite3_io_error_pending-- == 1 )  \
21705              { local_ioerr(); CODE; }
21706static void local_ioerr(){
21707  IOTRACE(("IOERR\n"));
21708  sqlite3_io_error_hit++;
21709  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21710}
21711#define SimulateDiskfullError(CODE) \
21712   if( sqlite3_diskfull_pending ){ \
21713     if( sqlite3_diskfull_pending == 1 ){ \
21714       local_ioerr(); \
21715       sqlite3_diskfull = 1; \
21716       sqlite3_io_error_hit = 1; \
21717       CODE; \
21718     }else{ \
21719       sqlite3_diskfull_pending--; \
21720     } \
21721   }
21722#else
21723#define SimulateIOErrorBenign(X)
21724#define SimulateIOError(A)
21725#define SimulateDiskfullError(A)
21726#endif
21727
21728/*
21729** When testing, keep a count of the number of open files.
21730*/
21731#ifdef SQLITE_TEST
21732SQLITE_API int sqlite3_open_file_count = 0;
21733#define OpenCounter(X)  sqlite3_open_file_count+=(X)
21734#else
21735#define OpenCounter(X)
21736#endif
21737
21738#endif /* !defined(_OS_COMMON_H_) */
21739
21740/************** End of os_common.h *******************************************/
21741/************** Continuing where we left off in os_unix.c ********************/
21742
21743/*
21744** Define various macros that are missing from some systems.
21745*/
21746#ifndef O_LARGEFILE
21747# define O_LARGEFILE 0
21748#endif
21749#ifdef SQLITE_DISABLE_LFS
21750# undef O_LARGEFILE
21751# define O_LARGEFILE 0
21752#endif
21753#ifndef O_NOFOLLOW
21754# define O_NOFOLLOW 0
21755#endif
21756#ifndef O_BINARY
21757# define O_BINARY 0
21758#endif
21759
21760/*
21761** The DJGPP compiler environment looks mostly like Unix, but it
21762** lacks the fcntl() system call.  So redefine fcntl() to be something
21763** that always succeeds.  This means that locking does not occur under
21764** DJGPP.  But it is DOS - what did you expect?
21765*/
21766#ifdef __DJGPP__
21767# define fcntl(A,B,C) 0
21768#endif
21769
21770/*
21771** The threadid macro resolves to the thread-id or to 0.  Used for
21772** testing and debugging only.
21773*/
21774#if SQLITE_THREADSAFE
21775#define threadid pthread_self()
21776#else
21777#define threadid 0
21778#endif
21779
21780
21781/*
21782** Helper functions to obtain and relinquish the global mutex. The
21783** global mutex is used to protect the unixOpenCnt, unixLockInfo and
21784** vxworksFileId objects used by this file, all of which may be
21785** shared by multiple threads.
21786**
21787** Function unixMutexHeld() is used to assert() that the global mutex
21788** is held when required. This function is only used as part of assert()
21789** statements. e.g.
21790**
21791**   unixEnterMutex()
21792**     assert( unixMutexHeld() );
21793**   unixEnterLeave()
21794*/
21795static void unixEnterMutex(void){
21796  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21797}
21798static void unixLeaveMutex(void){
21799  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21800}
21801#ifdef SQLITE_DEBUG
21802static int unixMutexHeld(void) {
21803  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21804}
21805#endif
21806
21807
21808#ifdef SQLITE_DEBUG
21809/*
21810** Helper function for printing out trace information from debugging
21811** binaries. This returns the string represetation of the supplied
21812** integer lock-type.
21813*/
21814static const char *locktypeName(int locktype){
21815  switch( locktype ){
21816    case NO_LOCK: return "NONE";
21817    case SHARED_LOCK: return "SHARED";
21818    case RESERVED_LOCK: return "RESERVED";
21819    case PENDING_LOCK: return "PENDING";
21820    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
21821  }
21822  return "ERROR";
21823}
21824#endif
21825
21826#ifdef SQLITE_LOCK_TRACE
21827/*
21828** Print out information about all locking operations.
21829**
21830** This routine is used for troubleshooting locks on multithreaded
21831** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
21832** command-line option on the compiler.  This code is normally
21833** turned off.
21834*/
21835static int lockTrace(int fd, int op, struct flock *p){
21836  char *zOpName, *zType;
21837  int s;
21838  int savedErrno;
21839  if( op==F_GETLK ){
21840    zOpName = "GETLK";
21841  }else if( op==F_SETLK ){
21842    zOpName = "SETLK";
21843  }else{
21844    s = fcntl(fd, op, p);
21845    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
21846    return s;
21847  }
21848  if( p->l_type==F_RDLCK ){
21849    zType = "RDLCK";
21850  }else if( p->l_type==F_WRLCK ){
21851    zType = "WRLCK";
21852  }else if( p->l_type==F_UNLCK ){
21853    zType = "UNLCK";
21854  }else{
21855    assert( 0 );
21856  }
21857  assert( p->l_whence==SEEK_SET );
21858  s = fcntl(fd, op, p);
21859  savedErrno = errno;
21860  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
21861     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
21862     (int)p->l_pid, s);
21863  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
21864    struct flock l2;
21865    l2 = *p;
21866    fcntl(fd, F_GETLK, &l2);
21867    if( l2.l_type==F_RDLCK ){
21868      zType = "RDLCK";
21869    }else if( l2.l_type==F_WRLCK ){
21870      zType = "WRLCK";
21871    }else if( l2.l_type==F_UNLCK ){
21872      zType = "UNLCK";
21873    }else{
21874      assert( 0 );
21875    }
21876    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
21877       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
21878  }
21879  errno = savedErrno;
21880  return s;
21881}
21882#define fcntl lockTrace
21883#endif /* SQLITE_LOCK_TRACE */
21884
21885
21886
21887/*
21888** This routine translates a standard POSIX errno code into something
21889** useful to the clients of the sqlite3 functions.  Specifically, it is
21890** intended to translate a variety of "try again" errors into SQLITE_BUSY
21891** and a variety of "please close the file descriptor NOW" errors into
21892** SQLITE_IOERR
21893**
21894** Errors during initialization of locks, or file system support for locks,
21895** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
21896*/
21897static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
21898  switch (posixError) {
21899  case 0:
21900    return SQLITE_OK;
21901
21902  case EAGAIN:
21903  case ETIMEDOUT:
21904  case EBUSY:
21905  case EINTR:
21906  case ENOLCK:
21907    /* random NFS retry error, unless during file system support
21908     * introspection, in which it actually means what it says */
21909    return SQLITE_BUSY;
21910
21911  case EACCES:
21912    /* EACCES is like EAGAIN during locking operations, but not any other time*/
21913    if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
21914	(sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
21915	(sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
21916	(sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
21917      return SQLITE_BUSY;
21918    }
21919    /* else fall through */
21920  case EPERM:
21921    return SQLITE_PERM;
21922
21923  case EDEADLK:
21924    return SQLITE_IOERR_BLOCKED;
21925
21926#if EOPNOTSUPP!=ENOTSUP
21927  case EOPNOTSUPP:
21928    /* something went terribly awry, unless during file system support
21929     * introspection, in which it actually means what it says */
21930#endif
21931#ifdef ENOTSUP
21932  case ENOTSUP:
21933    /* invalid fd, unless during file system support introspection, in which
21934     * it actually means what it says */
21935#endif
21936  case EIO:
21937  case EBADF:
21938  case EINVAL:
21939  case ENOTCONN:
21940  case ENODEV:
21941  case ENXIO:
21942  case ENOENT:
21943  case ESTALE:
21944  case ENOSYS:
21945    /* these should force the client to close the file and reconnect */
21946
21947  default:
21948    return sqliteIOErr;
21949  }
21950}
21951
21952
21953
21954/******************************************************************************
21955****************** Begin Unique File ID Utility Used By VxWorks ***************
21956**
21957** On most versions of unix, we can get a unique ID for a file by concatenating
21958** the device number and the inode number.  But this does not work on VxWorks.
21959** On VxWorks, a unique file id must be based on the canonical filename.
21960**
21961** A pointer to an instance of the following structure can be used as a
21962** unique file ID in VxWorks.  Each instance of this structure contains
21963** a copy of the canonical filename.  There is also a reference count.
21964** The structure is reclaimed when the number of pointers to it drops to
21965** zero.
21966**
21967** There are never very many files open at one time and lookups are not
21968** a performance-critical path, so it is sufficient to put these
21969** structures on a linked list.
21970*/
21971struct vxworksFileId {
21972  struct vxworksFileId *pNext;  /* Next in a list of them all */
21973  int nRef;                     /* Number of references to this one */
21974  int nName;                    /* Length of the zCanonicalName[] string */
21975  char *zCanonicalName;         /* Canonical filename */
21976};
21977
21978#if OS_VXWORKS
21979/*
21980** All unique filenames are held on a linked list headed by this
21981** variable:
21982*/
21983static struct vxworksFileId *vxworksFileList = 0;
21984
21985/*
21986** Simplify a filename into its canonical form
21987** by making the following changes:
21988**
21989**  * removing any trailing and duplicate /
21990**  * convert /./ into just /
21991**  * convert /A/../ where A is any simple name into just /
21992**
21993** Changes are made in-place.  Return the new name length.
21994**
21995** The original filename is in z[0..n-1].  Return the number of
21996** characters in the simplified name.
21997*/
21998static int vxworksSimplifyName(char *z, int n){
21999  int i, j;
22000  while( n>1 && z[n-1]=='/' ){ n--; }
22001  for(i=j=0; i<n; i++){
22002    if( z[i]=='/' ){
22003      if( z[i+1]=='/' ) continue;
22004      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
22005        i += 1;
22006        continue;
22007      }
22008      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
22009        while( j>0 && z[j-1]!='/' ){ j--; }
22010        if( j>0 ){ j--; }
22011        i += 2;
22012        continue;
22013      }
22014    }
22015    z[j++] = z[i];
22016  }
22017  z[j] = 0;
22018  return j;
22019}
22020
22021/*
22022** Find a unique file ID for the given absolute pathname.  Return
22023** a pointer to the vxworksFileId object.  This pointer is the unique
22024** file ID.
22025**
22026** The nRef field of the vxworksFileId object is incremented before
22027** the object is returned.  A new vxworksFileId object is created
22028** and added to the global list if necessary.
22029**
22030** If a memory allocation error occurs, return NULL.
22031*/
22032static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
22033  struct vxworksFileId *pNew;         /* search key and new file ID */
22034  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
22035  int n;                              /* Length of zAbsoluteName string */
22036
22037  assert( zAbsoluteName[0]=='/' );
22038  n = (int)strlen(zAbsoluteName);
22039  pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
22040  if( pNew==0 ) return 0;
22041  pNew->zCanonicalName = (char*)&pNew[1];
22042  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
22043  n = vxworksSimplifyName(pNew->zCanonicalName, n);
22044
22045  /* Search for an existing entry that matching the canonical name.
22046  ** If found, increment the reference count and return a pointer to
22047  ** the existing file ID.
22048  */
22049  unixEnterMutex();
22050  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
22051    if( pCandidate->nName==n
22052     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
22053    ){
22054       sqlite3_free(pNew);
22055       pCandidate->nRef++;
22056       unixLeaveMutex();
22057       return pCandidate;
22058    }
22059  }
22060
22061  /* No match was found.  We will make a new file ID */
22062  pNew->nRef = 1;
22063  pNew->nName = n;
22064  pNew->pNext = vxworksFileList;
22065  vxworksFileList = pNew;
22066  unixLeaveMutex();
22067  return pNew;
22068}
22069
22070/*
22071** Decrement the reference count on a vxworksFileId object.  Free
22072** the object when the reference count reaches zero.
22073*/
22074static void vxworksReleaseFileId(struct vxworksFileId *pId){
22075  unixEnterMutex();
22076  assert( pId->nRef>0 );
22077  pId->nRef--;
22078  if( pId->nRef==0 ){
22079    struct vxworksFileId **pp;
22080    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
22081    assert( *pp==pId );
22082    *pp = pId->pNext;
22083    sqlite3_free(pId);
22084  }
22085  unixLeaveMutex();
22086}
22087#endif /* OS_VXWORKS */
22088/*************** End of Unique File ID Utility Used By VxWorks ****************
22089******************************************************************************/
22090
22091
22092/******************************************************************************
22093*************************** Posix Advisory Locking ****************************
22094**
22095** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
22096** section 6.5.2.2 lines 483 through 490 specify that when a process
22097** sets or clears a lock, that operation overrides any prior locks set
22098** by the same process.  It does not explicitly say so, but this implies
22099** that it overrides locks set by the same process using a different
22100** file descriptor.  Consider this test case:
22101**
22102**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
22103**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
22104**
22105** Suppose ./file1 and ./file2 are really the same file (because
22106** one is a hard or symbolic link to the other) then if you set
22107** an exclusive lock on fd1, then try to get an exclusive lock
22108** on fd2, it works.  I would have expected the second lock to
22109** fail since there was already a lock on the file due to fd1.
22110** But not so.  Since both locks came from the same process, the
22111** second overrides the first, even though they were on different
22112** file descriptors opened on different file names.
22113**
22114** This means that we cannot use POSIX locks to synchronize file access
22115** among competing threads of the same process.  POSIX locks will work fine
22116** to synchronize access for threads in separate processes, but not
22117** threads within the same process.
22118**
22119** To work around the problem, SQLite has to manage file locks internally
22120** on its own.  Whenever a new database is opened, we have to find the
22121** specific inode of the database file (the inode is determined by the
22122** st_dev and st_ino fields of the stat structure that fstat() fills in)
22123** and check for locks already existing on that inode.  When locks are
22124** created or removed, we have to look at our own internal record of the
22125** locks to see if another thread has previously set a lock on that same
22126** inode.
22127**
22128** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
22129** For VxWorks, we have to use the alternative unique ID system based on
22130** canonical filename and implemented in the previous division.)
22131**
22132** The sqlite3_file structure for POSIX is no longer just an integer file
22133** descriptor.  It is now a structure that holds the integer file
22134** descriptor and a pointer to a structure that describes the internal
22135** locks on the corresponding inode.  There is one locking structure
22136** per inode, so if the same inode is opened twice, both unixFile structures
22137** point to the same locking structure.  The locking structure keeps
22138** a reference count (so we will know when to delete it) and a "cnt"
22139** field that tells us its internal lock status.  cnt==0 means the
22140** file is unlocked.  cnt==-1 means the file has an exclusive lock.
22141** cnt>0 means there are cnt shared locks on the file.
22142**
22143** Any attempt to lock or unlock a file first checks the locking
22144** structure.  The fcntl() system call is only invoked to set a
22145** POSIX lock if the internal lock structure transitions between
22146** a locked and an unlocked state.
22147**
22148** But wait:  there are yet more problems with POSIX advisory locks.
22149**
22150** If you close a file descriptor that points to a file that has locks,
22151** all locks on that file that are owned by the current process are
22152** released.  To work around this problem, each unixFile structure contains
22153** a pointer to an unixOpenCnt structure.  There is one unixOpenCnt structure
22154** per open inode, which means that multiple unixFile can point to a single
22155** unixOpenCnt.  When an attempt is made to close an unixFile, if there are
22156** other unixFile open on the same inode that are holding locks, the call
22157** to close() the file descriptor is deferred until all of the locks clear.
22158** The unixOpenCnt structure keeps a list of file descriptors that need to
22159** be closed and that list is walked (and cleared) when the last lock
22160** clears.
22161**
22162** Yet another problem:  LinuxThreads do not play well with posix locks.
22163**
22164** Many older versions of linux use the LinuxThreads library which is
22165** not posix compliant.  Under LinuxThreads, a lock created by thread
22166** A cannot be modified or overridden by a different thread B.
22167** Only thread A can modify the lock.  Locking behavior is correct
22168** if the appliation uses the newer Native Posix Thread Library (NPTL)
22169** on linux - with NPTL a lock created by thread A can override locks
22170** in thread B.  But there is no way to know at compile-time which
22171** threading library is being used.  So there is no way to know at
22172** compile-time whether or not thread A can override locks on thread B.
22173** We have to do a run-time check to discover the behavior of the
22174** current process.
22175**
22176** On systems where thread A is unable to modify locks created by
22177** thread B, we have to keep track of which thread created each
22178** lock.  Hence there is an extra field in the key to the unixLockInfo
22179** structure to record this information.  And on those systems it
22180** is illegal to begin a transaction in one thread and finish it
22181** in another.  For this latter restriction, there is no work-around.
22182** It is a limitation of LinuxThreads.
22183*/
22184
22185/*
22186** Set or check the unixFile.tid field.  This field is set when an unixFile
22187** is first opened.  All subsequent uses of the unixFile verify that the
22188** same thread is operating on the unixFile.  Some operating systems do
22189** not allow locks to be overridden by other threads and that restriction
22190** means that sqlite3* database handles cannot be moved from one thread
22191** to another while locks are held.
22192**
22193** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
22194** another as long as we are running on a system that supports threads
22195** overriding each others locks (which is now the most common behavior)
22196** or if no locks are held.  But the unixFile.pLock field needs to be
22197** recomputed because its key includes the thread-id.  See the
22198** transferOwnership() function below for additional information
22199*/
22200#if SQLITE_THREADSAFE && defined(__linux__)
22201# define SET_THREADID(X)   (X)->tid = pthread_self()
22202# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
22203                            !pthread_equal((X)->tid, pthread_self()))
22204#else
22205# define SET_THREADID(X)
22206# define CHECK_THREADID(X) 0
22207#endif
22208
22209/*
22210** An instance of the following structure serves as the key used
22211** to locate a particular unixOpenCnt structure given its inode.  This
22212** is the same as the unixLockKey except that the thread ID is omitted.
22213*/
22214struct unixFileId {
22215  dev_t dev;                  /* Device number */
22216#if OS_VXWORKS
22217  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
22218#else
22219  ino_t ino;                  /* Inode number */
22220#endif
22221};
22222
22223/*
22224** An instance of the following structure serves as the key used
22225** to locate a particular unixLockInfo structure given its inode.
22226**
22227** If threads cannot override each others locks (LinuxThreads), then we
22228** set the unixLockKey.tid field to the thread ID.  If threads can override
22229** each others locks (Posix and NPTL) then tid is always set to zero.
22230** tid is omitted if we compile without threading support or on an OS
22231** other than linux.
22232*/
22233struct unixLockKey {
22234  struct unixFileId fid;  /* Unique identifier for the file */
22235#if SQLITE_THREADSAFE && defined(__linux__)
22236  pthread_t tid;  /* Thread ID of lock owner. Zero if not using LinuxThreads */
22237#endif
22238};
22239
22240/*
22241** An instance of the following structure is allocated for each open
22242** inode.  Or, on LinuxThreads, there is one of these structures for
22243** each inode opened by each thread.
22244**
22245** A single inode can have multiple file descriptors, so each unixFile
22246** structure contains a pointer to an instance of this object and this
22247** object keeps a count of the number of unixFile pointing to it.
22248*/
22249struct unixLockInfo {
22250  struct unixLockKey lockKey;     /* The lookup key */
22251  int cnt;                        /* Number of SHARED locks held */
22252  int locktype;                   /* One of SHARED_LOCK, RESERVED_LOCK etc. */
22253  int nRef;                       /* Number of pointers to this structure */
22254  struct unixLockInfo *pNext;     /* List of all unixLockInfo objects */
22255  struct unixLockInfo *pPrev;     /*    .... doubly linked */
22256};
22257
22258/*
22259** An instance of the following structure is allocated for each open
22260** inode.  This structure keeps track of the number of locks on that
22261** inode.  If a close is attempted against an inode that is holding
22262** locks, the close is deferred until all locks clear by adding the
22263** file descriptor to be closed to the pending list.
22264**
22265** TODO:  Consider changing this so that there is only a single file
22266** descriptor for each open file, even when it is opened multiple times.
22267** The close() system call would only occur when the last database
22268** using the file closes.
22269*/
22270struct unixOpenCnt {
22271  struct unixFileId fileId;   /* The lookup key */
22272  int nRef;                   /* Number of pointers to this structure */
22273  int nLock;                  /* Number of outstanding locks */
22274  UnixUnusedFd *pUnused;      /* Unused file descriptors to close */
22275#if OS_VXWORKS
22276  sem_t *pSem;                     /* Named POSIX semaphore */
22277  char aSemName[MAX_PATHNAME+2];   /* Name of that semaphore */
22278#endif
22279  struct unixOpenCnt *pNext, *pPrev;   /* List of all unixOpenCnt objects */
22280};
22281
22282/*
22283** Lists of all unixLockInfo and unixOpenCnt objects.  These used to be hash
22284** tables.  But the number of objects is rarely more than a dozen and
22285** never exceeds a few thousand.  And lookup is not on a critical
22286** path so a simple linked list will suffice.
22287*/
22288static struct unixLockInfo *lockList = 0;
22289static struct unixOpenCnt *openList = 0;
22290
22291/*
22292** This variable remembers whether or not threads can override each others
22293** locks.
22294**
22295**    0:  No.  Threads cannot override each others locks.  (LinuxThreads)
22296**    1:  Yes.  Threads can override each others locks.  (Posix & NLPT)
22297**   -1:  We don't know yet.
22298**
22299** On some systems, we know at compile-time if threads can override each
22300** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
22301** will be set appropriately.  On other systems, we have to check at
22302** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
22303** undefined.
22304**
22305** This variable normally has file scope only.  But during testing, we make
22306** it a global so that the test code can change its value in order to verify
22307** that the right stuff happens in either case.
22308*/
22309#if SQLITE_THREADSAFE && defined(__linux__)
22310#  ifndef SQLITE_THREAD_OVERRIDE_LOCK
22311#    define SQLITE_THREAD_OVERRIDE_LOCK -1
22312#  endif
22313#  ifdef SQLITE_TEST
22314int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22315#  else
22316static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22317#  endif
22318#endif
22319
22320/*
22321** This structure holds information passed into individual test
22322** threads by the testThreadLockingBehavior() routine.
22323*/
22324struct threadTestData {
22325  int fd;                /* File to be locked */
22326  struct flock lock;     /* The locking operation */
22327  int result;            /* Result of the locking operation */
22328};
22329
22330#if SQLITE_THREADSAFE && defined(__linux__)
22331/*
22332** This function is used as the main routine for a thread launched by
22333** testThreadLockingBehavior(). It tests whether the shared-lock obtained
22334** by the main thread in testThreadLockingBehavior() conflicts with a
22335** hypothetical write-lock obtained by this thread on the same file.
22336**
22337** The write-lock is not actually acquired, as this is not possible if
22338** the file is open in read-only mode (see ticket #3472).
22339*/
22340static void *threadLockingTest(void *pArg){
22341  struct threadTestData *pData = (struct threadTestData*)pArg;
22342  pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
22343  return pArg;
22344}
22345#endif /* SQLITE_THREADSAFE && defined(__linux__) */
22346
22347
22348#if SQLITE_THREADSAFE && defined(__linux__)
22349/*
22350** This procedure attempts to determine whether or not threads
22351** can override each others locks then sets the
22352** threadsOverrideEachOthersLocks variable appropriately.
22353*/
22354static void testThreadLockingBehavior(int fd_orig){
22355  int fd;
22356  int rc;
22357  struct threadTestData d;
22358  struct flock l;
22359  pthread_t t;
22360
22361  fd = dup(fd_orig);
22362  if( fd<0 ) return;
22363  memset(&l, 0, sizeof(l));
22364  l.l_type = F_RDLCK;
22365  l.l_len = 1;
22366  l.l_start = 0;
22367  l.l_whence = SEEK_SET;
22368  rc = fcntl(fd_orig, F_SETLK, &l);
22369  if( rc!=0 ) return;
22370  memset(&d, 0, sizeof(d));
22371  d.fd = fd;
22372  d.lock = l;
22373  d.lock.l_type = F_WRLCK;
22374  if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
22375    pthread_join(t, 0);
22376  }
22377  close(fd);
22378  if( d.result!=0 ) return;
22379  threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
22380}
22381#endif /* SQLITE_THREADSAFE && defined(__linux__) */
22382
22383/*
22384** Release a unixLockInfo structure previously allocated by findLockInfo().
22385**
22386** The mutex entered using the unixEnterMutex() function must be held
22387** when this function is called.
22388*/
22389static void releaseLockInfo(struct unixLockInfo *pLock){
22390  assert( unixMutexHeld() );
22391  if( pLock ){
22392    pLock->nRef--;
22393    if( pLock->nRef==0 ){
22394      if( pLock->pPrev ){
22395        assert( pLock->pPrev->pNext==pLock );
22396        pLock->pPrev->pNext = pLock->pNext;
22397      }else{
22398        assert( lockList==pLock );
22399        lockList = pLock->pNext;
22400      }
22401      if( pLock->pNext ){
22402        assert( pLock->pNext->pPrev==pLock );
22403        pLock->pNext->pPrev = pLock->pPrev;
22404      }
22405      sqlite3_free(pLock);
22406    }
22407  }
22408}
22409
22410/*
22411** Release a unixOpenCnt structure previously allocated by findLockInfo().
22412**
22413** The mutex entered using the unixEnterMutex() function must be held
22414** when this function is called.
22415*/
22416static void releaseOpenCnt(struct unixOpenCnt *pOpen){
22417  assert( unixMutexHeld() );
22418  if( pOpen ){
22419    pOpen->nRef--;
22420    if( pOpen->nRef==0 ){
22421      if( pOpen->pPrev ){
22422        assert( pOpen->pPrev->pNext==pOpen );
22423        pOpen->pPrev->pNext = pOpen->pNext;
22424      }else{
22425        assert( openList==pOpen );
22426        openList = pOpen->pNext;
22427      }
22428      if( pOpen->pNext ){
22429        assert( pOpen->pNext->pPrev==pOpen );
22430        pOpen->pNext->pPrev = pOpen->pPrev;
22431      }
22432#if SQLITE_THREADSAFE && defined(__linux__)
22433      assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
22434#endif
22435
22436      /* If pOpen->pUnused is not null, then memory and file-descriptors
22437      ** are leaked.
22438      **
22439      ** This will only happen if, under Linuxthreads, the user has opened
22440      ** a transaction in one thread, then attempts to close the database
22441      ** handle from another thread (without first unlocking the db file).
22442      ** This is a misuse.  */
22443      sqlite3_free(pOpen);
22444    }
22445  }
22446}
22447
22448/*
22449** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
22450** describes that file descriptor.  Create new ones if necessary.  The
22451** return values might be uninitialized if an error occurs.
22452**
22453** The mutex entered using the unixEnterMutex() function must be held
22454** when this function is called.
22455**
22456** Return an appropriate error code.
22457*/
22458static int findLockInfo(
22459  unixFile *pFile,               /* Unix file with file desc used in the key */
22460  struct unixLockInfo **ppLock,  /* Return the unixLockInfo structure here */
22461  struct unixOpenCnt **ppOpen    /* Return the unixOpenCnt structure here */
22462){
22463  int rc;                        /* System call return code */
22464  int fd;                        /* The file descriptor for pFile */
22465  struct unixLockKey lockKey;    /* Lookup key for the unixLockInfo structure */
22466  struct unixFileId fileId;      /* Lookup key for the unixOpenCnt struct */
22467  struct stat statbuf;           /* Low-level file information */
22468  struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
22469  struct unixOpenCnt *pOpen;     /* Candidate unixOpenCnt object */
22470
22471  assert( unixMutexHeld() );
22472
22473  /* Get low-level information about the file that we can used to
22474  ** create a unique name for the file.
22475  */
22476  fd = pFile->h;
22477  rc = fstat(fd, &statbuf);
22478  if( rc!=0 ){
22479    pFile->lastErrno = errno;
22480#ifdef EOVERFLOW
22481    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
22482#endif
22483    return SQLITE_IOERR;
22484  }
22485
22486#ifdef __APPLE__
22487  /* On OS X on an msdos filesystem, the inode number is reported
22488  ** incorrectly for zero-size files.  See ticket #3260.  To work
22489  ** around this problem (we consider it a bug in OS X, not SQLite)
22490  ** we always increase the file size to 1 by writing a single byte
22491  ** prior to accessing the inode number.  The one byte written is
22492  ** an ASCII 'S' character which also happens to be the first byte
22493  ** in the header of every SQLite database.  In this way, if there
22494  ** is a race condition such that another thread has already populated
22495  ** the first page of the database, no damage is done.
22496  */
22497  if( statbuf.st_size==0 ){
22498    rc = write(fd, "S", 1);
22499    if( rc!=1 ){
22500      return SQLITE_IOERR;
22501    }
22502    rc = fstat(fd, &statbuf);
22503    if( rc!=0 ){
22504      pFile->lastErrno = errno;
22505      return SQLITE_IOERR;
22506    }
22507  }
22508#endif
22509
22510  memset(&lockKey, 0, sizeof(lockKey));
22511  lockKey.fid.dev = statbuf.st_dev;
22512#if OS_VXWORKS
22513  lockKey.fid.pId = pFile->pId;
22514#else
22515  lockKey.fid.ino = statbuf.st_ino;
22516#endif
22517#if SQLITE_THREADSAFE && defined(__linux__)
22518  if( threadsOverrideEachOthersLocks<0 ){
22519    testThreadLockingBehavior(fd);
22520  }
22521  lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
22522#endif
22523  fileId = lockKey.fid;
22524  if( ppLock!=0 ){
22525    pLock = lockList;
22526    while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
22527      pLock = pLock->pNext;
22528    }
22529    if( pLock==0 ){
22530      pLock = sqlite3_malloc( sizeof(*pLock) );
22531      if( pLock==0 ){
22532        rc = SQLITE_NOMEM;
22533        goto exit_findlockinfo;
22534      }
22535      memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey));
22536      pLock->nRef = 1;
22537      pLock->cnt = 0;
22538      pLock->locktype = 0;
22539      pLock->pNext = lockList;
22540      pLock->pPrev = 0;
22541      if( lockList ) lockList->pPrev = pLock;
22542      lockList = pLock;
22543    }else{
22544      pLock->nRef++;
22545    }
22546    *ppLock = pLock;
22547  }
22548  if( ppOpen!=0 ){
22549    pOpen = openList;
22550    while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
22551      pOpen = pOpen->pNext;
22552    }
22553    if( pOpen==0 ){
22554      pOpen = sqlite3_malloc( sizeof(*pOpen) );
22555      if( pOpen==0 ){
22556        releaseLockInfo(pLock);
22557        rc = SQLITE_NOMEM;
22558        goto exit_findlockinfo;
22559      }
22560      memset(pOpen, 0, sizeof(*pOpen));
22561      pOpen->fileId = fileId;
22562      pOpen->nRef = 1;
22563      pOpen->pNext = openList;
22564      if( openList ) openList->pPrev = pOpen;
22565      openList = pOpen;
22566    }else{
22567      pOpen->nRef++;
22568    }
22569    *ppOpen = pOpen;
22570  }
22571
22572exit_findlockinfo:
22573  return rc;
22574}
22575
22576/*
22577** If we are currently in a different thread than the thread that the
22578** unixFile argument belongs to, then transfer ownership of the unixFile
22579** over to the current thread.
22580**
22581** A unixFile is only owned by a thread on systems that use LinuxThreads.
22582**
22583** Ownership transfer is only allowed if the unixFile is currently unlocked.
22584** If the unixFile is locked and an ownership is wrong, then return
22585** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
22586*/
22587#if SQLITE_THREADSAFE && defined(__linux__)
22588static int transferOwnership(unixFile *pFile){
22589  int rc;
22590  pthread_t hSelf;
22591  if( threadsOverrideEachOthersLocks ){
22592    /* Ownership transfers not needed on this system */
22593    return SQLITE_OK;
22594  }
22595  hSelf = pthread_self();
22596  if( pthread_equal(pFile->tid, hSelf) ){
22597    /* We are still in the same thread */
22598    OSTRACE1("No-transfer, same thread\n");
22599    return SQLITE_OK;
22600  }
22601  if( pFile->locktype!=NO_LOCK ){
22602    /* We cannot change ownership while we are holding a lock! */
22603    return SQLITE_MISUSE_BKPT;
22604  }
22605  OSTRACE4("Transfer ownership of %d from %d to %d\n",
22606            pFile->h, pFile->tid, hSelf);
22607  pFile->tid = hSelf;
22608  if (pFile->pLock != NULL) {
22609    releaseLockInfo(pFile->pLock);
22610    rc = findLockInfo(pFile, &pFile->pLock, 0);
22611    OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
22612           locktypeName(pFile->locktype),
22613           locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
22614    return rc;
22615  } else {
22616    return SQLITE_OK;
22617  }
22618}
22619#else  /* if not SQLITE_THREADSAFE */
22620  /* On single-threaded builds, ownership transfer is a no-op */
22621# define transferOwnership(X) SQLITE_OK
22622#endif /* SQLITE_THREADSAFE */
22623
22624
22625/*
22626** This routine checks if there is a RESERVED lock held on the specified
22627** file by this or any other process. If such a lock is held, set *pResOut
22628** to a non-zero value otherwise *pResOut is set to zero.  The return value
22629** is set to SQLITE_OK unless an I/O error occurs during lock checking.
22630*/
22631static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
22632  int rc = SQLITE_OK;
22633  int reserved = 0;
22634  unixFile *pFile = (unixFile*)id;
22635
22636  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
22637
22638  assert( pFile );
22639  unixEnterMutex(); /* Because pFile->pLock is shared across threads */
22640
22641  /* Check if a thread in this process holds such a lock */
22642  if( pFile->pLock->locktype>SHARED_LOCK ){
22643    reserved = 1;
22644  }
22645
22646  /* Otherwise see if some other process holds it.
22647  */
22648#ifndef __DJGPP__
22649  if( !reserved ){
22650    struct flock lock;
22651    lock.l_whence = SEEK_SET;
22652    lock.l_start = RESERVED_BYTE;
22653    lock.l_len = 1;
22654    lock.l_type = F_WRLCK;
22655    if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
22656      int tErrno = errno;
22657      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
22658      pFile->lastErrno = tErrno;
22659    } else if( lock.l_type!=F_UNLCK ){
22660      reserved = 1;
22661    }
22662  }
22663#endif
22664
22665  unixLeaveMutex();
22666  OSTRACE4("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved);
22667
22668  *pResOut = reserved;
22669  return rc;
22670}
22671
22672/*
22673** Perform a file locking operation on a range of bytes in a file.
22674** The "op" parameter should be one of F_RDLCK, F_WRLCK, or F_UNLCK.
22675** Return 0 on success or -1 for failure.  On failure, write the error
22676** code into *pErrcode.
22677**
22678** If the SQLITE_WHOLE_FILE_LOCKING bit is clear, then only lock
22679** the range of bytes on the locking page between SHARED_FIRST and
22680** SHARED_SIZE.  If SQLITE_WHOLE_FILE_LOCKING is set, then lock all
22681** bytes from 0 up to but not including PENDING_BYTE, and all bytes
22682** that follow SHARED_FIRST.
22683**
22684** In other words, of SQLITE_WHOLE_FILE_LOCKING if false (the historical
22685** default case) then only lock a small range of bytes from SHARED_FIRST
22686** through SHARED_FIRST+SHARED_SIZE-1.  But if SQLITE_WHOLE_FILE_LOCKING is
22687** true then lock every byte in the file except for PENDING_BYTE and
22688** RESERVED_BYTE.
22689**
22690** SQLITE_WHOLE_FILE_LOCKING=true overlaps SQLITE_WHOLE_FILE_LOCKING=false
22691** and so the locking schemes are compatible.  One type of lock will
22692** effectively exclude the other type.  The reason for using the
22693** SQLITE_WHOLE_FILE_LOCKING=true is that by indicating the full range
22694** of bytes to be read or written, we give hints to NFS to help it
22695** maintain cache coherency.  On the other hand, whole file locking
22696** is slower, so we don't want to use it except for NFS.
22697*/
22698static int rangeLock(unixFile *pFile, int op, int *pErrcode){
22699  struct flock lock;
22700  int rc;
22701  lock.l_type = op;
22702  lock.l_start = SHARED_FIRST;
22703  lock.l_whence = SEEK_SET;
22704  if( (pFile->fileFlags & SQLITE_WHOLE_FILE_LOCKING)==0 ){
22705    lock.l_len = SHARED_SIZE;
22706    rc = fcntl(pFile->h, F_SETLK, &lock);
22707    *pErrcode = errno;
22708  }else{
22709    lock.l_len = 0;
22710    rc = fcntl(pFile->h, F_SETLK, &lock);
22711    *pErrcode = errno;
22712    if( NEVER(op==F_UNLCK) || rc!=(-1) ){
22713      lock.l_start = 0;
22714      lock.l_len = PENDING_BYTE;
22715      rc = fcntl(pFile->h, F_SETLK, &lock);
22716      if( ALWAYS(op!=F_UNLCK) && rc==(-1) ){
22717        *pErrcode = errno;
22718        lock.l_type = F_UNLCK;
22719        lock.l_start = SHARED_FIRST;
22720        lock.l_len = 0;
22721        fcntl(pFile->h, F_SETLK, &lock);
22722      }
22723    }
22724  }
22725  return rc;
22726}
22727
22728/*
22729** Lock the file with the lock specified by parameter locktype - one
22730** of the following:
22731**
22732**     (1) SHARED_LOCK
22733**     (2) RESERVED_LOCK
22734**     (3) PENDING_LOCK
22735**     (4) EXCLUSIVE_LOCK
22736**
22737** Sometimes when requesting one lock state, additional lock states
22738** are inserted in between.  The locking might fail on one of the later
22739** transitions leaving the lock state different from what it started but
22740** still short of its goal.  The following chart shows the allowed
22741** transitions and the inserted intermediate states:
22742**
22743**    UNLOCKED -> SHARED
22744**    SHARED -> RESERVED
22745**    SHARED -> (PENDING) -> EXCLUSIVE
22746**    RESERVED -> (PENDING) -> EXCLUSIVE
22747**    PENDING -> EXCLUSIVE
22748**
22749** This routine will only increase a lock.  Use the sqlite3OsUnlock()
22750** routine to lower a locking level.
22751*/
22752static int unixLock(sqlite3_file *id, int locktype){
22753  /* The following describes the implementation of the various locks and
22754  ** lock transitions in terms of the POSIX advisory shared and exclusive
22755  ** lock primitives (called read-locks and write-locks below, to avoid
22756  ** confusion with SQLite lock names). The algorithms are complicated
22757  ** slightly in order to be compatible with windows systems simultaneously
22758  ** accessing the same database file, in case that is ever required.
22759  **
22760  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
22761  ** byte', each single bytes at well known offsets, and the 'shared byte
22762  ** range', a range of 510 bytes at a well known offset.
22763  **
22764  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
22765  ** byte'.  If this is successful, a random byte from the 'shared byte
22766  ** range' is read-locked and the lock on the 'pending byte' released.
22767  **
22768  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
22769  ** A RESERVED lock is implemented by grabbing a write-lock on the
22770  ** 'reserved byte'.
22771  **
22772  ** A process may only obtain a PENDING lock after it has obtained a
22773  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
22774  ** on the 'pending byte'. This ensures that no new SHARED locks can be
22775  ** obtained, but existing SHARED locks are allowed to persist. A process
22776  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
22777  ** This property is used by the algorithm for rolling back a journal file
22778  ** after a crash.
22779  **
22780  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
22781  ** implemented by obtaining a write-lock on the entire 'shared byte
22782  ** range'. Since all other locks require a read-lock on one of the bytes
22783  ** within this range, this ensures that no other locks are held on the
22784  ** database.
22785  **
22786  ** The reason a single byte cannot be used instead of the 'shared byte
22787  ** range' is that some versions of windows do not support read-locks. By
22788  ** locking a random byte from a range, concurrent SHARED locks may exist
22789  ** even if the locking primitive used is always a write-lock.
22790  */
22791  int rc = SQLITE_OK;
22792  unixFile *pFile = (unixFile*)id;
22793  struct unixLockInfo *pLock = pFile->pLock;
22794  struct flock lock;
22795  int s = 0;
22796  int tErrno;
22797
22798  assert( pFile );
22799  OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
22800      locktypeName(locktype), locktypeName(pFile->locktype),
22801      locktypeName(pLock->locktype), pLock->cnt , getpid());
22802
22803  /* If there is already a lock of this type or more restrictive on the
22804  ** unixFile, do nothing. Don't use the end_lock: exit path, as
22805  ** unixEnterMutex() hasn't been called yet.
22806  */
22807  if( pFile->locktype>=locktype ){
22808    OSTRACE3("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
22809            locktypeName(locktype));
22810    return SQLITE_OK;
22811  }
22812
22813  /* Make sure the locking sequence is correct.
22814  **  (1) We never move from unlocked to anything higher than shared lock.
22815  **  (2) SQLite never explicitly requests a pendig lock.
22816  **  (3) A shared lock is always held when a reserve lock is requested.
22817  */
22818  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22819  assert( locktype!=PENDING_LOCK );
22820  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22821
22822  /* This mutex is needed because pFile->pLock is shared across threads
22823  */
22824  unixEnterMutex();
22825
22826  /* Make sure the current thread owns the pFile.
22827  */
22828  rc = transferOwnership(pFile);
22829  if( rc!=SQLITE_OK ){
22830    unixLeaveMutex();
22831    return rc;
22832  }
22833  pLock = pFile->pLock;
22834
22835  /* If some thread using this PID has a lock via a different unixFile*
22836  ** handle that precludes the requested lock, return BUSY.
22837  */
22838  if( (pFile->locktype!=pLock->locktype &&
22839          (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
22840  ){
22841    rc = SQLITE_BUSY;
22842    goto end_lock;
22843  }
22844
22845  /* If a SHARED lock is requested, and some thread using this PID already
22846  ** has a SHARED or RESERVED lock, then increment reference counts and
22847  ** return SQLITE_OK.
22848  */
22849  if( locktype==SHARED_LOCK &&
22850      (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
22851    assert( locktype==SHARED_LOCK );
22852    assert( pFile->locktype==0 );
22853    assert( pLock->cnt>0 );
22854    pFile->locktype = SHARED_LOCK;
22855    pLock->cnt++;
22856    pFile->pOpen->nLock++;
22857    goto end_lock;
22858  }
22859
22860
22861  /* A PENDING lock is needed before acquiring a SHARED lock and before
22862  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
22863  ** be released.
22864  */
22865  lock.l_len = 1L;
22866  lock.l_whence = SEEK_SET;
22867  if( locktype==SHARED_LOCK
22868      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
22869  ){
22870    lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
22871    lock.l_start = PENDING_BYTE;
22872    s = fcntl(pFile->h, F_SETLK, &lock);
22873    if( s==(-1) ){
22874      tErrno = errno;
22875      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
22876      if( IS_LOCK_ERROR(rc) ){
22877        pFile->lastErrno = tErrno;
22878      }
22879      goto end_lock;
22880    }
22881  }
22882
22883
22884  /* If control gets to this point, then actually go ahead and make
22885  ** operating system calls for the specified lock.
22886  */
22887  if( locktype==SHARED_LOCK ){
22888    assert( pLock->cnt==0 );
22889    assert( pLock->locktype==0 );
22890
22891    /* Now get the read-lock */
22892    s = rangeLock(pFile, F_RDLCK, &tErrno);
22893
22894    /* Drop the temporary PENDING lock */
22895    lock.l_start = PENDING_BYTE;
22896    lock.l_len = 1L;
22897    lock.l_type = F_UNLCK;
22898    if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
22899      if( s != -1 ){
22900        /* This could happen with a network mount */
22901        tErrno = errno;
22902        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
22903        if( IS_LOCK_ERROR(rc) ){
22904          pFile->lastErrno = tErrno;
22905        }
22906        goto end_lock;
22907      }
22908    }
22909    if( s==(-1) ){
22910      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
22911      if( IS_LOCK_ERROR(rc) ){
22912        pFile->lastErrno = tErrno;
22913      }
22914    }else{
22915      pFile->locktype = SHARED_LOCK;
22916      pFile->pOpen->nLock++;
22917      pLock->cnt = 1;
22918    }
22919  }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
22920    /* We are trying for an exclusive lock but another thread in this
22921    ** same process is still holding a shared lock. */
22922    rc = SQLITE_BUSY;
22923  }else{
22924    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
22925    ** assumed that there is a SHARED or greater lock on the file
22926    ** already.
22927    */
22928    assert( 0!=pFile->locktype );
22929    lock.l_type = F_WRLCK;
22930    switch( locktype ){
22931      case RESERVED_LOCK:
22932        lock.l_start = RESERVED_BYTE;
22933        s = fcntl(pFile->h, F_SETLK, &lock);
22934        tErrno = errno;
22935        break;
22936      case EXCLUSIVE_LOCK:
22937        s = rangeLock(pFile, F_WRLCK, &tErrno);
22938        break;
22939      default:
22940        assert(0);
22941    }
22942    if( s==(-1) ){
22943      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
22944      if( IS_LOCK_ERROR(rc) ){
22945        pFile->lastErrno = tErrno;
22946      }
22947    }
22948  }
22949
22950
22951#ifndef NDEBUG
22952  /* Set up the transaction-counter change checking flags when
22953  ** transitioning from a SHARED to a RESERVED lock.  The change
22954  ** from SHARED to RESERVED marks the beginning of a normal
22955  ** write operation (not a hot journal rollback).
22956  */
22957  if( rc==SQLITE_OK
22958   && pFile->locktype<=SHARED_LOCK
22959   && locktype==RESERVED_LOCK
22960  ){
22961    pFile->transCntrChng = 0;
22962    pFile->dbUpdate = 0;
22963    pFile->inNormalWrite = 1;
22964  }
22965#endif
22966
22967
22968  if( rc==SQLITE_OK ){
22969    pFile->locktype = locktype;
22970    pLock->locktype = locktype;
22971  }else if( locktype==EXCLUSIVE_LOCK ){
22972    pFile->locktype = PENDING_LOCK;
22973    pLock->locktype = PENDING_LOCK;
22974  }
22975
22976end_lock:
22977  unixLeaveMutex();
22978  OSTRACE4("LOCK    %d %s %s (unix)\n", pFile->h, locktypeName(locktype),
22979      rc==SQLITE_OK ? "ok" : "failed");
22980  return rc;
22981}
22982
22983/*
22984** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
22985** If all such file descriptors are closed without error, the list is
22986** cleared and SQLITE_OK returned.
22987**
22988** Otherwise, if an error occurs, then successfully closed file descriptor
22989** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
22990** not deleted and SQLITE_IOERR_CLOSE returned.
22991*/
22992static int closePendingFds(unixFile *pFile){
22993  int rc = SQLITE_OK;
22994  struct unixOpenCnt *pOpen = pFile->pOpen;
22995  UnixUnusedFd *pError = 0;
22996  UnixUnusedFd *p;
22997  UnixUnusedFd *pNext;
22998  for(p=pOpen->pUnused; p; p=pNext){
22999    pNext = p->pNext;
23000    if( close(p->fd) ){
23001      pFile->lastErrno = errno;
23002      rc = SQLITE_IOERR_CLOSE;
23003      p->pNext = pError;
23004      pError = p;
23005    }else{
23006      sqlite3_free(p);
23007    }
23008  }
23009  pOpen->pUnused = pError;
23010  return rc;
23011}
23012
23013/*
23014** Add the file descriptor used by file handle pFile to the corresponding
23015** pUnused list.
23016*/
23017static void setPendingFd(unixFile *pFile){
23018  struct unixOpenCnt *pOpen = pFile->pOpen;
23019  UnixUnusedFd *p = pFile->pUnused;
23020  p->pNext = pOpen->pUnused;
23021  pOpen->pUnused = p;
23022  pFile->h = -1;
23023  pFile->pUnused = 0;
23024}
23025
23026/*
23027** Lower the locking level on file descriptor pFile to locktype.  locktype
23028** must be either NO_LOCK or SHARED_LOCK.
23029**
23030** If the locking level of the file descriptor is already at or below
23031** the requested locking level, this routine is a no-op.
23032*/
23033static int unixUnlock(sqlite3_file *id, int locktype){
23034  unixFile *pFile = (unixFile*)id; /* The open file */
23035  struct unixLockInfo *pLock;      /* Structure describing current lock state */
23036  struct flock lock;               /* Information passed into fcntl() */
23037  int rc = SQLITE_OK;              /* Return code from this interface */
23038  int h;                           /* The underlying file descriptor */
23039  int tErrno;                      /* Error code from system call errors */
23040
23041  assert( pFile );
23042  OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, locktype,
23043      pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
23044
23045  assert( locktype<=SHARED_LOCK );
23046  if( pFile->locktype<=locktype ){
23047    return SQLITE_OK;
23048  }
23049  if( CHECK_THREADID(pFile) ){
23050    return SQLITE_MISUSE_BKPT;
23051  }
23052  unixEnterMutex();
23053  h = pFile->h;
23054  pLock = pFile->pLock;
23055  assert( pLock->cnt!=0 );
23056  if( pFile->locktype>SHARED_LOCK ){
23057    assert( pLock->locktype==pFile->locktype );
23058    SimulateIOErrorBenign(1);
23059    SimulateIOError( h=(-1) )
23060    SimulateIOErrorBenign(0);
23061
23062#ifndef NDEBUG
23063    /* When reducing a lock such that other processes can start
23064    ** reading the database file again, make sure that the
23065    ** transaction counter was updated if any part of the database
23066    ** file changed.  If the transaction counter is not updated,
23067    ** other connections to the same file might not realize that
23068    ** the file has changed and hence might not know to flush their
23069    ** cache.  The use of a stale cache can lead to database corruption.
23070    */
23071    assert( pFile->inNormalWrite==0
23072         || pFile->dbUpdate==0
23073         || pFile->transCntrChng==1 );
23074    pFile->inNormalWrite = 0;
23075#endif
23076
23077
23078    if( locktype==SHARED_LOCK ){
23079      if( rangeLock(pFile, F_RDLCK, &tErrno)==(-1) ){
23080        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23081        if( IS_LOCK_ERROR(rc) ){
23082          pFile->lastErrno = tErrno;
23083        }
23084        goto end_unlock;
23085      }
23086    }
23087    lock.l_type = F_UNLCK;
23088    lock.l_whence = SEEK_SET;
23089    lock.l_start = PENDING_BYTE;
23090    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
23091    if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23092      pLock->locktype = SHARED_LOCK;
23093    }else{
23094      tErrno = errno;
23095      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23096      if( IS_LOCK_ERROR(rc) ){
23097        pFile->lastErrno = tErrno;
23098      }
23099      goto end_unlock;
23100    }
23101  }
23102  if( locktype==NO_LOCK ){
23103    struct unixOpenCnt *pOpen;
23104
23105    /* Decrement the shared lock counter.  Release the lock using an
23106    ** OS call only when all threads in this same process have released
23107    ** the lock.
23108    */
23109    pLock->cnt--;
23110    if( pLock->cnt==0 ){
23111      lock.l_type = F_UNLCK;
23112      lock.l_whence = SEEK_SET;
23113      lock.l_start = lock.l_len = 0L;
23114      SimulateIOErrorBenign(1);
23115      SimulateIOError( h=(-1) )
23116      SimulateIOErrorBenign(0);
23117      if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23118        pLock->locktype = NO_LOCK;
23119      }else{
23120        tErrno = errno;
23121        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23122        if( IS_LOCK_ERROR(rc) ){
23123          pFile->lastErrno = tErrno;
23124        }
23125        pLock->locktype = NO_LOCK;
23126        pFile->locktype = NO_LOCK;
23127      }
23128    }
23129
23130    /* Decrement the count of locks against this same file.  When the
23131    ** count reaches zero, close any other file descriptors whose close
23132    ** was deferred because of outstanding locks.
23133    */
23134    pOpen = pFile->pOpen;
23135    pOpen->nLock--;
23136    assert( pOpen->nLock>=0 );
23137    if( pOpen->nLock==0 ){
23138      int rc2 = closePendingFds(pFile);
23139      if( rc==SQLITE_OK ){
23140        rc = rc2;
23141      }
23142    }
23143  }
23144
23145end_unlock:
23146  unixLeaveMutex();
23147  if( rc==SQLITE_OK ) pFile->locktype = locktype;
23148  return rc;
23149}
23150
23151/*
23152** This function performs the parts of the "close file" operation
23153** common to all locking schemes. It closes the directory and file
23154** handles, if they are valid, and sets all fields of the unixFile
23155** structure to 0.
23156**
23157** It is *not* necessary to hold the mutex when this routine is called,
23158** even on VxWorks.  A mutex will be acquired on VxWorks by the
23159** vxworksReleaseFileId() routine.
23160*/
23161static int closeUnixFile(sqlite3_file *id){
23162  unixFile *pFile = (unixFile*)id;
23163  if( pFile ){
23164    if( pFile->dirfd>=0 ){
23165      int err = close(pFile->dirfd);
23166      if( err ){
23167        pFile->lastErrno = errno;
23168        return SQLITE_IOERR_DIR_CLOSE;
23169      }else{
23170        pFile->dirfd=-1;
23171      }
23172    }
23173    if( pFile->h>=0 ){
23174      int err = close(pFile->h);
23175      if( err ){
23176        pFile->lastErrno = errno;
23177        return SQLITE_IOERR_CLOSE;
23178      }
23179    }
23180#if OS_VXWORKS
23181    if( pFile->pId ){
23182      if( pFile->isDelete ){
23183        unlink(pFile->pId->zCanonicalName);
23184      }
23185      vxworksReleaseFileId(pFile->pId);
23186      pFile->pId = 0;
23187    }
23188#endif
23189    OSTRACE2("CLOSE   %-3d\n", pFile->h);
23190    OpenCounter(-1);
23191    sqlite3_free(pFile->pUnused);
23192    memset(pFile, 0, sizeof(unixFile));
23193  }
23194  return SQLITE_OK;
23195}
23196
23197/*
23198** Close a file.
23199*/
23200static int unixClose(sqlite3_file *id){
23201  int rc = SQLITE_OK;
23202  if( id ){
23203    unixFile *pFile = (unixFile *)id;
23204    unixUnlock(id, NO_LOCK);
23205    unixEnterMutex();
23206    if( pFile->pOpen && pFile->pOpen->nLock ){
23207      /* If there are outstanding locks, do not actually close the file just
23208      ** yet because that would clear those locks.  Instead, add the file
23209      ** descriptor to pOpen->pUnused list.  It will be automatically closed
23210      ** when the last lock is cleared.
23211      */
23212      setPendingFd(pFile);
23213    }
23214    releaseLockInfo(pFile->pLock);
23215    releaseOpenCnt(pFile->pOpen);
23216    rc = closeUnixFile(id);
23217    unixLeaveMutex();
23218  }
23219  return rc;
23220}
23221
23222/************** End of the posix advisory lock implementation *****************
23223******************************************************************************/
23224
23225/******************************************************************************
23226****************************** No-op Locking **********************************
23227**
23228** Of the various locking implementations available, this is by far the
23229** simplest:  locking is ignored.  No attempt is made to lock the database
23230** file for reading or writing.
23231**
23232** This locking mode is appropriate for use on read-only databases
23233** (ex: databases that are burned into CD-ROM, for example.)  It can
23234** also be used if the application employs some external mechanism to
23235** prevent simultaneous access of the same database by two or more
23236** database connections.  But there is a serious risk of database
23237** corruption if this locking mode is used in situations where multiple
23238** database connections are accessing the same database file at the same
23239** time and one or more of those connections are writing.
23240*/
23241
23242static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
23243  UNUSED_PARAMETER(NotUsed);
23244  *pResOut = 0;
23245  return SQLITE_OK;
23246}
23247static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
23248  UNUSED_PARAMETER2(NotUsed, NotUsed2);
23249  return SQLITE_OK;
23250}
23251static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
23252  UNUSED_PARAMETER2(NotUsed, NotUsed2);
23253  return SQLITE_OK;
23254}
23255
23256/*
23257** Close the file.
23258*/
23259static int nolockClose(sqlite3_file *id) {
23260  return closeUnixFile(id);
23261}
23262
23263/******************* End of the no-op lock implementation *********************
23264******************************************************************************/
23265
23266/******************************************************************************
23267************************* Begin dot-file Locking ******************************
23268**
23269** The dotfile locking implementation uses the existance of separate lock
23270** files in order to control access to the database.  This works on just
23271** about every filesystem imaginable.  But there are serious downsides:
23272**
23273**    (1)  There is zero concurrency.  A single reader blocks all other
23274**         connections from reading or writing the database.
23275**
23276**    (2)  An application crash or power loss can leave stale lock files
23277**         sitting around that need to be cleared manually.
23278**
23279** Nevertheless, a dotlock is an appropriate locking mode for use if no
23280** other locking strategy is available.
23281**
23282** Dotfile locking works by creating a file in the same directory as the
23283** database and with the same name but with a ".lock" extension added.
23284** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
23285** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
23286*/
23287
23288/*
23289** The file suffix added to the data base filename in order to create the
23290** lock file.
23291*/
23292#define DOTLOCK_SUFFIX ".lock"
23293
23294/*
23295** This routine checks if there is a RESERVED lock held on the specified
23296** file by this or any other process. If such a lock is held, set *pResOut
23297** to a non-zero value otherwise *pResOut is set to zero.  The return value
23298** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23299**
23300** In dotfile locking, either a lock exists or it does not.  So in this
23301** variation of CheckReservedLock(), *pResOut is set to true if any lock
23302** is held on the file and false if the file is unlocked.
23303*/
23304static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
23305  int rc = SQLITE_OK;
23306  int reserved = 0;
23307  unixFile *pFile = (unixFile*)id;
23308
23309  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23310
23311  assert( pFile );
23312
23313  /* Check if a thread in this process holds such a lock */
23314  if( pFile->locktype>SHARED_LOCK ){
23315    /* Either this connection or some other connection in the same process
23316    ** holds a lock on the file.  No need to check further. */
23317    reserved = 1;
23318  }else{
23319    /* The lock is held if and only if the lockfile exists */
23320    const char *zLockFile = (const char*)pFile->lockingContext;
23321    reserved = access(zLockFile, 0)==0;
23322  }
23323  OSTRACE4("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved);
23324  *pResOut = reserved;
23325  return rc;
23326}
23327
23328/*
23329** Lock the file with the lock specified by parameter locktype - one
23330** of the following:
23331**
23332**     (1) SHARED_LOCK
23333**     (2) RESERVED_LOCK
23334**     (3) PENDING_LOCK
23335**     (4) EXCLUSIVE_LOCK
23336**
23337** Sometimes when requesting one lock state, additional lock states
23338** are inserted in between.  The locking might fail on one of the later
23339** transitions leaving the lock state different from what it started but
23340** still short of its goal.  The following chart shows the allowed
23341** transitions and the inserted intermediate states:
23342**
23343**    UNLOCKED -> SHARED
23344**    SHARED -> RESERVED
23345**    SHARED -> (PENDING) -> EXCLUSIVE
23346**    RESERVED -> (PENDING) -> EXCLUSIVE
23347**    PENDING -> EXCLUSIVE
23348**
23349** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23350** routine to lower a locking level.
23351**
23352** With dotfile locking, we really only support state (4): EXCLUSIVE.
23353** But we track the other locking levels internally.
23354*/
23355static int dotlockLock(sqlite3_file *id, int locktype) {
23356  unixFile *pFile = (unixFile*)id;
23357  int fd;
23358  char *zLockFile = (char *)pFile->lockingContext;
23359  int rc = SQLITE_OK;
23360
23361
23362  /* If we have any lock, then the lock file already exists.  All we have
23363  ** to do is adjust our internal record of the lock level.
23364  */
23365  if( pFile->locktype > NO_LOCK ){
23366    pFile->locktype = locktype;
23367#if !OS_VXWORKS
23368    /* Always update the timestamp on the old file */
23369    utimes(zLockFile, NULL);
23370#endif
23371    return SQLITE_OK;
23372  }
23373
23374  /* grab an exclusive lock */
23375  fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
23376  if( fd<0 ){
23377    /* failed to open/create the file, someone else may have stolen the lock */
23378    int tErrno = errno;
23379    if( EEXIST == tErrno ){
23380      rc = SQLITE_BUSY;
23381    } else {
23382      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23383      if( IS_LOCK_ERROR(rc) ){
23384        pFile->lastErrno = tErrno;
23385      }
23386    }
23387    return rc;
23388  }
23389  if( close(fd) ){
23390    pFile->lastErrno = errno;
23391    rc = SQLITE_IOERR_CLOSE;
23392  }
23393
23394  /* got it, set the type and return ok */
23395  pFile->locktype = locktype;
23396  return rc;
23397}
23398
23399/*
23400** Lower the locking level on file descriptor pFile to locktype.  locktype
23401** must be either NO_LOCK or SHARED_LOCK.
23402**
23403** If the locking level of the file descriptor is already at or below
23404** the requested locking level, this routine is a no-op.
23405**
23406** When the locking level reaches NO_LOCK, delete the lock file.
23407*/
23408static int dotlockUnlock(sqlite3_file *id, int locktype) {
23409  unixFile *pFile = (unixFile*)id;
23410  char *zLockFile = (char *)pFile->lockingContext;
23411
23412  assert( pFile );
23413  OSTRACE5("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, locktype,
23414	   pFile->locktype, getpid());
23415  assert( locktype<=SHARED_LOCK );
23416
23417  /* no-op if possible */
23418  if( pFile->locktype==locktype ){
23419    return SQLITE_OK;
23420  }
23421
23422  /* To downgrade to shared, simply update our internal notion of the
23423  ** lock state.  No need to mess with the file on disk.
23424  */
23425  if( locktype==SHARED_LOCK ){
23426    pFile->locktype = SHARED_LOCK;
23427    return SQLITE_OK;
23428  }
23429
23430  /* To fully unlock the database, delete the lock file */
23431  assert( locktype==NO_LOCK );
23432  if( unlink(zLockFile) ){
23433    int rc = 0;
23434    int tErrno = errno;
23435    if( ENOENT != tErrno ){
23436      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23437    }
23438    if( IS_LOCK_ERROR(rc) ){
23439      pFile->lastErrno = tErrno;
23440    }
23441    return rc;
23442  }
23443  pFile->locktype = NO_LOCK;
23444  return SQLITE_OK;
23445}
23446
23447/*
23448** Close a file.  Make sure the lock has been released before closing.
23449*/
23450static int dotlockClose(sqlite3_file *id) {
23451  int rc;
23452  if( id ){
23453    unixFile *pFile = (unixFile*)id;
23454    dotlockUnlock(id, NO_LOCK);
23455    sqlite3_free(pFile->lockingContext);
23456  }
23457  rc = closeUnixFile(id);
23458  return rc;
23459}
23460/****************** End of the dot-file lock implementation *******************
23461******************************************************************************/
23462
23463/******************************************************************************
23464************************** Begin flock Locking ********************************
23465**
23466** Use the flock() system call to do file locking.
23467**
23468** flock() locking is like dot-file locking in that the various
23469** fine-grain locking levels supported by SQLite are collapsed into
23470** a single exclusive lock.  In other words, SHARED, RESERVED, and
23471** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
23472** still works when you do this, but concurrency is reduced since
23473** only a single process can be reading the database at a time.
23474**
23475** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
23476** compiling for VXWORKS.
23477*/
23478#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
23479
23480/*
23481** This routine checks if there is a RESERVED lock held on the specified
23482** file by this or any other process. If such a lock is held, set *pResOut
23483** to a non-zero value otherwise *pResOut is set to zero.  The return value
23484** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23485*/
23486static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
23487  int rc = SQLITE_OK;
23488  int reserved = 0;
23489  unixFile *pFile = (unixFile*)id;
23490
23491  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23492
23493  assert( pFile );
23494
23495  /* Check if a thread in this process holds such a lock */
23496  if( pFile->locktype>SHARED_LOCK ){
23497    reserved = 1;
23498  }
23499
23500  /* Otherwise see if some other process holds it. */
23501  if( !reserved ){
23502    /* attempt to get the lock */
23503    int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
23504    if( !lrc ){
23505      /* got the lock, unlock it */
23506      lrc = flock(pFile->h, LOCK_UN);
23507      if ( lrc ) {
23508        int tErrno = errno;
23509        /* unlock failed with an error */
23510        lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23511        if( IS_LOCK_ERROR(lrc) ){
23512          pFile->lastErrno = tErrno;
23513          rc = lrc;
23514        }
23515      }
23516    } else {
23517      int tErrno = errno;
23518      reserved = 1;
23519      /* someone else might have it reserved */
23520      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23521      if( IS_LOCK_ERROR(lrc) ){
23522        pFile->lastErrno = tErrno;
23523        rc = lrc;
23524      }
23525    }
23526  }
23527  OSTRACE4("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved);
23528
23529#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
23530  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
23531    rc = SQLITE_OK;
23532    reserved=1;
23533  }
23534#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
23535  *pResOut = reserved;
23536  return rc;
23537}
23538
23539/*
23540** Lock the file with the lock specified by parameter locktype - one
23541** of the following:
23542**
23543**     (1) SHARED_LOCK
23544**     (2) RESERVED_LOCK
23545**     (3) PENDING_LOCK
23546**     (4) EXCLUSIVE_LOCK
23547**
23548** Sometimes when requesting one lock state, additional lock states
23549** are inserted in between.  The locking might fail on one of the later
23550** transitions leaving the lock state different from what it started but
23551** still short of its goal.  The following chart shows the allowed
23552** transitions and the inserted intermediate states:
23553**
23554**    UNLOCKED -> SHARED
23555**    SHARED -> RESERVED
23556**    SHARED -> (PENDING) -> EXCLUSIVE
23557**    RESERVED -> (PENDING) -> EXCLUSIVE
23558**    PENDING -> EXCLUSIVE
23559**
23560** flock() only really support EXCLUSIVE locks.  We track intermediate
23561** lock states in the sqlite3_file structure, but all locks SHARED or
23562** above are really EXCLUSIVE locks and exclude all other processes from
23563** access the file.
23564**
23565** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23566** routine to lower a locking level.
23567*/
23568static int flockLock(sqlite3_file *id, int locktype) {
23569  int rc = SQLITE_OK;
23570  unixFile *pFile = (unixFile*)id;
23571
23572  assert( pFile );
23573
23574  /* if we already have a lock, it is exclusive.
23575  ** Just adjust level and punt on outta here. */
23576  if (pFile->locktype > NO_LOCK) {
23577    pFile->locktype = locktype;
23578    return SQLITE_OK;
23579  }
23580
23581  /* grab an exclusive lock */
23582
23583  if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
23584    int tErrno = errno;
23585    /* didn't get, must be busy */
23586    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23587    if( IS_LOCK_ERROR(rc) ){
23588      pFile->lastErrno = tErrno;
23589    }
23590  } else {
23591    /* got it, set the type and return ok */
23592    pFile->locktype = locktype;
23593  }
23594  OSTRACE4("LOCK    %d %s %s (flock)\n", pFile->h, locktypeName(locktype),
23595           rc==SQLITE_OK ? "ok" : "failed");
23596#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
23597  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
23598    rc = SQLITE_BUSY;
23599  }
23600#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
23601  return rc;
23602}
23603
23604
23605/*
23606** Lower the locking level on file descriptor pFile to locktype.  locktype
23607** must be either NO_LOCK or SHARED_LOCK.
23608**
23609** If the locking level of the file descriptor is already at or below
23610** the requested locking level, this routine is a no-op.
23611*/
23612static int flockUnlock(sqlite3_file *id, int locktype) {
23613  unixFile *pFile = (unixFile*)id;
23614
23615  assert( pFile );
23616  OSTRACE5("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, locktype,
23617           pFile->locktype, getpid());
23618  assert( locktype<=SHARED_LOCK );
23619
23620  /* no-op if possible */
23621  if( pFile->locktype==locktype ){
23622    return SQLITE_OK;
23623  }
23624
23625  /* shared can just be set because we always have an exclusive */
23626  if (locktype==SHARED_LOCK) {
23627    pFile->locktype = locktype;
23628    return SQLITE_OK;
23629  }
23630
23631  /* no, really, unlock. */
23632  int rc = flock(pFile->h, LOCK_UN);
23633  if (rc) {
23634    int r, tErrno = errno;
23635    r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23636    if( IS_LOCK_ERROR(r) ){
23637      pFile->lastErrno = tErrno;
23638    }
23639#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
23640    if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
23641      r = SQLITE_BUSY;
23642    }
23643#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
23644
23645    return r;
23646  } else {
23647    pFile->locktype = NO_LOCK;
23648    return SQLITE_OK;
23649  }
23650}
23651
23652/*
23653** Close a file.
23654*/
23655static int flockClose(sqlite3_file *id) {
23656  if( id ){
23657    flockUnlock(id, NO_LOCK);
23658  }
23659  return closeUnixFile(id);
23660}
23661
23662#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
23663
23664/******************* End of the flock lock implementation *********************
23665******************************************************************************/
23666
23667/******************************************************************************
23668************************ Begin Named Semaphore Locking ************************
23669**
23670** Named semaphore locking is only supported on VxWorks.
23671**
23672** Semaphore locking is like dot-lock and flock in that it really only
23673** supports EXCLUSIVE locking.  Only a single process can read or write
23674** the database file at a time.  This reduces potential concurrency, but
23675** makes the lock implementation much easier.
23676*/
23677#if OS_VXWORKS
23678
23679/*
23680** This routine checks if there is a RESERVED lock held on the specified
23681** file by this or any other process. If such a lock is held, set *pResOut
23682** to a non-zero value otherwise *pResOut is set to zero.  The return value
23683** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23684*/
23685static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
23686  int rc = SQLITE_OK;
23687  int reserved = 0;
23688  unixFile *pFile = (unixFile*)id;
23689
23690  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23691
23692  assert( pFile );
23693
23694  /* Check if a thread in this process holds such a lock */
23695  if( pFile->locktype>SHARED_LOCK ){
23696    reserved = 1;
23697  }
23698
23699  /* Otherwise see if some other process holds it. */
23700  if( !reserved ){
23701    sem_t *pSem = pFile->pOpen->pSem;
23702    struct stat statBuf;
23703
23704    if( sem_trywait(pSem)==-1 ){
23705      int tErrno = errno;
23706      if( EAGAIN != tErrno ){
23707        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23708        pFile->lastErrno = tErrno;
23709      } else {
23710        /* someone else has the lock when we are in NO_LOCK */
23711        reserved = (pFile->locktype < SHARED_LOCK);
23712      }
23713    }else{
23714      /* we could have it if we want it */
23715      sem_post(pSem);
23716    }
23717  }
23718  OSTRACE4("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved);
23719
23720  *pResOut = reserved;
23721  return rc;
23722}
23723
23724/*
23725** Lock the file with the lock specified by parameter locktype - one
23726** of the following:
23727**
23728**     (1) SHARED_LOCK
23729**     (2) RESERVED_LOCK
23730**     (3) PENDING_LOCK
23731**     (4) EXCLUSIVE_LOCK
23732**
23733** Sometimes when requesting one lock state, additional lock states
23734** are inserted in between.  The locking might fail on one of the later
23735** transitions leaving the lock state different from what it started but
23736** still short of its goal.  The following chart shows the allowed
23737** transitions and the inserted intermediate states:
23738**
23739**    UNLOCKED -> SHARED
23740**    SHARED -> RESERVED
23741**    SHARED -> (PENDING) -> EXCLUSIVE
23742**    RESERVED -> (PENDING) -> EXCLUSIVE
23743**    PENDING -> EXCLUSIVE
23744**
23745** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
23746** lock states in the sqlite3_file structure, but all locks SHARED or
23747** above are really EXCLUSIVE locks and exclude all other processes from
23748** access the file.
23749**
23750** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23751** routine to lower a locking level.
23752*/
23753static int semLock(sqlite3_file *id, int locktype) {
23754  unixFile *pFile = (unixFile*)id;
23755  int fd;
23756  sem_t *pSem = pFile->pOpen->pSem;
23757  int rc = SQLITE_OK;
23758
23759  /* if we already have a lock, it is exclusive.
23760  ** Just adjust level and punt on outta here. */
23761  if (pFile->locktype > NO_LOCK) {
23762    pFile->locktype = locktype;
23763    rc = SQLITE_OK;
23764    goto sem_end_lock;
23765  }
23766
23767  /* lock semaphore now but bail out when already locked. */
23768  if( sem_trywait(pSem)==-1 ){
23769    rc = SQLITE_BUSY;
23770    goto sem_end_lock;
23771  }
23772
23773  /* got it, set the type and return ok */
23774  pFile->locktype = locktype;
23775
23776 sem_end_lock:
23777  return rc;
23778}
23779
23780/*
23781** Lower the locking level on file descriptor pFile to locktype.  locktype
23782** must be either NO_LOCK or SHARED_LOCK.
23783**
23784** If the locking level of the file descriptor is already at or below
23785** the requested locking level, this routine is a no-op.
23786*/
23787static int semUnlock(sqlite3_file *id, int locktype) {
23788  unixFile *pFile = (unixFile*)id;
23789  sem_t *pSem = pFile->pOpen->pSem;
23790
23791  assert( pFile );
23792  assert( pSem );
23793  OSTRACE5("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, locktype,
23794	   pFile->locktype, getpid());
23795  assert( locktype<=SHARED_LOCK );
23796
23797  /* no-op if possible */
23798  if( pFile->locktype==locktype ){
23799    return SQLITE_OK;
23800  }
23801
23802  /* shared can just be set because we always have an exclusive */
23803  if (locktype==SHARED_LOCK) {
23804    pFile->locktype = locktype;
23805    return SQLITE_OK;
23806  }
23807
23808  /* no, really unlock. */
23809  if ( sem_post(pSem)==-1 ) {
23810    int rc, tErrno = errno;
23811    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23812    if( IS_LOCK_ERROR(rc) ){
23813      pFile->lastErrno = tErrno;
23814    }
23815    return rc;
23816  }
23817  pFile->locktype = NO_LOCK;
23818  return SQLITE_OK;
23819}
23820
23821/*
23822 ** Close a file.
23823 */
23824static int semClose(sqlite3_file *id) {
23825  if( id ){
23826    unixFile *pFile = (unixFile*)id;
23827    semUnlock(id, NO_LOCK);
23828    assert( pFile );
23829    unixEnterMutex();
23830    releaseLockInfo(pFile->pLock);
23831    releaseOpenCnt(pFile->pOpen);
23832    unixLeaveMutex();
23833    closeUnixFile(id);
23834  }
23835  return SQLITE_OK;
23836}
23837
23838#endif /* OS_VXWORKS */
23839/*
23840** Named semaphore locking is only available on VxWorks.
23841**
23842*************** End of the named semaphore lock implementation ****************
23843******************************************************************************/
23844
23845
23846/******************************************************************************
23847*************************** Begin AFP Locking *********************************
23848**
23849** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
23850** on Apple Macintosh computers - both OS9 and OSX.
23851**
23852** Third-party implementations of AFP are available.  But this code here
23853** only works on OSX.
23854*/
23855
23856#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
23857/*
23858** The afpLockingContext structure contains all afp lock specific state
23859*/
23860typedef struct afpLockingContext afpLockingContext;
23861struct afpLockingContext {
23862  unsigned long long sharedByte;
23863  const char *dbPath;             /* Name of the open file */
23864};
23865
23866struct ByteRangeLockPB2
23867{
23868  unsigned long long offset;        /* offset to first byte to lock */
23869  unsigned long long length;        /* nbr of bytes to lock */
23870  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
23871  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
23872  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
23873  int fd;                           /* file desc to assoc this lock with */
23874};
23875
23876#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
23877
23878/*
23879** This is a utility for setting or clearing a bit-range lock on an
23880** AFP filesystem.
23881**
23882** Return SQLITE_OK on success, SQLITE_BUSY on failure.
23883*/
23884static int afpSetLock(
23885  const char *path,              /* Name of the file to be locked or unlocked */
23886  unixFile *pFile,               /* Open file descriptor on path */
23887  unsigned long long offset,     /* First byte to be locked */
23888  unsigned long long length,     /* Number of bytes to lock */
23889  int setLockFlag                /* True to set lock.  False to clear lock */
23890){
23891  struct ByteRangeLockPB2 pb;
23892  int err;
23893
23894  pb.unLockFlag = setLockFlag ? 0 : 1;
23895  pb.startEndFlag = 0;
23896  pb.offset = offset;
23897  pb.length = length;
23898  pb.fd = pFile->h;
23899
23900  OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
23901    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
23902    offset, length);
23903  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
23904  if ( err==-1 ) {
23905    int rc;
23906    int tErrno = errno;
23907    OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
23908             path, tErrno, strerror(tErrno));
23909#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
23910    rc = SQLITE_BUSY;
23911#else
23912    rc = sqliteErrorFromPosixError(tErrno,
23913                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
23914#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
23915    if( IS_LOCK_ERROR(rc) ){
23916      pFile->lastErrno = tErrno;
23917    }
23918    return rc;
23919  } else {
23920    return SQLITE_OK;
23921  }
23922}
23923
23924/*
23925** This routine checks if there is a RESERVED lock held on the specified
23926** file by this or any other process. If such a lock is held, set *pResOut
23927** to a non-zero value otherwise *pResOut is set to zero.  The return value
23928** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23929*/
23930static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
23931  int rc = SQLITE_OK;
23932  int reserved = 0;
23933  unixFile *pFile = (unixFile*)id;
23934
23935  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23936
23937  assert( pFile );
23938  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23939
23940  /* Check if a thread in this process holds such a lock */
23941  if( pFile->locktype>SHARED_LOCK ){
23942    reserved = 1;
23943  }
23944
23945  /* Otherwise see if some other process holds it.
23946   */
23947  if( !reserved ){
23948    /* lock the RESERVED byte */
23949    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
23950    if( SQLITE_OK==lrc ){
23951      /* if we succeeded in taking the reserved lock, unlock it to restore
23952      ** the original state */
23953      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
23954    } else {
23955      /* if we failed to get the lock then someone else must have it */
23956      reserved = 1;
23957    }
23958    if( IS_LOCK_ERROR(lrc) ){
23959      rc=lrc;
23960    }
23961  }
23962
23963  OSTRACE4("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved);
23964
23965  *pResOut = reserved;
23966  return rc;
23967}
23968
23969/*
23970** Lock the file with the lock specified by parameter locktype - one
23971** of the following:
23972**
23973**     (1) SHARED_LOCK
23974**     (2) RESERVED_LOCK
23975**     (3) PENDING_LOCK
23976**     (4) EXCLUSIVE_LOCK
23977**
23978** Sometimes when requesting one lock state, additional lock states
23979** are inserted in between.  The locking might fail on one of the later
23980** transitions leaving the lock state different from what it started but
23981** still short of its goal.  The following chart shows the allowed
23982** transitions and the inserted intermediate states:
23983**
23984**    UNLOCKED -> SHARED
23985**    SHARED -> RESERVED
23986**    SHARED -> (PENDING) -> EXCLUSIVE
23987**    RESERVED -> (PENDING) -> EXCLUSIVE
23988**    PENDING -> EXCLUSIVE
23989**
23990** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23991** routine to lower a locking level.
23992*/
23993static int afpLock(sqlite3_file *id, int locktype){
23994  int rc = SQLITE_OK;
23995  unixFile *pFile = (unixFile*)id;
23996  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23997
23998  assert( pFile );
23999  OSTRACE5("LOCK    %d %s was %s pid=%d (afp)\n", pFile->h,
24000         locktypeName(locktype), locktypeName(pFile->locktype), getpid());
24001
24002  /* If there is already a lock of this type or more restrictive on the
24003  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
24004  ** unixEnterMutex() hasn't been called yet.
24005  */
24006  if( pFile->locktype>=locktype ){
24007    OSTRACE3("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
24008           locktypeName(locktype));
24009    return SQLITE_OK;
24010  }
24011
24012  /* Make sure the locking sequence is correct
24013  */
24014  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
24015  assert( locktype!=PENDING_LOCK );
24016  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
24017
24018  /* This mutex is needed because pFile->pLock is shared across threads
24019  */
24020  unixEnterMutex();
24021
24022  /* Make sure the current thread owns the pFile.
24023  */
24024  rc = transferOwnership(pFile);
24025  if( rc!=SQLITE_OK ){
24026    unixLeaveMutex();
24027    return rc;
24028  }
24029
24030  /* A PENDING lock is needed before acquiring a SHARED lock and before
24031  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24032  ** be released.
24033  */
24034  if( locktype==SHARED_LOCK
24035      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
24036  ){
24037    int failed;
24038    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
24039    if (failed) {
24040      rc = failed;
24041      goto afp_end_lock;
24042    }
24043  }
24044
24045  /* If control gets to this point, then actually go ahead and make
24046  ** operating system calls for the specified lock.
24047  */
24048  if( locktype==SHARED_LOCK ){
24049    int lk, lrc1, lrc2;
24050    int lrc1Errno = 0;
24051
24052    /* Now get the read-lock SHARED_LOCK */
24053    /* note that the quality of the randomness doesn't matter that much */
24054    lk = random();
24055    context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
24056    lrc1 = afpSetLock(context->dbPath, pFile,
24057          SHARED_FIRST+context->sharedByte, 1, 1);
24058    if( IS_LOCK_ERROR(lrc1) ){
24059      lrc1Errno = pFile->lastErrno;
24060    }
24061    /* Drop the temporary PENDING lock */
24062    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
24063
24064    if( IS_LOCK_ERROR(lrc1) ) {
24065      pFile->lastErrno = lrc1Errno;
24066      rc = lrc1;
24067      goto afp_end_lock;
24068    } else if( IS_LOCK_ERROR(lrc2) ){
24069      rc = lrc2;
24070      goto afp_end_lock;
24071    } else if( lrc1 != SQLITE_OK ) {
24072      rc = lrc1;
24073    } else {
24074      pFile->locktype = SHARED_LOCK;
24075      pFile->pOpen->nLock++;
24076    }
24077  }else{
24078    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24079    ** assumed that there is a SHARED or greater lock on the file
24080    ** already.
24081    */
24082    int failed = 0;
24083    assert( 0!=pFile->locktype );
24084    if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
24085        /* Acquire a RESERVED lock */
24086        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
24087    }
24088    if (!failed && locktype == EXCLUSIVE_LOCK) {
24089      /* Acquire an EXCLUSIVE lock */
24090
24091      /* Remove the shared lock before trying the range.  we'll need to
24092      ** reestablish the shared lock if we can't get the  afpUnlock
24093      */
24094      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
24095                         context->sharedByte, 1, 0)) ){
24096        int failed2 = SQLITE_OK;
24097        /* now attemmpt to get the exclusive lock range */
24098        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
24099                               SHARED_SIZE, 1);
24100        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
24101                       SHARED_FIRST + context->sharedByte, 1, 1)) ){
24102          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
24103          ** a critical I/O error
24104          */
24105          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
24106               SQLITE_IOERR_LOCK;
24107          goto afp_end_lock;
24108        }
24109      }else{
24110        rc = failed;
24111      }
24112    }
24113    if( failed ){
24114      rc = failed;
24115    }
24116  }
24117
24118  if( rc==SQLITE_OK ){
24119    pFile->locktype = locktype;
24120  }else if( locktype==EXCLUSIVE_LOCK ){
24121    pFile->locktype = PENDING_LOCK;
24122  }
24123
24124afp_end_lock:
24125  unixLeaveMutex();
24126  OSTRACE4("LOCK    %d %s %s (afp)\n", pFile->h, locktypeName(locktype),
24127         rc==SQLITE_OK ? "ok" : "failed");
24128  return rc;
24129}
24130
24131/*
24132** Lower the locking level on file descriptor pFile to locktype.  locktype
24133** must be either NO_LOCK or SHARED_LOCK.
24134**
24135** If the locking level of the file descriptor is already at or below
24136** the requested locking level, this routine is a no-op.
24137*/
24138static int afpUnlock(sqlite3_file *id, int locktype) {
24139  int rc = SQLITE_OK;
24140  unixFile *pFile = (unixFile*)id;
24141  afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
24142
24143  assert( pFile );
24144  OSTRACE5("UNLOCK  %d %d was %d pid=%d (afp)\n", pFile->h, locktype,
24145         pFile->locktype, getpid());
24146
24147  assert( locktype<=SHARED_LOCK );
24148  if( pFile->locktype<=locktype ){
24149    return SQLITE_OK;
24150  }
24151  if( CHECK_THREADID(pFile) ){
24152    return SQLITE_MISUSE_BKPT;
24153  }
24154  unixEnterMutex();
24155  if( pFile->locktype>SHARED_LOCK ){
24156
24157    if( pFile->locktype==EXCLUSIVE_LOCK ){
24158      rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
24159      if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
24160        /* only re-establish the shared lock if necessary */
24161        int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
24162        rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
24163      }
24164    }
24165    if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
24166      rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
24167    }
24168    if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
24169      rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
24170    }
24171  }else if( locktype==NO_LOCK ){
24172    /* clear the shared lock */
24173    int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
24174    rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
24175  }
24176
24177  if( rc==SQLITE_OK ){
24178    if( locktype==NO_LOCK ){
24179      struct unixOpenCnt *pOpen = pFile->pOpen;
24180      pOpen->nLock--;
24181      assert( pOpen->nLock>=0 );
24182      if( pOpen->nLock==0 ){
24183        rc = closePendingFds(pFile);
24184      }
24185    }
24186  }
24187  unixLeaveMutex();
24188  if( rc==SQLITE_OK ){
24189    pFile->locktype = locktype;
24190  }
24191  return rc;
24192}
24193
24194/*
24195** Close a file & cleanup AFP specific locking context
24196*/
24197static int afpClose(sqlite3_file *id) {
24198  if( id ){
24199    unixFile *pFile = (unixFile*)id;
24200    afpUnlock(id, NO_LOCK);
24201    unixEnterMutex();
24202    if( pFile->pOpen && pFile->pOpen->nLock ){
24203      /* If there are outstanding locks, do not actually close the file just
24204      ** yet because that would clear those locks.  Instead, add the file
24205      ** descriptor to pOpen->aPending.  It will be automatically closed when
24206      ** the last lock is cleared.
24207      */
24208      setPendingFd(pFile);
24209    }
24210    releaseOpenCnt(pFile->pOpen);
24211    sqlite3_free(pFile->lockingContext);
24212    closeUnixFile(id);
24213    unixLeaveMutex();
24214  }
24215  return SQLITE_OK;
24216}
24217
24218#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24219/*
24220** The code above is the AFP lock implementation.  The code is specific
24221** to MacOSX and does not work on other unix platforms.  No alternative
24222** is available.  If you don't compile for a mac, then the "unix-afp"
24223** VFS is not available.
24224**
24225********************* End of the AFP lock implementation **********************
24226******************************************************************************/
24227
24228
24229/******************************************************************************
24230**************** Non-locking sqlite3_file methods *****************************
24231**
24232** The next division contains implementations for all methods of the
24233** sqlite3_file object other than the locking methods.  The locking
24234** methods were defined in divisions above (one locking method per
24235** division).  Those methods that are common to all locking modes
24236** are gather together into this division.
24237*/
24238
24239/*
24240** Seek to the offset passed as the second argument, then read cnt
24241** bytes into pBuf. Return the number of bytes actually read.
24242**
24243** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
24244** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
24245** one system to another.  Since SQLite does not define USE_PREAD
24246** any any form by default, we will not attempt to define _XOPEN_SOURCE.
24247** See tickets #2741 and #2681.
24248**
24249** To avoid stomping the errno value on a failed read the lastErrno value
24250** is set before returning.
24251*/
24252static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
24253  int got;
24254  i64 newOffset;
24255  TIMER_START;
24256#if defined(USE_PREAD)
24257  got = pread(id->h, pBuf, cnt, offset);
24258  SimulateIOError( got = -1 );
24259#elif defined(USE_PREAD64)
24260  got = pread64(id->h, pBuf, cnt, offset);
24261  SimulateIOError( got = -1 );
24262#else
24263  newOffset = lseek(id->h, offset, SEEK_SET);
24264  SimulateIOError( newOffset-- );
24265  if( newOffset!=offset ){
24266    if( newOffset == -1 ){
24267      ((unixFile*)id)->lastErrno = errno;
24268    }else{
24269      ((unixFile*)id)->lastErrno = 0;
24270    }
24271    return -1;
24272  }
24273  got = read(id->h, pBuf, cnt);
24274#endif
24275  TIMER_END;
24276  if( got<0 ){
24277    ((unixFile*)id)->lastErrno = errno;
24278  }
24279  OSTRACE5("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
24280  return got;
24281}
24282
24283/*
24284** Read data from a file into a buffer.  Return SQLITE_OK if all
24285** bytes were read successfully and SQLITE_IOERR if anything goes
24286** wrong.
24287*/
24288static int unixRead(
24289  sqlite3_file *id,
24290  void *pBuf,
24291  int amt,
24292  sqlite3_int64 offset
24293){
24294  unixFile *pFile = (unixFile *)id;
24295  int got;
24296  assert( id );
24297
24298  /* If this is a database file (not a journal, master-journal or temp
24299  ** file), the bytes in the locking range should never be read or written. */
24300  assert( pFile->pUnused==0
24301       || offset>=PENDING_BYTE+512
24302       || offset+amt<=PENDING_BYTE
24303  );
24304
24305  got = seekAndRead(pFile, offset, pBuf, amt);
24306  if( got==amt ){
24307    return SQLITE_OK;
24308  }else if( got<0 ){
24309    /* lastErrno set by seekAndRead */
24310    return SQLITE_IOERR_READ;
24311  }else{
24312    pFile->lastErrno = 0; /* not a system error */
24313    /* Unread parts of the buffer must be zero-filled */
24314    memset(&((char*)pBuf)[got], 0, amt-got);
24315    return SQLITE_IOERR_SHORT_READ;
24316  }
24317}
24318
24319/*
24320** Seek to the offset in id->offset then read cnt bytes into pBuf.
24321** Return the number of bytes actually read.  Update the offset.
24322**
24323** To avoid stomping the errno value on a failed write the lastErrno value
24324** is set before returning.
24325*/
24326static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
24327  int got;
24328  i64 newOffset;
24329  TIMER_START;
24330#if defined(USE_PREAD)
24331  got = pwrite(id->h, pBuf, cnt, offset);
24332#elif defined(USE_PREAD64)
24333  got = pwrite64(id->h, pBuf, cnt, offset);
24334#else
24335  newOffset = lseek(id->h, offset, SEEK_SET);
24336  if( newOffset!=offset ){
24337    if( newOffset == -1 ){
24338      ((unixFile*)id)->lastErrno = errno;
24339    }else{
24340      ((unixFile*)id)->lastErrno = 0;
24341    }
24342    return -1;
24343  }
24344  got = write(id->h, pBuf, cnt);
24345#endif
24346  TIMER_END;
24347  if( got<0 ){
24348    ((unixFile*)id)->lastErrno = errno;
24349  }
24350
24351  OSTRACE5("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
24352  return got;
24353}
24354
24355
24356/*
24357** Write data from a buffer into a file.  Return SQLITE_OK on success
24358** or some other error code on failure.
24359*/
24360static int unixWrite(
24361  sqlite3_file *id,
24362  const void *pBuf,
24363  int amt,
24364  sqlite3_int64 offset
24365){
24366  unixFile *pFile = (unixFile*)id;
24367  int wrote = 0;
24368  assert( id );
24369  assert( amt>0 );
24370
24371  /* If this is a database file (not a journal, master-journal or temp
24372  ** file), the bytes in the locking range should never be read or written. */
24373  assert( pFile->pUnused==0
24374       || offset>=PENDING_BYTE+512
24375       || offset+amt<=PENDING_BYTE
24376  );
24377
24378#ifndef NDEBUG
24379  /* If we are doing a normal write to a database file (as opposed to
24380  ** doing a hot-journal rollback or a write to some file other than a
24381  ** normal database file) then record the fact that the database
24382  ** has changed.  If the transaction counter is modified, record that
24383  ** fact too.
24384  */
24385  if( pFile->inNormalWrite ){
24386    pFile->dbUpdate = 1;  /* The database has been modified */
24387    if( offset<=24 && offset+amt>=27 ){
24388      int rc;
24389      char oldCntr[4];
24390      SimulateIOErrorBenign(1);
24391      rc = seekAndRead(pFile, 24, oldCntr, 4);
24392      SimulateIOErrorBenign(0);
24393      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
24394        pFile->transCntrChng = 1;  /* The transaction counter has changed */
24395      }
24396    }
24397  }
24398#endif
24399
24400  while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
24401    amt -= wrote;
24402    offset += wrote;
24403    pBuf = &((char*)pBuf)[wrote];
24404  }
24405  SimulateIOError(( wrote=(-1), amt=1 ));
24406  SimulateDiskfullError(( wrote=0, amt=1 ));
24407  if( amt>0 ){
24408    if( wrote<0 ){
24409      /* lastErrno set by seekAndWrite */
24410      return SQLITE_IOERR_WRITE;
24411    }else{
24412      pFile->lastErrno = 0; /* not a system error */
24413      return SQLITE_FULL;
24414    }
24415  }
24416  return SQLITE_OK;
24417}
24418
24419#ifdef SQLITE_TEST
24420/*
24421** Count the number of fullsyncs and normal syncs.  This is used to test
24422** that syncs and fullsyncs are occurring at the right times.
24423*/
24424SQLITE_API int sqlite3_sync_count = 0;
24425SQLITE_API int sqlite3_fullsync_count = 0;
24426#endif
24427
24428/*
24429** We do not trust systems to provide a working fdatasync().  Some do.
24430** Others do no.  To be safe, we will stick with the (slower) fsync().
24431** If you know that your system does support fdatasync() correctly,
24432** then simply compile with -Dfdatasync=fdatasync
24433*/
24434#if !defined(fdatasync) && !defined(__linux__)
24435# define fdatasync fsync
24436#endif
24437
24438/*
24439** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
24440** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
24441** only available on Mac OS X.  But that could change.
24442*/
24443#ifdef F_FULLFSYNC
24444# define HAVE_FULLFSYNC 1
24445#else
24446# define HAVE_FULLFSYNC 0
24447#endif
24448
24449
24450/*
24451** The fsync() system call does not work as advertised on many
24452** unix systems.  The following procedure is an attempt to make
24453** it work better.
24454**
24455** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
24456** for testing when we want to run through the test suite quickly.
24457** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
24458** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
24459** or power failure will likely corrupt the database file.
24460**
24461** SQLite sets the dataOnly flag if the size of the file is unchanged.
24462** The idea behind dataOnly is that it should only write the file content
24463** to disk, not the inode.  We only set dataOnly if the file size is
24464** unchanged since the file size is part of the inode.  However,
24465** Ted Ts'o tells us that fdatasync() will also write the inode if the
24466** file size has changed.  The only real difference between fdatasync()
24467** and fsync(), Ted tells us, is that fdatasync() will not flush the
24468** inode if the mtime or owner or other inode attributes have changed.
24469** We only care about the file size, not the other file attributes, so
24470** as far as SQLite is concerned, an fdatasync() is always adequate.
24471** So, we always use fdatasync() if it is available, regardless of
24472** the value of the dataOnly flag.
24473*/
24474static int full_fsync(int fd, int fullSync, int dataOnly){
24475  int rc;
24476
24477  /* The following "ifdef/elif/else/" block has the same structure as
24478  ** the one below. It is replicated here solely to avoid cluttering
24479  ** up the real code with the UNUSED_PARAMETER() macros.
24480  */
24481#ifdef SQLITE_NO_SYNC
24482  UNUSED_PARAMETER(fd);
24483  UNUSED_PARAMETER(fullSync);
24484  UNUSED_PARAMETER(dataOnly);
24485#elif HAVE_FULLFSYNC
24486  UNUSED_PARAMETER(dataOnly);
24487#else
24488  UNUSED_PARAMETER(fullSync);
24489  UNUSED_PARAMETER(dataOnly);
24490#endif
24491
24492  /* Record the number of times that we do a normal fsync() and
24493  ** FULLSYNC.  This is used during testing to verify that this procedure
24494  ** gets called with the correct arguments.
24495  */
24496#ifdef SQLITE_TEST
24497  if( fullSync ) sqlite3_fullsync_count++;
24498  sqlite3_sync_count++;
24499#endif
24500
24501  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
24502  ** no-op
24503  */
24504#ifdef SQLITE_NO_SYNC
24505  rc = SQLITE_OK;
24506#elif HAVE_FULLFSYNC
24507  if( fullSync ){
24508    rc = fcntl(fd, F_FULLFSYNC, 0);
24509  }else{
24510    rc = 1;
24511  }
24512  /* If the FULLFSYNC failed, fall back to attempting an fsync().
24513  ** It shouldn't be possible for fullfsync to fail on the local
24514  ** file system (on OSX), so failure indicates that FULLFSYNC
24515  ** isn't supported for this file system. So, attempt an fsync
24516  ** and (for now) ignore the overhead of a superfluous fcntl call.
24517  ** It'd be better to detect fullfsync support once and avoid
24518  ** the fcntl call every time sync is called.
24519  */
24520  if( rc ) rc = fsync(fd);
24521
24522#else
24523  rc = fdatasync(fd);
24524#if OS_VXWORKS
24525  if( rc==-1 && errno==ENOTSUP ){
24526    rc = fsync(fd);
24527  }
24528#endif /* OS_VXWORKS */
24529#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
24530
24531  if( OS_VXWORKS && rc!= -1 ){
24532    rc = 0;
24533  }
24534  return rc;
24535}
24536
24537/*
24538** Make sure all writes to a particular file are committed to disk.
24539**
24540** If dataOnly==0 then both the file itself and its metadata (file
24541** size, access time, etc) are synced.  If dataOnly!=0 then only the
24542** file data is synced.
24543**
24544** Under Unix, also make sure that the directory entry for the file
24545** has been created by fsync-ing the directory that contains the file.
24546** If we do not do this and we encounter a power failure, the directory
24547** entry for the journal might not exist after we reboot.  The next
24548** SQLite to access the file will not know that the journal exists (because
24549** the directory entry for the journal was never created) and the transaction
24550** will not roll back - possibly leading to database corruption.
24551*/
24552static int unixSync(sqlite3_file *id, int flags){
24553  int rc;
24554  unixFile *pFile = (unixFile*)id;
24555
24556  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
24557  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
24558
24559  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
24560  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
24561      || (flags&0x0F)==SQLITE_SYNC_FULL
24562  );
24563
24564  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
24565  ** line is to test that doing so does not cause any problems.
24566  */
24567  SimulateDiskfullError( return SQLITE_FULL );
24568
24569  assert( pFile );
24570  OSTRACE2("SYNC    %-3d\n", pFile->h);
24571  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
24572  SimulateIOError( rc=1 );
24573  if( rc ){
24574    pFile->lastErrno = errno;
24575    return SQLITE_IOERR_FSYNC;
24576  }
24577  if( pFile->dirfd>=0 ){
24578    int err;
24579    OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
24580            HAVE_FULLFSYNC, isFullsync);
24581#ifndef SQLITE_DISABLE_DIRSYNC
24582    /* The directory sync is only attempted if full_fsync is
24583    ** turned off or unavailable.  If a full_fsync occurred above,
24584    ** then the directory sync is superfluous.
24585    */
24586    if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
24587       /*
24588       ** We have received multiple reports of fsync() returning
24589       ** errors when applied to directories on certain file systems.
24590       ** A failed directory sync is not a big deal.  So it seems
24591       ** better to ignore the error.  Ticket #1657
24592       */
24593       /* pFile->lastErrno = errno; */
24594       /* return SQLITE_IOERR; */
24595    }
24596#endif
24597    err = close(pFile->dirfd); /* Only need to sync once, so close the */
24598    if( err==0 ){              /* directory when we are done */
24599      pFile->dirfd = -1;
24600    }else{
24601      pFile->lastErrno = errno;
24602      rc = SQLITE_IOERR_DIR_CLOSE;
24603    }
24604  }
24605  return rc;
24606}
24607
24608/*
24609** Truncate an open file to a specified size
24610*/
24611static int unixTruncate(sqlite3_file *id, i64 nByte){
24612  int rc;
24613  assert( id );
24614  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
24615  rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
24616  if( rc ){
24617    ((unixFile*)id)->lastErrno = errno;
24618    return SQLITE_IOERR_TRUNCATE;
24619  }else{
24620#ifndef NDEBUG
24621    /* If we are doing a normal write to a database file (as opposed to
24622    ** doing a hot-journal rollback or a write to some file other than a
24623    ** normal database file) and we truncate the file to zero length,
24624    ** that effectively updates the change counter.  This might happen
24625    ** when restoring a database using the backup API from a zero-length
24626    ** source.
24627    */
24628    if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
24629      ((unixFile*)id)->transCntrChng = 1;
24630    }
24631#endif
24632
24633    return SQLITE_OK;
24634  }
24635}
24636
24637/*
24638** Determine the current size of a file in bytes
24639*/
24640static int unixFileSize(sqlite3_file *id, i64 *pSize){
24641  int rc;
24642  struct stat buf;
24643  assert( id );
24644  rc = fstat(((unixFile*)id)->h, &buf);
24645  SimulateIOError( rc=1 );
24646  if( rc!=0 ){
24647    ((unixFile*)id)->lastErrno = errno;
24648    return SQLITE_IOERR_FSTAT;
24649  }
24650  *pSize = buf.st_size;
24651
24652  /* When opening a zero-size database, the findLockInfo() procedure
24653  ** writes a single byte into that file in order to work around a bug
24654  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
24655  ** layers, we need to report this file size as zero even though it is
24656  ** really 1.   Ticket #3260.
24657  */
24658  if( *pSize==1 ) *pSize = 0;
24659
24660
24661  return SQLITE_OK;
24662}
24663
24664#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
24665/*
24666** Handler for proxy-locking file-control verbs.  Defined below in the
24667** proxying locking division.
24668*/
24669static int proxyFileControl(sqlite3_file*,int,void*);
24670#endif
24671
24672
24673/*
24674** Information and control of an open file handle.
24675*/
24676static int unixFileControl(sqlite3_file *id, int op, void *pArg){
24677  switch( op ){
24678    case SQLITE_FCNTL_LOCKSTATE: {
24679      *(int*)pArg = ((unixFile*)id)->locktype;
24680      return SQLITE_OK;
24681    }
24682    case SQLITE_LAST_ERRNO: {
24683      *(int*)pArg = ((unixFile*)id)->lastErrno;
24684      return SQLITE_OK;
24685    }
24686#ifndef NDEBUG
24687    /* The pager calls this method to signal that it has done
24688    ** a rollback and that the database is therefore unchanged and
24689    ** it hence it is OK for the transaction change counter to be
24690    ** unchanged.
24691    */
24692    case SQLITE_FCNTL_DB_UNCHANGED: {
24693      ((unixFile*)id)->dbUpdate = 0;
24694      return SQLITE_OK;
24695    }
24696#endif
24697#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
24698    case SQLITE_SET_LOCKPROXYFILE:
24699    case SQLITE_GET_LOCKPROXYFILE: {
24700      return proxyFileControl(id,op,pArg);
24701    }
24702#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
24703  }
24704  return SQLITE_ERROR;
24705}
24706
24707/*
24708** Return the sector size in bytes of the underlying block device for
24709** the specified file. This is almost always 512 bytes, but may be
24710** larger for some devices.
24711**
24712** SQLite code assumes this function cannot fail. It also assumes that
24713** if two files are created in the same file-system directory (i.e.
24714** a database and its journal file) that the sector size will be the
24715** same for both.
24716*/
24717static int unixSectorSize(sqlite3_file *NotUsed){
24718  UNUSED_PARAMETER(NotUsed);
24719  return SQLITE_DEFAULT_SECTOR_SIZE;
24720}
24721
24722/*
24723** Return the device characteristics for the file. This is always 0 for unix.
24724*/
24725static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
24726  UNUSED_PARAMETER(NotUsed);
24727  return 0;
24728}
24729
24730/*
24731** Here ends the implementation of all sqlite3_file methods.
24732**
24733********************** End sqlite3_file Methods *******************************
24734******************************************************************************/
24735
24736/*
24737** This division contains definitions of sqlite3_io_methods objects that
24738** implement various file locking strategies.  It also contains definitions
24739** of "finder" functions.  A finder-function is used to locate the appropriate
24740** sqlite3_io_methods object for a particular database file.  The pAppData
24741** field of the sqlite3_vfs VFS objects are initialized to be pointers to
24742** the correct finder-function for that VFS.
24743**
24744** Most finder functions return a pointer to a fixed sqlite3_io_methods
24745** object.  The only interesting finder-function is autolockIoFinder, which
24746** looks at the filesystem type and tries to guess the best locking
24747** strategy from that.
24748**
24749** For finder-funtion F, two objects are created:
24750**
24751**    (1) The real finder-function named "FImpt()".
24752**
24753**    (2) A constant pointer to this function named just "F".
24754**
24755**
24756** A pointer to the F pointer is used as the pAppData value for VFS
24757** objects.  We have to do this instead of letting pAppData point
24758** directly at the finder-function since C90 rules prevent a void*
24759** from be cast into a function pointer.
24760**
24761**
24762** Each instance of this macro generates two objects:
24763**
24764**   *  A constant sqlite3_io_methods object call METHOD that has locking
24765**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
24766**
24767**   *  An I/O method finder function called FINDER that returns a pointer
24768**      to the METHOD object in the previous bullet.
24769*/
24770#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK)               \
24771static const sqlite3_io_methods METHOD = {                                   \
24772   1,                          /* iVersion */                                \
24773   CLOSE,                      /* xClose */                                  \
24774   unixRead,                   /* xRead */                                   \
24775   unixWrite,                  /* xWrite */                                  \
24776   unixTruncate,               /* xTruncate */                               \
24777   unixSync,                   /* xSync */                                   \
24778   unixFileSize,               /* xFileSize */                               \
24779   LOCK,                       /* xLock */                                   \
24780   UNLOCK,                     /* xUnlock */                                 \
24781   CKLOCK,                     /* xCheckReservedLock */                      \
24782   unixFileControl,            /* xFileControl */                            \
24783   unixSectorSize,             /* xSectorSize */                             \
24784   unixDeviceCharacteristics   /* xDeviceCapabilities */                     \
24785};                                                                           \
24786static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
24787  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
24788  return &METHOD;                                                            \
24789}                                                                            \
24790static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
24791    = FINDER##Impl;
24792
24793/*
24794** Here are all of the sqlite3_io_methods objects for each of the
24795** locking strategies.  Functions that return pointers to these methods
24796** are also created.
24797*/
24798IOMETHODS(
24799  posixIoFinder,            /* Finder function name */
24800  posixIoMethods,           /* sqlite3_io_methods object name */
24801  unixClose,                /* xClose method */
24802  unixLock,                 /* xLock method */
24803  unixUnlock,               /* xUnlock method */
24804  unixCheckReservedLock     /* xCheckReservedLock method */
24805)
24806IOMETHODS(
24807  nolockIoFinder,           /* Finder function name */
24808  nolockIoMethods,          /* sqlite3_io_methods object name */
24809  nolockClose,              /* xClose method */
24810  nolockLock,               /* xLock method */
24811  nolockUnlock,             /* xUnlock method */
24812  nolockCheckReservedLock   /* xCheckReservedLock method */
24813)
24814IOMETHODS(
24815  dotlockIoFinder,          /* Finder function name */
24816  dotlockIoMethods,         /* sqlite3_io_methods object name */
24817  dotlockClose,             /* xClose method */
24818  dotlockLock,              /* xLock method */
24819  dotlockUnlock,            /* xUnlock method */
24820  dotlockCheckReservedLock  /* xCheckReservedLock method */
24821)
24822
24823#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
24824IOMETHODS(
24825  flockIoFinder,            /* Finder function name */
24826  flockIoMethods,           /* sqlite3_io_methods object name */
24827  flockClose,               /* xClose method */
24828  flockLock,                /* xLock method */
24829  flockUnlock,              /* xUnlock method */
24830  flockCheckReservedLock    /* xCheckReservedLock method */
24831)
24832#endif
24833
24834#if OS_VXWORKS
24835IOMETHODS(
24836  semIoFinder,              /* Finder function name */
24837  semIoMethods,             /* sqlite3_io_methods object name */
24838  semClose,                 /* xClose method */
24839  semLock,                  /* xLock method */
24840  semUnlock,                /* xUnlock method */
24841  semCheckReservedLock      /* xCheckReservedLock method */
24842)
24843#endif
24844
24845#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24846IOMETHODS(
24847  afpIoFinder,              /* Finder function name */
24848  afpIoMethods,             /* sqlite3_io_methods object name */
24849  afpClose,                 /* xClose method */
24850  afpLock,                  /* xLock method */
24851  afpUnlock,                /* xUnlock method */
24852  afpCheckReservedLock      /* xCheckReservedLock method */
24853)
24854#endif
24855
24856/*
24857** The "Whole File Locking" finder returns the same set of methods as
24858** the posix locking finder.  But it also sets the SQLITE_WHOLE_FILE_LOCKING
24859** flag to force the posix advisory locks to cover the whole file instead
24860** of just a small span of bytes near the 1GiB boundary.  Whole File Locking
24861** is useful on NFS-mounted files since it helps NFS to maintain cache
24862** coherency.  But it is a detriment to other filesystems since it runs
24863** slower.
24864*/
24865static const sqlite3_io_methods *posixWflIoFinderImpl(const char*z, unixFile*p){
24866  UNUSED_PARAMETER(z);
24867  p->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
24868  return &posixIoMethods;
24869}
24870static const sqlite3_io_methods
24871  *(*const posixWflIoFinder)(const char*,unixFile *p) = posixWflIoFinderImpl;
24872
24873/*
24874** The proxy locking method is a "super-method" in the sense that it
24875** opens secondary file descriptors for the conch and lock files and
24876** it uses proxy, dot-file, AFP, and flock() locking methods on those
24877** secondary files.  For this reason, the division that implements
24878** proxy locking is located much further down in the file.  But we need
24879** to go ahead and define the sqlite3_io_methods and finder function
24880** for proxy locking here.  So we forward declare the I/O methods.
24881*/
24882#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24883static int proxyClose(sqlite3_file*);
24884static int proxyLock(sqlite3_file*, int);
24885static int proxyUnlock(sqlite3_file*, int);
24886static int proxyCheckReservedLock(sqlite3_file*, int*);
24887IOMETHODS(
24888  proxyIoFinder,            /* Finder function name */
24889  proxyIoMethods,           /* sqlite3_io_methods object name */
24890  proxyClose,               /* xClose method */
24891  proxyLock,                /* xLock method */
24892  proxyUnlock,              /* xUnlock method */
24893  proxyCheckReservedLock    /* xCheckReservedLock method */
24894)
24895#endif
24896
24897
24898#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24899/*
24900** This "finder" function attempts to determine the best locking strategy
24901** for the database file "filePath".  It then returns the sqlite3_io_methods
24902** object that implements that strategy.
24903**
24904** This is for MacOSX only.
24905*/
24906static const sqlite3_io_methods *autolockIoFinderImpl(
24907  const char *filePath,    /* name of the database file */
24908  unixFile *pNew           /* open file object for the database file */
24909){
24910  static const struct Mapping {
24911    const char *zFilesystem;              /* Filesystem type name */
24912    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
24913  } aMap[] = {
24914    { "hfs",    &posixIoMethods },
24915    { "ufs",    &posixIoMethods },
24916    { "afpfs",  &afpIoMethods },
24917#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
24918    { "smbfs",  &afpIoMethods },
24919#else
24920    { "smbfs",  &flockIoMethods },
24921#endif
24922    { "webdav", &nolockIoMethods },
24923    { 0, 0 }
24924  };
24925  int i;
24926  struct statfs fsInfo;
24927  struct flock lockInfo;
24928
24929  if( !filePath ){
24930    /* If filePath==NULL that means we are dealing with a transient file
24931    ** that does not need to be locked. */
24932    return &nolockIoMethods;
24933  }
24934  if( statfs(filePath, &fsInfo) != -1 ){
24935    if( fsInfo.f_flags & MNT_RDONLY ){
24936      return &nolockIoMethods;
24937    }
24938    for(i=0; aMap[i].zFilesystem; i++){
24939      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
24940        return aMap[i].pMethods;
24941      }
24942    }
24943  }
24944
24945  /* Default case. Handles, amongst others, "nfs".
24946  ** Test byte-range lock using fcntl(). If the call succeeds,
24947  ** assume that the file-system supports POSIX style locks.
24948  */
24949  lockInfo.l_len = 1;
24950  lockInfo.l_start = 0;
24951  lockInfo.l_whence = SEEK_SET;
24952  lockInfo.l_type = F_RDLCK;
24953  if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
24954    pNew->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
24955    return &posixIoMethods;
24956  }else{
24957    return &dotlockIoMethods;
24958  }
24959}
24960static const sqlite3_io_methods
24961  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
24962
24963#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24964
24965#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
24966/*
24967** This "finder" function attempts to determine the best locking strategy
24968** for the database file "filePath".  It then returns the sqlite3_io_methods
24969** object that implements that strategy.
24970**
24971** This is for VXWorks only.
24972*/
24973static const sqlite3_io_methods *autolockIoFinderImpl(
24974  const char *filePath,    /* name of the database file */
24975  unixFile *pNew           /* the open file object */
24976){
24977  struct flock lockInfo;
24978
24979  if( !filePath ){
24980    /* If filePath==NULL that means we are dealing with a transient file
24981    ** that does not need to be locked. */
24982    return &nolockIoMethods;
24983  }
24984
24985  /* Test if fcntl() is supported and use POSIX style locks.
24986  ** Otherwise fall back to the named semaphore method.
24987  */
24988  lockInfo.l_len = 1;
24989  lockInfo.l_start = 0;
24990  lockInfo.l_whence = SEEK_SET;
24991  lockInfo.l_type = F_RDLCK;
24992  if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
24993    return &posixIoMethods;
24994  }else{
24995    return &semIoMethods;
24996  }
24997}
24998static const sqlite3_io_methods
24999  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
25000
25001#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
25002
25003/*
25004** An abstract type for a pointer to a IO method finder function:
25005*/
25006typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
25007
25008
25009/****************************************************************************
25010**************************** sqlite3_vfs methods ****************************
25011**
25012** This division contains the implementation of methods on the
25013** sqlite3_vfs object.
25014*/
25015
25016/*
25017** Initialize the contents of the unixFile structure pointed to by pId.
25018*/
25019static int fillInUnixFile(
25020  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
25021  int h,                  /* Open file descriptor of file being opened */
25022  int dirfd,              /* Directory file descriptor */
25023  sqlite3_file *pId,      /* Write to the unixFile structure here */
25024  const char *zFilename,  /* Name of the file being opened */
25025  int noLock,             /* Omit locking if true */
25026  int isDelete            /* Delete on close if true */
25027){
25028  const sqlite3_io_methods *pLockingStyle;
25029  unixFile *pNew = (unixFile *)pId;
25030  int rc = SQLITE_OK;
25031
25032  assert( pNew->pLock==NULL );
25033  assert( pNew->pOpen==NULL );
25034
25035  /* Parameter isDelete is only used on vxworks. Express this explicitly
25036  ** here to prevent compiler warnings about unused parameters.
25037  */
25038  UNUSED_PARAMETER(isDelete);
25039
25040  OSTRACE3("OPEN    %-3d %s\n", h, zFilename);
25041  pNew->h = h;
25042  pNew->dirfd = dirfd;
25043  SET_THREADID(pNew);
25044  pNew->fileFlags = 0;
25045
25046#if OS_VXWORKS
25047  pNew->pId = vxworksFindFileId(zFilename);
25048  if( pNew->pId==0 ){
25049    noLock = 1;
25050    rc = SQLITE_NOMEM;
25051  }
25052#endif
25053
25054  if( noLock ){
25055    pLockingStyle = &nolockIoMethods;
25056  }else{
25057    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
25058#if SQLITE_ENABLE_LOCKING_STYLE
25059    /* Cache zFilename in the locking context (AFP and dotlock override) for
25060    ** proxyLock activation is possible (remote proxy is based on db name)
25061    ** zFilename remains valid until file is closed, to support */
25062    pNew->lockingContext = (void*)zFilename;
25063#endif
25064  }
25065
25066  if( pLockingStyle == &posixIoMethods ){
25067    unixEnterMutex();
25068    rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
25069    if( rc!=SQLITE_OK ){
25070      /* If an error occured in findLockInfo(), close the file descriptor
25071      ** immediately, before releasing the mutex. findLockInfo() may fail
25072      ** in two scenarios:
25073      **
25074      **   (a) A call to fstat() failed.
25075      **   (b) A malloc failed.
25076      **
25077      ** Scenario (b) may only occur if the process is holding no other
25078      ** file descriptors open on the same file. If there were other file
25079      ** descriptors on this file, then no malloc would be required by
25080      ** findLockInfo(). If this is the case, it is quite safe to close
25081      ** handle h - as it is guaranteed that no posix locks will be released
25082      ** by doing so.
25083      **
25084      ** If scenario (a) caused the error then things are not so safe. The
25085      ** implicit assumption here is that if fstat() fails, things are in
25086      ** such bad shape that dropping a lock or two doesn't matter much.
25087      */
25088      close(h);
25089      h = -1;
25090    }
25091    unixLeaveMutex();
25092  }
25093
25094#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25095  else if( pLockingStyle == &afpIoMethods ){
25096    /* AFP locking uses the file path so it needs to be included in
25097    ** the afpLockingContext.
25098    */
25099    afpLockingContext *pCtx;
25100    pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
25101    if( pCtx==0 ){
25102      rc = SQLITE_NOMEM;
25103    }else{
25104      /* NB: zFilename exists and remains valid until the file is closed
25105      ** according to requirement F11141.  So we do not need to make a
25106      ** copy of the filename. */
25107      pCtx->dbPath = zFilename;
25108      srandomdev();
25109      unixEnterMutex();
25110      rc = findLockInfo(pNew, NULL, &pNew->pOpen);
25111      unixLeaveMutex();
25112    }
25113  }
25114#endif
25115
25116  else if( pLockingStyle == &dotlockIoMethods ){
25117    /* Dotfile locking uses the file path so it needs to be included in
25118    ** the dotlockLockingContext
25119    */
25120    char *zLockFile;
25121    int nFilename;
25122    nFilename = (int)strlen(zFilename) + 6;
25123    zLockFile = (char *)sqlite3_malloc(nFilename);
25124    if( zLockFile==0 ){
25125      rc = SQLITE_NOMEM;
25126    }else{
25127      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
25128    }
25129    pNew->lockingContext = zLockFile;
25130  }
25131
25132#if OS_VXWORKS
25133  else if( pLockingStyle == &semIoMethods ){
25134    /* Named semaphore locking uses the file path so it needs to be
25135    ** included in the semLockingContext
25136    */
25137    unixEnterMutex();
25138    rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
25139    if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
25140      char *zSemName = pNew->pOpen->aSemName;
25141      int n;
25142      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
25143                       pNew->pId->zCanonicalName);
25144      for( n=1; zSemName[n]; n++ )
25145        if( zSemName[n]=='/' ) zSemName[n] = '_';
25146      pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
25147      if( pNew->pOpen->pSem == SEM_FAILED ){
25148        rc = SQLITE_NOMEM;
25149        pNew->pOpen->aSemName[0] = '\0';
25150      }
25151    }
25152    unixLeaveMutex();
25153  }
25154#endif
25155
25156  pNew->lastErrno = 0;
25157#if OS_VXWORKS
25158  if( rc!=SQLITE_OK ){
25159    unlink(zFilename);
25160    isDelete = 0;
25161  }
25162  pNew->isDelete = isDelete;
25163#endif
25164  if( rc!=SQLITE_OK ){
25165    if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
25166    if( h>=0 ) close(h);
25167  }else{
25168    pNew->pMethod = pLockingStyle;
25169    OpenCounter(+1);
25170  }
25171  return rc;
25172}
25173
25174/*
25175** Open a file descriptor to the directory containing file zFilename.
25176** If successful, *pFd is set to the opened file descriptor and
25177** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
25178** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
25179** value.
25180**
25181** If SQLITE_OK is returned, the caller is responsible for closing
25182** the file descriptor *pFd using close().
25183*/
25184static int openDirectory(const char *zFilename, int *pFd){
25185  int ii;
25186  int fd = -1;
25187  char zDirname[MAX_PATHNAME+1];
25188
25189  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
25190  for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
25191  if( ii>0 ){
25192    zDirname[ii] = '\0';
25193    fd = open(zDirname, O_RDONLY|O_BINARY, 0);
25194    if( fd>=0 ){
25195#ifdef FD_CLOEXEC
25196      fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25197#endif
25198      OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
25199    }
25200  }
25201  *pFd = fd;
25202  return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
25203}
25204
25205/*
25206** Create a temporary file name in zBuf.  zBuf must be allocated
25207** by the calling process and must be big enough to hold at least
25208** pVfs->mxPathname bytes.
25209*/
25210static int getTempname(int nBuf, char *zBuf){
25211  static const char *azDirs[] = {
25212     0,
25213     0,
25214     "/var/tmp",
25215     "/usr/tmp",
25216     "/tmp",
25217     ".",
25218  };
25219  static const unsigned char zChars[] =
25220    "abcdefghijklmnopqrstuvwxyz"
25221    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
25222    "0123456789";
25223  unsigned int i, j;
25224  struct stat buf;
25225  const char *zDir = ".";
25226
25227  /* It's odd to simulate an io-error here, but really this is just
25228  ** using the io-error infrastructure to test that SQLite handles this
25229  ** function failing.
25230  */
25231  SimulateIOError( return SQLITE_IOERR );
25232
25233  azDirs[0] = sqlite3_temp_directory;
25234  if (NULL == azDirs[1]) {
25235    azDirs[1] = getenv("TMPDIR");
25236  }
25237
25238  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
25239    if( azDirs[i]==0 ) continue;
25240    if( stat(azDirs[i], &buf) ) continue;
25241    if( !S_ISDIR(buf.st_mode) ) continue;
25242    if( access(azDirs[i], 07) ) continue;
25243    zDir = azDirs[i];
25244    break;
25245  }
25246
25247  /* Check that the output buffer is large enough for the temporary file
25248  ** name. If it is not, return SQLITE_ERROR.
25249  */
25250  if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
25251    return SQLITE_ERROR;
25252  }
25253
25254  do{
25255    sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
25256    j = (int)strlen(zBuf);
25257    sqlite3_randomness(15, &zBuf[j]);
25258    for(i=0; i<15; i++, j++){
25259      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
25260    }
25261    zBuf[j] = 0;
25262  }while( access(zBuf,0)==0 );
25263  return SQLITE_OK;
25264}
25265
25266#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25267/*
25268** Routine to transform a unixFile into a proxy-locking unixFile.
25269** Implementation in the proxy-lock division, but used by unixOpen()
25270** if SQLITE_PREFER_PROXY_LOCKING is defined.
25271*/
25272static int proxyTransformUnixFile(unixFile*, const char*);
25273#endif
25274
25275/*
25276** Search for an unused file descriptor that was opened on the database
25277** file (not a journal or master-journal file) identified by pathname
25278** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
25279** argument to this function.
25280**
25281** Such a file descriptor may exist if a database connection was closed
25282** but the associated file descriptor could not be closed because some
25283** other file descriptor open on the same file is holding a file-lock.
25284** Refer to comments in the unixClose() function and the lengthy comment
25285** describing "Posix Advisory Locking" at the start of this file for
25286** further details. Also, ticket #4018.
25287**
25288** If a suitable file descriptor is found, then it is returned. If no
25289** such file descriptor is located, -1 is returned.
25290*/
25291static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
25292  UnixUnusedFd *pUnused = 0;
25293
25294  /* Do not search for an unused file descriptor on vxworks. Not because
25295  ** vxworks would not benefit from the change (it might, we're not sure),
25296  ** but because no way to test it is currently available. It is better
25297  ** not to risk breaking vxworks support for the sake of such an obscure
25298  ** feature.  */
25299#if !OS_VXWORKS
25300  struct stat sStat;                   /* Results of stat() call */
25301
25302  /* A stat() call may fail for various reasons. If this happens, it is
25303  ** almost certain that an open() call on the same path will also fail.
25304  ** For this reason, if an error occurs in the stat() call here, it is
25305  ** ignored and -1 is returned. The caller will try to open a new file
25306  ** descriptor on the same path, fail, and return an error to SQLite.
25307  **
25308  ** Even if a subsequent open() call does succeed, the consequences of
25309  ** not searching for a resusable file descriptor are not dire.  */
25310  if( 0==stat(zPath, &sStat) ){
25311    struct unixOpenCnt *pOpen;
25312
25313    unixEnterMutex();
25314    pOpen = openList;
25315    while( pOpen && (pOpen->fileId.dev!=sStat.st_dev
25316                     || pOpen->fileId.ino!=sStat.st_ino) ){
25317       pOpen = pOpen->pNext;
25318    }
25319    if( pOpen ){
25320      UnixUnusedFd **pp;
25321      for(pp=&pOpen->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
25322      pUnused = *pp;
25323      if( pUnused ){
25324        *pp = pUnused->pNext;
25325      }
25326    }
25327    unixLeaveMutex();
25328  }
25329#endif    /* if !OS_VXWORKS */
25330  return pUnused;
25331}
25332
25333/*
25334** Open the file zPath.
25335**
25336** Previously, the SQLite OS layer used three functions in place of this
25337** one:
25338**
25339**     sqlite3OsOpenReadWrite();
25340**     sqlite3OsOpenReadOnly();
25341**     sqlite3OsOpenExclusive();
25342**
25343** These calls correspond to the following combinations of flags:
25344**
25345**     ReadWrite() ->     (READWRITE | CREATE)
25346**     ReadOnly()  ->     (READONLY)
25347**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
25348**
25349** The old OpenExclusive() accepted a boolean argument - "delFlag". If
25350** true, the file was configured to be automatically deleted when the
25351** file handle closed. To achieve the same effect using this new
25352** interface, add the DELETEONCLOSE flag to those specified above for
25353** OpenExclusive().
25354*/
25355static int unixOpen(
25356  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
25357  const char *zPath,           /* Pathname of file to be opened */
25358  sqlite3_file *pFile,         /* The file descriptor to be filled in */
25359  int flags,                   /* Input flags to control the opening */
25360  int *pOutFlags               /* Output flags returned to SQLite core */
25361){
25362  unixFile *p = (unixFile *)pFile;
25363  int fd = -1;                   /* File descriptor returned by open() */
25364  int dirfd = -1;                /* Directory file descriptor */
25365  int openFlags = 0;             /* Flags to pass to open() */
25366  int eType = flags&0xFFFFFF00;  /* Type of file to open */
25367  int noLock;                    /* True to omit locking primitives */
25368  int rc = SQLITE_OK;            /* Function Return Code */
25369
25370  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
25371  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
25372  int isCreate     = (flags & SQLITE_OPEN_CREATE);
25373  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
25374  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
25375
25376  /* If creating a master or main-file journal, this function will open
25377  ** a file-descriptor on the directory too. The first time unixSync()
25378  ** is called the directory file descriptor will be fsync()ed and close()d.
25379  */
25380  int isOpenDirectory = (isCreate &&
25381      (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
25382  );
25383
25384  /* If argument zPath is a NULL pointer, this function is required to open
25385  ** a temporary file. Use this buffer to store the file name in.
25386  */
25387  char zTmpname[MAX_PATHNAME+1];
25388  const char *zName = zPath;
25389
25390  /* Check the following statements are true:
25391  **
25392  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
25393  **   (b) if CREATE is set, then READWRITE must also be set, and
25394  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
25395  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
25396  */
25397  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
25398  assert(isCreate==0 || isReadWrite);
25399  assert(isExclusive==0 || isCreate);
25400  assert(isDelete==0 || isCreate);
25401
25402  /* The main DB, main journal, and master journal are never automatically
25403  ** deleted. Nor are they ever temporary files.  */
25404  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
25405  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
25406  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
25407
25408  /* Assert that the upper layer has set one of the "file-type" flags. */
25409  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
25410       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
25411       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
25412       || eType==SQLITE_OPEN_TRANSIENT_DB
25413  );
25414
25415  memset(p, 0, sizeof(unixFile));
25416
25417  if( eType==SQLITE_OPEN_MAIN_DB ){
25418    UnixUnusedFd *pUnused;
25419    pUnused = findReusableFd(zName, flags);
25420    if( pUnused ){
25421      fd = pUnused->fd;
25422    }else{
25423      pUnused = sqlite3_malloc(sizeof(*pUnused));
25424      if( !pUnused ){
25425        return SQLITE_NOMEM;
25426      }
25427    }
25428    p->pUnused = pUnused;
25429  }else if( !zName ){
25430    /* If zName is NULL, the upper layer is requesting a temp file. */
25431    assert(isDelete && !isOpenDirectory);
25432    rc = getTempname(MAX_PATHNAME+1, zTmpname);
25433    if( rc!=SQLITE_OK ){
25434      return rc;
25435    }
25436    zName = zTmpname;
25437  }
25438
25439  /* Determine the value of the flags parameter passed to POSIX function
25440  ** open(). These must be calculated even if open() is not called, as
25441  ** they may be stored as part of the file handle and used by the
25442  ** 'conch file' locking functions later on.  */
25443  if( isReadonly )  openFlags |= O_RDONLY;
25444  if( isReadWrite ) openFlags |= O_RDWR;
25445  if( isCreate )    openFlags |= O_CREAT;
25446  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
25447  openFlags |= (O_LARGEFILE|O_BINARY);
25448
25449  if( fd<0 ){
25450    mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
25451    fd = open(zName, openFlags, openMode);
25452    OSTRACE4("OPENX   %-3d %s 0%o\n", fd, zName, openFlags);
25453    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
25454      /* Failed to open the file for read/write access. Try read-only. */
25455      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
25456      openFlags &= ~(O_RDWR|O_CREAT);
25457      flags |= SQLITE_OPEN_READONLY;
25458      openFlags |= O_RDONLY;
25459      fd = open(zName, openFlags, openMode);
25460    }
25461    if( fd<0 ){
25462      rc = SQLITE_CANTOPEN_BKPT;
25463      goto open_finished;
25464    }
25465  }
25466  assert( fd>=0 );
25467  if( pOutFlags ){
25468    *pOutFlags = flags;
25469  }
25470
25471  if( p->pUnused ){
25472    p->pUnused->fd = fd;
25473    p->pUnused->flags = flags;
25474  }
25475
25476  if( isDelete ){
25477#if OS_VXWORKS
25478    zPath = zName;
25479#else
25480    unlink(zName);
25481#endif
25482  }
25483#if SQLITE_ENABLE_LOCKING_STYLE
25484  else{
25485    p->openFlags = openFlags;
25486  }
25487#endif
25488
25489  if( isOpenDirectory ){
25490    rc = openDirectory(zPath, &dirfd);
25491    if( rc!=SQLITE_OK ){
25492      /* It is safe to close fd at this point, because it is guaranteed not
25493      ** to be open on a database file. If it were open on a database file,
25494      ** it would not be safe to close as this would release any locks held
25495      ** on the file by this process.  */
25496      assert( eType!=SQLITE_OPEN_MAIN_DB );
25497      close(fd);             /* silently leak if fail, already in error */
25498      goto open_finished;
25499    }
25500  }
25501
25502#ifdef FD_CLOEXEC
25503  fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25504#endif
25505
25506  noLock = eType!=SQLITE_OPEN_MAIN_DB;
25507
25508#if SQLITE_PREFER_PROXY_LOCKING
25509  if( zPath!=NULL && !noLock && pVfs->xOpen ){
25510    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
25511    int useProxy = 0;
25512
25513    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
25514    ** never use proxy, NULL means use proxy for non-local files only.  */
25515    if( envforce!=NULL ){
25516      useProxy = atoi(envforce)>0;
25517    }else{
25518      struct statfs fsInfo;
25519      if( statfs(zPath, &fsInfo) == -1 ){
25520        /* In theory, the close(fd) call is sub-optimal. If the file opened
25521        ** with fd is a database file, and there are other connections open
25522        ** on that file that are currently holding advisory locks on it,
25523        ** then the call to close() will cancel those locks. In practice,
25524        ** we're assuming that statfs() doesn't fail very often. At least
25525        ** not while other file descriptors opened by the same process on
25526        ** the same file are working.  */
25527        p->lastErrno = errno;
25528        if( dirfd>=0 ){
25529          close(dirfd); /* silently leak if fail, in error */
25530        }
25531        close(fd); /* silently leak if fail, in error */
25532        rc = SQLITE_IOERR_ACCESS;
25533        goto open_finished;
25534      }
25535      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
25536    }
25537    if( useProxy ){
25538      rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
25539      if( rc==SQLITE_OK ){
25540        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
25541      }
25542      goto open_finished;
25543    }
25544  }
25545#endif
25546
25547  rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
25548open_finished:
25549  if( rc!=SQLITE_OK ){
25550    sqlite3_free(p->pUnused);
25551  }
25552  return rc;
25553}
25554
25555
25556/*
25557** Delete the file at zPath. If the dirSync argument is true, fsync()
25558** the directory after deleting the file.
25559*/
25560static int unixDelete(
25561  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
25562  const char *zPath,        /* Name of file to be deleted */
25563  int dirSync               /* If true, fsync() directory after deleting file */
25564){
25565  int rc = SQLITE_OK;
25566  UNUSED_PARAMETER(NotUsed);
25567  SimulateIOError(return SQLITE_IOERR_DELETE);
25568  unlink(zPath);
25569#ifndef SQLITE_DISABLE_DIRSYNC
25570  if( dirSync ){
25571    int fd;
25572    rc = openDirectory(zPath, &fd);
25573    if( rc==SQLITE_OK ){
25574#if OS_VXWORKS
25575      if( fsync(fd)==-1 )
25576#else
25577      if( fsync(fd) )
25578#endif
25579      {
25580        rc = SQLITE_IOERR_DIR_FSYNC;
25581      }
25582      if( close(fd)&&!rc ){
25583        rc = SQLITE_IOERR_DIR_CLOSE;
25584      }
25585    }
25586  }
25587#endif
25588  return rc;
25589}
25590
25591/*
25592** Test the existance of or access permissions of file zPath. The
25593** test performed depends on the value of flags:
25594**
25595**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
25596**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
25597**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
25598**
25599** Otherwise return 0.
25600*/
25601static int unixAccess(
25602  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
25603  const char *zPath,      /* Path of the file to examine */
25604  int flags,              /* What do we want to learn about the zPath file? */
25605  int *pResOut            /* Write result boolean here */
25606){
25607  int amode = 0;
25608  UNUSED_PARAMETER(NotUsed);
25609  SimulateIOError( return SQLITE_IOERR_ACCESS; );
25610  switch( flags ){
25611    case SQLITE_ACCESS_EXISTS:
25612      amode = F_OK;
25613      break;
25614    case SQLITE_ACCESS_READWRITE:
25615      amode = W_OK|R_OK;
25616      break;
25617    case SQLITE_ACCESS_READ:
25618      amode = R_OK;
25619      break;
25620
25621    default:
25622      assert(!"Invalid flags argument");
25623  }
25624  *pResOut = (access(zPath, amode)==0);
25625  return SQLITE_OK;
25626}
25627
25628
25629/*
25630** Turn a relative pathname into a full pathname. The relative path
25631** is stored as a nul-terminated string in the buffer pointed to by
25632** zPath.
25633**
25634** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
25635** (in this case, MAX_PATHNAME bytes). The full-path is written to
25636** this buffer before returning.
25637*/
25638static int unixFullPathname(
25639  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
25640  const char *zPath,            /* Possibly relative input path */
25641  int nOut,                     /* Size of output buffer in bytes */
25642  char *zOut                    /* Output buffer */
25643){
25644
25645  /* It's odd to simulate an io-error here, but really this is just
25646  ** using the io-error infrastructure to test that SQLite handles this
25647  ** function failing. This function could fail if, for example, the
25648  ** current working directory has been unlinked.
25649  */
25650  SimulateIOError( return SQLITE_ERROR );
25651
25652  assert( pVfs->mxPathname==MAX_PATHNAME );
25653  UNUSED_PARAMETER(pVfs);
25654
25655  zOut[nOut-1] = '\0';
25656  if( zPath[0]=='/' ){
25657    sqlite3_snprintf(nOut, zOut, "%s", zPath);
25658  }else{
25659    int nCwd;
25660    if( getcwd(zOut, nOut-1)==0 ){
25661      return SQLITE_CANTOPEN_BKPT;
25662    }
25663    nCwd = (int)strlen(zOut);
25664    sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
25665  }
25666  return SQLITE_OK;
25667}
25668
25669
25670#ifndef SQLITE_OMIT_LOAD_EXTENSION
25671/*
25672** Interfaces for opening a shared library, finding entry points
25673** within the shared library, and closing the shared library.
25674*/
25675#include <dlfcn.h>
25676static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
25677  UNUSED_PARAMETER(NotUsed);
25678  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
25679}
25680
25681/*
25682** SQLite calls this function immediately after a call to unixDlSym() or
25683** unixDlOpen() fails (returns a null pointer). If a more detailed error
25684** message is available, it is written to zBufOut. If no error message
25685** is available, zBufOut is left unmodified and SQLite uses a default
25686** error message.
25687*/
25688static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
25689  char *zErr;
25690  UNUSED_PARAMETER(NotUsed);
25691  unixEnterMutex();
25692  zErr = dlerror();
25693  if( zErr ){
25694    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
25695  }
25696  unixLeaveMutex();
25697}
25698static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
25699  /*
25700  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
25701  ** cast into a pointer to a function.  And yet the library dlsym() routine
25702  ** returns a void* which is really a pointer to a function.  So how do we
25703  ** use dlsym() with -pedantic-errors?
25704  **
25705  ** Variable x below is defined to be a pointer to a function taking
25706  ** parameters void* and const char* and returning a pointer to a function.
25707  ** We initialize x by assigning it a pointer to the dlsym() function.
25708  ** (That assignment requires a cast.)  Then we call the function that
25709  ** x points to.
25710  **
25711  ** This work-around is unlikely to work correctly on any system where
25712  ** you really cannot cast a function pointer into void*.  But then, on the
25713  ** other hand, dlsym() will not work on such a system either, so we have
25714  ** not really lost anything.
25715  */
25716  void (*(*x)(void*,const char*))(void);
25717  UNUSED_PARAMETER(NotUsed);
25718  x = (void(*(*)(void*,const char*))(void))dlsym;
25719  return (*x)(p, zSym);
25720}
25721static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
25722  UNUSED_PARAMETER(NotUsed);
25723  dlclose(pHandle);
25724}
25725#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
25726  #define unixDlOpen  0
25727  #define unixDlError 0
25728  #define unixDlSym   0
25729  #define unixDlClose 0
25730#endif
25731
25732/*
25733** Write nBuf bytes of random data to the supplied buffer zBuf.
25734*/
25735static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
25736  UNUSED_PARAMETER(NotUsed);
25737  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
25738
25739  /* We have to initialize zBuf to prevent valgrind from reporting
25740  ** errors.  The reports issued by valgrind are incorrect - we would
25741  ** prefer that the randomness be increased by making use of the
25742  ** uninitialized space in zBuf - but valgrind errors tend to worry
25743  ** some users.  Rather than argue, it seems easier just to initialize
25744  ** the whole array and silence valgrind, even if that means less randomness
25745  ** in the random seed.
25746  **
25747  ** When testing, initializing zBuf[] to zero is all we do.  That means
25748  ** that we always use the same random number sequence.  This makes the
25749  ** tests repeatable.
25750  */
25751  memset(zBuf, 0, nBuf);
25752#if !defined(SQLITE_TEST)
25753  {
25754    int pid, fd;
25755    fd = open("/dev/urandom", O_RDONLY);
25756    if( fd<0 ){
25757      time_t t;
25758      time(&t);
25759      memcpy(zBuf, &t, sizeof(t));
25760      pid = getpid();
25761      memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
25762      assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
25763      nBuf = sizeof(t) + sizeof(pid);
25764    }else{
25765      nBuf = read(fd, zBuf, nBuf);
25766      close(fd);
25767    }
25768  }
25769#endif
25770  return nBuf;
25771}
25772
25773
25774/*
25775** Sleep for a little while.  Return the amount of time slept.
25776** The argument is the number of microseconds we want to sleep.
25777** The return value is the number of microseconds of sleep actually
25778** requested from the underlying operating system, a number which
25779** might be greater than or equal to the argument, but not less
25780** than the argument.
25781*/
25782static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
25783#if OS_VXWORKS
25784  struct timespec sp;
25785
25786  sp.tv_sec = microseconds / 1000000;
25787  sp.tv_nsec = (microseconds % 1000000) * 1000;
25788  nanosleep(&sp, NULL);
25789  UNUSED_PARAMETER(NotUsed);
25790  return microseconds;
25791#elif defined(HAVE_USLEEP) && HAVE_USLEEP
25792  usleep(microseconds);
25793  UNUSED_PARAMETER(NotUsed);
25794  return microseconds;
25795#else
25796  int seconds = (microseconds+999999)/1000000;
25797  sleep(seconds);
25798  UNUSED_PARAMETER(NotUsed);
25799  return seconds*1000000;
25800#endif
25801}
25802
25803/*
25804** The following variable, if set to a non-zero value, is interpreted as
25805** the number of seconds since 1970 and is used to set the result of
25806** sqlite3OsCurrentTime() during testing.
25807*/
25808#ifdef SQLITE_TEST
25809SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
25810#endif
25811
25812/*
25813** Find the current time (in Universal Coordinated Time).  Write the
25814** current time and date as a Julian Day number into *prNow and
25815** return 0.  Return 1 if the time and date cannot be found.
25816*/
25817static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
25818#if defined(SQLITE_OMIT_FLOATING_POINT)
25819  time_t t;
25820  time(&t);
25821  *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
25822#elif defined(NO_GETTOD)
25823  time_t t;
25824  time(&t);
25825  *prNow = t/86400.0 + 2440587.5;
25826#elif OS_VXWORKS
25827  struct timespec sNow;
25828  clock_gettime(CLOCK_REALTIME, &sNow);
25829  *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
25830#else
25831  struct timeval sNow;
25832  gettimeofday(&sNow, 0);
25833  *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
25834#endif
25835
25836#ifdef SQLITE_TEST
25837  if( sqlite3_current_time ){
25838    *prNow = sqlite3_current_time/86400.0 + 2440587.5;
25839  }
25840#endif
25841  UNUSED_PARAMETER(NotUsed);
25842  return 0;
25843}
25844
25845/*
25846** We added the xGetLastError() method with the intention of providing
25847** better low-level error messages when operating-system problems come up
25848** during SQLite operation.  But so far, none of that has been implemented
25849** in the core.  So this routine is never called.  For now, it is merely
25850** a place-holder.
25851*/
25852static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
25853  UNUSED_PARAMETER(NotUsed);
25854  UNUSED_PARAMETER(NotUsed2);
25855  UNUSED_PARAMETER(NotUsed3);
25856  return 0;
25857}
25858
25859/*
25860************************ End of sqlite3_vfs methods ***************************
25861******************************************************************************/
25862
25863/******************************************************************************
25864************************** Begin Proxy Locking ********************************
25865**
25866** Proxy locking is a "uber-locking-method" in this sense:  It uses the
25867** other locking methods on secondary lock files.  Proxy locking is a
25868** meta-layer over top of the primitive locking implemented above.  For
25869** this reason, the division that implements of proxy locking is deferred
25870** until late in the file (here) after all of the other I/O methods have
25871** been defined - so that the primitive locking methods are available
25872** as services to help with the implementation of proxy locking.
25873**
25874****
25875**
25876** The default locking schemes in SQLite use byte-range locks on the
25877** database file to coordinate safe, concurrent access by multiple readers
25878** and writers [http://sqlite.org/lockingv3.html].  The five file locking
25879** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
25880** as POSIX read & write locks over fixed set of locations (via fsctl),
25881** on AFP and SMB only exclusive byte-range locks are available via fsctl
25882** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
25883** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
25884** address in the shared range is taken for a SHARED lock, the entire
25885** shared range is taken for an EXCLUSIVE lock):
25886**
25887**      PENDING_BYTE        0x40000000
25888**      RESERVED_BYTE       0x40000001
25889**      SHARED_RANGE        0x40000002 -> 0x40000200
25890**
25891** This works well on the local file system, but shows a nearly 100x
25892** slowdown in read performance on AFP because the AFP client disables
25893** the read cache when byte-range locks are present.  Enabling the read
25894** cache exposes a cache coherency problem that is present on all OS X
25895** supported network file systems.  NFS and AFP both observe the
25896** close-to-open semantics for ensuring cache coherency
25897** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
25898** address the requirements for concurrent database access by multiple
25899** readers and writers
25900** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
25901**
25902** To address the performance and cache coherency issues, proxy file locking
25903** changes the way database access is controlled by limiting access to a
25904** single host at a time and moving file locks off of the database file
25905** and onto a proxy file on the local file system.
25906**
25907**
25908** Using proxy locks
25909** -----------------
25910**
25911** C APIs
25912**
25913**  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
25914**                       <proxy_path> | ":auto:");
25915**  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
25916**
25917**
25918** SQL pragmas
25919**
25920**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
25921**  PRAGMA [database.]lock_proxy_file
25922**
25923** Specifying ":auto:" means that if there is a conch file with a matching
25924** host ID in it, the proxy path in the conch file will be used, otherwise
25925** a proxy path based on the user's temp dir
25926** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
25927** actual proxy file name is generated from the name and path of the
25928** database file.  For example:
25929**
25930**       For database path "/Users/me/foo.db"
25931**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
25932**
25933** Once a lock proxy is configured for a database connection, it can not
25934** be removed, however it may be switched to a different proxy path via
25935** the above APIs (assuming the conch file is not being held by another
25936** connection or process).
25937**
25938**
25939** How proxy locking works
25940** -----------------------
25941**
25942** Proxy file locking relies primarily on two new supporting files:
25943**
25944**   *  conch file to limit access to the database file to a single host
25945**      at a time
25946**
25947**   *  proxy file to act as a proxy for the advisory locks normally
25948**      taken on the database
25949**
25950** The conch file - to use a proxy file, sqlite must first "hold the conch"
25951** by taking an sqlite-style shared lock on the conch file, reading the
25952** contents and comparing the host's unique host ID (see below) and lock
25953** proxy path against the values stored in the conch.  The conch file is
25954** stored in the same directory as the database file and the file name
25955** is patterned after the database file name as ".<databasename>-conch".
25956** If the conch file does not exist, or it's contents do not match the
25957** host ID and/or proxy path, then the lock is escalated to an exclusive
25958** lock and the conch file contents is updated with the host ID and proxy
25959** path and the lock is downgraded to a shared lock again.  If the conch
25960** is held by another process (with a shared lock), the exclusive lock
25961** will fail and SQLITE_BUSY is returned.
25962**
25963** The proxy file - a single-byte file used for all advisory file locks
25964** normally taken on the database file.   This allows for safe sharing
25965** of the database file for multiple readers and writers on the same
25966** host (the conch ensures that they all use the same local lock file).
25967**
25968** There is a third file - the host ID file - used as a persistent record
25969** of a unique identifier for the host, a 128-byte unique host id file
25970** in the path defined by the HOSTIDPATH macro (default value is
25971** /Library/Caches/.com.apple.sqliteConchHostId).
25972**
25973** Requesting the lock proxy does not immediately take the conch, it is
25974** only taken when the first request to lock database file is made.
25975** This matches the semantics of the traditional locking behavior, where
25976** opening a connection to a database file does not take a lock on it.
25977** The shared lock and an open file descriptor are maintained until
25978** the connection to the database is closed.
25979**
25980** The proxy file and the lock file are never deleted so they only need
25981** to be created the first time they are used.
25982**
25983** Configuration options
25984** ---------------------
25985**
25986**  SQLITE_PREFER_PROXY_LOCKING
25987**
25988**       Database files accessed on non-local file systems are
25989**       automatically configured for proxy locking, lock files are
25990**       named automatically using the same logic as
25991**       PRAGMA lock_proxy_file=":auto:"
25992**
25993**  SQLITE_PROXY_DEBUG
25994**
25995**       Enables the logging of error messages during host id file
25996**       retrieval and creation
25997**
25998**  HOSTIDPATH
25999**
26000**       Overrides the default host ID file path location
26001**
26002**  LOCKPROXYDIR
26003**
26004**       Overrides the default directory used for lock proxy files that
26005**       are named automatically via the ":auto:" setting
26006**
26007**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
26008**
26009**       Permissions to use when creating a directory for storing the
26010**       lock proxy files, only used when LOCKPROXYDIR is not set.
26011**
26012**
26013** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
26014** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
26015** force proxy locking to be used for every database file opened, and 0
26016** will force automatic proxy locking to be disabled for all database
26017** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
26018** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
26019*/
26020
26021/*
26022** Proxy locking is only available on MacOSX
26023*/
26024#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26025
26026#ifdef SQLITE_TEST
26027/* simulate multiple hosts by creating unique hostid file paths */
26028SQLITE_API int sqlite3_hostid_num = 0;
26029#endif
26030
26031/*
26032** The proxyLockingContext has the path and file structures for the remote
26033** and local proxy files in it
26034*/
26035typedef struct proxyLockingContext proxyLockingContext;
26036struct proxyLockingContext {
26037  unixFile *conchFile;         /* Open conch file */
26038  char *conchFilePath;         /* Name of the conch file */
26039  unixFile *lockProxy;         /* Open proxy lock file */
26040  char *lockProxyPath;         /* Name of the proxy lock file */
26041  char *dbPath;                /* Name of the open file */
26042  int conchHeld;               /* True if the conch is currently held */
26043  void *oldLockingContext;     /* Original lockingcontext to restore on close */
26044  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
26045};
26046
26047/* HOSTIDLEN and CONCHLEN both include space for the string
26048** terminating nul
26049*/
26050#define HOSTIDLEN         128
26051#define CONCHLEN          (MAXPATHLEN+HOSTIDLEN+1)
26052#ifndef HOSTIDPATH
26053# define HOSTIDPATH       "/Library/Caches/.com.apple.sqliteConchHostId"
26054#endif
26055
26056/* basically a copy of unixRandomness with different
26057** test behavior built in */
26058static int proxyGenerateHostID(char *pHostID){
26059  int pid, fd, len;
26060  unsigned char *key = (unsigned char *)pHostID;
26061
26062  memset(key, 0, HOSTIDLEN);
26063  len = 0;
26064  fd = open("/dev/urandom", O_RDONLY);
26065  if( fd>=0 ){
26066    len = read(fd, key, HOSTIDLEN);
26067    close(fd); /* silently leak the fd if it fails */
26068  }
26069  if( len < HOSTIDLEN ){
26070    time_t t;
26071    time(&t);
26072    memcpy(key, &t, sizeof(t));
26073    pid = getpid();
26074    memcpy(&key[sizeof(t)], &pid, sizeof(pid));
26075  }
26076
26077#ifdef MAKE_PRETTY_HOSTID
26078  {
26079    int i;
26080    /* filter the bytes into printable ascii characters and NUL terminate */
26081    key[(HOSTIDLEN-1)] = 0x00;
26082    for( i=0; i<(HOSTIDLEN-1); i++ ){
26083      unsigned char pa = key[i]&0x7F;
26084      if( pa<0x20 ){
26085        key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
26086      }else if( pa==0x7F ){
26087        key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
26088      }
26089    }
26090  }
26091#endif
26092  return SQLITE_OK;
26093}
26094
26095/* writes the host id path to path, path should be an pre-allocated buffer
26096** with enough space for a path
26097*/
26098static void proxyGetHostIDPath(char *path, size_t len){
26099  strlcpy(path, HOSTIDPATH, len);
26100#ifdef SQLITE_TEST
26101  if( sqlite3_hostid_num>0 ){
26102    char suffix[2] = "1";
26103    suffix[0] = suffix[0] + sqlite3_hostid_num;
26104    strlcat(path, suffix, len);
26105  }
26106#endif
26107  OSTRACE3("GETHOSTIDPATH  %s pid=%d\n", path, getpid());
26108}
26109
26110/* get the host ID from a sqlite hostid file stored in the
26111** user-specific tmp directory, create the ID if it's not there already
26112*/
26113static int proxyGetHostID(char *pHostID, int *pError){
26114  int fd;
26115  char path[MAXPATHLEN];
26116  size_t len;
26117  int rc=SQLITE_OK;
26118
26119  proxyGetHostIDPath(path, MAXPATHLEN);
26120  /* try to create the host ID file, if it already exists read the contents */
26121  fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
26122  if( fd<0 ){
26123    int err=errno;
26124
26125    if( err!=EEXIST ){
26126#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
26127      fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
26128              path, strerror(err));
26129#endif
26130      return SQLITE_PERM;
26131    }
26132    /* couldn't create the file, read it instead */
26133    fd = open(path, O_RDONLY|O_EXCL);
26134    if( fd<0 ){
26135#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
26136      int err = errno;
26137      fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
26138              path, strerror(err));
26139#endif
26140      return SQLITE_PERM;
26141    }
26142    len = pread(fd, pHostID, HOSTIDLEN, 0);
26143    if( len<0 ){
26144      *pError = errno;
26145      rc = SQLITE_IOERR_READ;
26146    }else if( len<HOSTIDLEN ){
26147      *pError = 0;
26148      rc = SQLITE_IOERR_SHORT_READ;
26149    }
26150    close(fd); /* silently leak the fd if it fails */
26151    OSTRACE3("GETHOSTID  read %s pid=%d\n", pHostID, getpid());
26152    return rc;
26153  }else{
26154    /* we're creating the host ID file (use a random string of bytes) */
26155    proxyGenerateHostID(pHostID);
26156    len = pwrite(fd, pHostID, HOSTIDLEN, 0);
26157    if( len<0 ){
26158      *pError = errno;
26159      rc = SQLITE_IOERR_WRITE;
26160    }else if( len<HOSTIDLEN ){
26161      *pError = 0;
26162      rc = SQLITE_IOERR_WRITE;
26163    }
26164    close(fd); /* silently leak the fd if it fails */
26165    OSTRACE3("GETHOSTID  wrote %s pid=%d\n", pHostID, getpid());
26166    return rc;
26167  }
26168}
26169
26170static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
26171  int len;
26172  int dbLen;
26173  int i;
26174
26175#ifdef LOCKPROXYDIR
26176  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
26177#else
26178# ifdef _CS_DARWIN_USER_TEMP_DIR
26179  {
26180    confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
26181    len = strlcat(lPath, "sqliteplocks", maxLen);
26182    if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
26183      /* if mkdir fails, handle as lock file creation failure */
26184#  ifdef SQLITE_DEBUG
26185      int err = errno;
26186      if( err!=EEXIST ){
26187        fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
26188                SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
26189      }
26190#  endif
26191    }else{
26192      OSTRACE3("GETLOCKPATH  mkdir %s pid=%d\n", lPath, getpid());
26193    }
26194
26195  }
26196# else
26197  len = strlcpy(lPath, "/tmp/", maxLen);
26198# endif
26199#endif
26200
26201  if( lPath[len-1]!='/' ){
26202    len = strlcat(lPath, "/", maxLen);
26203  }
26204
26205  /* transform the db path to a unique cache name */
26206  dbLen = (int)strlen(dbPath);
26207  for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
26208    char c = dbPath[i];
26209    lPath[i+len] = (c=='/')?'_':c;
26210  }
26211  lPath[i+len]='\0';
26212  strlcat(lPath, ":auto:", maxLen);
26213  return SQLITE_OK;
26214}
26215
26216/*
26217** Create a new VFS file descriptor (stored in memory obtained from
26218** sqlite3_malloc) and open the file named "path" in the file descriptor.
26219**
26220** The caller is responsible not only for closing the file descriptor
26221** but also for freeing the memory associated with the file descriptor.
26222*/
26223static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
26224  unixFile *pNew;
26225  int flags = SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
26226  int rc = SQLITE_OK;
26227  sqlite3_vfs dummyVfs;
26228
26229  pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
26230  if( !pNew ){
26231    return SQLITE_NOMEM;
26232  }
26233  memset(pNew, 0, sizeof(unixFile));
26234
26235  /* Call unixOpen() to open the proxy file. The flags passed to unixOpen()
26236  ** suggest that the file being opened is a "main database". This is
26237  ** necessary as other file types do not necessarily support locking. It
26238  ** is better to use unixOpen() instead of opening the file directly with
26239  ** open(), as unixOpen() sets up the various mechanisms required to
26240  ** make sure a call to close() does not cause the system to discard
26241  ** POSIX locks prematurely.
26242  **
26243  ** It is important that the xOpen member of the VFS object passed to
26244  ** unixOpen() is NULL. This tells unixOpen() may try to open a proxy-file
26245  ** for the proxy-file (creating a potential infinite loop).
26246  */
26247  pUnused = findReusableFd(path, openFlags);
26248  if( pUnused ){
26249    fd = pUnused->fd;
26250  }else{
26251    pUnused = sqlite3_malloc(sizeof(*pUnused));
26252    if( !pUnused ){
26253      return SQLITE_NOMEM;
26254    }
26255  }
26256  if( fd<0 ){
26257    fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
26258    terrno = errno;
26259    if( fd<0 && errno==ENOENT && islockfile ){
26260      if( proxyCreateLockPath(path) == SQLITE_OK ){
26261        fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
26262      }
26263    }
26264  }
26265  if( fd<0 ){
26266    openFlags = O_RDONLY;
26267    fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
26268    terrno = errno;
26269  }
26270  if( fd<0 ){
26271    if( islockfile ){
26272      return SQLITE_BUSY;
26273    }
26274    switch (terrno) {
26275      case EACCES:
26276        return SQLITE_PERM;
26277      case EIO:
26278        return SQLITE_IOERR_LOCK; /* even though it is the conch */
26279      default:
26280        return SQLITE_CANTOPEN_BKPT;
26281    }
26282  }
26283
26284  pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
26285  if( pNew==NULL ){
26286    rc = SQLITE_NOMEM;
26287    goto end_create_proxy;
26288  }
26289  memset(pNew, 0, sizeof(unixFile));
26290  pNew->openFlags = openFlags;
26291  dummyVfs.pAppData = (void*)&autolockIoFinder;
26292  dummyVfs.xOpen = 0;
26293  rc = unixOpen(&dummyVfs, path, (sqlite3_file *)pNew, flags, &flags);
26294  if( rc==SQLITE_OK && (flags&SQLITE_OPEN_READONLY) ){
26295    pNew->pMethod->xClose((sqlite3_file *)pNew);
26296    rc = SQLITE_CANTOPEN;
26297  }
26298
26299  if( rc!=SQLITE_OK ){
26300    sqlite3_free(pNew);
26301    pNew = 0;
26302  }
26303
26304  *ppFile = pNew;
26305  return rc;
26306}
26307
26308/* takes the conch by taking a shared lock and read the contents conch, if
26309** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
26310** lockPath means that the lockPath in the conch file will be used if the
26311** host IDs match, or a new lock path will be generated automatically
26312** and written to the conch file.
26313*/
26314static int proxyTakeConch(unixFile *pFile){
26315  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26316
26317  if( pCtx->conchHeld>0 ){
26318    return SQLITE_OK;
26319  }else{
26320    unixFile *conchFile = pCtx->conchFile;
26321    char testValue[CONCHLEN];
26322    char conchValue[CONCHLEN];
26323    char lockPath[MAXPATHLEN];
26324    char *tLockPath = NULL;
26325    int rc = SQLITE_OK;
26326    int readRc = SQLITE_OK;
26327    int syncPerms = 0;
26328
26329    OSTRACE4("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
26330             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
26331
26332    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
26333    if( rc==SQLITE_OK ){
26334      int pError = 0;
26335      memset(testValue, 0, CONCHLEN); /* conch is fixed size */
26336      rc = proxyGetHostID(testValue, &pError);
26337      if( (rc&0xff)==SQLITE_IOERR ){
26338        pFile->lastErrno = pError;
26339      }
26340      if( pCtx->lockProxyPath ){
26341        strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
26342      }
26343    }
26344    if( rc!=SQLITE_OK ){
26345      goto end_takeconch;
26346    }
26347
26348    readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
26349    if( readRc!=SQLITE_IOERR_SHORT_READ ){
26350      if( readRc!=SQLITE_OK ){
26351        if( (rc&0xff)==SQLITE_IOERR ){
26352          pFile->lastErrno = conchFile->lastErrno;
26353        }
26354        rc = readRc;
26355        goto end_takeconch;
26356      }
26357      /* if the conch has data compare the contents */
26358      if( !pCtx->lockProxyPath ){
26359        /* for auto-named local lock file, just check the host ID and we'll
26360         ** use the local lock file path that's already in there */
26361        if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
26362          tLockPath = (char *)&conchValue[HOSTIDLEN];
26363          goto end_takeconch;
26364        }
26365      }else{
26366        /* we've got the conch if conchValue matches our path and host ID */
26367        if( !memcmp(testValue, conchValue, CONCHLEN) ){
26368          goto end_takeconch;
26369        }
26370      }
26371    }else{
26372      /* a short read means we're "creating" the conch (even though it could
26373      ** have been user-intervention), if we acquire the exclusive lock,
26374      ** we'll try to match the current on-disk permissions of the database
26375      */
26376      syncPerms = 1;
26377    }
26378
26379    /* either conch was emtpy or didn't match */
26380    if( !pCtx->lockProxyPath ){
26381      proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
26382      tLockPath = lockPath;
26383      strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
26384    }
26385
26386    /* update conch with host and path (this will fail if other process
26387     ** has a shared lock already) */
26388    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
26389    if( rc==SQLITE_OK ){
26390      rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
26391      if( rc==SQLITE_OK && syncPerms ){
26392        struct stat buf;
26393        int err = fstat(pFile->h, &buf);
26394        if( err==0 ){
26395          /* try to match the database file permissions, ignore failure */
26396#ifndef SQLITE_PROXY_DEBUG
26397          fchmod(conchFile->h, buf.st_mode);
26398#else
26399          if( fchmod(conchFile->h, buf.st_mode)!=0 ){
26400            int code = errno;
26401            fprintf(stderr, "fchmod %o FAILED with %d %s\n",
26402                             buf.st_mode, code, strerror(code));
26403          } else {
26404            fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
26405          }
26406        }else{
26407          int code = errno;
26408          fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
26409                          err, code, strerror(code));
26410#endif
26411        }
26412      }
26413    }
26414    conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
26415
26416end_takeconch:
26417    OSTRACE2("TRANSPROXY: CLOSE  %d\n", pFile->h);
26418    if( rc==SQLITE_OK && pFile->openFlags ){
26419      if( pFile->h>=0 ){
26420#ifdef STRICT_CLOSE_ERROR
26421        if( close(pFile->h) ){
26422          pFile->lastErrno = errno;
26423          return SQLITE_IOERR_CLOSE;
26424        }
26425#else
26426        close(pFile->h); /* silently leak fd if fail */
26427#endif
26428      }
26429      pFile->h = -1;
26430      int fd = open(pCtx->dbPath, pFile->openFlags,
26431                    SQLITE_DEFAULT_FILE_PERMISSIONS);
26432      OSTRACE2("TRANSPROXY: OPEN  %d\n", fd);
26433      if( fd>=0 ){
26434        pFile->h = fd;
26435      }else{
26436        rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
26437                               during locking */
26438      }
26439    }
26440    if( rc==SQLITE_OK && !pCtx->lockProxy ){
26441      char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
26442      /* ACS: Need to make a copy of path sometimes */
26443      rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
26444    }
26445    if( rc==SQLITE_OK ){
26446      pCtx->conchHeld = 1;
26447
26448      if( tLockPath ){
26449        pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
26450        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
26451          ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
26452                     pCtx->lockProxyPath;
26453        }
26454      }
26455>>>>>>> BEGIN MERGE CONFLICT
26456
26457      /* if the conch isn't writable and doesn't match, we can't take it */
26458      if( (conchFile->openFlags&O_RDWR) == 0 ){
26459        rc = SQLITE_BUSY;
26460        goto end_takeconch;
26461      }
26462
26463      /* either the conch didn't match or we need to create a new one */
26464      if( !pCtx->lockProxyPath ){
26465        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
26466        tempLockPath = lockPath;
26467        /* create a copy of the lock path _only_ if the conch is taken */
26468      }
26469
26470      /* update conch with host and path (this will fail if other process
26471      ** has a shared lock already), if the host id matches, use the big
26472      ** stick.
26473      */
26474      futimes(conchFile->h, NULL);
26475      if( hostIdMatch && !createConch ){
26476        if( conchFile->pLock && conchFile->pLock->cnt>1 ){
26477          /* We are trying for an exclusive lock but another thread in this
26478           ** same process is still holding a shared lock. */
26479          rc = SQLITE_BUSY;
26480        } else {
26481          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
26482        }
26483      }else{
26484        rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
26485      }
26486      if( rc==SQLITE_OK ){
26487        char writeBuffer[PROXY_MAXCONCHLEN];
26488        int writeSize = 0;
26489
26490        writeBuffer[0] = (char)PROXY_CONCHVERSION;
26491        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
26492        if( pCtx->lockProxyPath!=NULL ){
26493          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
26494        }else{
26495          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
26496        }
26497        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
26498        ftruncate(conchFile->h, writeSize);
26499        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
26500        fsync(conchFile->h);
26501        /* If we created a new conch file (not just updated the contents of a
26502         ** valid conch file), try to match the permissions of the database
26503         */
26504        if( rc==SQLITE_OK && createConch ){
26505          struct stat buf;
26506          int err = fstat(pFile->h, &buf);
26507          if( err==0 ){
26508            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
26509                                        S_IROTH|S_IWOTH);
26510            /* try to match the database file R/W permissions, ignore failure */
26511#ifndef SQLITE_PROXY_DEBUG
26512            fchmod(conchFile->h, cmode);
26513#else
26514            if( fchmod(conchFile->h, cmode)!=0 ){
26515              int code = errno;
26516              fprintf(stderr, "fchmod %o FAILED with %d %s\n",
26517                      cmode, code, strerror(code));
26518            } else {
26519              fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
26520            }
26521          }else{
26522            int code = errno;
26523            fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
26524                    err, code, strerror(code));
26525#endif
26526          }
26527        }
26528      }
26529      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
26530
26531    end_takeconch:
26532      OSTRACE2("TRANSPROXY: CLOSE  %d\n", pFile->h);
26533      if( rc==SQLITE_OK && pFile->openFlags ){
26534        if( pFile->h>=0 ){
26535#ifdef STRICT_CLOSE_ERROR
26536          if( close(pFile->h) ){
26537            pFile->lastErrno = errno;
26538            return SQLITE_IOERR_CLOSE;
26539          }
26540#else
26541          close(pFile->h); /* silently leak fd if fail */
26542#endif
26543        }
26544        pFile->h = -1;
26545        int fd = open(pCtx->dbPath, pFile->openFlags,
26546                      SQLITE_DEFAULT_FILE_PERMISSIONS);
26547        OSTRACE2("TRANSPROXY: OPEN  %d\n", fd);
26548        if( fd>=0 ){
26549          pFile->h = fd;
26550        }else{
26551          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
26552           during locking */
26553        }
26554      }
26555      if( rc==SQLITE_OK && !pCtx->lockProxy ){
26556        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
26557        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
26558        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
26559          /* we couldn't create the proxy lock file with the old lock file path
26560           ** so try again via auto-naming
26561           */
26562          forceNewLockPath = 1;
26563          tryOldLockPath = 0;
26564          continue; /* go back to the do {} while start point, try again */
26565        }
26566      }
26567      if( rc==SQLITE_OK ){
26568        /* Need to make a copy of path if we extracted the value
26569         ** from the conch file or the path was allocated on the stack
26570         */
26571        if( tempLockPath ){
26572          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
26573          if( !pCtx->lockProxyPath ){
26574            rc = SQLITE_NOMEM;
26575          }
26576        }
26577      }
26578      if( rc==SQLITE_OK ){
26579        pCtx->conchHeld = 1;
26580
26581        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
26582          afpLockingContext *afpCtx;
26583          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
26584          afpCtx->dbPath = pCtx->lockProxyPath;
26585        }
26586      } else {
26587        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
26588      }
26589      OSTRACE3("TAKECONCH  %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
26590      return rc;
26591    } while (1); /* in case we need to retry the :auto: lock file - we should never get here except via the 'continue' call. */
26592============================
26593    } else {
26594      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
26595    }
26596    OSTRACE3("TAKECONCH  %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
26597    return rc;
26598<<<<<<< END MERGE CONFLICT
26599  }
26600}
26601
26602/*
26603** If pFile holds a lock on a conch file, then release that lock.
26604*/
26605static int proxyReleaseConch(unixFile *pFile){
26606  int rc;                     /* Subroutine return code */
26607  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
26608  unixFile *conchFile;        /* Name of the conch file */
26609
26610  pCtx = (proxyLockingContext *)pFile->lockingContext;
26611  conchFile = pCtx->conchFile;
26612  OSTRACE4("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
26613           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
26614           getpid());
26615  pCtx->conchHeld = 0;
26616  rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
26617  OSTRACE3("RELEASECONCH  %d %s\n", conchFile->h,
26618           (rc==SQLITE_OK ? "ok" : "failed"));
26619  return rc;
26620}
26621
26622/*
26623** Given the name of a database file, compute the name of its conch file.
26624** Store the conch filename in memory obtained from sqlite3_malloc().
26625** Make *pConchPath point to the new name.  Return SQLITE_OK on success
26626** or SQLITE_NOMEM if unable to obtain memory.
26627**
26628** The caller is responsible for ensuring that the allocated memory
26629** space is eventually freed.
26630**
26631** *pConchPath is set to NULL if a memory allocation error occurs.
26632*/
26633static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
26634  int i;                        /* Loop counter */
26635  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
26636  char *conchPath;              /* buffer in which to construct conch name */
26637
26638  /* Allocate space for the conch filename and initialize the name to
26639  ** the name of the original database file. */
26640  *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
26641  if( conchPath==0 ){
26642    return SQLITE_NOMEM;
26643  }
26644  memcpy(conchPath, dbPath, len+1);
26645
26646  /* now insert a "." before the last / character */
26647  for( i=(len-1); i>=0; i-- ){
26648    if( conchPath[i]=='/' ){
26649      i++;
26650      break;
26651    }
26652  }
26653  conchPath[i]='.';
26654  while ( i<len ){
26655    conchPath[i+1]=dbPath[i];
26656    i++;
26657  }
26658
26659  /* append the "-conch" suffix to the file */
26660  memcpy(&conchPath[i+1], "-conch", 7);
26661  assert( (int)strlen(conchPath) == len+7 );
26662
26663  return SQLITE_OK;
26664}
26665
26666
26667/* Takes a fully configured proxy locking-style unix file and switches
26668** the local lock file path
26669*/
26670static int switchLockProxyPath(unixFile *pFile, const char *path) {
26671  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
26672  char *oldPath = pCtx->lockProxyPath;
26673  int rc = SQLITE_OK;
26674
26675  if( pFile->locktype!=NO_LOCK ){
26676    return SQLITE_BUSY;
26677  }
26678
26679  /* nothing to do if the path is NULL, :auto: or matches the existing path */
26680  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
26681    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
26682    return SQLITE_OK;
26683  }else{
26684    unixFile *lockProxy = pCtx->lockProxy;
26685    pCtx->lockProxy=NULL;
26686    pCtx->conchHeld = 0;
26687    if( lockProxy!=NULL ){
26688      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
26689      if( rc ) return rc;
26690      sqlite3_free(lockProxy);
26691    }
26692    sqlite3_free(oldPath);
26693    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
26694  }
26695
26696  return rc;
26697}
26698
26699/*
26700** pFile is a file that has been opened by a prior xOpen call.  dbPath
26701** is a string buffer at least MAXPATHLEN+1 characters in size.
26702**
26703** This routine find the filename associated with pFile and writes it
26704** int dbPath.
26705*/
26706static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
26707#if defined(__APPLE__)
26708  if( pFile->pMethod == &afpIoMethods ){
26709    /* afp style keeps a reference to the db path in the filePath field
26710    ** of the struct */
26711    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
26712    strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
26713  }else
26714#endif
26715  if( pFile->pMethod == &dotlockIoMethods ){
26716    /* dot lock style uses the locking context to store the dot lock
26717    ** file path */
26718    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
26719    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
26720  }else{
26721    /* all other styles use the locking context to store the db file path */
26722    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
26723    strcpy(dbPath, (char *)pFile->lockingContext);
26724  }
26725  return SQLITE_OK;
26726}
26727
26728/*
26729** Takes an already filled in unix file and alters it so all file locking
26730** will be performed on the local proxy lock file.  The following fields
26731** are preserved in the locking context so that they can be restored and
26732** the unix structure properly cleaned up at close time:
26733**  ->lockingContext
26734**  ->pMethod
26735*/
26736static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
26737  proxyLockingContext *pCtx;
26738  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
26739  char *lockPath=NULL;
26740  int rc = SQLITE_OK;
26741
26742  if( pFile->locktype!=NO_LOCK ){
26743    return SQLITE_BUSY;
26744  }
26745  proxyGetDbPathForUnixFile(pFile, dbPath);
26746  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
26747    lockPath=NULL;
26748  }else{
26749    lockPath=(char *)path;
26750  }
26751
26752  OSTRACE4("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
26753           (lockPath ? lockPath : ":auto:"), getpid());
26754
26755  pCtx = sqlite3_malloc( sizeof(*pCtx) );
26756  if( pCtx==0 ){
26757    return SQLITE_NOMEM;
26758  }
26759  memset(pCtx, 0, sizeof(*pCtx));
26760
26761  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
26762  if( rc==SQLITE_OK ){
26763    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
26764  }
26765  if( rc==SQLITE_OK && lockPath ){
26766    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
26767  }
26768
26769  if( rc==SQLITE_OK ){
26770    /* all memory is allocated, proxys are created and assigned,
26771    ** switch the locking context and pMethod then return.
26772    */
26773    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
26774    pCtx->oldLockingContext = pFile->lockingContext;
26775    pFile->lockingContext = pCtx;
26776    pCtx->pOldMethod = pFile->pMethod;
26777    pFile->pMethod = &proxyIoMethods;
26778  }else{
26779    if( pCtx->conchFile ){
26780      rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
26781      if( rc ) return rc;
26782      sqlite3_free(pCtx->conchFile);
26783    }
26784    sqlite3_free(pCtx->conchFilePath);
26785    sqlite3_free(pCtx);
26786  }
26787  OSTRACE3("TRANSPROXY  %d %s\n", pFile->h,
26788           (rc==SQLITE_OK ? "ok" : "failed"));
26789  return rc;
26790}
26791
26792
26793/*
26794** This routine handles sqlite3_file_control() calls that are specific
26795** to proxy locking.
26796*/
26797static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
26798  switch( op ){
26799    case SQLITE_GET_LOCKPROXYFILE: {
26800      unixFile *pFile = (unixFile*)id;
26801      if( pFile->pMethod == &proxyIoMethods ){
26802        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
26803        proxyTakeConch(pFile);
26804        if( pCtx->lockProxyPath ){
26805          *(const char **)pArg = pCtx->lockProxyPath;
26806        }else{
26807          *(const char **)pArg = ":auto: (not held)";
26808        }
26809      } else {
26810        *(const char **)pArg = NULL;
26811      }
26812      return SQLITE_OK;
26813    }
26814    case SQLITE_SET_LOCKPROXYFILE: {
26815      unixFile *pFile = (unixFile*)id;
26816      int rc = SQLITE_OK;
26817      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
26818      if( pArg==NULL || (const char *)pArg==0 ){
26819        if( isProxyStyle ){
26820          /* turn off proxy locking - not supported */
26821          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
26822        }else{
26823          /* turn off proxy locking - already off - NOOP */
26824          rc = SQLITE_OK;
26825        }
26826      }else{
26827        const char *proxyPath = (const char *)pArg;
26828        if( isProxyStyle ){
26829          proxyLockingContext *pCtx =
26830            (proxyLockingContext*)pFile->lockingContext;
26831          if( !strcmp(pArg, ":auto:")
26832           || (pCtx->lockProxyPath &&
26833               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
26834          ){
26835            rc = SQLITE_OK;
26836          }else{
26837            rc = switchLockProxyPath(pFile, proxyPath);
26838          }
26839        }else{
26840          /* turn on proxy file locking */
26841          rc = proxyTransformUnixFile(pFile, proxyPath);
26842        }
26843      }
26844      return rc;
26845    }
26846    default: {
26847      assert( 0 );  /* The call assures that only valid opcodes are sent */
26848    }
26849  }
26850  /*NOTREACHED*/
26851  return SQLITE_ERROR;
26852}
26853
26854/*
26855** Within this division (the proxying locking implementation) the procedures
26856** above this point are all utilities.  The lock-related methods of the
26857** proxy-locking sqlite3_io_method object follow.
26858*/
26859
26860
26861/*
26862** This routine checks if there is a RESERVED lock held on the specified
26863** file by this or any other process. If such a lock is held, set *pResOut
26864** to a non-zero value otherwise *pResOut is set to zero.  The return value
26865** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26866*/
26867static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
26868  unixFile *pFile = (unixFile*)id;
26869  int rc = proxyTakeConch(pFile);
26870  if( rc==SQLITE_OK ){
26871    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26872    unixFile *proxy = pCtx->lockProxy;
26873    return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
26874  }
26875  return rc;
26876}
26877
26878/*
26879** Lock the file with the lock specified by parameter locktype - one
26880** of the following:
26881**
26882**     (1) SHARED_LOCK
26883**     (2) RESERVED_LOCK
26884**     (3) PENDING_LOCK
26885**     (4) EXCLUSIVE_LOCK
26886**
26887** Sometimes when requesting one lock state, additional lock states
26888** are inserted in between.  The locking might fail on one of the later
26889** transitions leaving the lock state different from what it started but
26890** still short of its goal.  The following chart shows the allowed
26891** transitions and the inserted intermediate states:
26892**
26893**    UNLOCKED -> SHARED
26894**    SHARED -> RESERVED
26895**    SHARED -> (PENDING) -> EXCLUSIVE
26896**    RESERVED -> (PENDING) -> EXCLUSIVE
26897**    PENDING -> EXCLUSIVE
26898**
26899** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26900** routine to lower a locking level.
26901*/
26902static int proxyLock(sqlite3_file *id, int locktype) {
26903  unixFile *pFile = (unixFile*)id;
26904  int rc = proxyTakeConch(pFile);
26905  if( rc==SQLITE_OK ){
26906    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26907    unixFile *proxy = pCtx->lockProxy;
26908    rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
26909    pFile->locktype = proxy->locktype;
26910  }
26911  return rc;
26912}
26913
26914
26915/*
26916** Lower the locking level on file descriptor pFile to locktype.  locktype
26917** must be either NO_LOCK or SHARED_LOCK.
26918**
26919** If the locking level of the file descriptor is already at or below
26920** the requested locking level, this routine is a no-op.
26921*/
26922static int proxyUnlock(sqlite3_file *id, int locktype) {
26923  unixFile *pFile = (unixFile*)id;
26924  int rc = proxyTakeConch(pFile);
26925  if( rc==SQLITE_OK ){
26926    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26927    unixFile *proxy = pCtx->lockProxy;
26928    rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
26929    pFile->locktype = proxy->locktype;
26930  }
26931  return rc;
26932}
26933
26934/*
26935** Close a file that uses proxy locks.
26936*/
26937static int proxyClose(sqlite3_file *id) {
26938  if( id ){
26939    unixFile *pFile = (unixFile*)id;
26940    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26941    unixFile *lockProxy = pCtx->lockProxy;
26942    unixFile *conchFile = pCtx->conchFile;
26943    int rc = SQLITE_OK;
26944
26945    if( lockProxy ){
26946      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
26947      if( rc ) return rc;
26948      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
26949      if( rc ) return rc;
26950      sqlite3_free(lockProxy);
26951      pCtx->lockProxy = 0;
26952    }
26953    if( conchFile ){
26954      if( pCtx->conchHeld ){
26955        rc = proxyReleaseConch(pFile);
26956        if( rc ) return rc;
26957      }
26958      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
26959      if( rc ) return rc;
26960      sqlite3_free(conchFile);
26961    }
26962    sqlite3_free(pCtx->lockProxyPath);
26963    sqlite3_free(pCtx->conchFilePath);
26964    sqlite3_free(pCtx->dbPath);
26965    /* restore the original locking context and pMethod then close it */
26966    pFile->lockingContext = pCtx->oldLockingContext;
26967    pFile->pMethod = pCtx->pOldMethod;
26968    sqlite3_free(pCtx);
26969    return pFile->pMethod->xClose(id);
26970  }
26971  return SQLITE_OK;
26972}
26973
26974
26975
26976#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26977/*
26978** The proxy locking style is intended for use with AFP filesystems.
26979** And since AFP is only supported on MacOSX, the proxy locking is also
26980** restricted to MacOSX.
26981**
26982**
26983******************* End of the proxy lock implementation **********************
26984******************************************************************************/
26985
26986/*
26987** Initialize the operating system interface.
26988**
26989** This routine registers all VFS implementations for unix-like operating
26990** systems.  This routine, and the sqlite3_os_end() routine that follows,
26991** should be the only routines in this file that are visible from other
26992** files.
26993**
26994** This routine is called once during SQLite initialization and by a
26995** single thread.  The memory allocation and mutex subsystems have not
26996** necessarily been initialized when this routine is called, and so they
26997** should not be used.
26998*/
26999SQLITE_API int sqlite3_os_init(void){
27000  /*
27001  ** The following macro defines an initializer for an sqlite3_vfs object.
27002  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
27003  ** to the "finder" function.  (pAppData is a pointer to a pointer because
27004  ** silly C90 rules prohibit a void* from being cast to a function pointer
27005  ** and so we have to go through the intermediate pointer to avoid problems
27006  ** when compiling with -pedantic-errors on GCC.)
27007  **
27008  ** The FINDER parameter to this macro is the name of the pointer to the
27009  ** finder-function.  The finder-function returns a pointer to the
27010  ** sqlite_io_methods object that implements the desired locking
27011  ** behaviors.  See the division above that contains the IOMETHODS
27012  ** macro for addition information on finder-functions.
27013  **
27014  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
27015  ** object.  But the "autolockIoFinder" available on MacOSX does a little
27016  ** more than that; it looks at the filesystem type that hosts the
27017  ** database file and tries to choose an locking method appropriate for
27018  ** that filesystem time.
27019  */
27020  #define UNIXVFS(VFSNAME, FINDER) {                        \
27021    1,                    /* iVersion */                    \
27022    sizeof(unixFile),     /* szOsFile */                    \
27023    MAX_PATHNAME,         /* mxPathname */                  \
27024    0,                    /* pNext */                       \
27025    VFSNAME,              /* zName */                       \
27026    (void*)&FINDER,       /* pAppData */                    \
27027    unixOpen,             /* xOpen */                       \
27028    unixDelete,           /* xDelete */                     \
27029    unixAccess,           /* xAccess */                     \
27030    unixFullPathname,     /* xFullPathname */               \
27031    unixDlOpen,           /* xDlOpen */                     \
27032    unixDlError,          /* xDlError */                    \
27033    unixDlSym,            /* xDlSym */                      \
27034    unixDlClose,          /* xDlClose */                    \
27035    unixRandomness,       /* xRandomness */                 \
27036    unixSleep,            /* xSleep */                      \
27037    unixCurrentTime,      /* xCurrentTime */                \
27038    unixGetLastError      /* xGetLastError */               \
27039  }
27040
27041  /*
27042  ** All default VFSes for unix are contained in the following array.
27043  **
27044  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
27045  ** by the SQLite core when the VFS is registered.  So the following
27046  ** array cannot be const.
27047  */
27048  static sqlite3_vfs aVfs[] = {
27049#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
27050    UNIXVFS("unix",          autolockIoFinder ),
27051#else
27052    UNIXVFS("unix",          posixIoFinder ),
27053#endif
27054    UNIXVFS("unix-none",     nolockIoFinder ),
27055    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
27056    UNIXVFS("unix-wfl",      posixWflIoFinder ),
27057#if OS_VXWORKS
27058    UNIXVFS("unix-namedsem", semIoFinder ),
27059#endif
27060#if SQLITE_ENABLE_LOCKING_STYLE
27061    UNIXVFS("unix-posix",    posixIoFinder ),
27062#if !OS_VXWORKS
27063    UNIXVFS("unix-flock",    flockIoFinder ),
27064#endif
27065#endif
27066#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27067    UNIXVFS("unix-afp",      afpIoFinder ),
27068    UNIXVFS("unix-proxy",    proxyIoFinder ),
27069#endif
27070  };
27071  unsigned int i;          /* Loop counter */
27072
27073  /* Register all VFSes defined in the aVfs[] array */
27074  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
27075    sqlite3_vfs_register(&aVfs[i], i==0);
27076  }
27077  return SQLITE_OK;
27078}
27079
27080/*
27081** Shutdown the operating system interface.
27082**
27083** Some operating systems might need to do some cleanup in this routine,
27084** to release dynamically allocated objects.  But not on unix.
27085** This routine is a no-op for unix.
27086*/
27087SQLITE_API int sqlite3_os_end(void){
27088  return SQLITE_OK;
27089}
27090
27091#endif /* SQLITE_OS_UNIX */
27092
27093/************** End of os_unix.c *********************************************/
27094/************** Begin file os_win.c ******************************************/
27095/*
27096** 2004 May 22
27097**
27098** The author disclaims copyright to this source code.  In place of
27099** a legal notice, here is a blessing:
27100**
27101**    May you do good and not evil.
27102**    May you find forgiveness for yourself and forgive others.
27103**    May you share freely, never taking more than you give.
27104**
27105******************************************************************************
27106**
27107** This file contains code that is specific to windows.
27108*/
27109#if SQLITE_OS_WIN               /* This file is used for windows only */
27110
27111
27112/*
27113** A Note About Memory Allocation:
27114**
27115** This driver uses malloc()/free() directly rather than going through
27116** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
27117** are designed for use on embedded systems where memory is scarce and
27118** malloc failures happen frequently.  Win32 does not typically run on
27119** embedded systems, and when it does the developers normally have bigger
27120** problems to worry about than running out of memory.  So there is not
27121** a compelling need to use the wrappers.
27122**
27123** But there is a good reason to not use the wrappers.  If we use the
27124** wrappers then we will get simulated malloc() failures within this
27125** driver.  And that causes all kinds of problems for our tests.  We
27126** could enhance SQLite to deal with simulated malloc failures within
27127** the OS driver, but the code to deal with those failure would not
27128** be exercised on Linux (which does not need to malloc() in the driver)
27129** and so we would have difficulty writing coverage tests for that
27130** code.  Better to leave the code out, we think.
27131**
27132** The point of this discussion is as follows:  When creating a new
27133** OS layer for an embedded system, if you use this file as an example,
27134** avoid the use of malloc()/free().  Those routines work ok on windows
27135** desktops but not so well in embedded systems.
27136*/
27137
27138#include <winbase.h>
27139
27140#ifdef __CYGWIN__
27141# include <sys/cygwin.h>
27142#endif
27143
27144/*
27145** Macros used to determine whether or not to use threads.
27146*/
27147#if defined(THREADSAFE) && THREADSAFE
27148# define SQLITE_W32_THREADS 1
27149#endif
27150
27151/*
27152** Include code that is common to all os_*.c files
27153*/
27154/************** Include os_common.h in the middle of os_win.c ****************/
27155/************** Begin file os_common.h ***************************************/
27156/*
27157** 2004 May 22
27158**
27159** The author disclaims copyright to this source code.  In place of
27160** a legal notice, here is a blessing:
27161**
27162**    May you do good and not evil.
27163**    May you find forgiveness for yourself and forgive others.
27164**    May you share freely, never taking more than you give.
27165**
27166******************************************************************************
27167**
27168** This file contains macros and a little bit of code that is common to
27169** all of the platform-specific files (os_*.c) and is #included into those
27170** files.
27171**
27172** This file should be #included by the os_*.c files only.  It is not a
27173** general purpose header file.
27174*/
27175#ifndef _OS_COMMON_H_
27176#define _OS_COMMON_H_
27177
27178/*
27179** At least two bugs have slipped in because we changed the MEMORY_DEBUG
27180** macro to SQLITE_DEBUG and some older makefiles have not yet made the
27181** switch.  The following code should catch this problem at compile-time.
27182*/
27183#ifdef MEMORY_DEBUG
27184# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
27185#endif
27186
27187#ifdef SQLITE_DEBUG
27188SQLITE_PRIVATE int sqlite3OSTrace = 0;
27189#define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
27190#define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
27191#define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
27192#define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
27193#define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
27194#define OSTRACE6(X,Y,Z,A,B,C) \
27195    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
27196#define OSTRACE7(X,Y,Z,A,B,C,D) \
27197    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
27198#else
27199#define OSTRACE1(X)
27200#define OSTRACE2(X,Y)
27201#define OSTRACE3(X,Y,Z)
27202#define OSTRACE4(X,Y,Z,A)
27203#define OSTRACE5(X,Y,Z,A,B)
27204#define OSTRACE6(X,Y,Z,A,B,C)
27205#define OSTRACE7(X,Y,Z,A,B,C,D)
27206#endif
27207
27208/*
27209** Macros for performance tracing.  Normally turned off.  Only works
27210** on i486 hardware.
27211*/
27212#ifdef SQLITE_PERFORMANCE_TRACE
27213
27214/*
27215** hwtime.h contains inline assembler code for implementing
27216** high-performance timing routines.
27217*/
27218/************** Include hwtime.h in the middle of os_common.h ****************/
27219/************** Begin file hwtime.h ******************************************/
27220/*
27221** 2008 May 27
27222**
27223** The author disclaims copyright to this source code.  In place of
27224** a legal notice, here is a blessing:
27225**
27226**    May you do good and not evil.
27227**    May you find forgiveness for yourself and forgive others.
27228**    May you share freely, never taking more than you give.
27229**
27230******************************************************************************
27231**
27232** This file contains inline asm code for retrieving "high-performance"
27233** counters for x86 class CPUs.
27234*/
27235#ifndef _HWTIME_H_
27236#define _HWTIME_H_
27237
27238/*
27239** The following routine only works on pentium-class (or newer) processors.
27240** It uses the RDTSC opcode to read the cycle count value out of the
27241** processor and returns that value.  This can be used for high-res
27242** profiling.
27243*/
27244#if (defined(__GNUC__) || defined(_MSC_VER)) && \
27245      (defined(i386) || defined(__i386__) || defined(_M_IX86))
27246
27247  #if defined(__GNUC__)
27248
27249  __inline__ sqlite_uint64 sqlite3Hwtime(void){
27250     unsigned int lo, hi;
27251     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
27252     return (sqlite_uint64)hi << 32 | lo;
27253  }
27254
27255  #elif defined(_MSC_VER)
27256
27257  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
27258     __asm {
27259        rdtsc
27260        ret       ; return value at EDX:EAX
27261     }
27262  }
27263
27264  #endif
27265
27266#elif (defined(__GNUC__) && defined(__x86_64__))
27267
27268  __inline__ sqlite_uint64 sqlite3Hwtime(void){
27269      unsigned long val;
27270      __asm__ __volatile__ ("rdtsc" : "=A" (val));
27271      return val;
27272  }
27273
27274#elif (defined(__GNUC__) && defined(__ppc__))
27275
27276  __inline__ sqlite_uint64 sqlite3Hwtime(void){
27277      unsigned long long retval;
27278      unsigned long junk;
27279      __asm__ __volatile__ ("\n\
27280          1:      mftbu   %1\n\
27281                  mftb    %L0\n\
27282                  mftbu   %0\n\
27283                  cmpw    %0,%1\n\
27284                  bne     1b"
27285                  : "=r" (retval), "=r" (junk));
27286      return retval;
27287  }
27288
27289#else
27290
27291  #error Need implementation of sqlite3Hwtime() for your platform.
27292
27293  /*
27294  ** To compile without implementing sqlite3Hwtime() for your platform,
27295  ** you can remove the above #error and use the following
27296  ** stub function.  You will lose timing support for many
27297  ** of the debugging and testing utilities, but it should at
27298  ** least compile and run.
27299  */
27300SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
27301
27302#endif
27303
27304#endif /* !defined(_HWTIME_H_) */
27305
27306/************** End of hwtime.h **********************************************/
27307/************** Continuing where we left off in os_common.h ******************/
27308
27309static sqlite_uint64 g_start;
27310static sqlite_uint64 g_elapsed;
27311#define TIMER_START       g_start=sqlite3Hwtime()
27312#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
27313#define TIMER_ELAPSED     g_elapsed
27314#else
27315#define TIMER_START
27316#define TIMER_END
27317#define TIMER_ELAPSED     ((sqlite_uint64)0)
27318#endif
27319
27320/*
27321** If we compile with the SQLITE_TEST macro set, then the following block
27322** of code will give us the ability to simulate a disk I/O error.  This
27323** is used for testing the I/O recovery logic.
27324*/
27325#ifdef SQLITE_TEST
27326SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
27327SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
27328SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
27329SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
27330SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
27331SQLITE_API int sqlite3_diskfull_pending = 0;
27332SQLITE_API int sqlite3_diskfull = 0;
27333#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
27334#define SimulateIOError(CODE)  \
27335  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
27336       || sqlite3_io_error_pending-- == 1 )  \
27337              { local_ioerr(); CODE; }
27338static void local_ioerr(){
27339  IOTRACE(("IOERR\n"));
27340  sqlite3_io_error_hit++;
27341  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
27342}
27343#define SimulateDiskfullError(CODE) \
27344   if( sqlite3_diskfull_pending ){ \
27345     if( sqlite3_diskfull_pending == 1 ){ \
27346       local_ioerr(); \
27347       sqlite3_diskfull = 1; \
27348       sqlite3_io_error_hit = 1; \
27349       CODE; \
27350     }else{ \
27351       sqlite3_diskfull_pending--; \
27352     } \
27353   }
27354#else
27355#define SimulateIOErrorBenign(X)
27356#define SimulateIOError(A)
27357#define SimulateDiskfullError(A)
27358#endif
27359
27360/*
27361** When testing, keep a count of the number of open files.
27362*/
27363#ifdef SQLITE_TEST
27364SQLITE_API int sqlite3_open_file_count = 0;
27365#define OpenCounter(X)  sqlite3_open_file_count+=(X)
27366#else
27367#define OpenCounter(X)
27368#endif
27369
27370#endif /* !defined(_OS_COMMON_H_) */
27371
27372/************** End of os_common.h *******************************************/
27373/************** Continuing where we left off in os_win.c *********************/
27374
27375/*
27376** Some microsoft compilers lack this definition.
27377*/
27378#ifndef INVALID_FILE_ATTRIBUTES
27379# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
27380#endif
27381
27382/*
27383** Determine if we are dealing with WindowsCE - which has a much
27384** reduced API.
27385*/
27386#if SQLITE_OS_WINCE
27387# define AreFileApisANSI() 1
27388# define FormatMessageW(a,b,c,d,e,f,g) 0
27389#endif
27390
27391/*
27392** WinCE lacks native support for file locking so we have to fake it
27393** with some code of our own.
27394*/
27395#if SQLITE_OS_WINCE
27396typedef struct winceLock {
27397  int nReaders;       /* Number of reader locks obtained */
27398  BOOL bPending;      /* Indicates a pending lock has been obtained */
27399  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
27400  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
27401} winceLock;
27402#endif
27403
27404/*
27405** The winFile structure is a subclass of sqlite3_file* specific to the win32
27406** portability layer.
27407*/
27408typedef struct winFile winFile;
27409struct winFile {
27410  const sqlite3_io_methods *pMethod;/* Must be first */
27411  HANDLE h;               /* Handle for accessing the file */
27412  unsigned char locktype; /* Type of lock currently held on this file */
27413  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
27414  DWORD lastErrno;        /* The Windows errno from the last I/O error */
27415  DWORD sectorSize;       /* Sector size of the device file is on */
27416#if SQLITE_OS_WINCE
27417  WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
27418  HANDLE hMutex;          /* Mutex used to control access to shared lock */
27419  HANDLE hShared;         /* Shared memory segment used for locking */
27420  winceLock local;        /* Locks obtained by this instance of winFile */
27421  winceLock *shared;      /* Global shared lock memory for the file  */
27422#endif
27423};
27424
27425/*
27426** Forward prototypes.
27427*/
27428static int getSectorSize(
27429    sqlite3_vfs *pVfs,
27430    const char *zRelative     /* UTF-8 file name */
27431);
27432
27433/*
27434** The following variable is (normally) set once and never changes
27435** thereafter.  It records whether the operating system is Win95
27436** or WinNT.
27437**
27438** 0:   Operating system unknown.
27439** 1:   Operating system is Win95.
27440** 2:   Operating system is WinNT.
27441**
27442** In order to facilitate testing on a WinNT system, the test fixture
27443** can manually set this value to 1 to emulate Win98 behavior.
27444*/
27445#ifdef SQLITE_TEST
27446SQLITE_API int sqlite3_os_type = 0;
27447#else
27448static int sqlite3_os_type = 0;
27449#endif
27450
27451/*
27452** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
27453** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
27454**
27455** Here is an interesting observation:  Win95, Win98, and WinME lack
27456** the LockFileEx() API.  But we can still statically link against that
27457** API as long as we don't call it when running Win95/98/ME.  A call to
27458** this routine is used to determine if the host is Win95/98/ME or
27459** WinNT/2K/XP so that we will know whether or not we can safely call
27460** the LockFileEx() API.
27461*/
27462#if SQLITE_OS_WINCE
27463# define isNT()  (1)
27464#else
27465  static int isNT(void){
27466    if( sqlite3_os_type==0 ){
27467      OSVERSIONINFO sInfo;
27468      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
27469      GetVersionEx(&sInfo);
27470      sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
27471    }
27472    return sqlite3_os_type==2;
27473  }
27474#endif /* SQLITE_OS_WINCE */
27475
27476/*
27477** Convert a UTF-8 string to microsoft unicode (UTF-16?).
27478**
27479** Space to hold the returned string is obtained from malloc.
27480*/
27481static WCHAR *utf8ToUnicode(const char *zFilename){
27482  int nChar;
27483  WCHAR *zWideFilename;
27484
27485  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
27486  zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
27487  if( zWideFilename==0 ){
27488    return 0;
27489  }
27490  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
27491  if( nChar==0 ){
27492    free(zWideFilename);
27493    zWideFilename = 0;
27494  }
27495  return zWideFilename;
27496}
27497
27498/*
27499** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
27500** obtained from malloc().
27501*/
27502static char *unicodeToUtf8(const WCHAR *zWideFilename){
27503  int nByte;
27504  char *zFilename;
27505
27506  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
27507  zFilename = malloc( nByte );
27508  if( zFilename==0 ){
27509    return 0;
27510  }
27511  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
27512                              0, 0);
27513  if( nByte == 0 ){
27514    free(zFilename);
27515    zFilename = 0;
27516  }
27517  return zFilename;
27518}
27519
27520/*
27521** Convert an ansi string to microsoft unicode, based on the
27522** current codepage settings for file apis.
27523**
27524** Space to hold the returned string is obtained
27525** from malloc.
27526*/
27527static WCHAR *mbcsToUnicode(const char *zFilename){
27528  int nByte;
27529  WCHAR *zMbcsFilename;
27530  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
27531
27532  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
27533  zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
27534  if( zMbcsFilename==0 ){
27535    return 0;
27536  }
27537  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
27538  if( nByte==0 ){
27539    free(zMbcsFilename);
27540    zMbcsFilename = 0;
27541  }
27542  return zMbcsFilename;
27543}
27544
27545/*
27546** Convert microsoft unicode to multibyte character string, based on the
27547** user's Ansi codepage.
27548**
27549** Space to hold the returned string is obtained from
27550** malloc().
27551*/
27552static char *unicodeToMbcs(const WCHAR *zWideFilename){
27553  int nByte;
27554  char *zFilename;
27555  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
27556
27557  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
27558  zFilename = malloc( nByte );
27559  if( zFilename==0 ){
27560    return 0;
27561  }
27562  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
27563                              0, 0);
27564  if( nByte == 0 ){
27565    free(zFilename);
27566    zFilename = 0;
27567  }
27568  return zFilename;
27569}
27570
27571/*
27572** Convert multibyte character string to UTF-8.  Space to hold the
27573** returned string is obtained from malloc().
27574*/
27575SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
27576  char *zFilenameUtf8;
27577  WCHAR *zTmpWide;
27578
27579  zTmpWide = mbcsToUnicode(zFilename);
27580  if( zTmpWide==0 ){
27581    return 0;
27582  }
27583  zFilenameUtf8 = unicodeToUtf8(zTmpWide);
27584  free(zTmpWide);
27585  return zFilenameUtf8;
27586}
27587
27588/*
27589** Convert UTF-8 to multibyte character string.  Space to hold the
27590** returned string is obtained from malloc().
27591*/
27592static char *utf8ToMbcs(const char *zFilename){
27593  char *zFilenameMbcs;
27594  WCHAR *zTmpWide;
27595
27596  zTmpWide = utf8ToUnicode(zFilename);
27597  if( zTmpWide==0 ){
27598    return 0;
27599  }
27600  zFilenameMbcs = unicodeToMbcs(zTmpWide);
27601  free(zTmpWide);
27602  return zFilenameMbcs;
27603}
27604
27605#if SQLITE_OS_WINCE
27606/*************************************************************************
27607** This section contains code for WinCE only.
27608*/
27609/*
27610** WindowsCE does not have a localtime() function.  So create a
27611** substitute.
27612*/
27613struct tm *__cdecl localtime(const time_t *t)
27614{
27615  static struct tm y;
27616  FILETIME uTm, lTm;
27617  SYSTEMTIME pTm;
27618  sqlite3_int64 t64;
27619  t64 = *t;
27620  t64 = (t64 + 11644473600)*10000000;
27621  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
27622  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
27623  FileTimeToLocalFileTime(&uTm,&lTm);
27624  FileTimeToSystemTime(&lTm,&pTm);
27625  y.tm_year = pTm.wYear - 1900;
27626  y.tm_mon = pTm.wMonth - 1;
27627  y.tm_wday = pTm.wDayOfWeek;
27628  y.tm_mday = pTm.wDay;
27629  y.tm_hour = pTm.wHour;
27630  y.tm_min = pTm.wMinute;
27631  y.tm_sec = pTm.wSecond;
27632  return &y;
27633}
27634
27635/* This will never be called, but defined to make the code compile */
27636#define GetTempPathA(a,b)
27637
27638#define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
27639#define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
27640#define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
27641
27642#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
27643
27644/*
27645** Acquire a lock on the handle h
27646*/
27647static void winceMutexAcquire(HANDLE h){
27648   DWORD dwErr;
27649   do {
27650     dwErr = WaitForSingleObject(h, INFINITE);
27651   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
27652}
27653/*
27654** Release a lock acquired by winceMutexAcquire()
27655*/
27656#define winceMutexRelease(h) ReleaseMutex(h)
27657
27658/*
27659** Create the mutex and shared memory used for locking in the file
27660** descriptor pFile
27661*/
27662static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
27663  WCHAR *zTok;
27664  WCHAR *zName = utf8ToUnicode(zFilename);
27665  BOOL bInit = TRUE;
27666
27667  /* Initialize the local lockdata */
27668  ZeroMemory(&pFile->local, sizeof(pFile->local));
27669
27670  /* Replace the backslashes from the filename and lowercase it
27671  ** to derive a mutex name. */
27672  zTok = CharLowerW(zName);
27673  for (;*zTok;zTok++){
27674    if (*zTok == '\\') *zTok = '_';
27675  }
27676
27677  /* Create/open the named mutex */
27678  pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
27679  if (!pFile->hMutex){
27680    pFile->lastErrno = GetLastError();
27681    free(zName);
27682    return FALSE;
27683  }
27684
27685  /* Acquire the mutex before continuing */
27686  winceMutexAcquire(pFile->hMutex);
27687
27688  /* Since the names of named mutexes, semaphores, file mappings etc are
27689  ** case-sensitive, take advantage of that by uppercasing the mutex name
27690  ** and using that as the shared filemapping name.
27691  */
27692  CharUpperW(zName);
27693  pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
27694                                       PAGE_READWRITE, 0, sizeof(winceLock),
27695                                       zName);
27696
27697  /* Set a flag that indicates we're the first to create the memory so it
27698  ** must be zero-initialized */
27699  if (GetLastError() == ERROR_ALREADY_EXISTS){
27700    bInit = FALSE;
27701  }
27702
27703  free(zName);
27704
27705  /* If we succeeded in making the shared memory handle, map it. */
27706  if (pFile->hShared){
27707    pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
27708             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
27709    /* If mapping failed, close the shared memory handle and erase it */
27710    if (!pFile->shared){
27711      pFile->lastErrno = GetLastError();
27712      CloseHandle(pFile->hShared);
27713      pFile->hShared = NULL;
27714    }
27715  }
27716
27717  /* If shared memory could not be created, then close the mutex and fail */
27718  if (pFile->hShared == NULL){
27719    winceMutexRelease(pFile->hMutex);
27720    CloseHandle(pFile->hMutex);
27721    pFile->hMutex = NULL;
27722    return FALSE;
27723  }
27724
27725  /* Initialize the shared memory if we're supposed to */
27726  if (bInit) {
27727    ZeroMemory(pFile->shared, sizeof(winceLock));
27728  }
27729
27730  winceMutexRelease(pFile->hMutex);
27731  return TRUE;
27732}
27733
27734/*
27735** Destroy the part of winFile that deals with wince locks
27736*/
27737static void winceDestroyLock(winFile *pFile){
27738  if (pFile->hMutex){
27739    /* Acquire the mutex */
27740    winceMutexAcquire(pFile->hMutex);
27741
27742    /* The following blocks should probably assert in debug mode, but they
27743       are to cleanup in case any locks remained open */
27744    if (pFile->local.nReaders){
27745      pFile->shared->nReaders --;
27746    }
27747    if (pFile->local.bReserved){
27748      pFile->shared->bReserved = FALSE;
27749    }
27750    if (pFile->local.bPending){
27751      pFile->shared->bPending = FALSE;
27752    }
27753    if (pFile->local.bExclusive){
27754      pFile->shared->bExclusive = FALSE;
27755    }
27756
27757    /* De-reference and close our copy of the shared memory handle */
27758    UnmapViewOfFile(pFile->shared);
27759    CloseHandle(pFile->hShared);
27760
27761    /* Done with the mutex */
27762    winceMutexRelease(pFile->hMutex);
27763    CloseHandle(pFile->hMutex);
27764    pFile->hMutex = NULL;
27765  }
27766}
27767
27768/*
27769** An implementation of the LockFile() API of windows for wince
27770*/
27771static BOOL winceLockFile(
27772  HANDLE *phFile,
27773  DWORD dwFileOffsetLow,
27774  DWORD dwFileOffsetHigh,
27775  DWORD nNumberOfBytesToLockLow,
27776  DWORD nNumberOfBytesToLockHigh
27777){
27778  winFile *pFile = HANDLE_TO_WINFILE(phFile);
27779  BOOL bReturn = FALSE;
27780
27781  UNUSED_PARAMETER(dwFileOffsetHigh);
27782  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
27783
27784  if (!pFile->hMutex) return TRUE;
27785  winceMutexAcquire(pFile->hMutex);
27786
27787  /* Wanting an exclusive lock? */
27788  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
27789       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
27790    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
27791       pFile->shared->bExclusive = TRUE;
27792       pFile->local.bExclusive = TRUE;
27793       bReturn = TRUE;
27794    }
27795  }
27796
27797  /* Want a read-only lock? */
27798  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
27799           nNumberOfBytesToLockLow == 1){
27800    if (pFile->shared->bExclusive == 0){
27801      pFile->local.nReaders ++;
27802      if (pFile->local.nReaders == 1){
27803        pFile->shared->nReaders ++;
27804      }
27805      bReturn = TRUE;
27806    }
27807  }
27808
27809  /* Want a pending lock? */
27810  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
27811    /* If no pending lock has been acquired, then acquire it */
27812    if (pFile->shared->bPending == 0) {
27813      pFile->shared->bPending = TRUE;
27814      pFile->local.bPending = TRUE;
27815      bReturn = TRUE;
27816    }
27817  }
27818
27819  /* Want a reserved lock? */
27820  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
27821    if (pFile->shared->bReserved == 0) {
27822      pFile->shared->bReserved = TRUE;
27823      pFile->local.bReserved = TRUE;
27824      bReturn = TRUE;
27825    }
27826  }
27827
27828  winceMutexRelease(pFile->hMutex);
27829  return bReturn;
27830}
27831
27832/*
27833** An implementation of the UnlockFile API of windows for wince
27834*/
27835static BOOL winceUnlockFile(
27836  HANDLE *phFile,
27837  DWORD dwFileOffsetLow,
27838  DWORD dwFileOffsetHigh,
27839  DWORD nNumberOfBytesToUnlockLow,
27840  DWORD nNumberOfBytesToUnlockHigh
27841){
27842  winFile *pFile = HANDLE_TO_WINFILE(phFile);
27843  BOOL bReturn = FALSE;
27844
27845  UNUSED_PARAMETER(dwFileOffsetHigh);
27846  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
27847
27848  if (!pFile->hMutex) return TRUE;
27849  winceMutexAcquire(pFile->hMutex);
27850
27851  /* Releasing a reader lock or an exclusive lock */
27852  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
27853    /* Did we have an exclusive lock? */
27854    if (pFile->local.bExclusive){
27855      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
27856      pFile->local.bExclusive = FALSE;
27857      pFile->shared->bExclusive = FALSE;
27858      bReturn = TRUE;
27859    }
27860
27861    /* Did we just have a reader lock? */
27862    else if (pFile->local.nReaders){
27863      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
27864      pFile->local.nReaders --;
27865      if (pFile->local.nReaders == 0)
27866      {
27867        pFile->shared->nReaders --;
27868      }
27869      bReturn = TRUE;
27870    }
27871  }
27872
27873  /* Releasing a pending lock */
27874  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
27875    if (pFile->local.bPending){
27876      pFile->local.bPending = FALSE;
27877      pFile->shared->bPending = FALSE;
27878      bReturn = TRUE;
27879    }
27880  }
27881  /* Releasing a reserved lock */
27882  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
27883    if (pFile->local.bReserved) {
27884      pFile->local.bReserved = FALSE;
27885      pFile->shared->bReserved = FALSE;
27886      bReturn = TRUE;
27887    }
27888  }
27889
27890  winceMutexRelease(pFile->hMutex);
27891  return bReturn;
27892}
27893
27894/*
27895** An implementation of the LockFileEx() API of windows for wince
27896*/
27897static BOOL winceLockFileEx(
27898  HANDLE *phFile,
27899  DWORD dwFlags,
27900  DWORD dwReserved,
27901  DWORD nNumberOfBytesToLockLow,
27902  DWORD nNumberOfBytesToLockHigh,
27903  LPOVERLAPPED lpOverlapped
27904){
27905  UNUSED_PARAMETER(dwReserved);
27906  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
27907
27908  /* If the caller wants a shared read lock, forward this call
27909  ** to winceLockFile */
27910  if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
27911      dwFlags == 1 &&
27912      nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
27913    return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
27914  }
27915  return FALSE;
27916}
27917/*
27918** End of the special code for wince
27919*****************************************************************************/
27920#endif /* SQLITE_OS_WINCE */
27921
27922/*****************************************************************************
27923** The next group of routines implement the I/O methods specified
27924** by the sqlite3_io_methods object.
27925******************************************************************************/
27926
27927/*
27928** Close a file.
27929**
27930** It is reported that an attempt to close a handle might sometimes
27931** fail.  This is a very unreasonable result, but windows is notorious
27932** for being unreasonable so I do not doubt that it might happen.  If
27933** the close fails, we pause for 100 milliseconds and try again.  As
27934** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
27935** giving up and returning an error.
27936*/
27937#define MX_CLOSE_ATTEMPT 3
27938static int winClose(sqlite3_file *id){
27939  int rc, cnt = 0;
27940  winFile *pFile = (winFile*)id;
27941
27942  assert( id!=0 );
27943  OSTRACE2("CLOSE %d\n", pFile->h);
27944  do{
27945    rc = CloseHandle(pFile->h);
27946  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
27947#if SQLITE_OS_WINCE
27948#define WINCE_DELETION_ATTEMPTS 3
27949  winceDestroyLock(pFile);
27950  if( pFile->zDeleteOnClose ){
27951    int cnt = 0;
27952    while(
27953           DeleteFileW(pFile->zDeleteOnClose)==0
27954        && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
27955        && cnt++ < WINCE_DELETION_ATTEMPTS
27956    ){
27957       Sleep(100);  /* Wait a little before trying again */
27958    }
27959    free(pFile->zDeleteOnClose);
27960  }
27961#endif
27962  OpenCounter(-1);
27963  return rc ? SQLITE_OK : SQLITE_IOERR;
27964}
27965
27966/*
27967** Some microsoft compilers lack this definition.
27968*/
27969#ifndef INVALID_SET_FILE_POINTER
27970# define INVALID_SET_FILE_POINTER ((DWORD)-1)
27971#endif
27972
27973/*
27974** Read data from a file into a buffer.  Return SQLITE_OK if all
27975** bytes were read successfully and SQLITE_IOERR if anything goes
27976** wrong.
27977*/
27978static int winRead(
27979  sqlite3_file *id,          /* File to read from */
27980  void *pBuf,                /* Write content into this buffer */
27981  int amt,                   /* Number of bytes to read */
27982  sqlite3_int64 offset       /* Begin reading at this offset */
27983){
27984  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
27985  LONG lowerBits = (LONG)(offset & 0xffffffff);
27986  DWORD rc;
27987  winFile *pFile = (winFile*)id;
27988  DWORD error;
27989  DWORD got;
27990
27991  assert( id!=0 );
27992  SimulateIOError(return SQLITE_IOERR_READ);
27993  OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
27994  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
27995  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
27996    pFile->lastErrno = error;
27997    return SQLITE_FULL;
27998  }
27999  if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
28000    pFile->lastErrno = GetLastError();
28001    return SQLITE_IOERR_READ;
28002  }
28003  if( got==(DWORD)amt ){
28004    return SQLITE_OK;
28005  }else{
28006    /* Unread parts of the buffer must be zero-filled */
28007    memset(&((char*)pBuf)[got], 0, amt-got);
28008    return SQLITE_IOERR_SHORT_READ;
28009  }
28010}
28011
28012/*
28013** Write data from a buffer into a file.  Return SQLITE_OK on success
28014** or some other error code on failure.
28015*/
28016static int winWrite(
28017  sqlite3_file *id,         /* File to write into */
28018  const void *pBuf,         /* The bytes to be written */
28019  int amt,                  /* Number of bytes to write */
28020  sqlite3_int64 offset      /* Offset into the file to begin writing at */
28021){
28022  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
28023  LONG lowerBits = (LONG)(offset & 0xffffffff);
28024  DWORD rc;
28025  winFile *pFile = (winFile*)id;
28026  DWORD error;
28027  DWORD wrote = 0;
28028
28029  assert( id!=0 );
28030  SimulateIOError(return SQLITE_IOERR_WRITE);
28031  SimulateDiskfullError(return SQLITE_FULL);
28032  OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
28033  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
28034  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
28035    pFile->lastErrno = error;
28036    return SQLITE_FULL;
28037  }
28038  assert( amt>0 );
28039  while(
28040     amt>0
28041     && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
28042     && wrote>0
28043  ){
28044    amt -= wrote;
28045    pBuf = &((char*)pBuf)[wrote];
28046  }
28047  if( !rc || amt>(int)wrote ){
28048    pFile->lastErrno = GetLastError();
28049    return SQLITE_FULL;
28050  }
28051  return SQLITE_OK;
28052}
28053
28054/*
28055** Truncate an open file to a specified size
28056*/
28057static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
28058  LONG upperBits = (LONG)((nByte>>32) & 0x7fffffff);
28059  LONG lowerBits = (LONG)(nByte & 0xffffffff);
28060  DWORD rc;
28061  winFile *pFile = (winFile*)id;
28062  DWORD error;
28063
28064  assert( id!=0 );
28065  OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
28066  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
28067  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
28068  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
28069    pFile->lastErrno = error;
28070    return SQLITE_IOERR_TRUNCATE;
28071  }
28072  /* SetEndOfFile will fail if nByte is negative */
28073  if( !SetEndOfFile(pFile->h) ){
28074    pFile->lastErrno = GetLastError();
28075    return SQLITE_IOERR_TRUNCATE;
28076  }
28077  return SQLITE_OK;
28078}
28079
28080#ifdef SQLITE_TEST
28081/*
28082** Count the number of fullsyncs and normal syncs.  This is used to test
28083** that syncs and fullsyncs are occuring at the right times.
28084*/
28085SQLITE_API int sqlite3_sync_count = 0;
28086SQLITE_API int sqlite3_fullsync_count = 0;
28087#endif
28088
28089/*
28090** Make sure all writes to a particular file are committed to disk.
28091*/
28092static int winSync(sqlite3_file *id, int flags){
28093#ifndef SQLITE_NO_SYNC
28094  winFile *pFile = (winFile*)id;
28095
28096  assert( id!=0 );
28097  OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
28098#else
28099  UNUSED_PARAMETER(id);
28100#endif
28101#ifndef SQLITE_TEST
28102  UNUSED_PARAMETER(flags);
28103#else
28104  if( flags & SQLITE_SYNC_FULL ){
28105    sqlite3_fullsync_count++;
28106  }
28107  sqlite3_sync_count++;
28108#endif
28109  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
28110  ** no-op
28111  */
28112#ifdef SQLITE_NO_SYNC
28113    return SQLITE_OK;
28114#else
28115  if( FlushFileBuffers(pFile->h) ){
28116    return SQLITE_OK;
28117  }else{
28118    pFile->lastErrno = GetLastError();
28119    return SQLITE_IOERR;
28120  }
28121#endif
28122}
28123
28124/*
28125** Determine the current size of a file in bytes
28126*/
28127static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
28128  DWORD upperBits;
28129  DWORD lowerBits;
28130  winFile *pFile = (winFile*)id;
28131  DWORD error;
28132
28133  assert( id!=0 );
28134  SimulateIOError(return SQLITE_IOERR_FSTAT);
28135  lowerBits = GetFileSize(pFile->h, &upperBits);
28136  if(   (lowerBits == INVALID_FILE_SIZE)
28137     && ((error = GetLastError()) != NO_ERROR) )
28138  {
28139    pFile->lastErrno = error;
28140    return SQLITE_IOERR_FSTAT;
28141  }
28142  *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
28143  return SQLITE_OK;
28144}
28145
28146/*
28147** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
28148*/
28149#ifndef LOCKFILE_FAIL_IMMEDIATELY
28150# define LOCKFILE_FAIL_IMMEDIATELY 1
28151#endif
28152
28153/*
28154** Acquire a reader lock.
28155** Different API routines are called depending on whether or not this
28156** is Win95 or WinNT.
28157*/
28158static int getReadLock(winFile *pFile){
28159  int res;
28160  if( isNT() ){
28161    OVERLAPPED ovlp;
28162    ovlp.Offset = SHARED_FIRST;
28163    ovlp.OffsetHigh = 0;
28164    ovlp.hEvent = 0;
28165    res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
28166                     0, SHARED_SIZE, 0, &ovlp);
28167/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28168*/
28169#if SQLITE_OS_WINCE==0
28170  }else{
28171    int lk;
28172    sqlite3_randomness(sizeof(lk), &lk);
28173    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
28174    res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
28175#endif
28176  }
28177  if( res == 0 ){
28178    pFile->lastErrno = GetLastError();
28179  }
28180  return res;
28181}
28182
28183/*
28184** Undo a readlock
28185*/
28186static int unlockReadLock(winFile *pFile){
28187  int res;
28188  if( isNT() ){
28189    res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28190/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28191*/
28192#if SQLITE_OS_WINCE==0
28193  }else{
28194    res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
28195#endif
28196  }
28197  if( res == 0 ){
28198    pFile->lastErrno = GetLastError();
28199  }
28200  return res;
28201}
28202
28203/*
28204** Lock the file with the lock specified by parameter locktype - one
28205** of the following:
28206**
28207**     (1) SHARED_LOCK
28208**     (2) RESERVED_LOCK
28209**     (3) PENDING_LOCK
28210**     (4) EXCLUSIVE_LOCK
28211**
28212** Sometimes when requesting one lock state, additional lock states
28213** are inserted in between.  The locking might fail on one of the later
28214** transitions leaving the lock state different from what it started but
28215** still short of its goal.  The following chart shows the allowed
28216** transitions and the inserted intermediate states:
28217**
28218**    UNLOCKED -> SHARED
28219**    SHARED -> RESERVED
28220**    SHARED -> (PENDING) -> EXCLUSIVE
28221**    RESERVED -> (PENDING) -> EXCLUSIVE
28222**    PENDING -> EXCLUSIVE
28223**
28224** This routine will only increase a lock.  The winUnlock() routine
28225** erases all locks at once and returns us immediately to locking level 0.
28226** It is not possible to lower the locking level one step at a time.  You
28227** must go straight to locking level 0.
28228*/
28229static int winLock(sqlite3_file *id, int locktype){
28230  int rc = SQLITE_OK;    /* Return code from subroutines */
28231  int res = 1;           /* Result of a windows lock call */
28232  int newLocktype;       /* Set pFile->locktype to this value before exiting */
28233  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
28234  winFile *pFile = (winFile*)id;
28235  DWORD error = NO_ERROR;
28236
28237  assert( id!=0 );
28238  OSTRACE5("LOCK %d %d was %d(%d)\n",
28239          pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
28240
28241  /* If there is already a lock of this type or more restrictive on the
28242  ** OsFile, do nothing. Don't use the end_lock: exit path, as
28243  ** sqlite3OsEnterMutex() hasn't been called yet.
28244  */
28245  if( pFile->locktype>=locktype ){
28246    return SQLITE_OK;
28247  }
28248
28249  /* Make sure the locking sequence is correct
28250  */
28251  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
28252  assert( locktype!=PENDING_LOCK );
28253  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
28254
28255  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
28256  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
28257  ** the PENDING_LOCK byte is temporary.
28258  */
28259  newLocktype = pFile->locktype;
28260  if(   (pFile->locktype==NO_LOCK)
28261     || (   (locktype==EXCLUSIVE_LOCK)
28262         && (pFile->locktype==RESERVED_LOCK))
28263  ){
28264    int cnt = 3;
28265    while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
28266      /* Try 3 times to get the pending lock.  The pending lock might be
28267      ** held by another reader process who will release it momentarily.
28268      */
28269      OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
28270      Sleep(1);
28271    }
28272    gotPendingLock = res;
28273    if( !res ){
28274      error = GetLastError();
28275    }
28276  }
28277
28278  /* Acquire a shared lock
28279  */
28280  if( locktype==SHARED_LOCK && res ){
28281    assert( pFile->locktype==NO_LOCK );
28282    res = getReadLock(pFile);
28283    if( res ){
28284      newLocktype = SHARED_LOCK;
28285    }else{
28286      error = GetLastError();
28287    }
28288  }
28289
28290  /* Acquire a RESERVED lock
28291  */
28292  if( locktype==RESERVED_LOCK && res ){
28293    assert( pFile->locktype==SHARED_LOCK );
28294    res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28295    if( res ){
28296      newLocktype = RESERVED_LOCK;
28297    }else{
28298      error = GetLastError();
28299    }
28300  }
28301
28302  /* Acquire a PENDING lock
28303  */
28304  if( locktype==EXCLUSIVE_LOCK && res ){
28305    newLocktype = PENDING_LOCK;
28306    gotPendingLock = 0;
28307  }
28308
28309  /* Acquire an EXCLUSIVE lock
28310  */
28311  if( locktype==EXCLUSIVE_LOCK && res ){
28312    assert( pFile->locktype>=SHARED_LOCK );
28313    res = unlockReadLock(pFile);
28314    OSTRACE2("unreadlock = %d\n", res);
28315    res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28316    if( res ){
28317      newLocktype = EXCLUSIVE_LOCK;
28318    }else{
28319      error = GetLastError();
28320      OSTRACE2("error-code = %d\n", error);
28321      getReadLock(pFile);
28322    }
28323  }
28324
28325  /* If we are holding a PENDING lock that ought to be released, then
28326  ** release it now.
28327  */
28328  if( gotPendingLock && locktype==SHARED_LOCK ){
28329    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
28330  }
28331
28332  /* Update the state of the lock has held in the file descriptor then
28333  ** return the appropriate result code.
28334  */
28335  if( res ){
28336    rc = SQLITE_OK;
28337  }else{
28338    OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
28339           locktype, newLocktype);
28340    pFile->lastErrno = error;
28341    rc = SQLITE_BUSY;
28342  }
28343  pFile->locktype = (u8)newLocktype;
28344  return rc;
28345}
28346
28347/*
28348** This routine checks if there is a RESERVED lock held on the specified
28349** file by this or any other process. If such a lock is held, return
28350** non-zero, otherwise zero.
28351*/
28352static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
28353  int rc;
28354  winFile *pFile = (winFile*)id;
28355
28356  assert( id!=0 );
28357  if( pFile->locktype>=RESERVED_LOCK ){
28358    rc = 1;
28359    OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
28360  }else{
28361    rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28362    if( rc ){
28363      UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28364    }
28365    rc = !rc;
28366    OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
28367  }
28368  *pResOut = rc;
28369  return SQLITE_OK;
28370}
28371
28372/*
28373** Lower the locking level on file descriptor id to locktype.  locktype
28374** must be either NO_LOCK or SHARED_LOCK.
28375**
28376** If the locking level of the file descriptor is already at or below
28377** the requested locking level, this routine is a no-op.
28378**
28379** It is not possible for this routine to fail if the second argument
28380** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
28381** might return SQLITE_IOERR;
28382*/
28383static int winUnlock(sqlite3_file *id, int locktype){
28384  int type;
28385  winFile *pFile = (winFile*)id;
28386  int rc = SQLITE_OK;
28387  assert( pFile!=0 );
28388  assert( locktype<=SHARED_LOCK );
28389  OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
28390          pFile->locktype, pFile->sharedLockByte);
28391  type = pFile->locktype;
28392  if( type>=EXCLUSIVE_LOCK ){
28393    UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28394    if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
28395      /* This should never happen.  We should always be able to
28396      ** reacquire the read lock */
28397      rc = SQLITE_IOERR_UNLOCK;
28398    }
28399  }
28400  if( type>=RESERVED_LOCK ){
28401    UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28402  }
28403  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
28404    unlockReadLock(pFile);
28405  }
28406  if( type>=PENDING_LOCK ){
28407    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
28408  }
28409  pFile->locktype = (u8)locktype;
28410  return rc;
28411}
28412
28413/*
28414** Control and query of the open file handle.
28415*/
28416static int winFileControl(sqlite3_file *id, int op, void *pArg){
28417  switch( op ){
28418    case SQLITE_FCNTL_LOCKSTATE: {
28419      *(int*)pArg = ((winFile*)id)->locktype;
28420      return SQLITE_OK;
28421    }
28422    case SQLITE_LAST_ERRNO: {
28423      *(int*)pArg = (int)((winFile*)id)->lastErrno;
28424      return SQLITE_OK;
28425    }
28426  }
28427  return SQLITE_ERROR;
28428}
28429
28430/*
28431** Return the sector size in bytes of the underlying block device for
28432** the specified file. This is almost always 512 bytes, but may be
28433** larger for some devices.
28434**
28435** SQLite code assumes this function cannot fail. It also assumes that
28436** if two files are created in the same file-system directory (i.e.
28437** a database and its journal file) that the sector size will be the
28438** same for both.
28439*/
28440static int winSectorSize(sqlite3_file *id){
28441  assert( id!=0 );
28442  return (int)(((winFile*)id)->sectorSize);
28443}
28444
28445/*
28446** Return a vector of device characteristics.
28447*/
28448static int winDeviceCharacteristics(sqlite3_file *id){
28449  UNUSED_PARAMETER(id);
28450  return 0;
28451}
28452
28453/*
28454** This vector defines all the methods that can operate on an
28455** sqlite3_file for win32.
28456*/
28457static const sqlite3_io_methods winIoMethod = {
28458  1,                        /* iVersion */
28459  winClose,
28460  winRead,
28461  winWrite,
28462  winTruncate,
28463  winSync,
28464  winFileSize,
28465  winLock,
28466  winUnlock,
28467  winCheckReservedLock,
28468  winFileControl,
28469  winSectorSize,
28470  winDeviceCharacteristics
28471};
28472
28473/***************************************************************************
28474** Here ends the I/O methods that form the sqlite3_io_methods object.
28475**
28476** The next block of code implements the VFS methods.
28477****************************************************************************/
28478
28479/*
28480** Convert a UTF-8 filename into whatever form the underlying
28481** operating system wants filenames in.  Space to hold the result
28482** is obtained from malloc and must be freed by the calling
28483** function.
28484*/
28485static void *convertUtf8Filename(const char *zFilename){
28486  void *zConverted = 0;
28487  if( isNT() ){
28488    zConverted = utf8ToUnicode(zFilename);
28489/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28490*/
28491#if SQLITE_OS_WINCE==0
28492  }else{
28493    zConverted = utf8ToMbcs(zFilename);
28494#endif
28495  }
28496  /* caller will handle out of memory */
28497  return zConverted;
28498}
28499
28500/*
28501** Create a temporary file name in zBuf.  zBuf must be big enough to
28502** hold at pVfs->mxPathname characters.
28503*/
28504static int getTempname(int nBuf, char *zBuf){
28505  static char zChars[] =
28506    "abcdefghijklmnopqrstuvwxyz"
28507    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
28508    "0123456789";
28509  size_t i, j;
28510  char zTempPath[MAX_PATH+1];
28511  if( sqlite3_temp_directory ){
28512    sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
28513  }else if( isNT() ){
28514    char *zMulti;
28515    WCHAR zWidePath[MAX_PATH];
28516    GetTempPathW(MAX_PATH-30, zWidePath);
28517    zMulti = unicodeToUtf8(zWidePath);
28518    if( zMulti ){
28519      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
28520      free(zMulti);
28521    }else{
28522      return SQLITE_NOMEM;
28523    }
28524/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28525** Since the ASCII version of these Windows API do not exist for WINCE,
28526** it's important to not reference them for WINCE builds.
28527*/
28528#if SQLITE_OS_WINCE==0
28529  }else{
28530    char *zUtf8;
28531    char zMbcsPath[MAX_PATH];
28532    GetTempPathA(MAX_PATH-30, zMbcsPath);
28533    zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
28534    if( zUtf8 ){
28535      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
28536      free(zUtf8);
28537    }else{
28538      return SQLITE_NOMEM;
28539    }
28540#endif
28541  }
28542  for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
28543  zTempPath[i] = 0;
28544  sqlite3_snprintf(nBuf-30, zBuf,
28545                   "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
28546  j = sqlite3Strlen30(zBuf);
28547  sqlite3_randomness(20, &zBuf[j]);
28548  for(i=0; i<20; i++, j++){
28549    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
28550  }
28551  zBuf[j] = 0;
28552  OSTRACE2("TEMP FILENAME: %s\n", zBuf);
28553  return SQLITE_OK;
28554}
28555
28556/*
28557** The return value of getLastErrorMsg
28558** is zero if the error message fits in the buffer, or non-zero
28559** otherwise (if the message was truncated).
28560*/
28561static int getLastErrorMsg(int nBuf, char *zBuf){
28562  /* FormatMessage returns 0 on failure.  Otherwise it
28563  ** returns the number of TCHARs written to the output
28564  ** buffer, excluding the terminating null char.
28565  */
28566  DWORD error = GetLastError();
28567  DWORD dwLen = 0;
28568  char *zOut = 0;
28569
28570  if( isNT() ){
28571    WCHAR *zTempWide = NULL;
28572    dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
28573                           NULL,
28574                           error,
28575                           0,
28576                           (LPWSTR) &zTempWide,
28577                           0,
28578                           0);
28579    if( dwLen > 0 ){
28580      /* allocate a buffer and convert to UTF8 */
28581      zOut = unicodeToUtf8(zTempWide);
28582      /* free the system buffer allocated by FormatMessage */
28583      LocalFree(zTempWide);
28584    }
28585/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28586** Since the ASCII version of these Windows API do not exist for WINCE,
28587** it's important to not reference them for WINCE builds.
28588*/
28589#if SQLITE_OS_WINCE==0
28590  }else{
28591    char *zTemp = NULL;
28592    dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
28593                           NULL,
28594                           error,
28595                           0,
28596                           (LPSTR) &zTemp,
28597                           0,
28598                           0);
28599    if( dwLen > 0 ){
28600      /* allocate a buffer and convert to UTF8 */
28601      zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
28602      /* free the system buffer allocated by FormatMessage */
28603      LocalFree(zTemp);
28604    }
28605#endif
28606  }
28607  if( 0 == dwLen ){
28608    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
28609  }else{
28610    /* copy a maximum of nBuf chars to output buffer */
28611    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
28612    /* free the UTF8 buffer */
28613    free(zOut);
28614  }
28615  return 0;
28616}
28617
28618/*
28619** Open a file.
28620*/
28621static int winOpen(
28622  sqlite3_vfs *pVfs,        /* Not used */
28623  const char *zName,        /* Name of the file (UTF-8) */
28624  sqlite3_file *id,         /* Write the SQLite file handle here */
28625  int flags,                /* Open mode flags */
28626  int *pOutFlags            /* Status return flags */
28627){
28628  HANDLE h;
28629  DWORD dwDesiredAccess;
28630  DWORD dwShareMode;
28631  DWORD dwCreationDisposition;
28632  DWORD dwFlagsAndAttributes = 0;
28633#if SQLITE_OS_WINCE
28634  int isTemp = 0;
28635#endif
28636  winFile *pFile = (winFile*)id;
28637  void *zConverted;                 /* Filename in OS encoding */
28638  const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
28639  char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
28640
28641  assert( id!=0 );
28642  UNUSED_PARAMETER(pVfs);
28643
28644  /* If the second argument to this function is NULL, generate a
28645  ** temporary file name to use
28646  */
28647  if( !zUtf8Name ){
28648    int rc = getTempname(MAX_PATH+1, zTmpname);
28649    if( rc!=SQLITE_OK ){
28650      return rc;
28651    }
28652    zUtf8Name = zTmpname;
28653  }
28654
28655  /* Convert the filename to the system encoding. */
28656  zConverted = convertUtf8Filename(zUtf8Name);
28657  if( zConverted==0 ){
28658    return SQLITE_NOMEM;
28659  }
28660
28661  if( flags & SQLITE_OPEN_READWRITE ){
28662    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
28663  }else{
28664    dwDesiredAccess = GENERIC_READ;
28665  }
28666  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
28667  ** created. SQLite doesn't use it to indicate "exclusive access"
28668  ** as it is usually understood.
28669  */
28670  assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
28671  if( flags & SQLITE_OPEN_EXCLUSIVE ){
28672    /* Creates a new file, only if it does not already exist. */
28673    /* If the file exists, it fails. */
28674    dwCreationDisposition = CREATE_NEW;
28675  }else if( flags & SQLITE_OPEN_CREATE ){
28676    /* Open existing file, or create if it doesn't exist */
28677    dwCreationDisposition = OPEN_ALWAYS;
28678  }else{
28679    /* Opens a file, only if it exists. */
28680    dwCreationDisposition = OPEN_EXISTING;
28681  }
28682  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
28683  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
28684#if SQLITE_OS_WINCE
28685    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
28686    isTemp = 1;
28687#else
28688    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
28689                               | FILE_ATTRIBUTE_HIDDEN
28690                               | FILE_FLAG_DELETE_ON_CLOSE;
28691#endif
28692  }else{
28693    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
28694  }
28695  /* Reports from the internet are that performance is always
28696  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
28697#if SQLITE_OS_WINCE
28698  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
28699#endif
28700  if( isNT() ){
28701    h = CreateFileW((WCHAR*)zConverted,
28702       dwDesiredAccess,
28703       dwShareMode,
28704       NULL,
28705       dwCreationDisposition,
28706       dwFlagsAndAttributes,
28707       NULL
28708    );
28709/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28710** Since the ASCII version of these Windows API do not exist for WINCE,
28711** it's important to not reference them for WINCE builds.
28712*/
28713#if SQLITE_OS_WINCE==0
28714  }else{
28715    h = CreateFileA((char*)zConverted,
28716       dwDesiredAccess,
28717       dwShareMode,
28718       NULL,
28719       dwCreationDisposition,
28720       dwFlagsAndAttributes,
28721       NULL
28722    );
28723#endif
28724  }
28725  if( h==INVALID_HANDLE_VALUE ){
28726    free(zConverted);
28727    if( flags & SQLITE_OPEN_READWRITE ){
28728      return winOpen(pVfs, zName, id,
28729             ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
28730    }else{
28731      return SQLITE_CANTOPEN_BKPT;
28732    }
28733  }
28734  if( pOutFlags ){
28735    if( flags & SQLITE_OPEN_READWRITE ){
28736      *pOutFlags = SQLITE_OPEN_READWRITE;
28737    }else{
28738      *pOutFlags = SQLITE_OPEN_READONLY;
28739    }
28740  }
28741  memset(pFile, 0, sizeof(*pFile));
28742  pFile->pMethod = &winIoMethod;
28743  pFile->h = h;
28744  pFile->lastErrno = NO_ERROR;
28745  pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
28746#if SQLITE_OS_WINCE
28747  if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
28748               (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
28749       && !winceCreateLock(zName, pFile)
28750  ){
28751    CloseHandle(h);
28752    free(zConverted);
28753    return SQLITE_CANTOPEN_BKPT;
28754  }
28755  if( isTemp ){
28756    pFile->zDeleteOnClose = zConverted;
28757  }else
28758#endif
28759  {
28760    free(zConverted);
28761  }
28762  OpenCounter(+1);
28763  return SQLITE_OK;
28764}
28765
28766/*
28767** Delete the named file.
28768**
28769** Note that windows does not allow a file to be deleted if some other
28770** process has it open.  Sometimes a virus scanner or indexing program
28771** will open a journal file shortly after it is created in order to do
28772** whatever it does.  While this other process is holding the
28773** file open, we will be unable to delete it.  To work around this
28774** problem, we delay 100 milliseconds and try to delete again.  Up
28775** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
28776** up and returning an error.
28777*/
28778#define MX_DELETION_ATTEMPTS 5
28779static int winDelete(
28780  sqlite3_vfs *pVfs,          /* Not used on win32 */
28781  const char *zFilename,      /* Name of file to delete */
28782  int syncDir                 /* Not used on win32 */
28783){
28784  int cnt = 0;
28785  DWORD rc;
28786  DWORD error = 0;
28787  void *zConverted = convertUtf8Filename(zFilename);
28788  UNUSED_PARAMETER(pVfs);
28789  UNUSED_PARAMETER(syncDir);
28790  if( zConverted==0 ){
28791    return SQLITE_NOMEM;
28792  }
28793  SimulateIOError(return SQLITE_IOERR_DELETE);
28794  if( isNT() ){
28795    do{
28796      DeleteFileW(zConverted);
28797    }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
28798               || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
28799           && (++cnt < MX_DELETION_ATTEMPTS)
28800           && (Sleep(100), 1) );
28801/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28802** Since the ASCII version of these Windows API do not exist for WINCE,
28803** it's important to not reference them for WINCE builds.
28804*/
28805#if SQLITE_OS_WINCE==0
28806  }else{
28807    do{
28808      DeleteFileA(zConverted);
28809    }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
28810               || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
28811           && (++cnt < MX_DELETION_ATTEMPTS)
28812           && (Sleep(100), 1) );
28813#endif
28814  }
28815  free(zConverted);
28816  OSTRACE2("DELETE \"%s\"\n", zFilename);
28817  return (   (rc == INVALID_FILE_ATTRIBUTES)
28818          && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
28819}
28820
28821/*
28822** Check the existance and status of a file.
28823*/
28824static int winAccess(
28825  sqlite3_vfs *pVfs,         /* Not used on win32 */
28826  const char *zFilename,     /* Name of file to check */
28827  int flags,                 /* Type of test to make on this file */
28828  int *pResOut               /* OUT: Result */
28829){
28830  DWORD attr;
28831  int rc = 0;
28832  void *zConverted = convertUtf8Filename(zFilename);
28833  UNUSED_PARAMETER(pVfs);
28834  if( zConverted==0 ){
28835    return SQLITE_NOMEM;
28836  }
28837  if( isNT() ){
28838    attr = GetFileAttributesW((WCHAR*)zConverted);
28839/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28840** Since the ASCII version of these Windows API do not exist for WINCE,
28841** it's important to not reference them for WINCE builds.
28842*/
28843#if SQLITE_OS_WINCE==0
28844  }else{
28845    attr = GetFileAttributesA((char*)zConverted);
28846#endif
28847  }
28848  free(zConverted);
28849  switch( flags ){
28850    case SQLITE_ACCESS_READ:
28851    case SQLITE_ACCESS_EXISTS:
28852      rc = attr!=INVALID_FILE_ATTRIBUTES;
28853      break;
28854    case SQLITE_ACCESS_READWRITE:
28855      rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
28856      break;
28857    default:
28858      assert(!"Invalid flags argument");
28859  }
28860  *pResOut = rc;
28861  return SQLITE_OK;
28862}
28863
28864
28865/*
28866** Turn a relative pathname into a full pathname.  Write the full
28867** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
28868** bytes in size.
28869*/
28870static int winFullPathname(
28871  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
28872  const char *zRelative,        /* Possibly relative input path */
28873  int nFull,                    /* Size of output buffer in bytes */
28874  char *zFull                   /* Output buffer */
28875){
28876
28877#if defined(__CYGWIN__)
28878  UNUSED_PARAMETER(nFull);
28879  cygwin_conv_to_full_win32_path(zRelative, zFull);
28880  return SQLITE_OK;
28881#endif
28882
28883#if SQLITE_OS_WINCE
28884  UNUSED_PARAMETER(nFull);
28885  /* WinCE has no concept of a relative pathname, or so I am told. */
28886  sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
28887  return SQLITE_OK;
28888#endif
28889
28890#if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
28891  int nByte;
28892  void *zConverted;
28893  char *zOut;
28894  UNUSED_PARAMETER(nFull);
28895  zConverted = convertUtf8Filename(zRelative);
28896  if( isNT() ){
28897    WCHAR *zTemp;
28898    nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
28899    zTemp = malloc( nByte*sizeof(zTemp[0]) );
28900    if( zTemp==0 ){
28901      free(zConverted);
28902      return SQLITE_NOMEM;
28903    }
28904    GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
28905    free(zConverted);
28906    zOut = unicodeToUtf8(zTemp);
28907    free(zTemp);
28908/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28909** Since the ASCII version of these Windows API do not exist for WINCE,
28910** it's important to not reference them for WINCE builds.
28911*/
28912#if SQLITE_OS_WINCE==0
28913  }else{
28914    char *zTemp;
28915    nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
28916    zTemp = malloc( nByte*sizeof(zTemp[0]) );
28917    if( zTemp==0 ){
28918      free(zConverted);
28919      return SQLITE_NOMEM;
28920    }
28921    GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
28922    free(zConverted);
28923    zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
28924    free(zTemp);
28925#endif
28926  }
28927  if( zOut ){
28928    sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
28929    free(zOut);
28930    return SQLITE_OK;
28931  }else{
28932    return SQLITE_NOMEM;
28933  }
28934#endif
28935}
28936
28937/*
28938** Get the sector size of the device used to store
28939** file.
28940*/
28941static int getSectorSize(
28942    sqlite3_vfs *pVfs,
28943    const char *zRelative     /* UTF-8 file name */
28944){
28945  DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
28946  /* GetDiskFreeSpace is not supported under WINCE */
28947#if SQLITE_OS_WINCE
28948  UNUSED_PARAMETER(pVfs);
28949  UNUSED_PARAMETER(zRelative);
28950#else
28951  char zFullpath[MAX_PATH+1];
28952  int rc;
28953  DWORD dwRet = 0;
28954  DWORD dwDummy;
28955
28956  /*
28957  ** We need to get the full path name of the file
28958  ** to get the drive letter to look up the sector
28959  ** size.
28960  */
28961  rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
28962  if( rc == SQLITE_OK )
28963  {
28964    void *zConverted = convertUtf8Filename(zFullpath);
28965    if( zConverted ){
28966      if( isNT() ){
28967        /* trim path to just drive reference */
28968        WCHAR *p = zConverted;
28969        for(;*p;p++){
28970          if( *p == '\\' ){
28971            *p = '\0';
28972            break;
28973          }
28974        }
28975        dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
28976                                  &dwDummy,
28977                                  &bytesPerSector,
28978                                  &dwDummy,
28979                                  &dwDummy);
28980      }else{
28981        /* trim path to just drive reference */
28982        char *p = (char *)zConverted;
28983        for(;*p;p++){
28984          if( *p == '\\' ){
28985            *p = '\0';
28986            break;
28987          }
28988        }
28989        dwRet = GetDiskFreeSpaceA((char*)zConverted,
28990                                  &dwDummy,
28991                                  &bytesPerSector,
28992                                  &dwDummy,
28993                                  &dwDummy);
28994      }
28995      free(zConverted);
28996    }
28997    if( !dwRet ){
28998      bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
28999    }
29000  }
29001#endif
29002  return (int) bytesPerSector;
29003}
29004
29005#ifndef SQLITE_OMIT_LOAD_EXTENSION
29006/*
29007** Interfaces for opening a shared library, finding entry points
29008** within the shared library, and closing the shared library.
29009*/
29010/*
29011** Interfaces for opening a shared library, finding entry points
29012** within the shared library, and closing the shared library.
29013*/
29014static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
29015  HANDLE h;
29016  void *zConverted = convertUtf8Filename(zFilename);
29017  UNUSED_PARAMETER(pVfs);
29018  if( zConverted==0 ){
29019    return 0;
29020  }
29021  if( isNT() ){
29022    h = LoadLibraryW((WCHAR*)zConverted);
29023/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
29024** Since the ASCII version of these Windows API do not exist for WINCE,
29025** it's important to not reference them for WINCE builds.
29026*/
29027#if SQLITE_OS_WINCE==0
29028  }else{
29029    h = LoadLibraryA((char*)zConverted);
29030#endif
29031  }
29032  free(zConverted);
29033  return (void*)h;
29034}
29035static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
29036  UNUSED_PARAMETER(pVfs);
29037  getLastErrorMsg(nBuf, zBufOut);
29038}
29039void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
29040  UNUSED_PARAMETER(pVfs);
29041#if SQLITE_OS_WINCE
29042  /* The GetProcAddressA() routine is only available on wince. */
29043  return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
29044#else
29045  /* All other windows platforms expect GetProcAddress() to take
29046  ** an Ansi string regardless of the _UNICODE setting */
29047  return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
29048#endif
29049}
29050void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
29051  UNUSED_PARAMETER(pVfs);
29052  FreeLibrary((HANDLE)pHandle);
29053}
29054#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29055  #define winDlOpen  0
29056  #define winDlError 0
29057  #define winDlSym   0
29058  #define winDlClose 0
29059#endif
29060
29061
29062/*
29063** Write up to nBuf bytes of randomness into zBuf.
29064*/
29065static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
29066  int n = 0;
29067  UNUSED_PARAMETER(pVfs);
29068#if defined(SQLITE_TEST)
29069  n = nBuf;
29070  memset(zBuf, 0, nBuf);
29071#else
29072  if( sizeof(SYSTEMTIME)<=nBuf-n ){
29073    SYSTEMTIME x;
29074    GetSystemTime(&x);
29075    memcpy(&zBuf[n], &x, sizeof(x));
29076    n += sizeof(x);
29077  }
29078  if( sizeof(DWORD)<=nBuf-n ){
29079    DWORD pid = GetCurrentProcessId();
29080    memcpy(&zBuf[n], &pid, sizeof(pid));
29081    n += sizeof(pid);
29082  }
29083  if( sizeof(DWORD)<=nBuf-n ){
29084    DWORD cnt = GetTickCount();
29085    memcpy(&zBuf[n], &cnt, sizeof(cnt));
29086    n += sizeof(cnt);
29087  }
29088  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
29089    LARGE_INTEGER i;
29090    QueryPerformanceCounter(&i);
29091    memcpy(&zBuf[n], &i, sizeof(i));
29092    n += sizeof(i);
29093  }
29094#endif
29095  return n;
29096}
29097
29098
29099/*
29100** Sleep for a little while.  Return the amount of time slept.
29101*/
29102static int winSleep(sqlite3_vfs *pVfs, int microsec){
29103  Sleep((microsec+999)/1000);
29104  UNUSED_PARAMETER(pVfs);
29105  return ((microsec+999)/1000)*1000;
29106}
29107
29108/*
29109** The following variable, if set to a non-zero value, becomes the result
29110** returned from sqlite3OsCurrentTime().  This is used for testing.
29111*/
29112#ifdef SQLITE_TEST
29113SQLITE_API int sqlite3_current_time = 0;
29114#endif
29115
29116/*
29117** Find the current time (in Universal Coordinated Time).  Write the
29118** current time and date as a Julian Day number into *prNow and
29119** return 0.  Return 1 if the time and date cannot be found.
29120*/
29121int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
29122  FILETIME ft;
29123  /* FILETIME structure is a 64-bit value representing the number of
29124     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
29125  */
29126  sqlite3_int64 timeW;   /* Whole days */
29127  sqlite3_int64 timeF;   /* Fractional Days */
29128
29129  /* Number of 100-nanosecond intervals in a single day */
29130  static const sqlite3_int64 ntuPerDay =
29131      10000000*(sqlite3_int64)86400;
29132
29133  /* Number of 100-nanosecond intervals in half of a day */
29134  static const sqlite3_int64 ntuPerHalfDay =
29135      10000000*(sqlite3_int64)43200;
29136
29137  /* 2^32 - to avoid use of LL and warnings in gcc */
29138  static const sqlite3_int64 max32BitValue =
29139      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
29140
29141#if SQLITE_OS_WINCE
29142  SYSTEMTIME time;
29143  GetSystemTime(&time);
29144  /* if SystemTimeToFileTime() fails, it returns zero. */
29145  if (!SystemTimeToFileTime(&time,&ft)){
29146    return 1;
29147  }
29148#else
29149  GetSystemTimeAsFileTime( &ft );
29150#endif
29151  UNUSED_PARAMETER(pVfs);
29152  timeW = (((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + (sqlite3_int64)ft.dwLowDateTime;
29153  timeF = timeW % ntuPerDay;          /* fractional days (100-nanoseconds) */
29154  timeW = timeW / ntuPerDay;          /* whole days */
29155  timeW = timeW + 2305813;            /* add whole days (from 2305813.5) */
29156  timeF = timeF + ntuPerHalfDay;      /* add half a day (from 2305813.5) */
29157  timeW = timeW + (timeF/ntuPerDay);  /* add whole day if half day made one */
29158  timeF = timeF % ntuPerDay;          /* compute new fractional days */
29159  *prNow = (double)timeW + ((double)timeF / (double)ntuPerDay);
29160#ifdef SQLITE_TEST
29161  if( sqlite3_current_time ){
29162    *prNow = ((double)sqlite3_current_time + (double)43200) / (double)86400 + (double)2440587;
29163  }
29164#endif
29165  return 0;
29166}
29167
29168/*
29169** The idea is that this function works like a combination of
29170** GetLastError() and FormatMessage() on windows (or errno and
29171** strerror_r() on unix). After an error is returned by an OS
29172** function, SQLite calls this function with zBuf pointing to
29173** a buffer of nBuf bytes. The OS layer should populate the
29174** buffer with a nul-terminated UTF-8 encoded error message
29175** describing the last IO error to have occurred within the calling
29176** thread.
29177**
29178** If the error message is too large for the supplied buffer,
29179** it should be truncated. The return value of xGetLastError
29180** is zero if the error message fits in the buffer, or non-zero
29181** otherwise (if the message was truncated). If non-zero is returned,
29182** then it is not necessary to include the nul-terminator character
29183** in the output buffer.
29184**
29185** Not supplying an error message will have no adverse effect
29186** on SQLite. It is fine to have an implementation that never
29187** returns an error message:
29188**
29189**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
29190**     assert(zBuf[0]=='\0');
29191**     return 0;
29192**   }
29193**
29194** However if an error message is supplied, it will be incorporated
29195** by sqlite into the error message available to the user using
29196** sqlite3_errmsg(), possibly making IO errors easier to debug.
29197*/
29198static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
29199  UNUSED_PARAMETER(pVfs);
29200  return getLastErrorMsg(nBuf, zBuf);
29201}
29202
29203/*
29204** Initialize and deinitialize the operating system interface.
29205*/
29206SQLITE_API int sqlite3_os_init(void){
29207  static sqlite3_vfs winVfs = {
29208    1,                 /* iVersion */
29209    sizeof(winFile),   /* szOsFile */
29210    MAX_PATH,          /* mxPathname */
29211    0,                 /* pNext */
29212    "win32",           /* zName */
29213    0,                 /* pAppData */
29214
29215    winOpen,           /* xOpen */
29216    winDelete,         /* xDelete */
29217    winAccess,         /* xAccess */
29218    winFullPathname,   /* xFullPathname */
29219    winDlOpen,         /* xDlOpen */
29220    winDlError,        /* xDlError */
29221    winDlSym,          /* xDlSym */
29222    winDlClose,        /* xDlClose */
29223    winRandomness,     /* xRandomness */
29224    winSleep,          /* xSleep */
29225    winCurrentTime,    /* xCurrentTime */
29226    winGetLastError    /* xGetLastError */
29227  };
29228
29229  sqlite3_vfs_register(&winVfs, 1);
29230  return SQLITE_OK;
29231}
29232SQLITE_API int sqlite3_os_end(void){
29233  return SQLITE_OK;
29234}
29235
29236#endif /* SQLITE_OS_WIN */
29237
29238/************** End of os_win.c **********************************************/
29239/************** Begin file bitvec.c ******************************************/
29240/*
29241** 2008 February 16
29242**
29243** The author disclaims copyright to this source code.  In place of
29244** a legal notice, here is a blessing:
29245**
29246**    May you do good and not evil.
29247**    May you find forgiveness for yourself and forgive others.
29248**    May you share freely, never taking more than you give.
29249**
29250*************************************************************************
29251** This file implements an object that represents a fixed-length
29252** bitmap.  Bits are numbered starting with 1.
29253**
29254** A bitmap is used to record which pages of a database file have been
29255** journalled during a transaction, or which pages have the "dont-write"
29256** property.  Usually only a few pages are meet either condition.
29257** So the bitmap is usually sparse and has low cardinality.
29258** But sometimes (for example when during a DROP of a large table) most
29259** or all of the pages in a database can get journalled.  In those cases,
29260** the bitmap becomes dense with high cardinality.  The algorithm needs
29261** to handle both cases well.
29262**
29263** The size of the bitmap is fixed when the object is created.
29264**
29265** All bits are clear when the bitmap is created.  Individual bits
29266** may be set or cleared one at a time.
29267**
29268** Test operations are about 100 times more common that set operations.
29269** Clear operations are exceedingly rare.  There are usually between
29270** 5 and 500 set operations per Bitvec object, though the number of sets can
29271** sometimes grow into tens of thousands or larger.  The size of the
29272** Bitvec object is the number of pages in the database file at the
29273** start of a transaction, and is thus usually less than a few thousand,
29274** but can be as large as 2 billion for a really big database.
29275*/
29276
29277/* Size of the Bitvec structure in bytes. */
29278#define BITVEC_SZ        (sizeof(void*)*128)  /* 512 on 32bit.  1024 on 64bit */
29279
29280/* Round the union size down to the nearest pointer boundary, since that's how
29281** it will be aligned within the Bitvec struct. */
29282#define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
29283
29284/* Type of the array "element" for the bitmap representation.
29285** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
29286** Setting this to the "natural word" size of your CPU may improve
29287** performance. */
29288#define BITVEC_TELEM     u8
29289/* Size, in bits, of the bitmap element. */
29290#define BITVEC_SZELEM    8
29291/* Number of elements in a bitmap array. */
29292#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
29293/* Number of bits in the bitmap array. */
29294#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
29295
29296/* Number of u32 values in hash table. */
29297#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
29298/* Maximum number of entries in hash table before
29299** sub-dividing and re-hashing. */
29300#define BITVEC_MXHASH    (BITVEC_NINT/2)
29301/* Hashing function for the aHash representation.
29302** Empirical testing showed that the *37 multiplier
29303** (an arbitrary prime)in the hash function provided
29304** no fewer collisions than the no-op *1. */
29305#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
29306
29307#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
29308
29309
29310/*
29311** A bitmap is an instance of the following structure.
29312**
29313** This bitmap records the existance of zero or more bits
29314** with values between 1 and iSize, inclusive.
29315**
29316** There are three possible representations of the bitmap.
29317** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
29318** bitmap.  The least significant bit is bit 1.
29319**
29320** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
29321** a hash table that will hold up to BITVEC_MXHASH distinct values.
29322**
29323** Otherwise, the value i is redirected into one of BITVEC_NPTR
29324** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
29325** handles up to iDivisor separate values of i.  apSub[0] holds
29326** values between 1 and iDivisor.  apSub[1] holds values between
29327** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
29328** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
29329** to hold deal with values between 1 and iDivisor.
29330*/
29331struct Bitvec {
29332  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
29333  u32 nSet;       /* Number of bits that are set - only valid for aHash
29334                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
29335                  ** this would be 125. */
29336  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
29337                  /* Should >=0 for apSub element. */
29338                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
29339                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
29340  union {
29341    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
29342    u32 aHash[BITVEC_NINT];      /* Hash table representation */
29343    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
29344  } u;
29345};
29346
29347/*
29348** Create a new bitmap object able to handle bits between 0 and iSize,
29349** inclusive.  Return a pointer to the new object.  Return NULL if
29350** malloc fails.
29351*/
29352SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
29353  Bitvec *p;
29354  assert( sizeof(*p)==BITVEC_SZ );
29355  p = sqlite3MallocZero( sizeof(*p) );
29356  if( p ){
29357    p->iSize = iSize;
29358  }
29359  return p;
29360}
29361
29362/*
29363** Check to see if the i-th bit is set.  Return true or false.
29364** If p is NULL (if the bitmap has not been created) or if
29365** i is out of range, then return false.
29366*/
29367SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
29368  if( p==0 ) return 0;
29369  if( i>p->iSize || i==0 ) return 0;
29370  i--;
29371  while( p->iDivisor ){
29372    u32 bin = i/p->iDivisor;
29373    i = i%p->iDivisor;
29374    p = p->u.apSub[bin];
29375    if (!p) {
29376      return 0;
29377    }
29378  }
29379  if( p->iSize<=BITVEC_NBIT ){
29380    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
29381  } else{
29382    u32 h = BITVEC_HASH(i++);
29383    while( p->u.aHash[h] ){
29384      if( p->u.aHash[h]==i ) return 1;
29385      h = (h+1) % BITVEC_NINT;
29386    }
29387    return 0;
29388  }
29389}
29390
29391/*
29392** Set the i-th bit.  Return 0 on success and an error code if
29393** anything goes wrong.
29394**
29395** This routine might cause sub-bitmaps to be allocated.  Failing
29396** to get the memory needed to hold the sub-bitmap is the only
29397** that can go wrong with an insert, assuming p and i are valid.
29398**
29399** The calling function must ensure that p is a valid Bitvec object
29400** and that the value for "i" is within range of the Bitvec object.
29401** Otherwise the behavior is undefined.
29402*/
29403SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
29404  u32 h;
29405  if( p==0 ) return SQLITE_OK;
29406  assert( i>0 );
29407  assert( i<=p->iSize );
29408  i--;
29409  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
29410    u32 bin = i/p->iDivisor;
29411    i = i%p->iDivisor;
29412    if( p->u.apSub[bin]==0 ){
29413      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
29414      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
29415    }
29416    p = p->u.apSub[bin];
29417  }
29418  if( p->iSize<=BITVEC_NBIT ){
29419    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
29420    return SQLITE_OK;
29421  }
29422  h = BITVEC_HASH(i++);
29423  /* if there wasn't a hash collision, and this doesn't */
29424  /* completely fill the hash, then just add it without */
29425  /* worring about sub-dividing and re-hashing. */
29426  if( !p->u.aHash[h] ){
29427    if (p->nSet<(BITVEC_NINT-1)) {
29428      goto bitvec_set_end;
29429    } else {
29430      goto bitvec_set_rehash;
29431    }
29432  }
29433  /* there was a collision, check to see if it's already */
29434  /* in hash, if not, try to find a spot for it */
29435  do {
29436    if( p->u.aHash[h]==i ) return SQLITE_OK;
29437    h++;
29438    if( h>=BITVEC_NINT ) h = 0;
29439  } while( p->u.aHash[h] );
29440  /* we didn't find it in the hash.  h points to the first */
29441  /* available free spot. check to see if this is going to */
29442  /* make our hash too "full".  */
29443bitvec_set_rehash:
29444  if( p->nSet>=BITVEC_MXHASH ){
29445    unsigned int j;
29446    int rc;
29447    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
29448    if( aiValues==0 ){
29449      return SQLITE_NOMEM;
29450    }else{
29451      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
29452      memset(p->u.apSub, 0, sizeof(p->u.apSub));
29453      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
29454      rc = sqlite3BitvecSet(p, i);
29455      for(j=0; j<BITVEC_NINT; j++){
29456        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
29457      }
29458      sqlite3StackFree(0, aiValues);
29459      return rc;
29460    }
29461  }
29462bitvec_set_end:
29463  p->nSet++;
29464  p->u.aHash[h] = i;
29465  return SQLITE_OK;
29466}
29467
29468/*
29469** Clear the i-th bit.
29470**
29471** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
29472** that BitvecClear can use to rebuilt its hash table.
29473*/
29474SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
29475  if( p==0 ) return;
29476  assert( i>0 );
29477  i--;
29478  while( p->iDivisor ){
29479    u32 bin = i/p->iDivisor;
29480    i = i%p->iDivisor;
29481    p = p->u.apSub[bin];
29482    if (!p) {
29483      return;
29484    }
29485  }
29486  if( p->iSize<=BITVEC_NBIT ){
29487    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
29488  }else{
29489    unsigned int j;
29490    u32 *aiValues = pBuf;
29491    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
29492    memset(p->u.aHash, 0, sizeof(p->u.aHash));
29493    p->nSet = 0;
29494    for(j=0; j<BITVEC_NINT; j++){
29495      if( aiValues[j] && aiValues[j]!=(i+1) ){
29496        u32 h = BITVEC_HASH(aiValues[j]-1);
29497        p->nSet++;
29498        while( p->u.aHash[h] ){
29499          h++;
29500          if( h>=BITVEC_NINT ) h = 0;
29501        }
29502        p->u.aHash[h] = aiValues[j];
29503      }
29504    }
29505  }
29506}
29507
29508/*
29509** Destroy a bitmap object.  Reclaim all memory used.
29510*/
29511SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
29512  if( p==0 ) return;
29513  if( p->iDivisor ){
29514    unsigned int i;
29515    for(i=0; i<BITVEC_NPTR; i++){
29516      sqlite3BitvecDestroy(p->u.apSub[i]);
29517    }
29518  }
29519  sqlite3_free(p);
29520}
29521
29522/*
29523** Return the value of the iSize parameter specified when Bitvec *p
29524** was created.
29525*/
29526SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
29527  return p->iSize;
29528}
29529
29530#ifndef SQLITE_OMIT_BUILTIN_TEST
29531/*
29532** Let V[] be an array of unsigned characters sufficient to hold
29533** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
29534** Then the following macros can be used to set, clear, or test
29535** individual bits within V.
29536*/
29537#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
29538#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
29539#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
29540
29541/*
29542** This routine runs an extensive test of the Bitvec code.
29543**
29544** The input is an array of integers that acts as a program
29545** to test the Bitvec.  The integers are opcodes followed
29546** by 0, 1, or 3 operands, depending on the opcode.  Another
29547** opcode follows immediately after the last operand.
29548**
29549** There are 6 opcodes numbered from 0 through 5.  0 is the
29550** "halt" opcode and causes the test to end.
29551**
29552**    0          Halt and return the number of errors
29553**    1 N S X    Set N bits beginning with S and incrementing by X
29554**    2 N S X    Clear N bits beginning with S and incrementing by X
29555**    3 N        Set N randomly chosen bits
29556**    4 N        Clear N randomly chosen bits
29557**    5 N S X    Set N bits from S increment X in array only, not in bitvec
29558**
29559** The opcodes 1 through 4 perform set and clear operations are performed
29560** on both a Bitvec object and on a linear array of bits obtained from malloc.
29561** Opcode 5 works on the linear array only, not on the Bitvec.
29562** Opcode 5 is used to deliberately induce a fault in order to
29563** confirm that error detection works.
29564**
29565** At the conclusion of the test the linear array is compared
29566** against the Bitvec object.  If there are any differences,
29567** an error is returned.  If they are the same, zero is returned.
29568**
29569** If a memory allocation error occurs, return -1.
29570*/
29571SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
29572  Bitvec *pBitvec = 0;
29573  unsigned char *pV = 0;
29574  int rc = -1;
29575  int i, nx, pc, op;
29576  void *pTmpSpace;
29577
29578  /* Allocate the Bitvec to be tested and a linear array of
29579  ** bits to act as the reference */
29580  pBitvec = sqlite3BitvecCreate( sz );
29581  pV = sqlite3_malloc( (sz+7)/8 + 1 );
29582  pTmpSpace = sqlite3_malloc(BITVEC_SZ);
29583  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
29584  memset(pV, 0, (sz+7)/8 + 1);
29585
29586  /* NULL pBitvec tests */
29587  sqlite3BitvecSet(0, 1);
29588  sqlite3BitvecClear(0, 1, pTmpSpace);
29589
29590  /* Run the program */
29591  pc = 0;
29592  while( (op = aOp[pc])!=0 ){
29593    switch( op ){
29594      case 1:
29595      case 2:
29596      case 5: {
29597        nx = 4;
29598        i = aOp[pc+2] - 1;
29599        aOp[pc+2] += aOp[pc+3];
29600        break;
29601      }
29602      case 3:
29603      case 4:
29604      default: {
29605        nx = 2;
29606        sqlite3_randomness(sizeof(i), &i);
29607        break;
29608      }
29609    }
29610    if( (--aOp[pc+1]) > 0 ) nx = 0;
29611    pc += nx;
29612    i = (i & 0x7fffffff)%sz;
29613    if( (op & 1)!=0 ){
29614      SETBIT(pV, (i+1));
29615      if( op!=5 ){
29616        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
29617      }
29618    }else{
29619      CLEARBIT(pV, (i+1));
29620      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
29621    }
29622  }
29623
29624  /* Test to make sure the linear array exactly matches the
29625  ** Bitvec object.  Start with the assumption that they do
29626  ** match (rc==0).  Change rc to non-zero if a discrepancy
29627  ** is found.
29628  */
29629  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
29630          + sqlite3BitvecTest(pBitvec, 0)
29631          + (sqlite3BitvecSize(pBitvec) - sz);
29632  for(i=1; i<=sz; i++){
29633    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
29634      rc = i;
29635      break;
29636    }
29637  }
29638
29639  /* Free allocated structure */
29640bitvec_end:
29641  sqlite3_free(pTmpSpace);
29642  sqlite3_free(pV);
29643  sqlite3BitvecDestroy(pBitvec);
29644  return rc;
29645}
29646#endif /* SQLITE_OMIT_BUILTIN_TEST */
29647
29648/************** End of bitvec.c **********************************************/
29649/************** Begin file pcache.c ******************************************/
29650/*
29651** 2008 August 05
29652**
29653** The author disclaims copyright to this source code.  In place of
29654** a legal notice, here is a blessing:
29655**
29656**    May you do good and not evil.
29657**    May you find forgiveness for yourself and forgive others.
29658**    May you share freely, never taking more than you give.
29659**
29660*************************************************************************
29661** This file implements that page cache.
29662*/
29663
29664/*
29665** A complete page cache is an instance of this structure.
29666*/
29667struct PCache {
29668  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
29669  PgHdr *pSynced;                     /* Last synced page in dirty page list */
29670  int nRef;                           /* Number of referenced pages */
29671  int nMax;                           /* Configured cache size */
29672  int szPage;                         /* Size of every page in this cache */
29673  int szExtra;                        /* Size of extra space for each page */
29674  int bPurgeable;                     /* True if pages are on backing store */
29675  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
29676  void *pStress;                      /* Argument to xStress */
29677  sqlite3_pcache *pCache;             /* Pluggable cache module */
29678  PgHdr *pPage1;                      /* Reference to page 1 */
29679};
29680
29681/*
29682** Some of the assert() macros in this code are too expensive to run
29683** even during normal debugging.  Use them only rarely on long-running
29684** tests.  Enable the expensive asserts using the
29685** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
29686*/
29687#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
29688# define expensive_assert(X)  assert(X)
29689#else
29690# define expensive_assert(X)
29691#endif
29692
29693/********************************** Linked List Management ********************/
29694
29695#if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
29696/*
29697** Check that the pCache->pSynced variable is set correctly. If it
29698** is not, either fail an assert or return zero. Otherwise, return
29699** non-zero. This is only used in debugging builds, as follows:
29700**
29701**   expensive_assert( pcacheCheckSynced(pCache) );
29702*/
29703static int pcacheCheckSynced(PCache *pCache){
29704  PgHdr *p;
29705  for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
29706    assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
29707  }
29708  return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
29709}
29710#endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
29711
29712/*
29713** Remove page pPage from the list of dirty pages.
29714*/
29715static void pcacheRemoveFromDirtyList(PgHdr *pPage){
29716  PCache *p = pPage->pCache;
29717
29718  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
29719  assert( pPage->pDirtyPrev || pPage==p->pDirty );
29720
29721  /* Update the PCache1.pSynced variable if necessary. */
29722  if( p->pSynced==pPage ){
29723    PgHdr *pSynced = pPage->pDirtyPrev;
29724    while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
29725      pSynced = pSynced->pDirtyPrev;
29726    }
29727    p->pSynced = pSynced;
29728  }
29729
29730  if( pPage->pDirtyNext ){
29731    pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
29732  }else{
29733    assert( pPage==p->pDirtyTail );
29734    p->pDirtyTail = pPage->pDirtyPrev;
29735  }
29736  if( pPage->pDirtyPrev ){
29737    pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
29738  }else{
29739    assert( pPage==p->pDirty );
29740    p->pDirty = pPage->pDirtyNext;
29741  }
29742  pPage->pDirtyNext = 0;
29743  pPage->pDirtyPrev = 0;
29744
29745  expensive_assert( pcacheCheckSynced(p) );
29746}
29747
29748/*
29749** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
29750** pPage).
29751*/
29752static void pcacheAddToDirtyList(PgHdr *pPage){
29753  PCache *p = pPage->pCache;
29754
29755  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
29756
29757  pPage->pDirtyNext = p->pDirty;
29758  if( pPage->pDirtyNext ){
29759    assert( pPage->pDirtyNext->pDirtyPrev==0 );
29760    pPage->pDirtyNext->pDirtyPrev = pPage;
29761  }
29762  p->pDirty = pPage;
29763  if( !p->pDirtyTail ){
29764    p->pDirtyTail = pPage;
29765  }
29766  if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
29767    p->pSynced = pPage;
29768  }
29769  expensive_assert( pcacheCheckSynced(p) );
29770}
29771
29772/*
29773** Wrapper around the pluggable caches xUnpin method. If the cache is
29774** being used for an in-memory database, this function is a no-op.
29775*/
29776static void pcacheUnpin(PgHdr *p){
29777  PCache *pCache = p->pCache;
29778  if( pCache->bPurgeable ){
29779    if( p->pgno==1 ){
29780      pCache->pPage1 = 0;
29781    }
29782    sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
29783  }
29784}
29785
29786/*************************************************** General Interfaces ******
29787**
29788** Initialize and shutdown the page cache subsystem. Neither of these
29789** functions are threadsafe.
29790*/
29791SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
29792  if( sqlite3GlobalConfig.pcache.xInit==0 ){
29793    sqlite3PCacheSetDefault();
29794  }
29795  return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
29796}
29797SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
29798  if( sqlite3GlobalConfig.pcache.xShutdown ){
29799    sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
29800  }
29801}
29802
29803/*
29804** Return the size in bytes of a PCache object.
29805*/
29806SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
29807
29808/*
29809** Create a new PCache object. Storage space to hold the object
29810** has already been allocated and is passed in as the p pointer.
29811** The caller discovers how much space needs to be allocated by
29812** calling sqlite3PcacheSize().
29813*/
29814SQLITE_PRIVATE void sqlite3PcacheOpen(
29815  int szPage,                  /* Size of every page */
29816  int szExtra,                 /* Extra space associated with each page */
29817  int bPurgeable,              /* True if pages are on backing store */
29818  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
29819  void *pStress,               /* Argument to xStress */
29820  PCache *p                    /* Preallocated space for the PCache */
29821){
29822  memset(p, 0, sizeof(PCache));
29823  p->szPage = szPage;
29824  p->szExtra = szExtra;
29825  p->bPurgeable = bPurgeable;
29826  p->xStress = xStress;
29827  p->pStress = pStress;
29828  p->nMax = 100;
29829}
29830
29831/*
29832** Change the page size for PCache object. The caller must ensure that there
29833** are no outstanding page references when this function is called.
29834*/
29835SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
29836  assert( pCache->nRef==0 && pCache->pDirty==0 );
29837  if( pCache->pCache ){
29838    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
29839    pCache->pCache = 0;
29840    pCache->pPage1 = 0;
29841  }
29842  pCache->szPage = szPage;
29843}
29844
29845/*
29846** Try to obtain a page from the cache.
29847*/
29848SQLITE_PRIVATE int sqlite3PcacheFetch(
29849  PCache *pCache,       /* Obtain the page from this cache */
29850  Pgno pgno,            /* Page number to obtain */
29851  int createFlag,       /* If true, create page if it does not exist already */
29852  PgHdr **ppPage        /* Write the page here */
29853){
29854  PgHdr *pPage = 0;
29855  int eCreate;
29856
29857  assert( pCache!=0 );
29858  assert( createFlag==1 || createFlag==0 );
29859  assert( pgno>0 );
29860
29861  /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
29862  ** allocate it now.
29863  */
29864  if( !pCache->pCache && createFlag ){
29865    sqlite3_pcache *p;
29866    int nByte;
29867    nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
29868    p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
29869    if( !p ){
29870      return SQLITE_NOMEM;
29871    }
29872    sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
29873    pCache->pCache = p;
29874  }
29875
29876  eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
29877  if( pCache->pCache ){
29878    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
29879  }
29880
29881  if( !pPage && eCreate==1 ){
29882    PgHdr *pPg;
29883
29884    /* Find a dirty page to write-out and recycle. First try to find a
29885    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
29886    ** cleared), but if that is not possible settle for any other
29887    ** unreferenced dirty page.
29888    */
29889    expensive_assert( pcacheCheckSynced(pCache) );
29890    for(pPg=pCache->pSynced;
29891        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
29892        pPg=pPg->pDirtyPrev
29893    );
29894    pCache->pSynced = pPg;
29895    if( !pPg ){
29896      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
29897    }
29898    if( pPg ){
29899      int rc;
29900      rc = pCache->xStress(pCache->pStress, pPg);
29901      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
29902        return rc;
29903      }
29904    }
29905
29906    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
29907  }
29908
29909  if( pPage ){
29910    if( !pPage->pData ){
29911      memset(pPage, 0, sizeof(PgHdr) + pCache->szExtra);
29912      pPage->pExtra = (void*)&pPage[1];
29913      pPage->pData = (void *)&((char *)pPage)[sizeof(PgHdr) + pCache->szExtra];
29914      pPage->pCache = pCache;
29915      pPage->pgno = pgno;
29916    }
29917    assert( pPage->pCache==pCache );
29918    assert( pPage->pgno==pgno );
29919    assert( pPage->pExtra==(void *)&pPage[1] );
29920
29921    if( 0==pPage->nRef ){
29922      pCache->nRef++;
29923    }
29924    pPage->nRef++;
29925    if( pgno==1 ){
29926      pCache->pPage1 = pPage;
29927    }
29928  }
29929  *ppPage = pPage;
29930  return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
29931}
29932
29933/*
29934** Decrement the reference count on a page. If the page is clean and the
29935** reference count drops to 0, then it is made elible for recycling.
29936*/
29937SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
29938  assert( p->nRef>0 );
29939  p->nRef--;
29940  if( p->nRef==0 ){
29941    PCache *pCache = p->pCache;
29942    pCache->nRef--;
29943    if( (p->flags&PGHDR_DIRTY)==0 ){
29944      pcacheUnpin(p);
29945    }else{
29946      /* Move the page to the head of the dirty list. */
29947      pcacheRemoveFromDirtyList(p);
29948      pcacheAddToDirtyList(p);
29949    }
29950  }
29951}
29952
29953/*
29954** Increase the reference count of a supplied page by 1.
29955*/
29956SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
29957  assert(p->nRef>0);
29958  p->nRef++;
29959}
29960
29961/*
29962** Drop a page from the cache. There must be exactly one reference to the
29963** page. This function deletes that reference, so after it returns the
29964** page pointed to by p is invalid.
29965*/
29966SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
29967  PCache *pCache;
29968  assert( p->nRef==1 );
29969  if( p->flags&PGHDR_DIRTY ){
29970    pcacheRemoveFromDirtyList(p);
29971  }
29972  pCache = p->pCache;
29973  pCache->nRef--;
29974  if( p->pgno==1 ){
29975    pCache->pPage1 = 0;
29976  }
29977  sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
29978}
29979
29980/*
29981** Make sure the page is marked as dirty. If it isn't dirty already,
29982** make it so.
29983*/
29984SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
29985  p->flags &= ~PGHDR_DONT_WRITE;
29986  assert( p->nRef>0 );
29987  if( 0==(p->flags & PGHDR_DIRTY) ){
29988    p->flags |= PGHDR_DIRTY;
29989    pcacheAddToDirtyList( p);
29990  }
29991}
29992
29993/*
29994** Make sure the page is marked as clean. If it isn't clean already,
29995** make it so.
29996*/
29997SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
29998  if( (p->flags & PGHDR_DIRTY) ){
29999    pcacheRemoveFromDirtyList(p);
30000    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
30001    if( p->nRef==0 ){
30002      pcacheUnpin(p);
30003    }
30004  }
30005}
30006
30007/*
30008** Make every page in the cache clean.
30009*/
30010SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
30011  PgHdr *p;
30012  while( (p = pCache->pDirty)!=0 ){
30013    sqlite3PcacheMakeClean(p);
30014  }
30015}
30016
30017/*
30018** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
30019*/
30020SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
30021  PgHdr *p;
30022  for(p=pCache->pDirty; p; p=p->pDirtyNext){
30023    p->flags &= ~PGHDR_NEED_SYNC;
30024  }
30025  pCache->pSynced = pCache->pDirtyTail;
30026}
30027
30028/*
30029** Change the page number of page p to newPgno.
30030*/
30031SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
30032  PCache *pCache = p->pCache;
30033  assert( p->nRef>0 );
30034  assert( newPgno>0 );
30035  sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
30036  p->pgno = newPgno;
30037  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
30038    pcacheRemoveFromDirtyList(p);
30039    pcacheAddToDirtyList(p);
30040  }
30041}
30042
30043/*
30044** Drop every cache entry whose page number is greater than "pgno". The
30045** caller must ensure that there are no outstanding references to any pages
30046** other than page 1 with a page number greater than pgno.
30047**
30048** If there is a reference to page 1 and the pgno parameter passed to this
30049** function is 0, then the data area associated with page 1 is zeroed, but
30050** the page object is not dropped.
30051*/
30052SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
30053  if( pCache->pCache ){
30054    PgHdr *p;
30055    PgHdr *pNext;
30056    for(p=pCache->pDirty; p; p=pNext){
30057      pNext = p->pDirtyNext;
30058      if( p->pgno>pgno ){
30059        assert( p->flags&PGHDR_DIRTY );
30060        sqlite3PcacheMakeClean(p);
30061      }
30062    }
30063    if( pgno==0 && pCache->pPage1 ){
30064      memset(pCache->pPage1->pData, 0, pCache->szPage);
30065      pgno = 1;
30066    }
30067    sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
30068  }
30069}
30070
30071/*
30072** Close a cache.
30073*/
30074SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
30075  if( pCache->pCache ){
30076    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
30077  }
30078}
30079
30080/*
30081** Discard the contents of the cache.
30082*/
30083SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
30084  sqlite3PcacheTruncate(pCache, 0);
30085}
30086
30087/*
30088** Merge two lists of pages connected by pDirty and in pgno order.
30089** Do not both fixing the pDirtyPrev pointers.
30090*/
30091static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
30092  PgHdr result, *pTail;
30093  pTail = &result;
30094  while( pA && pB ){
30095    if( pA->pgno<pB->pgno ){
30096      pTail->pDirty = pA;
30097      pTail = pA;
30098      pA = pA->pDirty;
30099    }else{
30100      pTail->pDirty = pB;
30101      pTail = pB;
30102      pB = pB->pDirty;
30103    }
30104  }
30105  if( pA ){
30106    pTail->pDirty = pA;
30107  }else if( pB ){
30108    pTail->pDirty = pB;
30109  }else{
30110    pTail->pDirty = 0;
30111  }
30112  return result.pDirty;
30113}
30114
30115/*
30116** Sort the list of pages in accending order by pgno.  Pages are
30117** connected by pDirty pointers.  The pDirtyPrev pointers are
30118** corrupted by this sort.
30119**
30120** Since there cannot be more than 2^31 distinct pages in a database,
30121** there cannot be more than 31 buckets required by the merge sorter.
30122** One extra bucket is added to catch overflow in case something
30123** ever changes to make the previous sentence incorrect.
30124*/
30125#define N_SORT_BUCKET  32
30126static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
30127  PgHdr *a[N_SORT_BUCKET], *p;
30128  int i;
30129  memset(a, 0, sizeof(a));
30130  while( pIn ){
30131    p = pIn;
30132    pIn = p->pDirty;
30133    p->pDirty = 0;
30134    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
30135      if( a[i]==0 ){
30136        a[i] = p;
30137        break;
30138      }else{
30139        p = pcacheMergeDirtyList(a[i], p);
30140        a[i] = 0;
30141      }
30142    }
30143    if( NEVER(i==N_SORT_BUCKET-1) ){
30144      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
30145      ** the input list.  But that is impossible.
30146      */
30147      a[i] = pcacheMergeDirtyList(a[i], p);
30148    }
30149  }
30150  p = a[0];
30151  for(i=1; i<N_SORT_BUCKET; i++){
30152    p = pcacheMergeDirtyList(p, a[i]);
30153  }
30154  return p;
30155}
30156
30157/*
30158** Return a list of all dirty pages in the cache, sorted by page number.
30159*/
30160SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
30161  PgHdr *p;
30162  for(p=pCache->pDirty; p; p=p->pDirtyNext){
30163    p->pDirty = p->pDirtyNext;
30164  }
30165  return pcacheSortDirtyList(pCache->pDirty);
30166}
30167
30168/*
30169** Return the total number of referenced pages held by the cache.
30170*/
30171SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
30172  return pCache->nRef;
30173}
30174
30175/*
30176** Return the number of references to the page supplied as an argument.
30177*/
30178SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
30179  return p->nRef;
30180}
30181
30182/*
30183** Return the total number of pages in the cache.
30184*/
30185SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
30186  int nPage = 0;
30187  if( pCache->pCache ){
30188    nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
30189  }
30190  return nPage;
30191}
30192
30193#ifdef SQLITE_TEST
30194/*
30195** Get the suggested cache-size value.
30196*/
30197SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
30198  return pCache->nMax;
30199}
30200#endif
30201
30202/*
30203** Set the suggested cache-size value.
30204*/
30205SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
30206  pCache->nMax = mxPage;
30207  if( pCache->pCache ){
30208    sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
30209  }
30210}
30211
30212#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
30213/*
30214** For all dirty pages currently in the cache, invoke the specified
30215** callback. This is only used if the SQLITE_CHECK_PAGES macro is
30216** defined.
30217*/
30218SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
30219  PgHdr *pDirty;
30220  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
30221    xIter(pDirty);
30222  }
30223}
30224#endif
30225
30226/************** End of pcache.c **********************************************/
30227/************** Begin file pcache1.c *****************************************/
30228/*
30229** 2008 November 05
30230**
30231** The author disclaims copyright to this source code.  In place of
30232** a legal notice, here is a blessing:
30233**
30234**    May you do good and not evil.
30235**    May you find forgiveness for yourself and forgive others.
30236**    May you share freely, never taking more than you give.
30237**
30238*************************************************************************
30239**
30240** This file implements the default page cache implementation (the
30241** sqlite3_pcache interface). It also contains part of the implementation
30242** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
30243** If the default page cache implementation is overriden, then neither of
30244** these two features are available.
30245*/
30246
30247
30248typedef struct PCache1 PCache1;
30249typedef struct PgHdr1 PgHdr1;
30250typedef struct PgFreeslot PgFreeslot;
30251
30252/* Pointers to structures of this type are cast and returned as
30253** opaque sqlite3_pcache* handles
30254*/
30255struct PCache1 {
30256  /* Cache configuration parameters. Page size (szPage) and the purgeable
30257  ** flag (bPurgeable) are set when the cache is created. nMax may be
30258  ** modified at any time by a call to the pcache1CacheSize() method.
30259  ** The global mutex must be held when accessing nMax.
30260  */
30261  int szPage;                         /* Size of allocated pages in bytes */
30262  int bPurgeable;                     /* True if cache is purgeable */
30263  unsigned int nMin;                  /* Minimum number of pages reserved */
30264  unsigned int nMax;                  /* Configured "cache_size" value */
30265
30266  /* Hash table of all pages. The following variables may only be accessed
30267  ** when the accessor is holding the global mutex (see pcache1EnterMutex()
30268  ** and pcache1LeaveMutex()).
30269  */
30270  unsigned int nRecyclable;           /* Number of pages in the LRU list */
30271  unsigned int nPage;                 /* Total number of pages in apHash */
30272  unsigned int nHash;                 /* Number of slots in apHash[] */
30273  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
30274
30275  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
30276};
30277
30278/*
30279** Each cache entry is represented by an instance of the following
30280** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
30281** directly before this structure in memory (see the PGHDR1_TO_PAGE()
30282** macro below).
30283*/
30284struct PgHdr1 {
30285  unsigned int iKey;             /* Key value (page number) */
30286  PgHdr1 *pNext;                 /* Next in hash table chain */
30287  PCache1 *pCache;               /* Cache that currently owns this page */
30288  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
30289  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
30290};
30291
30292/*
30293** Free slots in the allocator used to divide up the buffer provided using
30294** the SQLITE_CONFIG_PAGECACHE mechanism.
30295*/
30296struct PgFreeslot {
30297  PgFreeslot *pNext;  /* Next free slot */
30298};
30299
30300/*
30301** Global data used by this cache.
30302*/
30303static SQLITE_WSD struct PCacheGlobal {
30304  sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
30305
30306  int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
30307  int nMinPage;                       /* Sum of nMinPage for purgeable caches */
30308  int nCurrentPage;                   /* Number of purgeable pages allocated */
30309  PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */
30310
30311  /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
30312  int szSlot;                         /* Size of each free slot */
30313  void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
30314  PgFreeslot *pFree;                  /* Free page blocks */
30315  int isInit;                         /* True if initialized */
30316} pcache1_g;
30317
30318/*
30319** All code in this file should access the global structure above via the
30320** alias "pcache1". This ensures that the WSD emulation is used when
30321** compiling for systems that do not support real WSD.
30322*/
30323#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
30324
30325/*
30326** When a PgHdr1 structure is allocated, the associated PCache1.szPage
30327** bytes of data are located directly before it in memory (i.e. the total
30328** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
30329** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
30330** an argument and returns a pointer to the associated block of szPage
30331** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
30332** a pointer to a block of szPage bytes of data and the return value is
30333** a pointer to the associated PgHdr1 structure.
30334**
30335**   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
30336*/
30337#define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
30338#define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
30339
30340/*
30341** Macros to enter and leave the global LRU mutex.
30342*/
30343#define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
30344#define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
30345
30346/******************************************************************************/
30347/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
30348
30349/*
30350** This function is called during initialization if a static buffer is
30351** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
30352** verb to sqlite3_config(). Parameter pBuf points to an allocation large
30353** enough to contain 'n' buffers of 'sz' bytes each.
30354*/
30355SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
30356  if( pcache1.isInit ){
30357    PgFreeslot *p;
30358    sz = ROUNDDOWN8(sz);
30359    pcache1.szSlot = sz;
30360    pcache1.pStart = pBuf;
30361    pcache1.pFree = 0;
30362    while( n-- ){
30363      p = (PgFreeslot*)pBuf;
30364      p->pNext = pcache1.pFree;
30365      pcache1.pFree = p;
30366      pBuf = (void*)&((char*)pBuf)[sz];
30367    }
30368    pcache1.pEnd = pBuf;
30369  }
30370}
30371
30372/*
30373** Malloc function used within this file to allocate space from the buffer
30374** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
30375** such buffer exists or there is no space left in it, this function falls
30376** back to sqlite3Malloc().
30377*/
30378static void *pcache1Alloc(int nByte){
30379  void *p;
30380  assert( sqlite3_mutex_held(pcache1.mutex) );
30381  if( nByte<=pcache1.szSlot && pcache1.pFree ){
30382    assert( pcache1.isInit );
30383    p = (PgHdr1 *)pcache1.pFree;
30384    pcache1.pFree = pcache1.pFree->pNext;
30385    sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
30386    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
30387  }else{
30388
30389    /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
30390    ** global pcache mutex and unlock the pager-cache object pCache. This is
30391    ** so that if the attempt to allocate a new buffer causes the the
30392    ** configured soft-heap-limit to be breached, it will be possible to
30393    ** reclaim memory from this pager-cache.
30394    */
30395    pcache1LeaveMutex();
30396    p = sqlite3Malloc(nByte);
30397    pcache1EnterMutex();
30398    if( p ){
30399      int sz = sqlite3MallocSize(p);
30400      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
30401    }
30402  }
30403  return p;
30404}
30405
30406/*
30407** Free an allocated buffer obtained from pcache1Alloc().
30408*/
30409static void pcache1Free(void *p){
30410  assert( sqlite3_mutex_held(pcache1.mutex) );
30411  if( p==0 ) return;
30412  if( p>=pcache1.pStart && p<pcache1.pEnd ){
30413    PgFreeslot *pSlot;
30414    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
30415    pSlot = (PgFreeslot*)p;
30416    pSlot->pNext = pcache1.pFree;
30417    pcache1.pFree = pSlot;
30418  }else{
30419    int iSize = sqlite3MallocSize(p);
30420    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
30421    sqlite3_free(p);
30422  }
30423}
30424
30425/*
30426** Allocate a new page object initially associated with cache pCache.
30427*/
30428static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
30429  int nByte = sizeof(PgHdr1) + pCache->szPage;
30430  void *pPg = pcache1Alloc(nByte);
30431  PgHdr1 *p;
30432  if( pPg ){
30433    p = PAGE_TO_PGHDR1(pCache, pPg);
30434    if( pCache->bPurgeable ){
30435      pcache1.nCurrentPage++;
30436    }
30437  }else{
30438    p = 0;
30439  }
30440  return p;
30441}
30442
30443/*
30444** Free a page object allocated by pcache1AllocPage().
30445**
30446** The pointer is allowed to be NULL, which is prudent.  But it turns out
30447** that the current implementation happens to never call this routine
30448** with a NULL pointer, so we mark the NULL test with ALWAYS().
30449*/
30450static void pcache1FreePage(PgHdr1 *p){
30451  if( ALWAYS(p) ){
30452    if( p->pCache->bPurgeable ){
30453      pcache1.nCurrentPage--;
30454    }
30455    pcache1Free(PGHDR1_TO_PAGE(p));
30456  }
30457}
30458
30459/*
30460** Malloc function used by SQLite to obtain space from the buffer configured
30461** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
30462** exists, this function falls back to sqlite3Malloc().
30463*/
30464SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
30465  void *p;
30466  pcache1EnterMutex();
30467  p = pcache1Alloc(sz);
30468  pcache1LeaveMutex();
30469  return p;
30470}
30471
30472/*
30473** Free an allocated buffer obtained from sqlite3PageMalloc().
30474*/
30475SQLITE_PRIVATE void sqlite3PageFree(void *p){
30476  pcache1EnterMutex();
30477  pcache1Free(p);
30478  pcache1LeaveMutex();
30479}
30480
30481/******************************************************************************/
30482/******** General Implementation Functions ************************************/
30483
30484/*
30485** This function is used to resize the hash table used by the cache passed
30486** as the first argument.
30487**
30488** The global mutex must be held when this function is called.
30489*/
30490static int pcache1ResizeHash(PCache1 *p){
30491  PgHdr1 **apNew;
30492  unsigned int nNew;
30493  unsigned int i;
30494
30495  assert( sqlite3_mutex_held(pcache1.mutex) );
30496
30497  nNew = p->nHash*2;
30498  if( nNew<256 ){
30499    nNew = 256;
30500  }
30501
30502  pcache1LeaveMutex();
30503  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
30504  apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
30505  if( p->nHash ){ sqlite3EndBenignMalloc(); }
30506  pcache1EnterMutex();
30507  if( apNew ){
30508    memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
30509    for(i=0; i<p->nHash; i++){
30510      PgHdr1 *pPage;
30511      PgHdr1 *pNext = p->apHash[i];
30512      while( (pPage = pNext)!=0 ){
30513        unsigned int h = pPage->iKey % nNew;
30514        pNext = pPage->pNext;
30515        pPage->pNext = apNew[h];
30516        apNew[h] = pPage;
30517      }
30518    }
30519    sqlite3_free(p->apHash);
30520    p->apHash = apNew;
30521    p->nHash = nNew;
30522  }
30523
30524  return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
30525}
30526
30527/*
30528** This function is used internally to remove the page pPage from the
30529** global LRU list, if is part of it. If pPage is not part of the global
30530** LRU list, then this function is a no-op.
30531**
30532** The global mutex must be held when this function is called.
30533*/
30534static void pcache1PinPage(PgHdr1 *pPage){
30535  assert( sqlite3_mutex_held(pcache1.mutex) );
30536  if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
30537    if( pPage->pLruPrev ){
30538      pPage->pLruPrev->pLruNext = pPage->pLruNext;
30539    }
30540    if( pPage->pLruNext ){
30541      pPage->pLruNext->pLruPrev = pPage->pLruPrev;
30542    }
30543    if( pcache1.pLruHead==pPage ){
30544      pcache1.pLruHead = pPage->pLruNext;
30545    }
30546    if( pcache1.pLruTail==pPage ){
30547      pcache1.pLruTail = pPage->pLruPrev;
30548    }
30549    pPage->pLruNext = 0;
30550    pPage->pLruPrev = 0;
30551    pPage->pCache->nRecyclable--;
30552  }
30553}
30554
30555
30556/*
30557** Remove the page supplied as an argument from the hash table
30558** (PCache1.apHash structure) that it is currently stored in.
30559**
30560** The global mutex must be held when this function is called.
30561*/
30562static void pcache1RemoveFromHash(PgHdr1 *pPage){
30563  unsigned int h;
30564  PCache1 *pCache = pPage->pCache;
30565  PgHdr1 **pp;
30566
30567  h = pPage->iKey % pCache->nHash;
30568  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
30569  *pp = (*pp)->pNext;
30570
30571  pCache->nPage--;
30572}
30573
30574/*
30575** If there are currently more than pcache.nMaxPage pages allocated, try
30576** to recycle pages to reduce the number allocated to pcache.nMaxPage.
30577*/
30578static void pcache1EnforceMaxPage(void){
30579  assert( sqlite3_mutex_held(pcache1.mutex) );
30580  while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
30581    PgHdr1 *p = pcache1.pLruTail;
30582    pcache1PinPage(p);
30583    pcache1RemoveFromHash(p);
30584    pcache1FreePage(p);
30585  }
30586}
30587
30588/*
30589** Discard all pages from cache pCache with a page number (key value)
30590** greater than or equal to iLimit. Any pinned pages that meet this
30591** criteria are unpinned before they are discarded.
30592**
30593** The global mutex must be held when this function is called.
30594*/
30595static void pcache1TruncateUnsafe(
30596  PCache1 *pCache,
30597  unsigned int iLimit
30598){
30599  TESTONLY( unsigned int nPage = 0; )      /* Used to assert pCache->nPage is correct */
30600  unsigned int h;
30601  assert( sqlite3_mutex_held(pcache1.mutex) );
30602  for(h=0; h<pCache->nHash; h++){
30603    PgHdr1 **pp = &pCache->apHash[h];
30604    PgHdr1 *pPage;
30605    while( (pPage = *pp)!=0 ){
30606      if( pPage->iKey>=iLimit ){
30607        pCache->nPage--;
30608        *pp = pPage->pNext;
30609        pcache1PinPage(pPage);
30610        pcache1FreePage(pPage);
30611      }else{
30612        pp = &pPage->pNext;
30613        TESTONLY( nPage++; )
30614      }
30615    }
30616  }
30617  assert( pCache->nPage==nPage );
30618}
30619
30620/******************************************************************************/
30621/******** sqlite3_pcache Methods **********************************************/
30622
30623/*
30624** Implementation of the sqlite3_pcache.xInit method.
30625*/
30626static int pcache1Init(void *NotUsed){
30627  UNUSED_PARAMETER(NotUsed);
30628  assert( pcache1.isInit==0 );
30629  memset(&pcache1, 0, sizeof(pcache1));
30630  if( sqlite3GlobalConfig.bCoreMutex ){
30631    pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
30632  }
30633  pcache1.isInit = 1;
30634  return SQLITE_OK;
30635}
30636
30637/*
30638** Implementation of the sqlite3_pcache.xShutdown method.
30639** Note that the static mutex allocated in xInit does
30640** not need to be freed.
30641*/
30642static void pcache1Shutdown(void *NotUsed){
30643  UNUSED_PARAMETER(NotUsed);
30644  assert( pcache1.isInit!=0 );
30645  memset(&pcache1, 0, sizeof(pcache1));
30646}
30647
30648/*
30649** Implementation of the sqlite3_pcache.xCreate method.
30650**
30651** Allocate a new cache.
30652*/
30653static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
30654  PCache1 *pCache;
30655
30656  pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
30657  if( pCache ){
30658    memset(pCache, 0, sizeof(PCache1));
30659    pCache->szPage = szPage;
30660    pCache->bPurgeable = (bPurgeable ? 1 : 0);
30661    if( bPurgeable ){
30662      pCache->nMin = 10;
30663      pcache1EnterMutex();
30664      pcache1.nMinPage += pCache->nMin;
30665      pcache1LeaveMutex();
30666    }
30667  }
30668  return (sqlite3_pcache *)pCache;
30669}
30670
30671/*
30672** Implementation of the sqlite3_pcache.xCachesize method.
30673**
30674** Configure the cache_size limit for a cache.
30675*/
30676static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
30677  PCache1 *pCache = (PCache1 *)p;
30678  if( pCache->bPurgeable ){
30679    pcache1EnterMutex();
30680    pcache1.nMaxPage += (nMax - pCache->nMax);
30681    pCache->nMax = nMax;
30682    pcache1EnforceMaxPage();
30683    pcache1LeaveMutex();
30684  }
30685}
30686
30687/*
30688** Implementation of the sqlite3_pcache.xPagecount method.
30689*/
30690static int pcache1Pagecount(sqlite3_pcache *p){
30691  int n;
30692  pcache1EnterMutex();
30693  n = ((PCache1 *)p)->nPage;
30694  pcache1LeaveMutex();
30695  return n;
30696}
30697
30698/*
30699** Implementation of the sqlite3_pcache.xFetch method.
30700**
30701** Fetch a page by key value.
30702**
30703** Whether or not a new page may be allocated by this function depends on
30704** the value of the createFlag argument.  0 means do not allocate a new
30705** page.  1 means allocate a new page if space is easily available.  2
30706** means to try really hard to allocate a new page.
30707**
30708** For a non-purgeable cache (a cache used as the storage for an in-memory
30709** database) there is really no difference between createFlag 1 and 2.  So
30710** the calling function (pcache.c) will never have a createFlag of 1 on
30711** a non-purgable cache.
30712**
30713** There are three different approaches to obtaining space for a page,
30714** depending on the value of parameter createFlag (which may be 0, 1 or 2).
30715**
30716**   1. Regardless of the value of createFlag, the cache is searched for a
30717**      copy of the requested page. If one is found, it is returned.
30718**
30719**   2. If createFlag==0 and the page is not already in the cache, NULL is
30720**      returned.
30721**
30722**   3. If createFlag is 1, and the page is not already in the cache,
30723**      and if either of the following are true, return NULL:
30724**
30725**       (a) the number of pages pinned by the cache is greater than
30726**           PCache1.nMax, or
30727**       (b) the number of pages pinned by the cache is greater than
30728**           the sum of nMax for all purgeable caches, less the sum of
30729**           nMin for all other purgeable caches.
30730**
30731**   4. If none of the first three conditions apply and the cache is marked
30732**      as purgeable, and if one of the following is true:
30733**
30734**       (a) The number of pages allocated for the cache is already
30735**           PCache1.nMax, or
30736**
30737**       (b) The number of pages allocated for all purgeable caches is
30738**           already equal to or greater than the sum of nMax for all
30739**           purgeable caches,
30740**
30741**      then attempt to recycle a page from the LRU list. If it is the right
30742**      size, return the recycled buffer. Otherwise, free the buffer and
30743**      proceed to step 5.
30744**
30745**   5. Otherwise, allocate and return a new page buffer.
30746*/
30747static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
30748  unsigned int nPinned;
30749  PCache1 *pCache = (PCache1 *)p;
30750  PgHdr1 *pPage = 0;
30751
30752  assert( pCache->bPurgeable || createFlag!=1 );
30753  pcache1EnterMutex();
30754  if( createFlag==1 ) sqlite3BeginBenignMalloc();
30755
30756  /* Search the hash table for an existing entry. */
30757  if( pCache->nHash>0 ){
30758    unsigned int h = iKey % pCache->nHash;
30759    for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
30760  }
30761
30762  if( pPage || createFlag==0 ){
30763    pcache1PinPage(pPage);
30764    goto fetch_out;
30765  }
30766
30767  /* Step 3 of header comment. */
30768  nPinned = pCache->nPage - pCache->nRecyclable;
30769  if( createFlag==1 && (
30770        nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
30771     || nPinned>=(pCache->nMax * 9 / 10)
30772  )){
30773    goto fetch_out;
30774  }
30775
30776  if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
30777    goto fetch_out;
30778  }
30779
30780  /* Step 4. Try to recycle a page buffer if appropriate. */
30781  if( pCache->bPurgeable && pcache1.pLruTail && (
30782     (pCache->nPage+1>=pCache->nMax) || pcache1.nCurrentPage>=pcache1.nMaxPage
30783  )){
30784    pPage = pcache1.pLruTail;
30785    pcache1RemoveFromHash(pPage);
30786    pcache1PinPage(pPage);
30787    if( pPage->pCache->szPage!=pCache->szPage ){
30788      pcache1FreePage(pPage);
30789      pPage = 0;
30790    }else{
30791      pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
30792    }
30793  }
30794
30795  /* Step 5. If a usable page buffer has still not been found,
30796  ** attempt to allocate a new one.
30797  */
30798  if( !pPage ){
30799    pPage = pcache1AllocPage(pCache);
30800  }
30801
30802  if( pPage ){
30803    unsigned int h = iKey % pCache->nHash;
30804    pCache->nPage++;
30805    pPage->iKey = iKey;
30806    pPage->pNext = pCache->apHash[h];
30807    pPage->pCache = pCache;
30808    pPage->pLruPrev = 0;
30809    pPage->pLruNext = 0;
30810    *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
30811    pCache->apHash[h] = pPage;
30812  }
30813
30814fetch_out:
30815  if( pPage && iKey>pCache->iMaxKey ){
30816    pCache->iMaxKey = iKey;
30817  }
30818  if( createFlag==1 ) sqlite3EndBenignMalloc();
30819  pcache1LeaveMutex();
30820  return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
30821}
30822
30823
30824/*
30825** Implementation of the sqlite3_pcache.xUnpin method.
30826**
30827** Mark a page as unpinned (eligible for asynchronous recycling).
30828*/
30829static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
30830  PCache1 *pCache = (PCache1 *)p;
30831  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
30832
30833  assert( pPage->pCache==pCache );
30834  pcache1EnterMutex();
30835
30836  /* It is an error to call this function if the page is already
30837  ** part of the global LRU list.
30838  */
30839  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
30840  assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
30841
30842  if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
30843    pcache1RemoveFromHash(pPage);
30844    pcache1FreePage(pPage);
30845  }else{
30846    /* Add the page to the global LRU list. Normally, the page is added to
30847    ** the head of the list (last page to be recycled). However, if the
30848    ** reuseUnlikely flag passed to this function is true, the page is added
30849    ** to the tail of the list (first page to be recycled).
30850    */
30851    if( pcache1.pLruHead ){
30852      pcache1.pLruHead->pLruPrev = pPage;
30853      pPage->pLruNext = pcache1.pLruHead;
30854      pcache1.pLruHead = pPage;
30855    }else{
30856      pcache1.pLruTail = pPage;
30857      pcache1.pLruHead = pPage;
30858    }
30859    pCache->nRecyclable++;
30860  }
30861
30862  pcache1LeaveMutex();
30863}
30864
30865/*
30866** Implementation of the sqlite3_pcache.xRekey method.
30867*/
30868static void pcache1Rekey(
30869  sqlite3_pcache *p,
30870  void *pPg,
30871  unsigned int iOld,
30872  unsigned int iNew
30873){
30874  PCache1 *pCache = (PCache1 *)p;
30875  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
30876  PgHdr1 **pp;
30877  unsigned int h;
30878  assert( pPage->iKey==iOld );
30879  assert( pPage->pCache==pCache );
30880
30881  pcache1EnterMutex();
30882
30883  h = iOld%pCache->nHash;
30884  pp = &pCache->apHash[h];
30885  while( (*pp)!=pPage ){
30886    pp = &(*pp)->pNext;
30887  }
30888  *pp = pPage->pNext;
30889
30890  h = iNew%pCache->nHash;
30891  pPage->iKey = iNew;
30892  pPage->pNext = pCache->apHash[h];
30893  pCache->apHash[h] = pPage;
30894  if( iNew>pCache->iMaxKey ){
30895    pCache->iMaxKey = iNew;
30896  }
30897
30898  pcache1LeaveMutex();
30899}
30900
30901/*
30902** Implementation of the sqlite3_pcache.xTruncate method.
30903**
30904** Discard all unpinned pages in the cache with a page number equal to
30905** or greater than parameter iLimit. Any pinned pages with a page number
30906** equal to or greater than iLimit are implicitly unpinned.
30907*/
30908static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
30909  PCache1 *pCache = (PCache1 *)p;
30910  pcache1EnterMutex();
30911  if( iLimit<=pCache->iMaxKey ){
30912    pcache1TruncateUnsafe(pCache, iLimit);
30913    pCache->iMaxKey = iLimit-1;
30914  }
30915  pcache1LeaveMutex();
30916}
30917
30918/*
30919** Implementation of the sqlite3_pcache.xDestroy method.
30920**
30921** Destroy a cache allocated using pcache1Create().
30922*/
30923static void pcache1Destroy(sqlite3_pcache *p){
30924  PCache1 *pCache = (PCache1 *)p;
30925  pcache1EnterMutex();
30926  pcache1TruncateUnsafe(pCache, 0);
30927  pcache1.nMaxPage -= pCache->nMax;
30928  pcache1.nMinPage -= pCache->nMin;
30929  pcache1EnforceMaxPage();
30930  pcache1LeaveMutex();
30931  sqlite3_free(pCache->apHash);
30932  sqlite3_free(pCache);
30933}
30934
30935/*
30936** This function is called during initialization (sqlite3_initialize()) to
30937** install the default pluggable cache module, assuming the user has not
30938** already provided an alternative.
30939*/
30940SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
30941  static sqlite3_pcache_methods defaultMethods = {
30942    0,                       /* pArg */
30943    pcache1Init,             /* xInit */
30944    pcache1Shutdown,         /* xShutdown */
30945    pcache1Create,           /* xCreate */
30946    pcache1Cachesize,        /* xCachesize */
30947    pcache1Pagecount,        /* xPagecount */
30948    pcache1Fetch,            /* xFetch */
30949    pcache1Unpin,            /* xUnpin */
30950    pcache1Rekey,            /* xRekey */
30951    pcache1Truncate,         /* xTruncate */
30952    pcache1Destroy           /* xDestroy */
30953  };
30954  sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
30955}
30956
30957#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
30958/*
30959** This function is called to free superfluous dynamically allocated memory
30960** held by the pager system. Memory in use by any SQLite pager allocated
30961** by the current thread may be sqlite3_free()ed.
30962**
30963** nReq is the number of bytes of memory required. Once this much has
30964** been released, the function returns. The return value is the total number
30965** of bytes of memory released.
30966*/
30967SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
30968  int nFree = 0;
30969  if( pcache1.pStart==0 ){
30970    PgHdr1 *p;
30971    pcache1EnterMutex();
30972    while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
30973      nFree += sqlite3MallocSize(PGHDR1_TO_PAGE(p));
30974      pcache1PinPage(p);
30975      pcache1RemoveFromHash(p);
30976      pcache1FreePage(p);
30977    }
30978    pcache1LeaveMutex();
30979  }
30980  return nFree;
30981}
30982#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
30983
30984#ifdef SQLITE_TEST
30985/*
30986** This function is used by test procedures to inspect the internal state
30987** of the global cache.
30988*/
30989SQLITE_PRIVATE void sqlite3PcacheStats(
30990  int *pnCurrent,      /* OUT: Total number of pages cached */
30991  int *pnMax,          /* OUT: Global maximum cache size */
30992  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
30993  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
30994){
30995  PgHdr1 *p;
30996  int nRecyclable = 0;
30997  for(p=pcache1.pLruHead; p; p=p->pLruNext){
30998    nRecyclable++;
30999  }
31000  *pnCurrent = pcache1.nCurrentPage;
31001  *pnMax = pcache1.nMaxPage;
31002  *pnMin = pcache1.nMinPage;
31003  *pnRecyclable = nRecyclable;
31004}
31005#endif
31006
31007/************** End of pcache1.c *********************************************/
31008/************** Begin file rowset.c ******************************************/
31009/*
31010** 2008 December 3
31011**
31012** The author disclaims copyright to this source code.  In place of
31013** a legal notice, here is a blessing:
31014**
31015**    May you do good and not evil.
31016**    May you find forgiveness for yourself and forgive others.
31017**    May you share freely, never taking more than you give.
31018**
31019*************************************************************************
31020**
31021** This module implements an object we call a "RowSet".
31022**
31023** The RowSet object is a collection of rowids.  Rowids
31024** are inserted into the RowSet in an arbitrary order.  Inserts
31025** can be intermixed with tests to see if a given rowid has been
31026** previously inserted into the RowSet.
31027**
31028** After all inserts are finished, it is possible to extract the
31029** elements of the RowSet in sorted order.  Once this extraction
31030** process has started, no new elements may be inserted.
31031**
31032** Hence, the primitive operations for a RowSet are:
31033**
31034**    CREATE
31035**    INSERT
31036**    TEST
31037**    SMALLEST
31038**    DESTROY
31039**
31040** The CREATE and DESTROY primitives are the constructor and destructor,
31041** obviously.  The INSERT primitive adds a new element to the RowSet.
31042** TEST checks to see if an element is already in the RowSet.  SMALLEST
31043** extracts the least value from the RowSet.
31044**
31045** The INSERT primitive might allocate additional memory.  Memory is
31046** allocated in chunks so most INSERTs do no allocation.  There is an
31047** upper bound on the size of allocated memory.  No memory is freed
31048** until DESTROY.
31049**
31050** The TEST primitive includes a "batch" number.  The TEST primitive
31051** will only see elements that were inserted before the last change
31052** in the batch number.  In other words, if an INSERT occurs between
31053** two TESTs where the TESTs have the same batch nubmer, then the
31054** value added by the INSERT will not be visible to the second TEST.
31055** The initial batch number is zero, so if the very first TEST contains
31056** a non-zero batch number, it will see all prior INSERTs.
31057**
31058** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
31059** that is attempted.
31060**
31061** The cost of an INSERT is roughly constant.  (Sometime new memory
31062** has to be allocated on an INSERT.)  The cost of a TEST with a new
31063** batch number is O(NlogN) where N is the number of elements in the RowSet.
31064** The cost of a TEST using the same batch number is O(logN).  The cost
31065** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
31066** primitives are constant time.  The cost of DESTROY is O(N).
31067**
31068** There is an added cost of O(N) when switching between TEST and
31069** SMALLEST primitives.
31070*/
31071
31072
31073/*
31074** Target size for allocation chunks.
31075*/
31076#define ROWSET_ALLOCATION_SIZE 1024
31077
31078/*
31079** The number of rowset entries per allocation chunk.
31080*/
31081#define ROWSET_ENTRY_PER_CHUNK  \
31082                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
31083
31084/*
31085** Each entry in a RowSet is an instance of the following object.
31086*/
31087struct RowSetEntry {
31088  i64 v;                        /* ROWID value for this entry */
31089  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
31090  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
31091};
31092
31093/*
31094** RowSetEntry objects are allocated in large chunks (instances of the
31095** following structure) to reduce memory allocation overhead.  The
31096** chunks are kept on a linked list so that they can be deallocated
31097** when the RowSet is destroyed.
31098*/
31099struct RowSetChunk {
31100  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
31101  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
31102};
31103
31104/*
31105** A RowSet in an instance of the following structure.
31106**
31107** A typedef of this structure if found in sqliteInt.h.
31108*/
31109struct RowSet {
31110  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
31111  sqlite3 *db;                   /* The database connection */
31112  struct RowSetEntry *pEntry;    /* List of entries using pRight */
31113  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
31114  struct RowSetEntry *pFresh;    /* Source of new entry objects */
31115  struct RowSetEntry *pTree;     /* Binary tree of entries */
31116  u16 nFresh;                    /* Number of objects on pFresh */
31117  u8 isSorted;                   /* True if pEntry is sorted */
31118  u8 iBatch;                     /* Current insert batch */
31119};
31120
31121/*
31122** Turn bulk memory into a RowSet object.  N bytes of memory
31123** are available at pSpace.  The db pointer is used as a memory context
31124** for any subsequent allocations that need to occur.
31125** Return a pointer to the new RowSet object.
31126**
31127** It must be the case that N is sufficient to make a Rowset.  If not
31128** an assertion fault occurs.
31129**
31130** If N is larger than the minimum, use the surplus as an initial
31131** allocation of entries available to be filled.
31132*/
31133SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
31134  RowSet *p;
31135  assert( N >= ROUND8(sizeof(*p)) );
31136  p = pSpace;
31137  p->pChunk = 0;
31138  p->db = db;
31139  p->pEntry = 0;
31140  p->pLast = 0;
31141  p->pTree = 0;
31142  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
31143  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
31144  p->isSorted = 1;
31145  p->iBatch = 0;
31146  return p;
31147}
31148
31149/*
31150** Deallocate all chunks from a RowSet.  This frees all memory that
31151** the RowSet has allocated over its lifetime.  This routine is
31152** the destructor for the RowSet.
31153*/
31154SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
31155  struct RowSetChunk *pChunk, *pNextChunk;
31156  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
31157    pNextChunk = pChunk->pNextChunk;
31158    sqlite3DbFree(p->db, pChunk);
31159  }
31160  p->pChunk = 0;
31161  p->nFresh = 0;
31162  p->pEntry = 0;
31163  p->pLast = 0;
31164  p->pTree = 0;
31165  p->isSorted = 1;
31166}
31167
31168/*
31169** Insert a new value into a RowSet.
31170**
31171** The mallocFailed flag of the database connection is set if a
31172** memory allocation fails.
31173*/
31174SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
31175  struct RowSetEntry *pEntry;  /* The new entry */
31176  struct RowSetEntry *pLast;   /* The last prior entry */
31177  assert( p!=0 );
31178  if( p->nFresh==0 ){
31179    struct RowSetChunk *pNew;
31180    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
31181    if( pNew==0 ){
31182      return;
31183    }
31184    pNew->pNextChunk = p->pChunk;
31185    p->pChunk = pNew;
31186    p->pFresh = pNew->aEntry;
31187    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
31188  }
31189  pEntry = p->pFresh++;
31190  p->nFresh--;
31191  pEntry->v = rowid;
31192  pEntry->pRight = 0;
31193  pLast = p->pLast;
31194  if( pLast ){
31195    if( p->isSorted && rowid<=pLast->v ){
31196      p->isSorted = 0;
31197    }
31198    pLast->pRight = pEntry;
31199  }else{
31200    assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
31201    p->pEntry = pEntry;
31202  }
31203  p->pLast = pEntry;
31204}
31205
31206/*
31207** Merge two lists of RowSetEntry objects.  Remove duplicates.
31208**
31209** The input lists are connected via pRight pointers and are
31210** assumed to each already be in sorted order.
31211*/
31212static struct RowSetEntry *rowSetMerge(
31213  struct RowSetEntry *pA,    /* First sorted list to be merged */
31214  struct RowSetEntry *pB     /* Second sorted list to be merged */
31215){
31216  struct RowSetEntry head;
31217  struct RowSetEntry *pTail;
31218
31219  pTail = &head;
31220  while( pA && pB ){
31221    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
31222    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
31223    if( pA->v<pB->v ){
31224      pTail->pRight = pA;
31225      pA = pA->pRight;
31226      pTail = pTail->pRight;
31227    }else if( pB->v<pA->v ){
31228      pTail->pRight = pB;
31229      pB = pB->pRight;
31230      pTail = pTail->pRight;
31231    }else{
31232      pA = pA->pRight;
31233    }
31234  }
31235  if( pA ){
31236    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
31237    pTail->pRight = pA;
31238  }else{
31239    assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
31240    pTail->pRight = pB;
31241  }
31242  return head.pRight;
31243}
31244
31245/*
31246** Sort all elements on the pEntry list of the RowSet into ascending order.
31247*/
31248static void rowSetSort(RowSet *p){
31249  unsigned int i;
31250  struct RowSetEntry *pEntry;
31251  struct RowSetEntry *aBucket[40];
31252
31253  assert( p->isSorted==0 );
31254  memset(aBucket, 0, sizeof(aBucket));
31255  while( p->pEntry ){
31256    pEntry = p->pEntry;
31257    p->pEntry = pEntry->pRight;
31258    pEntry->pRight = 0;
31259    for(i=0; aBucket[i]; i++){
31260      pEntry = rowSetMerge(aBucket[i], pEntry);
31261      aBucket[i] = 0;
31262    }
31263    aBucket[i] = pEntry;
31264  }
31265  pEntry = 0;
31266  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
31267    pEntry = rowSetMerge(pEntry, aBucket[i]);
31268  }
31269  p->pEntry = pEntry;
31270  p->pLast = 0;
31271  p->isSorted = 1;
31272}
31273
31274
31275/*
31276** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
31277** Convert this tree into a linked list connected by the pRight pointers
31278** and return pointers to the first and last elements of the new list.
31279*/
31280static void rowSetTreeToList(
31281  struct RowSetEntry *pIn,         /* Root of the input tree */
31282  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
31283  struct RowSetEntry **ppLast      /* Write tail of the output list here */
31284){
31285  assert( pIn!=0 );
31286  if( pIn->pLeft ){
31287    struct RowSetEntry *p;
31288    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
31289    p->pRight = pIn;
31290  }else{
31291    *ppFirst = pIn;
31292  }
31293  if( pIn->pRight ){
31294    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
31295  }else{
31296    *ppLast = pIn;
31297  }
31298  assert( (*ppLast)->pRight==0 );
31299}
31300
31301
31302/*
31303** Convert a sorted list of elements (connected by pRight) into a binary
31304** tree with depth of iDepth.  A depth of 1 means the tree contains a single
31305** node taken from the head of *ppList.  A depth of 2 means a tree with
31306** three nodes.  And so forth.
31307**
31308** Use as many entries from the input list as required and update the
31309** *ppList to point to the unused elements of the list.  If the input
31310** list contains too few elements, then construct an incomplete tree
31311** and leave *ppList set to NULL.
31312**
31313** Return a pointer to the root of the constructed binary tree.
31314*/
31315static struct RowSetEntry *rowSetNDeepTree(
31316  struct RowSetEntry **ppList,
31317  int iDepth
31318){
31319  struct RowSetEntry *p;         /* Root of the new tree */
31320  struct RowSetEntry *pLeft;     /* Left subtree */
31321  if( *ppList==0 ){
31322    return 0;
31323  }
31324  if( iDepth==1 ){
31325    p = *ppList;
31326    *ppList = p->pRight;
31327    p->pLeft = p->pRight = 0;
31328    return p;
31329  }
31330  pLeft = rowSetNDeepTree(ppList, iDepth-1);
31331  p = *ppList;
31332  if( p==0 ){
31333    return pLeft;
31334  }
31335  p->pLeft = pLeft;
31336  *ppList = p->pRight;
31337  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
31338  return p;
31339}
31340
31341/*
31342** Convert a sorted list of elements into a binary tree. Make the tree
31343** as deep as it needs to be in order to contain the entire list.
31344*/
31345static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
31346  int iDepth;           /* Depth of the tree so far */
31347  struct RowSetEntry *p;       /* Current tree root */
31348  struct RowSetEntry *pLeft;   /* Left subtree */
31349
31350  assert( pList!=0 );
31351  p = pList;
31352  pList = p->pRight;
31353  p->pLeft = p->pRight = 0;
31354  for(iDepth=1; pList; iDepth++){
31355    pLeft = p;
31356    p = pList;
31357    pList = p->pRight;
31358    p->pLeft = pLeft;
31359    p->pRight = rowSetNDeepTree(&pList, iDepth);
31360  }
31361  return p;
31362}
31363
31364/*
31365** Convert the list in p->pEntry into a sorted list if it is not
31366** sorted already.  If there is a binary tree on p->pTree, then
31367** convert it into a list too and merge it into the p->pEntry list.
31368*/
31369static void rowSetToList(RowSet *p){
31370  if( !p->isSorted ){
31371    rowSetSort(p);
31372  }
31373  if( p->pTree ){
31374    struct RowSetEntry *pHead, *pTail;
31375    rowSetTreeToList(p->pTree, &pHead, &pTail);
31376    p->pTree = 0;
31377    p->pEntry = rowSetMerge(p->pEntry, pHead);
31378  }
31379}
31380
31381/*
31382** Extract the smallest element from the RowSet.
31383** Write the element into *pRowid.  Return 1 on success.  Return
31384** 0 if the RowSet is already empty.
31385**
31386** After this routine has been called, the sqlite3RowSetInsert()
31387** routine may not be called again.
31388*/
31389SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
31390  rowSetToList(p);
31391  if( p->pEntry ){
31392    *pRowid = p->pEntry->v;
31393    p->pEntry = p->pEntry->pRight;
31394    if( p->pEntry==0 ){
31395      sqlite3RowSetClear(p);
31396    }
31397    return 1;
31398  }else{
31399    return 0;
31400  }
31401}
31402
31403/*
31404** Check to see if element iRowid was inserted into the the rowset as
31405** part of any insert batch prior to iBatch.  Return 1 or 0.
31406*/
31407SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
31408  struct RowSetEntry *p;
31409  if( iBatch!=pRowSet->iBatch ){
31410    if( pRowSet->pEntry ){
31411      rowSetToList(pRowSet);
31412      pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
31413      pRowSet->pEntry = 0;
31414      pRowSet->pLast = 0;
31415    }
31416    pRowSet->iBatch = iBatch;
31417  }
31418  p = pRowSet->pTree;
31419  while( p ){
31420    if( p->v<iRowid ){
31421      p = p->pRight;
31422    }else if( p->v>iRowid ){
31423      p = p->pLeft;
31424    }else{
31425      return 1;
31426    }
31427  }
31428  return 0;
31429}
31430
31431/************** End of rowset.c **********************************************/
31432/************** Begin file pager.c *******************************************/
31433/*
31434** 2001 September 15
31435**
31436** The author disclaims copyright to this source code.  In place of
31437** a legal notice, here is a blessing:
31438**
31439**    May you do good and not evil.
31440**    May you find forgiveness for yourself and forgive others.
31441**    May you share freely, never taking more than you give.
31442**
31443*************************************************************************
31444** This is the implementation of the page cache subsystem or "pager".
31445**
31446** The pager is used to access a database disk file.  It implements
31447** atomic commit and rollback through the use of a journal file that
31448** is separate from the database file.  The pager also implements file
31449** locking to prevent two processes from writing the same database
31450** file simultaneously, or one process from reading the database while
31451** another is writing.
31452*/
31453#ifndef SQLITE_OMIT_DISKIO
31454
31455/*
31456** Macros for troubleshooting.  Normally turned off
31457*/
31458#if 0
31459int sqlite3PagerTrace=1;  /* True to enable tracing */
31460#define sqlite3DebugPrintf printf
31461#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
31462#else
31463#define PAGERTRACE(X)
31464#endif
31465
31466/*
31467** The following two macros are used within the PAGERTRACE() macros above
31468** to print out file-descriptors.
31469**
31470** PAGERID() takes a pointer to a Pager struct as its argument. The
31471** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
31472** struct as its argument.
31473*/
31474#define PAGERID(p) ((int)(p->fd))
31475#define FILEHANDLEID(fd) ((int)fd)
31476
31477/*
31478** The page cache as a whole is always in one of the following
31479** states:
31480**
31481**   PAGER_UNLOCK        The page cache is not currently reading or
31482**                       writing the database file.  There is no
31483**                       data held in memory.  This is the initial
31484**                       state.
31485**
31486**   PAGER_SHARED        The page cache is reading the database.
31487**                       Writing is not permitted.  There can be
31488**                       multiple readers accessing the same database
31489**                       file at the same time.
31490**
31491**   PAGER_RESERVED      This process has reserved the database for writing
31492**                       but has not yet made any changes.  Only one process
31493**                       at a time can reserve the database.  The original
31494**                       database file has not been modified so other
31495**                       processes may still be reading the on-disk
31496**                       database file.
31497**
31498**   PAGER_EXCLUSIVE     The page cache is writing the database.
31499**                       Access is exclusive.  No other processes or
31500**                       threads can be reading or writing while one
31501**                       process is writing.
31502**
31503**   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
31504**                       after all dirty pages have been written to the
31505**                       database file and the file has been synced to
31506**                       disk. All that remains to do is to remove or
31507**                       truncate the journal file and the transaction
31508**                       will be committed.
31509**
31510** The page cache comes up in PAGER_UNLOCK.  The first time a
31511** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
31512** After all pages have been released using sqlite_page_unref(),
31513** the state transitions back to PAGER_UNLOCK.  The first time
31514** that sqlite3PagerWrite() is called, the state transitions to
31515** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
31516** called on an outstanding page which means that the pager must
31517** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
31518** PAGER_RESERVED means that there is an open rollback journal.
31519** The transition to PAGER_EXCLUSIVE occurs before any changes
31520** are made to the database file, though writes to the rollback
31521** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
31522** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
31523** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
31524*/
31525#define PAGER_UNLOCK      0
31526#define PAGER_SHARED      1   /* same as SHARED_LOCK */
31527#define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
31528#define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
31529#define PAGER_SYNCED      5
31530
31531/*
31532** A macro used for invoking the codec if there is one
31533*/
31534#ifdef SQLITE_HAS_CODEC
31535# define CODEC1(P,D,N,X,E) \
31536    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
31537# define CODEC2(P,D,N,X,E,O) \
31538    if( P->xCodec==0 ){ O=(char*)D; }else \
31539    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
31540#else
31541# define CODEC1(P,D,N,X,E)   /* NO-OP */
31542# define CODEC2(P,D,N,X,E,O) O=(char*)D
31543#endif
31544
31545/*
31546** The maximum allowed sector size. 64KiB. If the xSectorsize() method
31547** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
31548** This could conceivably cause corruption following a power failure on
31549** such a system. This is currently an undocumented limit.
31550*/
31551#define MAX_SECTOR_SIZE 0x10000
31552
31553/*
31554** An instance of the following structure is allocated for each active
31555** savepoint and statement transaction in the system. All such structures
31556** are stored in the Pager.aSavepoint[] array, which is allocated and
31557** resized using sqlite3Realloc().
31558**
31559** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
31560** set to 0. If a journal-header is written into the main journal while
31561** the savepoint is active, then iHdrOffset is set to the byte offset
31562** immediately following the last journal record written into the main
31563** journal before the journal-header. This is required during savepoint
31564** rollback (see pagerPlaybackSavepoint()).
31565*/
31566typedef struct PagerSavepoint PagerSavepoint;
31567struct PagerSavepoint {
31568  i64 iOffset;                 /* Starting offset in main journal */
31569  i64 iHdrOffset;              /* See above */
31570  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
31571  Pgno nOrig;                  /* Original number of pages in file */
31572  Pgno iSubRec;                /* Index of first record in sub-journal */
31573};
31574
31575/*
31576** A open page cache is an instance of the following structure.
31577**
31578** errCode
31579**
31580**   Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
31581**   or SQLITE_FULL. Once one of the first three errors occurs, it persists
31582**   and is returned as the result of every major pager API call.  The
31583**   SQLITE_FULL return code is slightly different. It persists only until the
31584**   next successful rollback is performed on the pager cache. Also,
31585**   SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
31586**   APIs, they may still be used successfully.
31587**
31588** dbSizeValid, dbSize, dbOrigSize, dbFileSize
31589**
31590**   Managing the size of the database file in pages is a little complicated.
31591**   The variable Pager.dbSize contains the number of pages that the database
31592**   image currently contains. As the database image grows or shrinks this
31593**   variable is updated. The variable Pager.dbFileSize contains the number
31594**   of pages in the database file. This may be different from Pager.dbSize
31595**   if some pages have been appended to the database image but not yet written
31596**   out from the cache to the actual file on disk. Or if the image has been
31597**   truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
31598**   contains the number of pages in the database image when the current
31599**   transaction was opened. The contents of all three of these variables is
31600**   only guaranteed to be correct if the boolean Pager.dbSizeValid is true.
31601**
31602**   TODO: Under what conditions is dbSizeValid set? Cleared?
31603**
31604** changeCountDone
31605**
31606**   This boolean variable is used to make sure that the change-counter
31607**   (the 4-byte header field at byte offset 24 of the database file) is
31608**   not updated more often than necessary.
31609**
31610**   It is set to true when the change-counter field is updated, which
31611**   can only happen if an exclusive lock is held on the database file.
31612**   It is cleared (set to false) whenever an exclusive lock is
31613**   relinquished on the database file. Each time a transaction is committed,
31614**   The changeCountDone flag is inspected. If it is true, the work of
31615**   updating the change-counter is omitted for the current transaction.
31616**
31617**   This mechanism means that when running in exclusive mode, a connection
31618**   need only update the change-counter once, for the first transaction
31619**   committed.
31620**
31621** dbModified
31622**
31623**   The dbModified flag is set whenever a database page is dirtied.
31624**   It is cleared at the end of each transaction.
31625**
31626**   It is used when committing or otherwise ending a transaction. If
31627**   the dbModified flag is clear then less work has to be done.
31628**
31629** journalStarted
31630**
31631**   This flag is set whenever the the main journal is synced.
31632**
31633**   The point of this flag is that it must be set after the
31634**   first journal header in a journal file has been synced to disk.
31635**   After this has happened, new pages appended to the database
31636**   do not need the PGHDR_NEED_SYNC flag set, as they do not need
31637**   to wait for a journal sync before they can be written out to
31638**   the database file (see function pager_write()).
31639**
31640** setMaster
31641**
31642**   This variable is used to ensure that the master journal file name
31643**   (if any) is only written into the journal file once.
31644**
31645**   When committing a transaction, the master journal file name (if any)
31646**   may be written into the journal file while the pager is still in
31647**   PAGER_RESERVED state (see CommitPhaseOne() for the action). It
31648**   then attempts to upgrade to an exclusive lock. If this attempt
31649**   fails, then SQLITE_BUSY may be returned to the user and the user
31650**   may attempt to commit the transaction again later (calling
31651**   CommitPhaseOne() again). This flag is used to ensure that the
31652**   master journal name is only written to the journal file the first
31653**   time CommitPhaseOne() is called.
31654**
31655** doNotSync
31656**
31657**   This variable is set and cleared by sqlite3PagerWrite().
31658**
31659** needSync
31660**
31661**   TODO: It might be easier to set this variable in writeJournalHdr()
31662**   and writeMasterJournal() only. Change its meaning to "unsynced data
31663**   has been written to the journal".
31664**
31665** subjInMemory
31666**
31667**   This is a boolean variable. If true, then any required sub-journal
31668**   is opened as an in-memory journal file. If false, then in-memory
31669**   sub-journals are only used for in-memory pager files.
31670*/
31671struct Pager {
31672  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
31673  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
31674  u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
31675  u8 useJournal;              /* Use a rollback journal on this file */
31676  u8 noReadlock;              /* Do not bother to obtain readlocks */
31677  u8 noSync;                  /* Do not sync the journal if true */
31678  u8 fullSync;                /* Do extra syncs of the journal for robustness */
31679  u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
31680  u8 tempFile;                /* zFilename is a temporary file */
31681  u8 readOnly;                /* True for a read-only database */
31682  u8 memDb;                   /* True to inhibit all file I/O */
31683
31684  /* The following block contains those class members that are dynamically
31685  ** modified during normal operations. The other variables in this structure
31686  ** are either constant throughout the lifetime of the pager, or else
31687  ** used to store configuration parameters that affect the way the pager
31688  ** operates.
31689  **
31690  ** The 'state' variable is described in more detail along with the
31691  ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the
31692  ** other variables in this block are described in the comment directly
31693  ** above this class definition.
31694  */
31695  u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
31696  u8 dbModified;              /* True if there are any changes to the Db */
31697  u8 needSync;                /* True if an fsync() is needed on the journal */
31698  u8 journalStarted;          /* True if header of journal is synced */
31699  u8 changeCountDone;         /* Set after incrementing the change-counter */
31700  u8 setMaster;               /* True if a m-j name has been written to jrnl */
31701  u8 doNotSync;               /* Boolean. While true, do not spill the cache */
31702  u8 dbSizeValid;             /* Set when dbSize is correct */
31703  u8 subjInMemory;            /* True to use in-memory sub-journals */
31704  Pgno dbSize;                /* Number of pages in the database */
31705  Pgno dbOrigSize;            /* dbSize before the current transaction */
31706  Pgno dbFileSize;            /* Number of pages in the database file */
31707  int errCode;                /* One of several kinds of errors */
31708  int nRec;                   /* Pages journalled since last j-header written */
31709  u32 cksumInit;              /* Quasi-random value added to every checksum */
31710  u32 nSubRec;                /* Number of records written to sub-journal */
31711  Bitvec *pInJournal;         /* One bit for each page in the database file */
31712  sqlite3_file *fd;           /* File descriptor for database */
31713  sqlite3_file *jfd;          /* File descriptor for main journal */
31714  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
31715  i64 journalOff;             /* Current write offset in the journal file */
31716  i64 journalHdr;             /* Byte offset to previous journal header */
31717  PagerSavepoint *aSavepoint; /* Array of active savepoints */
31718  int nSavepoint;             /* Number of elements in aSavepoint[] */
31719  char dbFileVers[16];        /* Changes whenever database file changes */
31720  u32 sectorSize;             /* Assumed sector size during rollback */
31721
31722  u16 nExtra;                 /* Add this many bytes to each in-memory page */
31723  i16 nReserve;               /* Number of unused bytes at end of each page */
31724  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
31725  int pageSize;               /* Number of bytes in a page */
31726  Pgno mxPgno;                /* Maximum allowed size of the database */
31727  char *zFilename;            /* Name of the database file */
31728  char *zJournal;             /* Name of the journal file */
31729  int (*xBusyHandler)(void*); /* Function to call when busy */
31730  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
31731#ifdef SQLITE_TEST
31732  int nHit, nMiss;            /* Cache hits and missing */
31733  int nRead, nWrite;          /* Database pages read/written */
31734#endif
31735  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
31736#ifdef SQLITE_HAS_CODEC
31737  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
31738  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
31739  void (*xCodecFree)(void*);             /* Destructor for the codec */
31740  void *pCodec;               /* First argument to xCodec... methods */
31741#endif
31742  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
31743  i64 journalSizeLimit;       /* Size limit for persistent journal files */
31744  PCache *pPCache;            /* Pointer to page cache object */
31745  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
31746};
31747
31748/*
31749** The following global variables hold counters used for
31750** testing purposes only.  These variables do not exist in
31751** a non-testing build.  These variables are not thread-safe.
31752*/
31753#ifdef SQLITE_TEST
31754SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
31755SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
31756SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
31757# define PAGER_INCR(v)  v++
31758#else
31759# define PAGER_INCR(v)
31760#endif
31761
31762
31763
31764/*
31765** Journal files begin with the following magic string.  The data
31766** was obtained from /dev/random.  It is used only as a sanity check.
31767**
31768** Since version 2.8.0, the journal format contains additional sanity
31769** checking information.  If the power fails while the journal is being
31770** written, semi-random garbage data might appear in the journal
31771** file after power is restored.  If an attempt is then made
31772** to roll the journal back, the database could be corrupted.  The additional
31773** sanity checking data is an attempt to discover the garbage in the
31774** journal and ignore it.
31775**
31776** The sanity checking information for the new journal format consists
31777** of a 32-bit checksum on each page of data.  The checksum covers both
31778** the page number and the pPager->pageSize bytes of data for the page.
31779** This cksum is initialized to a 32-bit random value that appears in the
31780** journal file right after the header.  The random initializer is important,
31781** because garbage data that appears at the end of a journal is likely
31782** data that was once in other files that have now been deleted.  If the
31783** garbage data came from an obsolete journal file, the checksums might
31784** be correct.  But by initializing the checksum to random value which
31785** is different for every journal, we minimize that risk.
31786*/
31787static const unsigned char aJournalMagic[] = {
31788  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
31789};
31790
31791/*
31792** The size of the of each page record in the journal is given by
31793** the following macro.
31794*/
31795#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
31796
31797/*
31798** The journal header size for this pager. This is usually the same
31799** size as a single disk sector. See also setSectorSize().
31800*/
31801#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
31802
31803/*
31804** The macro MEMDB is true if we are dealing with an in-memory database.
31805** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
31806** the value of MEMDB will be a constant and the compiler will optimize
31807** out code that would never execute.
31808*/
31809#ifdef SQLITE_OMIT_MEMORYDB
31810# define MEMDB 0
31811#else
31812# define MEMDB pPager->memDb
31813#endif
31814
31815/*
31816** The maximum legal page number is (2^31 - 1).
31817*/
31818#define PAGER_MAX_PGNO 2147483647
31819
31820#ifndef NDEBUG
31821/*
31822** Usage:
31823**
31824**   assert( assert_pager_state(pPager) );
31825*/
31826static int assert_pager_state(Pager *pPager){
31827
31828  /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */
31829  assert( pPager->tempFile==0 || pPager->state>=PAGER_EXCLUSIVE );
31830
31831  /* The changeCountDone flag is always set for temp-files */
31832  assert( pPager->tempFile==0 || pPager->changeCountDone );
31833
31834  return 1;
31835}
31836#endif
31837
31838/*
31839** Return true if it is necessary to write page *pPg into the sub-journal.
31840** A page needs to be written into the sub-journal if there exists one
31841** or more open savepoints for which:
31842**
31843**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
31844**   * The bit corresponding to the page-number is not set in
31845**     PagerSavepoint.pInSavepoint.
31846*/
31847static int subjRequiresPage(PgHdr *pPg){
31848  Pgno pgno = pPg->pgno;
31849  Pager *pPager = pPg->pPager;
31850  int i;
31851  for(i=0; i<pPager->nSavepoint; i++){
31852    PagerSavepoint *p = &pPager->aSavepoint[i];
31853    if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
31854      return 1;
31855    }
31856  }
31857  return 0;
31858}
31859
31860/*
31861** Return true if the page is already in the journal file.
31862*/
31863static int pageInJournal(PgHdr *pPg){
31864  return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
31865}
31866
31867/*
31868** Read a 32-bit integer from the given file descriptor.  Store the integer
31869** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
31870** error code is something goes wrong.
31871**
31872** All values are stored on disk as big-endian.
31873*/
31874static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
31875  unsigned char ac[4];
31876  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
31877  if( rc==SQLITE_OK ){
31878    *pRes = sqlite3Get4byte(ac);
31879  }
31880  return rc;
31881}
31882
31883/*
31884** Write a 32-bit integer into a string buffer in big-endian byte order.
31885*/
31886#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
31887
31888/*
31889** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
31890** on success or an error code is something goes wrong.
31891*/
31892static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
31893  char ac[4];
31894  put32bits(ac, val);
31895  return sqlite3OsWrite(fd, ac, 4, offset);
31896}
31897
31898/*
31899** The argument to this macro is a file descriptor (type sqlite3_file*).
31900** Return 0 if it is not open, or non-zero (but not 1) if it is.
31901**
31902** This is so that expressions can be written as:
31903**
31904**   if( isOpen(pPager->jfd) ){ ...
31905**
31906** instead of
31907**
31908**   if( pPager->jfd->pMethods ){ ...
31909*/
31910#define isOpen(pFd) ((pFd)->pMethods)
31911
31912/*
31913** If file pFd is open, call sqlite3OsUnlock() on it.
31914*/
31915static int osUnlock(sqlite3_file *pFd, int eLock){
31916  if( !isOpen(pFd) ){
31917    return SQLITE_OK;
31918  }
31919  return sqlite3OsUnlock(pFd, eLock);
31920}
31921
31922/*
31923** This function determines whether or not the atomic-write optimization
31924** can be used with this pager. The optimization can be used if:
31925**
31926**  (a) the value returned by OsDeviceCharacteristics() indicates that
31927**      a database page may be written atomically, and
31928**  (b) the value returned by OsSectorSize() is less than or equal
31929**      to the page size.
31930**
31931** The optimization is also always enabled for temporary files. It is
31932** an error to call this function if pPager is opened on an in-memory
31933** database.
31934**
31935** If the optimization cannot be used, 0 is returned. If it can be used,
31936** then the value returned is the size of the journal file when it
31937** contains rollback data for exactly one page.
31938*/
31939#ifdef SQLITE_ENABLE_ATOMIC_WRITE
31940static int jrnlBufferSize(Pager *pPager){
31941  assert( !MEMDB );
31942  if( !pPager->tempFile ){
31943    int dc;                           /* Device characteristics */
31944    int nSector;                      /* Sector size */
31945    int szPage;                       /* Page size */
31946
31947    assert( isOpen(pPager->fd) );
31948    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
31949    nSector = pPager->sectorSize;
31950    szPage = pPager->pageSize;
31951
31952    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
31953    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
31954    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
31955      return 0;
31956    }
31957  }
31958
31959  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
31960}
31961#endif
31962
31963/*
31964** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
31965** on the cache using a hash function.  This is used for testing
31966** and debugging only.
31967*/
31968#ifdef SQLITE_CHECK_PAGES
31969/*
31970** Return a 32-bit hash of the page data for pPage.
31971*/
31972static u32 pager_datahash(int nByte, unsigned char *pData){
31973  u32 hash = 0;
31974  int i;
31975  for(i=0; i<nByte; i++){
31976    hash = (hash*1039) + pData[i];
31977  }
31978  return hash;
31979}
31980static u32 pager_pagehash(PgHdr *pPage){
31981  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
31982}
31983static void pager_set_pagehash(PgHdr *pPage){
31984  pPage->pageHash = pager_pagehash(pPage);
31985}
31986
31987/*
31988** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
31989** is defined, and NDEBUG is not defined, an assert() statement checks
31990** that the page is either dirty or still matches the calculated page-hash.
31991*/
31992#define CHECK_PAGE(x) checkPage(x)
31993static void checkPage(PgHdr *pPg){
31994  Pager *pPager = pPg->pPager;
31995  assert( !pPg->pageHash || pPager->errCode
31996      || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
31997}
31998
31999#else
32000#define pager_datahash(X,Y)  0
32001#define pager_pagehash(X)  0
32002#define CHECK_PAGE(x)
32003#endif  /* SQLITE_CHECK_PAGES */
32004
32005/*
32006** When this is called the journal file for pager pPager must be open.
32007** This function attempts to read a master journal file name from the
32008** end of the file and, if successful, copies it into memory supplied
32009** by the caller. See comments above writeMasterJournal() for the format
32010** used to store a master journal file name at the end of a journal file.
32011**
32012** zMaster must point to a buffer of at least nMaster bytes allocated by
32013** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
32014** enough space to write the master journal name). If the master journal
32015** name in the journal is longer than nMaster bytes (including a
32016** nul-terminator), then this is handled as if no master journal name
32017** were present in the journal.
32018**
32019** If a master journal file name is present at the end of the journal
32020** file, then it is copied into the buffer pointed to by zMaster. A
32021** nul-terminator byte is appended to the buffer following the master
32022** journal file name.
32023**
32024** If it is determined that no master journal file name is present
32025** zMaster[0] is set to 0 and SQLITE_OK returned.
32026**
32027** If an error occurs while reading from the journal file, an SQLite
32028** error code is returned.
32029*/
32030static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
32031  int rc;                    /* Return code */
32032  u32 len;                   /* Length in bytes of master journal name */
32033  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
32034  u32 cksum;                 /* MJ checksum value read from journal */
32035  u32 u;                     /* Unsigned loop counter */
32036  unsigned char aMagic[8];   /* A buffer to hold the magic header */
32037  zMaster[0] = '\0';
32038
32039  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
32040   || szJ<16
32041   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
32042   || len>=nMaster
32043   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
32044   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
32045   || memcmp(aMagic, aJournalMagic, 8)
32046   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
32047  ){
32048    return rc;
32049  }
32050
32051  /* See if the checksum matches the master journal name */
32052  for(u=0; u<len; u++){
32053    cksum -= zMaster[u];
32054  }
32055  if( cksum ){
32056    /* If the checksum doesn't add up, then one or more of the disk sectors
32057    ** containing the master journal filename is corrupted. This means
32058    ** definitely roll back, so just return SQLITE_OK and report a (nul)
32059    ** master-journal filename.
32060    */
32061    len = 0;
32062  }
32063  zMaster[len] = '\0';
32064
32065  return SQLITE_OK;
32066}
32067
32068/*
32069** Return the offset of the sector boundary at or immediately
32070** following the value in pPager->journalOff, assuming a sector
32071** size of pPager->sectorSize bytes.
32072**
32073** i.e for a sector size of 512:
32074**
32075**   Pager.journalOff          Return value
32076**   ---------------------------------------
32077**   0                         0
32078**   512                       512
32079**   100                       512
32080**   2000                      2048
32081**
32082*/
32083static i64 journalHdrOffset(Pager *pPager){
32084  i64 offset = 0;
32085  i64 c = pPager->journalOff;
32086  if( c ){
32087    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
32088  }
32089  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
32090  assert( offset>=c );
32091  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
32092  return offset;
32093}
32094
32095/*
32096** The journal file must be open when this function is called.
32097**
32098** This function is a no-op if the journal file has not been written to
32099** within the current transaction (i.e. if Pager.journalOff==0).
32100**
32101** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
32102** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
32103** zero the 28-byte header at the start of the journal file. In either case,
32104** if the pager is not in no-sync mode, sync the journal file immediately
32105** after writing or truncating it.
32106**
32107** If Pager.journalSizeLimit is set to a positive, non-zero value, and
32108** following the truncation or zeroing described above the size of the
32109** journal file in bytes is larger than this value, then truncate the
32110** journal file to Pager.journalSizeLimit bytes. The journal file does
32111** not need to be synced following this operation.
32112**
32113** If an IO error occurs, abandon processing and return the IO error code.
32114** Otherwise, return SQLITE_OK.
32115*/
32116static int zeroJournalHdr(Pager *pPager, int doTruncate){
32117  int rc = SQLITE_OK;                               /* Return code */
32118  assert( isOpen(pPager->jfd) );
32119  if( pPager->journalOff ){
32120    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
32121
32122    IOTRACE(("JZEROHDR %p\n", pPager))
32123    if( doTruncate || iLimit==0 ){
32124      rc = sqlite3OsTruncate(pPager->jfd, 0);
32125    }else{
32126      static const char zeroHdr[28] = {0};
32127      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
32128    }
32129    if( rc==SQLITE_OK && !pPager->noSync ){
32130      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
32131    }
32132
32133    /* At this point the transaction is committed but the write lock
32134    ** is still held on the file. If there is a size limit configured for
32135    ** the persistent journal and the journal file currently consumes more
32136    ** space than that limit allows for, truncate it now. There is no need
32137    ** to sync the file following this operation.
32138    */
32139    if( rc==SQLITE_OK && iLimit>0 ){
32140      i64 sz;
32141      rc = sqlite3OsFileSize(pPager->jfd, &sz);
32142      if( rc==SQLITE_OK && sz>iLimit ){
32143        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
32144      }
32145    }
32146  }
32147  return rc;
32148}
32149
32150/*
32151** The journal file must be open when this routine is called. A journal
32152** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
32153** current location.
32154**
32155** The format for the journal header is as follows:
32156** - 8 bytes: Magic identifying journal format.
32157** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
32158** - 4 bytes: Random number used for page hash.
32159** - 4 bytes: Initial database page count.
32160** - 4 bytes: Sector size used by the process that wrote this journal.
32161** - 4 bytes: Database page size.
32162**
32163** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
32164*/
32165static int writeJournalHdr(Pager *pPager){
32166  int rc = SQLITE_OK;                 /* Return code */
32167  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
32168  u32 nHeader = pPager->pageSize;     /* Size of buffer pointed to by zHeader */
32169  u32 nWrite;                         /* Bytes of header sector written */
32170  int ii;                             /* Loop counter */
32171
32172  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
32173
32174  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
32175    nHeader = JOURNAL_HDR_SZ(pPager);
32176  }
32177
32178  /* If there are active savepoints and any of them were created
32179  ** since the most recent journal header was written, update the
32180  ** PagerSavepoint.iHdrOffset fields now.
32181  */
32182  for(ii=0; ii<pPager->nSavepoint; ii++){
32183    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
32184      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
32185    }
32186  }
32187
32188  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
32189
32190  /*
32191  ** Write the nRec Field - the number of page records that follow this
32192  ** journal header. Normally, zero is written to this value at this time.
32193  ** After the records are added to the journal (and the journal synced,
32194  ** if in full-sync mode), the zero is overwritten with the true number
32195  ** of records (see syncJournal()).
32196  **
32197  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
32198  ** reading the journal this value tells SQLite to assume that the
32199  ** rest of the journal file contains valid page records. This assumption
32200  ** is dangerous, as if a failure occurred whilst writing to the journal
32201  ** file it may contain some garbage data. There are two scenarios
32202  ** where this risk can be ignored:
32203  **
32204  **   * When the pager is in no-sync mode. Corruption can follow a
32205  **     power failure in this case anyway.
32206  **
32207  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
32208  **     that garbage data is never appended to the journal file.
32209  */
32210  assert( isOpen(pPager->fd) || pPager->noSync );
32211  if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
32212   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
32213  ){
32214    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
32215    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
32216  }else{
32217    memset(zHeader, 0, sizeof(aJournalMagic)+4);
32218  }
32219
32220  /* The random check-hash initialiser */
32221  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
32222  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
32223  /* The initial database size */
32224  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
32225  /* The assumed sector size for this process */
32226  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
32227
32228  /* The page size */
32229  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
32230
32231  /* Initializing the tail of the buffer is not necessary.  Everything
32232  ** works find if the following memset() is omitted.  But initializing
32233  ** the memory prevents valgrind from complaining, so we are willing to
32234  ** take the performance hit.
32235  */
32236  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
32237         nHeader-(sizeof(aJournalMagic)+20));
32238
32239  /* In theory, it is only necessary to write the 28 bytes that the
32240  ** journal header consumes to the journal file here. Then increment the
32241  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
32242  ** record is written to the following sector (leaving a gap in the file
32243  ** that will be implicitly filled in by the OS).
32244  **
32245  ** However it has been discovered that on some systems this pattern can
32246  ** be significantly slower than contiguously writing data to the file,
32247  ** even if that means explicitly writing data to the block of
32248  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
32249  ** is done.
32250  **
32251  ** The loop is required here in case the sector-size is larger than the
32252  ** database page size. Since the zHeader buffer is only Pager.pageSize
32253  ** bytes in size, more than one call to sqlite3OsWrite() may be required
32254  ** to populate the entire journal header sector.
32255  */
32256  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
32257    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
32258    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
32259    pPager->journalOff += nHeader;
32260  }
32261
32262  return rc;
32263}
32264
32265/*
32266** The journal file must be open when this is called. A journal header file
32267** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
32268** file. The current location in the journal file is given by
32269** pPager->journalOff. See comments above function writeJournalHdr() for
32270** a description of the journal header format.
32271**
32272** If the header is read successfully, *pNRec is set to the number of
32273** page records following this header and *pDbSize is set to the size of the
32274** database before the transaction began, in pages. Also, pPager->cksumInit
32275** is set to the value read from the journal header. SQLITE_OK is returned
32276** in this case.
32277**
32278** If the journal header file appears to be corrupted, SQLITE_DONE is
32279** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
32280** cannot be read from the journal file an error code is returned.
32281*/
32282static int readJournalHdr(
32283  Pager *pPager,               /* Pager object */
32284  int isHot,
32285  i64 journalSize,             /* Size of the open journal file in bytes */
32286  u32 *pNRec,                  /* OUT: Value read from the nRec field */
32287  u32 *pDbSize                 /* OUT: Value of original database size field */
32288){
32289  int rc;                      /* Return code */
32290  unsigned char aMagic[8];     /* A buffer to hold the magic header */
32291  i64 iHdrOff;                 /* Offset of journal header being read */
32292
32293  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
32294
32295  /* Advance Pager.journalOff to the start of the next sector. If the
32296  ** journal file is too small for there to be a header stored at this
32297  ** point, return SQLITE_DONE.
32298  */
32299  pPager->journalOff = journalHdrOffset(pPager);
32300  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
32301    return SQLITE_DONE;
32302  }
32303  iHdrOff = pPager->journalOff;
32304
32305  /* Read in the first 8 bytes of the journal header. If they do not match
32306  ** the  magic string found at the start of each journal header, return
32307  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
32308  ** proceed.
32309  */
32310  if( isHot || iHdrOff!=pPager->journalHdr ){
32311    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
32312    if( rc ){
32313      return rc;
32314    }
32315    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
32316      return SQLITE_DONE;
32317    }
32318  }
32319
32320  /* Read the first three 32-bit fields of the journal header: The nRec
32321  ** field, the checksum-initializer and the database size at the start
32322  ** of the transaction. Return an error code if anything goes wrong.
32323  */
32324  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
32325   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
32326   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
32327  ){
32328    return rc;
32329  }
32330
32331  if( pPager->journalOff==0 ){
32332    u32 iPageSize;               /* Page-size field of journal header */
32333    u32 iSectorSize;             /* Sector-size field of journal header */
32334    u16 iPageSize16;             /* Copy of iPageSize in 16-bit variable */
32335
32336    /* Read the page-size and sector-size journal header fields. */
32337    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
32338     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
32339    ){
32340      return rc;
32341    }
32342
32343    /* Check that the values read from the page-size and sector-size fields
32344    ** are within range. To be 'in range', both values need to be a power
32345    ** of two greater than or equal to 512 or 32, and not greater than their
32346    ** respective compile time maximum limits.
32347    */
32348    if( iPageSize<512                  || iSectorSize<32
32349     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
32350     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
32351    ){
32352      /* If the either the page-size or sector-size in the journal-header is
32353      ** invalid, then the process that wrote the journal-header must have
32354      ** crashed before the header was synced. In this case stop reading
32355      ** the journal file here.
32356      */
32357      return SQLITE_DONE;
32358    }
32359
32360    /* Update the page-size to match the value read from the journal.
32361    ** Use a testcase() macro to make sure that malloc failure within
32362    ** PagerSetPagesize() is tested.
32363    */
32364    iPageSize16 = (u16)iPageSize;
32365    rc = sqlite3PagerSetPagesize(pPager, &iPageSize16, -1);
32366    testcase( rc!=SQLITE_OK );
32367    assert( rc!=SQLITE_OK || iPageSize16==(u16)iPageSize );
32368
32369    /* Update the assumed sector-size to match the value used by
32370    ** the process that created this journal. If this journal was
32371    ** created by a process other than this one, then this routine
32372    ** is being called from within pager_playback(). The local value
32373    ** of Pager.sectorSize is restored at the end of that routine.
32374    */
32375    pPager->sectorSize = iSectorSize;
32376  }
32377
32378  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
32379  return rc;
32380}
32381
32382
32383/*
32384** Write the supplied master journal name into the journal file for pager
32385** pPager at the current location. The master journal name must be the last
32386** thing written to a journal file. If the pager is in full-sync mode, the
32387** journal file descriptor is advanced to the next sector boundary before
32388** anything is written. The format is:
32389**
32390**   + 4 bytes: PAGER_MJ_PGNO.
32391**   + N bytes: Master journal filename in utf-8.
32392**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
32393**   + 4 bytes: Master journal name checksum.
32394**   + 8 bytes: aJournalMagic[].
32395**
32396** The master journal page checksum is the sum of the bytes in the master
32397** journal name, where each byte is interpreted as a signed 8-bit integer.
32398**
32399** If zMaster is a NULL pointer (occurs for a single database transaction),
32400** this call is a no-op.
32401*/
32402static int writeMasterJournal(Pager *pPager, const char *zMaster){
32403  int rc;                          /* Return code */
32404  int nMaster;                     /* Length of string zMaster */
32405  i64 iHdrOff;                     /* Offset of header in journal file */
32406  i64 jrnlSize;                    /* Size of journal file on disk */
32407  u32 cksum = 0;                   /* Checksum of string zMaster */
32408
32409  if( !zMaster || pPager->setMaster
32410   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
32411   || pPager->journalMode==PAGER_JOURNALMODE_OFF
32412  ){
32413    return SQLITE_OK;
32414  }
32415  pPager->setMaster = 1;
32416  assert( isOpen(pPager->jfd) );
32417
32418  /* Calculate the length in bytes and the checksum of zMaster */
32419  for(nMaster=0; zMaster[nMaster]; nMaster++){
32420    cksum += zMaster[nMaster];
32421  }
32422
32423  /* If in full-sync mode, advance to the next disk sector before writing
32424  ** the master journal name. This is in case the previous page written to
32425  ** the journal has already been synced.
32426  */
32427  if( pPager->fullSync ){
32428    pPager->journalOff = journalHdrOffset(pPager);
32429  }
32430  iHdrOff = pPager->journalOff;
32431
32432  /* Write the master journal data to the end of the journal file. If
32433  ** an error occurs, return the error code to the caller.
32434  */
32435  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
32436   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
32437   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
32438   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
32439   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
32440  ){
32441    return rc;
32442  }
32443  pPager->journalOff += (nMaster+20);
32444  pPager->needSync = !pPager->noSync;
32445
32446  /* If the pager is in peristent-journal mode, then the physical
32447  ** journal-file may extend past the end of the master-journal name
32448  ** and 8 bytes of magic data just written to the file. This is
32449  ** dangerous because the code to rollback a hot-journal file
32450  ** will not be able to find the master-journal name to determine
32451  ** whether or not the journal is hot.
32452  **
32453  ** Easiest thing to do in this scenario is to truncate the journal
32454  ** file to the required size.
32455  */
32456  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
32457   && jrnlSize>pPager->journalOff
32458  ){
32459    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
32460  }
32461  return rc;
32462}
32463
32464/*
32465** Find a page in the hash table given its page number. Return
32466** a pointer to the page or NULL if the requested page is not
32467** already in memory.
32468*/
32469static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
32470  PgHdr *p;                         /* Return value */
32471
32472  /* It is not possible for a call to PcacheFetch() with createFlag==0 to
32473  ** fail, since no attempt to allocate dynamic memory will be made.
32474  */
32475  (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
32476  return p;
32477}
32478
32479/*
32480** Unless the pager is in error-state, discard all in-memory pages. If
32481** the pager is in error-state, then this call is a no-op.
32482**
32483** TODO: Why can we not reset the pager while in error state?
32484*/
32485static void pager_reset(Pager *pPager){
32486  if( SQLITE_OK==pPager->errCode ){
32487    sqlite3BackupRestart(pPager->pBackup);
32488    sqlite3PcacheClear(pPager->pPCache);
32489    pPager->dbSizeValid = 0;
32490  }
32491}
32492
32493/*
32494** Free all structures in the Pager.aSavepoint[] array and set both
32495** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
32496** if it is open and the pager is not in exclusive mode.
32497*/
32498static void releaseAllSavepoints(Pager *pPager){
32499  int ii;               /* Iterator for looping through Pager.aSavepoint */
32500  for(ii=0; ii<pPager->nSavepoint; ii++){
32501    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
32502  }
32503  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
32504    sqlite3OsClose(pPager->sjfd);
32505  }
32506  sqlite3_free(pPager->aSavepoint);
32507  pPager->aSavepoint = 0;
32508  pPager->nSavepoint = 0;
32509  pPager->nSubRec = 0;
32510}
32511
32512/*
32513** Set the bit number pgno in the PagerSavepoint.pInSavepoint
32514** bitvecs of all open savepoints. Return SQLITE_OK if successful
32515** or SQLITE_NOMEM if a malloc failure occurs.
32516*/
32517static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
32518  int ii;                   /* Loop counter */
32519  int rc = SQLITE_OK;       /* Result code */
32520
32521  for(ii=0; ii<pPager->nSavepoint; ii++){
32522    PagerSavepoint *p = &pPager->aSavepoint[ii];
32523    if( pgno<=p->nOrig ){
32524      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
32525      testcase( rc==SQLITE_NOMEM );
32526      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
32527    }
32528  }
32529  return rc;
32530}
32531
32532/*
32533** Unlock the database file. This function is a no-op if the pager
32534** is in exclusive mode.
32535**
32536** If the pager is currently in error state, discard the contents of
32537** the cache and reset the Pager structure internal state. If there is
32538** an open journal-file, then the next time a shared-lock is obtained
32539** on the pager file (by this or any other process), it will be
32540** treated as a hot-journal and rolled back.
32541*/
32542static void pager_unlock(Pager *pPager){
32543  if( !pPager->exclusiveMode ){
32544    int rc;                      /* Return code */
32545
32546    /* Always close the journal file when dropping the database lock.
32547    ** Otherwise, another connection with journal_mode=delete might
32548    ** delete the file out from under us.
32549    */
32550    sqlite3OsClose(pPager->jfd);
32551    sqlite3BitvecDestroy(pPager->pInJournal);
32552    pPager->pInJournal = 0;
32553    releaseAllSavepoints(pPager);
32554
32555    /* If the file is unlocked, somebody else might change it. The
32556    ** values stored in Pager.dbSize etc. might become invalid if
32557    ** this happens. TODO: Really, this doesn't need to be cleared
32558    ** until the change-counter check fails in PagerSharedLock().
32559    */
32560    pPager->dbSizeValid = 0;
32561
32562    rc = osUnlock(pPager->fd, NO_LOCK);
32563    if( rc ){
32564      pPager->errCode = rc;
32565    }
32566    IOTRACE(("UNLOCK %p\n", pPager))
32567
32568    /* If Pager.errCode is set, the contents of the pager cache cannot be
32569    ** trusted. Now that the pager file is unlocked, the contents of the
32570    ** cache can be discarded and the error code safely cleared.
32571    */
32572    if( pPager->errCode ){
32573      if( rc==SQLITE_OK ){
32574        pPager->errCode = SQLITE_OK;
32575      }
32576      pager_reset(pPager);
32577    }
32578
32579    pPager->changeCountDone = 0;
32580    pPager->state = PAGER_UNLOCK;
32581    pPager->dbModified = 0;
32582  }
32583}
32584
32585/*
32586** This function should be called when an IOERR, CORRUPT or FULL error
32587** may have occurred. The first argument is a pointer to the pager
32588** structure, the second the error-code about to be returned by a pager
32589** API function. The value returned is a copy of the second argument
32590** to this function.
32591**
32592** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
32593** the error becomes persistent. Until the persisten error is cleared,
32594** subsequent API calls on this Pager will immediately return the same
32595** error code.
32596**
32597** A persistent error indicates that the contents of the pager-cache
32598** cannot be trusted. This state can be cleared by completely discarding
32599** the contents of the pager-cache. If a transaction was active when
32600** the persistent error occurred, then the rollback journal may need
32601** to be replayed to restore the contents of the database file (as if
32602** it were a hot-journal).
32603*/
32604static int pager_error(Pager *pPager, int rc){
32605  int rc2 = rc & 0xff;
32606  assert( rc==SQLITE_OK || !MEMDB );
32607  assert(
32608       pPager->errCode==SQLITE_FULL ||
32609       pPager->errCode==SQLITE_OK ||
32610       (pPager->errCode & 0xff)==SQLITE_IOERR
32611  );
32612  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
32613    pPager->errCode = rc;
32614  }
32615  return rc;
32616}
32617
32618/*
32619** Execute a rollback if a transaction is active and unlock the
32620** database file.
32621**
32622** If the pager has already entered the error state, do not attempt
32623** the rollback at this time. Instead, pager_unlock() is called. The
32624** call to pager_unlock() will discard all in-memory pages, unlock
32625** the database file and clear the error state. If this means that
32626** there is a hot-journal left in the file-system, the next connection
32627** to obtain a shared lock on the pager (which may be this one) will
32628** roll it back.
32629**
32630** If the pager has not already entered the error state, but an IO or
32631** malloc error occurs during a rollback, then this will itself cause
32632** the pager to enter the error state. Which will be cleared by the
32633** call to pager_unlock(), as described above.
32634*/
32635static void pagerUnlockAndRollback(Pager *pPager){
32636  if( pPager->errCode==SQLITE_OK && pPager->state>=PAGER_RESERVED ){
32637    sqlite3BeginBenignMalloc();
32638    sqlite3PagerRollback(pPager);
32639    sqlite3EndBenignMalloc();
32640  }
32641  pager_unlock(pPager);
32642}
32643
32644/*
32645** This routine ends a transaction. A transaction is usually ended by
32646** either a COMMIT or a ROLLBACK operation. This routine may be called
32647** after rollback of a hot-journal, or if an error occurs while opening
32648** the journal file or writing the very first journal-header of a
32649** database transaction.
32650**
32651** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this
32652** routine is called, it is a no-op (returns SQLITE_OK).
32653**
32654** Otherwise, any active savepoints are released.
32655**
32656** If the journal file is open, then it is "finalized". Once a journal
32657** file has been finalized it is not possible to use it to roll back a
32658** transaction. Nor will it be considered to be a hot-journal by this
32659** or any other database connection. Exactly how a journal is finalized
32660** depends on whether or not the pager is running in exclusive mode and
32661** the current journal-mode (Pager.journalMode value), as follows:
32662**
32663**   journalMode==MEMORY
32664**     Journal file descriptor is simply closed. This destroys an
32665**     in-memory journal.
32666**
32667**   journalMode==TRUNCATE
32668**     Journal file is truncated to zero bytes in size.
32669**
32670**   journalMode==PERSIST
32671**     The first 28 bytes of the journal file are zeroed. This invalidates
32672**     the first journal header in the file, and hence the entire journal
32673**     file. An invalid journal file cannot be rolled back.
32674**
32675**   journalMode==DELETE
32676**     The journal file is closed and deleted using sqlite3OsDelete().
32677**
32678**     If the pager is running in exclusive mode, this method of finalizing
32679**     the journal file is never used. Instead, if the journalMode is
32680**     DELETE and the pager is in exclusive mode, the method described under
32681**     journalMode==PERSIST is used instead.
32682**
32683** After the journal is finalized, if running in non-exclusive mode, the
32684** pager moves to PAGER_SHARED state (and downgrades the lock on the
32685** database file accordingly).
32686**
32687** If the pager is running in exclusive mode and is in PAGER_SYNCED state,
32688** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in
32689** exclusive mode.
32690**
32691** SQLITE_OK is returned if no error occurs. If an error occurs during
32692** any of the IO operations to finalize the journal file or unlock the
32693** database then the IO error code is returned to the user. If the
32694** operation to finalize the journal file fails, then the code still
32695** tries to unlock the database file if not in exclusive mode. If the
32696** unlock operation fails as well, then the first error code related
32697** to the first error encountered (the journal finalization one) is
32698** returned.
32699*/
32700static int pager_end_transaction(Pager *pPager, int hasMaster){
32701  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
32702  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
32703
32704  if( pPager->state<PAGER_RESERVED ){
32705    return SQLITE_OK;
32706  }
32707  releaseAllSavepoints(pPager);
32708
32709  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
32710  if( isOpen(pPager->jfd) ){
32711
32712    /* Finalize the journal file. */
32713    if( sqlite3IsMemJournal(pPager->jfd) ){
32714      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
32715      sqlite3OsClose(pPager->jfd);
32716    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
32717      if( pPager->journalOff==0 ){
32718        rc = SQLITE_OK;
32719      }else{
32720        rc = sqlite3OsTruncate(pPager->jfd, 0);
32721      }
32722      pPager->journalOff = 0;
32723      pPager->journalStarted = 0;
32724    }else if( pPager->exclusiveMode
32725     || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
32726    ){
32727      rc = zeroJournalHdr(pPager, hasMaster);
32728      pager_error(pPager, rc);
32729      pPager->journalOff = 0;
32730      pPager->journalStarted = 0;
32731    }else{
32732      /* This branch may be executed with Pager.journalMode==MEMORY if
32733      ** a hot-journal was just rolled back. In this case the journal
32734      ** file should be closed and deleted. If this connection writes to
32735      ** the database file, it will do so using an in-memory journal.  */
32736      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
32737           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
32738      );
32739      sqlite3OsClose(pPager->jfd);
32740      if( !pPager->tempFile ){
32741        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
32742      }
32743    }
32744
32745#ifdef SQLITE_CHECK_PAGES
32746    sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
32747#endif
32748
32749    sqlite3PcacheCleanAll(pPager->pPCache);
32750    sqlite3BitvecDestroy(pPager->pInJournal);
32751    pPager->pInJournal = 0;
32752    pPager->nRec = 0;
32753  }
32754
32755  if( !pPager->exclusiveMode ){
32756    rc2 = osUnlock(pPager->fd, SHARED_LOCK);
32757    pPager->state = PAGER_SHARED;
32758    pPager->changeCountDone = 0;
32759  }else if( pPager->state==PAGER_SYNCED ){
32760    pPager->state = PAGER_EXCLUSIVE;
32761  }
32762  pPager->setMaster = 0;
32763  pPager->needSync = 0;
32764  pPager->dbModified = 0;
32765
32766  /* TODO: Is this optimal? Why is the db size invalidated here
32767  ** when the database file is not unlocked? */
32768  pPager->dbOrigSize = 0;
32769  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
32770  if( !MEMDB ){
32771    pPager->dbSizeValid = 0;
32772  }
32773
32774  return (rc==SQLITE_OK?rc2:rc);
32775}
32776
32777/*
32778** Parameter aData must point to a buffer of pPager->pageSize bytes
32779** of data. Compute and return a checksum based ont the contents of the
32780** page of data and the current value of pPager->cksumInit.
32781**
32782** This is not a real checksum. It is really just the sum of the
32783** random initial value (pPager->cksumInit) and every 200th byte
32784** of the page data, starting with byte offset (pPager->pageSize%200).
32785** Each byte is interpreted as an 8-bit unsigned integer.
32786**
32787** Changing the formula used to compute this checksum results in an
32788** incompatible journal file format.
32789**
32790** If journal corruption occurs due to a power failure, the most likely
32791** scenario is that one end or the other of the record will be changed.
32792** It is much less likely that the two ends of the journal record will be
32793** correct and the middle be corrupt.  Thus, this "checksum" scheme,
32794** though fast and simple, catches the mostly likely kind of corruption.
32795*/
32796static u32 pager_cksum(Pager *pPager, const u8 *aData){
32797  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
32798  int i = pPager->pageSize-200;          /* Loop counter */
32799  while( i>0 ){
32800    cksum += aData[i];
32801    i -= 200;
32802  }
32803  return cksum;
32804}
32805
32806/*
32807** Read a single page from either the journal file (if isMainJrnl==1) or
32808** from the sub-journal (if isMainJrnl==0) and playback that page.
32809** The page begins at offset *pOffset into the file. The *pOffset
32810** value is increased to the start of the next page in the journal.
32811**
32812** The isMainJrnl flag is true if this is the main rollback journal and
32813** false for the statement journal.  The main rollback journal uses
32814** checksums - the statement journal does not.
32815**
32816** If the page number of the page record read from the (sub-)journal file
32817** is greater than the current value of Pager.dbSize, then playback is
32818** skipped and SQLITE_OK is returned.
32819**
32820** If pDone is not NULL, then it is a record of pages that have already
32821** been played back.  If the page at *pOffset has already been played back
32822** (if the corresponding pDone bit is set) then skip the playback.
32823** Make sure the pDone bit corresponding to the *pOffset page is set
32824** prior to returning.
32825**
32826** If the page record is successfully read from the (sub-)journal file
32827** and played back, then SQLITE_OK is returned. If an IO error occurs
32828** while reading the record from the (sub-)journal file or while writing
32829** to the database file, then the IO error code is returned. If data
32830** is successfully read from the (sub-)journal file but appears to be
32831** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
32832** two circumstances:
32833**
32834**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
32835**   * If the record is being rolled back from the main journal file
32836**     and the checksum field does not match the record content.
32837**
32838** Neither of these two scenarios are possible during a savepoint rollback.
32839**
32840** If this is a savepoint rollback, then memory may have to be dynamically
32841** allocated by this function. If this is the case and an allocation fails,
32842** SQLITE_NOMEM is returned.
32843*/
32844static int pager_playback_one_page(
32845  Pager *pPager,                /* The pager being played back */
32846  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
32847  int isUnsync,                 /* True if reading from unsynced main journal */
32848  i64 *pOffset,                 /* Offset of record to playback */
32849  int isSavepnt,                /* True for a savepoint rollback */
32850  Bitvec *pDone                 /* Bitvec of pages already played back */
32851){
32852  int rc;
32853  PgHdr *pPg;                   /* An existing page in the cache */
32854  Pgno pgno;                    /* The page number of a page in journal */
32855  u32 cksum;                    /* Checksum used for sanity checking */
32856  char *aData;                  /* Temporary storage for the page */
32857  sqlite3_file *jfd;            /* The file descriptor for the journal file */
32858
32859  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
32860  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
32861  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
32862  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
32863
32864  aData = pPager->pTmpSpace;
32865  assert( aData );         /* Temp storage must have already been allocated */
32866
32867  /* Read the page number and page data from the journal or sub-journal
32868  ** file. Return an error code to the caller if an IO error occurs.
32869  */
32870  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
32871  rc = read32bits(jfd, *pOffset, &pgno);
32872  if( rc!=SQLITE_OK ) return rc;
32873  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
32874  if( rc!=SQLITE_OK ) return rc;
32875  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
32876
32877  /* Sanity checking on the page.  This is more important that I originally
32878  ** thought.  If a power failure occurs while the journal is being written,
32879  ** it could cause invalid data to be written into the journal.  We need to
32880  ** detect this invalid data (with high probability) and ignore it.
32881  */
32882  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
32883    assert( !isSavepnt );
32884    return SQLITE_DONE;
32885  }
32886  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
32887    return SQLITE_OK;
32888  }
32889  if( isMainJrnl ){
32890    rc = read32bits(jfd, (*pOffset)-4, &cksum);
32891    if( rc ) return rc;
32892    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
32893      return SQLITE_DONE;
32894    }
32895  }
32896
32897  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
32898    return rc;
32899  }
32900
32901  assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
32902
32903  /* If the pager is in RESERVED state, then there must be a copy of this
32904  ** page in the pager cache. In this case just update the pager cache,
32905  ** not the database file. The page is left marked dirty in this case.
32906  **
32907  ** An exception to the above rule: If the database is in no-sync mode
32908  ** and a page is moved during an incremental vacuum then the page may
32909  ** not be in the pager cache. Later: if a malloc() or IO error occurs
32910  ** during a Movepage() call, then the page may not be in the cache
32911  ** either. So the condition described in the above paragraph is not
32912  ** assert()able.
32913  **
32914  ** If in EXCLUSIVE state, then we update the pager cache if it exists
32915  ** and the main file. The page is then marked not dirty.
32916  **
32917  ** Ticket #1171:  The statement journal might contain page content that is
32918  ** different from the page content at the start of the transaction.
32919  ** This occurs when a page is changed prior to the start of a statement
32920  ** then changed again within the statement.  When rolling back such a
32921  ** statement we must not write to the original database unless we know
32922  ** for certain that original page contents are synced into the main rollback
32923  ** journal.  Otherwise, a power loss might leave modified data in the
32924  ** database file without an entry in the rollback journal that can
32925  ** restore the database to its original form.  Two conditions must be
32926  ** met before writing to the database files. (1) the database must be
32927  ** locked.  (2) we know that the original page content is fully synced
32928  ** in the main journal either because the page is not in cache or else
32929  ** the page is marked as needSync==0.
32930  **
32931  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
32932  ** is possible to fail a statement on a database that does not yet exist.
32933  ** Do not attempt to write if database file has never been opened.
32934  */
32935  pPg = pager_lookup(pPager, pgno);
32936  assert( pPg || !MEMDB );
32937  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
32938           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
32939           (isMainJrnl?"main-journal":"sub-journal")
32940  ));
32941  if( (pPager->state>=PAGER_EXCLUSIVE)
32942   && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
32943   && isOpen(pPager->fd)
32944   && !isUnsync
32945  ){
32946    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
32947    rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
32948    if( pgno>pPager->dbFileSize ){
32949      pPager->dbFileSize = pgno;
32950    }
32951    if( pPager->pBackup ){
32952      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
32953      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
32954      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
32955    }
32956  }else if( !isMainJrnl && pPg==0 ){
32957    /* If this is a rollback of a savepoint and data was not written to
32958    ** the database and the page is not in-memory, there is a potential
32959    ** problem. When the page is next fetched by the b-tree layer, it
32960    ** will be read from the database file, which may or may not be
32961    ** current.
32962    **
32963    ** There are a couple of different ways this can happen. All are quite
32964    ** obscure. When running in synchronous mode, this can only happen
32965    ** if the page is on the free-list at the start of the transaction, then
32966    ** populated, then moved using sqlite3PagerMovepage().
32967    **
32968    ** The solution is to add an in-memory page to the cache containing
32969    ** the data just read from the sub-journal. Mark the page as dirty
32970    ** and if the pager requires a journal-sync, then mark the page as
32971    ** requiring a journal-sync before it is written.
32972    */
32973    assert( isSavepnt );
32974    if( (rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1))!=SQLITE_OK ){
32975      return rc;
32976    }
32977    pPg->flags &= ~PGHDR_NEED_READ;
32978    sqlite3PcacheMakeDirty(pPg);
32979  }
32980  if( pPg ){
32981    /* No page should ever be explicitly rolled back that is in use, except
32982    ** for page 1 which is held in use in order to keep the lock on the
32983    ** database active. However such a page may be rolled back as a result
32984    ** of an internal error resulting in an automatic call to
32985    ** sqlite3PagerRollback().
32986    */
32987    void *pData;
32988    pData = pPg->pData;
32989    memcpy(pData, (u8*)aData, pPager->pageSize);
32990    pPager->xReiniter(pPg);
32991    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
32992      /* If the contents of this page were just restored from the main
32993      ** journal file, then its content must be as they were when the
32994      ** transaction was first opened. In this case we can mark the page
32995      ** as clean, since there will be no need to write it out to the.
32996      **
32997      ** There is one exception to this rule. If the page is being rolled
32998      ** back as part of a savepoint (or statement) rollback from an
32999      ** unsynced portion of the main journal file, then it is not safe
33000      ** to mark the page as clean. This is because marking the page as
33001      ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
33002      ** already in the journal file (recorded in Pager.pInJournal) and
33003      ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
33004      ** again within this transaction, it will be marked as dirty but
33005      ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
33006      ** be written out into the database file before its journal file
33007      ** segment is synced. If a crash occurs during or following this,
33008      ** database corruption may ensue.
33009      */
33010      sqlite3PcacheMakeClean(pPg);
33011    }
33012#ifdef SQLITE_CHECK_PAGES
33013    pPg->pageHash = pager_pagehash(pPg);
33014#endif
33015    /* If this was page 1, then restore the value of Pager.dbFileVers.
33016    ** Do this before any decoding. */
33017    if( pgno==1 ){
33018      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
33019    }
33020
33021    /* Decode the page just read from disk */
33022    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
33023    sqlite3PcacheRelease(pPg);
33024  }
33025  return rc;
33026}
33027
33028/*
33029** Parameter zMaster is the name of a master journal file. A single journal
33030** file that referred to the master journal file has just been rolled back.
33031** This routine checks if it is possible to delete the master journal file,
33032** and does so if it is.
33033**
33034** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
33035** available for use within this function.
33036**
33037** When a master journal file is created, it is populated with the names
33038** of all of its child journals, one after another, formatted as utf-8
33039** encoded text. The end of each child journal file is marked with a
33040** nul-terminator byte (0x00). i.e. the entire contents of a master journal
33041** file for a transaction involving two databases might be:
33042**
33043**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
33044**
33045** A master journal file may only be deleted once all of its child
33046** journals have been rolled back.
33047**
33048** This function reads the contents of the master-journal file into
33049** memory and loops through each of the child journal names. For
33050** each child journal, it checks if:
33051**
33052**   * if the child journal exists, and if so
33053**   * if the child journal contains a reference to master journal
33054**     file zMaster
33055**
33056** If a child journal can be found that matches both of the criteria
33057** above, this function returns without doing anything. Otherwise, if
33058** no such child journal can be found, file zMaster is deleted from
33059** the file-system using sqlite3OsDelete().
33060**
33061** If an IO error within this function, an error code is returned. This
33062** function allocates memory by calling sqlite3Malloc(). If an allocation
33063** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
33064** occur, SQLITE_OK is returned.
33065**
33066** TODO: This function allocates a single block of memory to load
33067** the entire contents of the master journal file. This could be
33068** a couple of kilobytes or so - potentially larger than the page
33069** size.
33070*/
33071static int pager_delmaster(Pager *pPager, const char *zMaster){
33072  sqlite3_vfs *pVfs = pPager->pVfs;
33073  int rc;                   /* Return code */
33074  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
33075  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
33076  char *zMasterJournal = 0; /* Contents of master journal file */
33077  i64 nMasterJournal;       /* Size of master journal file */
33078
33079  /* Allocate space for both the pJournal and pMaster file descriptors.
33080  ** If successful, open the master journal file for reading.
33081  */
33082  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
33083  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
33084  if( !pMaster ){
33085    rc = SQLITE_NOMEM;
33086  }else{
33087    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
33088    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
33089  }
33090  if( rc!=SQLITE_OK ) goto delmaster_out;
33091
33092  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
33093  if( rc!=SQLITE_OK ) goto delmaster_out;
33094
33095  if( nMasterJournal>0 ){
33096    char *zJournal;
33097    char *zMasterPtr = 0;
33098    int nMasterPtr = pVfs->mxPathname+1;
33099
33100    /* Load the entire master journal file into space obtained from
33101    ** sqlite3_malloc() and pointed to by zMasterJournal.
33102    */
33103    zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
33104    if( !zMasterJournal ){
33105      rc = SQLITE_NOMEM;
33106      goto delmaster_out;
33107    }
33108    zMasterPtr = &zMasterJournal[nMasterJournal+1];
33109    rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
33110    if( rc!=SQLITE_OK ) goto delmaster_out;
33111    zMasterJournal[nMasterJournal] = 0;
33112
33113    zJournal = zMasterJournal;
33114    while( (zJournal-zMasterJournal)<nMasterJournal ){
33115      int exists;
33116      rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
33117      if( rc!=SQLITE_OK ){
33118        goto delmaster_out;
33119      }
33120      if( exists ){
33121        /* One of the journals pointed to by the master journal exists.
33122        ** Open it and check if it points at the master journal. If
33123        ** so, return without deleting the master journal file.
33124        */
33125        int c;
33126        int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
33127        rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
33128        if( rc!=SQLITE_OK ){
33129          goto delmaster_out;
33130        }
33131
33132        rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
33133        sqlite3OsClose(pJournal);
33134        if( rc!=SQLITE_OK ){
33135          goto delmaster_out;
33136        }
33137
33138        c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
33139        if( c ){
33140          /* We have a match. Do not delete the master journal file. */
33141          goto delmaster_out;
33142        }
33143      }
33144      zJournal += (sqlite3Strlen30(zJournal)+1);
33145    }
33146  }
33147
33148  rc = sqlite3OsDelete(pVfs, zMaster, 0);
33149
33150delmaster_out:
33151  if( zMasterJournal ){
33152    sqlite3_free(zMasterJournal);
33153  }
33154  if( pMaster ){
33155    sqlite3OsClose(pMaster);
33156    assert( !isOpen(pJournal) );
33157  }
33158  sqlite3_free(pMaster);
33159  return rc;
33160}
33161
33162
33163/*
33164** This function is used to change the actual size of the database
33165** file in the file-system. This only happens when committing a transaction,
33166** or rolling back a transaction (including rolling back a hot-journal).
33167**
33168** If the main database file is not open, or an exclusive lock is not
33169** held, this function is a no-op. Otherwise, the size of the file is
33170** changed to nPage pages (nPage*pPager->pageSize bytes). If the file
33171** on disk is currently larger than nPage pages, then use the VFS
33172** xTruncate() method to truncate it.
33173**
33174** Or, it might might be the case that the file on disk is smaller than
33175** nPage pages. Some operating system implementations can get confused if
33176** you try to truncate a file to some size that is larger than it
33177** currently is, so detect this case and write a single zero byte to
33178** the end of the new file instead.
33179**
33180** If successful, return SQLITE_OK. If an IO error occurs while modifying
33181** the database file, return the error code to the caller.
33182*/
33183static int pager_truncate(Pager *pPager, Pgno nPage){
33184  int rc = SQLITE_OK;
33185  if( pPager->state>=PAGER_EXCLUSIVE && isOpen(pPager->fd) ){
33186    i64 currentSize, newSize;
33187    /* TODO: Is it safe to use Pager.dbFileSize here? */
33188    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
33189    newSize = pPager->pageSize*(i64)nPage;
33190    if( rc==SQLITE_OK && currentSize!=newSize ){
33191      if( currentSize>newSize ){
33192        rc = sqlite3OsTruncate(pPager->fd, newSize);
33193      }else{
33194        rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
33195      }
33196      if( rc==SQLITE_OK ){
33197        pPager->dbFileSize = nPage;
33198      }
33199    }
33200  }
33201  return rc;
33202}
33203
33204/*
33205** Set the value of the Pager.sectorSize variable for the given
33206** pager based on the value returned by the xSectorSize method
33207** of the open database file. The sector size will be used used
33208** to determine the size and alignment of journal header and
33209** master journal pointers within created journal files.
33210**
33211** For temporary files the effective sector size is always 512 bytes.
33212**
33213** Otherwise, for non-temporary files, the effective sector size is
33214** the value returned by the xSectorSize() method rounded up to 32 if
33215** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
33216** is greater than MAX_SECTOR_SIZE.
33217*/
33218static void setSectorSize(Pager *pPager){
33219  assert( isOpen(pPager->fd) || pPager->tempFile );
33220
33221  if( !pPager->tempFile ){
33222    /* Sector size doesn't matter for temporary files. Also, the file
33223    ** may not have been opened yet, in which case the OsSectorSize()
33224    ** call will segfault.
33225    */
33226    pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
33227  }
33228  if( pPager->sectorSize<32 ){
33229    pPager->sectorSize = 512;
33230  }
33231  if( pPager->sectorSize>MAX_SECTOR_SIZE ){
33232    assert( MAX_SECTOR_SIZE>=512 );
33233    pPager->sectorSize = MAX_SECTOR_SIZE;
33234  }
33235}
33236
33237/*
33238** Playback the journal and thus restore the database file to
33239** the state it was in before we started making changes.
33240**
33241** The journal file format is as follows:
33242**
33243**  (1)  8 byte prefix.  A copy of aJournalMagic[].
33244**  (2)  4 byte big-endian integer which is the number of valid page records
33245**       in the journal.  If this value is 0xffffffff, then compute the
33246**       number of page records from the journal size.
33247**  (3)  4 byte big-endian integer which is the initial value for the
33248**       sanity checksum.
33249**  (4)  4 byte integer which is the number of pages to truncate the
33250**       database to during a rollback.
33251**  (5)  4 byte big-endian integer which is the sector size.  The header
33252**       is this many bytes in size.
33253**  (6)  4 byte big-endian integer which is the page size.
33254**  (7)  zero padding out to the next sector size.
33255**  (8)  Zero or more pages instances, each as follows:
33256**        +  4 byte page number.
33257**        +  pPager->pageSize bytes of data.
33258**        +  4 byte checksum
33259**
33260** When we speak of the journal header, we mean the first 7 items above.
33261** Each entry in the journal is an instance of the 8th item.
33262**
33263** Call the value from the second bullet "nRec".  nRec is the number of
33264** valid page entries in the journal.  In most cases, you can compute the
33265** value of nRec from the size of the journal file.  But if a power
33266** failure occurred while the journal was being written, it could be the
33267** case that the size of the journal file had already been increased but
33268** the extra entries had not yet made it safely to disk.  In such a case,
33269** the value of nRec computed from the file size would be too large.  For
33270** that reason, we always use the nRec value in the header.
33271**
33272** If the nRec value is 0xffffffff it means that nRec should be computed
33273** from the file size.  This value is used when the user selects the
33274** no-sync option for the journal.  A power failure could lead to corruption
33275** in this case.  But for things like temporary table (which will be
33276** deleted when the power is restored) we don't care.
33277**
33278** If the file opened as the journal file is not a well-formed
33279** journal file then all pages up to the first corrupted page are rolled
33280** back (or no pages if the journal header is corrupted). The journal file
33281** is then deleted and SQLITE_OK returned, just as if no corruption had
33282** been encountered.
33283**
33284** If an I/O or malloc() error occurs, the journal-file is not deleted
33285** and an error code is returned.
33286**
33287** The isHot parameter indicates that we are trying to rollback a journal
33288** that might be a hot journal.  Or, it could be that the journal is
33289** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
33290** If the journal really is hot, reset the pager cache prior rolling
33291** back any content.  If the journal is merely persistent, no reset is
33292** needed.
33293*/
33294static int pager_playback(Pager *pPager, int isHot){
33295  sqlite3_vfs *pVfs = pPager->pVfs;
33296  i64 szJ;                 /* Size of the journal file in bytes */
33297  u32 nRec;                /* Number of Records in the journal */
33298  u32 u;                   /* Unsigned loop counter */
33299  Pgno mxPg = 0;           /* Size of the original file in pages */
33300  int rc;                  /* Result code of a subroutine */
33301  int res = 1;             /* Value returned by sqlite3OsAccess() */
33302  char *zMaster = 0;       /* Name of master journal file if any */
33303  int needPagerReset;      /* True to reset page prior to first page rollback */
33304
33305  /* Figure out how many records are in the journal.  Abort early if
33306  ** the journal is empty.
33307  */
33308  assert( isOpen(pPager->jfd) );
33309  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
33310  if( rc!=SQLITE_OK || szJ==0 ){
33311    goto end_playback;
33312  }
33313
33314  /* Read the master journal name from the journal, if it is present.
33315  ** If a master journal file name is specified, but the file is not
33316  ** present on disk, then the journal is not hot and does not need to be
33317  ** played back.
33318  **
33319  ** TODO: Technically the following is an error because it assumes that
33320  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
33321  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
33322  **  mxPathname is 512, which is the same as the minimum allowable value
33323  ** for pageSize.
33324  */
33325  zMaster = pPager->pTmpSpace;
33326  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
33327  if( rc==SQLITE_OK && zMaster[0] ){
33328    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
33329  }
33330  zMaster = 0;
33331  if( rc!=SQLITE_OK || !res ){
33332    goto end_playback;
33333  }
33334  pPager->journalOff = 0;
33335  needPagerReset = isHot;
33336
33337  /* This loop terminates either when a readJournalHdr() or
33338  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
33339  ** occurs.
33340  */
33341  while( 1 ){
33342    int isUnsync = 0;
33343
33344    /* Read the next journal header from the journal file.  If there are
33345    ** not enough bytes left in the journal file for a complete header, or
33346    ** it is corrupted, then a process must of failed while writing it.
33347    ** This indicates nothing more needs to be rolled back.
33348    */
33349    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
33350    if( rc!=SQLITE_OK ){
33351      if( rc==SQLITE_DONE ){
33352        rc = SQLITE_OK;
33353      }
33354      goto end_playback;
33355    }
33356
33357    /* If nRec is 0xffffffff, then this journal was created by a process
33358    ** working in no-sync mode. This means that the rest of the journal
33359    ** file consists of pages, there are no more journal headers. Compute
33360    ** the value of nRec based on this assumption.
33361    */
33362    if( nRec==0xffffffff ){
33363      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
33364      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
33365    }
33366
33367    /* If nRec is 0 and this rollback is of a transaction created by this
33368    ** process and if this is the final header in the journal, then it means
33369    ** that this part of the journal was being filled but has not yet been
33370    ** synced to disk.  Compute the number of pages based on the remaining
33371    ** size of the file.
33372    **
33373    ** The third term of the test was added to fix ticket #2565.
33374    ** When rolling back a hot journal, nRec==0 always means that the next
33375    ** chunk of the journal contains zero pages to be rolled back.  But
33376    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
33377    ** the journal, it means that the journal might contain additional
33378    ** pages that need to be rolled back and that the number of pages
33379    ** should be computed based on the journal file size.
33380    */
33381    if( nRec==0 && !isHot &&
33382        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
33383      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
33384      isUnsync = 1;
33385    }
33386
33387    /* If this is the first header read from the journal, truncate the
33388    ** database file back to its original size.
33389    */
33390    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
33391      rc = pager_truncate(pPager, mxPg);
33392      if( rc!=SQLITE_OK ){
33393        goto end_playback;
33394      }
33395      pPager->dbSize = mxPg;
33396    }
33397
33398    /* Copy original pages out of the journal and back into the
33399    ** database file and/or page cache.
33400    */
33401    for(u=0; u<nRec; u++){
33402      if( needPagerReset ){
33403        pager_reset(pPager);
33404        needPagerReset = 0;
33405      }
33406      rc = pager_playback_one_page(pPager,1,isUnsync,&pPager->journalOff,0,0);
33407      if( rc!=SQLITE_OK ){
33408        if( rc==SQLITE_DONE ){
33409          rc = SQLITE_OK;
33410          pPager->journalOff = szJ;
33411          break;
33412        }else{
33413          /* If we are unable to rollback, quit and return the error
33414          ** code.  This will cause the pager to enter the error state
33415          ** so that no further harm will be done.  Perhaps the next
33416          ** process to come along will be able to rollback the database.
33417          */
33418          goto end_playback;
33419        }
33420      }
33421    }
33422  }
33423  /*NOTREACHED*/
33424  assert( 0 );
33425
33426end_playback:
33427  /* Following a rollback, the database file should be back in its original
33428  ** state prior to the start of the transaction, so invoke the
33429  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
33430  ** assertion that the transaction counter was modified.
33431  */
33432  assert(
33433    pPager->fd->pMethods==0 ||
33434    sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
33435  );
33436
33437  /* If this playback is happening automatically as a result of an IO or
33438  ** malloc error that occurred after the change-counter was updated but
33439  ** before the transaction was committed, then the change-counter
33440  ** modification may just have been reverted. If this happens in exclusive
33441  ** mode, then subsequent transactions performed by the connection will not
33442  ** update the change-counter at all. This may lead to cache inconsistency
33443  ** problems for other processes at some point in the future. So, just
33444  ** in case this has happened, clear the changeCountDone flag now.
33445  */
33446  pPager->changeCountDone = pPager->tempFile;
33447
33448  if( rc==SQLITE_OK ){
33449    zMaster = pPager->pTmpSpace;
33450    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
33451    testcase( rc!=SQLITE_OK );
33452  }
33453  if( rc==SQLITE_OK && pPager->noSync==0 && pPager->state>=PAGER_EXCLUSIVE ){
33454    rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
33455  }
33456  if( rc==SQLITE_OK ){
33457    rc = pager_end_transaction(pPager, zMaster[0]!='\0');
33458    testcase( rc!=SQLITE_OK );
33459  }
33460  if( rc==SQLITE_OK && zMaster[0] && res ){
33461    /* If there was a master journal and this routine will return success,
33462    ** see if it is possible to delete the master journal.
33463    */
33464    rc = pager_delmaster(pPager, zMaster);
33465    testcase( rc!=SQLITE_OK );
33466  }
33467
33468  /* The Pager.sectorSize variable may have been updated while rolling
33469  ** back a journal created by a process with a different sector size
33470  ** value. Reset it to the correct value for this process.
33471  */
33472  setSectorSize(pPager);
33473  return rc;
33474}
33475
33476/*
33477** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
33478** the entire master journal file. The case pSavepoint==NULL occurs when
33479** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
33480** savepoint.
33481**
33482** When pSavepoint is not NULL (meaning a non-transaction savepoint is
33483** being rolled back), then the rollback consists of up to three stages,
33484** performed in the order specified:
33485**
33486**   * Pages are played back from the main journal starting at byte
33487**     offset PagerSavepoint.iOffset and continuing to
33488**     PagerSavepoint.iHdrOffset, or to the end of the main journal
33489**     file if PagerSavepoint.iHdrOffset is zero.
33490**
33491**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
33492**     back starting from the journal header immediately following
33493**     PagerSavepoint.iHdrOffset to the end of the main journal file.
33494**
33495**   * Pages are then played back from the sub-journal file, starting
33496**     with the PagerSavepoint.iSubRec and continuing to the end of
33497**     the journal file.
33498**
33499** Throughout the rollback process, each time a page is rolled back, the
33500** corresponding bit is set in a bitvec structure (variable pDone in the
33501** implementation below). This is used to ensure that a page is only
33502** rolled back the first time it is encountered in either journal.
33503**
33504** If pSavepoint is NULL, then pages are only played back from the main
33505** journal file. There is no need for a bitvec in this case.
33506**
33507** In either case, before playback commences the Pager.dbSize variable
33508** is reset to the value that it held at the start of the savepoint
33509** (or transaction). No page with a page-number greater than this value
33510** is played back. If one is encountered it is simply skipped.
33511*/
33512static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
33513  i64 szJ;                 /* Effective size of the main journal */
33514  i64 iHdrOff;             /* End of first segment of main-journal records */
33515  int rc = SQLITE_OK;      /* Return code */
33516  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
33517
33518  assert( pPager->state>=PAGER_SHARED );
33519
33520  /* Allocate a bitvec to use to store the set of pages rolled back */
33521  if( pSavepoint ){
33522    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
33523    if( !pDone ){
33524      return SQLITE_NOMEM;
33525    }
33526  }
33527
33528  /* Set the database size back to the value it was before the savepoint
33529  ** being reverted was opened.
33530  */
33531  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
33532
33533  /* Use pPager->journalOff as the effective size of the main rollback
33534  ** journal.  The actual file might be larger than this in
33535  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
33536  ** past pPager->journalOff is off-limits to us.
33537  */
33538  szJ = pPager->journalOff;
33539
33540  /* Begin by rolling back records from the main journal starting at
33541  ** PagerSavepoint.iOffset and continuing to the next journal header.
33542  ** There might be records in the main journal that have a page number
33543  ** greater than the current database size (pPager->dbSize) but those
33544  ** will be skipped automatically.  Pages are added to pDone as they
33545  ** are played back.
33546  */
33547  if( pSavepoint ){
33548    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
33549    pPager->journalOff = pSavepoint->iOffset;
33550    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
33551      rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
33552    }
33553    assert( rc!=SQLITE_DONE );
33554  }else{
33555    pPager->journalOff = 0;
33556  }
33557
33558  /* Continue rolling back records out of the main journal starting at
33559  ** the first journal header seen and continuing until the effective end
33560  ** of the main journal file.  Continue to skip out-of-range pages and
33561  ** continue adding pages rolled back to pDone.
33562  */
33563  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
33564    u32 ii;            /* Loop counter */
33565    u32 nJRec = 0;     /* Number of Journal Records */
33566    u32 dummy;
33567    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
33568    assert( rc!=SQLITE_DONE );
33569
33570    /*
33571    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
33572    ** test is related to ticket #2565.  See the discussion in the
33573    ** pager_playback() function for additional information.
33574    */
33575    if( nJRec==0
33576     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
33577    ){
33578      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
33579    }
33580    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
33581      rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
33582    }
33583    assert( rc!=SQLITE_DONE );
33584  }
33585  assert( rc!=SQLITE_OK || pPager->journalOff==szJ );
33586
33587  /* Finally,  rollback pages from the sub-journal.  Page that were
33588  ** previously rolled back out of the main journal (and are hence in pDone)
33589  ** will be skipped.  Out-of-range pages are also skipped.
33590  */
33591  if( pSavepoint ){
33592    u32 ii;            /* Loop counter */
33593    i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
33594    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
33595      assert( offset==ii*(4+pPager->pageSize) );
33596      rc = pager_playback_one_page(pPager, 0, 0, &offset, 1, pDone);
33597    }
33598    assert( rc!=SQLITE_DONE );
33599  }
33600
33601  sqlite3BitvecDestroy(pDone);
33602  if( rc==SQLITE_OK ){
33603    pPager->journalOff = szJ;
33604  }
33605  return rc;
33606}
33607
33608/*
33609** Change the maximum number of in-memory pages that are allowed.
33610*/
33611SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
33612  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
33613}
33614
33615/*
33616** Adjust the robustness of the database to damage due to OS crashes
33617** or power failures by changing the number of syncs()s when writing
33618** the rollback journal.  There are three levels:
33619**
33620**    OFF       sqlite3OsSync() is never called.  This is the default
33621**              for temporary and transient files.
33622**
33623**    NORMAL    The journal is synced once before writes begin on the
33624**              database.  This is normally adequate protection, but
33625**              it is theoretically possible, though very unlikely,
33626**              that an inopertune power failure could leave the journal
33627**              in a state which would cause damage to the database
33628**              when it is rolled back.
33629**
33630**    FULL      The journal is synced twice before writes begin on the
33631**              database (with some additional information - the nRec field
33632**              of the journal header - being written in between the two
33633**              syncs).  If we assume that writing a
33634**              single disk sector is atomic, then this mode provides
33635**              assurance that the journal will not be corrupted to the
33636**              point of causing damage to the database during rollback.
33637**
33638** Numeric values associated with these states are OFF==1, NORMAL=2,
33639** and FULL=3.
33640*/
33641#ifndef SQLITE_OMIT_PAGER_PRAGMAS
33642SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
33643  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
33644  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
33645  pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
33646  if( pPager->noSync ) pPager->needSync = 0;
33647}
33648#endif
33649
33650/*
33651** The following global variable is incremented whenever the library
33652** attempts to open a temporary file.  This information is used for
33653** testing and analysis only.
33654*/
33655#ifdef SQLITE_TEST
33656SQLITE_API int sqlite3_opentemp_count = 0;
33657#endif
33658
33659/*
33660** Open a temporary file.
33661**
33662** Write the file descriptor into *pFile. Return SQLITE_OK on success
33663** or some other error code if we fail. The OS will automatically
33664** delete the temporary file when it is closed.
33665**
33666** The flags passed to the VFS layer xOpen() call are those specified
33667** by parameter vfsFlags ORed with the following:
33668**
33669**     SQLITE_OPEN_READWRITE
33670**     SQLITE_OPEN_CREATE
33671**     SQLITE_OPEN_EXCLUSIVE
33672**     SQLITE_OPEN_DELETEONCLOSE
33673*/
33674static int pagerOpentemp(
33675  Pager *pPager,        /* The pager object */
33676  sqlite3_file *pFile,  /* Write the file descriptor here */
33677  int vfsFlags          /* Flags passed through to the VFS */
33678){
33679  int rc;               /* Return code */
33680
33681#ifdef SQLITE_TEST
33682  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
33683#endif
33684
33685  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
33686            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
33687  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
33688  assert( rc!=SQLITE_OK || isOpen(pFile) );
33689  return rc;
33690}
33691
33692/*
33693** Set the busy handler function.
33694**
33695** The pager invokes the busy-handler if sqlite3OsLock() returns
33696** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
33697** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
33698** lock. It does *not* invoke the busy handler when upgrading from
33699** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
33700** (which occurs during hot-journal rollback). Summary:
33701**
33702**   Transition                        | Invokes xBusyHandler
33703**   --------------------------------------------------------
33704**   NO_LOCK       -> SHARED_LOCK      | Yes
33705**   SHARED_LOCK   -> RESERVED_LOCK    | No
33706**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
33707**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
33708**
33709** If the busy-handler callback returns non-zero, the lock is
33710** retried. If it returns zero, then the SQLITE_BUSY error is
33711** returned to the caller of the pager API function.
33712*/
33713SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
33714  Pager *pPager,                       /* Pager object */
33715  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
33716  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
33717){
33718  pPager->xBusyHandler = xBusyHandler;
33719  pPager->pBusyHandlerArg = pBusyHandlerArg;
33720}
33721
33722/*
33723** Report the current page size and number of reserved bytes back
33724** to the codec.
33725*/
33726#ifdef SQLITE_HAS_CODEC
33727static void pagerReportSize(Pager *pPager){
33728  if( pPager->xCodecSizeChng ){
33729    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
33730                           (int)pPager->nReserve);
33731  }
33732}
33733#else
33734# define pagerReportSize(X)     /* No-op if we do not support a codec */
33735#endif
33736
33737/*
33738** Change the page size used by the Pager object. The new page size
33739** is passed in *pPageSize.
33740**
33741** If the pager is in the error state when this function is called, it
33742** is a no-op. The value returned is the error state error code (i.e.
33743** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL).
33744**
33745** Otherwise, if all of the following are true:
33746**
33747**   * the new page size (value of *pPageSize) is valid (a power
33748**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
33749**
33750**   * there are no outstanding page references, and
33751**
33752**   * the database is either not an in-memory database or it is
33753**     an in-memory database that currently consists of zero pages.
33754**
33755** then the pager object page size is set to *pPageSize.
33756**
33757** If the page size is changed, then this function uses sqlite3PagerMalloc()
33758** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
33759** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
33760** In all other cases, SQLITE_OK is returned.
33761**
33762** If the page size is not changed, either because one of the enumerated
33763** conditions above is not true, the pager was in error state when this
33764** function was called, or because the memory allocation attempt failed,
33765** then *pPageSize is set to the old, retained page size before returning.
33766*/
33767SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize, int nReserve){
33768  int rc = pPager->errCode;
33769
33770  if( rc==SQLITE_OK ){
33771    u16 pageSize = *pPageSize;
33772    assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
33773    if( (pPager->memDb==0 || pPager->dbSize==0)
33774     && sqlite3PcacheRefCount(pPager->pPCache)==0
33775     && pageSize && pageSize!=pPager->pageSize
33776    ){
33777      char *pNew = (char *)sqlite3PageMalloc(pageSize);
33778      if( !pNew ){
33779        rc = SQLITE_NOMEM;
33780      }else{
33781        pager_reset(pPager);
33782        pPager->pageSize = pageSize;
33783        sqlite3PageFree(pPager->pTmpSpace);
33784        pPager->pTmpSpace = pNew;
33785        sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
33786      }
33787    }
33788    *pPageSize = (u16)pPager->pageSize;
33789    if( nReserve<0 ) nReserve = pPager->nReserve;
33790    assert( nReserve>=0 && nReserve<1000 );
33791    pPager->nReserve = (i16)nReserve;
33792    pagerReportSize(pPager);
33793  }
33794  return rc;
33795}
33796
33797/*
33798** Return a pointer to the "temporary page" buffer held internally
33799** by the pager.  This is a buffer that is big enough to hold the
33800** entire content of a database page.  This buffer is used internally
33801** during rollback and will be overwritten whenever a rollback
33802** occurs.  But other modules are free to use it too, as long as
33803** no rollbacks are happening.
33804*/
33805SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
33806  return pPager->pTmpSpace;
33807}
33808
33809/*
33810** Attempt to set the maximum database page count if mxPage is positive.
33811** Make no changes if mxPage is zero or negative.  And never reduce the
33812** maximum page count below the current size of the database.
33813**
33814** Regardless of mxPage, return the current maximum page count.
33815*/
33816SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
33817  if( mxPage>0 ){
33818    pPager->mxPgno = mxPage;
33819  }
33820  sqlite3PagerPagecount(pPager, 0);
33821  return pPager->mxPgno;
33822}
33823
33824/*
33825** The following set of routines are used to disable the simulated
33826** I/O error mechanism.  These routines are used to avoid simulated
33827** errors in places where we do not care about errors.
33828**
33829** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
33830** and generate no code.
33831*/
33832#ifdef SQLITE_TEST
33833SQLITE_API extern int sqlite3_io_error_pending;
33834SQLITE_API extern int sqlite3_io_error_hit;
33835static int saved_cnt;
33836void disable_simulated_io_errors(void){
33837  saved_cnt = sqlite3_io_error_pending;
33838  sqlite3_io_error_pending = -1;
33839}
33840void enable_simulated_io_errors(void){
33841  sqlite3_io_error_pending = saved_cnt;
33842}
33843#else
33844# define disable_simulated_io_errors()
33845# define enable_simulated_io_errors()
33846#endif
33847
33848/*
33849** Read the first N bytes from the beginning of the file into memory
33850** that pDest points to.
33851**
33852** If the pager was opened on a transient file (zFilename==""), or
33853** opened on a file less than N bytes in size, the output buffer is
33854** zeroed and SQLITE_OK returned. The rationale for this is that this
33855** function is used to read database headers, and a new transient or
33856** zero sized database has a header than consists entirely of zeroes.
33857**
33858** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
33859** the error code is returned to the caller and the contents of the
33860** output buffer undefined.
33861*/
33862SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
33863  int rc = SQLITE_OK;
33864  memset(pDest, 0, N);
33865  assert( isOpen(pPager->fd) || pPager->tempFile );
33866  if( isOpen(pPager->fd) ){
33867    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
33868    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
33869    if( rc==SQLITE_IOERR_SHORT_READ ){
33870      rc = SQLITE_OK;
33871    }
33872  }
33873  return rc;
33874}
33875
33876/*
33877** Return the total number of pages in the database file associated
33878** with pPager. Normally, this is calculated as (<db file size>/<page-size>).
33879** However, if the file is between 1 and <page-size> bytes in size, then
33880** this is considered a 1 page file.
33881**
33882** If the pager is in error state when this function is called, then the
33883** error state error code is returned and *pnPage left unchanged. Or,
33884** if the file system has to be queried for the size of the file and
33885** the query attempt returns an IO error, the IO error code is returned
33886** and *pnPage is left unchanged.
33887**
33888** Otherwise, if everything is successful, then SQLITE_OK is returned
33889** and *pnPage is set to the number of pages in the database.
33890*/
33891SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
33892  Pgno nPage;               /* Value to return via *pnPage */
33893
33894  /* If the pager is already in the error state, return the error code. */
33895  if( pPager->errCode ){
33896    return pPager->errCode;
33897  }
33898
33899  /* Determine the number of pages in the file. Store this in nPage. */
33900  if( pPager->dbSizeValid ){
33901    nPage = pPager->dbSize;
33902  }else{
33903    int rc;                 /* Error returned by OsFileSize() */
33904    i64 n = 0;              /* File size in bytes returned by OsFileSize() */
33905
33906    assert( isOpen(pPager->fd) || pPager->tempFile );
33907    if( isOpen(pPager->fd) && (0 != (rc = sqlite3OsFileSize(pPager->fd, &n))) ){
33908      pager_error(pPager, rc);
33909      return rc;
33910    }
33911    if( n>0 && n<pPager->pageSize ){
33912      nPage = 1;
33913    }else{
33914      nPage = (Pgno)(n / pPager->pageSize);
33915    }
33916    if( pPager->state!=PAGER_UNLOCK ){
33917      pPager->dbSize = nPage;
33918      pPager->dbFileSize = nPage;
33919      pPager->dbSizeValid = 1;
33920    }
33921  }
33922
33923  /* If the current number of pages in the file is greater than the
33924  ** configured maximum pager number, increase the allowed limit so
33925  ** that the file can be read.
33926  */
33927  if( nPage>pPager->mxPgno ){
33928    pPager->mxPgno = (Pgno)nPage;
33929  }
33930
33931  /* Set the output variable and return SQLITE_OK */
33932  if( pnPage ){
33933    *pnPage = nPage;
33934  }
33935  return SQLITE_OK;
33936}
33937
33938
33939/*
33940** Try to obtain a lock of type locktype on the database file. If
33941** a similar or greater lock is already held, this function is a no-op
33942** (returning SQLITE_OK immediately).
33943**
33944** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
33945** the busy callback if the lock is currently not available. Repeat
33946** until the busy callback returns false or until the attempt to
33947** obtain the lock succeeds.
33948**
33949** Return SQLITE_OK on success and an error code if we cannot obtain
33950** the lock. If the lock is obtained successfully, set the Pager.state
33951** variable to locktype before returning.
33952*/
33953static int pager_wait_on_lock(Pager *pPager, int locktype){
33954  int rc;                              /* Return code */
33955
33956  /* The OS lock values must be the same as the Pager lock values */
33957  assert( PAGER_SHARED==SHARED_LOCK );
33958  assert( PAGER_RESERVED==RESERVED_LOCK );
33959  assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
33960
33961  /* If the file is currently unlocked then the size must be unknown. It
33962  ** must not have been modified at this point.
33963  */
33964  assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );
33965  assert( pPager->state>=PAGER_SHARED || pPager->dbModified==0 );
33966
33967  /* Check that this is either a no-op (because the requested lock is
33968  ** already held, or one of the transistions that the busy-handler
33969  ** may be invoked during, according to the comment above
33970  ** sqlite3PagerSetBusyhandler().
33971  */
33972  assert( (pPager->state>=locktype)
33973       || (pPager->state==PAGER_UNLOCK && locktype==PAGER_SHARED)
33974       || (pPager->state==PAGER_RESERVED && locktype==PAGER_EXCLUSIVE)
33975  );
33976
33977  if( pPager->state>=locktype ){
33978    rc = SQLITE_OK;
33979  }else{
33980    do {
33981      rc = sqlite3OsLock(pPager->fd, locktype);
33982    }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
33983    if( rc==SQLITE_OK ){
33984      pPager->state = (u8)locktype;
33985      IOTRACE(("LOCK %p %d\n", pPager, locktype))
33986    }
33987  }
33988  return rc;
33989}
33990
33991/*
33992** Function assertTruncateConstraint(pPager) checks that one of the
33993** following is true for all dirty pages currently in the page-cache:
33994**
33995**   a) The page number is less than or equal to the size of the
33996**      current database image, in pages, OR
33997**
33998**   b) if the page content were written at this time, it would not
33999**      be necessary to write the current content out to the sub-journal
34000**      (as determined by function subjRequiresPage()).
34001**
34002** If the condition asserted by this function were not true, and the
34003** dirty page were to be discarded from the cache via the pagerStress()
34004** routine, pagerStress() would not write the current page content to
34005** the database file. If a savepoint transaction were rolled back after
34006** this happened, the correct behaviour would be to restore the current
34007** content of the page. However, since this content is not present in either
34008** the database file or the portion of the rollback journal and
34009** sub-journal rolled back the content could not be restored and the
34010** database image would become corrupt. It is therefore fortunate that
34011** this circumstance cannot arise.
34012*/
34013#if defined(SQLITE_DEBUG)
34014static void assertTruncateConstraintCb(PgHdr *pPg){
34015  assert( pPg->flags&PGHDR_DIRTY );
34016  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
34017}
34018static void assertTruncateConstraint(Pager *pPager){
34019  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
34020}
34021#else
34022# define assertTruncateConstraint(pPager)
34023#endif
34024
34025/*
34026** Truncate the in-memory database file image to nPage pages. This
34027** function does not actually modify the database file on disk. It
34028** just sets the internal state of the pager object so that the
34029** truncation will be done when the current transaction is committed.
34030*/
34031SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
34032  assert( pPager->dbSizeValid );
34033  assert( pPager->dbSize>=nPage );
34034  assert( pPager->state>=PAGER_RESERVED );
34035  pPager->dbSize = nPage;
34036  assertTruncateConstraint(pPager);
34037}
34038
34039/*
34040** Shutdown the page cache.  Free all memory and close all files.
34041**
34042** If a transaction was in progress when this routine is called, that
34043** transaction is rolled back.  All outstanding pages are invalidated
34044** and their memory is freed.  Any attempt to use a page associated
34045** with this page cache after this function returns will likely
34046** result in a coredump.
34047**
34048** This function always succeeds. If a transaction is active an attempt
34049** is made to roll it back. If an error occurs during the rollback
34050** a hot journal may be left in the filesystem but no error is returned
34051** to the caller.
34052*/
34053SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
34054  disable_simulated_io_errors();
34055  sqlite3BeginBenignMalloc();
34056  pPager->errCode = 0;
34057  pPager->exclusiveMode = 0;
34058  pager_reset(pPager);
34059  if( MEMDB ){
34060    pager_unlock(pPager);
34061  }else{
34062    /* Set Pager.journalHdr to -1 for the benefit of the pager_playback()
34063    ** call which may be made from within pagerUnlockAndRollback(). If it
34064    ** is not -1, then the unsynced portion of an open journal file may
34065    ** be played back into the database. If a power failure occurs while
34066    ** this is happening, the database may become corrupt.
34067    */
34068    pPager->journalHdr = -1;
34069    pagerUnlockAndRollback(pPager);
34070  }
34071  sqlite3EndBenignMalloc();
34072  enable_simulated_io_errors();
34073  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
34074  IOTRACE(("CLOSE %p\n", pPager))
34075  sqlite3OsClose(pPager->fd);
34076  sqlite3PageFree(pPager->pTmpSpace);
34077  sqlite3PcacheClose(pPager->pPCache);
34078
34079#ifdef SQLITE_HAS_CODEC
34080  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
34081#endif
34082
34083  assert( !pPager->aSavepoint && !pPager->pInJournal );
34084  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
34085
34086  sqlite3_free(pPager);
34087  return SQLITE_OK;
34088}
34089
34090#if !defined(NDEBUG) || defined(SQLITE_TEST)
34091/*
34092** Return the page number for page pPg.
34093*/
34094SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
34095  return pPg->pgno;
34096}
34097#endif
34098
34099/*
34100** Increment the reference count for page pPg.
34101*/
34102SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
34103  sqlite3PcacheRef(pPg);
34104}
34105
34106/*
34107** Sync the journal. In other words, make sure all the pages that have
34108** been written to the journal have actually reached the surface of the
34109** disk and can be restored in the event of a hot-journal rollback.
34110**
34111** If the Pager.needSync flag is not set, then this function is a
34112** no-op. Otherwise, the actions required depend on the journal-mode
34113** and the device characteristics of the the file-system, as follows:
34114**
34115**   * If the journal file is an in-memory journal file, no action need
34116**     be taken.
34117**
34118**   * Otherwise, if the device does not support the SAFE_APPEND property,
34119**     then the nRec field of the most recently written journal header
34120**     is updated to contain the number of journal records that have
34121**     been written following it. If the pager is operating in full-sync
34122**     mode, then the journal file is synced before this field is updated.
34123**
34124**   * If the device does not support the SEQUENTIAL property, then
34125**     journal file is synced.
34126**
34127** Or, in pseudo-code:
34128**
34129**   if( NOT <in-memory journal> ){
34130**     if( NOT SAFE_APPEND ){
34131**       if( <full-sync mode> ) xSync(<journal file>);
34132**       <update nRec field>
34133**     }
34134**     if( NOT SEQUENTIAL ) xSync(<journal file>);
34135**   }
34136**
34137** The Pager.needSync flag is never be set for temporary files, or any
34138** file operating in no-sync mode (Pager.noSync set to non-zero).
34139**
34140** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
34141** page currently held in memory before returning SQLITE_OK. If an IO
34142** error is encountered, then the IO error code is returned to the caller.
34143*/
34144static int syncJournal(Pager *pPager){
34145  if( pPager->needSync ){
34146    assert( !pPager->tempFile );
34147    if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
34148      int rc;                              /* Return code */
34149      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
34150      assert( isOpen(pPager->jfd) );
34151
34152      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
34153        /* This block deals with an obscure problem. If the last connection
34154        ** that wrote to this database was operating in persistent-journal
34155        ** mode, then the journal file may at this point actually be larger
34156        ** than Pager.journalOff bytes. If the next thing in the journal
34157        ** file happens to be a journal-header (written as part of the
34158        ** previous connections transaction), and a crash or power-failure
34159        ** occurs after nRec is updated but before this connection writes
34160        ** anything else to the journal file (or commits/rolls back its
34161        ** transaction), then SQLite may become confused when doing the
34162        ** hot-journal rollback following recovery. It may roll back all
34163        ** of this connections data, then proceed to rolling back the old,
34164        ** out-of-date data that follows it. Database corruption.
34165        **
34166        ** To work around this, if the journal file does appear to contain
34167        ** a valid header following Pager.journalOff, then write a 0x00
34168        ** byte to the start of it to prevent it from being recognized.
34169        **
34170        ** Variable iNextHdrOffset is set to the offset at which this
34171        ** problematic header will occur, if it exists. aMagic is used
34172        ** as a temporary buffer to inspect the first couple of bytes of
34173        ** the potential journal header.
34174        */
34175        i64 iNextHdrOffset;
34176        u8 aMagic[8];
34177	u8 zHeader[sizeof(aJournalMagic)+4];
34178
34179	memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
34180	put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
34181
34182        iNextHdrOffset = journalHdrOffset(pPager);
34183        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
34184        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
34185          static const u8 zerobyte = 0;
34186          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
34187        }
34188        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
34189          return rc;
34190        }
34191
34192        /* Write the nRec value into the journal file header. If in
34193        ** full-synchronous mode, sync the journal first. This ensures that
34194        ** all data has really hit the disk before nRec is updated to mark
34195        ** it as a candidate for rollback.
34196        **
34197        ** This is not required if the persistent media supports the
34198        ** SAFE_APPEND property. Because in this case it is not possible
34199        ** for garbage data to be appended to the file, the nRec field
34200        ** is populated with 0xFFFFFFFF when the journal header is written
34201        ** and never needs to be updated.
34202        */
34203        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
34204          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
34205          IOTRACE(("JSYNC %p\n", pPager))
34206          rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
34207          if( rc!=SQLITE_OK ) return rc;
34208        }
34209        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
34210        rc = sqlite3OsWrite(
34211            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
34212	);
34213        if( rc!=SQLITE_OK ) return rc;
34214      }
34215      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
34216        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
34217        IOTRACE(("JSYNC %p\n", pPager))
34218        rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags|
34219          (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
34220        );
34221        if( rc!=SQLITE_OK ) return rc;
34222      }
34223    }
34224
34225    /* The journal file was just successfully synced. Set Pager.needSync
34226    ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess.
34227    */
34228    pPager->needSync = 0;
34229    pPager->journalStarted = 1;
34230    sqlite3PcacheClearSyncFlags(pPager->pPCache);
34231  }
34232
34233  return SQLITE_OK;
34234}
34235
34236/*
34237** The argument is the first in a linked list of dirty pages connected
34238** by the PgHdr.pDirty pointer. This function writes each one of the
34239** in-memory pages in the list to the database file. The argument may
34240** be NULL, representing an empty list. In this case this function is
34241** a no-op.
34242**
34243** The pager must hold at least a RESERVED lock when this function
34244** is called. Before writing anything to the database file, this lock
34245** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
34246** SQLITE_BUSY is returned and no data is written to the database file.
34247**
34248** If the pager is a temp-file pager and the actual file-system file
34249** is not yet open, it is created and opened before any data is
34250** written out.
34251**
34252** Once the lock has been upgraded and, if necessary, the file opened,
34253** the pages are written out to the database file in list order. Writing
34254** a page is skipped if it meets either of the following criteria:
34255**
34256**   * The page number is greater than Pager.dbSize, or
34257**   * The PGHDR_DONT_WRITE flag is set on the page.
34258**
34259** If writing out a page causes the database file to grow, Pager.dbFileSize
34260** is updated accordingly. If page 1 is written out, then the value cached
34261** in Pager.dbFileVers[] is updated to match the new value stored in
34262** the database file.
34263**
34264** If everything is successful, SQLITE_OK is returned. If an IO error
34265** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
34266** be obtained, SQLITE_BUSY is returned.
34267*/
34268static int pager_write_pagelist(PgHdr *pList){
34269  Pager *pPager;                       /* Pager object */
34270  int rc;                              /* Return code */
34271
34272  if( NEVER(pList==0) ) return SQLITE_OK;
34273  pPager = pList->pPager;
34274
34275  /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
34276  ** database file. If there is already an EXCLUSIVE lock, the following
34277  ** call is a no-op.
34278  **
34279  ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
34280  ** through an intermediate state PENDING.   A PENDING lock prevents new
34281  ** readers from attaching to the database but is unsufficient for us to
34282  ** write.  The idea of a PENDING lock is to prevent new readers from
34283  ** coming in while we wait for existing readers to clear.
34284  **
34285  ** While the pager is in the RESERVED state, the original database file
34286  ** is unchanged and we can rollback without having to playback the
34287  ** journal into the original database file.  Once we transition to
34288  ** EXCLUSIVE, it means the database file has been changed and any rollback
34289  ** will require a journal playback.
34290  */
34291  assert( pPager->state>=PAGER_RESERVED );
34292  rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
34293
34294  /* If the file is a temp-file has not yet been opened, open it now. It
34295  ** is not possible for rc to be other than SQLITE_OK if this branch
34296  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
34297  */
34298  if( !isOpen(pPager->fd) ){
34299    assert( pPager->tempFile && rc==SQLITE_OK );
34300    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
34301  }
34302
34303  while( rc==SQLITE_OK && pList ){
34304    Pgno pgno = pList->pgno;
34305
34306    /* If there are dirty pages in the page cache with page numbers greater
34307    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
34308    ** make the file smaller (presumably by auto-vacuum code). Do not write
34309    ** any such pages to the file.
34310    **
34311    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
34312    ** set (set by sqlite3PagerDontWrite()).  Note that if compiled with
34313    ** SQLITE_SECURE_DELETE the PGHDR_DONT_WRITE bit is never set and so
34314    ** the second test is always true.
34315    */
34316    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
34317      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
34318      char *pData;                                   /* Data to write */
34319
34320      /* Encode the database */
34321      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
34322
34323      /* Write out the page data. */
34324      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
34325
34326      /* If page 1 was just written, update Pager.dbFileVers to match
34327      ** the value now stored in the database file. If writing this
34328      ** page caused the database file to grow, update dbFileSize.
34329      */
34330      if( pgno==1 ){
34331        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
34332      }
34333      if( pgno>pPager->dbFileSize ){
34334        pPager->dbFileSize = pgno;
34335      }
34336
34337      /* Update any backup objects copying the contents of this pager. */
34338      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
34339
34340      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
34341                   PAGERID(pPager), pgno, pager_pagehash(pList)));
34342      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
34343      PAGER_INCR(sqlite3_pager_writedb_count);
34344      PAGER_INCR(pPager->nWrite);
34345    }else{
34346      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
34347    }
34348#ifdef SQLITE_CHECK_PAGES
34349    pList->pageHash = pager_pagehash(pList);
34350#endif
34351    pList = pList->pDirty;
34352  }
34353
34354  return rc;
34355}
34356
34357/*
34358** Append a record of the current state of page pPg to the sub-journal.
34359** It is the callers responsibility to use subjRequiresPage() to check
34360** that it is really required before calling this function.
34361**
34362** If successful, set the bit corresponding to pPg->pgno in the bitvecs
34363** for all open savepoints before returning.
34364**
34365** This function returns SQLITE_OK if everything is successful, an IO
34366** error code if the attempt to write to the sub-journal fails, or
34367** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
34368** bitvec.
34369*/
34370static int subjournalPage(PgHdr *pPg){
34371  int rc = SQLITE_OK;
34372  Pager *pPager = pPg->pPager;
34373  if( isOpen(pPager->sjfd) ){
34374    void *pData = pPg->pData;
34375    i64 offset = pPager->nSubRec*(4+pPager->pageSize);
34376    char *pData2;
34377
34378    CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
34379    PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
34380
34381    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
34382    rc = write32bits(pPager->sjfd, offset, pPg->pgno);
34383    if( rc==SQLITE_OK ){
34384      rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
34385    }
34386  }
34387  if( rc==SQLITE_OK ){
34388    pPager->nSubRec++;
34389    assert( pPager->nSavepoint>0 );
34390    rc = addToSavepointBitvecs(pPager, pPg->pgno);
34391  }
34392  return rc;
34393}
34394
34395
34396/*
34397** This function is called by the pcache layer when it has reached some
34398** soft memory limit. The first argument is a pointer to a Pager object
34399** (cast as a void*). The pager is always 'purgeable' (not an in-memory
34400** database). The second argument is a reference to a page that is
34401** currently dirty but has no outstanding references. The page
34402** is always associated with the Pager object passed as the first
34403** argument.
34404**
34405** The job of this function is to make pPg clean by writing its contents
34406** out to the database file, if possible. This may involve syncing the
34407** journal file.
34408**
34409** If successful, sqlite3PcacheMakeClean() is called on the page and
34410** SQLITE_OK returned. If an IO error occurs while trying to make the
34411** page clean, the IO error code is returned. If the page cannot be
34412** made clean for some other reason, but no error occurs, then SQLITE_OK
34413** is returned by sqlite3PcacheMakeClean() is not called.
34414*/
34415static int pagerStress(void *p, PgHdr *pPg){
34416  Pager *pPager = (Pager *)p;
34417  int rc = SQLITE_OK;
34418
34419  assert( pPg->pPager==pPager );
34420  assert( pPg->flags&PGHDR_DIRTY );
34421
34422  /* The doNotSync flag is set by the sqlite3PagerWrite() function while it
34423  ** is journalling a set of two or more database pages that are stored
34424  ** on the same disk sector. Syncing the journal is not allowed while
34425  ** this is happening as it is important that all members of such a
34426  ** set of pages are synced to disk together. So, if the page this function
34427  ** is trying to make clean will require a journal sync and the doNotSync
34428  ** flag is set, return without doing anything. The pcache layer will
34429  ** just have to go ahead and allocate a new page buffer instead of
34430  ** reusing pPg.
34431  **
34432  ** Similarly, if the pager has already entered the error state, do not
34433  ** try to write the contents of pPg to disk.
34434  */
34435  if( NEVER(pPager->errCode)
34436   || (pPager->doNotSync && pPg->flags&PGHDR_NEED_SYNC)
34437  ){
34438    return SQLITE_OK;
34439  }
34440
34441  /* Sync the journal file if required. */
34442  if( pPg->flags&PGHDR_NEED_SYNC ){
34443    rc = syncJournal(pPager);
34444    if( rc==SQLITE_OK && pPager->fullSync &&
34445      !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
34446      !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
34447    ){
34448      pPager->nRec = 0;
34449      rc = writeJournalHdr(pPager);
34450    }
34451  }
34452
34453  /* If the page number of this page is larger than the current size of
34454  ** the database image, it may need to be written to the sub-journal.
34455  ** This is because the call to pager_write_pagelist() below will not
34456  ** actually write data to the file in this case.
34457  **
34458  ** Consider the following sequence of events:
34459  **
34460  **   BEGIN;
34461  **     <journal page X>
34462  **     <modify page X>
34463  **     SAVEPOINT sp;
34464  **       <shrink database file to Y pages>
34465  **       pagerStress(page X)
34466  **     ROLLBACK TO sp;
34467  **
34468  ** If (X>Y), then when pagerStress is called page X will not be written
34469  ** out to the database file, but will be dropped from the cache. Then,
34470  ** following the "ROLLBACK TO sp" statement, reading page X will read
34471  ** data from the database file. This will be the copy of page X as it
34472  ** was when the transaction started, not as it was when "SAVEPOINT sp"
34473  ** was executed.
34474  **
34475  ** The solution is to write the current data for page X into the
34476  ** sub-journal file now (if it is not already there), so that it will
34477  ** be restored to its current value when the "ROLLBACK TO sp" is
34478  ** executed.
34479  */
34480  if( NEVER(
34481      rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
34482  ) ){
34483    rc = subjournalPage(pPg);
34484  }
34485
34486  /* Write the contents of the page out to the database file. */
34487  if( rc==SQLITE_OK ){
34488    pPg->pDirty = 0;
34489    rc = pager_write_pagelist(pPg);
34490  }
34491
34492  /* Mark the page as clean. */
34493  if( rc==SQLITE_OK ){
34494    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
34495    sqlite3PcacheMakeClean(pPg);
34496  }
34497
34498  return pager_error(pPager, rc);
34499}
34500
34501
34502/*
34503** Allocate and initialize a new Pager object and put a pointer to it
34504** in *ppPager. The pager should eventually be freed by passing it
34505** to sqlite3PagerClose().
34506**
34507** The zFilename argument is the path to the database file to open.
34508** If zFilename is NULL then a randomly-named temporary file is created
34509** and used as the file to be cached. Temporary files are be deleted
34510** automatically when they are closed. If zFilename is ":memory:" then
34511** all information is held in cache. It is never written to disk.
34512** This can be used to implement an in-memory database.
34513**
34514** The nExtra parameter specifies the number of bytes of space allocated
34515** along with each page reference. This space is available to the user
34516** via the sqlite3PagerGetExtra() API.
34517**
34518** The flags argument is used to specify properties that affect the
34519** operation of the pager. It should be passed some bitwise combination
34520** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
34521**
34522** The vfsFlags parameter is a bitmask to pass to the flags parameter
34523** of the xOpen() method of the supplied VFS when opening files.
34524**
34525** If the pager object is allocated and the specified file opened
34526** successfully, SQLITE_OK is returned and *ppPager set to point to
34527** the new pager object. If an error occurs, *ppPager is set to NULL
34528** and error code returned. This function may return SQLITE_NOMEM
34529** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
34530** various SQLITE_IO_XXX errors.
34531*/
34532SQLITE_PRIVATE int sqlite3PagerOpen(
34533  sqlite3_vfs *pVfs,       /* The virtual file system to use */
34534  Pager **ppPager,         /* OUT: Return the Pager structure here */
34535  const char *zFilename,   /* Name of the database file to open */
34536  int nExtra,              /* Extra bytes append to each in-memory page */
34537  int flags,               /* flags controlling this file */
34538  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
34539  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
34540){
34541  u8 *pPtr;
34542  Pager *pPager = 0;       /* Pager object to allocate and return */
34543  int rc = SQLITE_OK;      /* Return code */
34544  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
34545  int memDb = 0;           /* True if this is an in-memory file */
34546  int readOnly = 0;        /* True if this is a read-only file */
34547  int journalFileSize;     /* Bytes to allocate for each journal fd */
34548  char *zPathname = 0;     /* Full path to database file */
34549  int nPathname = 0;       /* Number of bytes in zPathname */
34550  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
34551  int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
34552  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
34553  u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
34554
34555  /* Figure out how much space is required for each journal file-handle
34556  ** (there are two of them, the main journal and the sub-journal). This
34557  ** is the maximum space required for an in-memory journal file handle
34558  ** and a regular journal file-handle. Note that a "regular journal-handle"
34559  ** may be a wrapper capable of caching the first portion of the journal
34560  ** file in memory to implement the atomic-write optimization (see
34561  ** source file journal.c).
34562  */
34563  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
34564    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
34565  }else{
34566    journalFileSize = ROUND8(sqlite3MemJournalSize());
34567  }
34568
34569  /* Set the output variable to NULL in case an error occurs. */
34570  *ppPager = 0;
34571
34572  /* Compute and store the full pathname in an allocated buffer pointed
34573  ** to by zPathname, length nPathname. Or, if this is a temporary file,
34574  ** leave both nPathname and zPathname set to 0.
34575  */
34576  if( zFilename && zFilename[0] ){
34577    nPathname = pVfs->mxPathname+1;
34578    zPathname = sqlite3Malloc(nPathname*2);
34579    if( zPathname==0 ){
34580      return SQLITE_NOMEM;
34581    }
34582#ifndef SQLITE_OMIT_MEMORYDB
34583    if( strcmp(zFilename,":memory:")==0 ){
34584      memDb = 1;
34585      zPathname[0] = 0;
34586    }else
34587#endif
34588    {
34589      zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
34590      rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
34591    }
34592
34593    nPathname = sqlite3Strlen30(zPathname);
34594    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
34595      /* This branch is taken when the journal path required by
34596      ** the database being opened will be more than pVfs->mxPathname
34597      ** bytes in length. This means the database cannot be opened,
34598      ** as it will not be possible to open the journal file or even
34599      ** check for a hot-journal before reading.
34600      */
34601      rc = SQLITE_CANTOPEN_BKPT;
34602    }
34603    if( rc!=SQLITE_OK ){
34604      sqlite3_free(zPathname);
34605      return rc;
34606    }
34607  }
34608
34609  /* Allocate memory for the Pager structure, PCache object, the
34610  ** three file descriptors, the database file name and the journal
34611  ** file name. The layout in memory is as follows:
34612  **
34613  **     Pager object                    (sizeof(Pager) bytes)
34614  **     PCache object                   (sqlite3PcacheSize() bytes)
34615  **     Database file handle            (pVfs->szOsFile bytes)
34616  **     Sub-journal file handle         (journalFileSize bytes)
34617  **     Main journal file handle        (journalFileSize bytes)
34618  **     Database file name              (nPathname+1 bytes)
34619  **     Journal file name               (nPathname+8+1 bytes)
34620  */
34621  pPtr = (u8 *)sqlite3MallocZero(
34622    ROUND8(sizeof(*pPager)) +      /* Pager structure */
34623    ROUND8(pcacheSize) +           /* PCache object */
34624    ROUND8(pVfs->szOsFile) +       /* The main db file */
34625    journalFileSize * 2 +          /* The two journal files */
34626    nPathname + 1 +                /* zFilename */
34627    nPathname + 8 + 1              /* zJournal */
34628  );
34629  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
34630  if( !pPtr ){
34631    sqlite3_free(zPathname);
34632    return SQLITE_NOMEM;
34633  }
34634  pPager =              (Pager*)(pPtr);
34635  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
34636  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
34637  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
34638  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
34639  pPager->zFilename =    (char*)(pPtr += journalFileSize);
34640  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
34641
34642  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
34643  if( zPathname ){
34644    pPager->zJournal =   (char*)(pPtr += nPathname + 1);
34645    memcpy(pPager->zFilename, zPathname, nPathname);
34646    memcpy(pPager->zJournal, zPathname, nPathname);
34647    memcpy(&pPager->zJournal[nPathname], "-journal", 8);
34648    if( pPager->zFilename[0]==0 ) pPager->zJournal[0] = 0;
34649    sqlite3_free(zPathname);
34650  }
34651  pPager->pVfs = pVfs;
34652  pPager->vfsFlags = vfsFlags;
34653
34654  /* Open the pager file.
34655  */
34656  if( zFilename && zFilename[0] && !memDb ){
34657    int fout = 0;                    /* VFS flags returned by xOpen() */
34658    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
34659    readOnly = (fout&SQLITE_OPEN_READONLY);
34660
34661    /* If the file was successfully opened for read/write access,
34662    ** choose a default page size in case we have to create the
34663    ** database file. The default page size is the maximum of:
34664    **
34665    **    + SQLITE_DEFAULT_PAGE_SIZE,
34666    **    + The value returned by sqlite3OsSectorSize()
34667    **    + The largest page size that can be written atomically.
34668    */
34669    if( rc==SQLITE_OK && !readOnly ){
34670      setSectorSize(pPager);
34671      assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
34672      if( szPageDflt<pPager->sectorSize ){
34673        if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
34674          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
34675        }else{
34676          szPageDflt = (u16)pPager->sectorSize;
34677        }
34678      }
34679#ifdef SQLITE_ENABLE_ATOMIC_WRITE
34680      {
34681        int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
34682        int ii;
34683        assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
34684        assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
34685        assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
34686        for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
34687          if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
34688            szPageDflt = ii;
34689          }
34690        }
34691      }
34692#endif
34693    }
34694  }else{
34695    /* If a temporary file is requested, it is not opened immediately.
34696    ** In this case we accept the default page size and delay actually
34697    ** opening the file until the first call to OsWrite().
34698    **
34699    ** This branch is also run for an in-memory database. An in-memory
34700    ** database is the same as a temp-file that is never written out to
34701    ** disk and uses an in-memory rollback journal.
34702    */
34703    tempFile = 1;
34704    pPager->state = PAGER_EXCLUSIVE;
34705    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
34706  }
34707
34708  /* The following call to PagerSetPagesize() serves to set the value of
34709  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
34710  */
34711  if( rc==SQLITE_OK ){
34712    assert( pPager->memDb==0 );
34713    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
34714    testcase( rc!=SQLITE_OK );
34715  }
34716
34717  /* If an error occurred in either of the blocks above, free the
34718  ** Pager structure and close the file.
34719  */
34720  if( rc!=SQLITE_OK ){
34721    assert( !pPager->pTmpSpace );
34722    sqlite3OsClose(pPager->fd);
34723    sqlite3_free(pPager);
34724    return rc;
34725  }
34726
34727  /* Initialize the PCache object. */
34728  assert( nExtra<1000 );
34729  nExtra = ROUND8(nExtra);
34730  sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
34731                    !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
34732
34733  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
34734  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
34735
34736  pPager->useJournal = (u8)useJournal;
34737  pPager->noReadlock = (noReadlock && readOnly) ?1:0;
34738  /* pPager->stmtOpen = 0; */
34739  /* pPager->stmtInUse = 0; */
34740  /* pPager->nRef = 0; */
34741  pPager->dbSizeValid = (u8)memDb;
34742  /* pPager->stmtSize = 0; */
34743  /* pPager->stmtJSize = 0; */
34744  /* pPager->nPage = 0; */
34745  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
34746  /* pPager->state = PAGER_UNLOCK; */
34747  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
34748  /* pPager->errMask = 0; */
34749  pPager->tempFile = (u8)tempFile;
34750  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
34751          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
34752  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
34753  pPager->exclusiveMode = (u8)tempFile;
34754  pPager->changeCountDone = pPager->tempFile;
34755  pPager->memDb = (u8)memDb;
34756  pPager->readOnly = (u8)readOnly;
34757  /* pPager->needSync = 0; */
34758  assert( useJournal || pPager->tempFile );
34759  pPager->noSync = pPager->tempFile;
34760  pPager->fullSync = pPager->noSync ?0:1;
34761  pPager->sync_flags = SQLITE_SYNC_NORMAL;
34762  /* pPager->pFirst = 0; */
34763  /* pPager->pFirstSynced = 0; */
34764  /* pPager->pLast = 0; */
34765  pPager->nExtra = (u16)nExtra;
34766  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
34767  assert( isOpen(pPager->fd) || tempFile );
34768  setSectorSize(pPager);
34769  if( !useJournal ){
34770    pPager->journalMode = PAGER_JOURNALMODE_OFF;
34771  }else if( memDb ){
34772    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
34773  }
34774  /* pPager->xBusyHandler = 0; */
34775  /* pPager->pBusyHandlerArg = 0; */
34776  pPager->xReiniter = xReinit;
34777  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
34778  *ppPager = pPager;
34779  return SQLITE_OK;
34780}
34781
34782
34783
34784/*
34785** This function is called after transitioning from PAGER_UNLOCK to
34786** PAGER_SHARED state. It tests if there is a hot journal present in
34787** the file-system for the given pager. A hot journal is one that
34788** needs to be played back. According to this function, a hot-journal
34789** file exists if the following criteria are met:
34790**
34791**   * The journal file exists in the file system, and
34792**   * No process holds a RESERVED or greater lock on the database file, and
34793**   * The database file itself is greater than 0 bytes in size, and
34794**   * The first byte of the journal file exists and is not 0x00.
34795**
34796** If the current size of the database file is 0 but a journal file
34797** exists, that is probably an old journal left over from a prior
34798** database with the same name. In this case the journal file is
34799** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
34800** is returned.
34801**
34802** This routine does not check if there is a master journal filename
34803** at the end of the file. If there is, and that master journal file
34804** does not exist, then the journal file is not really hot. In this
34805** case this routine will return a false-positive. The pager_playback()
34806** routine will discover that the journal file is not really hot and
34807** will not roll it back.
34808**
34809** If a hot-journal file is found to exist, *pExists is set to 1 and
34810** SQLITE_OK returned. If no hot-journal file is present, *pExists is
34811** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
34812** to determine whether or not a hot-journal file exists, the IO error
34813** code is returned and the value of *pExists is undefined.
34814*/
34815static int hasHotJournal(Pager *pPager, int *pExists){
34816  sqlite3_vfs * const pVfs = pPager->pVfs;
34817  int rc;                       /* Return code */
34818  int exists;                   /* True if a journal file is present */
34819
34820  assert( pPager!=0 );
34821  assert( pPager->useJournal );
34822  assert( isOpen(pPager->fd) );
34823  assert( !isOpen(pPager->jfd) );
34824  assert( pPager->state <= PAGER_SHARED );
34825
34826  *pExists = 0;
34827  rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
34828  if( rc==SQLITE_OK && exists ){
34829    int locked;                 /* True if some process holds a RESERVED lock */
34830
34831    /* Race condition here:  Another process might have been holding the
34832    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
34833    ** call above, but then delete the journal and drop the lock before
34834    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
34835    ** is the case, this routine might think there is a hot journal when
34836    ** in fact there is none.  This results in a false-positive which will
34837    ** be dealt with by the playback routine.  Ticket #3883.
34838    */
34839    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
34840    if( rc==SQLITE_OK && !locked ){
34841      int nPage;
34842
34843      /* Check the size of the database file. If it consists of 0 pages,
34844      ** then delete the journal file. See the header comment above for
34845      ** the reasoning here.  Delete the obsolete journal file under
34846      ** a RESERVED lock to avoid race conditions and to avoid violating
34847      ** [H33020].
34848      */
34849      rc = sqlite3PagerPagecount(pPager, &nPage);
34850      if( rc==SQLITE_OK ){
34851        if( nPage==0 ){
34852          sqlite3BeginBenignMalloc();
34853          if( sqlite3OsLock(pPager->fd, RESERVED_LOCK)==SQLITE_OK ){
34854            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
34855            sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
34856          }
34857          sqlite3EndBenignMalloc();
34858        }else{
34859          /* The journal file exists and no other connection has a reserved
34860          ** or greater lock on the database file. Now check that there is
34861          ** at least one non-zero bytes at the start of the journal file.
34862          ** If there is, then we consider this journal to be hot. If not,
34863          ** it can be ignored.
34864          */
34865          int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
34866          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
34867          if( rc==SQLITE_OK ){
34868            u8 first = 0;
34869            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
34870            if( rc==SQLITE_IOERR_SHORT_READ ){
34871              rc = SQLITE_OK;
34872            }
34873            sqlite3OsClose(pPager->jfd);
34874            *pExists = (first!=0);
34875          }else if( rc==SQLITE_CANTOPEN ){
34876            /* If we cannot open the rollback journal file in order to see if
34877            ** its has a zero header, that might be due to an I/O error, or
34878            ** it might be due to the race condition described above and in
34879            ** ticket #3883.  Either way, assume that the journal is hot.
34880            ** This might be a false positive.  But if it is, then the
34881            ** automatic journal playback and recovery mechanism will deal
34882            ** with it under an EXCLUSIVE lock where we do not need to
34883            ** worry so much with race conditions.
34884            */
34885            *pExists = 1;
34886            rc = SQLITE_OK;
34887          }
34888        }
34889      }
34890    }
34891  }
34892
34893  return rc;
34894}
34895
34896/*
34897** Read the content for page pPg out of the database file and into
34898** pPg->pData. A shared lock or greater must be held on the database
34899** file before this function is called.
34900**
34901** If page 1 is read, then the value of Pager.dbFileVers[] is set to
34902** the value read from the database file.
34903**
34904** If an IO error occurs, then the IO error is returned to the caller.
34905** Otherwise, SQLITE_OK is returned.
34906*/
34907static int readDbPage(PgHdr *pPg){
34908  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
34909  Pgno pgno = pPg->pgno;       /* Page number to read */
34910  int rc;                      /* Return code */
34911  i64 iOffset;                 /* Byte offset of file to read from */
34912
34913  assert( pPager->state>=PAGER_SHARED && !MEMDB );
34914  assert( isOpen(pPager->fd) );
34915
34916  if( NEVER(!isOpen(pPager->fd)) ){
34917    assert( pPager->tempFile );
34918    memset(pPg->pData, 0, pPager->pageSize);
34919    return SQLITE_OK;
34920  }
34921  iOffset = (pgno-1)*(i64)pPager->pageSize;
34922  rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
34923  if( rc==SQLITE_IOERR_SHORT_READ ){
34924    rc = SQLITE_OK;
34925  }
34926  if( pgno==1 ){
34927    u8 *dbFileVers = &((u8*)pPg->pData)[24];
34928    memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
34929  }
34930  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
34931
34932  PAGER_INCR(sqlite3_pager_readdb_count);
34933  PAGER_INCR(pPager->nRead);
34934  IOTRACE(("PGIN %p %d\n", pPager, pgno));
34935  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
34936               PAGERID(pPager), pgno, pager_pagehash(pPg)));
34937
34938  return rc;
34939}
34940
34941/*
34942** This function is called to obtain a shared lock on the database file.
34943** It is illegal to call sqlite3PagerAcquire() until after this function
34944** has been successfully called. If a shared-lock is already held when
34945** this function is called, it is a no-op.
34946**
34947** The following operations are also performed by this function.
34948**
34949**   1) If the pager is currently in PAGER_UNLOCK state (no lock held
34950**      on the database file), then an attempt is made to obtain a
34951**      SHARED lock on the database file. Immediately after obtaining
34952**      the SHARED lock, the file-system is checked for a hot-journal,
34953**      which is played back if present. Following any hot-journal
34954**      rollback, the contents of the cache are validated by checking
34955**      the 'change-counter' field of the database file header and
34956**      discarded if they are found to be invalid.
34957**
34958**   2) If the pager is running in exclusive-mode, and there are currently
34959**      no outstanding references to any pages, and is in the error state,
34960**      then an attempt is made to clear the error state by discarding
34961**      the contents of the page cache and rolling back any open journal
34962**      file.
34963**
34964** If the operation described by (2) above is not attempted, and if the
34965** pager is in an error state other than SQLITE_FULL when this is called,
34966** the error state error code is returned. It is permitted to read the
34967** database when in SQLITE_FULL error state.
34968**
34969** Otherwise, if everything is successful, SQLITE_OK is returned. If an
34970** IO error occurs while locking the database, checking for a hot-journal
34971** file or rolling back a journal file, the IO error code is returned.
34972*/
34973SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
34974  int rc = SQLITE_OK;                /* Return code */
34975  int isErrorReset = 0;              /* True if recovering from error state */
34976
34977  /* This routine is only called from b-tree and only when there are no
34978  ** outstanding pages */
34979  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
34980  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
34981
34982  /* If this database is in an error-state, now is a chance to clear
34983  ** the error. Discard the contents of the pager-cache and rollback
34984  ** any hot journal in the file-system.
34985  */
34986  if( pPager->errCode ){
34987    if( isOpen(pPager->jfd) || pPager->zJournal ){
34988      isErrorReset = 1;
34989    }
34990    pPager->errCode = SQLITE_OK;
34991    pager_reset(pPager);
34992  }
34993
34994  if( pPager->state==PAGER_UNLOCK || isErrorReset ){
34995    sqlite3_vfs * const pVfs = pPager->pVfs;
34996    int isHotJournal = 0;
34997    assert( !MEMDB );
34998    assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
34999    if( pPager->noReadlock ){
35000      assert( pPager->readOnly );
35001      pPager->state = PAGER_SHARED;
35002    }else{
35003      rc = pager_wait_on_lock(pPager, SHARED_LOCK);
35004      if( rc!=SQLITE_OK ){
35005        assert( pPager->state==PAGER_UNLOCK );
35006        return pager_error(pPager, rc);
35007      }
35008    }
35009    assert( pPager->state>=SHARED_LOCK );
35010
35011    /* If a journal file exists, and there is no RESERVED lock on the
35012    ** database file, then it either needs to be played back or deleted.
35013    */
35014    if( !isErrorReset ){
35015      assert( pPager->state <= PAGER_SHARED );
35016      rc = hasHotJournal(pPager, &isHotJournal);
35017      if( rc!=SQLITE_OK ){
35018        goto failed;
35019      }
35020    }
35021    if( isErrorReset || isHotJournal ){
35022      /* Get an EXCLUSIVE lock on the database file. At this point it is
35023      ** important that a RESERVED lock is not obtained on the way to the
35024      ** EXCLUSIVE lock. If it were, another process might open the
35025      ** database file, detect the RESERVED lock, and conclude that the
35026      ** database is safe to read while this process is still rolling the
35027      ** hot-journal back.
35028      **
35029      ** Because the intermediate RESERVED lock is not requested, any
35030      ** other process attempting to access the database file will get to
35031      ** this point in the code and fail to obtain its own EXCLUSIVE lock
35032      ** on the database file.
35033      */
35034      if( pPager->state<EXCLUSIVE_LOCK ){
35035        rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
35036        if( rc!=SQLITE_OK ){
35037          rc = pager_error(pPager, rc);
35038          goto failed;
35039        }
35040        pPager->state = PAGER_EXCLUSIVE;
35041      }
35042
35043      /* Open the journal for read/write access. This is because in
35044      ** exclusive-access mode the file descriptor will be kept open and
35045      ** possibly used for a transaction later on. On some systems, the
35046      ** OsTruncate() call used in exclusive-access mode also requires
35047      ** a read/write file handle.
35048      */
35049      if( !isOpen(pPager->jfd) ){
35050        int res;
35051        rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
35052        if( rc==SQLITE_OK ){
35053          if( res ){
35054            int fout = 0;
35055            int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
35056            assert( !pPager->tempFile );
35057            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
35058            assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
35059            if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
35060              rc = SQLITE_CANTOPEN_BKPT;
35061              sqlite3OsClose(pPager->jfd);
35062            }
35063          }else{
35064            /* If the journal does not exist, it usually means that some
35065            ** other connection managed to get in and roll it back before
35066            ** this connection obtained the exclusive lock above. Or, it
35067            ** may mean that the pager was in the error-state when this
35068            ** function was called and the journal file does not exist.  */
35069            rc = pager_end_transaction(pPager, 0);
35070          }
35071        }
35072      }
35073      if( rc!=SQLITE_OK ){
35074        goto failed;
35075      }
35076
35077      /* TODO: Why are these cleared here? Is it necessary? */
35078      pPager->journalStarted = 0;
35079      pPager->journalOff = 0;
35080      pPager->setMaster = 0;
35081      pPager->journalHdr = 0;
35082
35083      /* Playback and delete the journal.  Drop the database write
35084      ** lock and reacquire the read lock. Purge the cache before
35085      ** playing back the hot-journal so that we don't end up with
35086      ** an inconsistent cache.
35087      */
35088      if( isOpen(pPager->jfd) ){
35089        rc = pager_playback(pPager, 1);
35090        if( rc!=SQLITE_OK ){
35091          rc = pager_error(pPager, rc);
35092          goto failed;
35093        }
35094      }
35095      assert( (pPager->state==PAGER_SHARED)
35096           || (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
35097      );
35098    }
35099
35100    if( pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0 ){
35101      /* The shared-lock has just been acquired on the database file
35102      ** and there are already pages in the cache (from a previous
35103      ** read or write transaction).  Check to see if the database
35104      ** has been modified.  If the database has changed, flush the
35105      ** cache.
35106      **
35107      ** Database changes is detected by looking at 15 bytes beginning
35108      ** at offset 24 into the file.  The first 4 of these 16 bytes are
35109      ** a 32-bit counter that is incremented with each change.  The
35110      ** other bytes change randomly with each file change when
35111      ** a codec is in use.
35112      **
35113      ** There is a vanishingly small chance that a change will not be
35114      ** detected.  The chance of an undetected change is so small that
35115      ** it can be neglected.
35116      */
35117      char dbFileVers[sizeof(pPager->dbFileVers)];
35118      sqlite3PagerPagecount(pPager, 0);
35119
35120      if( pPager->errCode ){
35121        rc = pPager->errCode;
35122        goto failed;
35123      }
35124
35125      assert( pPager->dbSizeValid );
35126      if( pPager->dbSize>0 ){
35127        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
35128        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
35129        if( rc!=SQLITE_OK ){
35130          goto failed;
35131        }
35132      }else{
35133        memset(dbFileVers, 0, sizeof(dbFileVers));
35134      }
35135
35136      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
35137        pager_reset(pPager);
35138      }
35139    }
35140    assert( pPager->exclusiveMode || pPager->state==PAGER_SHARED );
35141  }
35142
35143 failed:
35144  if( rc!=SQLITE_OK ){
35145    /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
35146    pager_unlock(pPager);
35147  }
35148  return rc;
35149}
35150
35151/*
35152** If the reference count has reached zero, rollback any active
35153** transaction and unlock the pager.
35154**
35155** Except, in locking_mode=EXCLUSIVE when there is nothing to in
35156** the rollback journal, the unlock is not performed and there is
35157** nothing to rollback, so this routine is a no-op.
35158*/
35159static void pagerUnlockIfUnused(Pager *pPager){
35160  if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
35161   && (!pPager->exclusiveMode || pPager->journalOff>0)
35162  ){
35163    pagerUnlockAndRollback(pPager);
35164  }
35165}
35166
35167/*
35168** Acquire a reference to page number pgno in pager pPager (a page
35169** reference has type DbPage*). If the requested reference is
35170** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
35171**
35172** If the requested page is already in the cache, it is returned.
35173** Otherwise, a new page object is allocated and populated with data
35174** read from the database file. In some cases, the pcache module may
35175** choose not to allocate a new page object and may reuse an existing
35176** object with no outstanding references.
35177**
35178** The extra data appended to a page is always initialized to zeros the
35179** first time a page is loaded into memory. If the page requested is
35180** already in the cache when this function is called, then the extra
35181** data is left as it was when the page object was last used.
35182**
35183** If the database image is smaller than the requested page or if a
35184** non-zero value is passed as the noContent parameter and the
35185** requested page is not already stored in the cache, then no
35186** actual disk read occurs. In this case the memory image of the
35187** page is initialized to all zeros.
35188**
35189** If noContent is true, it means that we do not care about the contents
35190** of the page. This occurs in two seperate scenarios:
35191**
35192**   a) When reading a free-list leaf page from the database, and
35193**
35194**   b) When a savepoint is being rolled back and we need to load
35195**      a new page into the cache to populate with the data read
35196**      from the savepoint journal.
35197**
35198** If noContent is true, then the data returned is zeroed instead of
35199** being read from the database. Additionally, the bits corresponding
35200** to pgno in Pager.pInJournal (bitvec of pages already written to the
35201** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
35202** savepoints are set. This means if the page is made writable at any
35203** point in the future, using a call to sqlite3PagerWrite(), its contents
35204** will not be journaled. This saves IO.
35205**
35206** The acquisition might fail for several reasons.  In all cases,
35207** an appropriate error code is returned and *ppPage is set to NULL.
35208**
35209** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
35210** to find a page in the in-memory cache first.  If the page is not already
35211** in memory, this routine goes to disk to read it in whereas Lookup()
35212** just returns 0.  This routine acquires a read-lock the first time it
35213** has to go to disk, and could also playback an old journal if necessary.
35214** Since Lookup() never goes to disk, it never has to deal with locks
35215** or journal files.
35216*/
35217SQLITE_PRIVATE int sqlite3PagerAcquire(
35218  Pager *pPager,      /* The pager open on the database file */
35219  Pgno pgno,          /* Page number to fetch */
35220  DbPage **ppPage,    /* Write a pointer to the page here */
35221  int noContent       /* Do not bother reading content from disk if true */
35222){
35223  int rc;
35224  PgHdr *pPg;
35225
35226  assert( assert_pager_state(pPager) );
35227  assert( pPager->state>PAGER_UNLOCK );
35228
35229  if( pgno==0 ){
35230    return SQLITE_CORRUPT_BKPT;
35231  }
35232
35233  /* If the pager is in the error state, return an error immediately.
35234  ** Otherwise, request the page from the PCache layer. */
35235  if( pPager->errCode!=SQLITE_OK && pPager->errCode!=SQLITE_FULL ){
35236    rc = pPager->errCode;
35237  }else{
35238    rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
35239  }
35240
35241  if( rc!=SQLITE_OK ){
35242    /* Either the call to sqlite3PcacheFetch() returned an error or the
35243    ** pager was already in the error-state when this function was called.
35244    ** Set pPg to 0 and jump to the exception handler.  */
35245    pPg = 0;
35246    goto pager_acquire_err;
35247  }
35248  assert( (*ppPage)->pgno==pgno );
35249  assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
35250
35251  if( (*ppPage)->pPager ){
35252    /* In this case the pcache already contains an initialized copy of
35253    ** the page. Return without further ado.  */
35254    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
35255    PAGER_INCR(pPager->nHit);
35256    return SQLITE_OK;
35257
35258  }else{
35259    /* The pager cache has created a new page. Its content needs to
35260    ** be initialized.  */
35261    int nMax;
35262
35263    PAGER_INCR(pPager->nMiss);
35264    pPg = *ppPage;
35265    pPg->pPager = pPager;
35266
35267    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
35268    ** number greater than this, or the unused locking-page, is requested. */
35269    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
35270      rc = SQLITE_CORRUPT_BKPT;
35271      goto pager_acquire_err;
35272    }
35273
35274    rc = sqlite3PagerPagecount(pPager, &nMax);
35275    if( rc!=SQLITE_OK ){
35276      goto pager_acquire_err;
35277    }
35278
35279    if( MEMDB || nMax<(int)pgno || noContent || !isOpen(pPager->fd) ){
35280      if( pgno>pPager->mxPgno ){
35281	rc = SQLITE_FULL;
35282	goto pager_acquire_err;
35283      }
35284      if( noContent ){
35285        /* Failure to set the bits in the InJournal bit-vectors is benign.
35286        ** It merely means that we might do some extra work to journal a
35287        ** page that does not need to be journaled.  Nevertheless, be sure
35288        ** to test the case where a malloc error occurs while trying to set
35289        ** a bit in a bit vector.
35290        */
35291        sqlite3BeginBenignMalloc();
35292        if( pgno<=pPager->dbOrigSize ){
35293          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
35294          testcase( rc==SQLITE_NOMEM );
35295        }
35296        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
35297        testcase( rc==SQLITE_NOMEM );
35298        sqlite3EndBenignMalloc();
35299      }
35300      memset(pPg->pData, 0, pPager->pageSize);
35301      IOTRACE(("ZERO %p %d\n", pPager, pgno));
35302    }else{
35303      assert( pPg->pPager==pPager );
35304      rc = readDbPage(pPg);
35305      if( rc!=SQLITE_OK ){
35306        goto pager_acquire_err;
35307      }
35308    }
35309#ifdef SQLITE_CHECK_PAGES
35310    pPg->pageHash = pager_pagehash(pPg);
35311#endif
35312  }
35313
35314  return SQLITE_OK;
35315
35316pager_acquire_err:
35317  assert( rc!=SQLITE_OK );
35318  if( pPg ){
35319    sqlite3PcacheDrop(pPg);
35320  }
35321  pagerUnlockIfUnused(pPager);
35322
35323  *ppPage = 0;
35324  return rc;
35325}
35326
35327/*
35328** Acquire a page if it is already in the in-memory cache.  Do
35329** not read the page from disk.  Return a pointer to the page,
35330** or 0 if the page is not in cache. Also, return 0 if the
35331** pager is in PAGER_UNLOCK state when this function is called,
35332** or if the pager is in an error state other than SQLITE_FULL.
35333**
35334** See also sqlite3PagerGet().  The difference between this routine
35335** and sqlite3PagerGet() is that _get() will go to the disk and read
35336** in the page if the page is not already in cache.  This routine
35337** returns NULL if the page is not in cache or if a disk I/O error
35338** has ever happened.
35339*/
35340SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
35341  PgHdr *pPg = 0;
35342  assert( pPager!=0 );
35343  assert( pgno!=0 );
35344  assert( pPager->pPCache!=0 );
35345  assert( pPager->state > PAGER_UNLOCK );
35346  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
35347  return pPg;
35348}
35349
35350/*
35351** Release a page reference.
35352**
35353** If the number of references to the page drop to zero, then the
35354** page is added to the LRU list.  When all references to all pages
35355** are released, a rollback occurs and the lock on the database is
35356** removed.
35357*/
35358SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
35359  if( pPg ){
35360    Pager *pPager = pPg->pPager;
35361    sqlite3PcacheRelease(pPg);
35362    pagerUnlockIfUnused(pPager);
35363  }
35364}
35365
35366/*
35367** If the main journal file has already been opened, ensure that the
35368** sub-journal file is open too. If the main journal is not open,
35369** this function is a no-op.
35370**
35371** SQLITE_OK is returned if everything goes according to plan.
35372** An SQLITE_IOERR_XXX error code is returned if a call to
35373** sqlite3OsOpen() fails.
35374*/
35375static int openSubJournal(Pager *pPager){
35376  int rc = SQLITE_OK;
35377  if( isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ){
35378    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
35379      sqlite3MemJournalOpen(pPager->sjfd);
35380    }else{
35381      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
35382    }
35383  }
35384  return rc;
35385}
35386
35387/*
35388** This function is called at the start of every write transaction.
35389** There must already be a RESERVED or EXCLUSIVE lock on the database
35390** file when this routine is called.
35391**
35392** Open the journal file for pager pPager and write a journal header
35393** to the start of it. If there are active savepoints, open the sub-journal
35394** as well. This function is only used when the journal file is being
35395** opened to write a rollback log for a transaction. It is not used
35396** when opening a hot journal file to roll it back.
35397**
35398** If the journal file is already open (as it may be in exclusive mode),
35399** then this function just writes a journal header to the start of the
35400** already open file.
35401**
35402** Whether or not the journal file is opened by this function, the
35403** Pager.pInJournal bitvec structure is allocated.
35404**
35405** Return SQLITE_OK if everything is successful. Otherwise, return
35406** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
35407** an IO error code if opening or writing the journal file fails.
35408*/
35409static int pager_open_journal(Pager *pPager){
35410  int rc = SQLITE_OK;                        /* Return code */
35411  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
35412
35413  assert( pPager->state>=PAGER_RESERVED );
35414  assert( pPager->useJournal );
35415  assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF );
35416  assert( pPager->pInJournal==0 );
35417
35418  /* If already in the error state, this function is a no-op.  But on
35419  ** the other hand, this routine is never called if we are already in
35420  ** an error state. */
35421  if( NEVER(pPager->errCode) ) return pPager->errCode;
35422
35423  /* TODO: Is it really possible to get here with dbSizeValid==0? If not,
35424  ** the call to PagerPagecount() can be removed.
35425  */
35426  testcase( pPager->dbSizeValid==0 );
35427  sqlite3PagerPagecount(pPager, 0);
35428
35429  pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
35430  if( pPager->pInJournal==0 ){
35431    return SQLITE_NOMEM;
35432  }
35433
35434  /* Open the journal file if it is not already open. */
35435  if( !isOpen(pPager->jfd) ){
35436    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
35437      sqlite3MemJournalOpen(pPager->jfd);
35438    }else{
35439      const int flags =                   /* VFS flags to open journal file */
35440        SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
35441        (pPager->tempFile ?
35442          (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
35443          (SQLITE_OPEN_MAIN_JOURNAL)
35444        );
35445#ifdef SQLITE_ENABLE_ATOMIC_WRITE
35446      rc = sqlite3JournalOpen(
35447          pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
35448      );
35449#else
35450      rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
35451#endif
35452    }
35453    assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
35454  }
35455
35456
35457  /* Write the first journal header to the journal file and open
35458  ** the sub-journal if necessary.
35459  */
35460  if( rc==SQLITE_OK ){
35461    /* TODO: Check if all of these are really required. */
35462    pPager->dbOrigSize = pPager->dbSize;
35463    pPager->journalStarted = 0;
35464    pPager->needSync = 0;
35465    pPager->nRec = 0;
35466    pPager->journalOff = 0;
35467    pPager->setMaster = 0;
35468    pPager->journalHdr = 0;
35469    rc = writeJournalHdr(pPager);
35470  }
35471  if( rc==SQLITE_OK && pPager->nSavepoint ){
35472    rc = openSubJournal(pPager);
35473  }
35474
35475  if( rc!=SQLITE_OK ){
35476    sqlite3BitvecDestroy(pPager->pInJournal);
35477    pPager->pInJournal = 0;
35478  }
35479  return rc;
35480}
35481
35482/*
35483** Begin a write-transaction on the specified pager object. If a
35484** write-transaction has already been opened, this function is a no-op.
35485**
35486** If the exFlag argument is false, then acquire at least a RESERVED
35487** lock on the database file. If exFlag is true, then acquire at least
35488** an EXCLUSIVE lock. If such a lock is already held, no locking
35489** functions need be called.
35490**
35491** If this is not a temporary or in-memory file and, the journal file is
35492** opened if it has not been already. For a temporary file, the opening
35493** of the journal file is deferred until there is an actual need to
35494** write to the journal. TODO: Why handle temporary files differently?
35495**
35496** If the journal file is opened (or if it is already open), then a
35497** journal-header is written to the start of it.
35498**
35499** If the subjInMemory argument is non-zero, then any sub-journal opened
35500** within this transaction will be opened as an in-memory file. This
35501** has no effect if the sub-journal is already opened (as it may be when
35502** running in exclusive mode) or if the transaction does not require a
35503** sub-journal. If the subjInMemory argument is zero, then any required
35504** sub-journal is implemented in-memory if pPager is an in-memory database,
35505** or using a temporary file otherwise.
35506*/
35507SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
35508  int rc = SQLITE_OK;
35509  assert( pPager->state!=PAGER_UNLOCK );
35510  pPager->subjInMemory = (u8)subjInMemory;
35511  if( pPager->state==PAGER_SHARED ){
35512    assert( pPager->pInJournal==0 );
35513    assert( !MEMDB && !pPager->tempFile );
35514
35515    /* Obtain a RESERVED lock on the database file. If the exFlag parameter
35516    ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
35517    ** busy-handler callback can be used when upgrading to the EXCLUSIVE
35518    ** lock, but not when obtaining the RESERVED lock.
35519    */
35520    rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
35521    if( rc==SQLITE_OK ){
35522      pPager->state = PAGER_RESERVED;
35523      if( exFlag ){
35524        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
35525      }
35526    }
35527
35528    /* If the required locks were successfully obtained, open the journal
35529    ** file and write the first journal-header to it.
35530    */
35531    if( rc==SQLITE_OK && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
35532      rc = pager_open_journal(pPager);
35533    }
35534  }else if( isOpen(pPager->jfd) && pPager->journalOff==0 ){
35535    /* This happens when the pager was in exclusive-access mode the last
35536    ** time a (read or write) transaction was successfully concluded
35537    ** by this connection. Instead of deleting the journal file it was
35538    ** kept open and either was truncated to 0 bytes or its header was
35539    ** overwritten with zeros.
35540    */
35541    assert( pPager->nRec==0 );
35542    assert( pPager->dbOrigSize==0 );
35543    assert( pPager->pInJournal==0 );
35544    rc = pager_open_journal(pPager);
35545  }
35546
35547  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
35548  assert( !isOpen(pPager->jfd) || pPager->journalOff>0 || rc!=SQLITE_OK );
35549  if( rc!=SQLITE_OK ){
35550    assert( !pPager->dbModified );
35551    /* Ignore any IO error that occurs within pager_end_transaction(). The
35552    ** purpose of this call is to reset the internal state of the pager
35553    ** sub-system. It doesn't matter if the journal-file is not properly
35554    ** finalized at this point (since it is not a valid journal file anyway).
35555    */
35556    pager_end_transaction(pPager, 0);
35557  }
35558  return rc;
35559}
35560
35561/*
35562** Mark a single data page as writeable. The page is written into the
35563** main journal or sub-journal as required. If the page is written into
35564** one of the journals, the corresponding bit is set in the
35565** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
35566** of any open savepoints as appropriate.
35567*/
35568static int pager_write(PgHdr *pPg){
35569  void *pData = pPg->pData;
35570  Pager *pPager = pPg->pPager;
35571  int rc = SQLITE_OK;
35572
35573  /* This routine is not called unless a transaction has already been
35574  ** started.
35575  */
35576  assert( pPager->state>=PAGER_RESERVED );
35577
35578  /* If an error has been previously detected, we should not be
35579  ** calling this routine.  Repeat the error for robustness.
35580  */
35581  if( NEVER(pPager->errCode) )  return pPager->errCode;
35582
35583  /* Higher-level routines never call this function if database is not
35584  ** writable.  But check anyway, just for robustness. */
35585  if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
35586
35587  assert( !pPager->setMaster );
35588
35589  CHECK_PAGE(pPg);
35590
35591  /* Mark the page as dirty.  If the page has already been written
35592  ** to the journal then we can return right away.
35593  */
35594  sqlite3PcacheMakeDirty(pPg);
35595  if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
35596    pPager->dbModified = 1;
35597  }else{
35598
35599    /* If we get this far, it means that the page needs to be
35600    ** written to the transaction journal or the ckeckpoint journal
35601    ** or both.
35602    **
35603    ** Higher level routines should have already started a transaction,
35604    ** which means they have acquired the necessary locks and opened
35605    ** a rollback journal.  Double-check to makes sure this is the case.
35606    */
35607    rc = sqlite3PagerBegin(pPager, 0, pPager->subjInMemory);
35608    if( NEVER(rc!=SQLITE_OK) ){
35609      return rc;
35610    }
35611    if( !isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
35612      assert( pPager->useJournal );
35613      rc = pager_open_journal(pPager);
35614      if( rc!=SQLITE_OK ) return rc;
35615    }
35616    pPager->dbModified = 1;
35617
35618    /* The transaction journal now exists and we have a RESERVED or an
35619    ** EXCLUSIVE lock on the main database file.  Write the current page to
35620    ** the transaction journal if it is not there already.
35621    */
35622    if( !pageInJournal(pPg) && isOpen(pPager->jfd) ){
35623      if( pPg->pgno<=pPager->dbOrigSize ){
35624        u32 cksum;
35625        char *pData2;
35626
35627        /* We should never write to the journal file the page that
35628        ** contains the database locks.  The following assert verifies
35629        ** that we do not. */
35630        assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
35631        CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
35632        cksum = pager_cksum(pPager, (u8*)pData2);
35633        rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
35634        if( rc==SQLITE_OK ){
35635          rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
35636                              pPager->journalOff + 4);
35637          pPager->journalOff += pPager->pageSize+4;
35638        }
35639        if( rc==SQLITE_OK ){
35640          rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
35641          pPager->journalOff += 4;
35642        }
35643        IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
35644                 pPager->journalOff, pPager->pageSize));
35645        PAGER_INCR(sqlite3_pager_writej_count);
35646        PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
35647             PAGERID(pPager), pPg->pgno,
35648             ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
35649
35650        /* Even if an IO or diskfull error occurred while journalling the
35651        ** page in the block above, set the need-sync flag for the page.
35652        ** Otherwise, when the transaction is rolled back, the logic in
35653        ** playback_one_page() will think that the page needs to be restored
35654        ** in the database file. And if an IO error occurs while doing so,
35655        ** then corruption may follow.
35656        */
35657        if( !pPager->noSync ){
35658          pPg->flags |= PGHDR_NEED_SYNC;
35659          pPager->needSync = 1;
35660        }
35661
35662        /* An error has occurred writing to the journal file. The
35663        ** transaction will be rolled back by the layer above.
35664        */
35665        if( rc!=SQLITE_OK ){
35666          return rc;
35667        }
35668
35669        pPager->nRec++;
35670        assert( pPager->pInJournal!=0 );
35671        rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
35672        testcase( rc==SQLITE_NOMEM );
35673        assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
35674        rc |= addToSavepointBitvecs(pPager, pPg->pgno);
35675        if( rc!=SQLITE_OK ){
35676          assert( rc==SQLITE_NOMEM );
35677          return rc;
35678        }
35679      }else{
35680        if( !pPager->journalStarted && !pPager->noSync ){
35681          pPg->flags |= PGHDR_NEED_SYNC;
35682          pPager->needSync = 1;
35683        }
35684        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
35685                PAGERID(pPager), pPg->pgno,
35686               ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
35687      }
35688    }
35689
35690    /* If the statement journal is open and the page is not in it,
35691    ** then write the current page to the statement journal.  Note that
35692    ** the statement journal format differs from the standard journal format
35693    ** in that it omits the checksums and the header.
35694    */
35695    if( subjRequiresPage(pPg) ){
35696      rc = subjournalPage(pPg);
35697    }
35698  }
35699
35700  /* Update the database size and return.
35701  */
35702  assert( pPager->state>=PAGER_SHARED );
35703  if( pPager->dbSize<pPg->pgno ){
35704    pPager->dbSize = pPg->pgno;
35705  }
35706  return rc;
35707}
35708
35709/*
35710** Mark a data page as writeable. This routine must be called before
35711** making changes to a page. The caller must check the return value
35712** of this function and be careful not to change any page data unless
35713** this routine returns SQLITE_OK.
35714**
35715** The difference between this function and pager_write() is that this
35716** function also deals with the special case where 2 or more pages
35717** fit on a single disk sector. In this case all co-resident pages
35718** must have been written to the journal file before returning.
35719**
35720** If an error occurs, SQLITE_NOMEM or an IO error code is returned
35721** as appropriate. Otherwise, SQLITE_OK.
35722*/
35723SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
35724  int rc = SQLITE_OK;
35725
35726  PgHdr *pPg = pDbPage;
35727  Pager *pPager = pPg->pPager;
35728  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
35729
35730  if( nPagePerSector>1 ){
35731    Pgno nPageCount;          /* Total number of pages in database file */
35732    Pgno pg1;                 /* First page of the sector pPg is located on. */
35733    int nPage;                /* Number of pages starting at pg1 to journal */
35734    int ii;                   /* Loop counter */
35735    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
35736
35737    /* Set the doNotSync flag to 1. This is because we cannot allow a journal
35738    ** header to be written between the pages journaled by this function.
35739    */
35740    assert( !MEMDB );
35741    assert( pPager->doNotSync==0 );
35742    pPager->doNotSync = 1;
35743
35744    /* This trick assumes that both the page-size and sector-size are
35745    ** an integer power of 2. It sets variable pg1 to the identifier
35746    ** of the first page of the sector pPg is located on.
35747    */
35748    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
35749
35750    sqlite3PagerPagecount(pPager, (int *)&nPageCount);
35751    if( pPg->pgno>nPageCount ){
35752      nPage = (pPg->pgno - pg1)+1;
35753    }else if( (pg1+nPagePerSector-1)>nPageCount ){
35754      nPage = nPageCount+1-pg1;
35755    }else{
35756      nPage = nPagePerSector;
35757    }
35758    assert(nPage>0);
35759    assert(pg1<=pPg->pgno);
35760    assert((pg1+nPage)>pPg->pgno);
35761
35762    for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
35763      Pgno pg = pg1+ii;
35764      PgHdr *pPage;
35765      if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
35766        if( pg!=PAGER_MJ_PGNO(pPager) ){
35767          rc = sqlite3PagerGet(pPager, pg, &pPage);
35768          if( rc==SQLITE_OK ){
35769            rc = pager_write(pPage);
35770            if( pPage->flags&PGHDR_NEED_SYNC ){
35771              needSync = 1;
35772              assert(pPager->needSync);
35773            }
35774            sqlite3PagerUnref(pPage);
35775          }
35776        }
35777      }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
35778        if( pPage->flags&PGHDR_NEED_SYNC ){
35779          needSync = 1;
35780        }
35781        sqlite3PagerUnref(pPage);
35782      }
35783    }
35784
35785    /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
35786    ** starting at pg1, then it needs to be set for all of them. Because
35787    ** writing to any of these nPage pages may damage the others, the
35788    ** journal file must contain sync()ed copies of all of them
35789    ** before any of them can be written out to the database file.
35790    */
35791    if( rc==SQLITE_OK && needSync ){
35792      assert( !MEMDB && pPager->noSync==0 );
35793      for(ii=0; ii<nPage; ii++){
35794        PgHdr *pPage = pager_lookup(pPager, pg1+ii);
35795        if( pPage ){
35796          pPage->flags |= PGHDR_NEED_SYNC;
35797          sqlite3PagerUnref(pPage);
35798        }
35799      }
35800      assert(pPager->needSync);
35801    }
35802
35803    assert( pPager->doNotSync==1 );
35804    pPager->doNotSync = 0;
35805  }else{
35806    rc = pager_write(pDbPage);
35807  }
35808  return rc;
35809}
35810
35811/*
35812** Return TRUE if the page given in the argument was previously passed
35813** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
35814** to change the content of the page.
35815*/
35816#ifndef NDEBUG
35817SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
35818  return pPg->flags&PGHDR_DIRTY;
35819}
35820#endif
35821
35822#ifndef SQLITE_SECURE_DELETE
35823/*
35824** A call to this routine tells the pager that it is not necessary to
35825** write the information on page pPg back to the disk, even though
35826** that page might be marked as dirty.  This happens, for example, when
35827** the page has been added as a leaf of the freelist and so its
35828** content no longer matters.
35829**
35830** The overlying software layer calls this routine when all of the data
35831** on the given page is unused. The pager marks the page as clean so
35832** that it does not get written to disk.
35833**
35834** Tests show that this optimization can quadruple the speed of large
35835** DELETE operations.
35836*/
35837SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
35838  Pager *pPager = pPg->pPager;
35839  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
35840    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
35841    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
35842    pPg->flags |= PGHDR_DONT_WRITE;
35843#ifdef SQLITE_CHECK_PAGES
35844    pPg->pageHash = pager_pagehash(pPg);
35845#endif
35846  }
35847}
35848#endif /* !defined(SQLITE_SECURE_DELETE) */
35849
35850/*
35851** This routine is called to increment the value of the database file
35852** change-counter, stored as a 4-byte big-endian integer starting at
35853** byte offset 24 of the pager file.
35854**
35855** If the isDirectMode flag is zero, then this is done by calling
35856** sqlite3PagerWrite() on page 1, then modifying the contents of the
35857** page data. In this case the file will be updated when the current
35858** transaction is committed.
35859**
35860** The isDirectMode flag may only be non-zero if the library was compiled
35861** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
35862** if isDirect is non-zero, then the database file is updated directly
35863** by writing an updated version of page 1 using a call to the
35864** sqlite3OsWrite() function.
35865*/
35866static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
35867  int rc = SQLITE_OK;
35868
35869  /* Declare and initialize constant integer 'isDirect'. If the
35870  ** atomic-write optimization is enabled in this build, then isDirect
35871  ** is initialized to the value passed as the isDirectMode parameter
35872  ** to this function. Otherwise, it is always set to zero.
35873  **
35874  ** The idea is that if the atomic-write optimization is not
35875  ** enabled at compile time, the compiler can omit the tests of
35876  ** 'isDirect' below, as well as the block enclosed in the
35877  ** "if( isDirect )" condition.
35878  */
35879#ifndef SQLITE_ENABLE_ATOMIC_WRITE
35880# define DIRECT_MODE 0
35881  assert( isDirectMode==0 );
35882  UNUSED_PARAMETER(isDirectMode);
35883#else
35884# define DIRECT_MODE isDirectMode
35885#endif
35886
35887  assert( pPager->state>=PAGER_RESERVED );
35888  if( !pPager->changeCountDone && pPager->dbSize>0 ){
35889    PgHdr *pPgHdr;                /* Reference to page 1 */
35890    u32 change_counter;           /* Initial value of change-counter field */
35891
35892    assert( !pPager->tempFile && isOpen(pPager->fd) );
35893
35894    /* Open page 1 of the file for writing. */
35895    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
35896    assert( pPgHdr==0 || rc==SQLITE_OK );
35897
35898    /* If page one was fetched successfully, and this function is not
35899    ** operating in direct-mode, make page 1 writable.  When not in
35900    ** direct mode, page 1 is always held in cache and hence the PagerGet()
35901    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
35902    */
35903    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
35904      rc = sqlite3PagerWrite(pPgHdr);
35905    }
35906
35907    if( rc==SQLITE_OK ){
35908      /* Increment the value just read and write it back to byte 24. */
35909      change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
35910      change_counter++;
35911      put32bits(((char*)pPgHdr->pData)+24, change_counter);
35912
35913      /* If running in direct mode, write the contents of page 1 to the file. */
35914      if( DIRECT_MODE ){
35915        const void *zBuf = pPgHdr->pData;
35916        assert( pPager->dbFileSize>0 );
35917        rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
35918        if( rc==SQLITE_OK ){
35919          pPager->changeCountDone = 1;
35920        }
35921      }else{
35922        pPager->changeCountDone = 1;
35923      }
35924    }
35925
35926    /* Release the page reference. */
35927    sqlite3PagerUnref(pPgHdr);
35928  }
35929  return rc;
35930}
35931
35932/*
35933** Sync the pager file to disk. This is a no-op for in-memory files
35934** or pages with the Pager.noSync flag set.
35935**
35936** If successful, or called on a pager for which it is a no-op, this
35937** function returns SQLITE_OK. Otherwise, an IO error code is returned.
35938*/
35939SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
35940  int rc;                              /* Return code */
35941  assert( !MEMDB );
35942  if( pPager->noSync ){
35943    rc = SQLITE_OK;
35944  }else{
35945    rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
35946  }
35947  return rc;
35948}
35949
35950/*
35951** Sync the database file for the pager pPager. zMaster points to the name
35952** of a master journal file that should be written into the individual
35953** journal file. zMaster may be NULL, which is interpreted as no master
35954** journal (a single database transaction).
35955**
35956** This routine ensures that:
35957**
35958**   * The database file change-counter is updated,
35959**   * the journal is synced (unless the atomic-write optimization is used),
35960**   * all dirty pages are written to the database file,
35961**   * the database file is truncated (if required), and
35962**   * the database file synced.
35963**
35964** The only thing that remains to commit the transaction is to finalize
35965** (delete, truncate or zero the first part of) the journal file (or
35966** delete the master journal file if specified).
35967**
35968** Note that if zMaster==NULL, this does not overwrite a previous value
35969** passed to an sqlite3PagerCommitPhaseOne() call.
35970**
35971** If the final parameter - noSync - is true, then the database file itself
35972** is not synced. The caller must call sqlite3PagerSync() directly to
35973** sync the database file before calling CommitPhaseTwo() to delete the
35974** journal file in this case.
35975*/
35976SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
35977  Pager *pPager,                  /* Pager object */
35978  const char *zMaster,            /* If not NULL, the master journal name */
35979  int noSync                      /* True to omit the xSync on the db file */
35980){
35981  int rc = SQLITE_OK;             /* Return code */
35982
35983  /* The dbOrigSize is never set if journal_mode=OFF */
35984  assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF || pPager->dbOrigSize==0 );
35985
35986  /* If a prior error occurred, this routine should not be called.  ROLLBACK
35987  ** is the appropriate response to an error, not COMMIT.  Guard against
35988  ** coding errors by repeating the prior error. */
35989  if( NEVER(pPager->errCode) ) return pPager->errCode;
35990
35991  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
35992      pPager->zFilename, zMaster, pPager->dbSize));
35993
35994  if( MEMDB && pPager->dbModified ){
35995    /* If this is an in-memory db, or no pages have been written to, or this
35996    ** function has already been called, it is mostly a no-op.  However, any
35997    ** backup in progress needs to be restarted.
35998    */
35999    sqlite3BackupRestart(pPager->pBackup);
36000  }else if( pPager->state!=PAGER_SYNCED && pPager->dbModified ){
36001
36002    /* The following block updates the change-counter. Exactly how it
36003    ** does this depends on whether or not the atomic-update optimization
36004    ** was enabled at compile time, and if this transaction meets the
36005    ** runtime criteria to use the operation:
36006    **
36007    **    * The file-system supports the atomic-write property for
36008    **      blocks of size page-size, and
36009    **    * This commit is not part of a multi-file transaction, and
36010    **    * Exactly one page has been modified and store in the journal file.
36011    **
36012    ** If the optimization was not enabled at compile time, then the
36013    ** pager_incr_changecounter() function is called to update the change
36014    ** counter in 'indirect-mode'. If the optimization is compiled in but
36015    ** is not applicable to this transaction, call sqlite3JournalCreate()
36016    ** to make sure the journal file has actually been created, then call
36017    ** pager_incr_changecounter() to update the change-counter in indirect
36018    ** mode.
36019    **
36020    ** Otherwise, if the optimization is both enabled and applicable,
36021    ** then call pager_incr_changecounter() to update the change-counter
36022    ** in 'direct' mode. In this case the journal file will never be
36023    ** created for this transaction.
36024    */
36025#ifdef SQLITE_ENABLE_ATOMIC_WRITE
36026    PgHdr *pPg;
36027    assert( isOpen(pPager->jfd) || pPager->journalMode==PAGER_JOURNALMODE_OFF );
36028    if( !zMaster && isOpen(pPager->jfd)
36029     && pPager->journalOff==jrnlBufferSize(pPager)
36030     && pPager->dbSize>=pPager->dbFileSize
36031     && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
36032    ){
36033      /* Update the db file change counter via the direct-write method. The
36034      ** following call will modify the in-memory representation of page 1
36035      ** to include the updated change counter and then write page 1
36036      ** directly to the database file. Because of the atomic-write
36037      ** property of the host file-system, this is safe.
36038      */
36039      rc = pager_incr_changecounter(pPager, 1);
36040    }else{
36041      rc = sqlite3JournalCreate(pPager->jfd);
36042      if( rc==SQLITE_OK ){
36043        rc = pager_incr_changecounter(pPager, 0);
36044      }
36045    }
36046#else
36047    rc = pager_incr_changecounter(pPager, 0);
36048#endif
36049    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36050
36051    /* If this transaction has made the database smaller, then all pages
36052    ** being discarded by the truncation must be written to the journal
36053    ** file. This can only happen in auto-vacuum mode.
36054    **
36055    ** Before reading the pages with page numbers larger than the
36056    ** current value of Pager.dbSize, set dbSize back to the value
36057    ** that it took at the start of the transaction. Otherwise, the
36058    ** calls to sqlite3PagerGet() return zeroed pages instead of
36059    ** reading data from the database file.
36060    **
36061    ** When journal_mode==OFF the dbOrigSize is always zero, so this
36062    ** block never runs if journal_mode=OFF.
36063    */
36064#ifndef SQLITE_OMIT_AUTOVACUUM
36065    if( pPager->dbSize<pPager->dbOrigSize
36066     && ALWAYS(pPager->journalMode!=PAGER_JOURNALMODE_OFF)
36067    ){
36068      Pgno i;                                   /* Iterator variable */
36069      const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
36070      const Pgno dbSize = pPager->dbSize;       /* Database image size */
36071      pPager->dbSize = pPager->dbOrigSize;
36072      for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
36073        if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
36074          PgHdr *pPage;             /* Page to journal */
36075          rc = sqlite3PagerGet(pPager, i, &pPage);
36076          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36077          rc = sqlite3PagerWrite(pPage);
36078          sqlite3PagerUnref(pPage);
36079          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36080        }
36081      }
36082      pPager->dbSize = dbSize;
36083    }
36084#endif
36085
36086    /* Write the master journal name into the journal file. If a master
36087    ** journal file name has already been written to the journal file,
36088    ** or if zMaster is NULL (no master journal), then this call is a no-op.
36089    */
36090    rc = writeMasterJournal(pPager, zMaster);
36091    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36092
36093    /* Sync the journal file. If the atomic-update optimization is being
36094    ** used, this call will not create the journal file or perform any
36095    ** real IO.
36096    */
36097    rc = syncJournal(pPager);
36098    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36099
36100    /* Write all dirty pages to the database file. */
36101    rc = pager_write_pagelist(sqlite3PcacheDirtyList(pPager->pPCache));
36102    if( rc!=SQLITE_OK ){
36103      assert( rc!=SQLITE_IOERR_BLOCKED );
36104      goto commit_phase_one_exit;
36105    }
36106    sqlite3PcacheCleanAll(pPager->pPCache);
36107
36108    /* If the file on disk is not the same size as the database image,
36109    ** then use pager_truncate to grow or shrink the file here.
36110    */
36111    if( pPager->dbSize!=pPager->dbFileSize ){
36112      Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
36113      assert( pPager->state>=PAGER_EXCLUSIVE );
36114      rc = pager_truncate(pPager, nNew);
36115      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36116    }
36117
36118    /* Finally, sync the database file. */
36119    if( !pPager->noSync && !noSync ){
36120      rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
36121    }
36122    IOTRACE(("DBSYNC %p\n", pPager))
36123
36124    pPager->state = PAGER_SYNCED;
36125  }
36126
36127commit_phase_one_exit:
36128  return rc;
36129}
36130
36131
36132/*
36133** When this function is called, the database file has been completely
36134** updated to reflect the changes made by the current transaction and
36135** synced to disk. The journal file still exists in the file-system
36136** though, and if a failure occurs at this point it will eventually
36137** be used as a hot-journal and the current transaction rolled back.
36138**
36139** This function finalizes the journal file, either by deleting,
36140** truncating or partially zeroing it, so that it cannot be used
36141** for hot-journal rollback. Once this is done the transaction is
36142** irrevocably committed.
36143**
36144** If an error occurs, an IO error code is returned and the pager
36145** moves into the error state. Otherwise, SQLITE_OK is returned.
36146*/
36147SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
36148  int rc = SQLITE_OK;                  /* Return code */
36149
36150  /* This routine should not be called if a prior error has occurred.
36151  ** But if (due to a coding error elsewhere in the system) it does get
36152  ** called, just return the same error code without doing anything. */
36153  if( NEVER(pPager->errCode) ) return pPager->errCode;
36154
36155  /* This function should not be called if the pager is not in at least
36156  ** PAGER_RESERVED state. And indeed SQLite never does this. But it is
36157  ** nice to have this defensive test here anyway.
36158  */
36159  if( NEVER(pPager->state<PAGER_RESERVED) ) return SQLITE_ERROR;
36160
36161  /* An optimization. If the database was not actually modified during
36162  ** this transaction, the pager is running in exclusive-mode and is
36163  ** using persistent journals, then this function is a no-op.
36164  **
36165  ** The start of the journal file currently contains a single journal
36166  ** header with the nRec field set to 0. If such a journal is used as
36167  ** a hot-journal during hot-journal rollback, 0 changes will be made
36168  ** to the database file. So there is no need to zero the journal
36169  ** header. Since the pager is in exclusive mode, there is no need
36170  ** to drop any locks either.
36171  */
36172  if( pPager->dbModified==0 && pPager->exclusiveMode
36173   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
36174  ){
36175    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
36176    return SQLITE_OK;
36177  }
36178
36179  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
36180  assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dbModified );
36181  rc = pager_end_transaction(pPager, pPager->setMaster);
36182  return pager_error(pPager, rc);
36183}
36184
36185/*
36186** Rollback all changes. The database falls back to PAGER_SHARED mode.
36187**
36188** This function performs two tasks:
36189**
36190**   1) It rolls back the journal file, restoring all database file and
36191**      in-memory cache pages to the state they were in when the transaction
36192**      was opened, and
36193**   2) It finalizes the journal file, so that it is not used for hot
36194**      rollback at any point in the future.
36195**
36196** subject to the following qualifications:
36197**
36198** * If the journal file is not yet open when this function is called,
36199**   then only (2) is performed. In this case there is no journal file
36200**   to roll back.
36201**
36202** * If in an error state other than SQLITE_FULL, then task (1) is
36203**   performed. If successful, task (2). Regardless of the outcome
36204**   of either, the error state error code is returned to the caller
36205**   (i.e. either SQLITE_IOERR or SQLITE_CORRUPT).
36206**
36207** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether
36208**   or not (1) is succussful, also attempt (2). If successful, return
36209**   SQLITE_OK. Otherwise, enter the error state and return the first
36210**   error code encountered.
36211**
36212**   In this case there is no chance that the database was written to.
36213**   So is safe to finalize the journal file even if the playback
36214**   (operation 1) failed. However the pager must enter the error state
36215**   as the contents of the in-memory cache are now suspect.
36216**
36217** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only
36218**   attempt (2) if (1) is successful. Return SQLITE_OK if successful,
36219**   otherwise enter the error state and return the error code from the
36220**   failing operation.
36221**
36222**   In this case the database file may have been written to. So if the
36223**   playback operation did not succeed it would not be safe to finalize
36224**   the journal file. It needs to be left in the file-system so that
36225**   some other process can use it to restore the database state (by
36226**   hot-journal rollback).
36227*/
36228SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
36229  int rc = SQLITE_OK;                  /* Return code */
36230  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
36231  if( !pPager->dbModified || !isOpen(pPager->jfd) ){
36232    rc = pager_end_transaction(pPager, pPager->setMaster);
36233  }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
36234    if( pPager->state>=PAGER_EXCLUSIVE ){
36235      pager_playback(pPager, 0);
36236    }
36237    rc = pPager->errCode;
36238  }else{
36239    if( pPager->state==PAGER_RESERVED ){
36240      int rc2;
36241      rc = pager_playback(pPager, 0);
36242      rc2 = pager_end_transaction(pPager, pPager->setMaster);
36243      if( rc==SQLITE_OK ){
36244        rc = rc2;
36245      }
36246    }else{
36247      rc = pager_playback(pPager, 0);
36248    }
36249
36250    if( !MEMDB ){
36251      pPager->dbSizeValid = 0;
36252    }
36253
36254    /* If an error occurs during a ROLLBACK, we can no longer trust the pager
36255    ** cache. So call pager_error() on the way out to make any error
36256    ** persistent.
36257    */
36258    rc = pager_error(pPager, rc);
36259  }
36260  return rc;
36261}
36262
36263/*
36264** Return TRUE if the database file is opened read-only.  Return FALSE
36265** if the database is (in theory) writable.
36266*/
36267SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
36268  return pPager->readOnly;
36269}
36270
36271/*
36272** Return the number of references to the pager.
36273*/
36274SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
36275  return sqlite3PcacheRefCount(pPager->pPCache);
36276}
36277
36278/*
36279** Return the number of references to the specified page.
36280*/
36281SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
36282  return sqlite3PcachePageRefcount(pPage);
36283}
36284
36285#ifdef SQLITE_TEST
36286/*
36287** This routine is used for testing and analysis only.
36288*/
36289SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
36290  static int a[11];
36291  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
36292  a[1] = sqlite3PcachePagecount(pPager->pPCache);
36293  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
36294  a[3] = pPager->dbSizeValid ? (int) pPager->dbSize : -1;
36295  a[4] = pPager->state;
36296  a[5] = pPager->errCode;
36297  a[6] = pPager->nHit;
36298  a[7] = pPager->nMiss;
36299  a[8] = 0;  /* Used to be pPager->nOvfl */
36300  a[9] = pPager->nRead;
36301  a[10] = pPager->nWrite;
36302  return a;
36303}
36304#endif
36305
36306/*
36307** Return true if this is an in-memory pager.
36308*/
36309SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
36310  return MEMDB;
36311}
36312
36313/*
36314** Check that there are at least nSavepoint savepoints open. If there are
36315** currently less than nSavepoints open, then open one or more savepoints
36316** to make up the difference. If the number of savepoints is already
36317** equal to nSavepoint, then this function is a no-op.
36318**
36319** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
36320** occurs while opening the sub-journal file, then an IO error code is
36321** returned. Otherwise, SQLITE_OK.
36322*/
36323SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
36324  int rc = SQLITE_OK;                       /* Return code */
36325  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
36326
36327  if( nSavepoint>nCurrent && pPager->useJournal ){
36328    int ii;                                 /* Iterator variable */
36329    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
36330
36331    /* Either there is no active journal or the sub-journal is open or
36332    ** the journal is always stored in memory */
36333    assert( pPager->nSavepoint==0 || isOpen(pPager->sjfd) ||
36334            pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
36335
36336    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
36337    ** if the allocation fails. Otherwise, zero the new portion in case a
36338    ** malloc failure occurs while populating it in the for(...) loop below.
36339    */
36340    aNew = (PagerSavepoint *)sqlite3Realloc(
36341        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
36342    );
36343    if( !aNew ){
36344      return SQLITE_NOMEM;
36345    }
36346    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
36347    pPager->aSavepoint = aNew;
36348    pPager->nSavepoint = nSavepoint;
36349
36350    /* Populate the PagerSavepoint structures just allocated. */
36351    for(ii=nCurrent; ii<nSavepoint; ii++){
36352      assert( pPager->dbSizeValid );
36353      aNew[ii].nOrig = pPager->dbSize;
36354      if( isOpen(pPager->jfd) && ALWAYS(pPager->journalOff>0) ){
36355        aNew[ii].iOffset = pPager->journalOff;
36356      }else{
36357        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
36358      }
36359      aNew[ii].iSubRec = pPager->nSubRec;
36360      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
36361      if( !aNew[ii].pInSavepoint ){
36362        return SQLITE_NOMEM;
36363      }
36364    }
36365
36366    /* Open the sub-journal, if it is not already opened. */
36367    rc = openSubJournal(pPager);
36368    assertTruncateConstraint(pPager);
36369  }
36370
36371  return rc;
36372}
36373
36374/*
36375** This function is called to rollback or release (commit) a savepoint.
36376** The savepoint to release or rollback need not be the most recently
36377** created savepoint.
36378**
36379** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
36380** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
36381** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
36382** that have occurred since the specified savepoint was created.
36383**
36384** The savepoint to rollback or release is identified by parameter
36385** iSavepoint. A value of 0 means to operate on the outermost savepoint
36386** (the first created). A value of (Pager.nSavepoint-1) means operate
36387** on the most recently created savepoint. If iSavepoint is greater than
36388** (Pager.nSavepoint-1), then this function is a no-op.
36389**
36390** If a negative value is passed to this function, then the current
36391** transaction is rolled back. This is different to calling
36392** sqlite3PagerRollback() because this function does not terminate
36393** the transaction or unlock the database, it just restores the
36394** contents of the database to its original state.
36395**
36396** In any case, all savepoints with an index greater than iSavepoint
36397** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
36398** then savepoint iSavepoint is also destroyed.
36399**
36400** This function may return SQLITE_NOMEM if a memory allocation fails,
36401** or an IO error code if an IO error occurs while rolling back a
36402** savepoint. If no errors occur, SQLITE_OK is returned.
36403*/
36404SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
36405  int rc = SQLITE_OK;
36406
36407  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
36408  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
36409
36410  if( iSavepoint<pPager->nSavepoint ){
36411    int ii;            /* Iterator variable */
36412    int nNew;          /* Number of remaining savepoints after this op. */
36413
36414    /* Figure out how many savepoints will still be active after this
36415    ** operation. Store this value in nNew. Then free resources associated
36416    ** with any savepoints that are destroyed by this operation.
36417    */
36418    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
36419    for(ii=nNew; ii<pPager->nSavepoint; ii++){
36420      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
36421    }
36422    pPager->nSavepoint = nNew;
36423
36424    /* If this is a release of the outermost savepoint, truncate
36425    ** the sub-journal to zero bytes in size. */
36426    if( op==SAVEPOINT_RELEASE ){
36427      if( nNew==0 && isOpen(pPager->sjfd) ){
36428        /* Only truncate if it is an in-memory sub-journal. */
36429        if( sqlite3IsMemJournal(pPager->sjfd) ){
36430          rc = sqlite3OsTruncate(pPager->sjfd, 0);
36431        }
36432        pPager->nSubRec = 0;
36433      }
36434    }
36435    /* Else this is a rollback operation, playback the specified savepoint.
36436    ** If this is a temp-file, it is possible that the journal file has
36437    ** not yet been opened. In this case there have been no changes to
36438    ** the database file, so the playback operation can be skipped.
36439    */
36440    else if( isOpen(pPager->jfd) ){
36441      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
36442      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
36443      assert(rc!=SQLITE_DONE);
36444    }
36445
36446  }
36447  return rc;
36448}
36449
36450/*
36451** Return the full pathname of the database file.
36452*/
36453SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
36454  return pPager->zFilename;
36455}
36456
36457/*
36458** Return the VFS structure for the pager.
36459*/
36460SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
36461  return pPager->pVfs;
36462}
36463
36464/*
36465** Return the file handle for the database file associated
36466** with the pager.  This might return NULL if the file has
36467** not yet been opened.
36468*/
36469SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
36470  return pPager->fd;
36471}
36472
36473/*
36474** Return the full pathname of the journal file.
36475*/
36476SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
36477  return pPager->zJournal;
36478}
36479
36480/*
36481** Return true if fsync() calls are disabled for this pager.  Return FALSE
36482** if fsync()s are executed normally.
36483*/
36484SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
36485  return pPager->noSync;
36486}
36487
36488#ifdef SQLITE_HAS_CODEC
36489/*
36490** Set or retrieve the codec for this pager
36491*/
36492static void sqlite3PagerSetCodec(
36493  Pager *pPager,
36494  void *(*xCodec)(void*,void*,Pgno,int),
36495  void (*xCodecSizeChng)(void*,int,int),
36496  void (*xCodecFree)(void*),
36497  void *pCodec
36498){
36499  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
36500  pPager->xCodec = pPager->memDb ? 0 : xCodec;
36501  pPager->xCodecSizeChng = xCodecSizeChng;
36502  pPager->xCodecFree = xCodecFree;
36503  pPager->pCodec = pCodec;
36504  pagerReportSize(pPager);
36505}
36506static void *sqlite3PagerGetCodec(Pager *pPager){
36507  return pPager->pCodec;
36508}
36509#endif
36510
36511#ifndef SQLITE_OMIT_AUTOVACUUM
36512/*
36513** Move the page pPg to location pgno in the file.
36514**
36515** There must be no references to the page previously located at
36516** pgno (which we call pPgOld) though that page is allowed to be
36517** in cache.  If the page previously located at pgno is not already
36518** in the rollback journal, it is not put there by by this routine.
36519**
36520** References to the page pPg remain valid. Updating any
36521** meta-data associated with pPg (i.e. data stored in the nExtra bytes
36522** allocated along with the page) is the responsibility of the caller.
36523**
36524** A transaction must be active when this routine is called. It used to be
36525** required that a statement transaction was not active, but this restriction
36526** has been removed (CREATE INDEX needs to move a page when a statement
36527** transaction is active).
36528**
36529** If the fourth argument, isCommit, is non-zero, then this page is being
36530** moved as part of a database reorganization just before the transaction
36531** is being committed. In this case, it is guaranteed that the database page
36532** pPg refers to will not be written to again within this transaction.
36533**
36534** This function may return SQLITE_NOMEM or an IO error code if an error
36535** occurs. Otherwise, it returns SQLITE_OK.
36536*/
36537SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
36538  PgHdr *pPgOld;               /* The page being overwritten. */
36539  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
36540  int rc;                      /* Return code */
36541  Pgno origPgno;               /* The original page number */
36542
36543  assert( pPg->nRef>0 );
36544
36545  /* In order to be able to rollback, an in-memory database must journal
36546  ** the page we are moving from.
36547  */
36548  if( MEMDB ){
36549    rc = sqlite3PagerWrite(pPg);
36550    if( rc ) return rc;
36551  }
36552
36553  /* If the page being moved is dirty and has not been saved by the latest
36554  ** savepoint, then save the current contents of the page into the
36555  ** sub-journal now. This is required to handle the following scenario:
36556  **
36557  **   BEGIN;
36558  **     <journal page X, then modify it in memory>
36559  **     SAVEPOINT one;
36560  **       <Move page X to location Y>
36561  **     ROLLBACK TO one;
36562  **
36563  ** If page X were not written to the sub-journal here, it would not
36564  ** be possible to restore its contents when the "ROLLBACK TO one"
36565  ** statement were is processed.
36566  **
36567  ** subjournalPage() may need to allocate space to store pPg->pgno into
36568  ** one or more savepoint bitvecs. This is the reason this function
36569  ** may return SQLITE_NOMEM.
36570  */
36571  if( pPg->flags&PGHDR_DIRTY
36572   && subjRequiresPage(pPg)
36573   && SQLITE_OK!=(rc = subjournalPage(pPg))
36574  ){
36575    return rc;
36576  }
36577
36578  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
36579      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
36580  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
36581
36582  /* If the journal needs to be sync()ed before page pPg->pgno can
36583  ** be written to, store pPg->pgno in local variable needSyncPgno.
36584  **
36585  ** If the isCommit flag is set, there is no need to remember that
36586  ** the journal needs to be sync()ed before database page pPg->pgno
36587  ** can be written to. The caller has already promised not to write to it.
36588  */
36589  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
36590    needSyncPgno = pPg->pgno;
36591    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
36592    assert( pPg->flags&PGHDR_DIRTY );
36593    assert( pPager->needSync );
36594  }
36595
36596  /* If the cache contains a page with page-number pgno, remove it
36597  ** from its hash chain. Also, if the PgHdr.needSync was set for
36598  ** page pgno before the 'move' operation, it needs to be retained
36599  ** for the page moved there.
36600  */
36601  pPg->flags &= ~PGHDR_NEED_SYNC;
36602  pPgOld = pager_lookup(pPager, pgno);
36603  assert( !pPgOld || pPgOld->nRef==1 );
36604  if( pPgOld ){
36605    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
36606    if( MEMDB ){
36607      /* Do not discard pages from an in-memory database since we might
36608      ** need to rollback later.  Just move the page out of the way. */
36609      assert( pPager->dbSizeValid );
36610      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
36611    }else{
36612      sqlite3PcacheDrop(pPgOld);
36613    }
36614  }
36615
36616  origPgno = pPg->pgno;
36617  sqlite3PcacheMove(pPg, pgno);
36618  sqlite3PcacheMakeDirty(pPg);
36619  pPager->dbModified = 1;
36620
36621  if( needSyncPgno ){
36622    /* If needSyncPgno is non-zero, then the journal file needs to be
36623    ** sync()ed before any data is written to database file page needSyncPgno.
36624    ** Currently, no such page exists in the page-cache and the
36625    ** "is journaled" bitvec flag has been set. This needs to be remedied by
36626    ** loading the page into the pager-cache and setting the PgHdr.needSync
36627    ** flag.
36628    **
36629    ** If the attempt to load the page into the page-cache fails, (due
36630    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
36631    ** array. Otherwise, if the page is loaded and written again in
36632    ** this transaction, it may be written to the database file before
36633    ** it is synced into the journal file. This way, it may end up in
36634    ** the journal file twice, but that is not a problem.
36635    **
36636    ** The sqlite3PagerGet() call may cause the journal to sync. So make
36637    ** sure the Pager.needSync flag is set too.
36638    */
36639    PgHdr *pPgHdr;
36640    assert( pPager->needSync );
36641    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
36642    if( rc!=SQLITE_OK ){
36643      if( needSyncPgno<=pPager->dbOrigSize ){
36644        assert( pPager->pTmpSpace!=0 );
36645        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
36646      }
36647      return rc;
36648    }
36649    pPager->needSync = 1;
36650    assert( pPager->noSync==0 && !MEMDB );
36651    pPgHdr->flags |= PGHDR_NEED_SYNC;
36652    sqlite3PcacheMakeDirty(pPgHdr);
36653    sqlite3PagerUnref(pPgHdr);
36654  }
36655
36656  /*
36657  ** For an in-memory database, make sure the original page continues
36658  ** to exist, in case the transaction needs to roll back.  Use pPgOld
36659  ** as the original page since it has already been allocated.
36660  */
36661  if( MEMDB ){
36662    sqlite3PcacheMove(pPgOld, origPgno);
36663    sqlite3PagerUnref(pPgOld);
36664  }
36665
36666  return SQLITE_OK;
36667}
36668#endif
36669
36670/*
36671** Return a pointer to the data for the specified page.
36672*/
36673SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
36674  assert( pPg->nRef>0 || pPg->pPager->memDb );
36675  return pPg->pData;
36676}
36677
36678/*
36679** Return a pointer to the Pager.nExtra bytes of "extra" space
36680** allocated along with the specified page.
36681*/
36682SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
36683  return pPg->pExtra;
36684}
36685
36686/*
36687** Get/set the locking-mode for this pager. Parameter eMode must be one
36688** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
36689** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
36690** the locking-mode is set to the value specified.
36691**
36692** The returned value is either PAGER_LOCKINGMODE_NORMAL or
36693** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
36694** locking-mode.
36695*/
36696SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
36697  assert( eMode==PAGER_LOCKINGMODE_QUERY
36698            || eMode==PAGER_LOCKINGMODE_NORMAL
36699            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
36700  assert( PAGER_LOCKINGMODE_QUERY<0 );
36701  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
36702  if( eMode>=0 && !pPager->tempFile ){
36703    pPager->exclusiveMode = (u8)eMode;
36704  }
36705  return (int)pPager->exclusiveMode;
36706}
36707
36708/*
36709** Get/set the journal-mode for this pager. Parameter eMode must be one of:
36710**
36711**    PAGER_JOURNALMODE_QUERY
36712**    PAGER_JOURNALMODE_DELETE
36713**    PAGER_JOURNALMODE_TRUNCATE
36714**    PAGER_JOURNALMODE_PERSIST
36715**    PAGER_JOURNALMODE_OFF
36716**    PAGER_JOURNALMODE_MEMORY
36717**
36718** If the parameter is not _QUERY, then the journal_mode is set to the
36719** value specified if the change is allowed.  The change is disallowed
36720** for the following reasons:
36721**
36722**   *  An in-memory database can only have its journal_mode set to _OFF
36723**      or _MEMORY.
36724**
36725**   *  The journal mode may not be changed while a transaction is active.
36726**
36727** The returned indicate the current (possibly updated) journal-mode.
36728*/
36729SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
36730  assert( eMode==PAGER_JOURNALMODE_QUERY
36731            || eMode==PAGER_JOURNALMODE_DELETE
36732            || eMode==PAGER_JOURNALMODE_TRUNCATE
36733            || eMode==PAGER_JOURNALMODE_PERSIST
36734            || eMode==PAGER_JOURNALMODE_OFF
36735            || eMode==PAGER_JOURNALMODE_MEMORY );
36736  assert( PAGER_JOURNALMODE_QUERY<0 );
36737  if( eMode>=0
36738   && (!MEMDB || eMode==PAGER_JOURNALMODE_MEMORY
36739              || eMode==PAGER_JOURNALMODE_OFF)
36740   && !pPager->dbModified
36741   && (!isOpen(pPager->jfd) || 0==pPager->journalOff)
36742  ){
36743    if( isOpen(pPager->jfd) ){
36744      sqlite3OsClose(pPager->jfd);
36745    }
36746    pPager->journalMode = (u8)eMode;
36747  }
36748  return (int)pPager->journalMode;
36749}
36750
36751/*
36752** Get/set the size-limit used for persistent journal files.
36753**
36754** Setting the size limit to -1 means no limit is enforced.
36755** An attempt to set a limit smaller than -1 is a no-op.
36756*/
36757SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
36758  if( iLimit>=-1 ){
36759    pPager->journalSizeLimit = iLimit;
36760  }
36761  return pPager->journalSizeLimit;
36762}
36763
36764/*
36765** Return a pointer to the pPager->pBackup variable. The backup module
36766** in backup.c maintains the content of this variable. This module
36767** uses it opaquely as an argument to sqlite3BackupRestart() and
36768** sqlite3BackupUpdate() only.
36769*/
36770SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
36771  return &pPager->pBackup;
36772}
36773
36774#endif /* SQLITE_OMIT_DISKIO */
36775
36776/************** End of pager.c ***********************************************/
36777/************** Begin file btmutex.c *****************************************/
36778/*
36779** 2007 August 27
36780**
36781** The author disclaims copyright to this source code.  In place of
36782** a legal notice, here is a blessing:
36783**
36784**    May you do good and not evil.
36785**    May you find forgiveness for yourself and forgive others.
36786**    May you share freely, never taking more than you give.
36787**
36788*************************************************************************
36789**
36790** This file contains code used to implement mutexes on Btree objects.
36791** This code really belongs in btree.c.  But btree.c is getting too
36792** big and we want to break it down some.  This packaged seemed like
36793** a good breakout.
36794*/
36795/************** Include btreeInt.h in the middle of btmutex.c ****************/
36796/************** Begin file btreeInt.h ****************************************/
36797/*
36798** 2004 April 6
36799**
36800** The author disclaims copyright to this source code.  In place of
36801** a legal notice, here is a blessing:
36802**
36803**    May you do good and not evil.
36804**    May you find forgiveness for yourself and forgive others.
36805**    May you share freely, never taking more than you give.
36806**
36807*************************************************************************
36808** This file implements a external (disk-based) database using BTrees.
36809** For a detailed discussion of BTrees, refer to
36810**
36811**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
36812**     "Sorting And Searching", pages 473-480. Addison-Wesley
36813**     Publishing Company, Reading, Massachusetts.
36814**
36815** The basic idea is that each page of the file contains N database
36816** entries and N+1 pointers to subpages.
36817**
36818**   ----------------------------------------------------------------
36819**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
36820**   ----------------------------------------------------------------
36821**
36822** All of the keys on the page that Ptr(0) points to have values less
36823** than Key(0).  All of the keys on page Ptr(1) and its subpages have
36824** values greater than Key(0) and less than Key(1).  All of the keys
36825** on Ptr(N) and its subpages have values greater than Key(N-1).  And
36826** so forth.
36827**
36828** Finding a particular key requires reading O(log(M)) pages from the
36829** disk where M is the number of entries in the tree.
36830**
36831** In this implementation, a single file can hold one or more separate
36832** BTrees.  Each BTree is identified by the index of its root page.  The
36833** key and data for any entry are combined to form the "payload".  A
36834** fixed amount of payload can be carried directly on the database
36835** page.  If the payload is larger than the preset amount then surplus
36836** bytes are stored on overflow pages.  The payload for an entry
36837** and the preceding pointer are combined to form a "Cell".  Each
36838** page has a small header which contains the Ptr(N) pointer and other
36839** information such as the size of key and data.
36840**
36841** FORMAT DETAILS
36842**
36843** The file is divided into pages.  The first page is called page 1,
36844** the second is page 2, and so forth.  A page number of zero indicates
36845** "no such page".  The page size can be any power of 2 between 512 and 32768.
36846** Each page can be either a btree page, a freelist page, an overflow
36847** page, or a pointer-map page.
36848**
36849** The first page is always a btree page.  The first 100 bytes of the first
36850** page contain a special header (the "file header") that describes the file.
36851** The format of the file header is as follows:
36852**
36853**   OFFSET   SIZE    DESCRIPTION
36854**      0      16     Header string: "SQLite format 3\000"
36855**     16       2     Page size in bytes.
36856**     18       1     File format write version
36857**     19       1     File format read version
36858**     20       1     Bytes of unused space at the end of each page
36859**     21       1     Max embedded payload fraction
36860**     22       1     Min embedded payload fraction
36861**     23       1     Min leaf payload fraction
36862**     24       4     File change counter
36863**     28       4     Reserved for future use
36864**     32       4     First freelist page
36865**     36       4     Number of freelist pages in the file
36866**     40      60     15 4-byte meta values passed to higher layers
36867**
36868**     40       4     Schema cookie
36869**     44       4     File format of schema layer
36870**     48       4     Size of page cache
36871**     52       4     Largest root-page (auto/incr_vacuum)
36872**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
36873**     60       4     User version
36874**     64       4     Incremental vacuum mode
36875**     68       4     unused
36876**     72       4     unused
36877**     76       4     unused
36878**
36879** All of the integer values are big-endian (most significant byte first).
36880**
36881** The file change counter is incremented when the database is changed
36882** This counter allows other processes to know when the file has changed
36883** and thus when they need to flush their cache.
36884**
36885** The max embedded payload fraction is the amount of the total usable
36886** space in a page that can be consumed by a single cell for standard
36887** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
36888** is to limit the maximum cell size so that at least 4 cells will fit
36889** on one page.  Thus the default max embedded payload fraction is 64.
36890**
36891** If the payload for a cell is larger than the max payload, then extra
36892** payload is spilled to overflow pages.  Once an overflow page is allocated,
36893** as many bytes as possible are moved into the overflow pages without letting
36894** the cell size drop below the min embedded payload fraction.
36895**
36896** The min leaf payload fraction is like the min embedded payload fraction
36897** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
36898** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
36899** not specified in the header.
36900**
36901** Each btree pages is divided into three sections:  The header, the
36902** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
36903** file header that occurs before the page header.
36904**
36905**      |----------------|
36906**      | file header    |   100 bytes.  Page 1 only.
36907**      |----------------|
36908**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
36909**      |----------------|
36910**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
36911**      | array          |   |  Grows downward
36912**      |                |   v
36913**      |----------------|
36914**      | unallocated    |
36915**      | space          |
36916**      |----------------|   ^  Grows upwards
36917**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
36918**      | area           |   |  and free space fragments.
36919**      |----------------|
36920**
36921** The page headers looks like this:
36922**
36923**   OFFSET   SIZE     DESCRIPTION
36924**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
36925**      1       2      byte offset to the first freeblock
36926**      3       2      number of cells on this page
36927**      5       2      first byte of the cell content area
36928**      7       1      number of fragmented free bytes
36929**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
36930**
36931** The flags define the format of this btree page.  The leaf flag means that
36932** this page has no children.  The zerodata flag means that this page carries
36933** only keys and no data.  The intkey flag means that the key is a integer
36934** which is stored in the key size entry of the cell header rather than in
36935** the payload area.
36936**
36937** The cell pointer array begins on the first byte after the page header.
36938** The cell pointer array contains zero or more 2-byte numbers which are
36939** offsets from the beginning of the page to the cell content in the cell
36940** content area.  The cell pointers occur in sorted order.  The system strives
36941** to keep free space after the last cell pointer so that new cells can
36942** be easily added without having to defragment the page.
36943**
36944** Cell content is stored at the very end of the page and grows toward the
36945** beginning of the page.
36946**
36947** Unused space within the cell content area is collected into a linked list of
36948** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
36949** to the first freeblock is given in the header.  Freeblocks occur in
36950** increasing order.  Because a freeblock must be at least 4 bytes in size,
36951** any group of 3 or fewer unused bytes in the cell content area cannot
36952** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
36953** a fragment.  The total number of bytes in all fragments is recorded.
36954** in the page header at offset 7.
36955**
36956**    SIZE    DESCRIPTION
36957**      2     Byte offset of the next freeblock
36958**      2     Bytes in this freeblock
36959**
36960** Cells are of variable length.  Cells are stored in the cell content area at
36961** the end of the page.  Pointers to the cells are in the cell pointer array
36962** that immediately follows the page header.  Cells is not necessarily
36963** contiguous or in order, but cell pointers are contiguous and in order.
36964**
36965** Cell content makes use of variable length integers.  A variable
36966** length integer is 1 to 9 bytes where the lower 7 bits of each
36967** byte are used.  The integer consists of all bytes that have bit 8 set and
36968** the first byte with bit 8 clear.  The most significant byte of the integer
36969** appears first.  A variable-length integer may not be more than 9 bytes long.
36970** As a special case, all 8 bytes of the 9th byte are used as data.  This
36971** allows a 64-bit integer to be encoded in 9 bytes.
36972**
36973**    0x00                      becomes  0x00000000
36974**    0x7f                      becomes  0x0000007f
36975**    0x81 0x00                 becomes  0x00000080
36976**    0x82 0x00                 becomes  0x00000100
36977**    0x80 0x7f                 becomes  0x0000007f
36978**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
36979**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
36980**
36981** Variable length integers are used for rowids and to hold the number of
36982** bytes of key and data in a btree cell.
36983**
36984** The content of a cell looks like this:
36985**
36986**    SIZE    DESCRIPTION
36987**      4     Page number of the left child. Omitted if leaf flag is set.
36988**     var    Number of bytes of data. Omitted if the zerodata flag is set.
36989**     var    Number of bytes of key. Or the key itself if intkey flag is set.
36990**      *     Payload
36991**      4     First page of the overflow chain.  Omitted if no overflow
36992**
36993** Overflow pages form a linked list.  Each page except the last is completely
36994** filled with data (pagesize - 4 bytes).  The last page can have as little
36995** as 1 byte of data.
36996**
36997**    SIZE    DESCRIPTION
36998**      4     Page number of next overflow page
36999**      *     Data
37000**
37001** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
37002** file header points to the first in a linked list of trunk page.  Each trunk
37003** page points to multiple leaf pages.  The content of a leaf page is
37004** unspecified.  A trunk page looks like this:
37005**
37006**    SIZE    DESCRIPTION
37007**      4     Page number of next trunk page
37008**      4     Number of leaf pointers on this page
37009**      *     zero or more pages numbers of leaves
37010*/
37011
37012
37013/* The following value is the maximum cell size assuming a maximum page
37014** size give above.
37015*/
37016#define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
37017
37018/* The maximum number of cells on a single page of the database.  This
37019** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
37020** plus 2 bytes for the index to the cell in the page header).  Such
37021** small cells will be rare, but they are possible.
37022*/
37023#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
37024
37025/* Forward declarations */
37026typedef struct MemPage MemPage;
37027typedef struct BtLock BtLock;
37028
37029/*
37030** This is a magic string that appears at the beginning of every
37031** SQLite database in order to identify the file as a real database.
37032**
37033** You can change this value at compile-time by specifying a
37034** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
37035** header must be exactly 16 bytes including the zero-terminator so
37036** the string itself should be 15 characters long.  If you change
37037** the header, then your custom library will not be able to read
37038** databases generated by the standard tools and the standard tools
37039** will not be able to read databases created by your custom library.
37040*/
37041#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
37042#  define SQLITE_FILE_HEADER "SQLite format 3"
37043#endif
37044
37045/*
37046** Page type flags.  An ORed combination of these flags appear as the
37047** first byte of on-disk image of every BTree page.
37048*/
37049#define PTF_INTKEY    0x01
37050#define PTF_ZERODATA  0x02
37051#define PTF_LEAFDATA  0x04
37052#define PTF_LEAF      0x08
37053
37054/*
37055** As each page of the file is loaded into memory, an instance of the following
37056** structure is appended and initialized to zero.  This structure stores
37057** information about the page that is decoded from the raw file page.
37058**
37059** The pParent field points back to the parent page.  This allows us to
37060** walk up the BTree from any leaf to the root.  Care must be taken to
37061** unref() the parent page pointer when this page is no longer referenced.
37062** The pageDestructor() routine handles that chore.
37063**
37064** Access to all fields of this structure is controlled by the mutex
37065** stored in MemPage.pBt->mutex.
37066*/
37067struct MemPage {
37068  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
37069  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
37070  u8 intKey;           /* True if intkey flag is set */
37071  u8 leaf;             /* True if leaf flag is set */
37072  u8 hasData;          /* True if this page stores data */
37073  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
37074  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
37075  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
37076  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
37077  u16 cellOffset;      /* Index in aData of first cell pointer */
37078  u16 nFree;           /* Number of free bytes on the page */
37079  u16 nCell;           /* Number of cells on this page, local and ovfl */
37080  u16 maskPage;        /* Mask for page offset */
37081  struct _OvflCell {   /* Cells that will not fit on aData[] */
37082    u8 *pCell;          /* Pointers to the body of the overflow cell */
37083    u16 idx;            /* Insert this cell before idx-th non-overflow cell */
37084  } aOvfl[5];
37085  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
37086  u8 *aData;           /* Pointer to disk image of the page data */
37087  DbPage *pDbPage;     /* Pager page handle */
37088  Pgno pgno;           /* Page number for this page */
37089};
37090
37091/*
37092** The in-memory image of a disk page has the auxiliary information appended
37093** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
37094** that extra information.
37095*/
37096#define EXTRA_SIZE sizeof(MemPage)
37097
37098/*
37099** A linked list of the following structures is stored at BtShared.pLock.
37100** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
37101** is opened on the table with root page BtShared.iTable. Locks are removed
37102** from this list when a transaction is committed or rolled back, or when
37103** a btree handle is closed.
37104*/
37105struct BtLock {
37106  Btree *pBtree;        /* Btree handle holding this lock */
37107  Pgno iTable;          /* Root page of table */
37108  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
37109  BtLock *pNext;        /* Next in BtShared.pLock list */
37110};
37111
37112/* Candidate values for BtLock.eLock */
37113#define READ_LOCK     1
37114#define WRITE_LOCK    2
37115
37116/* A Btree handle
37117**
37118** A database connection contains a pointer to an instance of
37119** this object for every database file that it has open.  This structure
37120** is opaque to the database connection.  The database connection cannot
37121** see the internals of this structure and only deals with pointers to
37122** this structure.
37123**
37124** For some database files, the same underlying database cache might be
37125** shared between multiple connections.  In that case, each connection
37126** has it own instance of this object.  But each instance of this object
37127** points to the same BtShared object.  The database cache and the
37128** schema associated with the database file are all contained within
37129** the BtShared object.
37130**
37131** All fields in this structure are accessed under sqlite3.mutex.
37132** The pBt pointer itself may not be changed while there exists cursors
37133** in the referenced BtShared that point back to this Btree since those
37134** cursors have to do go through this Btree to find their BtShared and
37135** they often do so without holding sqlite3.mutex.
37136*/
37137struct Btree {
37138  sqlite3 *db;       /* The database connection holding this btree */
37139  BtShared *pBt;     /* Sharable content of this btree */
37140  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
37141  u8 sharable;       /* True if we can share pBt with another db */
37142  u8 locked;         /* True if db currently has pBt locked */
37143  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
37144  int nBackup;       /* Number of backup operations reading this btree */
37145  Btree *pNext;      /* List of other sharable Btrees from the same db */
37146  Btree *pPrev;      /* Back pointer of the same list */
37147#ifndef SQLITE_OMIT_SHARED_CACHE
37148  BtLock lock;       /* Object used to lock page 1 */
37149#endif
37150};
37151
37152/*
37153** Btree.inTrans may take one of the following values.
37154**
37155** If the shared-data extension is enabled, there may be multiple users
37156** of the Btree structure. At most one of these may open a write transaction,
37157** but any number may have active read transactions.
37158*/
37159#define TRANS_NONE  0
37160#define TRANS_READ  1
37161#define TRANS_WRITE 2
37162
37163/*
37164** An instance of this object represents a single database file.
37165**
37166** A single database file can be in use as the same time by two
37167** or more database connections.  When two or more connections are
37168** sharing the same database file, each connection has it own
37169** private Btree object for the file and each of those Btrees points
37170** to this one BtShared object.  BtShared.nRef is the number of
37171** connections currently sharing this database file.
37172**
37173** Fields in this structure are accessed under the BtShared.mutex
37174** mutex, except for nRef and pNext which are accessed under the
37175** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
37176** may not be modified once it is initially set as long as nRef>0.
37177** The pSchema field may be set once under BtShared.mutex and
37178** thereafter is unchanged as long as nRef>0.
37179**
37180** isPending:
37181**
37182**   If a BtShared client fails to obtain a write-lock on a database
37183**   table (because there exists one or more read-locks on the table),
37184**   the shared-cache enters 'pending-lock' state and isPending is
37185**   set to true.
37186**
37187**   The shared-cache leaves the 'pending lock' state when either of
37188**   the following occur:
37189**
37190**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
37191**     2) The number of locks held by other connections drops to zero.
37192**
37193**   while in the 'pending-lock' state, no connection may start a new
37194**   transaction.
37195**
37196**   This feature is included to help prevent writer-starvation.
37197*/
37198struct BtShared {
37199  Pager *pPager;        /* The page cache */
37200  sqlite3 *db;          /* Database connection currently using this Btree */
37201  BtCursor *pCursor;    /* A list of all open cursors */
37202  MemPage *pPage1;      /* First page of the database */
37203  u8 readOnly;          /* True if the underlying file is readonly */
37204  u8 pageSizeFixed;     /* True if the page size can no longer be changed */
37205#ifndef SQLITE_OMIT_AUTOVACUUM
37206  u8 autoVacuum;        /* True if auto-vacuum is enabled */
37207  u8 incrVacuum;        /* True if incr-vacuum is enabled */
37208#endif
37209  u16 pageSize;         /* Total number of bytes on a page */
37210  u16 usableSize;       /* Number of usable bytes on each page */
37211  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
37212  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
37213  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
37214  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
37215  u8 inTransaction;     /* Transaction state */
37216  int nTransaction;     /* Number of open transactions (read + write) */
37217  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
37218  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
37219  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
37220  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
37221#ifndef SQLITE_OMIT_SHARED_CACHE
37222  int nRef;             /* Number of references to this structure */
37223  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
37224  BtLock *pLock;        /* List of locks held on this shared-btree struct */
37225  Btree *pWriter;       /* Btree with currently open write transaction */
37226  u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
37227  u8 isPending;         /* If waiting for read-locks to clear */
37228#endif
37229  u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
37230};
37231
37232/*
37233** An instance of the following structure is used to hold information
37234** about a cell.  The parseCellPtr() function fills in this structure
37235** based on information extract from the raw disk page.
37236*/
37237typedef struct CellInfo CellInfo;
37238struct CellInfo {
37239  u8 *pCell;     /* Pointer to the start of cell content */
37240  i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
37241  u32 nData;     /* Number of bytes of data */
37242  u32 nPayload;  /* Total amount of payload */
37243  u16 nHeader;   /* Size of the cell content header in bytes */
37244  u16 nLocal;    /* Amount of payload held locally */
37245  u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
37246  u16 nSize;     /* Size of the cell content on the main b-tree page */
37247};
37248
37249/*
37250** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
37251** this will be declared corrupt. This value is calculated based on a
37252** maximum database size of 2^31 pages a minimum fanout of 2 for a
37253** root-node and 3 for all other internal nodes.
37254**
37255** If a tree that appears to be taller than this is encountered, it is
37256** assumed that the database is corrupt.
37257*/
37258#define BTCURSOR_MAX_DEPTH 20
37259
37260/*
37261** A cursor is a pointer to a particular entry within a particular
37262** b-tree within a database file.
37263**
37264** The entry is identified by its MemPage and the index in
37265** MemPage.aCell[] of the entry.
37266**
37267** A single database file can shared by two more database connections,
37268** but cursors cannot be shared.  Each cursor is associated with a
37269** particular database connection identified BtCursor.pBtree.db.
37270**
37271** Fields in this structure are accessed under the BtShared.mutex
37272** found at self->pBt->mutex.
37273*/
37274struct BtCursor {
37275  Btree *pBtree;            /* The Btree to which this cursor belongs */
37276  BtShared *pBt;            /* The BtShared this cursor points to */
37277  BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
37278  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
37279  Pgno pgnoRoot;            /* The root page of this tree */
37280  sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
37281  CellInfo info;            /* A parse of the cell we are pointing at */
37282  u8 wrFlag;                /* True if writable */
37283  u8 atLast;                /* Cursor pointing to the last entry */
37284  u8 validNKey;             /* True if info.nKey is valid */
37285  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
37286  void *pKey;      /* Saved key that was cursor's last known position */
37287  i64 nKey;        /* Size of pKey, or last integer key */
37288  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
37289#ifndef SQLITE_OMIT_INCRBLOB
37290  u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
37291  Pgno *aOverflow;          /* Cache of overflow page locations */
37292#endif
37293  i16 iPage;                            /* Index of current page in apPage */
37294  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
37295  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
37296};
37297
37298/*
37299** Potential values for BtCursor.eState.
37300**
37301** CURSOR_VALID:
37302**   Cursor points to a valid entry. getPayload() etc. may be called.
37303**
37304** CURSOR_INVALID:
37305**   Cursor does not point to a valid entry. This can happen (for example)
37306**   because the table is empty or because BtreeCursorFirst() has not been
37307**   called.
37308**
37309** CURSOR_REQUIRESEEK:
37310**   The table that this cursor was opened on still exists, but has been
37311**   modified since the cursor was last used. The cursor position is saved
37312**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
37313**   this state, restoreCursorPosition() can be called to attempt to
37314**   seek the cursor to the saved position.
37315**
37316** CURSOR_FAULT:
37317**   A unrecoverable error (an I/O error or a malloc failure) has occurred
37318**   on a different connection that shares the BtShared cache with this
37319**   cursor.  The error has left the cache in an inconsistent state.
37320**   Do nothing else with this cursor.  Any attempt to use the cursor
37321**   should return the error code stored in BtCursor.skip
37322*/
37323#define CURSOR_INVALID           0
37324#define CURSOR_VALID             1
37325#define CURSOR_REQUIRESEEK       2
37326#define CURSOR_FAULT             3
37327
37328/*
37329** The database page the PENDING_BYTE occupies. This page is never used.
37330*/
37331# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
37332
37333/*
37334** These macros define the location of the pointer-map entry for a
37335** database page. The first argument to each is the number of usable
37336** bytes on each page of the database (often 1024). The second is the
37337** page number to look up in the pointer map.
37338**
37339** PTRMAP_PAGENO returns the database page number of the pointer-map
37340** page that stores the required pointer. PTRMAP_PTROFFSET returns
37341** the offset of the requested map entry.
37342**
37343** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
37344** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
37345** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
37346** this test.
37347*/
37348#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
37349#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
37350#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
37351
37352/*
37353** The pointer map is a lookup table that identifies the parent page for
37354** each child page in the database file.  The parent page is the page that
37355** contains a pointer to the child.  Every page in the database contains
37356** 0 or 1 parent pages.  (In this context 'database page' refers
37357** to any page that is not part of the pointer map itself.)  Each pointer map
37358** entry consists of a single byte 'type' and a 4 byte parent page number.
37359** The PTRMAP_XXX identifiers below are the valid types.
37360**
37361** The purpose of the pointer map is to facility moving pages from one
37362** position in the file to another as part of autovacuum.  When a page
37363** is moved, the pointer in its parent must be updated to point to the
37364** new location.  The pointer map is used to locate the parent page quickly.
37365**
37366** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
37367**                  used in this case.
37368**
37369** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
37370**                  is not used in this case.
37371**
37372** PTRMAP_OVERFLOW1: The database page is the first page in a list of
37373**                   overflow pages. The page number identifies the page that
37374**                   contains the cell with a pointer to this overflow page.
37375**
37376** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
37377**                   overflow pages. The page-number identifies the previous
37378**                   page in the overflow page list.
37379**
37380** PTRMAP_BTREE: The database page is a non-root btree page. The page number
37381**               identifies the parent page in the btree.
37382*/
37383#define PTRMAP_ROOTPAGE 1
37384#define PTRMAP_FREEPAGE 2
37385#define PTRMAP_OVERFLOW1 3
37386#define PTRMAP_OVERFLOW2 4
37387#define PTRMAP_BTREE 5
37388
37389/* A bunch of assert() statements to check the transaction state variables
37390** of handle p (type Btree*) are internally consistent.
37391*/
37392#define btreeIntegrity(p) \
37393  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
37394  assert( p->pBt->inTransaction>=p->inTrans );
37395
37396
37397/*
37398** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
37399** if the database supports auto-vacuum or not. Because it is used
37400** within an expression that is an argument to another macro
37401** (sqliteMallocRaw), it is not possible to use conditional compilation.
37402** So, this macro is defined instead.
37403*/
37404#ifndef SQLITE_OMIT_AUTOVACUUM
37405#define ISAUTOVACUUM (pBt->autoVacuum)
37406#else
37407#define ISAUTOVACUUM 0
37408#endif
37409
37410
37411/*
37412** This structure is passed around through all the sanity checking routines
37413** in order to keep track of some global state information.
37414*/
37415typedef struct IntegrityCk IntegrityCk;
37416struct IntegrityCk {
37417  BtShared *pBt;    /* The tree being checked out */
37418  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
37419  Pgno nPage;       /* Number of pages in the database */
37420  int *anRef;       /* Number of times each page is referenced */
37421  int mxErr;        /* Stop accumulating errors when this reaches zero */
37422  int nErr;         /* Number of messages written to zErrMsg so far */
37423  int mallocFailed; /* A memory allocation error has occurred */
37424  StrAccum errMsg;  /* Accumulate the error message text here */
37425};
37426
37427/*
37428** Read or write a two- and four-byte big-endian integer values.
37429*/
37430#define get2byte(x)   ((x)[0]<<8 | (x)[1])
37431#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
37432#define get4byte sqlite3Get4byte
37433#define put4byte sqlite3Put4byte
37434
37435/************** End of btreeInt.h ********************************************/
37436/************** Continuing where we left off in btmutex.c ********************/
37437#ifndef SQLITE_OMIT_SHARED_CACHE
37438#if SQLITE_THREADSAFE
37439
37440/*
37441** Obtain the BtShared mutex associated with B-Tree handle p. Also,
37442** set BtShared.db to the database handle associated with p and the
37443** p->locked boolean to true.
37444*/
37445static void lockBtreeMutex(Btree *p){
37446  assert( p->locked==0 );
37447  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
37448  assert( sqlite3_mutex_held(p->db->mutex) );
37449
37450  sqlite3_mutex_enter(p->pBt->mutex);
37451  p->pBt->db = p->db;
37452  p->locked = 1;
37453}
37454
37455/*
37456** Release the BtShared mutex associated with B-Tree handle p and
37457** clear the p->locked boolean.
37458*/
37459static void unlockBtreeMutex(Btree *p){
37460  assert( p->locked==1 );
37461  assert( sqlite3_mutex_held(p->pBt->mutex) );
37462  assert( sqlite3_mutex_held(p->db->mutex) );
37463  assert( p->db==p->pBt->db );
37464
37465  sqlite3_mutex_leave(p->pBt->mutex);
37466  p->locked = 0;
37467}
37468
37469/*
37470** Enter a mutex on the given BTree object.
37471**
37472** If the object is not sharable, then no mutex is ever required
37473** and this routine is a no-op.  The underlying mutex is non-recursive.
37474** But we keep a reference count in Btree.wantToLock so the behavior
37475** of this interface is recursive.
37476**
37477** To avoid deadlocks, multiple Btrees are locked in the same order
37478** by all database connections.  The p->pNext is a list of other
37479** Btrees belonging to the same database connection as the p Btree
37480** which need to be locked after p.  If we cannot get a lock on
37481** p, then first unlock all of the others on p->pNext, then wait
37482** for the lock to become available on p, then relock all of the
37483** subsequent Btrees that desire a lock.
37484*/
37485SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
37486  Btree *pLater;
37487
37488  /* Some basic sanity checking on the Btree.  The list of Btrees
37489  ** connected by pNext and pPrev should be in sorted order by
37490  ** Btree.pBt value. All elements of the list should belong to
37491  ** the same connection. Only shared Btrees are on the list. */
37492  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
37493  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
37494  assert( p->pNext==0 || p->pNext->db==p->db );
37495  assert( p->pPrev==0 || p->pPrev->db==p->db );
37496  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
37497
37498  /* Check for locking consistency */
37499  assert( !p->locked || p->wantToLock>0 );
37500  assert( p->sharable || p->wantToLock==0 );
37501
37502  /* We should already hold a lock on the database connection */
37503  assert( sqlite3_mutex_held(p->db->mutex) );
37504
37505  /* Unless the database is sharable and unlocked, then BtShared.db
37506  ** should already be set correctly. */
37507  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
37508
37509  if( !p->sharable ) return;
37510  p->wantToLock++;
37511  if( p->locked ) return;
37512
37513  /* In most cases, we should be able to acquire the lock we
37514  ** want without having to go throught the ascending lock
37515  ** procedure that follows.  Just be sure not to block.
37516  */
37517  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
37518    p->pBt->db = p->db;
37519    p->locked = 1;
37520    return;
37521  }
37522
37523  /* To avoid deadlock, first release all locks with a larger
37524  ** BtShared address.  Then acquire our lock.  Then reacquire
37525  ** the other BtShared locks that we used to hold in ascending
37526  ** order.
37527  */
37528  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
37529    assert( pLater->sharable );
37530    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
37531    assert( !pLater->locked || pLater->wantToLock>0 );
37532    if( pLater->locked ){
37533      unlockBtreeMutex(pLater);
37534    }
37535  }
37536  lockBtreeMutex(p);
37537  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
37538    if( pLater->wantToLock ){
37539      lockBtreeMutex(pLater);
37540    }
37541  }
37542}
37543
37544/*
37545** Exit the recursive mutex on a Btree.
37546*/
37547SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
37548  if( p->sharable ){
37549    assert( p->wantToLock>0 );
37550    p->wantToLock--;
37551    if( p->wantToLock==0 ){
37552      unlockBtreeMutex(p);
37553    }
37554  }
37555}
37556
37557#ifndef NDEBUG
37558/*
37559** Return true if the BtShared mutex is held on the btree, or if the
37560** B-Tree is not marked as sharable.
37561**
37562** This routine is used only from within assert() statements.
37563*/
37564SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
37565  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
37566  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
37567  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
37568  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
37569
37570  return (p->sharable==0 || p->locked);
37571}
37572#endif
37573
37574
37575#ifndef SQLITE_OMIT_INCRBLOB
37576/*
37577** Enter and leave a mutex on a Btree given a cursor owned by that
37578** Btree.  These entry points are used by incremental I/O and can be
37579** omitted if that module is not used.
37580*/
37581SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
37582  sqlite3BtreeEnter(pCur->pBtree);
37583}
37584SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
37585  sqlite3BtreeLeave(pCur->pBtree);
37586}
37587#endif /* SQLITE_OMIT_INCRBLOB */
37588
37589
37590/*
37591** Enter the mutex on every Btree associated with a database
37592** connection.  This is needed (for example) prior to parsing
37593** a statement since we will be comparing table and column names
37594** against all schemas and we do not want those schemas being
37595** reset out from under us.
37596**
37597** There is a corresponding leave-all procedures.
37598**
37599** Enter the mutexes in accending order by BtShared pointer address
37600** to avoid the possibility of deadlock when two threads with
37601** two or more btrees in common both try to lock all their btrees
37602** at the same instant.
37603*/
37604SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
37605  int i;
37606  Btree *p, *pLater;
37607  assert( sqlite3_mutex_held(db->mutex) );
37608  for(i=0; i<db->nDb; i++){
37609    p = db->aDb[i].pBt;
37610    assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
37611    if( p && p->sharable ){
37612      p->wantToLock++;
37613      if( !p->locked ){
37614        assert( p->wantToLock==1 );
37615        while( p->pPrev ) p = p->pPrev;
37616        /* Reason for ALWAYS:  There must be at least on unlocked Btree in
37617        ** the chain.  Otherwise the !p->locked test above would have failed */
37618        while( p->locked && ALWAYS(p->pNext) ) p = p->pNext;
37619        for(pLater = p->pNext; pLater; pLater=pLater->pNext){
37620          if( pLater->locked ){
37621            unlockBtreeMutex(pLater);
37622          }
37623        }
37624        while( p ){
37625          lockBtreeMutex(p);
37626          p = p->pNext;
37627        }
37628      }
37629    }
37630  }
37631}
37632SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
37633  int i;
37634  Btree *p;
37635  assert( sqlite3_mutex_held(db->mutex) );
37636  for(i=0; i<db->nDb; i++){
37637    p = db->aDb[i].pBt;
37638    if( p && p->sharable ){
37639      assert( p->wantToLock>0 );
37640      p->wantToLock--;
37641      if( p->wantToLock==0 ){
37642        unlockBtreeMutex(p);
37643      }
37644    }
37645  }
37646}
37647
37648#ifndef NDEBUG
37649/*
37650** Return true if the current thread holds the database connection
37651** mutex and all required BtShared mutexes.
37652**
37653** This routine is used inside assert() statements only.
37654*/
37655SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
37656  int i;
37657  if( !sqlite3_mutex_held(db->mutex) ){
37658    return 0;
37659  }
37660  for(i=0; i<db->nDb; i++){
37661    Btree *p;
37662    p = db->aDb[i].pBt;
37663    if( p && p->sharable &&
37664         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
37665      return 0;
37666    }
37667  }
37668  return 1;
37669}
37670#endif /* NDEBUG */
37671
37672/*
37673** Add a new Btree pointer to a BtreeMutexArray.
37674** if the pointer can possibly be shared with
37675** another database connection.
37676**
37677** The pointers are kept in sorted order by pBtree->pBt.  That
37678** way when we go to enter all the mutexes, we can enter them
37679** in order without every having to backup and retry and without
37680** worrying about deadlock.
37681**
37682** The number of shared btrees will always be small (usually 0 or 1)
37683** so an insertion sort is an adequate algorithm here.
37684*/
37685SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
37686  int i, j;
37687  BtShared *pBt;
37688  if( pBtree==0 || pBtree->sharable==0 ) return;
37689#ifndef NDEBUG
37690  {
37691    for(i=0; i<pArray->nMutex; i++){
37692      assert( pArray->aBtree[i]!=pBtree );
37693    }
37694  }
37695#endif
37696  assert( pArray->nMutex>=0 );
37697  assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
37698  pBt = pBtree->pBt;
37699  for(i=0; i<pArray->nMutex; i++){
37700    assert( pArray->aBtree[i]!=pBtree );
37701    if( pArray->aBtree[i]->pBt>pBt ){
37702      for(j=pArray->nMutex; j>i; j--){
37703        pArray->aBtree[j] = pArray->aBtree[j-1];
37704      }
37705      pArray->aBtree[i] = pBtree;
37706      pArray->nMutex++;
37707      return;
37708    }
37709  }
37710  pArray->aBtree[pArray->nMutex++] = pBtree;
37711}
37712
37713/*
37714** Enter the mutex of every btree in the array.  This routine is
37715** called at the beginning of sqlite3VdbeExec().  The mutexes are
37716** exited at the end of the same function.
37717*/
37718SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
37719  int i;
37720  for(i=0; i<pArray->nMutex; i++){
37721    Btree *p = pArray->aBtree[i];
37722    /* Some basic sanity checking */
37723    assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
37724    assert( !p->locked || p->wantToLock>0 );
37725
37726    /* We should already hold a lock on the database connection */
37727    assert( sqlite3_mutex_held(p->db->mutex) );
37728
37729    /* The Btree is sharable because only sharable Btrees are entered
37730    ** into the array in the first place. */
37731    assert( p->sharable );
37732
37733    p->wantToLock++;
37734    if( !p->locked ){
37735      lockBtreeMutex(p);
37736    }
37737  }
37738}
37739
37740/*
37741** Leave the mutex of every btree in the group.
37742*/
37743SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
37744  int i;
37745  for(i=0; i<pArray->nMutex; i++){
37746    Btree *p = pArray->aBtree[i];
37747    /* Some basic sanity checking */
37748    assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
37749    assert( p->locked );
37750    assert( p->wantToLock>0 );
37751
37752    /* We should already hold a lock on the database connection */
37753    assert( sqlite3_mutex_held(p->db->mutex) );
37754
37755    p->wantToLock--;
37756    if( p->wantToLock==0 ){
37757      unlockBtreeMutex(p);
37758    }
37759  }
37760}
37761
37762#else
37763SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
37764  p->pBt->db = p->db;
37765}
37766SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
37767  int i;
37768  for(i=0; i<db->nDb; i++){
37769    Btree *p = db->aDb[i].pBt;
37770    if( p ){
37771      p->pBt->db = p->db;
37772    }
37773  }
37774}
37775#endif /* if SQLITE_THREADSAFE */
37776#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
37777
37778/************** End of btmutex.c *********************************************/
37779/************** Begin file btree.c *******************************************/
37780/*
37781** 2004 April 6
37782**
37783** The author disclaims copyright to this source code.  In place of
37784** a legal notice, here is a blessing:
37785**
37786**    May you do good and not evil.
37787**    May you find forgiveness for yourself and forgive others.
37788**    May you share freely, never taking more than you give.
37789**
37790*************************************************************************
37791** This file implements a external (disk-based) database using BTrees.
37792** See the header comment on "btreeInt.h" for additional information.
37793** Including a description of file format and an overview of operation.
37794*/
37795
37796/*
37797** The header string that appears at the beginning of every
37798** SQLite database.
37799*/
37800static const char zMagicHeader[] = SQLITE_FILE_HEADER;
37801
37802/*
37803** Set this global variable to 1 to enable tracing using the TRACE
37804** macro.
37805*/
37806#if 0
37807int sqlite3BtreeTrace=1;  /* True to enable tracing */
37808# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
37809#else
37810# define TRACE(X)
37811#endif
37812
37813
37814
37815#ifndef SQLITE_OMIT_SHARED_CACHE
37816/*
37817** A list of BtShared objects that are eligible for participation
37818** in shared cache.  This variable has file scope during normal builds,
37819** but the test harness needs to access it so we make it global for
37820** test builds.
37821**
37822** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
37823*/
37824#ifdef SQLITE_TEST
37825SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
37826#else
37827static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
37828#endif
37829#endif /* SQLITE_OMIT_SHARED_CACHE */
37830
37831#ifndef SQLITE_OMIT_SHARED_CACHE
37832/*
37833** Enable or disable the shared pager and schema features.
37834**
37835** This routine has no effect on existing database connections.
37836** The shared cache setting effects only future calls to
37837** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
37838*/
37839SQLITE_API int sqlite3_enable_shared_cache(int enable){
37840  sqlite3GlobalConfig.sharedCacheEnabled = enable;
37841  return SQLITE_OK;
37842}
37843#endif
37844
37845
37846
37847#ifdef SQLITE_OMIT_SHARED_CACHE
37848  /*
37849  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
37850  ** and clearAllSharedCacheTableLocks()
37851  ** manipulate entries in the BtShared.pLock linked list used to store
37852  ** shared-cache table level locks. If the library is compiled with the
37853  ** shared-cache feature disabled, then there is only ever one user
37854  ** of each BtShared structure and so this locking is not necessary.
37855  ** So define the lock related functions as no-ops.
37856  */
37857  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
37858  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
37859  #define clearAllSharedCacheTableLocks(a)
37860  #define downgradeAllSharedCacheTableLocks(a)
37861  #define hasSharedCacheTableLock(a,b,c,d) 1
37862  #define hasReadConflicts(a, b) 0
37863#endif
37864
37865#ifndef SQLITE_OMIT_SHARED_CACHE
37866
37867#ifdef SQLITE_DEBUG
37868/*
37869**** This function is only used as part of an assert() statement. ***
37870**
37871** Check to see if pBtree holds the required locks to read or write to the
37872** table with root page iRoot.   Return 1 if it does and 0 if not.
37873**
37874** For example, when writing to a table with root-page iRoot via
37875** Btree connection pBtree:
37876**
37877**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
37878**
37879** When writing to an index that resides in a sharable database, the
37880** caller should have first obtained a lock specifying the root page of
37881** the corresponding table. This makes things a bit more complicated,
37882** as this module treats each table as a separate structure. To determine
37883** the table corresponding to the index being written, this
37884** function has to search through the database schema.
37885**
37886** Instead of a lock on the table/index rooted at page iRoot, the caller may
37887** hold a write-lock on the schema table (root page 1). This is also
37888** acceptable.
37889*/
37890static int hasSharedCacheTableLock(
37891  Btree *pBtree,         /* Handle that must hold lock */
37892  Pgno iRoot,            /* Root page of b-tree */
37893  int isIndex,           /* True if iRoot is the root of an index b-tree */
37894  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
37895){
37896  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
37897  Pgno iTab = 0;
37898  BtLock *pLock;
37899
37900  /* If this database is not shareable, or if the client is reading
37901  ** and has the read-uncommitted flag set, then no lock is required.
37902  ** Return true immediately.
37903  */
37904  if( (pBtree->sharable==0)
37905   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
37906  ){
37907    return 1;
37908  }
37909
37910  /* If the client is reading  or writing an index and the schema is
37911  ** not loaded, then it is too difficult to actually check to see if
37912  ** the correct locks are held.  So do not bother - just return true.
37913  ** This case does not come up very often anyhow.
37914  */
37915  if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
37916    return 1;
37917  }
37918
37919  /* Figure out the root-page that the lock should be held on. For table
37920  ** b-trees, this is just the root page of the b-tree being read or
37921  ** written. For index b-trees, it is the root page of the associated
37922  ** table.  */
37923  if( isIndex ){
37924    HashElem *p;
37925    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
37926      Index *pIdx = (Index *)sqliteHashData(p);
37927      if( pIdx->tnum==(int)iRoot ){
37928        iTab = pIdx->pTable->tnum;
37929      }
37930    }
37931  }else{
37932    iTab = iRoot;
37933  }
37934
37935  /* Search for the required lock. Either a write-lock on root-page iTab, a
37936  ** write-lock on the schema table, or (if the client is reading) a
37937  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
37938  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
37939    if( pLock->pBtree==pBtree
37940     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
37941     && pLock->eLock>=eLockType
37942    ){
37943      return 1;
37944    }
37945  }
37946
37947  /* Failed to find the required lock. */
37948  return 0;
37949}
37950#endif /* SQLITE_DEBUG */
37951
37952#ifdef SQLITE_DEBUG
37953/*
37954**** This function may be used as part of assert() statements only. ****
37955**
37956** Return true if it would be illegal for pBtree to write into the
37957** table or index rooted at iRoot because other shared connections are
37958** simultaneously reading that same table or index.
37959**
37960** It is illegal for pBtree to write if some other Btree object that
37961** shares the same BtShared object is currently reading or writing
37962** the iRoot table.  Except, if the other Btree object has the
37963** read-uncommitted flag set, then it is OK for the other object to
37964** have a read cursor.
37965**
37966** For example, before writing to any part of the table or index
37967** rooted at page iRoot, one should call:
37968**
37969**    assert( !hasReadConflicts(pBtree, iRoot) );
37970*/
37971static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
37972  BtCursor *p;
37973  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
37974    if( p->pgnoRoot==iRoot
37975     && p->pBtree!=pBtree
37976     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
37977    ){
37978      return 1;
37979    }
37980  }
37981  return 0;
37982}
37983#endif    /* #ifdef SQLITE_DEBUG */
37984
37985/*
37986** Query to see if Btree handle p may obtain a lock of type eLock
37987** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
37988** SQLITE_OK if the lock may be obtained (by calling
37989** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
37990*/
37991static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
37992  BtShared *pBt = p->pBt;
37993  BtLock *pIter;
37994
37995  assert( sqlite3BtreeHoldsMutex(p) );
37996  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
37997  assert( p->db!=0 );
37998  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
37999
38000  /* If requesting a write-lock, then the Btree must have an open write
38001  ** transaction on this file. And, obviously, for this to be so there
38002  ** must be an open write transaction on the file itself.
38003  */
38004  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
38005  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
38006
38007  /* This routine is a no-op if the shared-cache is not enabled */
38008  if( !p->sharable ){
38009    return SQLITE_OK;
38010  }
38011
38012  /* If some other connection is holding an exclusive lock, the
38013  ** requested lock may not be obtained.
38014  */
38015  if( pBt->pWriter!=p && pBt->isExclusive ){
38016    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
38017    return SQLITE_LOCKED_SHAREDCACHE;
38018  }
38019
38020  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
38021    /* The condition (pIter->eLock!=eLock) in the following if(...)
38022    ** statement is a simplification of:
38023    **
38024    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
38025    **
38026    ** since we know that if eLock==WRITE_LOCK, then no other connection
38027    ** may hold a WRITE_LOCK on any table in this file (since there can
38028    ** only be a single writer).
38029    */
38030    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
38031    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
38032    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
38033      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
38034      if( eLock==WRITE_LOCK ){
38035        assert( p==pBt->pWriter );
38036        pBt->isPending = 1;
38037      }
38038      return SQLITE_LOCKED_SHAREDCACHE;
38039    }
38040  }
38041  return SQLITE_OK;
38042}
38043#endif /* !SQLITE_OMIT_SHARED_CACHE */
38044
38045#ifndef SQLITE_OMIT_SHARED_CACHE
38046/*
38047** Add a lock on the table with root-page iTable to the shared-btree used
38048** by Btree handle p. Parameter eLock must be either READ_LOCK or
38049** WRITE_LOCK.
38050**
38051** This function assumes the following:
38052**
38053**   (a) The specified Btree object p is connected to a sharable
38054**       database (one with the BtShared.sharable flag set), and
38055**
38056**   (b) No other Btree objects hold a lock that conflicts
38057**       with the requested lock (i.e. querySharedCacheTableLock() has
38058**       already been called and returned SQLITE_OK).
38059**
38060** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
38061** is returned if a malloc attempt fails.
38062*/
38063static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
38064  BtShared *pBt = p->pBt;
38065  BtLock *pLock = 0;
38066  BtLock *pIter;
38067
38068  assert( sqlite3BtreeHoldsMutex(p) );
38069  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
38070  assert( p->db!=0 );
38071
38072  /* A connection with the read-uncommitted flag set will never try to
38073  ** obtain a read-lock using this function. The only read-lock obtained
38074  ** by a connection in read-uncommitted mode is on the sqlite_master
38075  ** table, and that lock is obtained in BtreeBeginTrans().  */
38076  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
38077
38078  /* This function should only be called on a sharable b-tree after it
38079  ** has been determined that no other b-tree holds a conflicting lock.  */
38080  assert( p->sharable );
38081  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
38082
38083  /* First search the list for an existing lock on this table. */
38084  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
38085    if( pIter->iTable==iTable && pIter->pBtree==p ){
38086      pLock = pIter;
38087      break;
38088    }
38089  }
38090
38091  /* If the above search did not find a BtLock struct associating Btree p
38092  ** with table iTable, allocate one and link it into the list.
38093  */
38094  if( !pLock ){
38095    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
38096    if( !pLock ){
38097      return SQLITE_NOMEM;
38098    }
38099    pLock->iTable = iTable;
38100    pLock->pBtree = p;
38101    pLock->pNext = pBt->pLock;
38102    pBt->pLock = pLock;
38103  }
38104
38105  /* Set the BtLock.eLock variable to the maximum of the current lock
38106  ** and the requested lock. This means if a write-lock was already held
38107  ** and a read-lock requested, we don't incorrectly downgrade the lock.
38108  */
38109  assert( WRITE_LOCK>READ_LOCK );
38110  if( eLock>pLock->eLock ){
38111    pLock->eLock = eLock;
38112  }
38113
38114  return SQLITE_OK;
38115}
38116#endif /* !SQLITE_OMIT_SHARED_CACHE */
38117
38118#ifndef SQLITE_OMIT_SHARED_CACHE
38119/*
38120** Release all the table locks (locks obtained via calls to
38121** the setSharedCacheTableLock() procedure) held by Btree object p.
38122**
38123** This function assumes that Btree p has an open read or write
38124** transaction. If it does not, then the BtShared.isPending variable
38125** may be incorrectly cleared.
38126*/
38127static void clearAllSharedCacheTableLocks(Btree *p){
38128  BtShared *pBt = p->pBt;
38129  BtLock **ppIter = &pBt->pLock;
38130
38131  assert( sqlite3BtreeHoldsMutex(p) );
38132  assert( p->sharable || 0==*ppIter );
38133  assert( p->inTrans>0 );
38134
38135  while( *ppIter ){
38136    BtLock *pLock = *ppIter;
38137    assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
38138    assert( pLock->pBtree->inTrans>=pLock->eLock );
38139    if( pLock->pBtree==p ){
38140      *ppIter = pLock->pNext;
38141      assert( pLock->iTable!=1 || pLock==&p->lock );
38142      if( pLock->iTable!=1 ){
38143        sqlite3_free(pLock);
38144      }
38145    }else{
38146      ppIter = &pLock->pNext;
38147    }
38148  }
38149
38150  assert( pBt->isPending==0 || pBt->pWriter );
38151  if( pBt->pWriter==p ){
38152    pBt->pWriter = 0;
38153    pBt->isExclusive = 0;
38154    pBt->isPending = 0;
38155  }else if( pBt->nTransaction==2 ){
38156    /* This function is called when Btree p is concluding its
38157    ** transaction. If there currently exists a writer, and p is not
38158    ** that writer, then the number of locks held by connections other
38159    ** than the writer must be about to drop to zero. In this case
38160    ** set the isPending flag to 0.
38161    **
38162    ** If there is not currently a writer, then BtShared.isPending must
38163    ** be zero already. So this next line is harmless in that case.
38164    */
38165    pBt->isPending = 0;
38166  }
38167}
38168
38169/*
38170** This function changes all write-locks held by Btree p into read-locks.
38171*/
38172static void downgradeAllSharedCacheTableLocks(Btree *p){
38173  BtShared *pBt = p->pBt;
38174  if( pBt->pWriter==p ){
38175    BtLock *pLock;
38176    pBt->pWriter = 0;
38177    pBt->isExclusive = 0;
38178    pBt->isPending = 0;
38179    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
38180      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
38181      pLock->eLock = READ_LOCK;
38182    }
38183  }
38184}
38185
38186#endif /* SQLITE_OMIT_SHARED_CACHE */
38187
38188static void releasePage(MemPage *pPage);  /* Forward reference */
38189
38190/*
38191***** This routine is used inside of assert() only ****
38192**
38193** Verify that the cursor holds the mutex on its BtShared
38194*/
38195#ifdef SQLITE_DEBUG
38196static int cursorHoldsMutex(BtCursor *p){
38197  return sqlite3_mutex_held(p->pBt->mutex);
38198}
38199#endif
38200
38201
38202#ifndef SQLITE_OMIT_INCRBLOB
38203/*
38204** Invalidate the overflow page-list cache for cursor pCur, if any.
38205*/
38206static void invalidateOverflowCache(BtCursor *pCur){
38207  assert( cursorHoldsMutex(pCur) );
38208  sqlite3_free(pCur->aOverflow);
38209  pCur->aOverflow = 0;
38210}
38211
38212/*
38213** Invalidate the overflow page-list cache for all cursors opened
38214** on the shared btree structure pBt.
38215*/
38216static void invalidateAllOverflowCache(BtShared *pBt){
38217  BtCursor *p;
38218  assert( sqlite3_mutex_held(pBt->mutex) );
38219  for(p=pBt->pCursor; p; p=p->pNext){
38220    invalidateOverflowCache(p);
38221  }
38222}
38223
38224/*
38225** This function is called before modifying the contents of a table
38226** to invalidate any incrblob cursors that are open on the
38227** row or one of the rows being modified.
38228**
38229** If argument isClearTable is true, then the entire contents of the
38230** table is about to be deleted. In this case invalidate all incrblob
38231** cursors open on any row within the table with root-page pgnoRoot.
38232**
38233** Otherwise, if argument isClearTable is false, then the row with
38234** rowid iRow is being replaced or deleted. In this case invalidate
38235** only those incrblob cursors open on that specific row.
38236*/
38237static void invalidateIncrblobCursors(
38238  Btree *pBtree,          /* The database file to check */
38239  i64 iRow,               /* The rowid that might be changing */
38240  int isClearTable        /* True if all rows are being deleted */
38241){
38242  BtCursor *p;
38243  BtShared *pBt = pBtree->pBt;
38244  assert( sqlite3BtreeHoldsMutex(pBtree) );
38245  for(p=pBt->pCursor; p; p=p->pNext){
38246    if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
38247      p->eState = CURSOR_INVALID;
38248    }
38249  }
38250}
38251
38252#else
38253  /* Stub functions when INCRBLOB is omitted */
38254  #define invalidateOverflowCache(x)
38255  #define invalidateAllOverflowCache(x)
38256  #define invalidateIncrblobCursors(x,y,z)
38257#endif /* SQLITE_OMIT_INCRBLOB */
38258
38259/*
38260** Set bit pgno of the BtShared.pHasContent bitvec. This is called
38261** when a page that previously contained data becomes a free-list leaf
38262** page.
38263**
38264** The BtShared.pHasContent bitvec exists to work around an obscure
38265** bug caused by the interaction of two useful IO optimizations surrounding
38266** free-list leaf pages:
38267**
38268**   1) When all data is deleted from a page and the page becomes
38269**      a free-list leaf page, the page is not written to the database
38270**      (as free-list leaf pages contain no meaningful data). Sometimes
38271**      such a page is not even journalled (as it will not be modified,
38272**      why bother journalling it?).
38273**
38274**   2) When a free-list leaf page is reused, its content is not read
38275**      from the database or written to the journal file (why should it
38276**      be, if it is not at all meaningful?).
38277**
38278** By themselves, these optimizations work fine and provide a handy
38279** performance boost to bulk delete or insert operations. However, if
38280** a page is moved to the free-list and then reused within the same
38281** transaction, a problem comes up. If the page is not journalled when
38282** it is moved to the free-list and it is also not journalled when it
38283** is extracted from the free-list and reused, then the original data
38284** may be lost. In the event of a rollback, it may not be possible
38285** to restore the database to its original configuration.
38286**
38287** The solution is the BtShared.pHasContent bitvec. Whenever a page is
38288** moved to become a free-list leaf page, the corresponding bit is
38289** set in the bitvec. Whenever a leaf page is extracted from the free-list,
38290** optimization 2 above is omitted if the corresponding bit is already
38291** set in BtShared.pHasContent. The contents of the bitvec are cleared
38292** at the end of every transaction.
38293*/
38294static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
38295  int rc = SQLITE_OK;
38296  if( !pBt->pHasContent ){
38297    int nPage = 100;
38298    sqlite3PagerPagecount(pBt->pPager, &nPage);
38299    /* If sqlite3PagerPagecount() fails there is no harm because the
38300    ** nPage variable is unchanged from its default value of 100 */
38301    pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
38302    if( !pBt->pHasContent ){
38303      rc = SQLITE_NOMEM;
38304    }
38305  }
38306  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
38307    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
38308  }
38309  return rc;
38310}
38311
38312/*
38313** Query the BtShared.pHasContent vector.
38314**
38315** This function is called when a free-list leaf page is removed from the
38316** free-list for reuse. It returns false if it is safe to retrieve the
38317** page from the pager layer with the 'no-content' flag set. True otherwise.
38318*/
38319static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
38320  Bitvec *p = pBt->pHasContent;
38321  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
38322}
38323
38324/*
38325** Clear (destroy) the BtShared.pHasContent bitvec. This should be
38326** invoked at the conclusion of each write-transaction.
38327*/
38328static void btreeClearHasContent(BtShared *pBt){
38329  sqlite3BitvecDestroy(pBt->pHasContent);
38330  pBt->pHasContent = 0;
38331}
38332
38333/*
38334** Save the current cursor position in the variables BtCursor.nKey
38335** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
38336**
38337** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
38338** prior to calling this routine.
38339*/
38340static int saveCursorPosition(BtCursor *pCur){
38341  int rc;
38342
38343  assert( CURSOR_VALID==pCur->eState );
38344  assert( 0==pCur->pKey );
38345  assert( cursorHoldsMutex(pCur) );
38346
38347  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
38348  assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
38349
38350  /* If this is an intKey table, then the above call to BtreeKeySize()
38351  ** stores the integer key in pCur->nKey. In this case this value is
38352  ** all that is required. Otherwise, if pCur is not open on an intKey
38353  ** table, then malloc space for and store the pCur->nKey bytes of key
38354  ** data.
38355  */
38356  if( 0==pCur->apPage[0]->intKey ){
38357    void *pKey = sqlite3Malloc( (int)pCur->nKey );
38358    if( pKey ){
38359      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
38360      if( rc==SQLITE_OK ){
38361        pCur->pKey = pKey;
38362      }else{
38363        sqlite3_free(pKey);
38364      }
38365    }else{
38366      rc = SQLITE_NOMEM;
38367    }
38368  }
38369  assert( !pCur->apPage[0]->intKey || !pCur->pKey );
38370
38371  if( rc==SQLITE_OK ){
38372    int i;
38373    for(i=0; i<=pCur->iPage; i++){
38374      releasePage(pCur->apPage[i]);
38375      pCur->apPage[i] = 0;
38376    }
38377    pCur->iPage = -1;
38378    pCur->eState = CURSOR_REQUIRESEEK;
38379  }
38380
38381  invalidateOverflowCache(pCur);
38382  return rc;
38383}
38384
38385/*
38386** Save the positions of all cursors (except pExcept) that are open on
38387** the table  with root-page iRoot. Usually, this is called just before cursor
38388** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
38389*/
38390static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
38391  BtCursor *p;
38392  assert( sqlite3_mutex_held(pBt->mutex) );
38393  assert( pExcept==0 || pExcept->pBt==pBt );
38394  for(p=pBt->pCursor; p; p=p->pNext){
38395    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
38396        p->eState==CURSOR_VALID ){
38397      int rc = saveCursorPosition(p);
38398      if( SQLITE_OK!=rc ){
38399        return rc;
38400      }
38401    }
38402  }
38403  return SQLITE_OK;
38404}
38405
38406/*
38407** Clear the current cursor position.
38408*/
38409SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
38410  assert( cursorHoldsMutex(pCur) );
38411  sqlite3_free(pCur->pKey);
38412  pCur->pKey = 0;
38413  pCur->eState = CURSOR_INVALID;
38414}
38415
38416/*
38417** In this version of BtreeMoveto, pKey is a packed index record
38418** such as is generated by the OP_MakeRecord opcode.  Unpack the
38419** record and then call BtreeMovetoUnpacked() to do the work.
38420*/
38421static int btreeMoveto(
38422  BtCursor *pCur,     /* Cursor open on the btree to be searched */
38423  const void *pKey,   /* Packed key if the btree is an index */
38424  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
38425  int bias,           /* Bias search to the high end */
38426  int *pRes           /* Write search results here */
38427){
38428  int rc;                    /* Status code */
38429  UnpackedRecord *pIdxKey;   /* Unpacked index key */
38430  char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
38431
38432  if( pKey ){
38433    assert( nKey==(i64)(int)nKey );
38434    pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
38435                                      aSpace, sizeof(aSpace));
38436    if( pIdxKey==0 ) return SQLITE_NOMEM;
38437  }else{
38438    pIdxKey = 0;
38439  }
38440  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
38441  if( pKey ){
38442    sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
38443  }
38444  return rc;
38445}
38446
38447/*
38448** Restore the cursor to the position it was in (or as close to as possible)
38449** when saveCursorPosition() was called. Note that this call deletes the
38450** saved position info stored by saveCursorPosition(), so there can be
38451** at most one effective restoreCursorPosition() call after each
38452** saveCursorPosition().
38453*/
38454static int btreeRestoreCursorPosition(BtCursor *pCur){
38455  int rc;
38456  assert( cursorHoldsMutex(pCur) );
38457  assert( pCur->eState>=CURSOR_REQUIRESEEK );
38458  if( pCur->eState==CURSOR_FAULT ){
38459    return pCur->skipNext;
38460  }
38461  pCur->eState = CURSOR_INVALID;
38462  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
38463  if( rc==SQLITE_OK ){
38464    sqlite3_free(pCur->pKey);
38465    pCur->pKey = 0;
38466    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
38467  }
38468  return rc;
38469}
38470
38471#define restoreCursorPosition(p) \
38472  (p->eState>=CURSOR_REQUIRESEEK ? \
38473         btreeRestoreCursorPosition(p) : \
38474         SQLITE_OK)
38475
38476/*
38477** Determine whether or not a cursor has moved from the position it
38478** was last placed at.  Cursors can move when the row they are pointing
38479** at is deleted out from under them.
38480**
38481** This routine returns an error code if something goes wrong.  The
38482** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
38483*/
38484SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
38485  int rc;
38486
38487  rc = restoreCursorPosition(pCur);
38488  if( rc ){
38489    *pHasMoved = 1;
38490    return rc;
38491  }
38492  if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
38493    *pHasMoved = 1;
38494  }else{
38495    *pHasMoved = 0;
38496  }
38497  return SQLITE_OK;
38498}
38499
38500#ifndef SQLITE_OMIT_AUTOVACUUM
38501/*
38502** Given a page number of a regular database page, return the page
38503** number for the pointer-map page that contains the entry for the
38504** input page number.
38505*/
38506static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
38507  int nPagesPerMapPage;
38508  Pgno iPtrMap, ret;
38509  assert( sqlite3_mutex_held(pBt->mutex) );
38510  nPagesPerMapPage = (pBt->usableSize/5)+1;
38511  iPtrMap = (pgno-2)/nPagesPerMapPage;
38512  ret = (iPtrMap*nPagesPerMapPage) + 2;
38513  if( ret==PENDING_BYTE_PAGE(pBt) ){
38514    ret++;
38515  }
38516  return ret;
38517}
38518
38519/*
38520** Write an entry into the pointer map.
38521**
38522** This routine updates the pointer map entry for page number 'key'
38523** so that it maps to type 'eType' and parent page number 'pgno'.
38524**
38525** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
38526** a no-op.  If an error occurs, the appropriate error code is written
38527** into *pRC.
38528*/
38529static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
38530  DbPage *pDbPage;  /* The pointer map page */
38531  u8 *pPtrmap;      /* The pointer map data */
38532  Pgno iPtrmap;     /* The pointer map page number */
38533  int offset;       /* Offset in pointer map page */
38534  int rc;           /* Return code from subfunctions */
38535
38536  if( *pRC ) return;
38537
38538  assert( sqlite3_mutex_held(pBt->mutex) );
38539  /* The master-journal page number must never be used as a pointer map page */
38540  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
38541
38542  assert( pBt->autoVacuum );
38543  if( key==0 ){
38544    *pRC = SQLITE_CORRUPT_BKPT;
38545    return;
38546  }
38547  iPtrmap = PTRMAP_PAGENO(pBt, key);
38548  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
38549  if( rc!=SQLITE_OK ){
38550    *pRC = rc;
38551    return;
38552  }
38553  offset = PTRMAP_PTROFFSET(iPtrmap, key);
38554  if( offset<0 ){
38555    *pRC = SQLITE_CORRUPT_BKPT;
38556    goto ptrmap_exit;
38557  }
38558  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
38559
38560  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
38561    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
38562    *pRC= rc = sqlite3PagerWrite(pDbPage);
38563    if( rc==SQLITE_OK ){
38564      pPtrmap[offset] = eType;
38565      put4byte(&pPtrmap[offset+1], parent);
38566    }
38567  }
38568
38569ptrmap_exit:
38570  sqlite3PagerUnref(pDbPage);
38571}
38572
38573/*
38574** Read an entry from the pointer map.
38575**
38576** This routine retrieves the pointer map entry for page 'key', writing
38577** the type and parent page number to *pEType and *pPgno respectively.
38578** An error code is returned if something goes wrong, otherwise SQLITE_OK.
38579*/
38580static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
38581  DbPage *pDbPage;   /* The pointer map page */
38582  int iPtrmap;       /* Pointer map page index */
38583  u8 *pPtrmap;       /* Pointer map page data */
38584  int offset;        /* Offset of entry in pointer map */
38585  int rc;
38586
38587  assert( sqlite3_mutex_held(pBt->mutex) );
38588
38589  iPtrmap = PTRMAP_PAGENO(pBt, key);
38590  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
38591  if( rc!=0 ){
38592    return rc;
38593  }
38594  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
38595
38596  offset = PTRMAP_PTROFFSET(iPtrmap, key);
38597  assert( pEType!=0 );
38598  *pEType = pPtrmap[offset];
38599  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
38600
38601  sqlite3PagerUnref(pDbPage);
38602  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
38603  return SQLITE_OK;
38604}
38605
38606#else /* if defined SQLITE_OMIT_AUTOVACUUM */
38607  #define ptrmapPut(w,x,y,z,rc)
38608  #define ptrmapGet(w,x,y,z) SQLITE_OK
38609  #define ptrmapPutOvflPtr(x, y, rc)
38610#endif
38611
38612/*
38613** Given a btree page and a cell index (0 means the first cell on
38614** the page, 1 means the second cell, and so forth) return a pointer
38615** to the cell content.
38616**
38617** This routine works only for pages that do not contain overflow cells.
38618*/
38619#define findCell(P,I) \
38620  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
38621
38622/*
38623** This a more complex version of findCell() that works for
38624** pages that do contain overflow cells.
38625*/
38626static u8 *findOverflowCell(MemPage *pPage, int iCell){
38627  int i;
38628  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38629  for(i=pPage->nOverflow-1; i>=0; i--){
38630    int k;
38631    struct _OvflCell *pOvfl;
38632    pOvfl = &pPage->aOvfl[i];
38633    k = pOvfl->idx;
38634    if( k<=iCell ){
38635      if( k==iCell ){
38636        return pOvfl->pCell;
38637      }
38638      iCell--;
38639    }
38640  }
38641  return findCell(pPage, iCell);
38642}
38643
38644/*
38645** Parse a cell content block and fill in the CellInfo structure.  There
38646** are two versions of this function.  btreeParseCell() takes a
38647** cell index as the second argument and btreeParseCellPtr()
38648** takes a pointer to the body of the cell as its second argument.
38649**
38650** Within this file, the parseCell() macro can be called instead of
38651** btreeParseCellPtr(). Using some compilers, this will be faster.
38652*/
38653static void btreeParseCellPtr(
38654  MemPage *pPage,         /* Page containing the cell */
38655  u8 *pCell,              /* Pointer to the cell text. */
38656  CellInfo *pInfo         /* Fill in this structure */
38657){
38658  u16 n;                  /* Number bytes in cell content header */
38659  u32 nPayload;           /* Number of bytes of cell payload */
38660
38661  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38662
38663  pInfo->pCell = pCell;
38664  assert( pPage->leaf==0 || pPage->leaf==1 );
38665  n = pPage->childPtrSize;
38666  assert( n==4-4*pPage->leaf );
38667  if( pPage->intKey ){
38668    if( pPage->hasData ){
38669      n += getVarint32(&pCell[n], nPayload);
38670    }else{
38671      nPayload = 0;
38672    }
38673    n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
38674    pInfo->nData = nPayload;
38675  }else{
38676    pInfo->nData = 0;
38677    n += getVarint32(&pCell[n], nPayload);
38678    pInfo->nKey = nPayload;
38679  }
38680  pInfo->nPayload = nPayload;
38681  pInfo->nHeader = n;
38682  testcase( nPayload==pPage->maxLocal );
38683  testcase( nPayload==pPage->maxLocal+1 );
38684  if( likely(nPayload<=pPage->maxLocal) ){
38685    /* This is the (easy) common case where the entire payload fits
38686    ** on the local page.  No overflow is required.
38687    */
38688    int nSize;          /* Total size of cell content in bytes */
38689    nSize = nPayload + n;
38690    pInfo->nLocal = (u16)nPayload;
38691    pInfo->iOverflow = 0;
38692    if( (nSize & ~3)==0 ){
38693      nSize = 4;        /* Minimum cell size is 4 */
38694    }
38695    pInfo->nSize = (u16)nSize;
38696  }else{
38697    /* If the payload will not fit completely on the local page, we have
38698    ** to decide how much to store locally and how much to spill onto
38699    ** overflow pages.  The strategy is to minimize the amount of unused
38700    ** space on overflow pages while keeping the amount of local storage
38701    ** in between minLocal and maxLocal.
38702    **
38703    ** Warning:  changing the way overflow payload is distributed in any
38704    ** way will result in an incompatible file format.
38705    */
38706    int minLocal;  /* Minimum amount of payload held locally */
38707    int maxLocal;  /* Maximum amount of payload held locally */
38708    int surplus;   /* Overflow payload available for local storage */
38709
38710    minLocal = pPage->minLocal;
38711    maxLocal = pPage->maxLocal;
38712    surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
38713    testcase( surplus==maxLocal );
38714    testcase( surplus==maxLocal+1 );
38715    if( surplus <= maxLocal ){
38716      pInfo->nLocal = (u16)surplus;
38717    }else{
38718      pInfo->nLocal = (u16)minLocal;
38719    }
38720    pInfo->iOverflow = (u16)(pInfo->nLocal + n);
38721    pInfo->nSize = pInfo->iOverflow + 4;
38722  }
38723}
38724#define parseCell(pPage, iCell, pInfo) \
38725  btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
38726static void btreeParseCell(
38727  MemPage *pPage,         /* Page containing the cell */
38728  int iCell,              /* The cell index.  First cell is 0 */
38729  CellInfo *pInfo         /* Fill in this structure */
38730){
38731  parseCell(pPage, iCell, pInfo);
38732}
38733
38734/*
38735** Compute the total number of bytes that a Cell needs in the cell
38736** data area of the btree-page.  The return number includes the cell
38737** data header and the local payload, but not any overflow page or
38738** the space used by the cell pointer.
38739*/
38740static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
38741  u8 *pIter = &pCell[pPage->childPtrSize];
38742  u32 nSize;
38743
38744#ifdef SQLITE_DEBUG
38745  /* The value returned by this function should always be the same as
38746  ** the (CellInfo.nSize) value found by doing a full parse of the
38747  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
38748  ** this function verifies that this invariant is not violated. */
38749  CellInfo debuginfo;
38750  btreeParseCellPtr(pPage, pCell, &debuginfo);
38751#endif
38752
38753  if( pPage->intKey ){
38754    u8 *pEnd;
38755    if( pPage->hasData ){
38756      pIter += getVarint32(pIter, nSize);
38757    }else{
38758      nSize = 0;
38759    }
38760
38761    /* pIter now points at the 64-bit integer key value, a variable length
38762    ** integer. The following block moves pIter to point at the first byte
38763    ** past the end of the key value. */
38764    pEnd = &pIter[9];
38765    while( (*pIter++)&0x80 && pIter<pEnd );
38766  }else{
38767    pIter += getVarint32(pIter, nSize);
38768  }
38769
38770  testcase( nSize==pPage->maxLocal );
38771  testcase( nSize==pPage->maxLocal+1 );
38772  if( nSize>pPage->maxLocal ){
38773    int minLocal = pPage->minLocal;
38774    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
38775    testcase( nSize==pPage->maxLocal );
38776    testcase( nSize==pPage->maxLocal+1 );
38777    if( nSize>pPage->maxLocal ){
38778      nSize = minLocal;
38779    }
38780    nSize += 4;
38781  }
38782  nSize += (u32)(pIter - pCell);
38783
38784  /* The minimum size of any cell is 4 bytes. */
38785  if( nSize<4 ){
38786    nSize = 4;
38787  }
38788
38789  assert( nSize==debuginfo.nSize );
38790  return (u16)nSize;
38791}
38792
38793#ifdef SQLITE_DEBUG
38794/* This variation on cellSizePtr() is used inside of assert() statements
38795** only. */
38796static u16 cellSize(MemPage *pPage, int iCell){
38797  return cellSizePtr(pPage, findCell(pPage, iCell));
38798}
38799#endif
38800
38801#ifndef SQLITE_OMIT_AUTOVACUUM
38802/*
38803** If the cell pCell, part of page pPage contains a pointer
38804** to an overflow page, insert an entry into the pointer-map
38805** for the overflow page.
38806*/
38807static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
38808  CellInfo info;
38809  if( *pRC ) return;
38810  assert( pCell!=0 );
38811  btreeParseCellPtr(pPage, pCell, &info);
38812  assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
38813  if( info.iOverflow ){
38814    Pgno ovfl = get4byte(&pCell[info.iOverflow]);
38815    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
38816  }
38817}
38818#endif
38819
38820
38821/*
38822** Defragment the page given.  All Cells are moved to the
38823** end of the page and all free space is collected into one
38824** big FreeBlk that occurs in between the header and cell
38825** pointer array and the cell content area.
38826*/
38827static int defragmentPage(MemPage *pPage){
38828  int i;                     /* Loop counter */
38829  int pc;                    /* Address of a i-th cell */
38830  int hdr;                   /* Offset to the page header */
38831  int size;                  /* Size of a cell */
38832  int usableSize;            /* Number of usable bytes on a page */
38833  int cellOffset;            /* Offset to the cell pointer array */
38834  int cbrk;                  /* Offset to the cell content area */
38835  int nCell;                 /* Number of cells on the page */
38836  unsigned char *data;       /* The page data */
38837  unsigned char *temp;       /* Temp area for cell content */
38838  int iCellFirst;            /* First allowable cell index */
38839  int iCellLast;             /* Last possible cell index */
38840
38841
38842  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38843  assert( pPage->pBt!=0 );
38844  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
38845  assert( pPage->nOverflow==0 );
38846  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38847  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
38848  data = pPage->aData;
38849  hdr = pPage->hdrOffset;
38850  cellOffset = pPage->cellOffset;
38851  nCell = pPage->nCell;
38852  assert( nCell==get2byte(&data[hdr+3]) );
38853  usableSize = pPage->pBt->usableSize;
38854  cbrk = get2byte(&data[hdr+5]);
38855  memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
38856  cbrk = usableSize;
38857  iCellFirst = cellOffset + 2*nCell;
38858  iCellLast = usableSize - 4;
38859  for(i=0; i<nCell; i++){
38860    u8 *pAddr;     /* The i-th cell pointer */
38861    pAddr = &data[cellOffset + i*2];
38862    pc = get2byte(pAddr);
38863    testcase( pc==iCellFirst );
38864    testcase( pc==iCellLast );
38865#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
38866    /* These conditions have already been verified in btreeInitPage()
38867    ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
38868    */
38869    if( pc<iCellFirst || pc>iCellLast ){
38870      return SQLITE_CORRUPT_BKPT;
38871    }
38872#endif
38873    assert( pc>=iCellFirst && pc<=iCellLast );
38874    size = cellSizePtr(pPage, &temp[pc]);
38875    cbrk -= size;
38876#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
38877    if( cbrk<iCellFirst ){
38878      return SQLITE_CORRUPT_BKPT;
38879    }
38880#else
38881    if( cbrk<iCellFirst || pc+size>usableSize ){
38882      return SQLITE_CORRUPT_BKPT;
38883    }
38884#endif
38885    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
38886    testcase( cbrk+size==usableSize );
38887    testcase( pc+size==usableSize );
38888    memcpy(&data[cbrk], &temp[pc], size);
38889    put2byte(pAddr, cbrk);
38890  }
38891  assert( cbrk>=iCellFirst );
38892  put2byte(&data[hdr+5], cbrk);
38893  data[hdr+1] = 0;
38894  data[hdr+2] = 0;
38895  data[hdr+7] = 0;
38896  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
38897  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38898  if( cbrk-iCellFirst!=pPage->nFree ){
38899    return SQLITE_CORRUPT_BKPT;
38900  }
38901  return SQLITE_OK;
38902}
38903
38904/*
38905** Allocate nByte bytes of space from within the B-Tree page passed
38906** as the first argument. Write into *pIdx the index into pPage->aData[]
38907** of the first byte of allocated space. Return either SQLITE_OK or
38908** an error code (usually SQLITE_CORRUPT).
38909**
38910** The caller guarantees that there is sufficient space to make the
38911** allocation.  This routine might need to defragment in order to bring
38912** all the space together, however.  This routine will avoid using
38913** the first two bytes past the cell pointer area since presumably this
38914** allocation is being made in order to insert a new cell, so we will
38915** also end up needing a new cell pointer.
38916*/
38917static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
38918  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
38919  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
38920  int nFrag;                           /* Number of fragmented bytes on pPage */
38921  int top;                             /* First byte of cell content area */
38922  int gap;        /* First byte of gap between cell pointers and cell content */
38923  int rc;         /* Integer return code */
38924  int usableSize; /* Usable size of the page */
38925
38926  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38927  assert( pPage->pBt );
38928  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38929  assert( nByte>=0 );  /* Minimum cell size is 4 */
38930  assert( pPage->nFree>=nByte );
38931  assert( pPage->nOverflow==0 );
38932  usableSize = pPage->pBt->usableSize;
38933  assert( nByte < usableSize-8 );
38934
38935  nFrag = data[hdr+7];
38936  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
38937  gap = pPage->cellOffset + 2*pPage->nCell;
38938  top = get2byte(&data[hdr+5]);
38939  if( gap>top ) return SQLITE_CORRUPT_BKPT;
38940  testcase( gap+2==top );
38941  testcase( gap+1==top );
38942  testcase( gap==top );
38943
38944  if( nFrag>=60 ){
38945    /* Always defragment highly fragmented pages */
38946    rc = defragmentPage(pPage);
38947    if( rc ) return rc;
38948    top = get2byte(&data[hdr+5]);
38949  }else if( gap+2<=top ){
38950    /* Search the freelist looking for a free slot big enough to satisfy
38951    ** the request. The allocation is made from the first free slot in
38952    ** the list that is large enough to accomadate it.
38953    */
38954    int pc, addr;
38955    for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
38956      int size;            /* Size of the free slot */
38957      if( pc>usableSize-4 || pc<addr+4 ){
38958        return SQLITE_CORRUPT_BKPT;
38959      }
38960      size = get2byte(&data[pc+2]);
38961      if( size>=nByte ){
38962        int x = size - nByte;
38963        testcase( x==4 );
38964        testcase( x==3 );
38965        if( x<4 ){
38966          /* Remove the slot from the free-list. Update the number of
38967          ** fragmented bytes within the page. */
38968          memcpy(&data[addr], &data[pc], 2);
38969          data[hdr+7] = (u8)(nFrag + x);
38970        }else if( size+pc > usableSize ){
38971          return SQLITE_CORRUPT_BKPT;
38972        }else{
38973          /* The slot remains on the free-list. Reduce its size to account
38974          ** for the portion used by the new allocation. */
38975          put2byte(&data[pc+2], x);
38976        }
38977        *pIdx = pc + x;
38978        return SQLITE_OK;
38979      }
38980    }
38981  }
38982
38983  /* Check to make sure there is enough space in the gap to satisfy
38984  ** the allocation.  If not, defragment.
38985  */
38986  testcase( gap+2+nByte==top );
38987  if( gap+2+nByte>top ){
38988    rc = defragmentPage(pPage);
38989    if( rc ) return rc;
38990    top = get2byte(&data[hdr+5]);
38991    assert( gap+nByte<=top );
38992  }
38993
38994
38995  /* Allocate memory from the gap in between the cell pointer array
38996  ** and the cell content area.  The btreeInitPage() call has already
38997  ** validated the freelist.  Given that the freelist is valid, there
38998  ** is no way that the allocation can extend off the end of the page.
38999  ** The assert() below verifies the previous sentence.
39000  */
39001  top -= nByte;
39002  put2byte(&data[hdr+5], top);
39003  assert( top+nByte <= pPage->pBt->usableSize );
39004  *pIdx = top;
39005  return SQLITE_OK;
39006}
39007
39008/*
39009** Return a section of the pPage->aData to the freelist.
39010** The first byte of the new free block is pPage->aDisk[start]
39011** and the size of the block is "size" bytes.
39012**
39013** Most of the effort here is involved in coalesing adjacent
39014** free blocks into a single big free block.
39015*/
39016static int freeSpace(MemPage *pPage, int start, int size){
39017  int addr, pbegin, hdr;
39018  int iLast;                        /* Largest possible freeblock offset */
39019  unsigned char *data = pPage->aData;
39020
39021  assert( pPage->pBt!=0 );
39022  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
39023  assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
39024  assert( (start + size)<=pPage->pBt->usableSize );
39025  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39026  assert( size>=0 );   /* Minimum cell size is 4 */
39027
39028#ifdef SQLITE_SECURE_DELETE
39029  /* Overwrite deleted information with zeros when the SECURE_DELETE
39030  ** option is enabled at compile-time */
39031  memset(&data[start], 0, size);
39032#endif
39033
39034  /* Add the space back into the linked list of freeblocks.  Note that
39035  ** even though the freeblock list was checked by btreeInitPage(),
39036  ** btreeInitPage() did not detect overlapping cells or
39037  ** freeblocks that overlapped cells.   Nor does it detect when the
39038  ** cell content area exceeds the value in the page header.  If these
39039  ** situations arise, then subsequent insert operations might corrupt
39040  ** the freelist.  So we do need to check for corruption while scanning
39041  ** the freelist.
39042  */
39043  hdr = pPage->hdrOffset;
39044  addr = hdr + 1;
39045  iLast = pPage->pBt->usableSize - 4;
39046  assert( start<=iLast );
39047  while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
39048    if( pbegin<addr+4 ){
39049      return SQLITE_CORRUPT_BKPT;
39050    }
39051    addr = pbegin;
39052  }
39053  if( pbegin>iLast ){
39054    return SQLITE_CORRUPT_BKPT;
39055  }
39056  assert( pbegin>addr || pbegin==0 );
39057  put2byte(&data[addr], start);
39058  put2byte(&data[start], pbegin);
39059  put2byte(&data[start+2], size);
39060  pPage->nFree = pPage->nFree + (u16)size;
39061
39062  /* Coalesce adjacent free blocks */
39063  addr = hdr + 1;
39064  while( (pbegin = get2byte(&data[addr]))>0 ){
39065    int pnext, psize, x;
39066    assert( pbegin>addr );
39067    assert( pbegin<=pPage->pBt->usableSize-4 );
39068    pnext = get2byte(&data[pbegin]);
39069    psize = get2byte(&data[pbegin+2]);
39070    if( pbegin + psize + 3 >= pnext && pnext>0 ){
39071      int frag = pnext - (pbegin+psize);
39072      if( (frag<0) || (frag>(int)data[hdr+7]) ){
39073        return SQLITE_CORRUPT_BKPT;
39074      }
39075      data[hdr+7] -= (u8)frag;
39076      x = get2byte(&data[pnext]);
39077      put2byte(&data[pbegin], x);
39078      x = pnext + get2byte(&data[pnext+2]) - pbegin;
39079      put2byte(&data[pbegin+2], x);
39080    }else{
39081      addr = pbegin;
39082    }
39083  }
39084
39085  /* If the cell content area begins with a freeblock, remove it. */
39086  if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
39087    int top;
39088    pbegin = get2byte(&data[hdr+1]);
39089    memcpy(&data[hdr+1], &data[pbegin], 2);
39090    top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
39091    put2byte(&data[hdr+5], top);
39092  }
39093  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
39094  return SQLITE_OK;
39095}
39096
39097/*
39098** Decode the flags byte (the first byte of the header) for a page
39099** and initialize fields of the MemPage structure accordingly.
39100**
39101** Only the following combinations are supported.  Anything different
39102** indicates a corrupt database files:
39103**
39104**         PTF_ZERODATA
39105**         PTF_ZERODATA | PTF_LEAF
39106**         PTF_LEAFDATA | PTF_INTKEY
39107**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
39108*/
39109static int decodeFlags(MemPage *pPage, int flagByte){
39110  BtShared *pBt;     /* A copy of pPage->pBt */
39111
39112  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
39113  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39114  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
39115  flagByte &= ~PTF_LEAF;
39116  pPage->childPtrSize = 4-4*pPage->leaf;
39117  pBt = pPage->pBt;
39118  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
39119    pPage->intKey = 1;
39120    pPage->hasData = pPage->leaf;
39121    pPage->maxLocal = pBt->maxLeaf;
39122    pPage->minLocal = pBt->minLeaf;
39123  }else if( flagByte==PTF_ZERODATA ){
39124    pPage->intKey = 0;
39125    pPage->hasData = 0;
39126    pPage->maxLocal = pBt->maxLocal;
39127    pPage->minLocal = pBt->minLocal;
39128  }else{
39129    return SQLITE_CORRUPT_BKPT;
39130  }
39131  return SQLITE_OK;
39132}
39133
39134/*
39135** Initialize the auxiliary information for a disk block.
39136**
39137** Return SQLITE_OK on success.  If we see that the page does
39138** not contain a well-formed database page, then return
39139** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
39140** guarantee that the page is well-formed.  It only shows that
39141** we failed to detect any corruption.
39142*/
39143static int btreeInitPage(MemPage *pPage){
39144
39145  assert( pPage->pBt!=0 );
39146  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39147  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
39148  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
39149  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
39150
39151  if( !pPage->isInit ){
39152    u16 pc;            /* Address of a freeblock within pPage->aData[] */
39153    u8 hdr;            /* Offset to beginning of page header */
39154    u8 *data;          /* Equal to pPage->aData */
39155    BtShared *pBt;        /* The main btree structure */
39156    u16 usableSize;    /* Amount of usable space on each page */
39157    u16 cellOffset;    /* Offset from start of page to first cell pointer */
39158    u16 nFree;         /* Number of unused bytes on the page */
39159    u16 top;           /* First byte of the cell content area */
39160    int iCellFirst;    /* First allowable cell or freeblock offset */
39161    int iCellLast;     /* Last possible cell or freeblock offset */
39162
39163    pBt = pPage->pBt;
39164
39165    hdr = pPage->hdrOffset;
39166    data = pPage->aData;
39167    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
39168    assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
39169    pPage->maskPage = pBt->pageSize - 1;
39170    pPage->nOverflow = 0;
39171    usableSize = pBt->usableSize;
39172    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
39173    top = get2byte(&data[hdr+5]);
39174    pPage->nCell = get2byte(&data[hdr+3]);
39175    if( pPage->nCell>MX_CELL(pBt) ){
39176      /* To many cells for a single page.  The page must be corrupt */
39177      return SQLITE_CORRUPT_BKPT;
39178    }
39179    testcase( pPage->nCell==MX_CELL(pBt) );
39180
39181    /* A malformed database page might cause us to read past the end
39182    ** of page when parsing a cell.
39183    **
39184    ** The following block of code checks early to see if a cell extends
39185    ** past the end of a page boundary and causes SQLITE_CORRUPT to be
39186    ** returned if it does.
39187    */
39188    iCellFirst = cellOffset + 2*pPage->nCell;
39189    iCellLast = usableSize - 4;
39190#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
39191    {
39192      int i;            /* Index into the cell pointer array */
39193      int sz;           /* Size of a cell */
39194
39195      if( !pPage->leaf ) iCellLast--;
39196      for(i=0; i<pPage->nCell; i++){
39197        pc = get2byte(&data[cellOffset+i*2]);
39198        testcase( pc==iCellFirst );
39199        testcase( pc==iCellLast );
39200        if( pc<iCellFirst || pc>iCellLast ){
39201          return SQLITE_CORRUPT_BKPT;
39202        }
39203        sz = cellSizePtr(pPage, &data[pc]);
39204        testcase( pc+sz==usableSize );
39205        if( pc+sz>usableSize ){
39206          return SQLITE_CORRUPT_BKPT;
39207        }
39208      }
39209      if( !pPage->leaf ) iCellLast++;
39210    }
39211#endif
39212
39213    /* Compute the total free space on the page */
39214    pc = get2byte(&data[hdr+1]);
39215    nFree = data[hdr+7] + top;
39216    while( pc>0 ){
39217      u16 next, size;
39218      if( pc<iCellFirst || pc>iCellLast ){
39219        /* Start of free block is off the page */
39220        return SQLITE_CORRUPT_BKPT;
39221      }
39222      next = get2byte(&data[pc]);
39223      size = get2byte(&data[pc+2]);
39224      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
39225        /* Free blocks must be in ascending order. And the last byte of
39226	** the free-block must lie on the database page.  */
39227        return SQLITE_CORRUPT_BKPT;
39228      }
39229      nFree = nFree + size;
39230      pc = next;
39231    }
39232
39233    /* At this point, nFree contains the sum of the offset to the start
39234    ** of the cell-content area plus the number of free bytes within
39235    ** the cell-content area. If this is greater than the usable-size
39236    ** of the page, then the page must be corrupted. This check also
39237    ** serves to verify that the offset to the start of the cell-content
39238    ** area, according to the page header, lies within the page.
39239    */
39240    if( nFree>usableSize ){
39241      return SQLITE_CORRUPT_BKPT;
39242    }
39243    pPage->nFree = (u16)(nFree - iCellFirst);
39244    pPage->isInit = 1;
39245  }
39246  return SQLITE_OK;
39247}
39248
39249/*
39250** Set up a raw page so that it looks like a database page holding
39251** no entries.
39252*/
39253static void zeroPage(MemPage *pPage, int flags){
39254  unsigned char *data = pPage->aData;
39255  BtShared *pBt = pPage->pBt;
39256  u8 hdr = pPage->hdrOffset;
39257  u16 first;
39258
39259  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
39260  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
39261  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
39262  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
39263  assert( sqlite3_mutex_held(pBt->mutex) );
39264#ifdef SQLITE_SECURE_DELETE
39265  memset(&data[hdr], 0, pBt->usableSize - hdr);
39266#endif
39267  data[hdr] = (char)flags;
39268  first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
39269  memset(&data[hdr+1], 0, 4);
39270  data[hdr+7] = 0;
39271  put2byte(&data[hdr+5], pBt->usableSize);
39272  pPage->nFree = pBt->usableSize - first;
39273  decodeFlags(pPage, flags);
39274  pPage->hdrOffset = hdr;
39275  pPage->cellOffset = first;
39276  pPage->nOverflow = 0;
39277  assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
39278  pPage->maskPage = pBt->pageSize - 1;
39279  pPage->nCell = 0;
39280  pPage->isInit = 1;
39281}
39282
39283
39284/*
39285** Convert a DbPage obtained from the pager into a MemPage used by
39286** the btree layer.
39287*/
39288static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
39289  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
39290  pPage->aData = sqlite3PagerGetData(pDbPage);
39291  pPage->pDbPage = pDbPage;
39292  pPage->pBt = pBt;
39293  pPage->pgno = pgno;
39294  pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
39295  return pPage;
39296}
39297
39298/*
39299** Get a page from the pager.  Initialize the MemPage.pBt and
39300** MemPage.aData elements if needed.
39301**
39302** If the noContent flag is set, it means that we do not care about
39303** the content of the page at this time.  So do not go to the disk
39304** to fetch the content.  Just fill in the content with zeros for now.
39305** If in the future we call sqlite3PagerWrite() on this page, that
39306** means we have started to be concerned about content and the disk
39307** read should occur at that point.
39308*/
39309static int btreeGetPage(
39310  BtShared *pBt,       /* The btree */
39311  Pgno pgno,           /* Number of the page to fetch */
39312  MemPage **ppPage,    /* Return the page in this parameter */
39313  int noContent        /* Do not load page content if true */
39314){
39315  int rc;
39316  DbPage *pDbPage;
39317
39318  assert( sqlite3_mutex_held(pBt->mutex) );
39319  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
39320  if( rc ) return rc;
39321  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
39322  return SQLITE_OK;
39323}
39324
39325/*
39326** Retrieve a page from the pager cache. If the requested page is not
39327** already in the pager cache return NULL. Initialize the MemPage.pBt and
39328** MemPage.aData elements if needed.
39329*/
39330static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
39331  DbPage *pDbPage;
39332  assert( sqlite3_mutex_held(pBt->mutex) );
39333  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
39334  if( pDbPage ){
39335    return btreePageFromDbPage(pDbPage, pgno, pBt);
39336  }
39337  return 0;
39338}
39339
39340/*
39341** Return the size of the database file in pages. If there is any kind of
39342** error, return ((unsigned int)-1).
39343*/
39344static Pgno pagerPagecount(BtShared *pBt){
39345  int nPage = -1;
39346  int rc;
39347  assert( pBt->pPage1 );
39348  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
39349  assert( rc==SQLITE_OK || nPage==-1 );
39350  return (Pgno)nPage;
39351}
39352
39353/*
39354** Get a page from the pager and initialize it.  This routine is just a
39355** convenience wrapper around separate calls to btreeGetPage() and
39356** btreeInitPage().
39357**
39358** If an error occurs, then the value *ppPage is set to is undefined. It
39359** may remain unchanged, or it may be set to an invalid value.
39360*/
39361static int getAndInitPage(
39362  BtShared *pBt,          /* The database file */
39363  Pgno pgno,           /* Number of the page to get */
39364  MemPage **ppPage     /* Write the page pointer here */
39365){
39366  int rc;
39367  TESTONLY( Pgno iLastPg = pagerPagecount(pBt); )
39368  assert( sqlite3_mutex_held(pBt->mutex) );
39369
39370  rc = btreeGetPage(pBt, pgno, ppPage, 0);
39371  if( rc==SQLITE_OK ){
39372    rc = btreeInitPage(*ppPage);
39373    if( rc!=SQLITE_OK ){
39374      releasePage(*ppPage);
39375    }
39376  }
39377
39378  /* If the requested page number was either 0 or greater than the page
39379  ** number of the last page in the database, this function should return
39380  ** SQLITE_CORRUPT or some other error (i.e. SQLITE_FULL). Check that this
39381  ** is the case.  */
39382  assert( (pgno>0 && pgno<=iLastPg) || rc!=SQLITE_OK );
39383  testcase( pgno==0 );
39384  testcase( pgno==iLastPg );
39385
39386  return rc;
39387}
39388
39389/*
39390** Release a MemPage.  This should be called once for each prior
39391** call to btreeGetPage.
39392*/
39393static void releasePage(MemPage *pPage){
39394  if( pPage ){
39395    assert( pPage->aData );
39396    assert( pPage->pBt );
39397    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
39398    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
39399    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39400    sqlite3PagerUnref(pPage->pDbPage);
39401  }
39402}
39403
39404/*
39405** During a rollback, when the pager reloads information into the cache
39406** so that the cache is restored to its original state at the start of
39407** the transaction, for each page restored this routine is called.
39408**
39409** This routine needs to reset the extra data section at the end of the
39410** page to agree with the restored data.
39411*/
39412static void pageReinit(DbPage *pData){
39413  MemPage *pPage;
39414  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
39415  assert( sqlite3PagerPageRefcount(pData)>0 );
39416  if( pPage->isInit ){
39417    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39418    pPage->isInit = 0;
39419    if( sqlite3PagerPageRefcount(pData)>1 ){
39420      /* pPage might not be a btree page;  it might be an overflow page
39421      ** or ptrmap page or a free page.  In those cases, the following
39422      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
39423      ** But no harm is done by this.  And it is very important that
39424      ** btreeInitPage() be called on every btree page so we make
39425      ** the call for every page that comes in for re-initing. */
39426      btreeInitPage(pPage);
39427    }
39428  }
39429}
39430
39431/*
39432** Invoke the busy handler for a btree.
39433*/
39434static int btreeInvokeBusyHandler(void *pArg){
39435  BtShared *pBt = (BtShared*)pArg;
39436  assert( pBt->db );
39437  assert( sqlite3_mutex_held(pBt->db->mutex) );
39438  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
39439}
39440
39441/*
39442** Open a database file.
39443**
39444** zFilename is the name of the database file.  If zFilename is NULL
39445** a new database with a random name is created.  This randomly named
39446** database file will be deleted when sqlite3BtreeClose() is called.
39447** If zFilename is ":memory:" then an in-memory database is created
39448** that is automatically destroyed when it is closed.
39449**
39450** If the database is already opened in the same database connection
39451** and we are in shared cache mode, then the open will fail with an
39452** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
39453** objects in the same database connection since doing so will lead
39454** to problems with locking.
39455*/
39456SQLITE_PRIVATE int sqlite3BtreeOpen(
39457  const char *zFilename,  /* Name of the file containing the BTree database */
39458  sqlite3 *db,            /* Associated database handle */
39459  Btree **ppBtree,        /* Pointer to new Btree object written here */
39460  int flags,              /* Options */
39461  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
39462){
39463  sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
39464  BtShared *pBt = 0;             /* Shared part of btree structure */
39465  Btree *p;                      /* Handle to return */
39466  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
39467  int rc = SQLITE_OK;            /* Result code from this function */
39468  u8 nReserve;                   /* Byte of unused space on each page */
39469  unsigned char zDbHeader[100];  /* Database header content */
39470
39471  /* Set the variable isMemdb to true for an in-memory database, or
39472  ** false for a file-based database. This symbol is only required if
39473  ** either of the shared-data or autovacuum features are compiled
39474  ** into the library.
39475  */
39476#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
39477  #ifdef SQLITE_OMIT_MEMORYDB
39478    const int isMemdb = 0;
39479  #else
39480    const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
39481  #endif
39482#endif
39483
39484  assert( db!=0 );
39485  assert( sqlite3_mutex_held(db->mutex) );
39486
39487  pVfs = db->pVfs;
39488  p = sqlite3MallocZero(sizeof(Btree));
39489  if( !p ){
39490    return SQLITE_NOMEM;
39491  }
39492  p->inTrans = TRANS_NONE;
39493  p->db = db;
39494#ifndef SQLITE_OMIT_SHARED_CACHE
39495  p->lock.pBtree = p;
39496  p->lock.iTable = 1;
39497#endif
39498
39499#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
39500  /*
39501  ** If this Btree is a candidate for shared cache, try to find an
39502  ** existing BtShared object that we can share with
39503  */
39504  if( isMemdb==0 && zFilename && zFilename[0] ){
39505    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
39506      int nFullPathname = pVfs->mxPathname+1;
39507      char *zFullPathname = sqlite3Malloc(nFullPathname);
39508      sqlite3_mutex *mutexShared;
39509      p->sharable = 1;
39510      if( !zFullPathname ){
39511        sqlite3_free(p);
39512        return SQLITE_NOMEM;
39513      }
39514      sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
39515      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
39516      sqlite3_mutex_enter(mutexOpen);
39517      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
39518      sqlite3_mutex_enter(mutexShared);
39519      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
39520        assert( pBt->nRef>0 );
39521        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
39522                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
39523          int iDb;
39524          for(iDb=db->nDb-1; iDb>=0; iDb--){
39525            Btree *pExisting = db->aDb[iDb].pBt;
39526            if( pExisting && pExisting->pBt==pBt ){
39527              sqlite3_mutex_leave(mutexShared);
39528              sqlite3_mutex_leave(mutexOpen);
39529              sqlite3_free(zFullPathname);
39530              sqlite3_free(p);
39531              return SQLITE_CONSTRAINT;
39532            }
39533          }
39534          p->pBt = pBt;
39535          pBt->nRef++;
39536          break;
39537        }
39538      }
39539      sqlite3_mutex_leave(mutexShared);
39540      sqlite3_free(zFullPathname);
39541    }
39542#ifdef SQLITE_DEBUG
39543    else{
39544      /* In debug mode, we mark all persistent databases as sharable
39545      ** even when they are not.  This exercises the locking code and
39546      ** gives more opportunity for asserts(sqlite3_mutex_held())
39547      ** statements to find locking problems.
39548      */
39549      p->sharable = 1;
39550    }
39551#endif
39552  }
39553#endif
39554  if( pBt==0 ){
39555    /*
39556    ** The following asserts make sure that structures used by the btree are
39557    ** the right size.  This is to guard against size changes that result
39558    ** when compiling on a different architecture.
39559    */
39560    assert( sizeof(i64)==8 || sizeof(i64)==4 );
39561    assert( sizeof(u64)==8 || sizeof(u64)==4 );
39562    assert( sizeof(u32)==4 );
39563    assert( sizeof(u16)==2 );
39564    assert( sizeof(Pgno)==4 );
39565
39566    pBt = sqlite3MallocZero( sizeof(*pBt) );
39567    if( pBt==0 ){
39568      rc = SQLITE_NOMEM;
39569      goto btree_open_out;
39570    }
39571    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
39572                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
39573    if( rc==SQLITE_OK ){
39574      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
39575    }
39576    if( rc!=SQLITE_OK ){
39577      goto btree_open_out;
39578    }
39579    pBt->db = db;
39580    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
39581    p->pBt = pBt;
39582
39583    pBt->pCursor = 0;
39584    pBt->pPage1 = 0;
39585    pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
39586    pBt->pageSize = get2byte(&zDbHeader[16]);
39587    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
39588         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
39589      pBt->pageSize = 0;
39590#ifndef SQLITE_OMIT_AUTOVACUUM
39591      /* If the magic name ":memory:" will create an in-memory database, then
39592      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
39593      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
39594      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
39595      ** regular file-name. In this case the auto-vacuum applies as per normal.
39596      */
39597      if( zFilename && !isMemdb ){
39598        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
39599        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
39600      }
39601#endif
39602      nReserve = 0;
39603    }else{
39604      nReserve = zDbHeader[20];
39605      pBt->pageSizeFixed = 1;
39606#ifndef SQLITE_OMIT_AUTOVACUUM
39607      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
39608      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
39609#endif
39610    }
39611    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
39612    if( rc ) goto btree_open_out;
39613    pBt->usableSize = pBt->pageSize - nReserve;
39614    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
39615
39616#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
39617    /* Add the new BtShared object to the linked list sharable BtShareds.
39618    */
39619    if( p->sharable ){
39620      sqlite3_mutex *mutexShared;
39621      pBt->nRef = 1;
39622      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
39623      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
39624        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
39625        if( pBt->mutex==0 ){
39626          rc = SQLITE_NOMEM;
39627          db->mallocFailed = 0;
39628          goto btree_open_out;
39629        }
39630      }
39631      sqlite3_mutex_enter(mutexShared);
39632      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
39633      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
39634      sqlite3_mutex_leave(mutexShared);
39635    }
39636#endif
39637  }
39638
39639#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
39640  /* If the new Btree uses a sharable pBtShared, then link the new
39641  ** Btree into the list of all sharable Btrees for the same connection.
39642  ** The list is kept in ascending order by pBt address.
39643  */
39644  if( p->sharable ){
39645    int i;
39646    Btree *pSib;
39647    for(i=0; i<db->nDb; i++){
39648      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
39649        while( pSib->pPrev ){ pSib = pSib->pPrev; }
39650        if( p->pBt<pSib->pBt ){
39651          p->pNext = pSib;
39652          p->pPrev = 0;
39653          pSib->pPrev = p;
39654        }else{
39655          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
39656            pSib = pSib->pNext;
39657          }
39658          p->pNext = pSib->pNext;
39659          p->pPrev = pSib;
39660          if( p->pNext ){
39661            p->pNext->pPrev = p;
39662          }
39663          pSib->pNext = p;
39664        }
39665        break;
39666      }
39667    }
39668  }
39669#endif
39670  *ppBtree = p;
39671
39672btree_open_out:
39673  if( rc!=SQLITE_OK ){
39674    if( pBt && pBt->pPager ){
39675      sqlite3PagerClose(pBt->pPager);
39676    }
39677    sqlite3_free(pBt);
39678    sqlite3_free(p);
39679    *ppBtree = 0;
39680  }
39681  if( mutexOpen ){
39682    assert( sqlite3_mutex_held(mutexOpen) );
39683    sqlite3_mutex_leave(mutexOpen);
39684  }
39685  return rc;
39686}
39687
39688/*
39689** Decrement the BtShared.nRef counter.  When it reaches zero,
39690** remove the BtShared structure from the sharing list.  Return
39691** true if the BtShared.nRef counter reaches zero and return
39692** false if it is still positive.
39693*/
39694static int removeFromSharingList(BtShared *pBt){
39695#ifndef SQLITE_OMIT_SHARED_CACHE
39696  sqlite3_mutex *pMaster;
39697  BtShared *pList;
39698  int removed = 0;
39699
39700  assert( sqlite3_mutex_notheld(pBt->mutex) );
39701  pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
39702  sqlite3_mutex_enter(pMaster);
39703  pBt->nRef--;
39704  if( pBt->nRef<=0 ){
39705    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
39706      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
39707    }else{
39708      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
39709      while( ALWAYS(pList) && pList->pNext!=pBt ){
39710        pList=pList->pNext;
39711      }
39712      if( ALWAYS(pList) ){
39713        pList->pNext = pBt->pNext;
39714      }
39715    }
39716    if( SQLITE_THREADSAFE ){
39717      sqlite3_mutex_free(pBt->mutex);
39718    }
39719    removed = 1;
39720  }
39721  sqlite3_mutex_leave(pMaster);
39722  return removed;
39723#else
39724  return 1;
39725#endif
39726}
39727
39728/*
39729** Make sure pBt->pTmpSpace points to an allocation of
39730** MX_CELL_SIZE(pBt) bytes.
39731*/
39732static void allocateTempSpace(BtShared *pBt){
39733  if( !pBt->pTmpSpace ){
39734    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
39735  }
39736}
39737
39738/*
39739** Free the pBt->pTmpSpace allocation
39740*/
39741static void freeTempSpace(BtShared *pBt){
39742  sqlite3PageFree( pBt->pTmpSpace);
39743  pBt->pTmpSpace = 0;
39744}
39745
39746/*
39747** Close an open database and invalidate all cursors.
39748*/
39749SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
39750  BtShared *pBt = p->pBt;
39751  BtCursor *pCur;
39752
39753  /* Close all cursors opened via this handle.  */
39754  assert( sqlite3_mutex_held(p->db->mutex) );
39755  sqlite3BtreeEnter(p);
39756  pCur = pBt->pCursor;
39757  while( pCur ){
39758    BtCursor *pTmp = pCur;
39759    pCur = pCur->pNext;
39760    if( pTmp->pBtree==p ){
39761      sqlite3BtreeCloseCursor(pTmp);
39762    }
39763  }
39764
39765  /* Rollback any active transaction and free the handle structure.
39766  ** The call to sqlite3BtreeRollback() drops any table-locks held by
39767  ** this handle.
39768  */
39769  sqlite3BtreeRollback(p);
39770  sqlite3BtreeLeave(p);
39771
39772  /* If there are still other outstanding references to the shared-btree
39773  ** structure, return now. The remainder of this procedure cleans
39774  ** up the shared-btree.
39775  */
39776  assert( p->wantToLock==0 && p->locked==0 );
39777  if( !p->sharable || removeFromSharingList(pBt) ){
39778    /* The pBt is no longer on the sharing list, so we can access
39779    ** it without having to hold the mutex.
39780    **
39781    ** Clean out and delete the BtShared object.
39782    */
39783    assert( !pBt->pCursor );
39784    sqlite3PagerClose(pBt->pPager);
39785    if( pBt->xFreeSchema && pBt->pSchema ){
39786      pBt->xFreeSchema(pBt->pSchema);
39787    }
39788    sqlite3_free(pBt->pSchema);
39789    freeTempSpace(pBt);
39790    sqlite3_free(pBt);
39791  }
39792
39793#ifndef SQLITE_OMIT_SHARED_CACHE
39794  assert( p->wantToLock==0 );
39795  assert( p->locked==0 );
39796  if( p->pPrev ) p->pPrev->pNext = p->pNext;
39797  if( p->pNext ) p->pNext->pPrev = p->pPrev;
39798#endif
39799
39800  sqlite3_free(p);
39801  return SQLITE_OK;
39802}
39803
39804/*
39805** Change the limit on the number of pages allowed in the cache.
39806**
39807** The maximum number of cache pages is set to the absolute
39808** value of mxPage.  If mxPage is negative, the pager will
39809** operate asynchronously - it will not stop to do fsync()s
39810** to insure data is written to the disk surface before
39811** continuing.  Transactions still work if synchronous is off,
39812** and the database cannot be corrupted if this program
39813** crashes.  But if the operating system crashes or there is
39814** an abrupt power failure when synchronous is off, the database
39815** could be left in an inconsistent and unrecoverable state.
39816** Synchronous is on by default so database corruption is not
39817** normally a worry.
39818*/
39819SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
39820  BtShared *pBt = p->pBt;
39821  assert( sqlite3_mutex_held(p->db->mutex) );
39822  sqlite3BtreeEnter(p);
39823  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
39824  sqlite3BtreeLeave(p);
39825  return SQLITE_OK;
39826}
39827
39828/*
39829** Change the way data is synced to disk in order to increase or decrease
39830** how well the database resists damage due to OS crashes and power
39831** failures.  Level 1 is the same as asynchronous (no syncs() occur and
39832** there is a high probability of damage)  Level 2 is the default.  There
39833** is a very low but non-zero probability of damage.  Level 3 reduces the
39834** probability of damage to near zero but with a write performance reduction.
39835*/
39836#ifndef SQLITE_OMIT_PAGER_PRAGMAS
39837SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
39838  BtShared *pBt = p->pBt;
39839  assert( sqlite3_mutex_held(p->db->mutex) );
39840  sqlite3BtreeEnter(p);
39841  sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
39842  sqlite3BtreeLeave(p);
39843  return SQLITE_OK;
39844}
39845#endif
39846
39847/*
39848** Return TRUE if the given btree is set to safety level 1.  In other
39849** words, return TRUE if no sync() occurs on the disk files.
39850*/
39851SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
39852  BtShared *pBt = p->pBt;
39853  int rc;
39854  assert( sqlite3_mutex_held(p->db->mutex) );
39855  sqlite3BtreeEnter(p);
39856  assert( pBt && pBt->pPager );
39857  rc = sqlite3PagerNosync(pBt->pPager);
39858  sqlite3BtreeLeave(p);
39859  return rc;
39860}
39861
39862#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
39863/*
39864** Change the default pages size and the number of reserved bytes per page.
39865** Or, if the page size has already been fixed, return SQLITE_READONLY
39866** without changing anything.
39867**
39868** The page size must be a power of 2 between 512 and 65536.  If the page
39869** size supplied does not meet this constraint then the page size is not
39870** changed.
39871**
39872** Page sizes are constrained to be a power of two so that the region
39873** of the database file used for locking (beginning at PENDING_BYTE,
39874** the first byte past the 1GB boundary, 0x40000000) needs to occur
39875** at the beginning of a page.
39876**
39877** If parameter nReserve is less than zero, then the number of reserved
39878** bytes per page is left unchanged.
39879**
39880** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
39881** and autovacuum mode can no longer be changed.
39882*/
39883SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
39884  int rc = SQLITE_OK;
39885  BtShared *pBt = p->pBt;
39886  assert( nReserve>=-1 && nReserve<=255 );
39887  sqlite3BtreeEnter(p);
39888  if( pBt->pageSizeFixed ){
39889    sqlite3BtreeLeave(p);
39890    return SQLITE_READONLY;
39891  }
39892  if( nReserve<0 ){
39893    nReserve = pBt->pageSize - pBt->usableSize;
39894  }
39895  assert( nReserve>=0 && nReserve<=255 );
39896  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
39897        ((pageSize-1)&pageSize)==0 ){
39898    assert( (pageSize & 7)==0 );
39899    assert( !pBt->pPage1 && !pBt->pCursor );
39900    pBt->pageSize = (u16)pageSize;
39901    freeTempSpace(pBt);
39902  }
39903  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
39904  pBt->usableSize = pBt->pageSize - (u16)nReserve;
39905  if( iFix ) pBt->pageSizeFixed = 1;
39906  sqlite3BtreeLeave(p);
39907  return rc;
39908}
39909
39910/*
39911** Return the currently defined page size
39912*/
39913SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
39914  return p->pBt->pageSize;
39915}
39916
39917/*
39918** Return the number of bytes of space at the end of every page that
39919** are intentually left unused.  This is the "reserved" space that is
39920** sometimes used by extensions.
39921*/
39922SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
39923  int n;
39924  sqlite3BtreeEnter(p);
39925  n = p->pBt->pageSize - p->pBt->usableSize;
39926  sqlite3BtreeLeave(p);
39927  return n;
39928}
39929
39930/*
39931** Set the maximum page count for a database if mxPage is positive.
39932** No changes are made if mxPage is 0 or negative.
39933** Regardless of the value of mxPage, return the maximum page count.
39934*/
39935SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
39936  int n;
39937  sqlite3BtreeEnter(p);
39938  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
39939  sqlite3BtreeLeave(p);
39940  return n;
39941}
39942#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
39943
39944/*
39945** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
39946** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
39947** is disabled. The default value for the auto-vacuum property is
39948** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
39949*/
39950SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
39951#ifdef SQLITE_OMIT_AUTOVACUUM
39952  return SQLITE_READONLY;
39953#else
39954  BtShared *pBt = p->pBt;
39955  int rc = SQLITE_OK;
39956  u8 av = (u8)autoVacuum;
39957
39958  sqlite3BtreeEnter(p);
39959  if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
39960    rc = SQLITE_READONLY;
39961  }else{
39962    pBt->autoVacuum = av ?1:0;
39963    pBt->incrVacuum = av==2 ?1:0;
39964  }
39965  sqlite3BtreeLeave(p);
39966  return rc;
39967#endif
39968}
39969
39970/*
39971** Return the value of the 'auto-vacuum' property. If auto-vacuum is
39972** enabled 1 is returned. Otherwise 0.
39973*/
39974SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
39975#ifdef SQLITE_OMIT_AUTOVACUUM
39976  return BTREE_AUTOVACUUM_NONE;
39977#else
39978  int rc;
39979  sqlite3BtreeEnter(p);
39980  rc = (
39981    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
39982    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
39983    BTREE_AUTOVACUUM_INCR
39984  );
39985  sqlite3BtreeLeave(p);
39986  return rc;
39987#endif
39988}
39989
39990
39991/*
39992** Get a reference to pPage1 of the database file.  This will
39993** also acquire a readlock on that file.
39994**
39995** SQLITE_OK is returned on success.  If the file is not a
39996** well-formed database file, then SQLITE_CORRUPT is returned.
39997** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
39998** is returned if we run out of memory.
39999*/
40000static int lockBtree(BtShared *pBt){
40001  int rc;
40002  MemPage *pPage1;
40003  int nPage;
40004
40005  assert( sqlite3_mutex_held(pBt->mutex) );
40006  assert( pBt->pPage1==0 );
40007  rc = sqlite3PagerSharedLock(pBt->pPager);
40008  if( rc!=SQLITE_OK ) return rc;
40009  rc = btreeGetPage(pBt, 1, &pPage1, 0);
40010  if( rc!=SQLITE_OK ) return rc;
40011
40012  /* Do some checking to help insure the file we opened really is
40013  ** a valid database file.
40014  */
40015  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
40016  if( rc!=SQLITE_OK ){
40017    goto page1_init_failed;
40018  }else if( nPage>0 ){
40019    int pageSize;
40020    int usableSize;
40021    u8 *page1 = pPage1->aData;
40022    rc = SQLITE_NOTADB;
40023    if( memcmp(page1, zMagicHeader, 16)!=0 ){
40024      goto page1_init_failed;
40025    }
40026    if( page1[18]>1 ){
40027      pBt->readOnly = 1;
40028    }
40029    if( page1[19]>1 ){
40030      goto page1_init_failed;
40031    }
40032
40033    /* The maximum embedded fraction must be exactly 25%.  And the minimum
40034    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
40035    ** The original design allowed these amounts to vary, but as of
40036    ** version 3.6.0, we require them to be fixed.
40037    */
40038    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
40039      goto page1_init_failed;
40040    }
40041    pageSize = get2byte(&page1[16]);
40042    if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
40043        (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
40044    ){
40045      goto page1_init_failed;
40046    }
40047    assert( (pageSize & 7)==0 );
40048    usableSize = pageSize - page1[20];
40049    if( pageSize!=pBt->pageSize ){
40050      /* After reading the first page of the database assuming a page size
40051      ** of BtShared.pageSize, we have discovered that the page-size is
40052      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
40053      ** zero and return SQLITE_OK. The caller will call this function
40054      ** again with the correct page-size.
40055      */
40056      releasePage(pPage1);
40057      pBt->usableSize = (u16)usableSize;
40058      pBt->pageSize = (u16)pageSize;
40059      freeTempSpace(pBt);
40060      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
40061                                   pageSize-usableSize);
40062      return rc;
40063    }
40064    if( usableSize<480 ){
40065      goto page1_init_failed;
40066    }
40067    pBt->pageSize = (u16)pageSize;
40068    pBt->usableSize = (u16)usableSize;
40069#ifndef SQLITE_OMIT_AUTOVACUUM
40070    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
40071    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
40072#endif
40073  }
40074
40075  /* maxLocal is the maximum amount of payload to store locally for
40076  ** a cell.  Make sure it is small enough so that at least minFanout
40077  ** cells can will fit on one page.  We assume a 10-byte page header.
40078  ** Besides the payload, the cell must store:
40079  **     2-byte pointer to the cell
40080  **     4-byte child pointer
40081  **     9-byte nKey value
40082  **     4-byte nData value
40083  **     4-byte overflow page pointer
40084  ** So a cell consists of a 2-byte poiner, a header which is as much as
40085  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
40086  ** page pointer.
40087  */
40088  pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
40089  pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
40090  pBt->maxLeaf = pBt->usableSize - 35;
40091  pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
40092  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
40093  pBt->pPage1 = pPage1;
40094  return SQLITE_OK;
40095
40096page1_init_failed:
40097  releasePage(pPage1);
40098  pBt->pPage1 = 0;
40099  return rc;
40100}
40101
40102/*
40103** If there are no outstanding cursors and we are not in the middle
40104** of a transaction but there is a read lock on the database, then
40105** this routine unrefs the first page of the database file which
40106** has the effect of releasing the read lock.
40107**
40108** If there is a transaction in progress, this routine is a no-op.
40109*/
40110static void unlockBtreeIfUnused(BtShared *pBt){
40111  assert( sqlite3_mutex_held(pBt->mutex) );
40112  assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
40113  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
40114    assert( pBt->pPage1->aData );
40115    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
40116    assert( pBt->pPage1->aData );
40117    releasePage(pBt->pPage1);
40118    pBt->pPage1 = 0;
40119  }
40120}
40121
40122/*
40123** If pBt points to an empty file then convert that empty file
40124** into a new empty database by initializing the first page of
40125** the database.
40126*/
40127static int newDatabase(BtShared *pBt){
40128  MemPage *pP1;
40129  unsigned char *data;
40130  int rc;
40131  int nPage;
40132
40133  assert( sqlite3_mutex_held(pBt->mutex) );
40134  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
40135  if( rc!=SQLITE_OK || nPage>0 ){
40136    return rc;
40137  }
40138  pP1 = pBt->pPage1;
40139  assert( pP1!=0 );
40140  data = pP1->aData;
40141  rc = sqlite3PagerWrite(pP1->pDbPage);
40142  if( rc ) return rc;
40143  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
40144  assert( sizeof(zMagicHeader)==16 );
40145  put2byte(&data[16], pBt->pageSize);
40146  data[18] = 1;
40147  data[19] = 1;
40148  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
40149  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
40150  data[21] = 64;
40151  data[22] = 32;
40152  data[23] = 32;
40153  memset(&data[24], 0, 100-24);
40154  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
40155  pBt->pageSizeFixed = 1;
40156#ifndef SQLITE_OMIT_AUTOVACUUM
40157  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
40158  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
40159  put4byte(&data[36 + 4*4], pBt->autoVacuum);
40160  put4byte(&data[36 + 7*4], pBt->incrVacuum);
40161#endif
40162  return SQLITE_OK;
40163}
40164
40165/*
40166** Attempt to start a new transaction. A write-transaction
40167** is started if the second argument is nonzero, otherwise a read-
40168** transaction.  If the second argument is 2 or more and exclusive
40169** transaction is started, meaning that no other process is allowed
40170** to access the database.  A preexisting transaction may not be
40171** upgraded to exclusive by calling this routine a second time - the
40172** exclusivity flag only works for a new transaction.
40173**
40174** A write-transaction must be started before attempting any
40175** changes to the database.  None of the following routines
40176** will work unless a transaction is started first:
40177**
40178**      sqlite3BtreeCreateTable()
40179**      sqlite3BtreeCreateIndex()
40180**      sqlite3BtreeClearTable()
40181**      sqlite3BtreeDropTable()
40182**      sqlite3BtreeInsert()
40183**      sqlite3BtreeDelete()
40184**      sqlite3BtreeUpdateMeta()
40185**
40186** If an initial attempt to acquire the lock fails because of lock contention
40187** and the database was previously unlocked, then invoke the busy handler
40188** if there is one.  But if there was previously a read-lock, do not
40189** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
40190** returned when there is already a read-lock in order to avoid a deadlock.
40191**
40192** Suppose there are two processes A and B.  A has a read lock and B has
40193** a reserved lock.  B tries to promote to exclusive but is blocked because
40194** of A's read lock.  A tries to promote to reserved but is blocked by B.
40195** One or the other of the two processes must give way or there can be
40196** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
40197** when A already has a read lock, we encourage A to give up and let B
40198** proceed.
40199*/
40200SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
40201  sqlite3 *pBlock = 0;
40202  BtShared *pBt = p->pBt;
40203  int rc = SQLITE_OK;
40204
40205  sqlite3BtreeEnter(p);
40206  btreeIntegrity(p);
40207
40208  /* If the btree is already in a write-transaction, or it
40209  ** is already in a read-transaction and a read-transaction
40210  ** is requested, this is a no-op.
40211  */
40212  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
40213    goto trans_begun;
40214  }
40215
40216  /* Write transactions are not possible on a read-only database */
40217  if( pBt->readOnly && wrflag ){
40218    rc = SQLITE_READONLY;
40219    goto trans_begun;
40220  }
40221
40222#ifndef SQLITE_OMIT_SHARED_CACHE
40223  /* If another database handle has already opened a write transaction
40224  ** on this shared-btree structure and a second write transaction is
40225  ** requested, return SQLITE_LOCKED.
40226  */
40227  if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
40228    pBlock = pBt->pWriter->db;
40229  }else if( wrflag>1 ){
40230    BtLock *pIter;
40231    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
40232      if( pIter->pBtree!=p ){
40233        pBlock = pIter->pBtree->db;
40234        break;
40235      }
40236    }
40237  }
40238  if( pBlock ){
40239    sqlite3ConnectionBlocked(p->db, pBlock);
40240    rc = SQLITE_LOCKED_SHAREDCACHE;
40241    goto trans_begun;
40242  }
40243#endif
40244
40245  /* Any read-only or read-write transaction implies a read-lock on
40246  ** page 1. So if some other shared-cache client already has a write-lock
40247  ** on page 1, the transaction cannot be opened. */
40248  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
40249  if( SQLITE_OK!=rc ) goto trans_begun;
40250
40251  do {
40252    /* Call lockBtree() until either pBt->pPage1 is populated or
40253    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
40254    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
40255    ** reading page 1 it discovers that the page-size of the database
40256    ** file is not pBt->pageSize. In this case lockBtree() will update
40257    ** pBt->pageSize to the page-size of the file on disk.
40258    */
40259    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
40260
40261    if( rc==SQLITE_OK && wrflag ){
40262      if( pBt->readOnly ){
40263        rc = SQLITE_READONLY;
40264      }else{
40265        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
40266        if( rc==SQLITE_OK ){
40267          rc = newDatabase(pBt);
40268        }
40269      }
40270    }
40271
40272    if( rc!=SQLITE_OK ){
40273      unlockBtreeIfUnused(pBt);
40274    }
40275  }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
40276          btreeInvokeBusyHandler(pBt) );
40277
40278  if( rc==SQLITE_OK ){
40279    if( p->inTrans==TRANS_NONE ){
40280      pBt->nTransaction++;
40281#ifndef SQLITE_OMIT_SHARED_CACHE
40282      if( p->sharable ){
40283	assert( p->lock.pBtree==p && p->lock.iTable==1 );
40284        p->lock.eLock = READ_LOCK;
40285        p->lock.pNext = pBt->pLock;
40286        pBt->pLock = &p->lock;
40287      }
40288#endif
40289    }
40290    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
40291    if( p->inTrans>pBt->inTransaction ){
40292      pBt->inTransaction = p->inTrans;
40293    }
40294#ifndef SQLITE_OMIT_SHARED_CACHE
40295    if( wrflag ){
40296      assert( !pBt->pWriter );
40297      pBt->pWriter = p;
40298      pBt->isExclusive = (u8)(wrflag>1);
40299    }
40300#endif
40301  }
40302
40303
40304trans_begun:
40305  if( rc==SQLITE_OK && wrflag ){
40306    /* This call makes sure that the pager has the correct number of
40307    ** open savepoints. If the second parameter is greater than 0 and
40308    ** the sub-journal is not already open, then it will be opened here.
40309    */
40310    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
40311  }
40312
40313  btreeIntegrity(p);
40314  sqlite3BtreeLeave(p);
40315  return rc;
40316}
40317
40318#ifndef SQLITE_OMIT_AUTOVACUUM
40319
40320/*
40321** Set the pointer-map entries for all children of page pPage. Also, if
40322** pPage contains cells that point to overflow pages, set the pointer
40323** map entries for the overflow pages as well.
40324*/
40325static int setChildPtrmaps(MemPage *pPage){
40326  int i;                             /* Counter variable */
40327  int nCell;                         /* Number of cells in page pPage */
40328  int rc;                            /* Return code */
40329  BtShared *pBt = pPage->pBt;
40330  u8 isInitOrig = pPage->isInit;
40331  Pgno pgno = pPage->pgno;
40332
40333  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
40334  rc = btreeInitPage(pPage);
40335  if( rc!=SQLITE_OK ){
40336    goto set_child_ptrmaps_out;
40337  }
40338  nCell = pPage->nCell;
40339
40340  for(i=0; i<nCell; i++){
40341    u8 *pCell = findCell(pPage, i);
40342
40343    ptrmapPutOvflPtr(pPage, pCell, &rc);
40344
40345    if( !pPage->leaf ){
40346      Pgno childPgno = get4byte(pCell);
40347      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
40348    }
40349  }
40350
40351  if( !pPage->leaf ){
40352    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
40353    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
40354  }
40355
40356set_child_ptrmaps_out:
40357  pPage->isInit = isInitOrig;
40358  return rc;
40359}
40360
40361/*
40362** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
40363** that it points to iTo. Parameter eType describes the type of pointer to
40364** be modified, as  follows:
40365**
40366** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
40367**                   page of pPage.
40368**
40369** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
40370**                   page pointed to by one of the cells on pPage.
40371**
40372** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
40373**                   overflow page in the list.
40374*/
40375static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
40376  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
40377  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
40378  if( eType==PTRMAP_OVERFLOW2 ){
40379    /* The pointer is always the first 4 bytes of the page in this case.  */
40380    if( get4byte(pPage->aData)!=iFrom ){
40381      return SQLITE_CORRUPT_BKPT;
40382    }
40383    put4byte(pPage->aData, iTo);
40384  }else{
40385    u8 isInitOrig = pPage->isInit;
40386    int i;
40387    int nCell;
40388
40389    btreeInitPage(pPage);
40390    nCell = pPage->nCell;
40391
40392    for(i=0; i<nCell; i++){
40393      u8 *pCell = findCell(pPage, i);
40394      if( eType==PTRMAP_OVERFLOW1 ){
40395        CellInfo info;
40396        btreeParseCellPtr(pPage, pCell, &info);
40397        if( info.iOverflow ){
40398          if( iFrom==get4byte(&pCell[info.iOverflow]) ){
40399            put4byte(&pCell[info.iOverflow], iTo);
40400            break;
40401          }
40402        }
40403      }else{
40404        if( get4byte(pCell)==iFrom ){
40405          put4byte(pCell, iTo);
40406          break;
40407        }
40408      }
40409    }
40410
40411    if( i==nCell ){
40412      if( eType!=PTRMAP_BTREE ||
40413          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
40414        return SQLITE_CORRUPT_BKPT;
40415      }
40416      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
40417    }
40418
40419    pPage->isInit = isInitOrig;
40420  }
40421  return SQLITE_OK;
40422}
40423
40424
40425/*
40426** Move the open database page pDbPage to location iFreePage in the
40427** database. The pDbPage reference remains valid.
40428**
40429** The isCommit flag indicates that there is no need to remember that
40430** the journal needs to be sync()ed before database page pDbPage->pgno
40431** can be written to. The caller has already promised not to write to that
40432** page.
40433*/
40434static int relocatePage(
40435  BtShared *pBt,           /* Btree */
40436  MemPage *pDbPage,        /* Open page to move */
40437  u8 eType,                /* Pointer map 'type' entry for pDbPage */
40438  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
40439  Pgno iFreePage,          /* The location to move pDbPage to */
40440  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
40441){
40442  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
40443  Pgno iDbPage = pDbPage->pgno;
40444  Pager *pPager = pBt->pPager;
40445  int rc;
40446
40447  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
40448      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
40449  assert( sqlite3_mutex_held(pBt->mutex) );
40450  assert( pDbPage->pBt==pBt );
40451
40452  /* Move page iDbPage from its current location to page number iFreePage */
40453  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
40454      iDbPage, iFreePage, iPtrPage, eType));
40455  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
40456  if( rc!=SQLITE_OK ){
40457    return rc;
40458  }
40459  pDbPage->pgno = iFreePage;
40460
40461  /* If pDbPage was a btree-page, then it may have child pages and/or cells
40462  ** that point to overflow pages. The pointer map entries for all these
40463  ** pages need to be changed.
40464  **
40465  ** If pDbPage is an overflow page, then the first 4 bytes may store a
40466  ** pointer to a subsequent overflow page. If this is the case, then
40467  ** the pointer map needs to be updated for the subsequent overflow page.
40468  */
40469  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
40470    rc = setChildPtrmaps(pDbPage);
40471    if( rc!=SQLITE_OK ){
40472      return rc;
40473    }
40474  }else{
40475    Pgno nextOvfl = get4byte(pDbPage->aData);
40476    if( nextOvfl!=0 ){
40477      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
40478      if( rc!=SQLITE_OK ){
40479        return rc;
40480      }
40481    }
40482  }
40483
40484  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
40485  ** that it points at iFreePage. Also fix the pointer map entry for
40486  ** iPtrPage.
40487  */
40488  if( eType!=PTRMAP_ROOTPAGE ){
40489    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
40490    if( rc!=SQLITE_OK ){
40491      return rc;
40492    }
40493    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
40494    if( rc!=SQLITE_OK ){
40495      releasePage(pPtrPage);
40496      return rc;
40497    }
40498    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
40499    releasePage(pPtrPage);
40500    if( rc==SQLITE_OK ){
40501      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
40502    }
40503  }
40504  return rc;
40505}
40506
40507/* Forward declaration required by incrVacuumStep(). */
40508static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
40509
40510/*
40511** Perform a single step of an incremental-vacuum. If successful,
40512** return SQLITE_OK. If there is no work to do (and therefore no
40513** point in calling this function again), return SQLITE_DONE.
40514**
40515** More specificly, this function attempts to re-organize the
40516** database so that the last page of the file currently in use
40517** is no longer in use.
40518**
40519** If the nFin parameter is non-zero, this function assumes
40520** that the caller will keep calling incrVacuumStep() until
40521** it returns SQLITE_DONE or an error, and that nFin is the
40522** number of pages the database file will contain after this
40523** process is complete.  If nFin is zero, it is assumed that
40524** incrVacuumStep() will be called a finite amount of times
40525** which may or may not empty the freelist.  A full autovacuum
40526** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
40527*/
40528static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
40529  Pgno nFreeList;           /* Number of pages still on the free-list */
40530
40531  assert( sqlite3_mutex_held(pBt->mutex) );
40532  assert( iLastPg>nFin );
40533
40534  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
40535    int rc;
40536    u8 eType;
40537    Pgno iPtrPage;
40538
40539    nFreeList = get4byte(&pBt->pPage1->aData[36]);
40540    if( nFreeList==0 ){
40541      return SQLITE_DONE;
40542    }
40543
40544    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
40545    if( rc!=SQLITE_OK ){
40546      return rc;
40547    }
40548    if( eType==PTRMAP_ROOTPAGE ){
40549      return SQLITE_CORRUPT_BKPT;
40550    }
40551
40552    if( eType==PTRMAP_FREEPAGE ){
40553      if( nFin==0 ){
40554        /* Remove the page from the files free-list. This is not required
40555        ** if nFin is non-zero. In that case, the free-list will be
40556        ** truncated to zero after this function returns, so it doesn't
40557        ** matter if it still contains some garbage entries.
40558        */
40559        Pgno iFreePg;
40560        MemPage *pFreePg;
40561        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
40562        if( rc!=SQLITE_OK ){
40563          return rc;
40564        }
40565        assert( iFreePg==iLastPg );
40566        releasePage(pFreePg);
40567      }
40568    } else {
40569      Pgno iFreePg;             /* Index of free page to move pLastPg to */
40570      MemPage *pLastPg;
40571
40572      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
40573      if( rc!=SQLITE_OK ){
40574        return rc;
40575      }
40576
40577      /* If nFin is zero, this loop runs exactly once and page pLastPg
40578      ** is swapped with the first free page pulled off the free list.
40579      **
40580      ** On the other hand, if nFin is greater than zero, then keep
40581      ** looping until a free-page located within the first nFin pages
40582      ** of the file is found.
40583      */
40584      do {
40585        MemPage *pFreePg;
40586        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
40587        if( rc!=SQLITE_OK ){
40588          releasePage(pLastPg);
40589          return rc;
40590        }
40591        releasePage(pFreePg);
40592      }while( nFin!=0 && iFreePg>nFin );
40593      assert( iFreePg<iLastPg );
40594
40595      rc = sqlite3PagerWrite(pLastPg->pDbPage);
40596      if( rc==SQLITE_OK ){
40597        rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
40598      }
40599      releasePage(pLastPg);
40600      if( rc!=SQLITE_OK ){
40601        return rc;
40602      }
40603    }
40604  }
40605
40606  if( nFin==0 ){
40607    iLastPg--;
40608    while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
40609      if( PTRMAP_ISPAGE(pBt, iLastPg) ){
40610        MemPage *pPg;
40611        int rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
40612        if( rc!=SQLITE_OK ){
40613          return rc;
40614        }
40615        rc = sqlite3PagerWrite(pPg->pDbPage);
40616        releasePage(pPg);
40617        if( rc!=SQLITE_OK ){
40618          return rc;
40619        }
40620      }
40621      iLastPg--;
40622    }
40623    sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
40624  }
40625  return SQLITE_OK;
40626}
40627
40628/*
40629** A write-transaction must be opened before calling this function.
40630** It performs a single unit of work towards an incremental vacuum.
40631**
40632** If the incremental vacuum is finished after this function has run,
40633** SQLITE_DONE is returned. If it is not finished, but no error occurred,
40634** SQLITE_OK is returned. Otherwise an SQLite error code.
40635*/
40636SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
40637  int rc;
40638  BtShared *pBt = p->pBt;
40639
40640  sqlite3BtreeEnter(p);
40641  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
40642  if( !pBt->autoVacuum ){
40643    rc = SQLITE_DONE;
40644  }else{
40645    invalidateAllOverflowCache(pBt);
40646    rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
40647  }
40648  sqlite3BtreeLeave(p);
40649  return rc;
40650}
40651
40652/*
40653** This routine is called prior to sqlite3PagerCommit when a transaction
40654** is commited for an auto-vacuum database.
40655**
40656** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
40657** the database file should be truncated to during the commit process.
40658** i.e. the database has been reorganized so that only the first *pnTrunc
40659** pages are in use.
40660*/
40661static int autoVacuumCommit(BtShared *pBt){
40662  int rc = SQLITE_OK;
40663  Pager *pPager = pBt->pPager;
40664  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
40665
40666  assert( sqlite3_mutex_held(pBt->mutex) );
40667  invalidateAllOverflowCache(pBt);
40668  assert(pBt->autoVacuum);
40669  if( !pBt->incrVacuum ){
40670    Pgno nFin;         /* Number of pages in database after autovacuuming */
40671    Pgno nFree;        /* Number of pages on the freelist initially */
40672    Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
40673    Pgno iFree;        /* The next page to be freed */
40674    int nEntry;        /* Number of entries on one ptrmap page */
40675    Pgno nOrig;        /* Database size before freeing */
40676
40677    nOrig = pagerPagecount(pBt);
40678    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
40679      /* It is not possible to create a database for which the final page
40680      ** is either a pointer-map page or the pending-byte page. If one
40681      ** is encountered, this indicates corruption.
40682      */
40683      return SQLITE_CORRUPT_BKPT;
40684    }
40685
40686    nFree = get4byte(&pBt->pPage1->aData[36]);
40687    nEntry = pBt->usableSize/5;
40688    nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
40689    nFin = nOrig - nFree - nPtrmap;
40690    if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
40691      nFin--;
40692    }
40693    while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
40694      nFin--;
40695    }
40696    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
40697
40698    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
40699      rc = incrVacuumStep(pBt, nFin, iFree);
40700    }
40701    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
40702      rc = SQLITE_OK;
40703      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
40704      put4byte(&pBt->pPage1->aData[32], 0);
40705      put4byte(&pBt->pPage1->aData[36], 0);
40706      sqlite3PagerTruncateImage(pBt->pPager, nFin);
40707    }
40708    if( rc!=SQLITE_OK ){
40709      sqlite3PagerRollback(pPager);
40710    }
40711  }
40712
40713  assert( nRef==sqlite3PagerRefcount(pPager) );
40714  return rc;
40715}
40716
40717#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
40718# define setChildPtrmaps(x) SQLITE_OK
40719#endif
40720
40721/*
40722** This routine does the first phase of a two-phase commit.  This routine
40723** causes a rollback journal to be created (if it does not already exist)
40724** and populated with enough information so that if a power loss occurs
40725** the database can be restored to its original state by playing back
40726** the journal.  Then the contents of the journal are flushed out to
40727** the disk.  After the journal is safely on oxide, the changes to the
40728** database are written into the database file and flushed to oxide.
40729** At the end of this call, the rollback journal still exists on the
40730** disk and we are still holding all locks, so the transaction has not
40731** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
40732** commit process.
40733**
40734** This call is a no-op if no write-transaction is currently active on pBt.
40735**
40736** Otherwise, sync the database file for the btree pBt. zMaster points to
40737** the name of a master journal file that should be written into the
40738** individual journal file, or is NULL, indicating no master journal file
40739** (single database transaction).
40740**
40741** When this is called, the master journal should already have been
40742** created, populated with this journal pointer and synced to disk.
40743**
40744** Once this is routine has returned, the only thing required to commit
40745** the write-transaction for this database file is to delete the journal.
40746*/
40747SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
40748  int rc = SQLITE_OK;
40749  if( p->inTrans==TRANS_WRITE ){
40750    BtShared *pBt = p->pBt;
40751    sqlite3BtreeEnter(p);
40752#ifndef SQLITE_OMIT_AUTOVACUUM
40753    if( pBt->autoVacuum ){
40754      rc = autoVacuumCommit(pBt);
40755      if( rc!=SQLITE_OK ){
40756        sqlite3BtreeLeave(p);
40757        return rc;
40758      }
40759    }
40760#endif
40761    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
40762    sqlite3BtreeLeave(p);
40763  }
40764  return rc;
40765}
40766
40767/*
40768** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
40769** at the conclusion of a transaction.
40770*/
40771static void btreeEndTransaction(Btree *p){
40772  BtShared *pBt = p->pBt;
40773  assert( sqlite3BtreeHoldsMutex(p) );
40774
40775  btreeClearHasContent(pBt);
40776  if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
40777    /* If there are other active statements that belong to this database
40778    ** handle, downgrade to a read-only transaction. The other statements
40779    ** may still be reading from the database.  */
40780    downgradeAllSharedCacheTableLocks(p);
40781    p->inTrans = TRANS_READ;
40782  }else{
40783    /* If the handle had any kind of transaction open, decrement the
40784    ** transaction count of the shared btree. If the transaction count
40785    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
40786    ** call below will unlock the pager.  */
40787    if( p->inTrans!=TRANS_NONE ){
40788      clearAllSharedCacheTableLocks(p);
40789      pBt->nTransaction--;
40790      if( 0==pBt->nTransaction ){
40791        pBt->inTransaction = TRANS_NONE;
40792      }
40793    }
40794
40795    /* Set the current transaction state to TRANS_NONE and unlock the
40796    ** pager if this call closed the only read or write transaction.  */
40797    p->inTrans = TRANS_NONE;
40798    unlockBtreeIfUnused(pBt);
40799  }
40800
40801  btreeIntegrity(p);
40802}
40803
40804/*
40805** Commit the transaction currently in progress.
40806**
40807** This routine implements the second phase of a 2-phase commit.  The
40808** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
40809** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
40810** routine did all the work of writing information out to disk and flushing the
40811** contents so that they are written onto the disk platter.  All this
40812** routine has to do is delete or truncate or zero the header in the
40813** the rollback journal (which causes the transaction to commit) and
40814** drop locks.
40815**
40816** This will release the write lock on the database file.  If there
40817** are no active cursors, it also releases the read lock.
40818*/
40819SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
40820  BtShared *pBt = p->pBt;
40821
40822  sqlite3BtreeEnter(p);
40823  btreeIntegrity(p);
40824
40825  /* If the handle has a write-transaction open, commit the shared-btrees
40826  ** transaction and set the shared state to TRANS_READ.
40827  */
40828  if( p->inTrans==TRANS_WRITE ){
40829    int rc;
40830    assert( pBt->inTransaction==TRANS_WRITE );
40831    assert( pBt->nTransaction>0 );
40832    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
40833    if( rc!=SQLITE_OK ){
40834      sqlite3BtreeLeave(p);
40835      return rc;
40836    }
40837    pBt->inTransaction = TRANS_READ;
40838  }
40839
40840  btreeEndTransaction(p);
40841  sqlite3BtreeLeave(p);
40842  return SQLITE_OK;
40843}
40844
40845/*
40846** Do both phases of a commit.
40847*/
40848SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
40849  int rc;
40850  sqlite3BtreeEnter(p);
40851  rc = sqlite3BtreeCommitPhaseOne(p, 0);
40852  if( rc==SQLITE_OK ){
40853    rc = sqlite3BtreeCommitPhaseTwo(p);
40854  }
40855  sqlite3BtreeLeave(p);
40856  return rc;
40857}
40858
40859#ifndef NDEBUG
40860/*
40861** Return the number of write-cursors open on this handle. This is for use
40862** in assert() expressions, so it is only compiled if NDEBUG is not
40863** defined.
40864**
40865** For the purposes of this routine, a write-cursor is any cursor that
40866** is capable of writing to the databse.  That means the cursor was
40867** originally opened for writing and the cursor has not be disabled
40868** by having its state changed to CURSOR_FAULT.
40869*/
40870static int countWriteCursors(BtShared *pBt){
40871  BtCursor *pCur;
40872  int r = 0;
40873  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
40874    if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
40875  }
40876  return r;
40877}
40878#endif
40879
40880/*
40881** This routine sets the state to CURSOR_FAULT and the error
40882** code to errCode for every cursor on BtShared that pBtree
40883** references.
40884**
40885** Every cursor is tripped, including cursors that belong
40886** to other database connections that happen to be sharing
40887** the cache with pBtree.
40888**
40889** This routine gets called when a rollback occurs.
40890** All cursors using the same cache must be tripped
40891** to prevent them from trying to use the btree after
40892** the rollback.  The rollback may have deleted tables
40893** or moved root pages, so it is not sufficient to
40894** save the state of the cursor.  The cursor must be
40895** invalidated.
40896*/
40897SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
40898  BtCursor *p;
40899  sqlite3BtreeEnter(pBtree);
40900  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
40901    int i;
40902    sqlite3BtreeClearCursor(p);
40903    p->eState = CURSOR_FAULT;
40904    p->skipNext = errCode;
40905    for(i=0; i<=p->iPage; i++){
40906      releasePage(p->apPage[i]);
40907      p->apPage[i] = 0;
40908    }
40909  }
40910  sqlite3BtreeLeave(pBtree);
40911}
40912
40913/*
40914** Rollback the transaction in progress.  All cursors will be
40915** invalided by this operation.  Any attempt to use a cursor
40916** that was open at the beginning of this operation will result
40917** in an error.
40918**
40919** This will release the write lock on the database file.  If there
40920** are no active cursors, it also releases the read lock.
40921*/
40922SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
40923  int rc;
40924  BtShared *pBt = p->pBt;
40925  MemPage *pPage1;
40926
40927  sqlite3BtreeEnter(p);
40928  rc = saveAllCursors(pBt, 0, 0);
40929#ifndef SQLITE_OMIT_SHARED_CACHE
40930  if( rc!=SQLITE_OK ){
40931    /* This is a horrible situation. An IO or malloc() error occurred whilst
40932    ** trying to save cursor positions. If this is an automatic rollback (as
40933    ** the result of a constraint, malloc() failure or IO error) then
40934    ** the cache may be internally inconsistent (not contain valid trees) so
40935    ** we cannot simply return the error to the caller. Instead, abort
40936    ** all queries that may be using any of the cursors that failed to save.
40937    */
40938    sqlite3BtreeTripAllCursors(p, rc);
40939  }
40940#endif
40941  btreeIntegrity(p);
40942
40943  if( p->inTrans==TRANS_WRITE ){
40944    int rc2;
40945
40946    assert( TRANS_WRITE==pBt->inTransaction );
40947    rc2 = sqlite3PagerRollback(pBt->pPager);
40948    if( rc2!=SQLITE_OK ){
40949      rc = rc2;
40950    }
40951
40952    /* The rollback may have destroyed the pPage1->aData value.  So
40953    ** call btreeGetPage() on page 1 again to make
40954    ** sure pPage1->aData is set correctly. */
40955    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
40956      releasePage(pPage1);
40957    }
40958    assert( countWriteCursors(pBt)==0 );
40959    pBt->inTransaction = TRANS_READ;
40960  }
40961
40962  btreeEndTransaction(p);
40963  sqlite3BtreeLeave(p);
40964  return rc;
40965}
40966
40967/*
40968** Start a statement subtransaction. The subtransaction can can be rolled
40969** back independently of the main transaction. You must start a transaction
40970** before starting a subtransaction. The subtransaction is ended automatically
40971** if the main transaction commits or rolls back.
40972**
40973** Statement subtransactions are used around individual SQL statements
40974** that are contained within a BEGIN...COMMIT block.  If a constraint
40975** error occurs within the statement, the effect of that one statement
40976** can be rolled back without having to rollback the entire transaction.
40977**
40978** A statement sub-transaction is implemented as an anonymous savepoint. The
40979** value passed as the second parameter is the total number of savepoints,
40980** including the new anonymous savepoint, open on the B-Tree. i.e. if there
40981** are no active savepoints and no other statement-transactions open,
40982** iStatement is 1. This anonymous savepoint can be released or rolled back
40983** using the sqlite3BtreeSavepoint() function.
40984*/
40985SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
40986  int rc;
40987  BtShared *pBt = p->pBt;
40988  sqlite3BtreeEnter(p);
40989  assert( p->inTrans==TRANS_WRITE );
40990  assert( pBt->readOnly==0 );
40991  assert( iStatement>0 );
40992  assert( iStatement>p->db->nSavepoint );
40993  if( NEVER(p->inTrans!=TRANS_WRITE || pBt->readOnly) ){
40994    rc = SQLITE_INTERNAL;
40995  }else{
40996    assert( pBt->inTransaction==TRANS_WRITE );
40997    /* At the pager level, a statement transaction is a savepoint with
40998    ** an index greater than all savepoints created explicitly using
40999    ** SQL statements. It is illegal to open, release or rollback any
41000    ** such savepoints while the statement transaction savepoint is active.
41001    */
41002    rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
41003  }
41004  sqlite3BtreeLeave(p);
41005  return rc;
41006}
41007
41008/*
41009** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
41010** or SAVEPOINT_RELEASE. This function either releases or rolls back the
41011** savepoint identified by parameter iSavepoint, depending on the value
41012** of op.
41013**
41014** Normally, iSavepoint is greater than or equal to zero. However, if op is
41015** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
41016** contents of the entire transaction are rolled back. This is different
41017** from a normal transaction rollback, as no locks are released and the
41018** transaction remains open.
41019*/
41020SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
41021  int rc = SQLITE_OK;
41022  if( p && p->inTrans==TRANS_WRITE ){
41023    BtShared *pBt = p->pBt;
41024    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
41025    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
41026    sqlite3BtreeEnter(p);
41027    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
41028    if( rc==SQLITE_OK ){
41029      rc = newDatabase(pBt);
41030    }
41031    sqlite3BtreeLeave(p);
41032  }
41033  return rc;
41034}
41035
41036/*
41037** Create a new cursor for the BTree whose root is on the page
41038** iTable. If a read-only cursor is requested, it is assumed that
41039** the caller already has at least a read-only transaction open
41040** on the database already. If a write-cursor is requested, then
41041** the caller is assumed to have an open write transaction.
41042**
41043** If wrFlag==0, then the cursor can only be used for reading.
41044** If wrFlag==1, then the cursor can be used for reading or for
41045** writing if other conditions for writing are also met.  These
41046** are the conditions that must be met in order for writing to
41047** be allowed:
41048**
41049** 1:  The cursor must have been opened with wrFlag==1
41050**
41051** 2:  Other database connections that share the same pager cache
41052**     but which are not in the READ_UNCOMMITTED state may not have
41053**     cursors open with wrFlag==0 on the same table.  Otherwise
41054**     the changes made by this write cursor would be visible to
41055**     the read cursors in the other database connection.
41056**
41057** 3:  The database must be writable (not on read-only media)
41058**
41059** 4:  There must be an active transaction.
41060**
41061** No checking is done to make sure that page iTable really is the
41062** root page of a b-tree.  If it is not, then the cursor acquired
41063** will not work correctly.
41064**
41065** It is assumed that the sqlite3BtreeCursorZero() has been called
41066** on pCur to initialize the memory space prior to invoking this routine.
41067*/
41068static int btreeCursor(
41069  Btree *p,                              /* The btree */
41070  int iTable,                            /* Root page of table to open */
41071  int wrFlag,                            /* 1 to write. 0 read-only */
41072  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
41073  BtCursor *pCur                         /* Space for new cursor */
41074){
41075  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
41076
41077  assert( sqlite3BtreeHoldsMutex(p) );
41078  assert( wrFlag==0 || wrFlag==1 );
41079
41080  /* The following assert statements verify that if this is a sharable
41081  ** b-tree database, the connection is holding the required table locks,
41082  ** and that no other connection has any open cursor that conflicts with
41083  ** this lock.  */
41084  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
41085  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
41086
41087  /* Assert that the caller has opened the required transaction. */
41088  assert( p->inTrans>TRANS_NONE );
41089  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
41090  assert( pBt->pPage1 && pBt->pPage1->aData );
41091
41092  if( NEVER(wrFlag && pBt->readOnly) ){
41093    return SQLITE_READONLY;
41094  }
41095  if( iTable==1 && pagerPagecount(pBt)==0 ){
41096    return SQLITE_EMPTY;
41097  }
41098
41099  /* Now that no other errors can occur, finish filling in the BtCursor
41100  ** variables and link the cursor into the BtShared list.  */
41101  pCur->pgnoRoot = (Pgno)iTable;
41102  pCur->iPage = -1;
41103  pCur->pKeyInfo = pKeyInfo;
41104  pCur->pBtree = p;
41105  pCur->pBt = pBt;
41106  pCur->wrFlag = (u8)wrFlag;
41107  pCur->pNext = pBt->pCursor;
41108  if( pCur->pNext ){
41109    pCur->pNext->pPrev = pCur;
41110  }
41111  pBt->pCursor = pCur;
41112  pCur->eState = CURSOR_INVALID;
41113  pCur->cachedRowid = 0;
41114  return SQLITE_OK;
41115}
41116SQLITE_PRIVATE int sqlite3BtreeCursor(
41117  Btree *p,                                   /* The btree */
41118  int iTable,                                 /* Root page of table to open */
41119  int wrFlag,                                 /* 1 to write. 0 read-only */
41120  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
41121  BtCursor *pCur                              /* Write new cursor here */
41122){
41123  int rc;
41124  sqlite3BtreeEnter(p);
41125  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
41126  sqlite3BtreeLeave(p);
41127  return rc;
41128}
41129
41130/*
41131** Return the size of a BtCursor object in bytes.
41132**
41133** This interfaces is needed so that users of cursors can preallocate
41134** sufficient storage to hold a cursor.  The BtCursor object is opaque
41135** to users so they cannot do the sizeof() themselves - they must call
41136** this routine.
41137*/
41138SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
41139  return ROUND8(sizeof(BtCursor));
41140}
41141
41142/*
41143** Initialize memory that will be converted into a BtCursor object.
41144**
41145** The simple approach here would be to memset() the entire object
41146** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
41147** do not need to be zeroed and they are large, so we can save a lot
41148** of run-time by skipping the initialization of those elements.
41149*/
41150SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
41151  memset(p, 0, offsetof(BtCursor, iPage));
41152}
41153
41154/*
41155** Set the cached rowid value of every cursor in the same database file
41156** as pCur and having the same root page number as pCur.  The value is
41157** set to iRowid.
41158**
41159** Only positive rowid values are considered valid for this cache.
41160** The cache is initialized to zero, indicating an invalid cache.
41161** A btree will work fine with zero or negative rowids.  We just cannot
41162** cache zero or negative rowids, which means tables that use zero or
41163** negative rowids might run a little slower.  But in practice, zero
41164** or negative rowids are very uncommon so this should not be a problem.
41165*/
41166SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
41167  BtCursor *p;
41168  for(p=pCur->pBt->pCursor; p; p=p->pNext){
41169    if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
41170  }
41171  assert( pCur->cachedRowid==iRowid );
41172}
41173
41174/*
41175** Return the cached rowid for the given cursor.  A negative or zero
41176** return value indicates that the rowid cache is invalid and should be
41177** ignored.  If the rowid cache has never before been set, then a
41178** zero is returned.
41179*/
41180SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
41181  return pCur->cachedRowid;
41182}
41183
41184/*
41185** Close a cursor.  The read lock on the database file is released
41186** when the last cursor is closed.
41187*/
41188SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
41189  Btree *pBtree = pCur->pBtree;
41190  if( pBtree ){
41191    int i;
41192    BtShared *pBt = pCur->pBt;
41193    sqlite3BtreeEnter(pBtree);
41194    sqlite3BtreeClearCursor(pCur);
41195    if( pCur->pPrev ){
41196      pCur->pPrev->pNext = pCur->pNext;
41197    }else{
41198      pBt->pCursor = pCur->pNext;
41199    }
41200    if( pCur->pNext ){
41201      pCur->pNext->pPrev = pCur->pPrev;
41202    }
41203    for(i=0; i<=pCur->iPage; i++){
41204      releasePage(pCur->apPage[i]);
41205    }
41206    unlockBtreeIfUnused(pBt);
41207    invalidateOverflowCache(pCur);
41208    /* sqlite3_free(pCur); */
41209    sqlite3BtreeLeave(pBtree);
41210  }
41211  return SQLITE_OK;
41212}
41213
41214/*
41215** Make sure the BtCursor* given in the argument has a valid
41216** BtCursor.info structure.  If it is not already valid, call
41217** btreeParseCell() to fill it in.
41218**
41219** BtCursor.info is a cache of the information in the current cell.
41220** Using this cache reduces the number of calls to btreeParseCell().
41221**
41222** 2007-06-25:  There is a bug in some versions of MSVC that cause the
41223** compiler to crash when getCellInfo() is implemented as a macro.
41224** But there is a measureable speed advantage to using the macro on gcc
41225** (when less compiler optimizations like -Os or -O0 are used and the
41226** compiler is not doing agressive inlining.)  So we use a real function
41227** for MSVC and a macro for everything else.  Ticket #2457.
41228*/
41229#ifndef NDEBUG
41230  static void assertCellInfo(BtCursor *pCur){
41231    CellInfo info;
41232    int iPage = pCur->iPage;
41233    memset(&info, 0, sizeof(info));
41234    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
41235    assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
41236  }
41237#else
41238  #define assertCellInfo(x)
41239#endif
41240#ifdef _MSC_VER
41241  /* Use a real function in MSVC to work around bugs in that compiler. */
41242  static void getCellInfo(BtCursor *pCur){
41243    if( pCur->info.nSize==0 ){
41244      int iPage = pCur->iPage;
41245      btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
41246      pCur->validNKey = 1;
41247    }else{
41248      assertCellInfo(pCur);
41249    }
41250  }
41251#else /* if not _MSC_VER */
41252  /* Use a macro in all other compilers so that the function is inlined */
41253#define getCellInfo(pCur)                                                      \
41254  if( pCur->info.nSize==0 ){                                                   \
41255    int iPage = pCur->iPage;                                                   \
41256    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
41257    pCur->validNKey = 1;                                                       \
41258  }else{                                                                       \
41259    assertCellInfo(pCur);                                                      \
41260  }
41261#endif /* _MSC_VER */
41262
41263#ifndef NDEBUG  /* The next routine used only within assert() statements */
41264/*
41265** Return true if the given BtCursor is valid.  A valid cursor is one
41266** that is currently pointing to a row in a (non-empty) table.
41267** This is a verification routine is used only within assert() statements.
41268*/
41269SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
41270  return pCur && pCur->eState==CURSOR_VALID;
41271}
41272#endif /* NDEBUG */
41273
41274/*
41275** Set *pSize to the size of the buffer needed to hold the value of
41276** the key for the current entry.  If the cursor is not pointing
41277** to a valid entry, *pSize is set to 0.
41278**
41279** For a table with the INTKEY flag set, this routine returns the key
41280** itself, not the number of bytes in the key.
41281**
41282** The caller must position the cursor prior to invoking this routine.
41283**
41284** This routine cannot fail.  It always returns SQLITE_OK.
41285*/
41286SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
41287  assert( cursorHoldsMutex(pCur) );
41288  assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
41289  if( pCur->eState!=CURSOR_VALID ){
41290    *pSize = 0;
41291  }else{
41292    getCellInfo(pCur);
41293    *pSize = pCur->info.nKey;
41294  }
41295  return SQLITE_OK;
41296}
41297
41298/*
41299** Set *pSize to the number of bytes of data in the entry the
41300** cursor currently points to.
41301**
41302** The caller must guarantee that the cursor is pointing to a non-NULL
41303** valid entry.  In other words, the calling procedure must guarantee
41304** that the cursor has Cursor.eState==CURSOR_VALID.
41305**
41306** Failure is not possible.  This function always returns SQLITE_OK.
41307** It might just as well be a procedure (returning void) but we continue
41308** to return an integer result code for historical reasons.
41309*/
41310SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
41311  assert( cursorHoldsMutex(pCur) );
41312  assert( pCur->eState==CURSOR_VALID );
41313  getCellInfo(pCur);
41314  *pSize = pCur->info.nData;
41315  return SQLITE_OK;
41316}
41317
41318/*
41319** Given the page number of an overflow page in the database (parameter
41320** ovfl), this function finds the page number of the next page in the
41321** linked list of overflow pages. If possible, it uses the auto-vacuum
41322** pointer-map data instead of reading the content of page ovfl to do so.
41323**
41324** If an error occurs an SQLite error code is returned. Otherwise:
41325**
41326** The page number of the next overflow page in the linked list is
41327** written to *pPgnoNext. If page ovfl is the last page in its linked
41328** list, *pPgnoNext is set to zero.
41329**
41330** If ppPage is not NULL, and a reference to the MemPage object corresponding
41331** to page number pOvfl was obtained, then *ppPage is set to point to that
41332** reference. It is the responsibility of the caller to call releasePage()
41333** on *ppPage to free the reference. In no reference was obtained (because
41334** the pointer-map was used to obtain the value for *pPgnoNext), then
41335** *ppPage is set to zero.
41336*/
41337static int getOverflowPage(
41338  BtShared *pBt,               /* The database file */
41339  Pgno ovfl,                   /* Current overflow page number */
41340  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
41341  Pgno *pPgnoNext              /* OUT: Next overflow page number */
41342){
41343  Pgno next = 0;
41344  MemPage *pPage = 0;
41345  int rc = SQLITE_OK;
41346
41347  assert( sqlite3_mutex_held(pBt->mutex) );
41348  assert(pPgnoNext);
41349
41350#ifndef SQLITE_OMIT_AUTOVACUUM
41351  /* Try to find the next page in the overflow list using the
41352  ** autovacuum pointer-map pages. Guess that the next page in
41353  ** the overflow list is page number (ovfl+1). If that guess turns
41354  ** out to be wrong, fall back to loading the data of page
41355  ** number ovfl to determine the next page number.
41356  */
41357  if( pBt->autoVacuum ){
41358    Pgno pgno;
41359    Pgno iGuess = ovfl+1;
41360    u8 eType;
41361
41362    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
41363      iGuess++;
41364    }
41365
41366    if( iGuess<=pagerPagecount(pBt) ){
41367      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
41368      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
41369        next = iGuess;
41370        rc = SQLITE_DONE;
41371      }
41372    }
41373  }
41374#endif
41375
41376  assert( next==0 || rc==SQLITE_DONE );
41377  if( rc==SQLITE_OK ){
41378    rc = btreeGetPage(pBt, ovfl, &pPage, 0);
41379    assert( rc==SQLITE_OK || pPage==0 );
41380    if( rc==SQLITE_OK ){
41381      next = get4byte(pPage->aData);
41382    }
41383  }
41384
41385  *pPgnoNext = next;
41386  if( ppPage ){
41387    *ppPage = pPage;
41388  }else{
41389    releasePage(pPage);
41390  }
41391  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
41392}
41393
41394/*
41395** Copy data from a buffer to a page, or from a page to a buffer.
41396**
41397** pPayload is a pointer to data stored on database page pDbPage.
41398** If argument eOp is false, then nByte bytes of data are copied
41399** from pPayload to the buffer pointed at by pBuf. If eOp is true,
41400** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
41401** of data are copied from the buffer pBuf to pPayload.
41402**
41403** SQLITE_OK is returned on success, otherwise an error code.
41404*/
41405static int copyPayload(
41406  void *pPayload,           /* Pointer to page data */
41407  void *pBuf,               /* Pointer to buffer */
41408  int nByte,                /* Number of bytes to copy */
41409  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
41410  DbPage *pDbPage           /* Page containing pPayload */
41411){
41412  if( eOp ){
41413    /* Copy data from buffer to page (a write operation) */
41414    int rc = sqlite3PagerWrite(pDbPage);
41415    if( rc!=SQLITE_OK ){
41416      return rc;
41417    }
41418    memcpy(pPayload, pBuf, nByte);
41419  }else{
41420    /* Copy data from page to buffer (a read operation) */
41421    memcpy(pBuf, pPayload, nByte);
41422  }
41423  return SQLITE_OK;
41424}
41425
41426/*
41427** This function is used to read or overwrite payload information
41428** for the entry that the pCur cursor is pointing to. If the eOp
41429** parameter is 0, this is a read operation (data copied into
41430** buffer pBuf). If it is non-zero, a write (data copied from
41431** buffer pBuf).
41432**
41433** A total of "amt" bytes are read or written beginning at "offset".
41434** Data is read to or from the buffer pBuf.
41435**
41436** The content being read or written might appear on the main page
41437** or be scattered out on multiple overflow pages.
41438**
41439** If the BtCursor.isIncrblobHandle flag is set, and the current
41440** cursor entry uses one or more overflow pages, this function
41441** allocates space for and lazily popluates the overflow page-list
41442** cache array (BtCursor.aOverflow). Subsequent calls use this
41443** cache to make seeking to the supplied offset more efficient.
41444**
41445** Once an overflow page-list cache has been allocated, it may be
41446** invalidated if some other cursor writes to the same table, or if
41447** the cursor is moved to a different row. Additionally, in auto-vacuum
41448** mode, the following events may invalidate an overflow page-list cache.
41449**
41450**   * An incremental vacuum,
41451**   * A commit in auto_vacuum="full" mode,
41452**   * Creating a table (may require moving an overflow page).
41453*/
41454static int accessPayload(
41455  BtCursor *pCur,      /* Cursor pointing to entry to read from */
41456  u32 offset,          /* Begin reading this far into payload */
41457  u32 amt,             /* Read this many bytes */
41458  unsigned char *pBuf, /* Write the bytes into this buffer */
41459  int eOp              /* zero to read. non-zero to write. */
41460){
41461  unsigned char *aPayload;
41462  int rc = SQLITE_OK;
41463  u32 nKey;
41464  int iIdx = 0;
41465  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
41466  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
41467
41468  assert( pPage );
41469  assert( pCur->eState==CURSOR_VALID );
41470  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
41471  assert( cursorHoldsMutex(pCur) );
41472
41473  getCellInfo(pCur);
41474  aPayload = pCur->info.pCell + pCur->info.nHeader;
41475  nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
41476
41477  if( NEVER(offset+amt > nKey+pCur->info.nData)
41478   || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
41479  ){
41480    /* Trying to read or write past the end of the data is an error */
41481    return SQLITE_CORRUPT_BKPT;
41482  }
41483
41484  /* Check if data must be read/written to/from the btree page itself. */
41485  if( offset<pCur->info.nLocal ){
41486    int a = amt;
41487    if( a+offset>pCur->info.nLocal ){
41488      a = pCur->info.nLocal - offset;
41489    }
41490    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
41491    offset = 0;
41492    pBuf += a;
41493    amt -= a;
41494  }else{
41495    offset -= pCur->info.nLocal;
41496  }
41497
41498  if( rc==SQLITE_OK && amt>0 ){
41499    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
41500    Pgno nextPage;
41501
41502    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
41503
41504#ifndef SQLITE_OMIT_INCRBLOB
41505    /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
41506    ** has not been allocated, allocate it now. The array is sized at
41507    ** one entry for each overflow page in the overflow chain. The
41508    ** page number of the first overflow page is stored in aOverflow[0],
41509    ** etc. A value of 0 in the aOverflow[] array means "not yet known"
41510    ** (the cache is lazily populated).
41511    */
41512    if( pCur->isIncrblobHandle && !pCur->aOverflow ){
41513      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
41514      pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
41515      /* nOvfl is always positive.  If it were zero, fetchPayload would have
41516      ** been used instead of this routine. */
41517      if( ALWAYS(nOvfl) && !pCur->aOverflow ){
41518        rc = SQLITE_NOMEM;
41519      }
41520    }
41521
41522    /* If the overflow page-list cache has been allocated and the
41523    ** entry for the first required overflow page is valid, skip
41524    ** directly to it.
41525    */
41526    if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
41527      iIdx = (offset/ovflSize);
41528      nextPage = pCur->aOverflow[iIdx];
41529      offset = (offset%ovflSize);
41530    }
41531#endif
41532
41533    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
41534
41535#ifndef SQLITE_OMIT_INCRBLOB
41536      /* If required, populate the overflow page-list cache. */
41537      if( pCur->aOverflow ){
41538        assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
41539        pCur->aOverflow[iIdx] = nextPage;
41540      }
41541#endif
41542
41543      if( offset>=ovflSize ){
41544        /* The only reason to read this page is to obtain the page
41545        ** number for the next page in the overflow chain. The page
41546        ** data is not required. So first try to lookup the overflow
41547        ** page-list cache, if any, then fall back to the getOverflowPage()
41548        ** function.
41549        */
41550#ifndef SQLITE_OMIT_INCRBLOB
41551        if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
41552          nextPage = pCur->aOverflow[iIdx+1];
41553        } else
41554#endif
41555          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
41556        offset -= ovflSize;
41557      }else{
41558        /* Need to read this page properly. It contains some of the
41559        ** range of data that is being read (eOp==0) or written (eOp!=0).
41560        */
41561        DbPage *pDbPage;
41562        int a = amt;
41563        rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
41564        if( rc==SQLITE_OK ){
41565          aPayload = sqlite3PagerGetData(pDbPage);
41566          nextPage = get4byte(aPayload);
41567          if( a + offset > ovflSize ){
41568            a = ovflSize - offset;
41569          }
41570          rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
41571          sqlite3PagerUnref(pDbPage);
41572          offset = 0;
41573          amt -= a;
41574          pBuf += a;
41575        }
41576      }
41577    }
41578  }
41579
41580  if( rc==SQLITE_OK && amt>0 ){
41581    return SQLITE_CORRUPT_BKPT;
41582  }
41583  return rc;
41584}
41585
41586/*
41587** Read part of the key associated with cursor pCur.  Exactly
41588** "amt" bytes will be transfered into pBuf[].  The transfer
41589** begins at "offset".
41590**
41591** The caller must ensure that pCur is pointing to a valid row
41592** in the table.
41593**
41594** Return SQLITE_OK on success or an error code if anything goes
41595** wrong.  An error is returned if "offset+amt" is larger than
41596** the available payload.
41597*/
41598SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
41599  assert( cursorHoldsMutex(pCur) );
41600  assert( pCur->eState==CURSOR_VALID );
41601  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
41602  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
41603  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
41604}
41605
41606/*
41607** Read part of the data associated with cursor pCur.  Exactly
41608** "amt" bytes will be transfered into pBuf[].  The transfer
41609** begins at "offset".
41610**
41611** Return SQLITE_OK on success or an error code if anything goes
41612** wrong.  An error is returned if "offset+amt" is larger than
41613** the available payload.
41614*/
41615SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
41616  int rc;
41617
41618#ifndef SQLITE_OMIT_INCRBLOB
41619  if ( pCur->eState==CURSOR_INVALID ){
41620    return SQLITE_ABORT;
41621  }
41622#endif
41623
41624  assert( cursorHoldsMutex(pCur) );
41625  rc = restoreCursorPosition(pCur);
41626  if( rc==SQLITE_OK ){
41627    assert( pCur->eState==CURSOR_VALID );
41628    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
41629    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
41630    rc = accessPayload(pCur, offset, amt, pBuf, 0);
41631  }
41632  return rc;
41633}
41634
41635/*
41636** Return a pointer to payload information from the entry that the
41637** pCur cursor is pointing to.  The pointer is to the beginning of
41638** the key if skipKey==0 and it points to the beginning of data if
41639** skipKey==1.  The number of bytes of available key/data is written
41640** into *pAmt.  If *pAmt==0, then the value returned will not be
41641** a valid pointer.
41642**
41643** This routine is an optimization.  It is common for the entire key
41644** and data to fit on the local page and for there to be no overflow
41645** pages.  When that is so, this routine can be used to access the
41646** key and data without making a copy.  If the key and/or data spills
41647** onto overflow pages, then accessPayload() must be used to reassemble
41648** the key/data and copy it into a preallocated buffer.
41649**
41650** The pointer returned by this routine looks directly into the cached
41651** page of the database.  The data might change or move the next time
41652** any btree routine is called.
41653*/
41654static const unsigned char *fetchPayload(
41655  BtCursor *pCur,      /* Cursor pointing to entry to read from */
41656  int *pAmt,           /* Write the number of available bytes here */
41657  int skipKey          /* read beginning at data if this is true */
41658){
41659  unsigned char *aPayload;
41660  MemPage *pPage;
41661  u32 nKey;
41662  u32 nLocal;
41663
41664  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
41665  assert( pCur->eState==CURSOR_VALID );
41666  assert( cursorHoldsMutex(pCur) );
41667  pPage = pCur->apPage[pCur->iPage];
41668  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
41669  if( NEVER(pCur->info.nSize==0) ){
41670    btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
41671                   &pCur->info);
41672  }
41673  aPayload = pCur->info.pCell;
41674  aPayload += pCur->info.nHeader;
41675  if( pPage->intKey ){
41676    nKey = 0;
41677  }else{
41678    nKey = (int)pCur->info.nKey;
41679  }
41680  if( skipKey ){
41681    aPayload += nKey;
41682    nLocal = pCur->info.nLocal - nKey;
41683  }else{
41684    nLocal = pCur->info.nLocal;
41685    assert( nLocal<=nKey );
41686  }
41687  *pAmt = nLocal;
41688  return aPayload;
41689}
41690
41691
41692/*
41693** For the entry that cursor pCur is point to, return as
41694** many bytes of the key or data as are available on the local
41695** b-tree page.  Write the number of available bytes into *pAmt.
41696**
41697** The pointer returned is ephemeral.  The key/data may move
41698** or be destroyed on the next call to any Btree routine,
41699** including calls from other threads against the same cache.
41700** Hence, a mutex on the BtShared should be held prior to calling
41701** this routine.
41702**
41703** These routines is used to get quick access to key and data
41704** in the common case where no overflow pages are used.
41705*/
41706SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
41707  const void *p = 0;
41708  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41709  assert( cursorHoldsMutex(pCur) );
41710  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
41711    p = (const void*)fetchPayload(pCur, pAmt, 0);
41712  }
41713  return p;
41714}
41715SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
41716  const void *p = 0;
41717  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41718  assert( cursorHoldsMutex(pCur) );
41719  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
41720    p = (const void*)fetchPayload(pCur, pAmt, 1);
41721  }
41722  return p;
41723}
41724
41725
41726/*
41727** Move the cursor down to a new child page.  The newPgno argument is the
41728** page number of the child page to move to.
41729**
41730** This function returns SQLITE_CORRUPT if the page-header flags field of
41731** the new child page does not match the flags field of the parent (i.e.
41732** if an intkey page appears to be the parent of a non-intkey page, or
41733** vice-versa).
41734*/
41735static int moveToChild(BtCursor *pCur, u32 newPgno){
41736  int rc;
41737  int i = pCur->iPage;
41738  MemPage *pNewPage;
41739  BtShared *pBt = pCur->pBt;
41740
41741  assert( cursorHoldsMutex(pCur) );
41742  assert( pCur->eState==CURSOR_VALID );
41743  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
41744  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
41745    return SQLITE_CORRUPT_BKPT;
41746  }
41747  rc = getAndInitPage(pBt, newPgno, &pNewPage);
41748  if( rc ) return rc;
41749  pCur->apPage[i+1] = pNewPage;
41750  pCur->aiIdx[i+1] = 0;
41751  pCur->iPage++;
41752
41753  pCur->info.nSize = 0;
41754  pCur->validNKey = 0;
41755  if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
41756    return SQLITE_CORRUPT_BKPT;
41757  }
41758  return SQLITE_OK;
41759}
41760
41761#ifndef NDEBUG
41762/*
41763** Page pParent is an internal (non-leaf) tree page. This function
41764** asserts that page number iChild is the left-child if the iIdx'th
41765** cell in page pParent. Or, if iIdx is equal to the total number of
41766** cells in pParent, that page number iChild is the right-child of
41767** the page.
41768*/
41769static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
41770  assert( iIdx<=pParent->nCell );
41771  if( iIdx==pParent->nCell ){
41772    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
41773  }else{
41774    assert( get4byte(findCell(pParent, iIdx))==iChild );
41775  }
41776}
41777#else
41778#  define assertParentIndex(x,y,z)
41779#endif
41780
41781/*
41782** Move the cursor up to the parent page.
41783**
41784** pCur->idx is set to the cell index that contains the pointer
41785** to the page we are coming from.  If we are coming from the
41786** right-most child page then pCur->idx is set to one more than
41787** the largest cell index.
41788*/
41789static void moveToParent(BtCursor *pCur){
41790  assert( cursorHoldsMutex(pCur) );
41791  assert( pCur->eState==CURSOR_VALID );
41792  assert( pCur->iPage>0 );
41793  assert( pCur->apPage[pCur->iPage] );
41794  assertParentIndex(
41795    pCur->apPage[pCur->iPage-1],
41796    pCur->aiIdx[pCur->iPage-1],
41797    pCur->apPage[pCur->iPage]->pgno
41798  );
41799  releasePage(pCur->apPage[pCur->iPage]);
41800  pCur->iPage--;
41801  pCur->info.nSize = 0;
41802  pCur->validNKey = 0;
41803}
41804
41805/*
41806** Move the cursor to point to the root page of its b-tree structure.
41807**
41808** If the table has a virtual root page, then the cursor is moved to point
41809** to the virtual root page instead of the actual root page. A table has a
41810** virtual root page when the actual root page contains no cells and a
41811** single child page. This can only happen with the table rooted at page 1.
41812**
41813** If the b-tree structure is empty, the cursor state is set to
41814** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
41815** cell located on the root (or virtual root) page and the cursor state
41816** is set to CURSOR_VALID.
41817**
41818** If this function returns successfully, it may be assumed that the
41819** page-header flags indicate that the [virtual] root-page is the expected
41820** kind of b-tree page (i.e. if when opening the cursor the caller did not
41821** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
41822** indicating a table b-tree, or if the caller did specify a KeyInfo
41823** structure the flags byte is set to 0x02 or 0x0A, indicating an index
41824** b-tree).
41825*/
41826static int moveToRoot(BtCursor *pCur){
41827  MemPage *pRoot;
41828  int rc = SQLITE_OK;
41829  Btree *p = pCur->pBtree;
41830  BtShared *pBt = p->pBt;
41831
41832  assert( cursorHoldsMutex(pCur) );
41833  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
41834  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
41835  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
41836  if( pCur->eState>=CURSOR_REQUIRESEEK ){
41837    if( pCur->eState==CURSOR_FAULT ){
41838      assert( pCur->skipNext!=SQLITE_OK );
41839      return pCur->skipNext;
41840    }
41841    sqlite3BtreeClearCursor(pCur);
41842  }
41843
41844  if( pCur->iPage>=0 ){
41845    int i;
41846    for(i=1; i<=pCur->iPage; i++){
41847      releasePage(pCur->apPage[i]);
41848    }
41849    pCur->iPage = 0;
41850  }else{
41851    rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
41852    if( rc!=SQLITE_OK ){
41853      pCur->eState = CURSOR_INVALID;
41854      return rc;
41855    }
41856    pCur->iPage = 0;
41857
41858    /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
41859    ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
41860    ** NULL, the caller expects a table b-tree. If this is not the case,
41861    ** return an SQLITE_CORRUPT error.  */
41862    assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
41863    if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
41864      return SQLITE_CORRUPT_BKPT;
41865    }
41866  }
41867
41868  /* Assert that the root page is of the correct type. This must be the
41869  ** case as the call to this function that loaded the root-page (either
41870  ** this call or a previous invocation) would have detected corruption
41871  ** if the assumption were not true, and it is not possible for the flags
41872  ** byte to have been modified while this cursor is holding a reference
41873  ** to the page.  */
41874  pRoot = pCur->apPage[0];
41875  assert( pRoot->pgno==pCur->pgnoRoot );
41876  assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
41877
41878  pCur->aiIdx[0] = 0;
41879  pCur->info.nSize = 0;
41880  pCur->atLast = 0;
41881  pCur->validNKey = 0;
41882
41883  if( pRoot->nCell==0 && !pRoot->leaf ){
41884    Pgno subpage;
41885    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
41886    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
41887    pCur->eState = CURSOR_VALID;
41888    rc = moveToChild(pCur, subpage);
41889  }else{
41890    pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
41891  }
41892  return rc;
41893}
41894
41895/*
41896** Move the cursor down to the left-most leaf entry beneath the
41897** entry to which it is currently pointing.
41898**
41899** The left-most leaf is the one with the smallest key - the first
41900** in ascending order.
41901*/
41902static int moveToLeftmost(BtCursor *pCur){
41903  Pgno pgno;
41904  int rc = SQLITE_OK;
41905  MemPage *pPage;
41906
41907  assert( cursorHoldsMutex(pCur) );
41908  assert( pCur->eState==CURSOR_VALID );
41909  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
41910    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
41911    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
41912    rc = moveToChild(pCur, pgno);
41913  }
41914  return rc;
41915}
41916
41917/*
41918** Move the cursor down to the right-most leaf entry beneath the
41919** page to which it is currently pointing.  Notice the difference
41920** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
41921** finds the left-most entry beneath the *entry* whereas moveToRightmost()
41922** finds the right-most entry beneath the *page*.
41923**
41924** The right-most entry is the one with the largest key - the last
41925** key in ascending order.
41926*/
41927static int moveToRightmost(BtCursor *pCur){
41928  Pgno pgno;
41929  int rc = SQLITE_OK;
41930  MemPage *pPage = 0;
41931
41932  assert( cursorHoldsMutex(pCur) );
41933  assert( pCur->eState==CURSOR_VALID );
41934  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
41935    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
41936    pCur->aiIdx[pCur->iPage] = pPage->nCell;
41937    rc = moveToChild(pCur, pgno);
41938  }
41939  if( rc==SQLITE_OK ){
41940    pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
41941    pCur->info.nSize = 0;
41942    pCur->validNKey = 0;
41943  }
41944  return rc;
41945}
41946
41947/* Move the cursor to the first entry in the table.  Return SQLITE_OK
41948** on success.  Set *pRes to 0 if the cursor actually points to something
41949** or set *pRes to 1 if the table is empty.
41950*/
41951SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
41952  int rc;
41953
41954  assert( cursorHoldsMutex(pCur) );
41955  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41956  rc = moveToRoot(pCur);
41957  if( rc==SQLITE_OK ){
41958    if( pCur->eState==CURSOR_INVALID ){
41959      assert( pCur->apPage[pCur->iPage]->nCell==0 );
41960      *pRes = 1;
41961      rc = SQLITE_OK;
41962    }else{
41963      assert( pCur->apPage[pCur->iPage]->nCell>0 );
41964      *pRes = 0;
41965      rc = moveToLeftmost(pCur);
41966    }
41967  }
41968  return rc;
41969}
41970
41971/* Move the cursor to the last entry in the table.  Return SQLITE_OK
41972** on success.  Set *pRes to 0 if the cursor actually points to something
41973** or set *pRes to 1 if the table is empty.
41974*/
41975SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
41976  int rc;
41977
41978  assert( cursorHoldsMutex(pCur) );
41979  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41980
41981  /* If the cursor already points to the last entry, this is a no-op. */
41982  if( CURSOR_VALID==pCur->eState && pCur->atLast ){
41983#ifdef SQLITE_DEBUG
41984    /* This block serves to assert() that the cursor really does point
41985    ** to the last entry in the b-tree. */
41986    int ii;
41987    for(ii=0; ii<pCur->iPage; ii++){
41988      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
41989    }
41990    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
41991    assert( pCur->apPage[pCur->iPage]->leaf );
41992#endif
41993    return SQLITE_OK;
41994  }
41995
41996  rc = moveToRoot(pCur);
41997  if( rc==SQLITE_OK ){
41998    if( CURSOR_INVALID==pCur->eState ){
41999      assert( pCur->apPage[pCur->iPage]->nCell==0 );
42000      *pRes = 1;
42001    }else{
42002      assert( pCur->eState==CURSOR_VALID );
42003      *pRes = 0;
42004      rc = moveToRightmost(pCur);
42005      pCur->atLast = rc==SQLITE_OK ?1:0;
42006    }
42007  }
42008  return rc;
42009}
42010
42011/* Move the cursor so that it points to an entry near the key
42012** specified by pIdxKey or intKey.   Return a success code.
42013**
42014** For INTKEY tables, the intKey parameter is used.  pIdxKey
42015** must be NULL.  For index tables, pIdxKey is used and intKey
42016** is ignored.
42017**
42018** If an exact match is not found, then the cursor is always
42019** left pointing at a leaf page which would hold the entry if it
42020** were present.  The cursor might point to an entry that comes
42021** before or after the key.
42022**
42023** An integer is written into *pRes which is the result of
42024** comparing the key with the entry to which the cursor is
42025** pointing.  The meaning of the integer written into
42026** *pRes is as follows:
42027**
42028**     *pRes<0      The cursor is left pointing at an entry that
42029**                  is smaller than intKey/pIdxKey or if the table is empty
42030**                  and the cursor is therefore left point to nothing.
42031**
42032**     *pRes==0     The cursor is left pointing at an entry that
42033**                  exactly matches intKey/pIdxKey.
42034**
42035**     *pRes>0      The cursor is left pointing at an entry that
42036**                  is larger than intKey/pIdxKey.
42037**
42038*/
42039SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
42040  BtCursor *pCur,          /* The cursor to be moved */
42041  UnpackedRecord *pIdxKey, /* Unpacked index key */
42042  i64 intKey,              /* The table key */
42043  int biasRight,           /* If true, bias the search to the high end */
42044  int *pRes                /* Write search results here */
42045){
42046  int rc;
42047
42048  assert( cursorHoldsMutex(pCur) );
42049  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
42050  assert( pRes );
42051  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
42052
42053  /* If the cursor is already positioned at the point we are trying
42054  ** to move to, then just return without doing any work */
42055  if( pCur->eState==CURSOR_VALID && pCur->validNKey
42056   && pCur->apPage[0]->intKey
42057  ){
42058    if( pCur->info.nKey==intKey ){
42059      *pRes = 0;
42060      return SQLITE_OK;
42061    }
42062    if( pCur->atLast && pCur->info.nKey<intKey ){
42063      *pRes = -1;
42064      return SQLITE_OK;
42065    }
42066  }
42067
42068  rc = moveToRoot(pCur);
42069  if( rc ){
42070    return rc;
42071  }
42072  assert( pCur->apPage[pCur->iPage] );
42073  assert( pCur->apPage[pCur->iPage]->isInit );
42074  assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
42075  if( pCur->eState==CURSOR_INVALID ){
42076    *pRes = -1;
42077    assert( pCur->apPage[pCur->iPage]->nCell==0 );
42078    return SQLITE_OK;
42079  }
42080  assert( pCur->apPage[0]->intKey || pIdxKey );
42081  for(;;){
42082    int lwr, upr;
42083    Pgno chldPg;
42084    MemPage *pPage = pCur->apPage[pCur->iPage];
42085    int c;
42086
42087    /* pPage->nCell must be greater than zero. If this is the root-page
42088    ** the cursor would have been INVALID above and this for(;;) loop
42089    ** not run. If this is not the root-page, then the moveToChild() routine
42090    ** would have already detected db corruption. Similarly, pPage must
42091    ** be the right kind (index or table) of b-tree page. Otherwise
42092    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
42093    assert( pPage->nCell>0 );
42094    assert( pPage->intKey==(pIdxKey==0) );
42095    lwr = 0;
42096    upr = pPage->nCell-1;
42097    if( biasRight ){
42098      pCur->aiIdx[pCur->iPage] = (u16)upr;
42099    }else{
42100      pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
42101    }
42102    for(;;){
42103      int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
42104      u8 *pCell;                          /* Pointer to current cell in pPage */
42105
42106      pCur->info.nSize = 0;
42107      pCell = findCell(pPage, idx) + pPage->childPtrSize;
42108      if( pPage->intKey ){
42109        i64 nCellKey;
42110        if( pPage->hasData ){
42111          u32 dummy;
42112          pCell += getVarint32(pCell, dummy);
42113        }
42114        getVarint(pCell, (u64*)&nCellKey);
42115        if( nCellKey==intKey ){
42116          c = 0;
42117        }else if( nCellKey<intKey ){
42118          c = -1;
42119        }else{
42120          assert( nCellKey>intKey );
42121          c = +1;
42122        }
42123        pCur->validNKey = 1;
42124        pCur->info.nKey = nCellKey;
42125      }else{
42126        /* The maximum supported page-size is 32768 bytes. This means that
42127        ** the maximum number of record bytes stored on an index B-Tree
42128        ** page is at most 8198 bytes, which may be stored as a 2-byte
42129        ** varint. This information is used to attempt to avoid parsing
42130        ** the entire cell by checking for the cases where the record is
42131        ** stored entirely within the b-tree page by inspecting the first
42132        ** 2 bytes of the cell.
42133        */
42134        int nCell = pCell[0];
42135        if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
42136          /* This branch runs if the record-size field of the cell is a
42137          ** single byte varint and the record fits entirely on the main
42138          ** b-tree page.  */
42139          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
42140        }else if( !(pCell[1] & 0x80)
42141          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
42142        ){
42143          /* The record-size field is a 2 byte varint and the record
42144          ** fits entirely on the main b-tree page.  */
42145          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
42146        }else{
42147          /* The record flows over onto one or more overflow pages. In
42148          ** this case the whole cell needs to be parsed, a buffer allocated
42149          ** and accessPayload() used to retrieve the record into the
42150          ** buffer before VdbeRecordCompare() can be called. */
42151          void *pCellKey;
42152          u8 * const pCellBody = pCell - pPage->childPtrSize;
42153          btreeParseCellPtr(pPage, pCellBody, &pCur->info);
42154          nCell = (int)pCur->info.nKey;
42155          pCellKey = sqlite3Malloc( nCell );
42156          if( pCellKey==0 ){
42157            rc = SQLITE_NOMEM;
42158            goto moveto_finish;
42159          }
42160          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
42161          if( rc ){
42162            sqlite3_free(pCellKey);
42163            goto moveto_finish;
42164          }
42165          c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
42166          sqlite3_free(pCellKey);
42167        }
42168      }
42169      if( c==0 ){
42170        if( pPage->intKey && !pPage->leaf ){
42171          lwr = idx;
42172          upr = lwr - 1;
42173          break;
42174        }else{
42175          *pRes = 0;
42176          rc = SQLITE_OK;
42177          goto moveto_finish;
42178        }
42179      }
42180      if( c<0 ){
42181        lwr = idx+1;
42182      }else{
42183        upr = idx-1;
42184      }
42185      if( lwr>upr ){
42186        break;
42187      }
42188      pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
42189    }
42190    assert( lwr==upr+1 );
42191    assert( pPage->isInit );
42192    if( pPage->leaf ){
42193      chldPg = 0;
42194    }else if( lwr>=pPage->nCell ){
42195      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
42196    }else{
42197      chldPg = get4byte(findCell(pPage, lwr));
42198    }
42199    if( chldPg==0 ){
42200      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
42201      *pRes = c;
42202      rc = SQLITE_OK;
42203      goto moveto_finish;
42204    }
42205    pCur->aiIdx[pCur->iPage] = (u16)lwr;
42206    pCur->info.nSize = 0;
42207    pCur->validNKey = 0;
42208    rc = moveToChild(pCur, chldPg);
42209    if( rc ) goto moveto_finish;
42210  }
42211moveto_finish:
42212  return rc;
42213}
42214
42215
42216/*
42217** Return TRUE if the cursor is not pointing at an entry of the table.
42218**
42219** TRUE will be returned after a call to sqlite3BtreeNext() moves
42220** past the last entry in the table or sqlite3BtreePrev() moves past
42221** the first entry.  TRUE is also returned if the table is empty.
42222*/
42223SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
42224  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
42225  ** have been deleted? This API will need to change to return an error code
42226  ** as well as the boolean result value.
42227  */
42228  return (CURSOR_VALID!=pCur->eState);
42229}
42230
42231/*
42232** Advance the cursor to the next entry in the database.  If
42233** successful then set *pRes=0.  If the cursor
42234** was already pointing to the last entry in the database before
42235** this routine was called, then set *pRes=1.
42236*/
42237SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
42238  int rc;
42239  int idx;
42240  MemPage *pPage;
42241
42242  assert( cursorHoldsMutex(pCur) );
42243  rc = restoreCursorPosition(pCur);
42244  if( rc!=SQLITE_OK ){
42245    return rc;
42246  }
42247  assert( pRes!=0 );
42248  if( CURSOR_INVALID==pCur->eState ){
42249    *pRes = 1;
42250    return SQLITE_OK;
42251  }
42252  if( pCur->skipNext>0 ){
42253    pCur->skipNext = 0;
42254    *pRes = 0;
42255    return SQLITE_OK;
42256  }
42257  pCur->skipNext = 0;
42258
42259  pPage = pCur->apPage[pCur->iPage];
42260  idx = ++pCur->aiIdx[pCur->iPage];
42261  assert( pPage->isInit );
42262  assert( idx<=pPage->nCell );
42263
42264  pCur->info.nSize = 0;
42265  pCur->validNKey = 0;
42266  if( idx>=pPage->nCell ){
42267    if( !pPage->leaf ){
42268      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
42269      if( rc ) return rc;
42270      rc = moveToLeftmost(pCur);
42271      *pRes = 0;
42272      return rc;
42273    }
42274    do{
42275      if( pCur->iPage==0 ){
42276        *pRes = 1;
42277        pCur->eState = CURSOR_INVALID;
42278        return SQLITE_OK;
42279      }
42280      moveToParent(pCur);
42281      pPage = pCur->apPage[pCur->iPage];
42282    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
42283    *pRes = 0;
42284    if( pPage->intKey ){
42285      rc = sqlite3BtreeNext(pCur, pRes);
42286    }else{
42287      rc = SQLITE_OK;
42288    }
42289    return rc;
42290  }
42291  *pRes = 0;
42292  if( pPage->leaf ){
42293    return SQLITE_OK;
42294  }
42295  rc = moveToLeftmost(pCur);
42296  return rc;
42297}
42298
42299
42300/*
42301** Step the cursor to the back to the previous entry in the database.  If
42302** successful then set *pRes=0.  If the cursor
42303** was already pointing to the first entry in the database before
42304** this routine was called, then set *pRes=1.
42305*/
42306SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
42307  int rc;
42308  MemPage *pPage;
42309
42310  assert( cursorHoldsMutex(pCur) );
42311  rc = restoreCursorPosition(pCur);
42312  if( rc!=SQLITE_OK ){
42313    return rc;
42314  }
42315  pCur->atLast = 0;
42316  if( CURSOR_INVALID==pCur->eState ){
42317    *pRes = 1;
42318    return SQLITE_OK;
42319  }
42320  if( pCur->skipNext<0 ){
42321    pCur->skipNext = 0;
42322    *pRes = 0;
42323    return SQLITE_OK;
42324  }
42325  pCur->skipNext = 0;
42326
42327  pPage = pCur->apPage[pCur->iPage];
42328  assert( pPage->isInit );
42329  if( !pPage->leaf ){
42330    int idx = pCur->aiIdx[pCur->iPage];
42331    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
42332    if( rc ){
42333      return rc;
42334    }
42335    rc = moveToRightmost(pCur);
42336  }else{
42337    while( pCur->aiIdx[pCur->iPage]==0 ){
42338      if( pCur->iPage==0 ){
42339        pCur->eState = CURSOR_INVALID;
42340        *pRes = 1;
42341        return SQLITE_OK;
42342      }
42343      moveToParent(pCur);
42344    }
42345    pCur->info.nSize = 0;
42346    pCur->validNKey = 0;
42347
42348    pCur->aiIdx[pCur->iPage]--;
42349    pPage = pCur->apPage[pCur->iPage];
42350    if( pPage->intKey && !pPage->leaf ){
42351      rc = sqlite3BtreePrevious(pCur, pRes);
42352    }else{
42353      rc = SQLITE_OK;
42354    }
42355  }
42356  *pRes = 0;
42357  return rc;
42358}
42359
42360/*
42361** Allocate a new page from the database file.
42362**
42363** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
42364** has already been called on the new page.)  The new page has also
42365** been referenced and the calling routine is responsible for calling
42366** sqlite3PagerUnref() on the new page when it is done.
42367**
42368** SQLITE_OK is returned on success.  Any other return value indicates
42369** an error.  *ppPage and *pPgno are undefined in the event of an error.
42370** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
42371**
42372** If the "nearby" parameter is not 0, then a (feeble) effort is made to
42373** locate a page close to the page number "nearby".  This can be used in an
42374** attempt to keep related pages close to each other in the database file,
42375** which in turn can make database access faster.
42376**
42377** If the "exact" parameter is not 0, and the page-number nearby exists
42378** anywhere on the free-list, then it is guarenteed to be returned. This
42379** is only used by auto-vacuum databases when allocating a new table.
42380*/
42381static int allocateBtreePage(
42382  BtShared *pBt,
42383  MemPage **ppPage,
42384  Pgno *pPgno,
42385  Pgno nearby,
42386  u8 exact
42387){
42388  MemPage *pPage1;
42389  int rc;
42390  u32 n;     /* Number of pages on the freelist */
42391  u32 k;     /* Number of leaves on the trunk of the freelist */
42392  MemPage *pTrunk = 0;
42393  MemPage *pPrevTrunk = 0;
42394  Pgno mxPage;     /* Total size of the database file */
42395
42396  assert( sqlite3_mutex_held(pBt->mutex) );
42397  pPage1 = pBt->pPage1;
42398  mxPage = pagerPagecount(pBt);
42399  n = get4byte(&pPage1->aData[36]);
42400  testcase( n==mxPage-1 );
42401  if( n>=mxPage ){
42402    return SQLITE_CORRUPT_BKPT;
42403  }
42404  if( n>0 ){
42405    /* There are pages on the freelist.  Reuse one of those pages. */
42406    Pgno iTrunk;
42407    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
42408
42409    /* If the 'exact' parameter was true and a query of the pointer-map
42410    ** shows that the page 'nearby' is somewhere on the free-list, then
42411    ** the entire-list will be searched for that page.
42412    */
42413#ifndef SQLITE_OMIT_AUTOVACUUM
42414    if( exact && nearby<=mxPage ){
42415      u8 eType;
42416      assert( nearby>0 );
42417      assert( pBt->autoVacuum );
42418      rc = ptrmapGet(pBt, nearby, &eType, 0);
42419      if( rc ) return rc;
42420      if( eType==PTRMAP_FREEPAGE ){
42421        searchList = 1;
42422      }
42423      *pPgno = nearby;
42424    }
42425#endif
42426
42427    /* Decrement the free-list count by 1. Set iTrunk to the index of the
42428    ** first free-list trunk page. iPrevTrunk is initially 1.
42429    */
42430    rc = sqlite3PagerWrite(pPage1->pDbPage);
42431    if( rc ) return rc;
42432    put4byte(&pPage1->aData[36], n-1);
42433
42434    /* The code within this loop is run only once if the 'searchList' variable
42435    ** is not true. Otherwise, it runs once for each trunk-page on the
42436    ** free-list until the page 'nearby' is located.
42437    */
42438    do {
42439      pPrevTrunk = pTrunk;
42440      if( pPrevTrunk ){
42441        iTrunk = get4byte(&pPrevTrunk->aData[0]);
42442      }else{
42443        iTrunk = get4byte(&pPage1->aData[32]);
42444      }
42445      testcase( iTrunk==mxPage );
42446      if( iTrunk>mxPage ){
42447        rc = SQLITE_CORRUPT_BKPT;
42448      }else{
42449        rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
42450      }
42451      if( rc ){
42452        pTrunk = 0;
42453        goto end_allocate_page;
42454      }
42455
42456      k = get4byte(&pTrunk->aData[4]);
42457      if( k==0 && !searchList ){
42458        /* The trunk has no leaves and the list is not being searched.
42459        ** So extract the trunk page itself and use it as the newly
42460        ** allocated page */
42461        assert( pPrevTrunk==0 );
42462        rc = sqlite3PagerWrite(pTrunk->pDbPage);
42463        if( rc ){
42464          goto end_allocate_page;
42465        }
42466        *pPgno = iTrunk;
42467        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
42468        *ppPage = pTrunk;
42469        pTrunk = 0;
42470        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
42471      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
42472        /* Value of k is out of range.  Database corruption */
42473        rc = SQLITE_CORRUPT_BKPT;
42474        goto end_allocate_page;
42475#ifndef SQLITE_OMIT_AUTOVACUUM
42476      }else if( searchList && nearby==iTrunk ){
42477        /* The list is being searched and this trunk page is the page
42478        ** to allocate, regardless of whether it has leaves.
42479        */
42480        assert( *pPgno==iTrunk );
42481        *ppPage = pTrunk;
42482        searchList = 0;
42483        rc = sqlite3PagerWrite(pTrunk->pDbPage);
42484        if( rc ){
42485          goto end_allocate_page;
42486        }
42487        if( k==0 ){
42488          if( !pPrevTrunk ){
42489            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
42490          }else{
42491            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
42492          }
42493        }else{
42494          /* The trunk page is required by the caller but it contains
42495          ** pointers to free-list leaves. The first leaf becomes a trunk
42496          ** page in this case.
42497          */
42498          MemPage *pNewTrunk;
42499          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
42500          if( iNewTrunk>mxPage ){
42501            rc = SQLITE_CORRUPT_BKPT;
42502            goto end_allocate_page;
42503          }
42504          testcase( iNewTrunk==mxPage );
42505          rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
42506          if( rc!=SQLITE_OK ){
42507            goto end_allocate_page;
42508          }
42509          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
42510          if( rc!=SQLITE_OK ){
42511            releasePage(pNewTrunk);
42512            goto end_allocate_page;
42513          }
42514          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
42515          put4byte(&pNewTrunk->aData[4], k-1);
42516          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
42517          releasePage(pNewTrunk);
42518          if( !pPrevTrunk ){
42519            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
42520            put4byte(&pPage1->aData[32], iNewTrunk);
42521          }else{
42522            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
42523            if( rc ){
42524              goto end_allocate_page;
42525            }
42526            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
42527          }
42528        }
42529        pTrunk = 0;
42530        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
42531#endif
42532      }else if( k>0 ){
42533        /* Extract a leaf from the trunk */
42534        u32 closest;
42535        Pgno iPage;
42536        unsigned char *aData = pTrunk->aData;
42537        rc = sqlite3PagerWrite(pTrunk->pDbPage);
42538        if( rc ){
42539          goto end_allocate_page;
42540        }
42541        if( nearby>0 ){
42542          u32 i;
42543          int dist;
42544          closest = 0;
42545          dist = get4byte(&aData[8]) - nearby;
42546          if( dist<0 ) dist = -dist;
42547          for(i=1; i<k; i++){
42548            int d2 = get4byte(&aData[8+i*4]) - nearby;
42549            if( d2<0 ) d2 = -d2;
42550            if( d2<dist ){
42551              closest = i;
42552              dist = d2;
42553            }
42554          }
42555        }else{
42556          closest = 0;
42557        }
42558
42559        iPage = get4byte(&aData[8+closest*4]);
42560        testcase( iPage==mxPage );
42561        if( iPage>mxPage ){
42562          rc = SQLITE_CORRUPT_BKPT;
42563          goto end_allocate_page;
42564        }
42565        testcase( iPage==mxPage );
42566        if( !searchList || iPage==nearby ){
42567          int noContent;
42568          *pPgno = iPage;
42569          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
42570                 ": %d more free pages\n",
42571                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
42572          if( closest<k-1 ){
42573            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
42574          }
42575          put4byte(&aData[4], k-1);
42576          assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
42577          noContent = !btreeGetHasContent(pBt, *pPgno);
42578          rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
42579          if( rc==SQLITE_OK ){
42580            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
42581            if( rc!=SQLITE_OK ){
42582              releasePage(*ppPage);
42583            }
42584          }
42585          searchList = 0;
42586        }
42587      }
42588      releasePage(pPrevTrunk);
42589      pPrevTrunk = 0;
42590    }while( searchList );
42591  }else{
42592    /* There are no pages on the freelist, so create a new page at the
42593    ** end of the file */
42594    int nPage = pagerPagecount(pBt);
42595    *pPgno = nPage + 1;
42596
42597    if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
42598      (*pPgno)++;
42599    }
42600
42601#ifndef SQLITE_OMIT_AUTOVACUUM
42602    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
42603      /* If *pPgno refers to a pointer-map page, allocate two new pages
42604      ** at the end of the file instead of one. The first allocated page
42605      ** becomes a new pointer-map page, the second is used by the caller.
42606      */
42607      MemPage *pPg = 0;
42608      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
42609      assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
42610      rc = btreeGetPage(pBt, *pPgno, &pPg, 0);
42611      if( rc==SQLITE_OK ){
42612        rc = sqlite3PagerWrite(pPg->pDbPage);
42613        releasePage(pPg);
42614      }
42615      if( rc ) return rc;
42616      (*pPgno)++;
42617      if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
42618    }
42619#endif
42620
42621    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
42622    rc = btreeGetPage(pBt, *pPgno, ppPage, 0);
42623    if( rc ) return rc;
42624    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
42625    if( rc!=SQLITE_OK ){
42626      releasePage(*ppPage);
42627    }
42628    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
42629  }
42630
42631  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
42632
42633end_allocate_page:
42634  releasePage(pTrunk);
42635  releasePage(pPrevTrunk);
42636  if( rc==SQLITE_OK ){
42637    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
42638      releasePage(*ppPage);
42639      return SQLITE_CORRUPT_BKPT;
42640    }
42641    (*ppPage)->isInit = 0;
42642  }else{
42643    *ppPage = 0;
42644  }
42645  return rc;
42646}
42647
42648/*
42649** This function is used to add page iPage to the database file free-list.
42650** It is assumed that the page is not already a part of the free-list.
42651**
42652** The value passed as the second argument to this function is optional.
42653** If the caller happens to have a pointer to the MemPage object
42654** corresponding to page iPage handy, it may pass it as the second value.
42655** Otherwise, it may pass NULL.
42656**
42657** If a pointer to a MemPage object is passed as the second argument,
42658** its reference count is not altered by this function.
42659*/
42660static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
42661  MemPage *pTrunk = 0;                /* Free-list trunk page */
42662  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
42663  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
42664  MemPage *pPage;                     /* Page being freed. May be NULL. */
42665  int rc;                             /* Return Code */
42666  int nFree;                          /* Initial number of pages on free-list */
42667
42668  assert( sqlite3_mutex_held(pBt->mutex) );
42669  assert( iPage>1 );
42670  assert( !pMemPage || pMemPage->pgno==iPage );
42671
42672  if( pMemPage ){
42673    pPage = pMemPage;
42674    sqlite3PagerRef(pPage->pDbPage);
42675  }else{
42676    pPage = btreePageLookup(pBt, iPage);
42677  }
42678
42679  /* Increment the free page count on pPage1 */
42680  rc = sqlite3PagerWrite(pPage1->pDbPage);
42681  if( rc ) goto freepage_out;
42682  nFree = get4byte(&pPage1->aData[36]);
42683  put4byte(&pPage1->aData[36], nFree+1);
42684
42685#ifdef SQLITE_SECURE_DELETE
42686  /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
42687  ** always fully overwrite deleted information with zeros.
42688  */
42689  if( (!pPage && (rc = btreeGetPage(pBt, iPage, &pPage, 0)))
42690   ||            (rc = sqlite3PagerWrite(pPage->pDbPage))
42691  ){
42692    goto freepage_out;
42693  }
42694  memset(pPage->aData, 0, pPage->pBt->pageSize);
42695#endif
42696
42697  /* If the database supports auto-vacuum, write an entry in the pointer-map
42698  ** to indicate that the page is free.
42699  */
42700  if( ISAUTOVACUUM ){
42701    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
42702    if( rc ) goto freepage_out;
42703  }
42704
42705  /* Now manipulate the actual database free-list structure. There are two
42706  ** possibilities. If the free-list is currently empty, or if the first
42707  ** trunk page in the free-list is full, then this page will become a
42708  ** new free-list trunk page. Otherwise, it will become a leaf of the
42709  ** first trunk page in the current free-list. This block tests if it
42710  ** is possible to add the page as a new free-list leaf.
42711  */
42712  if( nFree!=0 ){
42713    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
42714
42715    iTrunk = get4byte(&pPage1->aData[32]);
42716    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
42717    if( rc!=SQLITE_OK ){
42718      goto freepage_out;
42719    }
42720
42721    nLeaf = get4byte(&pTrunk->aData[4]);
42722    assert( pBt->usableSize>32 );
42723    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
42724      rc = SQLITE_CORRUPT_BKPT;
42725      goto freepage_out;
42726    }
42727    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
42728      /* In this case there is room on the trunk page to insert the page
42729      ** being freed as a new leaf.
42730      **
42731      ** Note that the trunk page is not really full until it contains
42732      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
42733      ** coded.  But due to a coding error in versions of SQLite prior to
42734      ** 3.6.0, databases with freelist trunk pages holding more than
42735      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
42736      ** to maintain backwards compatibility with older versions of SQLite,
42737      ** we will continue to restrict the number of entries to usableSize/4 - 8
42738      ** for now.  At some point in the future (once everyone has upgraded
42739      ** to 3.6.0 or later) we should consider fixing the conditional above
42740      ** to read "usableSize/4-2" instead of "usableSize/4-8".
42741      */
42742      rc = sqlite3PagerWrite(pTrunk->pDbPage);
42743      if( rc==SQLITE_OK ){
42744        put4byte(&pTrunk->aData[4], nLeaf+1);
42745        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
42746#ifndef SQLITE_SECURE_DELETE
42747        if( pPage ){
42748          sqlite3PagerDontWrite(pPage->pDbPage);
42749        }
42750#endif
42751        rc = btreeSetHasContent(pBt, iPage);
42752      }
42753      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
42754      goto freepage_out;
42755    }
42756  }
42757
42758  /* If control flows to this point, then it was not possible to add the
42759  ** the page being freed as a leaf page of the first trunk in the free-list.
42760  ** Possibly because the free-list is empty, or possibly because the
42761  ** first trunk in the free-list is full. Either way, the page being freed
42762  ** will become the new first trunk page in the free-list.
42763  */
42764  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
42765    goto freepage_out;
42766  }
42767  rc = sqlite3PagerWrite(pPage->pDbPage);
42768  if( rc!=SQLITE_OK ){
42769    goto freepage_out;
42770  }
42771  put4byte(pPage->aData, iTrunk);
42772  put4byte(&pPage->aData[4], 0);
42773  put4byte(&pPage1->aData[32], iPage);
42774  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
42775
42776freepage_out:
42777  if( pPage ){
42778    pPage->isInit = 0;
42779  }
42780  releasePage(pPage);
42781  releasePage(pTrunk);
42782  return rc;
42783}
42784static void freePage(MemPage *pPage, int *pRC){
42785  if( (*pRC)==SQLITE_OK ){
42786    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
42787  }
42788}
42789
42790/*
42791** Free any overflow pages associated with the given Cell.
42792*/
42793static int clearCell(MemPage *pPage, unsigned char *pCell){
42794  BtShared *pBt = pPage->pBt;
42795  CellInfo info;
42796  Pgno ovflPgno;
42797  int rc;
42798  int nOvfl;
42799  u16 ovflPageSize;
42800
42801  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42802  btreeParseCellPtr(pPage, pCell, &info);
42803  if( info.iOverflow==0 ){
42804    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
42805  }
42806  ovflPgno = get4byte(&pCell[info.iOverflow]);
42807  assert( pBt->usableSize > 4 );
42808  ovflPageSize = pBt->usableSize - 4;
42809  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
42810  assert( ovflPgno==0 || nOvfl>0 );
42811  while( nOvfl-- ){
42812    Pgno iNext = 0;
42813    MemPage *pOvfl = 0;
42814    if( ovflPgno<2 || ovflPgno>pagerPagecount(pBt) ){
42815      /* 0 is not a legal page number and page 1 cannot be an
42816      ** overflow page. Therefore if ovflPgno<2 or past the end of the
42817      ** file the database must be corrupt. */
42818      return SQLITE_CORRUPT_BKPT;
42819    }
42820    if( nOvfl ){
42821      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
42822      if( rc ) return rc;
42823    }
42824    rc = freePage2(pBt, pOvfl, ovflPgno);
42825    if( pOvfl ){
42826      sqlite3PagerUnref(pOvfl->pDbPage);
42827    }
42828    if( rc ) return rc;
42829    ovflPgno = iNext;
42830  }
42831  return SQLITE_OK;
42832}
42833
42834/*
42835** Create the byte sequence used to represent a cell on page pPage
42836** and write that byte sequence into pCell[].  Overflow pages are
42837** allocated and filled in as necessary.  The calling procedure
42838** is responsible for making sure sufficient space has been allocated
42839** for pCell[].
42840**
42841** Note that pCell does not necessary need to point to the pPage->aData
42842** area.  pCell might point to some temporary storage.  The cell will
42843** be constructed in this temporary area then copied into pPage->aData
42844** later.
42845*/
42846static int fillInCell(
42847  MemPage *pPage,                /* The page that contains the cell */
42848  unsigned char *pCell,          /* Complete text of the cell */
42849  const void *pKey, i64 nKey,    /* The key */
42850  const void *pData,int nData,   /* The data */
42851  int nZero,                     /* Extra zero bytes to append to pData */
42852  int *pnSize                    /* Write cell size here */
42853){
42854  int nPayload;
42855  const u8 *pSrc;
42856  int nSrc, n, rc;
42857  int spaceLeft;
42858  MemPage *pOvfl = 0;
42859  MemPage *pToRelease = 0;
42860  unsigned char *pPrior;
42861  unsigned char *pPayload;
42862  BtShared *pBt = pPage->pBt;
42863  Pgno pgnoOvfl = 0;
42864  int nHeader;
42865  CellInfo info;
42866
42867  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42868
42869  /* pPage is not necessarily writeable since pCell might be auxiliary
42870  ** buffer space that is separate from the pPage buffer area */
42871  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
42872            || sqlite3PagerIswriteable(pPage->pDbPage) );
42873
42874  /* Fill in the header. */
42875  nHeader = 0;
42876  if( !pPage->leaf ){
42877    nHeader += 4;
42878  }
42879  if( pPage->hasData ){
42880    nHeader += putVarint(&pCell[nHeader], nData+nZero);
42881  }else{
42882    nData = nZero = 0;
42883  }
42884  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
42885  btreeParseCellPtr(pPage, pCell, &info);
42886  assert( info.nHeader==nHeader );
42887  assert( info.nKey==nKey );
42888  assert( info.nData==(u32)(nData+nZero) );
42889
42890  /* Fill in the payload */
42891  nPayload = nData + nZero;
42892  if( pPage->intKey ){
42893    pSrc = pData;
42894    nSrc = nData;
42895    nData = 0;
42896  }else{
42897    if( NEVER(nKey>0x7fffffff || pKey==0) ){
42898      return SQLITE_CORRUPT_BKPT;
42899    }
42900    nPayload += (int)nKey;
42901    pSrc = pKey;
42902    nSrc = (int)nKey;
42903  }
42904  *pnSize = info.nSize;
42905  spaceLeft = info.nLocal;
42906  pPayload = &pCell[nHeader];
42907  pPrior = &pCell[info.iOverflow];
42908
42909  while( nPayload>0 ){
42910    if( spaceLeft==0 ){
42911#ifndef SQLITE_OMIT_AUTOVACUUM
42912      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
42913      if( pBt->autoVacuum ){
42914        do{
42915          pgnoOvfl++;
42916        } while(
42917          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
42918        );
42919      }
42920#endif
42921      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
42922#ifndef SQLITE_OMIT_AUTOVACUUM
42923      /* If the database supports auto-vacuum, and the second or subsequent
42924      ** overflow page is being allocated, add an entry to the pointer-map
42925      ** for that page now.
42926      **
42927      ** If this is the first overflow page, then write a partial entry
42928      ** to the pointer-map. If we write nothing to this pointer-map slot,
42929      ** then the optimistic overflow chain processing in clearCell()
42930      ** may misinterpret the uninitialised values and delete the
42931      ** wrong pages from the database.
42932      */
42933      if( pBt->autoVacuum && rc==SQLITE_OK ){
42934        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
42935        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
42936        if( rc ){
42937          releasePage(pOvfl);
42938        }
42939      }
42940#endif
42941      if( rc ){
42942        releasePage(pToRelease);
42943        return rc;
42944      }
42945
42946      /* If pToRelease is not zero than pPrior points into the data area
42947      ** of pToRelease.  Make sure pToRelease is still writeable. */
42948      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
42949
42950      /* If pPrior is part of the data area of pPage, then make sure pPage
42951      ** is still writeable */
42952      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
42953            || sqlite3PagerIswriteable(pPage->pDbPage) );
42954
42955      put4byte(pPrior, pgnoOvfl);
42956      releasePage(pToRelease);
42957      pToRelease = pOvfl;
42958      pPrior = pOvfl->aData;
42959      put4byte(pPrior, 0);
42960      pPayload = &pOvfl->aData[4];
42961      spaceLeft = pBt->usableSize - 4;
42962    }
42963    n = nPayload;
42964    if( n>spaceLeft ) n = spaceLeft;
42965
42966    /* If pToRelease is not zero than pPayload points into the data area
42967    ** of pToRelease.  Make sure pToRelease is still writeable. */
42968    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
42969
42970    /* If pPayload is part of the data area of pPage, then make sure pPage
42971    ** is still writeable */
42972    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
42973            || sqlite3PagerIswriteable(pPage->pDbPage) );
42974
42975    if( nSrc>0 ){
42976      if( n>nSrc ) n = nSrc;
42977      assert( pSrc );
42978      memcpy(pPayload, pSrc, n);
42979    }else{
42980      memset(pPayload, 0, n);
42981    }
42982    nPayload -= n;
42983    pPayload += n;
42984    pSrc += n;
42985    nSrc -= n;
42986    spaceLeft -= n;
42987    if( nSrc==0 ){
42988      nSrc = nData;
42989      pSrc = pData;
42990    }
42991  }
42992  releasePage(pToRelease);
42993  return SQLITE_OK;
42994}
42995
42996/*
42997** Remove the i-th cell from pPage.  This routine effects pPage only.
42998** The cell content is not freed or deallocated.  It is assumed that
42999** the cell content has been copied someplace else.  This routine just
43000** removes the reference to the cell from pPage.
43001**
43002** "sz" must be the number of bytes in the cell.
43003*/
43004static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
43005  int i;          /* Loop counter */
43006  int pc;         /* Offset to cell content of cell being deleted */
43007  u8 *data;       /* pPage->aData */
43008  u8 *ptr;        /* Used to move bytes around within data[] */
43009  int rc;         /* The return code */
43010  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
43011
43012  if( *pRC ) return;
43013
43014  assert( idx>=0 && idx<pPage->nCell );
43015  assert( sz==cellSize(pPage, idx) );
43016  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
43017  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43018  data = pPage->aData;
43019  ptr = &data[pPage->cellOffset + 2*idx];
43020  pc = get2byte(ptr);
43021  hdr = pPage->hdrOffset;
43022  testcase( pc==get2byte(&data[hdr+5]) );
43023  testcase( pc+sz==pPage->pBt->usableSize );
43024  if( pc < get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
43025    *pRC = SQLITE_CORRUPT_BKPT;
43026    return;
43027  }
43028  rc = freeSpace(pPage, pc, sz);
43029  if( rc ){
43030    *pRC = rc;
43031    return;
43032  }
43033  for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
43034    ptr[0] = ptr[2];
43035    ptr[1] = ptr[3];
43036  }
43037  pPage->nCell--;
43038  put2byte(&data[hdr+3], pPage->nCell);
43039  pPage->nFree += 2;
43040}
43041
43042/*
43043** Insert a new cell on pPage at cell index "i".  pCell points to the
43044** content of the cell.
43045**
43046** If the cell content will fit on the page, then put it there.  If it
43047** will not fit, then make a copy of the cell content into pTemp if
43048** pTemp is not null.  Regardless of pTemp, allocate a new entry
43049** in pPage->aOvfl[] and make it point to the cell content (either
43050** in pTemp or the original pCell) and also record its index.
43051** Allocating a new entry in pPage->aCell[] implies that
43052** pPage->nOverflow is incremented.
43053**
43054** If nSkip is non-zero, then do not copy the first nSkip bytes of the
43055** cell. The caller will overwrite them after this function returns. If
43056** nSkip is non-zero, then pCell may not point to an invalid memory location
43057** (but pCell+nSkip is always valid).
43058*/
43059static void insertCell(
43060  MemPage *pPage,   /* Page into which we are copying */
43061  int i,            /* New cell becomes the i-th cell of the page */
43062  u8 *pCell,        /* Content of the new cell */
43063  int sz,           /* Bytes of content in pCell */
43064  u8 *pTemp,        /* Temp storage space for pCell, if needed */
43065  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
43066  int *pRC          /* Read and write return code from here */
43067){
43068  int idx;          /* Where to write new cell content in data[] */
43069  int j;            /* Loop counter */
43070  int end;          /* First byte past the last cell pointer in data[] */
43071  int ins;          /* Index in data[] where new cell pointer is inserted */
43072  int cellOffset;   /* Address of first cell pointer in data[] */
43073  u8 *data;         /* The content of the whole page */
43074  u8 *ptr;          /* Used for moving information around in data[] */
43075
43076  int nSkip = (iChild ? 4 : 0);
43077
43078  if( *pRC ) return;
43079
43080  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
43081  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
43082  assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
43083  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43084  /* The cell should normally be sized correctly.  However, when moving a
43085  ** malformed cell from a leaf page to an interior page, if the cell size
43086  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
43087  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
43088  ** the term after the || in the following assert(). */
43089  assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
43090  if( pPage->nOverflow || sz+2>pPage->nFree ){
43091    if( pTemp ){
43092      memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
43093      pCell = pTemp;
43094    }
43095    if( iChild ){
43096      put4byte(pCell, iChild);
43097    }
43098    j = pPage->nOverflow++;
43099    assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
43100    pPage->aOvfl[j].pCell = pCell;
43101    pPage->aOvfl[j].idx = (u16)i;
43102  }else{
43103    int rc = sqlite3PagerWrite(pPage->pDbPage);
43104    if( rc!=SQLITE_OK ){
43105      *pRC = rc;
43106      return;
43107    }
43108    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
43109    data = pPage->aData;
43110    cellOffset = pPage->cellOffset;
43111    end = cellOffset + 2*pPage->nCell;
43112    ins = cellOffset + 2*i;
43113    rc = allocateSpace(pPage, sz, &idx);
43114    if( rc ){ *pRC = rc; return; }
43115    /* The allocateSpace() routine guarantees the following two properties
43116    ** if it returns success */
43117    assert( idx >= end+2 );
43118    assert( idx+sz <= pPage->pBt->usableSize );
43119    pPage->nCell++;
43120    pPage->nFree -= (u16)(2 + sz);
43121    memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
43122    if( iChild ){
43123      put4byte(&data[idx], iChild);
43124    }
43125    for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
43126      ptr[0] = ptr[-2];
43127      ptr[1] = ptr[-1];
43128    }
43129    put2byte(&data[ins], idx);
43130    put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
43131#ifndef SQLITE_OMIT_AUTOVACUUM
43132    if( pPage->pBt->autoVacuum ){
43133      /* The cell may contain a pointer to an overflow page. If so, write
43134      ** the entry for the overflow page into the pointer map.
43135      */
43136      ptrmapPutOvflPtr(pPage, pCell, pRC);
43137    }
43138#endif
43139  }
43140}
43141
43142/*
43143** Add a list of cells to a page.  The page should be initially empty.
43144** The cells are guaranteed to fit on the page.
43145*/
43146static void assemblePage(
43147  MemPage *pPage,   /* The page to be assemblied */
43148  int nCell,        /* The number of cells to add to this page */
43149  u8 **apCell,      /* Pointers to cell bodies */
43150  u16 *aSize        /* Sizes of the cells */
43151){
43152  int i;            /* Loop counter */
43153  u8 *pCellptr;     /* Address of next cell pointer */
43154  int cellbody;     /* Address of next cell body */
43155  u8 * const data = pPage->aData;             /* Pointer to data for pPage */
43156  const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
43157  const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
43158
43159  assert( pPage->nOverflow==0 );
43160  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43161  assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
43162  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
43163
43164  /* Check that the page has just been zeroed by zeroPage() */
43165  assert( pPage->nCell==0 );
43166  assert( get2byte(&data[hdr+5])==nUsable );
43167
43168  pCellptr = &data[pPage->cellOffset + nCell*2];
43169  cellbody = nUsable;
43170  for(i=nCell-1; i>=0; i--){
43171    pCellptr -= 2;
43172    cellbody -= aSize[i];
43173    put2byte(pCellptr, cellbody);
43174    memcpy(&data[cellbody], apCell[i], aSize[i]);
43175  }
43176  put2byte(&data[hdr+3], nCell);
43177  put2byte(&data[hdr+5], cellbody);
43178  pPage->nFree -= (nCell*2 + nUsable - cellbody);
43179  pPage->nCell = (u16)nCell;
43180}
43181
43182/*
43183** The following parameters determine how many adjacent pages get involved
43184** in a balancing operation.  NN is the number of neighbors on either side
43185** of the page that participate in the balancing operation.  NB is the
43186** total number of pages that participate, including the target page and
43187** NN neighbors on either side.
43188**
43189** The minimum value of NN is 1 (of course).  Increasing NN above 1
43190** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
43191** in exchange for a larger degradation in INSERT and UPDATE performance.
43192** The value of NN appears to give the best results overall.
43193*/
43194#define NN 1             /* Number of neighbors on either side of pPage */
43195#define NB (NN*2+1)      /* Total pages involved in the balance */
43196
43197
43198#ifndef SQLITE_OMIT_QUICKBALANCE
43199/*
43200** This version of balance() handles the common special case where
43201** a new entry is being inserted on the extreme right-end of the
43202** tree, in other words, when the new entry will become the largest
43203** entry in the tree.
43204**
43205** Instead of trying to balance the 3 right-most leaf pages, just add
43206** a new page to the right-hand side and put the one new entry in
43207** that page.  This leaves the right side of the tree somewhat
43208** unbalanced.  But odds are that we will be inserting new entries
43209** at the end soon afterwards so the nearly empty page will quickly
43210** fill up.  On average.
43211**
43212** pPage is the leaf page which is the right-most page in the tree.
43213** pParent is its parent.  pPage must have a single overflow entry
43214** which is also the right-most entry on the page.
43215**
43216** The pSpace buffer is used to store a temporary copy of the divider
43217** cell that will be inserted into pParent. Such a cell consists of a 4
43218** byte page number followed by a variable length integer. In other
43219** words, at most 13 bytes. Hence the pSpace buffer must be at
43220** least 13 bytes in size.
43221*/
43222static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
43223  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
43224  MemPage *pNew;                       /* Newly allocated page */
43225  int rc;                              /* Return Code */
43226  Pgno pgnoNew;                        /* Page number of pNew */
43227
43228  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43229  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43230  assert( pPage->nOverflow==1 );
43231
43232  if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
43233
43234  /* Allocate a new page. This page will become the right-sibling of
43235  ** pPage. Make the parent page writable, so that the new divider cell
43236  ** may be inserted. If both these operations are successful, proceed.
43237  */
43238  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
43239
43240  if( rc==SQLITE_OK ){
43241
43242    u8 *pOut = &pSpace[4];
43243    u8 *pCell = pPage->aOvfl[0].pCell;
43244    u16 szCell = cellSizePtr(pPage, pCell);
43245    u8 *pStop;
43246
43247    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
43248    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
43249    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
43250    assemblePage(pNew, 1, &pCell, &szCell);
43251
43252    /* If this is an auto-vacuum database, update the pointer map
43253    ** with entries for the new page, and any pointer from the
43254    ** cell on the page to an overflow page. If either of these
43255    ** operations fails, the return code is set, but the contents
43256    ** of the parent page are still manipulated by thh code below.
43257    ** That is Ok, at this point the parent page is guaranteed to
43258    ** be marked as dirty. Returning an error code will cause a
43259    ** rollback, undoing any changes made to the parent page.
43260    */
43261    if( ISAUTOVACUUM ){
43262      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
43263      if( szCell>pNew->minLocal ){
43264        ptrmapPutOvflPtr(pNew, pCell, &rc);
43265      }
43266    }
43267
43268    /* Create a divider cell to insert into pParent. The divider cell
43269    ** consists of a 4-byte page number (the page number of pPage) and
43270    ** a variable length key value (which must be the same value as the
43271    ** largest key on pPage).
43272    **
43273    ** To find the largest key value on pPage, first find the right-most
43274    ** cell on pPage. The first two fields of this cell are the
43275    ** record-length (a variable length integer at most 32-bits in size)
43276    ** and the key value (a variable length integer, may have any value).
43277    ** The first of the while(...) loops below skips over the record-length
43278    ** field. The second while(...) loop copies the key value from the
43279    ** cell on pPage into the pSpace buffer.
43280    */
43281    pCell = findCell(pPage, pPage->nCell-1);
43282    pStop = &pCell[9];
43283    while( (*(pCell++)&0x80) && pCell<pStop );
43284    pStop = &pCell[9];
43285    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
43286
43287    /* Insert the new divider cell into pParent. */
43288    insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
43289               0, pPage->pgno, &rc);
43290
43291    /* Set the right-child pointer of pParent to point to the new page. */
43292    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
43293
43294    /* Release the reference to the new page. */
43295    releasePage(pNew);
43296  }
43297
43298  return rc;
43299}
43300#endif /* SQLITE_OMIT_QUICKBALANCE */
43301
43302#if 0
43303/*
43304** This function does not contribute anything to the operation of SQLite.
43305** it is sometimes activated temporarily while debugging code responsible
43306** for setting pointer-map entries.
43307*/
43308static int ptrmapCheckPages(MemPage **apPage, int nPage){
43309  int i, j;
43310  for(i=0; i<nPage; i++){
43311    Pgno n;
43312    u8 e;
43313    MemPage *pPage = apPage[i];
43314    BtShared *pBt = pPage->pBt;
43315    assert( pPage->isInit );
43316
43317    for(j=0; j<pPage->nCell; j++){
43318      CellInfo info;
43319      u8 *z;
43320
43321      z = findCell(pPage, j);
43322      btreeParseCellPtr(pPage, z, &info);
43323      if( info.iOverflow ){
43324        Pgno ovfl = get4byte(&z[info.iOverflow]);
43325        ptrmapGet(pBt, ovfl, &e, &n);
43326        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
43327      }
43328      if( !pPage->leaf ){
43329        Pgno child = get4byte(z);
43330        ptrmapGet(pBt, child, &e, &n);
43331        assert( n==pPage->pgno && e==PTRMAP_BTREE );
43332      }
43333    }
43334    if( !pPage->leaf ){
43335      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
43336      ptrmapGet(pBt, child, &e, &n);
43337      assert( n==pPage->pgno && e==PTRMAP_BTREE );
43338    }
43339  }
43340  return 1;
43341}
43342#endif
43343
43344/*
43345** This function is used to copy the contents of the b-tree node stored
43346** on page pFrom to page pTo. If page pFrom was not a leaf page, then
43347** the pointer-map entries for each child page are updated so that the
43348** parent page stored in the pointer map is page pTo. If pFrom contained
43349** any cells with overflow page pointers, then the corresponding pointer
43350** map entries are also updated so that the parent page is page pTo.
43351**
43352** If pFrom is currently carrying any overflow cells (entries in the
43353** MemPage.aOvfl[] array), they are not copied to pTo.
43354**
43355** Before returning, page pTo is reinitialized using btreeInitPage().
43356**
43357** The performance of this function is not critical. It is only used by
43358** the balance_shallower() and balance_deeper() procedures, neither of
43359** which are called often under normal circumstances.
43360*/
43361static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
43362  if( (*pRC)==SQLITE_OK ){
43363    BtShared * const pBt = pFrom->pBt;
43364    u8 * const aFrom = pFrom->aData;
43365    u8 * const aTo = pTo->aData;
43366    int const iFromHdr = pFrom->hdrOffset;
43367    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
43368    int rc;
43369    int iData;
43370
43371
43372    assert( pFrom->isInit );
43373    assert( pFrom->nFree>=iToHdr );
43374    assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
43375
43376    /* Copy the b-tree node content from page pFrom to page pTo. */
43377    iData = get2byte(&aFrom[iFromHdr+5]);
43378    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
43379    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
43380
43381    /* Reinitialize page pTo so that the contents of the MemPage structure
43382    ** match the new data. The initialization of pTo can actually fail under
43383    ** fairly obscure circumstances, even though it is a copy of initialized
43384    ** page pFrom.
43385    */
43386    pTo->isInit = 0;
43387    rc = btreeInitPage(pTo);
43388    if( rc!=SQLITE_OK ){
43389      *pRC = rc;
43390      return;
43391    }
43392
43393    /* If this is an auto-vacuum database, update the pointer-map entries
43394    ** for any b-tree or overflow pages that pTo now contains the pointers to.
43395    */
43396    if( ISAUTOVACUUM ){
43397      *pRC = setChildPtrmaps(pTo);
43398    }
43399  }
43400}
43401
43402/*
43403** This routine redistributes cells on the iParentIdx'th child of pParent
43404** (hereafter "the page") and up to 2 siblings so that all pages have about the
43405** same amount of free space. Usually a single sibling on either side of the
43406** page are used in the balancing, though both siblings might come from one
43407** side if the page is the first or last child of its parent. If the page
43408** has fewer than 2 siblings (something which can only happen if the page
43409** is a root page or a child of a root page) then all available siblings
43410** participate in the balancing.
43411**
43412** The number of siblings of the page might be increased or decreased by
43413** one or two in an effort to keep pages nearly full but not over full.
43414**
43415** Note that when this routine is called, some of the cells on the page
43416** might not actually be stored in MemPage.aData[]. This can happen
43417** if the page is overfull. This routine ensures that all cells allocated
43418** to the page and its siblings fit into MemPage.aData[] before returning.
43419**
43420** In the course of balancing the page and its siblings, cells may be
43421** inserted into or removed from the parent page (pParent). Doing so
43422** may cause the parent page to become overfull or underfull. If this
43423** happens, it is the responsibility of the caller to invoke the correct
43424** balancing routine to fix this problem (see the balance() routine).
43425**
43426** If this routine fails for any reason, it might leave the database
43427** in a corrupted state. So if this routine fails, the database should
43428** be rolled back.
43429**
43430** The third argument to this function, aOvflSpace, is a pointer to a
43431** buffer big enough to hold one page. If while inserting cells into the parent
43432** page (pParent) the parent page becomes overfull, this buffer is
43433** used to store the parent's overflow cells. Because this function inserts
43434** a maximum of four divider cells into the parent page, and the maximum
43435** size of a cell stored within an internal node is always less than 1/4
43436** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
43437** enough for all overflow cells.
43438**
43439** If aOvflSpace is set to a null pointer, this function returns
43440** SQLITE_NOMEM.
43441*/
43442static int balance_nonroot(
43443  MemPage *pParent,               /* Parent page of siblings being balanced */
43444  int iParentIdx,                 /* Index of "the page" in pParent */
43445  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
43446  int isRoot                      /* True if pParent is a root-page */
43447){
43448  BtShared *pBt;               /* The whole database */
43449  int nCell = 0;               /* Number of cells in apCell[] */
43450  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
43451  int nNew = 0;                /* Number of pages in apNew[] */
43452  int nOld;                    /* Number of pages in apOld[] */
43453  int i, j, k;                 /* Loop counters */
43454  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
43455  int rc = SQLITE_OK;          /* The return code */
43456  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
43457  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
43458  int usableSpace;             /* Bytes in pPage beyond the header */
43459  int pageFlags;               /* Value of pPage->aData[0] */
43460  int subtotal;                /* Subtotal of bytes in cells on one page */
43461  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
43462  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
43463  int szScratch;               /* Size of scratch memory requested */
43464  MemPage *apOld[NB];          /* pPage and up to two siblings */
43465  MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
43466  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
43467  u8 *pRight;                  /* Location in parent of right-sibling pointer */
43468  u8 *apDiv[NB-1];             /* Divider cells in pParent */
43469  int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
43470  int szNew[NB+2];             /* Combined size of cells place on i-th page */
43471  u8 **apCell = 0;             /* All cells begin balanced */
43472  u16 *szCell;                 /* Local size of all cells in apCell[] */
43473  u8 *aSpace1;                 /* Space for copies of dividers cells */
43474  Pgno pgno;                   /* Temp var to store a page number in */
43475
43476  pBt = pParent->pBt;
43477  assert( sqlite3_mutex_held(pBt->mutex) );
43478  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43479
43480#if 0
43481  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
43482#endif
43483
43484  /* At this point pParent may have at most one overflow cell. And if
43485  ** this overflow cell is present, it must be the cell with
43486  ** index iParentIdx. This scenario comes about when this function
43487  ** is called (indirectly) from sqlite3BtreeDelete().
43488  */
43489  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
43490  assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
43491
43492  if( !aOvflSpace ){
43493    return SQLITE_NOMEM;
43494  }
43495
43496  /* Find the sibling pages to balance. Also locate the cells in pParent
43497  ** that divide the siblings. An attempt is made to find NN siblings on
43498  ** either side of pPage. More siblings are taken from one side, however,
43499  ** if there are fewer than NN siblings on the other side. If pParent
43500  ** has NB or fewer children then all children of pParent are taken.
43501  **
43502  ** This loop also drops the divider cells from the parent page. This
43503  ** way, the remainder of the function does not have to deal with any
43504  ** overflow cells in the parent page, since if any existed they will
43505  ** have already been removed.
43506  */
43507  i = pParent->nOverflow + pParent->nCell;
43508  if( i<2 ){
43509    nxDiv = 0;
43510    nOld = i+1;
43511  }else{
43512    nOld = 3;
43513    if( iParentIdx==0 ){
43514      nxDiv = 0;
43515    }else if( iParentIdx==i ){
43516      nxDiv = i-2;
43517    }else{
43518      nxDiv = iParentIdx-1;
43519    }
43520    i = 2;
43521  }
43522  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
43523    pRight = &pParent->aData[pParent->hdrOffset+8];
43524  }else{
43525    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
43526  }
43527  pgno = get4byte(pRight);
43528  while( 1 ){
43529    rc = getAndInitPage(pBt, pgno, &apOld[i]);
43530    if( rc ){
43531      memset(apOld, 0, (i+1)*sizeof(MemPage*));
43532      goto balance_cleanup;
43533    }
43534    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
43535    if( (i--)==0 ) break;
43536
43537    if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
43538      apDiv[i] = pParent->aOvfl[0].pCell;
43539      pgno = get4byte(apDiv[i]);
43540      szNew[i] = cellSizePtr(pParent, apDiv[i]);
43541      pParent->nOverflow = 0;
43542    }else{
43543      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
43544      pgno = get4byte(apDiv[i]);
43545      szNew[i] = cellSizePtr(pParent, apDiv[i]);
43546
43547      /* Drop the cell from the parent page. apDiv[i] still points to
43548      ** the cell within the parent, even though it has been dropped.
43549      ** This is safe because dropping a cell only overwrites the first
43550      ** four bytes of it, and this function does not need the first
43551      ** four bytes of the divider cell. So the pointer is safe to use
43552      ** later on.
43553      **
43554      ** Unless SQLite is compiled in secure-delete mode. In this case,
43555      ** the dropCell() routine will overwrite the entire cell with zeroes.
43556      ** In this case, temporarily copy the cell into the aOvflSpace[]
43557      ** buffer. It will be copied out again as soon as the aSpace[] buffer
43558      ** is allocated.  */
43559#ifdef SQLITE_SECURE_DELETE
43560      memcpy(&aOvflSpace[apDiv[i]-pParent->aData], apDiv[i], szNew[i]);
43561      apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
43562#endif
43563      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
43564    }
43565  }
43566
43567  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
43568  ** alignment */
43569  nMaxCells = (nMaxCells + 3)&~3;
43570
43571  /*
43572  ** Allocate space for memory structures
43573  */
43574  k = pBt->pageSize + ROUND8(sizeof(MemPage));
43575  szScratch =
43576       nMaxCells*sizeof(u8*)                       /* apCell */
43577     + nMaxCells*sizeof(u16)                       /* szCell */
43578     + pBt->pageSize                               /* aSpace1 */
43579     + k*nOld;                                     /* Page copies (apCopy) */
43580  apCell = sqlite3ScratchMalloc( szScratch );
43581  if( apCell==0 ){
43582    rc = SQLITE_NOMEM;
43583    goto balance_cleanup;
43584  }
43585  szCell = (u16*)&apCell[nMaxCells];
43586  aSpace1 = (u8*)&szCell[nMaxCells];
43587  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
43588
43589  /*
43590  ** Load pointers to all cells on sibling pages and the divider cells
43591  ** into the local apCell[] array.  Make copies of the divider cells
43592  ** into space obtained from aSpace1[] and remove the the divider Cells
43593  ** from pParent.
43594  **
43595  ** If the siblings are on leaf pages, then the child pointers of the
43596  ** divider cells are stripped from the cells before they are copied
43597  ** into aSpace1[].  In this way, all cells in apCell[] are without
43598  ** child pointers.  If siblings are not leaves, then all cell in
43599  ** apCell[] include child pointers.  Either way, all cells in apCell[]
43600  ** are alike.
43601  **
43602  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
43603  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
43604  */
43605  leafCorrection = apOld[0]->leaf*4;
43606  leafData = apOld[0]->hasData;
43607  for(i=0; i<nOld; i++){
43608    int limit;
43609
43610    /* Before doing anything else, take a copy of the i'th original sibling
43611    ** The rest of this function will use data from the copies rather
43612    ** that the original pages since the original pages will be in the
43613    ** process of being overwritten.  */
43614    MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
43615    memcpy(pOld, apOld[i], sizeof(MemPage));
43616    pOld->aData = (void*)&pOld[1];
43617    memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
43618
43619    limit = pOld->nCell+pOld->nOverflow;
43620    for(j=0; j<limit; j++){
43621      assert( nCell<nMaxCells );
43622      apCell[nCell] = findOverflowCell(pOld, j);
43623      szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
43624      nCell++;
43625    }
43626    if( i<nOld-1 && !leafData){
43627      u16 sz = (u16)szNew[i];
43628      u8 *pTemp;
43629      assert( nCell<nMaxCells );
43630      szCell[nCell] = sz;
43631      pTemp = &aSpace1[iSpace1];
43632      iSpace1 += sz;
43633      assert( sz<=pBt->pageSize/4 );
43634      assert( iSpace1<=pBt->pageSize );
43635      memcpy(pTemp, apDiv[i], sz);
43636      apCell[nCell] = pTemp+leafCorrection;
43637      assert( leafCorrection==0 || leafCorrection==4 );
43638      szCell[nCell] = szCell[nCell] - leafCorrection;
43639      if( !pOld->leaf ){
43640        assert( leafCorrection==0 );
43641        assert( pOld->hdrOffset==0 );
43642        /* The right pointer of the child page pOld becomes the left
43643        ** pointer of the divider cell */
43644        memcpy(apCell[nCell], &pOld->aData[8], 4);
43645      }else{
43646        assert( leafCorrection==4 );
43647        if( szCell[nCell]<4 ){
43648          /* Do not allow any cells smaller than 4 bytes. */
43649          szCell[nCell] = 4;
43650        }
43651      }
43652      nCell++;
43653    }
43654  }
43655
43656  /*
43657  ** Figure out the number of pages needed to hold all nCell cells.
43658  ** Store this number in "k".  Also compute szNew[] which is the total
43659  ** size of all cells on the i-th page and cntNew[] which is the index
43660  ** in apCell[] of the cell that divides page i from page i+1.
43661  ** cntNew[k] should equal nCell.
43662  **
43663  ** Values computed by this block:
43664  **
43665  **           k: The total number of sibling pages
43666  **    szNew[i]: Spaced used on the i-th sibling page.
43667  **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
43668  **              the right of the i-th sibling page.
43669  ** usableSpace: Number of bytes of space available on each sibling.
43670  **
43671  */
43672  usableSpace = pBt->usableSize - 12 + leafCorrection;
43673  for(subtotal=k=i=0; i<nCell; i++){
43674    assert( i<nMaxCells );
43675    subtotal += szCell[i] + 2;
43676    if( subtotal > usableSpace ){
43677      szNew[k] = subtotal - szCell[i];
43678      cntNew[k] = i;
43679      if( leafData ){ i--; }
43680      subtotal = 0;
43681      k++;
43682      if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
43683    }
43684  }
43685  szNew[k] = subtotal;
43686  cntNew[k] = nCell;
43687  k++;
43688
43689  /*
43690  ** The packing computed by the previous block is biased toward the siblings
43691  ** on the left side.  The left siblings are always nearly full, while the
43692  ** right-most sibling might be nearly empty.  This block of code attempts
43693  ** to adjust the packing of siblings to get a better balance.
43694  **
43695  ** This adjustment is more than an optimization.  The packing above might
43696  ** be so out of balance as to be illegal.  For example, the right-most
43697  ** sibling might be completely empty.  This adjustment is not optional.
43698  */
43699  for(i=k-1; i>0; i--){
43700    int szRight = szNew[i];  /* Size of sibling on the right */
43701    int szLeft = szNew[i-1]; /* Size of sibling on the left */
43702    int r;              /* Index of right-most cell in left sibling */
43703    int d;              /* Index of first cell to the left of right sibling */
43704
43705    r = cntNew[i-1] - 1;
43706    d = r + 1 - leafData;
43707    assert( d<nMaxCells );
43708    assert( r<nMaxCells );
43709    while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
43710      szRight += szCell[d] + 2;
43711      szLeft -= szCell[r] + 2;
43712      cntNew[i-1]--;
43713      r = cntNew[i-1] - 1;
43714      d = r + 1 - leafData;
43715    }
43716    szNew[i] = szRight;
43717    szNew[i-1] = szLeft;
43718  }
43719
43720  /* Either we found one or more cells (cntnew[0])>0) or pPage is
43721  ** a virtual root page.  A virtual root page is when the real root
43722  ** page is page 1 and we are the only child of that page.
43723  */
43724  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
43725
43726  TRACE(("BALANCE: old: %d %d %d  ",
43727    apOld[0]->pgno,
43728    nOld>=2 ? apOld[1]->pgno : 0,
43729    nOld>=3 ? apOld[2]->pgno : 0
43730  ));
43731
43732  /*
43733  ** Allocate k new pages.  Reuse old pages where possible.
43734  */
43735  if( apOld[0]->pgno<=1 ){
43736    rc = SQLITE_CORRUPT_BKPT;
43737    goto balance_cleanup;
43738  }
43739  pageFlags = apOld[0]->aData[0];
43740  for(i=0; i<k; i++){
43741    MemPage *pNew;
43742    if( i<nOld ){
43743      pNew = apNew[i] = apOld[i];
43744      apOld[i] = 0;
43745      rc = sqlite3PagerWrite(pNew->pDbPage);
43746      nNew++;
43747      if( rc ) goto balance_cleanup;
43748    }else{
43749      assert( i>0 );
43750      rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
43751      if( rc ) goto balance_cleanup;
43752      apNew[i] = pNew;
43753      nNew++;
43754
43755      /* Set the pointer-map entry for the new sibling page. */
43756      if( ISAUTOVACUUM ){
43757        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
43758        if( rc!=SQLITE_OK ){
43759          goto balance_cleanup;
43760        }
43761      }
43762    }
43763  }
43764
43765  /* Free any old pages that were not reused as new pages.
43766  */
43767  while( i<nOld ){
43768    freePage(apOld[i], &rc);
43769    if( rc ) goto balance_cleanup;
43770    releasePage(apOld[i]);
43771    apOld[i] = 0;
43772    i++;
43773  }
43774
43775  /*
43776  ** Put the new pages in accending order.  This helps to
43777  ** keep entries in the disk file in order so that a scan
43778  ** of the table is a linear scan through the file.  That
43779  ** in turn helps the operating system to deliver pages
43780  ** from the disk more rapidly.
43781  **
43782  ** An O(n^2) insertion sort algorithm is used, but since
43783  ** n is never more than NB (a small constant), that should
43784  ** not be a problem.
43785  **
43786  ** When NB==3, this one optimization makes the database
43787  ** about 25% faster for large insertions and deletions.
43788  */
43789  for(i=0; i<k-1; i++){
43790    int minV = apNew[i]->pgno;
43791    int minI = i;
43792    for(j=i+1; j<k; j++){
43793      if( apNew[j]->pgno<(unsigned)minV ){
43794        minI = j;
43795        minV = apNew[j]->pgno;
43796      }
43797    }
43798    if( minI>i ){
43799      int t;
43800      MemPage *pT;
43801      t = apNew[i]->pgno;
43802      pT = apNew[i];
43803      apNew[i] = apNew[minI];
43804      apNew[minI] = pT;
43805    }
43806  }
43807  TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
43808    apNew[0]->pgno, szNew[0],
43809    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
43810    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
43811    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
43812    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
43813
43814  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43815  put4byte(pRight, apNew[nNew-1]->pgno);
43816
43817  /*
43818  ** Evenly distribute the data in apCell[] across the new pages.
43819  ** Insert divider cells into pParent as necessary.
43820  */
43821  j = 0;
43822  for(i=0; i<nNew; i++){
43823    /* Assemble the new sibling page. */
43824    MemPage *pNew = apNew[i];
43825    assert( j<nMaxCells );
43826    zeroPage(pNew, pageFlags);
43827    assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
43828    assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
43829    assert( pNew->nOverflow==0 );
43830
43831    j = cntNew[i];
43832
43833    /* If the sibling page assembled above was not the right-most sibling,
43834    ** insert a divider cell into the parent page.
43835    */
43836    assert( i<nNew-1 || j==nCell );
43837    if( j<nCell ){
43838      u8 *pCell;
43839      u8 *pTemp;
43840      int sz;
43841
43842      assert( j<nMaxCells );
43843      pCell = apCell[j];
43844      sz = szCell[j] + leafCorrection;
43845      pTemp = &aOvflSpace[iOvflSpace];
43846      if( !pNew->leaf ){
43847        memcpy(&pNew->aData[8], pCell, 4);
43848      }else if( leafData ){
43849        /* If the tree is a leaf-data tree, and the siblings are leaves,
43850        ** then there is no divider cell in apCell[]. Instead, the divider
43851        ** cell consists of the integer key for the right-most cell of
43852        ** the sibling-page assembled above only.
43853        */
43854        CellInfo info;
43855        j--;
43856        btreeParseCellPtr(pNew, apCell[j], &info);
43857        pCell = pTemp;
43858        sz = 4 + putVarint(&pCell[4], info.nKey);
43859        pTemp = 0;
43860      }else{
43861        pCell -= 4;
43862        /* Obscure case for non-leaf-data trees: If the cell at pCell was
43863        ** previously stored on a leaf node, and its reported size was 4
43864        ** bytes, then it may actually be smaller than this
43865        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
43866        ** any cell). But it is important to pass the correct size to
43867        ** insertCell(), so reparse the cell now.
43868        **
43869        ** Note that this can never happen in an SQLite data file, as all
43870        ** cells are at least 4 bytes. It only happens in b-trees used
43871        ** to evaluate "IN (SELECT ...)" and similar clauses.
43872        */
43873        if( szCell[j]==4 ){
43874          assert(leafCorrection==4);
43875          sz = cellSizePtr(pParent, pCell);
43876        }
43877      }
43878      iOvflSpace += sz;
43879      assert( sz<=pBt->pageSize/4 );
43880      assert( iOvflSpace<=pBt->pageSize );
43881      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
43882      if( rc!=SQLITE_OK ) goto balance_cleanup;
43883      assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43884
43885      j++;
43886      nxDiv++;
43887    }
43888  }
43889  assert( j==nCell );
43890  assert( nOld>0 );
43891  assert( nNew>0 );
43892  if( (pageFlags & PTF_LEAF)==0 ){
43893    u8 *zChild = &apCopy[nOld-1]->aData[8];
43894    memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
43895  }
43896
43897  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
43898    /* The root page of the b-tree now contains no cells. The only sibling
43899    ** page is the right-child of the parent. Copy the contents of the
43900    ** child page into the parent, decreasing the overall height of the
43901    ** b-tree structure by one. This is described as the "balance-shallower"
43902    ** sub-algorithm in some documentation.
43903    **
43904    ** If this is an auto-vacuum database, the call to copyNodeContent()
43905    ** sets all pointer-map entries corresponding to database image pages
43906    ** for which the pointer is stored within the content being copied.
43907    **
43908    ** The second assert below verifies that the child page is defragmented
43909    ** (it must be, as it was just reconstructed using assemblePage()). This
43910    ** is important if the parent page happens to be page 1 of the database
43911    ** image.  */
43912    assert( nNew==1 );
43913    assert( apNew[0]->nFree ==
43914        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
43915    );
43916    copyNodeContent(apNew[0], pParent, &rc);
43917    freePage(apNew[0], &rc);
43918  }else if( ISAUTOVACUUM ){
43919    /* Fix the pointer-map entries for all the cells that were shifted around.
43920    ** There are several different types of pointer-map entries that need to
43921    ** be dealt with by this routine. Some of these have been set already, but
43922    ** many have not. The following is a summary:
43923    **
43924    **   1) The entries associated with new sibling pages that were not
43925    **      siblings when this function was called. These have already
43926    **      been set. We don't need to worry about old siblings that were
43927    **      moved to the free-list - the freePage() code has taken care
43928    **      of those.
43929    **
43930    **   2) The pointer-map entries associated with the first overflow
43931    **      page in any overflow chains used by new divider cells. These
43932    **      have also already been taken care of by the insertCell() code.
43933    **
43934    **   3) If the sibling pages are not leaves, then the child pages of
43935    **      cells stored on the sibling pages may need to be updated.
43936    **
43937    **   4) If the sibling pages are not internal intkey nodes, then any
43938    **      overflow pages used by these cells may need to be updated
43939    **      (internal intkey nodes never contain pointers to overflow pages).
43940    **
43941    **   5) If the sibling pages are not leaves, then the pointer-map
43942    **      entries for the right-child pages of each sibling may need
43943    **      to be updated.
43944    **
43945    ** Cases 1 and 2 are dealt with above by other code. The next
43946    ** block deals with cases 3 and 4 and the one after that, case 5. Since
43947    ** setting a pointer map entry is a relatively expensive operation, this
43948    ** code only sets pointer map entries for child or overflow pages that have
43949    ** actually moved between pages.  */
43950    MemPage *pNew = apNew[0];
43951    MemPage *pOld = apCopy[0];
43952    int nOverflow = pOld->nOverflow;
43953    int iNextOld = pOld->nCell + nOverflow;
43954    int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
43955    j = 0;                             /* Current 'old' sibling page */
43956    k = 0;                             /* Current 'new' sibling page */
43957    for(i=0; i<nCell; i++){
43958      int isDivider = 0;
43959      while( i==iNextOld ){
43960        /* Cell i is the cell immediately following the last cell on old
43961        ** sibling page j. If the siblings are not leaf pages of an
43962        ** intkey b-tree, then cell i was a divider cell. */
43963        pOld = apCopy[++j];
43964        iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
43965        if( pOld->nOverflow ){
43966          nOverflow = pOld->nOverflow;
43967          iOverflow = i + !leafData + pOld->aOvfl[0].idx;
43968        }
43969        isDivider = !leafData;
43970      }
43971
43972      assert(nOverflow>0 || iOverflow<i );
43973      assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
43974      assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
43975      if( i==iOverflow ){
43976        isDivider = 1;
43977        if( (--nOverflow)>0 ){
43978          iOverflow++;
43979        }
43980      }
43981
43982      if( i==cntNew[k] ){
43983        /* Cell i is the cell immediately following the last cell on new
43984        ** sibling page k. If the siblings are not leaf pages of an
43985        ** intkey b-tree, then cell i is a divider cell.  */
43986        pNew = apNew[++k];
43987        if( !leafData ) continue;
43988      }
43989      assert( j<nOld );
43990      assert( k<nNew );
43991
43992      /* If the cell was originally divider cell (and is not now) or
43993      ** an overflow cell, or if the cell was located on a different sibling
43994      ** page before the balancing, then the pointer map entries associated
43995      ** with any child or overflow pages need to be updated.  */
43996      if( isDivider || pOld->pgno!=pNew->pgno ){
43997        if( !leafCorrection ){
43998          ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
43999        }
44000        if( szCell[i]>pNew->minLocal ){
44001          ptrmapPutOvflPtr(pNew, apCell[i], &rc);
44002        }
44003      }
44004    }
44005
44006    if( !leafCorrection ){
44007      for(i=0; i<nNew; i++){
44008        u32 key = get4byte(&apNew[i]->aData[8]);
44009        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
44010      }
44011    }
44012
44013#if 0
44014    /* The ptrmapCheckPages() contains assert() statements that verify that
44015    ** all pointer map pages are set correctly. This is helpful while
44016    ** debugging. This is usually disabled because a corrupt database may
44017    ** cause an assert() statement to fail.  */
44018    ptrmapCheckPages(apNew, nNew);
44019    ptrmapCheckPages(&pParent, 1);
44020#endif
44021  }
44022
44023  assert( pParent->isInit );
44024  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
44025          nOld, nNew, nCell));
44026
44027  /*
44028  ** Cleanup before returning.
44029  */
44030balance_cleanup:
44031  sqlite3ScratchFree(apCell);
44032  for(i=0; i<nOld; i++){
44033    releasePage(apOld[i]);
44034  }
44035  for(i=0; i<nNew; i++){
44036    releasePage(apNew[i]);
44037  }
44038
44039  return rc;
44040}
44041
44042
44043/*
44044** This function is called when the root page of a b-tree structure is
44045** overfull (has one or more overflow pages).
44046**
44047** A new child page is allocated and the contents of the current root
44048** page, including overflow cells, are copied into the child. The root
44049** page is then overwritten to make it an empty page with the right-child
44050** pointer pointing to the new page.
44051**
44052** Before returning, all pointer-map entries corresponding to pages
44053** that the new child-page now contains pointers to are updated. The
44054** entry corresponding to the new right-child pointer of the root
44055** page is also updated.
44056**
44057** If successful, *ppChild is set to contain a reference to the child
44058** page and SQLITE_OK is returned. In this case the caller is required
44059** to call releasePage() on *ppChild exactly once. If an error occurs,
44060** an error code is returned and *ppChild is set to 0.
44061*/
44062static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
44063  int rc;                        /* Return value from subprocedures */
44064  MemPage *pChild = 0;           /* Pointer to a new child page */
44065  Pgno pgnoChild = 0;            /* Page number of the new child page */
44066  BtShared *pBt = pRoot->pBt;    /* The BTree */
44067
44068  assert( pRoot->nOverflow>0 );
44069  assert( sqlite3_mutex_held(pBt->mutex) );
44070
44071  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
44072  ** page that will become the new right-child of pPage. Copy the contents
44073  ** of the node stored on pRoot into the new child page.
44074  */
44075  rc = sqlite3PagerWrite(pRoot->pDbPage);
44076  if( rc==SQLITE_OK ){
44077    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
44078    copyNodeContent(pRoot, pChild, &rc);
44079    if( ISAUTOVACUUM ){
44080      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
44081    }
44082  }
44083  if( rc ){
44084    *ppChild = 0;
44085    releasePage(pChild);
44086    return rc;
44087  }
44088  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
44089  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
44090  assert( pChild->nCell==pRoot->nCell );
44091
44092  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
44093
44094  /* Copy the overflow cells from pRoot to pChild */
44095  memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
44096  pChild->nOverflow = pRoot->nOverflow;
44097
44098  /* Zero the contents of pRoot. Then install pChild as the right-child. */
44099  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
44100  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
44101
44102  *ppChild = pChild;
44103  return SQLITE_OK;
44104}
44105
44106/*
44107** The page that pCur currently points to has just been modified in
44108** some way. This function figures out if this modification means the
44109** tree needs to be balanced, and if so calls the appropriate balancing
44110** routine. Balancing routines are:
44111**
44112**   balance_quick()
44113**   balance_deeper()
44114**   balance_nonroot()
44115*/
44116static int balance(BtCursor *pCur){
44117  int rc = SQLITE_OK;
44118  const int nMin = pCur->pBt->usableSize * 2 / 3;
44119  u8 aBalanceQuickSpace[13];
44120  u8 *pFree = 0;
44121
44122  TESTONLY( int balance_quick_called = 0 );
44123  TESTONLY( int balance_deeper_called = 0 );
44124
44125  do {
44126    int iPage = pCur->iPage;
44127    MemPage *pPage = pCur->apPage[iPage];
44128
44129    if( iPage==0 ){
44130      if( pPage->nOverflow ){
44131        /* The root page of the b-tree is overfull. In this case call the
44132        ** balance_deeper() function to create a new child for the root-page
44133        ** and copy the current contents of the root-page to it. The
44134        ** next iteration of the do-loop will balance the child page.
44135        */
44136        assert( (balance_deeper_called++)==0 );
44137        rc = balance_deeper(pPage, &pCur->apPage[1]);
44138        if( rc==SQLITE_OK ){
44139          pCur->iPage = 1;
44140          pCur->aiIdx[0] = 0;
44141          pCur->aiIdx[1] = 0;
44142          assert( pCur->apPage[1]->nOverflow );
44143        }
44144      }else{
44145        break;
44146      }
44147    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
44148      break;
44149    }else{
44150      MemPage * const pParent = pCur->apPage[iPage-1];
44151      int const iIdx = pCur->aiIdx[iPage-1];
44152
44153      rc = sqlite3PagerWrite(pParent->pDbPage);
44154      if( rc==SQLITE_OK ){
44155#ifndef SQLITE_OMIT_QUICKBALANCE
44156        if( pPage->hasData
44157         && pPage->nOverflow==1
44158         && pPage->aOvfl[0].idx==pPage->nCell
44159         && pParent->pgno!=1
44160         && pParent->nCell==iIdx
44161        ){
44162          /* Call balance_quick() to create a new sibling of pPage on which
44163          ** to store the overflow cell. balance_quick() inserts a new cell
44164          ** into pParent, which may cause pParent overflow. If this
44165          ** happens, the next interation of the do-loop will balance pParent
44166          ** use either balance_nonroot() or balance_deeper(). Until this
44167          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
44168          ** buffer.
44169          **
44170          ** The purpose of the following assert() is to check that only a
44171          ** single call to balance_quick() is made for each call to this
44172          ** function. If this were not verified, a subtle bug involving reuse
44173          ** of the aBalanceQuickSpace[] might sneak in.
44174          */
44175          assert( (balance_quick_called++)==0 );
44176          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
44177        }else
44178#endif
44179        {
44180          /* In this case, call balance_nonroot() to redistribute cells
44181          ** between pPage and up to 2 of its sibling pages. This involves
44182          ** modifying the contents of pParent, which may cause pParent to
44183          ** become overfull or underfull. The next iteration of the do-loop
44184          ** will balance the parent page to correct this.
44185          **
44186          ** If the parent page becomes overfull, the overflow cell or cells
44187          ** are stored in the pSpace buffer allocated immediately below.
44188          ** A subsequent iteration of the do-loop will deal with this by
44189          ** calling balance_nonroot() (balance_deeper() may be called first,
44190          ** but it doesn't deal with overflow cells - just moves them to a
44191          ** different page). Once this subsequent call to balance_nonroot()
44192          ** has completed, it is safe to release the pSpace buffer used by
44193          ** the previous call, as the overflow cell data will have been
44194          ** copied either into the body of a database page or into the new
44195          ** pSpace buffer passed to the latter call to balance_nonroot().
44196          */
44197          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
44198          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
44199          if( pFree ){
44200            /* If pFree is not NULL, it points to the pSpace buffer used
44201            ** by a previous call to balance_nonroot(). Its contents are
44202            ** now stored either on real database pages or within the
44203            ** new pSpace buffer, so it may be safely freed here. */
44204            sqlite3PageFree(pFree);
44205          }
44206
44207          /* The pSpace buffer will be freed after the next call to
44208          ** balance_nonroot(), or just before this function returns, whichever
44209          ** comes first. */
44210          pFree = pSpace;
44211        }
44212      }
44213
44214      pPage->nOverflow = 0;
44215
44216      /* The next iteration of the do-loop balances the parent page. */
44217      releasePage(pPage);
44218      pCur->iPage--;
44219    }
44220  }while( rc==SQLITE_OK );
44221
44222  if( pFree ){
44223    sqlite3PageFree(pFree);
44224  }
44225  return rc;
44226}
44227
44228
44229/*
44230** Insert a new record into the BTree.  The key is given by (pKey,nKey)
44231** and the data is given by (pData,nData).  The cursor is used only to
44232** define what table the record should be inserted into.  The cursor
44233** is left pointing at a random location.
44234**
44235** For an INTKEY table, only the nKey value of the key is used.  pKey is
44236** ignored.  For a ZERODATA table, the pData and nData are both ignored.
44237**
44238** If the seekResult parameter is non-zero, then a successful call to
44239** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
44240** been performed. seekResult is the search result returned (a negative
44241** number if pCur points at an entry that is smaller than (pKey, nKey), or
44242** a positive value if pCur points at an etry that is larger than
44243** (pKey, nKey)).
44244**
44245** If the seekResult parameter is non-zero, then the caller guarantees that
44246** cursor pCur is pointing at the existing copy of a row that is to be
44247** overwritten.  If the seekResult parameter is 0, then cursor pCur may
44248** point to any entry or to no entry at all and so this function has to seek
44249** the cursor before the new key can be inserted.
44250*/
44251SQLITE_PRIVATE int sqlite3BtreeInsert(
44252  BtCursor *pCur,                /* Insert data into the table of this cursor */
44253  const void *pKey, i64 nKey,    /* The key of the new record */
44254  const void *pData, int nData,  /* The data of the new record */
44255  int nZero,                     /* Number of extra 0 bytes to append to data */
44256  int appendBias,                /* True if this is likely an append */
44257  int seekResult                 /* Result of prior MovetoUnpacked() call */
44258){
44259  int rc;
44260  int loc = seekResult;          /* -1: before desired location  +1: after */
44261  int szNew = 0;
44262  int idx;
44263  MemPage *pPage;
44264  Btree *p = pCur->pBtree;
44265  BtShared *pBt = p->pBt;
44266  unsigned char *oldCell;
44267  unsigned char *newCell = 0;
44268
44269  if( pCur->eState==CURSOR_FAULT ){
44270    assert( pCur->skipNext!=SQLITE_OK );
44271    return pCur->skipNext;
44272  }
44273
44274  assert( cursorHoldsMutex(pCur) );
44275  assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
44276  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
44277
44278  /* Assert that the caller has been consistent. If this cursor was opened
44279  ** expecting an index b-tree, then the caller should be inserting blob
44280  ** keys with no associated data. If the cursor was opened expecting an
44281  ** intkey table, the caller should be inserting integer keys with a
44282  ** blob of associated data.  */
44283  assert( (pKey==0)==(pCur->pKeyInfo==0) );
44284
44285  /* If this is an insert into a table b-tree, invalidate any incrblob
44286  ** cursors open on the row being replaced (assuming this is a replace
44287  ** operation - if it is not, the following is a no-op).  */
44288  if( pCur->pKeyInfo==0 ){
44289    invalidateIncrblobCursors(p, nKey, 0);
44290  }
44291
44292  /* Save the positions of any other cursors open on this table.
44293  **
44294  ** In some cases, the call to btreeMoveto() below is a no-op. For
44295  ** example, when inserting data into a table with auto-generated integer
44296  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
44297  ** integer key to use. It then calls this function to actually insert the
44298  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
44299  ** that the cursor is already where it needs to be and returns without
44300  ** doing any work. To avoid thwarting these optimizations, it is important
44301  ** not to clear the cursor here.
44302  */
44303  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
44304  if( rc ) return rc;
44305  if( !loc ){
44306    rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
44307    if( rc ) return rc;
44308  }
44309  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
44310
44311  pPage = pCur->apPage[pCur->iPage];
44312  assert( pPage->intKey || nKey>=0 );
44313  assert( pPage->leaf || !pPage->intKey );
44314
44315  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
44316          pCur->pgnoRoot, nKey, nData, pPage->pgno,
44317          loc==0 ? "overwrite" : "new entry"));
44318  assert( pPage->isInit );
44319  allocateTempSpace(pBt);
44320  newCell = pBt->pTmpSpace;
44321  if( newCell==0 ) return SQLITE_NOMEM;
44322  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
44323  if( rc ) goto end_insert;
44324  assert( szNew==cellSizePtr(pPage, newCell) );
44325  assert( szNew<=MX_CELL_SIZE(pBt) );
44326  idx = pCur->aiIdx[pCur->iPage];
44327  if( loc==0 ){
44328    u16 szOld;
44329    assert( idx<pPage->nCell );
44330    rc = sqlite3PagerWrite(pPage->pDbPage);
44331    if( rc ){
44332      goto end_insert;
44333    }
44334    oldCell = findCell(pPage, idx);
44335    if( !pPage->leaf ){
44336      memcpy(newCell, oldCell, 4);
44337    }
44338    szOld = cellSizePtr(pPage, oldCell);
44339    rc = clearCell(pPage, oldCell);
44340    dropCell(pPage, idx, szOld, &rc);
44341    if( rc ) goto end_insert;
44342  }else if( loc<0 && pPage->nCell>0 ){
44343    assert( pPage->leaf );
44344    idx = ++pCur->aiIdx[pCur->iPage];
44345  }else{
44346    assert( pPage->leaf );
44347  }
44348  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
44349  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
44350
44351  /* If no error has occured and pPage has an overflow cell, call balance()
44352  ** to redistribute the cells within the tree. Since balance() may move
44353  ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
44354  ** variables.
44355  **
44356  ** Previous versions of SQLite called moveToRoot() to move the cursor
44357  ** back to the root page as balance() used to invalidate the contents
44358  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
44359  ** set the cursor state to "invalid". This makes common insert operations
44360  ** slightly faster.
44361  **
44362  ** There is a subtle but important optimization here too. When inserting
44363  ** multiple records into an intkey b-tree using a single cursor (as can
44364  ** happen while processing an "INSERT INTO ... SELECT" statement), it
44365  ** is advantageous to leave the cursor pointing to the last entry in
44366  ** the b-tree if possible. If the cursor is left pointing to the last
44367  ** entry in the table, and the next row inserted has an integer key
44368  ** larger than the largest existing key, it is possible to insert the
44369  ** row without seeking the cursor. This can be a big performance boost.
44370  */
44371  pCur->info.nSize = 0;
44372  pCur->validNKey = 0;
44373  if( rc==SQLITE_OK && pPage->nOverflow ){
44374    rc = balance(pCur);
44375
44376    /* Must make sure nOverflow is reset to zero even if the balance()
44377    ** fails. Internal data structure corruption will result otherwise.
44378    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
44379    ** from trying to save the current position of the cursor.  */
44380    pCur->apPage[pCur->iPage]->nOverflow = 0;
44381    pCur->eState = CURSOR_INVALID;
44382  }
44383  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
44384
44385end_insert:
44386  return rc;
44387}
44388
44389/*
44390** Delete the entry that the cursor is pointing to.  The cursor
44391** is left pointing at a arbitrary location.
44392*/
44393SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
44394  Btree *p = pCur->pBtree;
44395  BtShared *pBt = p->pBt;
44396  int rc;                              /* Return code */
44397  MemPage *pPage;                      /* Page to delete cell from */
44398  unsigned char *pCell;                /* Pointer to cell to delete */
44399  int iCellIdx;                        /* Index of cell to delete */
44400  int iCellDepth;                      /* Depth of node containing pCell */
44401
44402  assert( cursorHoldsMutex(pCur) );
44403  assert( pBt->inTransaction==TRANS_WRITE );
44404  assert( !pBt->readOnly );
44405  assert( pCur->wrFlag );
44406  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
44407  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
44408
44409  if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
44410   || NEVER(pCur->eState!=CURSOR_VALID)
44411  ){
44412    return SQLITE_ERROR;  /* Something has gone awry. */
44413  }
44414
44415  /* If this is a delete operation to remove a row from a table b-tree,
44416  ** invalidate any incrblob cursors open on the row being deleted.  */
44417  if( pCur->pKeyInfo==0 ){
44418    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
44419  }
44420
44421  iCellDepth = pCur->iPage;
44422  iCellIdx = pCur->aiIdx[iCellDepth];
44423  pPage = pCur->apPage[iCellDepth];
44424  pCell = findCell(pPage, iCellIdx);
44425
44426  /* If the page containing the entry to delete is not a leaf page, move
44427  ** the cursor to the largest entry in the tree that is smaller than
44428  ** the entry being deleted. This cell will replace the cell being deleted
44429  ** from the internal node. The 'previous' entry is used for this instead
44430  ** of the 'next' entry, as the previous entry is always a part of the
44431  ** sub-tree headed by the child page of the cell being deleted. This makes
44432  ** balancing the tree following the delete operation easier.  */
44433  if( !pPage->leaf ){
44434    int notUsed;
44435    rc = sqlite3BtreePrevious(pCur, &notUsed);
44436    if( rc ) return rc;
44437  }
44438
44439  /* Save the positions of any other cursors open on this table before
44440  ** making any modifications. Make the page containing the entry to be
44441  ** deleted writable. Then free any overflow pages associated with the
44442  ** entry and finally remove the cell itself from within the page.
44443  */
44444  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
44445  if( rc ) return rc;
44446  rc = sqlite3PagerWrite(pPage->pDbPage);
44447  if( rc ) return rc;
44448  rc = clearCell(pPage, pCell);
44449  dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
44450  if( rc ) return rc;
44451
44452  /* If the cell deleted was not located on a leaf page, then the cursor
44453  ** is currently pointing to the largest entry in the sub-tree headed
44454  ** by the child-page of the cell that was just deleted from an internal
44455  ** node. The cell from the leaf node needs to be moved to the internal
44456  ** node to replace the deleted cell.  */
44457  if( !pPage->leaf ){
44458    MemPage *pLeaf = pCur->apPage[pCur->iPage];
44459    int nCell;
44460    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
44461    unsigned char *pTmp;
44462
44463    pCell = findCell(pLeaf, pLeaf->nCell-1);
44464    nCell = cellSizePtr(pLeaf, pCell);
44465    assert( MX_CELL_SIZE(pBt)>=nCell );
44466
44467    allocateTempSpace(pBt);
44468    pTmp = pBt->pTmpSpace;
44469
44470    rc = sqlite3PagerWrite(pLeaf->pDbPage);
44471    insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
44472    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
44473    if( rc ) return rc;
44474  }
44475
44476  /* Balance the tree. If the entry deleted was located on a leaf page,
44477  ** then the cursor still points to that page. In this case the first
44478  ** call to balance() repairs the tree, and the if(...) condition is
44479  ** never true.
44480  **
44481  ** Otherwise, if the entry deleted was on an internal node page, then
44482  ** pCur is pointing to the leaf page from which a cell was removed to
44483  ** replace the cell deleted from the internal node. This is slightly
44484  ** tricky as the leaf node may be underfull, and the internal node may
44485  ** be either under or overfull. In this case run the balancing algorithm
44486  ** on the leaf node first. If the balance proceeds far enough up the
44487  ** tree that we can be sure that any problem in the internal node has
44488  ** been corrected, so be it. Otherwise, after balancing the leaf node,
44489  ** walk the cursor up the tree to the internal node and balance it as
44490  ** well.  */
44491  rc = balance(pCur);
44492  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
44493    while( pCur->iPage>iCellDepth ){
44494      releasePage(pCur->apPage[pCur->iPage--]);
44495    }
44496    rc = balance(pCur);
44497  }
44498
44499  if( rc==SQLITE_OK ){
44500    moveToRoot(pCur);
44501  }
44502  return rc;
44503}
44504
44505/*
44506** Create a new BTree table.  Write into *piTable the page
44507** number for the root page of the new table.
44508**
44509** The type of type is determined by the flags parameter.  Only the
44510** following values of flags are currently in use.  Other values for
44511** flags might not work:
44512**
44513**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
44514**     BTREE_ZERODATA                  Used for SQL indices
44515*/
44516static int btreeCreateTable(Btree *p, int *piTable, int flags){
44517  BtShared *pBt = p->pBt;
44518  MemPage *pRoot;
44519  Pgno pgnoRoot;
44520  int rc;
44521
44522  assert( sqlite3BtreeHoldsMutex(p) );
44523  assert( pBt->inTransaction==TRANS_WRITE );
44524  assert( !pBt->readOnly );
44525
44526#ifdef SQLITE_OMIT_AUTOVACUUM
44527  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
44528  if( rc ){
44529    return rc;
44530  }
44531#else
44532  if( pBt->autoVacuum ){
44533    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
44534    MemPage *pPageMove; /* The page to move to. */
44535
44536    /* Creating a new table may probably require moving an existing database
44537    ** to make room for the new tables root page. In case this page turns
44538    ** out to be an overflow page, delete all overflow page-map caches
44539    ** held by open cursors.
44540    */
44541    invalidateAllOverflowCache(pBt);
44542
44543    /* Read the value of meta[3] from the database to determine where the
44544    ** root page of the new table should go. meta[3] is the largest root-page
44545    ** created so far, so the new root-page is (meta[3]+1).
44546    */
44547    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
44548    pgnoRoot++;
44549
44550    /* The new root-page may not be allocated on a pointer-map page, or the
44551    ** PENDING_BYTE page.
44552    */
44553    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
44554        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
44555      pgnoRoot++;
44556    }
44557    assert( pgnoRoot>=3 );
44558
44559    /* Allocate a page. The page that currently resides at pgnoRoot will
44560    ** be moved to the allocated page (unless the allocated page happens
44561    ** to reside at pgnoRoot).
44562    */
44563    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
44564    if( rc!=SQLITE_OK ){
44565      return rc;
44566    }
44567
44568    if( pgnoMove!=pgnoRoot ){
44569      /* pgnoRoot is the page that will be used for the root-page of
44570      ** the new table (assuming an error did not occur). But we were
44571      ** allocated pgnoMove. If required (i.e. if it was not allocated
44572      ** by extending the file), the current page at position pgnoMove
44573      ** is already journaled.
44574      */
44575      u8 eType = 0;
44576      Pgno iPtrPage = 0;
44577
44578      releasePage(pPageMove);
44579
44580      /* Move the page currently at pgnoRoot to pgnoMove. */
44581      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
44582      if( rc!=SQLITE_OK ){
44583        return rc;
44584      }
44585      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
44586      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
44587        rc = SQLITE_CORRUPT_BKPT;
44588      }
44589      if( rc!=SQLITE_OK ){
44590        releasePage(pRoot);
44591        return rc;
44592      }
44593      assert( eType!=PTRMAP_ROOTPAGE );
44594      assert( eType!=PTRMAP_FREEPAGE );
44595      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
44596      releasePage(pRoot);
44597
44598      /* Obtain the page at pgnoRoot */
44599      if( rc!=SQLITE_OK ){
44600        return rc;
44601      }
44602      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
44603      if( rc!=SQLITE_OK ){
44604        return rc;
44605      }
44606      rc = sqlite3PagerWrite(pRoot->pDbPage);
44607      if( rc!=SQLITE_OK ){
44608        releasePage(pRoot);
44609        return rc;
44610      }
44611    }else{
44612      pRoot = pPageMove;
44613    }
44614
44615    /* Update the pointer-map and meta-data with the new root-page number. */
44616    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
44617    if( rc ){
44618      releasePage(pRoot);
44619      return rc;
44620    }
44621    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
44622    if( rc ){
44623      releasePage(pRoot);
44624      return rc;
44625    }
44626
44627  }else{
44628    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
44629    if( rc ) return rc;
44630  }
44631#endif
44632  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
44633  zeroPage(pRoot, flags | PTF_LEAF);
44634  sqlite3PagerUnref(pRoot->pDbPage);
44635  *piTable = (int)pgnoRoot;
44636  return SQLITE_OK;
44637}
44638SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
44639  int rc;
44640  sqlite3BtreeEnter(p);
44641  rc = btreeCreateTable(p, piTable, flags);
44642  sqlite3BtreeLeave(p);
44643  return rc;
44644}
44645
44646/*
44647** Erase the given database page and all its children.  Return
44648** the page to the freelist.
44649*/
44650static int clearDatabasePage(
44651  BtShared *pBt,           /* The BTree that contains the table */
44652  Pgno pgno,               /* Page number to clear */
44653  int freePageFlag,        /* Deallocate page if true */
44654  int *pnChange            /* Add number of Cells freed to this counter */
44655){
44656  MemPage *pPage;
44657  int rc;
44658  unsigned char *pCell;
44659  int i;
44660
44661  assert( sqlite3_mutex_held(pBt->mutex) );
44662  if( pgno>pagerPagecount(pBt) ){
44663    return SQLITE_CORRUPT_BKPT;
44664  }
44665
44666  rc = getAndInitPage(pBt, pgno, &pPage);
44667  if( rc ) return rc;
44668  for(i=0; i<pPage->nCell; i++){
44669    pCell = findCell(pPage, i);
44670    if( !pPage->leaf ){
44671      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
44672      if( rc ) goto cleardatabasepage_out;
44673    }
44674    rc = clearCell(pPage, pCell);
44675    if( rc ) goto cleardatabasepage_out;
44676  }
44677  if( !pPage->leaf ){
44678    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
44679    if( rc ) goto cleardatabasepage_out;
44680  }else if( pnChange ){
44681    assert( pPage->intKey );
44682    *pnChange += pPage->nCell;
44683  }
44684  if( freePageFlag ){
44685    freePage(pPage, &rc);
44686  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
44687    zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
44688  }
44689
44690cleardatabasepage_out:
44691  releasePage(pPage);
44692  return rc;
44693}
44694
44695/*
44696** Delete all information from a single table in the database.  iTable is
44697** the page number of the root of the table.  After this routine returns,
44698** the root page is empty, but still exists.
44699**
44700** This routine will fail with SQLITE_LOCKED if there are any open
44701** read cursors on the table.  Open write cursors are moved to the
44702** root of the table.
44703**
44704** If pnChange is not NULL, then table iTable must be an intkey table. The
44705** integer value pointed to by pnChange is incremented by the number of
44706** entries in the table.
44707*/
44708SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
44709  int rc;
44710  BtShared *pBt = p->pBt;
44711  sqlite3BtreeEnter(p);
44712  assert( p->inTrans==TRANS_WRITE );
44713
44714  /* Invalidate all incrblob cursors open on table iTable (assuming iTable
44715  ** is the root of a table b-tree - if it is not, the following call is
44716  ** a no-op).  */
44717  invalidateIncrblobCursors(p, 0, 1);
44718
44719  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
44720  if( SQLITE_OK==rc ){
44721    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
44722  }
44723  sqlite3BtreeLeave(p);
44724  return rc;
44725}
44726
44727/*
44728** Erase all information in a table and add the root of the table to
44729** the freelist.  Except, the root of the principle table (the one on
44730** page 1) is never added to the freelist.
44731**
44732** This routine will fail with SQLITE_LOCKED if there are any open
44733** cursors on the table.
44734**
44735** If AUTOVACUUM is enabled and the page at iTable is not the last
44736** root page in the database file, then the last root page
44737** in the database file is moved into the slot formerly occupied by
44738** iTable and that last slot formerly occupied by the last root page
44739** is added to the freelist instead of iTable.  In this say, all
44740** root pages are kept at the beginning of the database file, which
44741** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
44742** page number that used to be the last root page in the file before
44743** the move.  If no page gets moved, *piMoved is set to 0.
44744** The last root page is recorded in meta[3] and the value of
44745** meta[3] is updated by this procedure.
44746*/
44747static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
44748  int rc;
44749  MemPage *pPage = 0;
44750  BtShared *pBt = p->pBt;
44751
44752  assert( sqlite3BtreeHoldsMutex(p) );
44753  assert( p->inTrans==TRANS_WRITE );
44754
44755  /* It is illegal to drop a table if any cursors are open on the
44756  ** database. This is because in auto-vacuum mode the backend may
44757  ** need to move another root-page to fill a gap left by the deleted
44758  ** root page. If an open cursor was using this page a problem would
44759  ** occur.
44760  **
44761  ** This error is caught long before control reaches this point.
44762  */
44763  if( NEVER(pBt->pCursor) ){
44764    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
44765    return SQLITE_LOCKED_SHAREDCACHE;
44766  }
44767
44768  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
44769  if( rc ) return rc;
44770  rc = sqlite3BtreeClearTable(p, iTable, 0);
44771  if( rc ){
44772    releasePage(pPage);
44773    return rc;
44774  }
44775
44776  *piMoved = 0;
44777
44778  if( iTable>1 ){
44779#ifdef SQLITE_OMIT_AUTOVACUUM
44780    freePage(pPage, &rc);
44781    releasePage(pPage);
44782#else
44783    if( pBt->autoVacuum ){
44784      Pgno maxRootPgno;
44785      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
44786
44787      if( iTable==maxRootPgno ){
44788        /* If the table being dropped is the table with the largest root-page
44789        ** number in the database, put the root page on the free list.
44790        */
44791        freePage(pPage, &rc);
44792        releasePage(pPage);
44793        if( rc!=SQLITE_OK ){
44794          return rc;
44795        }
44796      }else{
44797        /* The table being dropped does not have the largest root-page
44798        ** number in the database. So move the page that does into the
44799        ** gap left by the deleted root-page.
44800        */
44801        MemPage *pMove;
44802        releasePage(pPage);
44803        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
44804        if( rc!=SQLITE_OK ){
44805          return rc;
44806        }
44807        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
44808        releasePage(pMove);
44809        if( rc!=SQLITE_OK ){
44810          return rc;
44811        }
44812        pMove = 0;
44813        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
44814        freePage(pMove, &rc);
44815        releasePage(pMove);
44816        if( rc!=SQLITE_OK ){
44817          return rc;
44818        }
44819        *piMoved = maxRootPgno;
44820      }
44821
44822      /* Set the new 'max-root-page' value in the database header. This
44823      ** is the old value less one, less one more if that happens to
44824      ** be a root-page number, less one again if that is the
44825      ** PENDING_BYTE_PAGE.
44826      */
44827      maxRootPgno--;
44828      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
44829             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
44830        maxRootPgno--;
44831      }
44832      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
44833
44834      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
44835    }else{
44836      freePage(pPage, &rc);
44837      releasePage(pPage);
44838    }
44839#endif
44840  }else{
44841    /* If sqlite3BtreeDropTable was called on page 1.
44842    ** This really never should happen except in a corrupt
44843    ** database.
44844    */
44845    zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
44846    releasePage(pPage);
44847  }
44848  return rc;
44849}
44850SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
44851  int rc;
44852  sqlite3BtreeEnter(p);
44853  rc = btreeDropTable(p, iTable, piMoved);
44854  sqlite3BtreeLeave(p);
44855  return rc;
44856}
44857
44858
44859/*
44860** This function may only be called if the b-tree connection already
44861** has a read or write transaction open on the database.
44862**
44863** Read the meta-information out of a database file.  Meta[0]
44864** is the number of free pages currently in the database.  Meta[1]
44865** through meta[15] are available for use by higher layers.  Meta[0]
44866** is read-only, the others are read/write.
44867**
44868** The schema layer numbers meta values differently.  At the schema
44869** layer (and the SetCookie and ReadCookie opcodes) the number of
44870** free pages is not visible.  So Cookie[0] is the same as Meta[1].
44871*/
44872SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
44873  BtShared *pBt = p->pBt;
44874
44875  sqlite3BtreeEnter(p);
44876  assert( p->inTrans>TRANS_NONE );
44877  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
44878  assert( pBt->pPage1 );
44879  assert( idx>=0 && idx<=15 );
44880
44881  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
44882
44883  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
44884  ** database, mark the database as read-only.  */
44885#ifdef SQLITE_OMIT_AUTOVACUUM
44886  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
44887#endif
44888
44889  sqlite3BtreeLeave(p);
44890}
44891
44892/*
44893** Write meta-information back into the database.  Meta[0] is
44894** read-only and may not be written.
44895*/
44896SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
44897  BtShared *pBt = p->pBt;
44898  unsigned char *pP1;
44899  int rc;
44900  assert( idx>=1 && idx<=15 );
44901  sqlite3BtreeEnter(p);
44902  assert( p->inTrans==TRANS_WRITE );
44903  assert( pBt->pPage1!=0 );
44904  pP1 = pBt->pPage1->aData;
44905  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
44906  if( rc==SQLITE_OK ){
44907    put4byte(&pP1[36 + idx*4], iMeta);
44908#ifndef SQLITE_OMIT_AUTOVACUUM
44909    if( idx==BTREE_INCR_VACUUM ){
44910      assert( pBt->autoVacuum || iMeta==0 );
44911      assert( iMeta==0 || iMeta==1 );
44912      pBt->incrVacuum = (u8)iMeta;
44913    }
44914#endif
44915  }
44916  sqlite3BtreeLeave(p);
44917  return rc;
44918}
44919
44920#ifndef SQLITE_OMIT_BTREECOUNT
44921/*
44922** The first argument, pCur, is a cursor opened on some b-tree. Count the
44923** number of entries in the b-tree and write the result to *pnEntry.
44924**
44925** SQLITE_OK is returned if the operation is successfully executed.
44926** Otherwise, if an error is encountered (i.e. an IO error or database
44927** corruption) an SQLite error code is returned.
44928*/
44929SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
44930  i64 nEntry = 0;                      /* Value to return in *pnEntry */
44931  int rc;                              /* Return code */
44932  rc = moveToRoot(pCur);
44933
44934  /* Unless an error occurs, the following loop runs one iteration for each
44935  ** page in the B-Tree structure (not including overflow pages).
44936  */
44937  while( rc==SQLITE_OK ){
44938    int iIdx;                          /* Index of child node in parent */
44939    MemPage *pPage;                    /* Current page of the b-tree */
44940
44941    /* If this is a leaf page or the tree is not an int-key tree, then
44942    ** this page contains countable entries. Increment the entry counter
44943    ** accordingly.
44944    */
44945    pPage = pCur->apPage[pCur->iPage];
44946    if( pPage->leaf || !pPage->intKey ){
44947      nEntry += pPage->nCell;
44948    }
44949
44950    /* pPage is a leaf node. This loop navigates the cursor so that it
44951    ** points to the first interior cell that it points to the parent of
44952    ** the next page in the tree that has not yet been visited. The
44953    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
44954    ** of the page, or to the number of cells in the page if the next page
44955    ** to visit is the right-child of its parent.
44956    **
44957    ** If all pages in the tree have been visited, return SQLITE_OK to the
44958    ** caller.
44959    */
44960    if( pPage->leaf ){
44961      do {
44962        if( pCur->iPage==0 ){
44963          /* All pages of the b-tree have been visited. Return successfully. */
44964          *pnEntry = nEntry;
44965          return SQLITE_OK;
44966        }
44967        moveToParent(pCur);
44968      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
44969
44970      pCur->aiIdx[pCur->iPage]++;
44971      pPage = pCur->apPage[pCur->iPage];
44972    }
44973
44974    /* Descend to the child node of the cell that the cursor currently
44975    ** points at. This is the right-child if (iIdx==pPage->nCell).
44976    */
44977    iIdx = pCur->aiIdx[pCur->iPage];
44978    if( iIdx==pPage->nCell ){
44979      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
44980    }else{
44981      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
44982    }
44983  }
44984
44985  /* An error has occurred. Return an error code. */
44986  return rc;
44987}
44988#endif
44989
44990/*
44991** Return the pager associated with a BTree.  This routine is used for
44992** testing and debugging only.
44993*/
44994SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
44995  return p->pBt->pPager;
44996}
44997
44998#ifndef SQLITE_OMIT_INTEGRITY_CHECK
44999/*
45000** Append a message to the error message string.
45001*/
45002static void checkAppendMsg(
45003  IntegrityCk *pCheck,
45004  char *zMsg1,
45005  const char *zFormat,
45006  ...
45007){
45008  va_list ap;
45009  if( !pCheck->mxErr ) return;
45010  pCheck->mxErr--;
45011  pCheck->nErr++;
45012  va_start(ap, zFormat);
45013  if( pCheck->errMsg.nChar ){
45014    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
45015  }
45016  if( zMsg1 ){
45017    sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
45018  }
45019  sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
45020  va_end(ap);
45021  if( pCheck->errMsg.mallocFailed ){
45022    pCheck->mallocFailed = 1;
45023  }
45024}
45025#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45026
45027#ifndef SQLITE_OMIT_INTEGRITY_CHECK
45028/*
45029** Add 1 to the reference count for page iPage.  If this is the second
45030** reference to the page, add an error message to pCheck->zErrMsg.
45031** Return 1 if there are 2 ore more references to the page and 0 if
45032** if this is the first reference to the page.
45033**
45034** Also check that the page number is in bounds.
45035*/
45036static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
45037  if( iPage==0 ) return 1;
45038  if( iPage>pCheck->nPage ){
45039    checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
45040    return 1;
45041  }
45042  if( pCheck->anRef[iPage]==1 ){
45043    checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
45044    return 1;
45045  }
45046  return  (pCheck->anRef[iPage]++)>1;
45047}
45048
45049#ifndef SQLITE_OMIT_AUTOVACUUM
45050/*
45051** Check that the entry in the pointer-map for page iChild maps to
45052** page iParent, pointer type ptrType. If not, append an error message
45053** to pCheck.
45054*/
45055static void checkPtrmap(
45056  IntegrityCk *pCheck,   /* Integrity check context */
45057  Pgno iChild,           /* Child page number */
45058  u8 eType,              /* Expected pointer map type */
45059  Pgno iParent,          /* Expected pointer map parent page number */
45060  char *zContext         /* Context description (used for error msg) */
45061){
45062  int rc;
45063  u8 ePtrmapType;
45064  Pgno iPtrmapParent;
45065
45066  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
45067  if( rc!=SQLITE_OK ){
45068    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
45069    checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
45070    return;
45071  }
45072
45073  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
45074    checkAppendMsg(pCheck, zContext,
45075      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
45076      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
45077  }
45078}
45079#endif
45080
45081/*
45082** Check the integrity of the freelist or of an overflow page list.
45083** Verify that the number of pages on the list is N.
45084*/
45085static void checkList(
45086  IntegrityCk *pCheck,  /* Integrity checking context */
45087  int isFreeList,       /* True for a freelist.  False for overflow page list */
45088  int iPage,            /* Page number for first page in the list */
45089  int N,                /* Expected number of pages in the list */
45090  char *zContext        /* Context for error messages */
45091){
45092  int i;
45093  int expected = N;
45094  int iFirst = iPage;
45095  while( N-- > 0 && pCheck->mxErr ){
45096    DbPage *pOvflPage;
45097    unsigned char *pOvflData;
45098    if( iPage<1 ){
45099      checkAppendMsg(pCheck, zContext,
45100         "%d of %d pages missing from overflow list starting at %d",
45101          N+1, expected, iFirst);
45102      break;
45103    }
45104    if( checkRef(pCheck, iPage, zContext) ) break;
45105    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
45106      checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
45107      break;
45108    }
45109    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
45110    if( isFreeList ){
45111      int n = get4byte(&pOvflData[4]);
45112#ifndef SQLITE_OMIT_AUTOVACUUM
45113      if( pCheck->pBt->autoVacuum ){
45114        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
45115      }
45116#endif
45117      if( n>pCheck->pBt->usableSize/4-2 ){
45118        checkAppendMsg(pCheck, zContext,
45119           "freelist leaf count too big on page %d", iPage);
45120        N--;
45121      }else{
45122        for(i=0; i<n; i++){
45123          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
45124#ifndef SQLITE_OMIT_AUTOVACUUM
45125          if( pCheck->pBt->autoVacuum ){
45126            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
45127          }
45128#endif
45129          checkRef(pCheck, iFreePage, zContext);
45130        }
45131        N -= n;
45132      }
45133    }
45134#ifndef SQLITE_OMIT_AUTOVACUUM
45135    else{
45136      /* If this database supports auto-vacuum and iPage is not the last
45137      ** page in this overflow list, check that the pointer-map entry for
45138      ** the following page matches iPage.
45139      */
45140      if( pCheck->pBt->autoVacuum && N>0 ){
45141        i = get4byte(pOvflData);
45142        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
45143      }
45144    }
45145#endif
45146    iPage = get4byte(pOvflData);
45147    sqlite3PagerUnref(pOvflPage);
45148  }
45149}
45150#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45151
45152#ifndef SQLITE_OMIT_INTEGRITY_CHECK
45153/*
45154** Do various sanity checks on a single page of a tree.  Return
45155** the tree depth.  Root pages return 0.  Parents of root pages
45156** return 1, and so forth.
45157**
45158** These checks are done:
45159**
45160**      1.  Make sure that cells and freeblocks do not overlap
45161**          but combine to completely cover the page.
45162**  NO  2.  Make sure cell keys are in order.
45163**  NO  3.  Make sure no key is less than or equal to zLowerBound.
45164**  NO  4.  Make sure no key is greater than or equal to zUpperBound.
45165**      5.  Check the integrity of overflow pages.
45166**      6.  Recursively call checkTreePage on all children.
45167**      7.  Verify that the depth of all children is the same.
45168**      8.  Make sure this page is at least 33% full or else it is
45169**          the root of the tree.
45170*/
45171static int checkTreePage(
45172  IntegrityCk *pCheck,  /* Context for the sanity check */
45173  int iPage,            /* Page number of the page to check */
45174  char *zParentContext, /* Parent context */
45175  i64 *pnParentMinKey,
45176  i64 *pnParentMaxKey
45177){
45178  MemPage *pPage;
45179  int i, rc, depth, d2, pgno, cnt;
45180  int hdr, cellStart;
45181  int nCell;
45182  u8 *data;
45183  BtShared *pBt;
45184  int usableSize;
45185  char zContext[100];
45186  char *hit = 0;
45187  i64 nMinKey = 0;
45188  i64 nMaxKey = 0;
45189
45190  sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
45191
45192  /* Check that the page exists
45193  */
45194  pBt = pCheck->pBt;
45195  usableSize = pBt->usableSize;
45196  if( iPage==0 ) return 0;
45197  if( checkRef(pCheck, iPage, zParentContext) ) return 0;
45198  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
45199    checkAppendMsg(pCheck, zContext,
45200       "unable to get the page. error code=%d", rc);
45201    return 0;
45202  }
45203
45204  /* Clear MemPage.isInit to make sure the corruption detection code in
45205  ** btreeInitPage() is executed.  */
45206  pPage->isInit = 0;
45207  if( (rc = btreeInitPage(pPage))!=0 ){
45208    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
45209    checkAppendMsg(pCheck, zContext,
45210                   "btreeInitPage() returns error code %d", rc);
45211    releasePage(pPage);
45212    return 0;
45213  }
45214
45215  /* Check out all the cells.
45216  */
45217  depth = 0;
45218  for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
45219    u8 *pCell;
45220    u32 sz;
45221    CellInfo info;
45222
45223    /* Check payload overflow pages
45224    */
45225    sqlite3_snprintf(sizeof(zContext), zContext,
45226             "On tree page %d cell %d: ", iPage, i);
45227    pCell = findCell(pPage,i);
45228    btreeParseCellPtr(pPage, pCell, &info);
45229    sz = info.nData;
45230    if( !pPage->intKey ) sz += (int)info.nKey;
45231    /* For intKey pages, check that the keys are in order.
45232    */
45233    else if( i==0 ) nMinKey = nMaxKey = info.nKey;
45234    else{
45235      if( info.nKey <= nMaxKey ){
45236        checkAppendMsg(pCheck, zContext,
45237            "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
45238      }
45239      nMaxKey = info.nKey;
45240    }
45241    assert( sz==info.nPayload );
45242    if( (sz>info.nLocal)
45243     && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
45244    ){
45245      int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
45246      Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
45247#ifndef SQLITE_OMIT_AUTOVACUUM
45248      if( pBt->autoVacuum ){
45249        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
45250      }
45251#endif
45252      checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
45253    }
45254
45255    /* Check sanity of left child page.
45256    */
45257    if( !pPage->leaf ){
45258      pgno = get4byte(pCell);
45259#ifndef SQLITE_OMIT_AUTOVACUUM
45260      if( pBt->autoVacuum ){
45261        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
45262      }
45263#endif
45264      d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
45265      if( i>0 && d2!=depth ){
45266        checkAppendMsg(pCheck, zContext, "Child page depth differs");
45267      }
45268      depth = d2;
45269    }
45270  }
45271
45272  if( !pPage->leaf ){
45273    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
45274    sqlite3_snprintf(sizeof(zContext), zContext,
45275                     "On page %d at right child: ", iPage);
45276#ifndef SQLITE_OMIT_AUTOVACUUM
45277    if( pBt->autoVacuum ){
45278      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
45279    }
45280#endif
45281    checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
45282  }
45283
45284  /* For intKey leaf pages, check that the min/max keys are in order
45285  ** with any left/parent/right pages.
45286  */
45287  if( pPage->leaf && pPage->intKey ){
45288    /* if we are a left child page */
45289    if( pnParentMinKey ){
45290      /* if we are the left most child page */
45291      if( !pnParentMaxKey ){
45292        if( nMaxKey > *pnParentMinKey ){
45293          checkAppendMsg(pCheck, zContext,
45294              "Rowid %lld out of order (max larger than parent min of %lld)",
45295              nMaxKey, *pnParentMinKey);
45296        }
45297      }else{
45298        if( nMinKey <= *pnParentMinKey ){
45299          checkAppendMsg(pCheck, zContext,
45300              "Rowid %lld out of order (min less than parent min of %lld)",
45301              nMinKey, *pnParentMinKey);
45302        }
45303        if( nMaxKey > *pnParentMaxKey ){
45304          checkAppendMsg(pCheck, zContext,
45305              "Rowid %lld out of order (max larger than parent max of %lld)",
45306              nMaxKey, *pnParentMaxKey);
45307        }
45308        *pnParentMinKey = nMaxKey;
45309      }
45310    /* else if we're a right child page */
45311    } else if( pnParentMaxKey ){
45312      if( nMinKey <= *pnParentMaxKey ){
45313        checkAppendMsg(pCheck, zContext,
45314            "Rowid %lld out of order (min less than parent max of %lld)",
45315            nMinKey, *pnParentMaxKey);
45316      }
45317    }
45318  }
45319
45320  /* Check for complete coverage of the page
45321  */
45322  data = pPage->aData;
45323  hdr = pPage->hdrOffset;
45324  hit = sqlite3PageMalloc( pBt->pageSize );
45325  if( hit==0 ){
45326    pCheck->mallocFailed = 1;
45327  }else{
45328    u16 contentOffset = get2byte(&data[hdr+5]);
45329    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
45330    memset(hit+contentOffset, 0, usableSize-contentOffset);
45331    memset(hit, 1, contentOffset);
45332    nCell = get2byte(&data[hdr+3]);
45333    cellStart = hdr + 12 - 4*pPage->leaf;
45334    for(i=0; i<nCell; i++){
45335      int pc = get2byte(&data[cellStart+i*2]);
45336      u16 size = 1024;
45337      int j;
45338      if( pc<=usableSize-4 ){
45339        size = cellSizePtr(pPage, &data[pc]);
45340      }
45341      if( (pc+size-1)>=usableSize ){
45342        checkAppendMsg(pCheck, 0,
45343            "Corruption detected in cell %d on page %d",i,iPage);
45344      }else{
45345        for(j=pc+size-1; j>=pc; j--) hit[j]++;
45346      }
45347    }
45348    i = get2byte(&data[hdr+1]);
45349    while( i>0 ){
45350      int size, j;
45351      assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
45352      size = get2byte(&data[i+2]);
45353      assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
45354      for(j=i+size-1; j>=i; j--) hit[j]++;
45355      j = get2byte(&data[i]);
45356      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
45357      assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
45358      i = j;
45359    }
45360    for(i=cnt=0; i<usableSize; i++){
45361      if( hit[i]==0 ){
45362        cnt++;
45363      }else if( hit[i]>1 ){
45364        checkAppendMsg(pCheck, 0,
45365          "Multiple uses for byte %d of page %d", i, iPage);
45366        break;
45367      }
45368    }
45369    if( cnt!=data[hdr+7] ){
45370      checkAppendMsg(pCheck, 0,
45371          "Fragmentation of %d bytes reported as %d on page %d",
45372          cnt, data[hdr+7], iPage);
45373    }
45374  }
45375  sqlite3PageFree(hit);
45376  releasePage(pPage);
45377  return depth+1;
45378}
45379#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45380
45381#ifndef SQLITE_OMIT_INTEGRITY_CHECK
45382/*
45383** This routine does a complete check of the given BTree file.  aRoot[] is
45384** an array of pages numbers were each page number is the root page of
45385** a table.  nRoot is the number of entries in aRoot.
45386**
45387** A read-only or read-write transaction must be opened before calling
45388** this function.
45389**
45390** Write the number of error seen in *pnErr.  Except for some memory
45391** allocation errors,  an error message held in memory obtained from
45392** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
45393** returned.  If a memory allocation error occurs, NULL is returned.
45394*/
45395SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
45396  Btree *p,     /* The btree to be checked */
45397  int *aRoot,   /* An array of root pages numbers for individual trees */
45398  int nRoot,    /* Number of entries in aRoot[] */
45399  int mxErr,    /* Stop reporting errors after this many */
45400  int *pnErr    /* Write number of errors seen to this variable */
45401){
45402  Pgno i;
45403  int nRef;
45404  IntegrityCk sCheck;
45405  BtShared *pBt = p->pBt;
45406  char zErr[100];
45407
45408  sqlite3BtreeEnter(p);
45409  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
45410  nRef = sqlite3PagerRefcount(pBt->pPager);
45411  sCheck.pBt = pBt;
45412  sCheck.pPager = pBt->pPager;
45413  sCheck.nPage = pagerPagecount(sCheck.pBt);
45414  sCheck.mxErr = mxErr;
45415  sCheck.nErr = 0;
45416  sCheck.mallocFailed = 0;
45417  *pnErr = 0;
45418  if( sCheck.nPage==0 ){
45419    sqlite3BtreeLeave(p);
45420    return 0;
45421  }
45422  sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
45423  if( !sCheck.anRef ){
45424    *pnErr = 1;
45425    sqlite3BtreeLeave(p);
45426    return 0;
45427  }
45428  for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
45429  i = PENDING_BYTE_PAGE(pBt);
45430  if( i<=sCheck.nPage ){
45431    sCheck.anRef[i] = 1;
45432  }
45433  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
45434
45435  /* Check the integrity of the freelist
45436  */
45437  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
45438            get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
45439
45440  /* Check all the tables.
45441  */
45442  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
45443    if( aRoot[i]==0 ) continue;
45444#ifndef SQLITE_OMIT_AUTOVACUUM
45445    if( pBt->autoVacuum && aRoot[i]>1 ){
45446      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
45447    }
45448#endif
45449    checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
45450  }
45451
45452  /* Make sure every page in the file is referenced
45453  */
45454  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
45455#ifdef SQLITE_OMIT_AUTOVACUUM
45456    if( sCheck.anRef[i]==0 ){
45457      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
45458    }
45459#else
45460    /* If the database supports auto-vacuum, make sure no tables contain
45461    ** references to pointer-map pages.
45462    */
45463    if( sCheck.anRef[i]==0 &&
45464       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
45465      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
45466    }
45467    if( sCheck.anRef[i]!=0 &&
45468       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
45469      checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
45470    }
45471#endif
45472  }
45473
45474  /* Make sure this analysis did not leave any unref() pages.
45475  ** This is an internal consistency check; an integrity check
45476  ** of the integrity check.
45477  */
45478  if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
45479    checkAppendMsg(&sCheck, 0,
45480      "Outstanding page count goes from %d to %d during this analysis",
45481      nRef, sqlite3PagerRefcount(pBt->pPager)
45482    );
45483  }
45484
45485  /* Clean  up and report errors.
45486  */
45487  sqlite3BtreeLeave(p);
45488  sqlite3_free(sCheck.anRef);
45489  if( sCheck.mallocFailed ){
45490    sqlite3StrAccumReset(&sCheck.errMsg);
45491    *pnErr = sCheck.nErr+1;
45492    return 0;
45493  }
45494  *pnErr = sCheck.nErr;
45495  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
45496  return sqlite3StrAccumFinish(&sCheck.errMsg);
45497}
45498#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45499
45500/*
45501** Return the full pathname of the underlying database file.
45502**
45503** The pager filename is invariant as long as the pager is
45504** open so it is safe to access without the BtShared mutex.
45505*/
45506SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
45507  assert( p->pBt->pPager!=0 );
45508  return sqlite3PagerFilename(p->pBt->pPager);
45509}
45510
45511/*
45512** Return the pathname of the journal file for this database. The return
45513** value of this routine is the same regardless of whether the journal file
45514** has been created or not.
45515**
45516** The pager journal filename is invariant as long as the pager is
45517** open so it is safe to access without the BtShared mutex.
45518*/
45519SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
45520  assert( p->pBt->pPager!=0 );
45521  return sqlite3PagerJournalname(p->pBt->pPager);
45522}
45523
45524/*
45525** Return non-zero if a transaction is active.
45526*/
45527SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
45528  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
45529  return (p && (p->inTrans==TRANS_WRITE));
45530}
45531
45532/*
45533** Return non-zero if a read (or write) transaction is active.
45534*/
45535SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
45536  assert( p );
45537  assert( sqlite3_mutex_held(p->db->mutex) );
45538  return p->inTrans!=TRANS_NONE;
45539}
45540
45541SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
45542  assert( p );
45543  assert( sqlite3_mutex_held(p->db->mutex) );
45544  return p->nBackup!=0;
45545}
45546
45547/*
45548** This function returns a pointer to a blob of memory associated with
45549** a single shared-btree. The memory is used by client code for its own
45550** purposes (for example, to store a high-level schema associated with
45551** the shared-btree). The btree layer manages reference counting issues.
45552**
45553** The first time this is called on a shared-btree, nBytes bytes of memory
45554** are allocated, zeroed, and returned to the caller. For each subsequent
45555** call the nBytes parameter is ignored and a pointer to the same blob
45556** of memory returned.
45557**
45558** If the nBytes parameter is 0 and the blob of memory has not yet been
45559** allocated, a null pointer is returned. If the blob has already been
45560** allocated, it is returned as normal.
45561**
45562** Just before the shared-btree is closed, the function passed as the
45563** xFree argument when the memory allocation was made is invoked on the
45564** blob of allocated memory. This function should not call sqlite3_free()
45565** on the memory, the btree layer does that.
45566*/
45567SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
45568  BtShared *pBt = p->pBt;
45569  sqlite3BtreeEnter(p);
45570  if( !pBt->pSchema && nBytes ){
45571    pBt->pSchema = sqlite3MallocZero(nBytes);
45572    pBt->xFreeSchema = xFree;
45573  }
45574  sqlite3BtreeLeave(p);
45575  return pBt->pSchema;
45576}
45577
45578/*
45579** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
45580** btree as the argument handle holds an exclusive lock on the
45581** sqlite_master table. Otherwise SQLITE_OK.
45582*/
45583SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
45584  int rc;
45585  assert( sqlite3_mutex_held(p->db->mutex) );
45586  sqlite3BtreeEnter(p);
45587  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
45588  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
45589  sqlite3BtreeLeave(p);
45590  return rc;
45591}
45592
45593
45594#ifndef SQLITE_OMIT_SHARED_CACHE
45595/*
45596** Obtain a lock on the table whose root page is iTab.  The
45597** lock is a write lock if isWritelock is true or a read lock
45598** if it is false.
45599*/
45600SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
45601  int rc = SQLITE_OK;
45602  assert( p->inTrans!=TRANS_NONE );
45603  if( p->sharable ){
45604    u8 lockType = READ_LOCK + isWriteLock;
45605    assert( READ_LOCK+1==WRITE_LOCK );
45606    assert( isWriteLock==0 || isWriteLock==1 );
45607
45608    sqlite3BtreeEnter(p);
45609    rc = querySharedCacheTableLock(p, iTab, lockType);
45610    if( rc==SQLITE_OK ){
45611      rc = setSharedCacheTableLock(p, iTab, lockType);
45612    }
45613    sqlite3BtreeLeave(p);
45614  }
45615  return rc;
45616}
45617#endif
45618
45619#ifndef SQLITE_OMIT_INCRBLOB
45620/*
45621** Argument pCsr must be a cursor opened for writing on an
45622** INTKEY table currently pointing at a valid table entry.
45623** This function modifies the data stored as part of that entry.
45624**
45625** Only the data content may only be modified, it is not possible to
45626** change the length of the data stored. If this function is called with
45627** parameters that attempt to write past the end of the existing data,
45628** no modifications are made and SQLITE_CORRUPT is returned.
45629*/
45630SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
45631  int rc;
45632  assert( cursorHoldsMutex(pCsr) );
45633  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
45634  assert( pCsr->isIncrblobHandle );
45635
45636  rc = restoreCursorPosition(pCsr);
45637  if( rc!=SQLITE_OK ){
45638    return rc;
45639  }
45640  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
45641  if( pCsr->eState!=CURSOR_VALID ){
45642    return SQLITE_ABORT;
45643  }
45644
45645  /* Check some assumptions:
45646  **   (a) the cursor is open for writing,
45647  **   (b) there is a read/write transaction open,
45648  **   (c) the connection holds a write-lock on the table (if required),
45649  **   (d) there are no conflicting read-locks, and
45650  **   (e) the cursor points at a valid row of an intKey table.
45651  */
45652  if( !pCsr->wrFlag ){
45653    return SQLITE_READONLY;
45654  }
45655  assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
45656  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
45657  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
45658  assert( pCsr->apPage[pCsr->iPage]->intKey );
45659
45660  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
45661}
45662
45663/*
45664** Set a flag on this cursor to cache the locations of pages from the
45665** overflow list for the current row. This is used by cursors opened
45666** for incremental blob IO only.
45667**
45668** This function sets a flag only. The actual page location cache
45669** (stored in BtCursor.aOverflow[]) is allocated and used by function
45670** accessPayload() (the worker function for sqlite3BtreeData() and
45671** sqlite3BtreePutData()).
45672*/
45673SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
45674  assert( cursorHoldsMutex(pCur) );
45675  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
45676  assert(!pCur->isIncrblobHandle);
45677  assert(!pCur->aOverflow);
45678  pCur->isIncrblobHandle = 1;
45679}
45680#endif
45681
45682/************** End of btree.c ***********************************************/
45683/************** Begin file backup.c ******************************************/
45684/*
45685** 2009 January 28
45686**
45687** The author disclaims copyright to this source code.  In place of
45688** a legal notice, here is a blessing:
45689**
45690**    May you do good and not evil.
45691**    May you find forgiveness for yourself and forgive others.
45692**    May you share freely, never taking more than you give.
45693**
45694*************************************************************************
45695** This file contains the implementation of the sqlite3_backup_XXX()
45696** API functions and the related features.
45697*/
45698
45699/* Macro to find the minimum of two numeric values.
45700*/
45701#ifndef MIN
45702# define MIN(x,y) ((x)<(y)?(x):(y))
45703#endif
45704
45705/*
45706** Structure allocated for each backup operation.
45707*/
45708struct sqlite3_backup {
45709  sqlite3* pDestDb;        /* Destination database handle */
45710  Btree *pDest;            /* Destination b-tree file */
45711  u32 iDestSchema;         /* Original schema cookie in destination */
45712  int bDestLocked;         /* True once a write-transaction is open on pDest */
45713
45714  Pgno iNext;              /* Page number of the next source page to copy */
45715  sqlite3* pSrcDb;         /* Source database handle */
45716  Btree *pSrc;             /* Source b-tree file */
45717
45718  int rc;                  /* Backup process error code */
45719
45720  /* These two variables are set by every call to backup_step(). They are
45721  ** read by calls to backup_remaining() and backup_pagecount().
45722  */
45723  Pgno nRemaining;         /* Number of pages left to copy */
45724  Pgno nPagecount;         /* Total number of pages to copy */
45725
45726  int isAttached;          /* True once backup has been registered with pager */
45727  sqlite3_backup *pNext;   /* Next backup associated with source pager */
45728};
45729
45730/*
45731** THREAD SAFETY NOTES:
45732**
45733**   Once it has been created using backup_init(), a single sqlite3_backup
45734**   structure may be accessed via two groups of thread-safe entry points:
45735**
45736**     * Via the sqlite3_backup_XXX() API function backup_step() and
45737**       backup_finish(). Both these functions obtain the source database
45738**       handle mutex and the mutex associated with the source BtShared
45739**       structure, in that order.
45740**
45741**     * Via the BackupUpdate() and BackupRestart() functions, which are
45742**       invoked by the pager layer to report various state changes in
45743**       the page cache associated with the source database. The mutex
45744**       associated with the source database BtShared structure will always
45745**       be held when either of these functions are invoked.
45746**
45747**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
45748**   backup_pagecount() are not thread-safe functions. If they are called
45749**   while some other thread is calling backup_step() or backup_finish(),
45750**   the values returned may be invalid. There is no way for a call to
45751**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
45752**   or backup_pagecount().
45753**
45754**   Depending on the SQLite configuration, the database handles and/or
45755**   the Btree objects may have their own mutexes that require locking.
45756**   Non-sharable Btrees (in-memory databases for example), do not have
45757**   associated mutexes.
45758*/
45759
45760/*
45761** Return a pointer corresponding to database zDb (i.e. "main", "temp")
45762** in connection handle pDb. If such a database cannot be found, return
45763** a NULL pointer and write an error message to pErrorDb.
45764**
45765** If the "temp" database is requested, it may need to be opened by this
45766** function. If an error occurs while doing so, return 0 and write an
45767** error message to pErrorDb.
45768*/
45769static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
45770  int i = sqlite3FindDbName(pDb, zDb);
45771
45772  if( i==1 ){
45773    Parse *pParse;
45774    int rc = 0;
45775    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
45776    if( pParse==0 ){
45777      sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
45778      rc = SQLITE_NOMEM;
45779    }else{
45780      pParse->db = pDb;
45781      if( sqlite3OpenTempDatabase(pParse) ){
45782        sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
45783        rc = SQLITE_ERROR;
45784      }
45785      sqlite3DbFree(pErrorDb, pParse->zErrMsg);
45786      sqlite3StackFree(pErrorDb, pParse);
45787    }
45788    if( rc ){
45789      return 0;
45790    }
45791  }
45792
45793  if( i<0 ){
45794    sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
45795    return 0;
45796  }
45797
45798  return pDb->aDb[i].pBt;
45799}
45800
45801/*
45802** Create an sqlite3_backup process to copy the contents of zSrcDb from
45803** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
45804** a pointer to the new sqlite3_backup object.
45805**
45806** If an error occurs, NULL is returned and an error code and error message
45807** stored in database handle pDestDb.
45808*/
45809SQLITE_API sqlite3_backup *sqlite3_backup_init(
45810  sqlite3* pDestDb,                     /* Database to write to */
45811  const char *zDestDb,                  /* Name of database within pDestDb */
45812  sqlite3* pSrcDb,                      /* Database connection to read from */
45813  const char *zSrcDb                    /* Name of database within pSrcDb */
45814){
45815  sqlite3_backup *p;                    /* Value to return */
45816
45817  /* Lock the source database handle. The destination database
45818  ** handle is not locked in this routine, but it is locked in
45819  ** sqlite3_backup_step(). The user is required to ensure that no
45820  ** other thread accesses the destination handle for the duration
45821  ** of the backup operation.  Any attempt to use the destination
45822  ** database connection while a backup is in progress may cause
45823  ** a malfunction or a deadlock.
45824  */
45825  sqlite3_mutex_enter(pSrcDb->mutex);
45826  sqlite3_mutex_enter(pDestDb->mutex);
45827
45828  if( pSrcDb==pDestDb ){
45829    sqlite3Error(
45830        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
45831    );
45832    p = 0;
45833  }else {
45834    /* Allocate space for a new sqlite3_backup object */
45835    p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
45836    if( !p ){
45837      sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
45838    }
45839  }
45840
45841  /* If the allocation succeeded, populate the new object. */
45842  if( p ){
45843    memset(p, 0, sizeof(sqlite3_backup));
45844    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
45845    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
45846    p->pDestDb = pDestDb;
45847    p->pSrcDb = pSrcDb;
45848    p->iNext = 1;
45849    p->isAttached = 0;
45850
45851    if( 0==p->pSrc || 0==p->pDest ){
45852      /* One (or both) of the named databases did not exist. An error has
45853      ** already been written into the pDestDb handle. All that is left
45854      ** to do here is free the sqlite3_backup structure.
45855      */
45856      sqlite3_free(p);
45857      p = 0;
45858    }
45859  }
45860  if( p ){
45861    p->pSrc->nBackup++;
45862  }
45863
45864  sqlite3_mutex_leave(pDestDb->mutex);
45865  sqlite3_mutex_leave(pSrcDb->mutex);
45866  return p;
45867}
45868
45869/*
45870** Argument rc is an SQLite error code. Return true if this error is
45871** considered fatal if encountered during a backup operation. All errors
45872** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
45873*/
45874static int isFatalError(int rc){
45875  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
45876}
45877
45878/*
45879** Parameter zSrcData points to a buffer containing the data for
45880** page iSrcPg from the source database. Copy this data into the
45881** destination database.
45882*/
45883static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
45884  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
45885  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
45886  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
45887  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
45888  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
45889
45890  int rc = SQLITE_OK;
45891  i64 iOff;
45892
45893  assert( p->bDestLocked );
45894  assert( !isFatalError(p->rc) );
45895  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
45896  assert( zSrcData );
45897
45898  /* Catch the case where the destination is an in-memory database and the
45899  ** page sizes of the source and destination differ.
45900  */
45901  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(sqlite3BtreePager(p->pDest)) ){
45902    rc = SQLITE_READONLY;
45903  }
45904
45905  /* This loop runs once for each destination page spanned by the source
45906  ** page. For each iteration, variable iOff is set to the byte offset
45907  ** of the destination page.
45908  */
45909  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
45910    DbPage *pDestPg = 0;
45911    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
45912    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
45913    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
45914     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
45915    ){
45916      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
45917      u8 *zDestData = sqlite3PagerGetData(pDestPg);
45918      u8 *zOut = &zDestData[iOff%nDestPgsz];
45919
45920      /* Copy the data from the source page into the destination page.
45921      ** Then clear the Btree layer MemPage.isInit flag. Both this module
45922      ** and the pager code use this trick (clearing the first byte
45923      ** of the page 'extra' space to invalidate the Btree layers
45924      ** cached parse of the page). MemPage.isInit is marked
45925      ** "MUST BE FIRST" for this purpose.
45926      */
45927      memcpy(zOut, zIn, nCopy);
45928      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
45929    }
45930    sqlite3PagerUnref(pDestPg);
45931  }
45932
45933  return rc;
45934}
45935
45936/*
45937** If pFile is currently larger than iSize bytes, then truncate it to
45938** exactly iSize bytes. If pFile is not larger than iSize bytes, then
45939** this function is a no-op.
45940**
45941** Return SQLITE_OK if everything is successful, or an SQLite error
45942** code if an error occurs.
45943*/
45944static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
45945  i64 iCurrent;
45946  int rc = sqlite3OsFileSize(pFile, &iCurrent);
45947  if( rc==SQLITE_OK && iCurrent>iSize ){
45948    rc = sqlite3OsTruncate(pFile, iSize);
45949  }
45950  return rc;
45951}
45952
45953/*
45954** Register this backup object with the associated source pager for
45955** callbacks when pages are changed or the cache invalidated.
45956*/
45957static void attachBackupObject(sqlite3_backup *p){
45958  sqlite3_backup **pp;
45959  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
45960  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
45961  p->pNext = *pp;
45962  *pp = p;
45963  p->isAttached = 1;
45964}
45965
45966/*
45967** Copy nPage pages from the source b-tree to the destination.
45968*/
45969SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
45970  int rc;
45971
45972  sqlite3_mutex_enter(p->pSrcDb->mutex);
45973  sqlite3BtreeEnter(p->pSrc);
45974  if( p->pDestDb ){
45975    sqlite3_mutex_enter(p->pDestDb->mutex);
45976  }
45977
45978  rc = p->rc;
45979  if( !isFatalError(rc) ){
45980    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
45981    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
45982    int ii;                            /* Iterator variable */
45983    int nSrcPage = -1;                 /* Size of source db in pages */
45984    int bCloseTrans = 0;               /* True if src db requires unlocking */
45985
45986    /* If the source pager is currently in a write-transaction, return
45987    ** SQLITE_BUSY immediately.
45988    */
45989    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
45990      rc = SQLITE_BUSY;
45991    }else{
45992      rc = SQLITE_OK;
45993    }
45994
45995    /* Lock the destination database, if it is not locked already. */
45996    if( SQLITE_OK==rc && p->bDestLocked==0
45997     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
45998    ){
45999      p->bDestLocked = 1;
46000      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
46001    }
46002
46003    /* If there is no open read-transaction on the source database, open
46004    ** one now. If a transaction is opened here, then it will be closed
46005    ** before this function exits.
46006    */
46007    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
46008      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
46009      bCloseTrans = 1;
46010    }
46011
46012    /* Now that there is a read-lock on the source database, query the
46013    ** source pager for the number of pages in the database.
46014    */
46015    if( rc==SQLITE_OK ){
46016      rc = sqlite3PagerPagecount(pSrcPager, &nSrcPage);
46017    }
46018    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
46019      const Pgno iSrcPg = p->iNext;                 /* Source page number */
46020      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
46021        DbPage *pSrcPg;                             /* Source page object */
46022        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
46023        if( rc==SQLITE_OK ){
46024          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
46025          sqlite3PagerUnref(pSrcPg);
46026        }
46027      }
46028      p->iNext++;
46029    }
46030    if( rc==SQLITE_OK ){
46031      p->nPagecount = nSrcPage;
46032      p->nRemaining = nSrcPage+1-p->iNext;
46033      if( p->iNext>(Pgno)nSrcPage ){
46034        rc = SQLITE_DONE;
46035      }else if( !p->isAttached ){
46036        attachBackupObject(p);
46037      }
46038    }
46039
46040    /* Update the schema version field in the destination database. This
46041    ** is to make sure that the schema-version really does change in
46042    ** the case where the source and destination databases have the
46043    ** same schema version.
46044    */
46045    if( rc==SQLITE_DONE
46046     && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
46047    ){
46048      const int nSrcPagesize = sqlite3BtreeGetPageSize(p->pSrc);
46049      const int nDestPagesize = sqlite3BtreeGetPageSize(p->pDest);
46050      int nDestTruncate;
46051
46052      if( p->pDestDb ){
46053        sqlite3ResetInternalSchema(p->pDestDb, 0);
46054      }
46055
46056      /* Set nDestTruncate to the final number of pages in the destination
46057      ** database. The complication here is that the destination page
46058      ** size may be different to the source page size.
46059      **
46060      ** If the source page size is smaller than the destination page size,
46061      ** round up. In this case the call to sqlite3OsTruncate() below will
46062      ** fix the size of the file. However it is important to call
46063      ** sqlite3PagerTruncateImage() here so that any pages in the
46064      ** destination file that lie beyond the nDestTruncate page mark are
46065      ** journalled by PagerCommitPhaseOne() before they are destroyed
46066      ** by the file truncation.
46067      */
46068      if( nSrcPagesize<nDestPagesize ){
46069        int ratio = nDestPagesize/nSrcPagesize;
46070        nDestTruncate = (nSrcPage+ratio-1)/ratio;
46071        if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
46072          nDestTruncate--;
46073        }
46074      }else{
46075        nDestTruncate = nSrcPage * (nSrcPagesize/nDestPagesize);
46076      }
46077      sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
46078
46079      if( nSrcPagesize<nDestPagesize ){
46080        /* If the source page-size is smaller than the destination page-size,
46081        ** two extra things may need to happen:
46082        **
46083        **   * The destination may need to be truncated, and
46084        **
46085        **   * Data stored on the pages immediately following the
46086        **     pending-byte page in the source database may need to be
46087        **     copied into the destination database.
46088        */
46089        const i64 iSize = (i64)nSrcPagesize * (i64)nSrcPage;
46090        sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
46091
46092        assert( pFile );
46093        assert( (i64)nDestTruncate*(i64)nDestPagesize >= iSize || (
46094              nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
46095           && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+nDestPagesize
46096        ));
46097        if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
46098         && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
46099         && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
46100        ){
46101          i64 iOff;
46102          i64 iEnd = MIN(PENDING_BYTE + nDestPagesize, iSize);
46103          for(
46104            iOff=PENDING_BYTE+nSrcPagesize;
46105            rc==SQLITE_OK && iOff<iEnd;
46106            iOff+=nSrcPagesize
46107          ){
46108            PgHdr *pSrcPg = 0;
46109            const Pgno iSrcPg = (Pgno)((iOff/nSrcPagesize)+1);
46110            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
46111            if( rc==SQLITE_OK ){
46112              u8 *zData = sqlite3PagerGetData(pSrcPg);
46113              rc = sqlite3OsWrite(pFile, zData, nSrcPagesize, iOff);
46114            }
46115            sqlite3PagerUnref(pSrcPg);
46116          }
46117        }
46118      }else{
46119        rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
46120      }
46121
46122      /* Finish committing the transaction to the destination database. */
46123      if( SQLITE_OK==rc
46124       && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
46125      ){
46126        rc = SQLITE_DONE;
46127      }
46128    }
46129
46130    /* If bCloseTrans is true, then this function opened a read transaction
46131    ** on the source database. Close the read transaction here. There is
46132    ** no need to check the return values of the btree methods here, as
46133    ** "committing" a read-only transaction cannot fail.
46134    */
46135    if( bCloseTrans ){
46136      TESTONLY( int rc2 );
46137      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
46138      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
46139      assert( rc2==SQLITE_OK );
46140    }
46141
46142    p->rc = rc;
46143  }
46144  if( p->pDestDb ){
46145    sqlite3_mutex_leave(p->pDestDb->mutex);
46146  }
46147  sqlite3BtreeLeave(p->pSrc);
46148  sqlite3_mutex_leave(p->pSrcDb->mutex);
46149  return rc;
46150}
46151
46152/*
46153** Release all resources associated with an sqlite3_backup* handle.
46154*/
46155SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
46156  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
46157  sqlite3_mutex *mutex;                /* Mutex to protect source database */
46158  int rc;                              /* Value to return */
46159
46160  /* Enter the mutexes */
46161  if( p==0 ) return SQLITE_OK;
46162  sqlite3_mutex_enter(p->pSrcDb->mutex);
46163  sqlite3BtreeEnter(p->pSrc);
46164  mutex = p->pSrcDb->mutex;
46165  if( p->pDestDb ){
46166    sqlite3_mutex_enter(p->pDestDb->mutex);
46167  }
46168
46169  /* Detach this backup from the source pager. */
46170  if( p->pDestDb ){
46171    p->pSrc->nBackup--;
46172  }
46173  if( p->isAttached ){
46174    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
46175    while( *pp!=p ){
46176      pp = &(*pp)->pNext;
46177    }
46178    *pp = p->pNext;
46179  }
46180
46181  /* If a transaction is still open on the Btree, roll it back. */
46182  sqlite3BtreeRollback(p->pDest);
46183
46184  /* Set the error code of the destination database handle. */
46185  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
46186  sqlite3Error(p->pDestDb, rc, 0);
46187
46188  /* Exit the mutexes and free the backup context structure. */
46189  if( p->pDestDb ){
46190    sqlite3_mutex_leave(p->pDestDb->mutex);
46191  }
46192  sqlite3BtreeLeave(p->pSrc);
46193  if( p->pDestDb ){
46194    sqlite3_free(p);
46195  }
46196  sqlite3_mutex_leave(mutex);
46197  return rc;
46198}
46199
46200/*
46201** Return the number of pages still to be backed up as of the most recent
46202** call to sqlite3_backup_step().
46203*/
46204SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
46205  return p->nRemaining;
46206}
46207
46208/*
46209** Return the total number of pages in the source database as of the most
46210** recent call to sqlite3_backup_step().
46211*/
46212SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
46213  return p->nPagecount;
46214}
46215
46216/*
46217** This function is called after the contents of page iPage of the
46218** source database have been modified. If page iPage has already been
46219** copied into the destination database, then the data written to the
46220** destination is now invalidated. The destination copy of iPage needs
46221** to be updated with the new data before the backup operation is
46222** complete.
46223**
46224** It is assumed that the mutex associated with the BtShared object
46225** corresponding to the source database is held when this function is
46226** called.
46227*/
46228SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
46229  sqlite3_backup *p;                   /* Iterator variable */
46230  for(p=pBackup; p; p=p->pNext){
46231    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
46232    if( !isFatalError(p->rc) && iPage<p->iNext ){
46233      /* The backup process p has already copied page iPage. But now it
46234      ** has been modified by a transaction on the source pager. Copy
46235      ** the new data into the backup.
46236      */
46237      int rc = backupOnePage(p, iPage, aData);
46238      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
46239      if( rc!=SQLITE_OK ){
46240        p->rc = rc;
46241      }
46242    }
46243  }
46244}
46245
46246/*
46247** Restart the backup process. This is called when the pager layer
46248** detects that the database has been modified by an external database
46249** connection. In this case there is no way of knowing which of the
46250** pages that have been copied into the destination database are still
46251** valid and which are not, so the entire process needs to be restarted.
46252**
46253** It is assumed that the mutex associated with the BtShared object
46254** corresponding to the source database is held when this function is
46255** called.
46256*/
46257SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
46258  sqlite3_backup *p;                   /* Iterator variable */
46259  for(p=pBackup; p; p=p->pNext){
46260    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
46261    p->iNext = 1;
46262  }
46263}
46264
46265#ifndef SQLITE_OMIT_VACUUM
46266/*
46267** Copy the complete content of pBtFrom into pBtTo.  A transaction
46268** must be active for both files.
46269**
46270** The size of file pTo may be reduced by this operation. If anything
46271** goes wrong, the transaction on pTo is rolled back. If successful, the
46272** transaction is committed before returning.
46273*/
46274SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
46275  int rc;
46276  sqlite3_backup b;
46277  sqlite3BtreeEnter(pTo);
46278  sqlite3BtreeEnter(pFrom);
46279
46280  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
46281  ** to 0. This is used by the implementations of sqlite3_backup_step()
46282  ** and sqlite3_backup_finish() to detect that they are being called
46283  ** from this function, not directly by the user.
46284  */
46285  memset(&b, 0, sizeof(b));
46286  b.pSrcDb = pFrom->db;
46287  b.pSrc = pFrom;
46288  b.pDest = pTo;
46289  b.iNext = 1;
46290
46291  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
46292  ** file. By passing this as the number of pages to copy to
46293  ** sqlite3_backup_step(), we can guarantee that the copy finishes
46294  ** within a single call (unless an error occurs). The assert() statement
46295  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
46296  ** or an error code.
46297  */
46298  sqlite3_backup_step(&b, 0x7FFFFFFF);
46299  assert( b.rc!=SQLITE_OK );
46300  rc = sqlite3_backup_finish(&b);
46301  if( rc==SQLITE_OK ){
46302    pTo->pBt->pageSizeFixed = 0;
46303  }
46304
46305  sqlite3BtreeLeave(pFrom);
46306  sqlite3BtreeLeave(pTo);
46307  return rc;
46308}
46309#endif /* SQLITE_OMIT_VACUUM */
46310
46311/************** End of backup.c **********************************************/
46312/************** Begin file vdbemem.c *****************************************/
46313/*
46314** 2004 May 26
46315**
46316** The author disclaims copyright to this source code.  In place of
46317** a legal notice, here is a blessing:
46318**
46319**    May you do good and not evil.
46320**    May you find forgiveness for yourself and forgive others.
46321**    May you share freely, never taking more than you give.
46322**
46323*************************************************************************
46324**
46325** This file contains code use to manipulate "Mem" structure.  A "Mem"
46326** stores a single value in the VDBE.  Mem is an opaque structure visible
46327** only within the VDBE.  Interface routines refer to a Mem using the
46328** name sqlite_value
46329*/
46330
46331/*
46332** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
46333** P if required.
46334*/
46335#define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
46336
46337/*
46338** If pMem is an object with a valid string representation, this routine
46339** ensures the internal encoding for the string representation is
46340** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
46341**
46342** If pMem is not a string object, or the encoding of the string
46343** representation is already stored using the requested encoding, then this
46344** routine is a no-op.
46345**
46346** SQLITE_OK is returned if the conversion is successful (or not required).
46347** SQLITE_NOMEM may be returned if a malloc() fails during conversion
46348** between formats.
46349*/
46350SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
46351  int rc;
46352  assert( (pMem->flags&MEM_RowSet)==0 );
46353  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
46354           || desiredEnc==SQLITE_UTF16BE );
46355  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
46356    return SQLITE_OK;
46357  }
46358  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46359#ifdef SQLITE_OMIT_UTF16
46360  return SQLITE_ERROR;
46361#else
46362
46363  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
46364  ** then the encoding of the value may not have changed.
46365  */
46366  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
46367  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
46368  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
46369  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
46370  return rc;
46371#endif
46372}
46373
46374/*
46375** Make sure pMem->z points to a writable allocation of at least
46376** n bytes.
46377**
46378** If the memory cell currently contains string or blob data
46379** and the third argument passed to this function is true, the
46380** current content of the cell is preserved. Otherwise, it may
46381** be discarded.
46382**
46383** This function sets the MEM_Dyn flag and clears any xDel callback.
46384** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
46385** not set, Mem.n is zeroed.
46386*/
46387SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
46388  assert( 1 >=
46389    ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
46390    (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
46391    ((pMem->flags&MEM_Ephem) ? 1 : 0) +
46392    ((pMem->flags&MEM_Static) ? 1 : 0)
46393  );
46394  assert( (pMem->flags&MEM_RowSet)==0 );
46395
46396  if( n<32 ) n = 32;
46397  if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
46398    if( preserve && pMem->z==pMem->zMalloc ){
46399      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
46400      preserve = 0;
46401    }else{
46402      sqlite3DbFree(pMem->db, pMem->zMalloc);
46403      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
46404    }
46405  }
46406
46407  if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
46408    memcpy(pMem->zMalloc, pMem->z, pMem->n);
46409  }
46410  if( pMem->flags&MEM_Dyn && pMem->xDel ){
46411    pMem->xDel((void *)(pMem->z));
46412  }
46413
46414  pMem->z = pMem->zMalloc;
46415  if( pMem->z==0 ){
46416    pMem->flags = MEM_Null;
46417  }else{
46418    pMem->flags &= ~(MEM_Ephem|MEM_Static);
46419  }
46420  pMem->xDel = 0;
46421  return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
46422}
46423
46424/*
46425** Make the given Mem object MEM_Dyn.  In other words, make it so
46426** that any TEXT or BLOB content is stored in memory obtained from
46427** malloc().  In this way, we know that the memory is safe to be
46428** overwritten or altered.
46429**
46430** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
46431*/
46432SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
46433  int f;
46434  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46435  assert( (pMem->flags&MEM_RowSet)==0 );
46436  expandBlob(pMem);
46437  f = pMem->flags;
46438  if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
46439    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
46440      return SQLITE_NOMEM;
46441    }
46442    pMem->z[pMem->n] = 0;
46443    pMem->z[pMem->n+1] = 0;
46444    pMem->flags |= MEM_Term;
46445  }
46446
46447  return SQLITE_OK;
46448}
46449
46450/*
46451** If the given Mem* has a zero-filled tail, turn it into an ordinary
46452** blob stored in dynamically allocated space.
46453*/
46454#ifndef SQLITE_OMIT_INCRBLOB
46455SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
46456  if( pMem->flags & MEM_Zero ){
46457    int nByte;
46458    assert( pMem->flags&MEM_Blob );
46459    assert( (pMem->flags&MEM_RowSet)==0 );
46460    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46461
46462    /* Set nByte to the number of bytes required to store the expanded blob. */
46463    nByte = pMem->n + pMem->u.nZero;
46464    if( nByte<=0 ){
46465      nByte = 1;
46466    }
46467    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
46468      return SQLITE_NOMEM;
46469    }
46470
46471    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
46472    pMem->n += pMem->u.nZero;
46473    pMem->flags &= ~(MEM_Zero|MEM_Term);
46474  }
46475  return SQLITE_OK;
46476}
46477#endif
46478
46479
46480/*
46481** Make sure the given Mem is \u0000 terminated.
46482*/
46483SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
46484  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46485  if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
46486    return SQLITE_OK;   /* Nothing to do */
46487  }
46488  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
46489    return SQLITE_NOMEM;
46490  }
46491  pMem->z[pMem->n] = 0;
46492  pMem->z[pMem->n+1] = 0;
46493  pMem->flags |= MEM_Term;
46494  return SQLITE_OK;
46495}
46496
46497/*
46498** Add MEM_Str to the set of representations for the given Mem.  Numbers
46499** are converted using sqlite3_snprintf().  Converting a BLOB to a string
46500** is a no-op.
46501**
46502** Existing representations MEM_Int and MEM_Real are *not* invalidated.
46503**
46504** A MEM_Null value will never be passed to this function. This function is
46505** used for converting values to text for returning to the user (i.e. via
46506** sqlite3_value_text()), or for ensuring that values to be used as btree
46507** keys are strings. In the former case a NULL pointer is returned the
46508** user and the later is an internal programming error.
46509*/
46510SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
46511  int rc = SQLITE_OK;
46512  int fg = pMem->flags;
46513  const int nByte = 32;
46514
46515  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46516  assert( !(fg&MEM_Zero) );
46517  assert( !(fg&(MEM_Str|MEM_Blob)) );
46518  assert( fg&(MEM_Int|MEM_Real) );
46519  assert( (pMem->flags&MEM_RowSet)==0 );
46520  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46521
46522
46523  if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
46524    return SQLITE_NOMEM;
46525  }
46526
46527  /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
46528  ** string representation of the value. Then, if the required encoding
46529  ** is UTF-16le or UTF-16be do a translation.
46530  **
46531  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
46532  */
46533  if( fg & MEM_Int ){
46534    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
46535  }else{
46536    assert( fg & MEM_Real );
46537    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
46538  }
46539  pMem->n = sqlite3Strlen30(pMem->z);
46540  pMem->enc = SQLITE_UTF8;
46541  pMem->flags |= MEM_Str|MEM_Term;
46542  sqlite3VdbeChangeEncoding(pMem, enc);
46543  return rc;
46544}
46545
46546/*
46547** Memory cell pMem contains the context of an aggregate function.
46548** This routine calls the finalize method for that function.  The
46549** result of the aggregate is stored back into pMem.
46550**
46551** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
46552** otherwise.
46553*/
46554SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
46555  int rc = SQLITE_OK;
46556  if( ALWAYS(pFunc && pFunc->xFinalize) ){
46557    sqlite3_context ctx;
46558    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
46559    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46560    memset(&ctx, 0, sizeof(ctx));
46561    ctx.s.flags = MEM_Null;
46562    ctx.s.db = pMem->db;
46563    ctx.pMem = pMem;
46564    ctx.pFunc = pFunc;
46565    pFunc->xFinalize(&ctx);
46566    assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
46567    sqlite3DbFree(pMem->db, pMem->zMalloc);
46568    memcpy(pMem, &ctx.s, sizeof(ctx.s));
46569    rc = ctx.isError;
46570  }
46571  return rc;
46572}
46573
46574/*
46575** If the memory cell contains a string value that must be freed by
46576** invoking an external callback, free it now. Calling this function
46577** does not free any Mem.zMalloc buffer.
46578*/
46579SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
46580  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
46581  testcase( p->flags & MEM_Agg );
46582  testcase( p->flags & MEM_Dyn );
46583  testcase( p->flags & MEM_RowSet );
46584  testcase( p->flags & MEM_Frame );
46585  if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
46586    if( p->flags&MEM_Agg ){
46587      sqlite3VdbeMemFinalize(p, p->u.pDef);
46588      assert( (p->flags & MEM_Agg)==0 );
46589      sqlite3VdbeMemRelease(p);
46590    }else if( p->flags&MEM_Dyn && p->xDel ){
46591      assert( (p->flags&MEM_RowSet)==0 );
46592      p->xDel((void *)p->z);
46593      p->xDel = 0;
46594    }else if( p->flags&MEM_RowSet ){
46595      sqlite3RowSetClear(p->u.pRowSet);
46596    }else if( p->flags&MEM_Frame ){
46597      sqlite3VdbeMemSetNull(p);
46598    }
46599  }
46600}
46601
46602/*
46603** Release any memory held by the Mem. This may leave the Mem in an
46604** inconsistent state, for example with (Mem.z==0) and
46605** (Mem.type==SQLITE_TEXT).
46606*/
46607SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
46608  sqlite3VdbeMemReleaseExternal(p);
46609  sqlite3DbFree(p->db, p->zMalloc);
46610  p->z = 0;
46611  p->zMalloc = 0;
46612  p->xDel = 0;
46613}
46614
46615/*
46616** Convert a 64-bit IEEE double into a 64-bit signed integer.
46617** If the double is too large, return 0x8000000000000000.
46618**
46619** Most systems appear to do this simply by assigning
46620** variables and without the extra range tests.  But
46621** there are reports that windows throws an expection
46622** if the floating point value is out of range. (See ticket #2880.)
46623** Because we do not completely understand the problem, we will
46624** take the conservative approach and always do range tests
46625** before attempting the conversion.
46626*/
46627static i64 doubleToInt64(double r){
46628  /*
46629  ** Many compilers we encounter do not define constants for the
46630  ** minimum and maximum 64-bit integers, or they define them
46631  ** inconsistently.  And many do not understand the "LL" notation.
46632  ** So we define our own static constants here using nothing
46633  ** larger than a 32-bit integer constant.
46634  */
46635  static const i64 maxInt = LARGEST_INT64;
46636  static const i64 minInt = SMALLEST_INT64;
46637
46638  if( r<(double)minInt ){
46639    return minInt;
46640  }else if( r>(double)maxInt ){
46641    /* minInt is correct here - not maxInt.  It turns out that assigning
46642    ** a very large positive number to an integer results in a very large
46643    ** negative integer.  This makes no sense, but it is what x86 hardware
46644    ** does so for compatibility we will do the same in software. */
46645    return minInt;
46646  }else{
46647    return (i64)r;
46648  }
46649}
46650
46651/*
46652** Return some kind of integer value which is the best we can do
46653** at representing the value that *pMem describes as an integer.
46654** If pMem is an integer, then the value is exact.  If pMem is
46655** a floating-point then the value returned is the integer part.
46656** If pMem is a string or blob, then we make an attempt to convert
46657** it into a integer and return that.  If pMem represents an
46658** an SQL-NULL value, return 0.
46659**
46660** If pMem represents a string value, its encoding might be changed.
46661*/
46662SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
46663  int flags;
46664  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46665  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46666  flags = pMem->flags;
46667  if( flags & MEM_Int ){
46668    return pMem->u.i;
46669  }else if( flags & MEM_Real ){
46670    return doubleToInt64(pMem->r);
46671  }else if( flags & (MEM_Str|MEM_Blob) ){
46672    i64 value;
46673    pMem->flags |= MEM_Str;
46674    if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
46675       || sqlite3VdbeMemNulTerminate(pMem) ){
46676      return 0;
46677    }
46678    assert( pMem->z );
46679    sqlite3Atoi64(pMem->z, &value);
46680    return value;
46681  }else{
46682    return 0;
46683  }
46684}
46685
46686/*
46687** Return the best representation of pMem that we can get into a
46688** double.  If pMem is already a double or an integer, return its
46689** value.  If it is a string or blob, try to convert it to a double.
46690** If it is a NULL, return 0.0.
46691*/
46692SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
46693  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46694  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46695  if( pMem->flags & MEM_Real ){
46696    return pMem->r;
46697  }else if( pMem->flags & MEM_Int ){
46698    return (double)pMem->u.i;
46699  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
46700    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
46701    double val = (double)0;
46702    pMem->flags |= MEM_Str;
46703    if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
46704       || sqlite3VdbeMemNulTerminate(pMem) ){
46705      /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
46706      return (double)0;
46707    }
46708    assert( pMem->z );
46709    sqlite3AtoF(pMem->z, &val);
46710    return val;
46711  }else{
46712    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
46713    return (double)0;
46714  }
46715}
46716
46717/*
46718** The MEM structure is already a MEM_Real.  Try to also make it a
46719** MEM_Int if we can.
46720*/
46721SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
46722  assert( pMem->flags & MEM_Real );
46723  assert( (pMem->flags & MEM_RowSet)==0 );
46724  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46725  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46726
46727  pMem->u.i = doubleToInt64(pMem->r);
46728
46729  /* Only mark the value as an integer if
46730  **
46731  **    (1) the round-trip conversion real->int->real is a no-op, and
46732  **    (2) The integer is neither the largest nor the smallest
46733  **        possible integer (ticket #3922)
46734  **
46735  ** The second and third terms in the following conditional enforces
46736  ** the second condition under the assumption that addition overflow causes
46737  ** values to wrap around.  On x86 hardware, the third term is always
46738  ** true and could be omitted.  But we leave it in because other
46739  ** architectures might behave differently.
46740  */
46741  if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
46742      && ALWAYS(pMem->u.i<LARGEST_INT64) ){
46743    pMem->flags |= MEM_Int;
46744  }
46745}
46746
46747/*
46748** Convert pMem to type integer.  Invalidate any prior representations.
46749*/
46750SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
46751  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46752  assert( (pMem->flags & MEM_RowSet)==0 );
46753  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46754
46755  pMem->u.i = sqlite3VdbeIntValue(pMem);
46756  MemSetTypeFlag(pMem, MEM_Int);
46757  return SQLITE_OK;
46758}
46759
46760/*
46761** Convert pMem so that it is of type MEM_Real.
46762** Invalidate any prior representations.
46763*/
46764SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
46765  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46766  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46767
46768  pMem->r = sqlite3VdbeRealValue(pMem);
46769  MemSetTypeFlag(pMem, MEM_Real);
46770  return SQLITE_OK;
46771}
46772
46773/*
46774** Convert pMem so that it has types MEM_Real or MEM_Int or both.
46775** Invalidate any prior representations.
46776*/
46777SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
46778  double r1, r2;
46779  i64 i;
46780  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
46781  assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
46782  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46783  r1 = sqlite3VdbeRealValue(pMem);
46784  i = doubleToInt64(r1);
46785  r2 = (double)i;
46786  if( r1==r2 ){
46787    sqlite3VdbeMemIntegerify(pMem);
46788  }else{
46789    pMem->r = r1;
46790    MemSetTypeFlag(pMem, MEM_Real);
46791  }
46792  return SQLITE_OK;
46793}
46794
46795/*
46796** Delete any previous value and set the value stored in *pMem to NULL.
46797*/
46798SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
46799  if( pMem->flags & MEM_Frame ){
46800    sqlite3VdbeFrameDelete(pMem->u.pFrame);
46801  }
46802  if( pMem->flags & MEM_RowSet ){
46803    sqlite3RowSetClear(pMem->u.pRowSet);
46804  }
46805  MemSetTypeFlag(pMem, MEM_Null);
46806  pMem->type = SQLITE_NULL;
46807}
46808
46809/*
46810** Delete any previous value and set the value to be a BLOB of length
46811** n containing all zeros.
46812*/
46813SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
46814  sqlite3VdbeMemRelease(pMem);
46815  pMem->flags = MEM_Blob|MEM_Zero;
46816  pMem->type = SQLITE_BLOB;
46817  pMem->n = 0;
46818  if( n<0 ) n = 0;
46819  pMem->u.nZero = n;
46820  pMem->enc = SQLITE_UTF8;
46821
46822#ifdef SQLITE_OMIT_INCRBLOB
46823  sqlite3VdbeMemGrow(pMem, n, 0);
46824  if( pMem->z ){
46825    pMem->n = n;
46826    memset(pMem->z, 0, n);
46827  }
46828#endif
46829}
46830
46831/*
46832** Delete any previous value and set the value stored in *pMem to val,
46833** manifest type INTEGER.
46834*/
46835SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
46836  sqlite3VdbeMemRelease(pMem);
46837  pMem->u.i = val;
46838  pMem->flags = MEM_Int;
46839  pMem->type = SQLITE_INTEGER;
46840}
46841
46842/*
46843** Delete any previous value and set the value stored in *pMem to val,
46844** manifest type REAL.
46845*/
46846SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
46847  if( sqlite3IsNaN(val) ){
46848    sqlite3VdbeMemSetNull(pMem);
46849  }else{
46850    sqlite3VdbeMemRelease(pMem);
46851    pMem->r = val;
46852    pMem->flags = MEM_Real;
46853    pMem->type = SQLITE_FLOAT;
46854  }
46855}
46856
46857/*
46858** Delete any previous value and set the value of pMem to be an
46859** empty boolean index.
46860*/
46861SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
46862  sqlite3 *db = pMem->db;
46863  assert( db!=0 );
46864  assert( (pMem->flags & MEM_RowSet)==0 );
46865  sqlite3VdbeMemRelease(pMem);
46866  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
46867  if( db->mallocFailed ){
46868    pMem->flags = MEM_Null;
46869  }else{
46870    assert( pMem->zMalloc );
46871    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
46872                                       sqlite3DbMallocSize(db, pMem->zMalloc));
46873    assert( pMem->u.pRowSet!=0 );
46874    pMem->flags = MEM_RowSet;
46875  }
46876}
46877
46878/*
46879** Return true if the Mem object contains a TEXT or BLOB that is
46880** too large - whose size exceeds SQLITE_MAX_LENGTH.
46881*/
46882SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
46883  assert( p->db!=0 );
46884  if( p->flags & (MEM_Str|MEM_Blob) ){
46885    int n = p->n;
46886    if( p->flags & MEM_Zero ){
46887      n += p->u.nZero;
46888    }
46889    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
46890  }
46891  return 0;
46892}
46893
46894/*
46895** Size of struct Mem not including the Mem.zMalloc member.
46896*/
46897#define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
46898
46899/*
46900** Make an shallow copy of pFrom into pTo.  Prior contents of
46901** pTo are freed.  The pFrom->z field is not duplicated.  If
46902** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
46903** and flags gets srcType (either MEM_Ephem or MEM_Static).
46904*/
46905SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
46906  assert( (pFrom->flags & MEM_RowSet)==0 );
46907  sqlite3VdbeMemReleaseExternal(pTo);
46908  memcpy(pTo, pFrom, MEMCELLSIZE);
46909  pTo->xDel = 0;
46910  if( (pFrom->flags&MEM_Dyn)!=0 || pFrom->z==pFrom->zMalloc ){
46911    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
46912    assert( srcType==MEM_Ephem || srcType==MEM_Static );
46913    pTo->flags |= srcType;
46914  }
46915}
46916
46917/*
46918** Make a full copy of pFrom into pTo.  Prior contents of pTo are
46919** freed before the copy is made.
46920*/
46921SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
46922  int rc = SQLITE_OK;
46923
46924  assert( (pFrom->flags & MEM_RowSet)==0 );
46925  sqlite3VdbeMemReleaseExternal(pTo);
46926  memcpy(pTo, pFrom, MEMCELLSIZE);
46927  pTo->flags &= ~MEM_Dyn;
46928
46929  if( pTo->flags&(MEM_Str|MEM_Blob) ){
46930    if( 0==(pFrom->flags&MEM_Static) ){
46931      pTo->flags |= MEM_Ephem;
46932      rc = sqlite3VdbeMemMakeWriteable(pTo);
46933    }
46934  }
46935
46936  return rc;
46937}
46938
46939/*
46940** Transfer the contents of pFrom to pTo. Any existing value in pTo is
46941** freed. If pFrom contains ephemeral data, a copy is made.
46942**
46943** pFrom contains an SQL NULL when this routine returns.
46944*/
46945SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
46946  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
46947  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
46948  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
46949
46950  sqlite3VdbeMemRelease(pTo);
46951  memcpy(pTo, pFrom, sizeof(Mem));
46952  pFrom->flags = MEM_Null;
46953  pFrom->xDel = 0;
46954  pFrom->zMalloc = 0;
46955}
46956
46957/*
46958** Change the value of a Mem to be a string or a BLOB.
46959**
46960** The memory management strategy depends on the value of the xDel
46961** parameter. If the value passed is SQLITE_TRANSIENT, then the
46962** string is copied into a (possibly existing) buffer managed by the
46963** Mem structure. Otherwise, any existing buffer is freed and the
46964** pointer copied.
46965**
46966** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
46967** size limit) then no memory allocation occurs.  If the string can be
46968** stored without allocating memory, then it is.  If a memory allocation
46969** is required to store the string, then value of pMem is unchanged.  In
46970** either case, SQLITE_TOOBIG is returned.
46971*/
46972SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
46973  Mem *pMem,          /* Memory cell to set to string value */
46974  const char *z,      /* String pointer */
46975  int n,              /* Bytes in string, or negative */
46976  u8 enc,             /* Encoding of z.  0 for BLOBs */
46977  void (*xDel)(void*) /* Destructor function */
46978){
46979  int nByte = n;      /* New value for pMem->n */
46980  int iLimit;         /* Maximum allowed string or blob size */
46981  u16 flags = 0;      /* New value for pMem->flags */
46982
46983  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46984  assert( (pMem->flags & MEM_RowSet)==0 );
46985
46986  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
46987  if( !z ){
46988    sqlite3VdbeMemSetNull(pMem);
46989    return SQLITE_OK;
46990  }
46991
46992  if( pMem->db ){
46993    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
46994  }else{
46995    iLimit = SQLITE_MAX_LENGTH;
46996  }
46997  flags = (enc==0?MEM_Blob:MEM_Str);
46998  if( nByte<0 ){
46999    assert( enc!=0 );
47000    if( enc==SQLITE_UTF8 ){
47001      for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
47002    }else{
47003      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
47004    }
47005    flags |= MEM_Term;
47006  }
47007
47008  /* The following block sets the new values of Mem.z and Mem.xDel. It
47009  ** also sets a flag in local variable "flags" to indicate the memory
47010  ** management (one of MEM_Dyn or MEM_Static).
47011  */
47012  if( xDel==SQLITE_TRANSIENT ){
47013    int nAlloc = nByte;
47014    if( flags&MEM_Term ){
47015      nAlloc += (enc==SQLITE_UTF8?1:2);
47016    }
47017    if( nByte>iLimit ){
47018      return SQLITE_TOOBIG;
47019    }
47020    if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
47021      return SQLITE_NOMEM;
47022    }
47023    memcpy(pMem->z, z, nAlloc);
47024  }else if( xDel==SQLITE_DYNAMIC ){
47025    sqlite3VdbeMemRelease(pMem);
47026    pMem->zMalloc = pMem->z = (char *)z;
47027    pMem->xDel = 0;
47028  }else{
47029    sqlite3VdbeMemRelease(pMem);
47030    pMem->z = (char *)z;
47031    pMem->xDel = xDel;
47032    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
47033  }
47034
47035  pMem->n = nByte;
47036  pMem->flags = flags;
47037  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
47038  pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
47039
47040#ifndef SQLITE_OMIT_UTF16
47041  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
47042    return SQLITE_NOMEM;
47043  }
47044#endif
47045
47046  if( nByte>iLimit ){
47047    return SQLITE_TOOBIG;
47048  }
47049
47050  return SQLITE_OK;
47051}
47052
47053/*
47054** Compare the values contained by the two memory cells, returning
47055** negative, zero or positive if pMem1 is less than, equal to, or greater
47056** than pMem2. Sorting order is NULL's first, followed by numbers (integers
47057** and reals) sorted numerically, followed by text ordered by the collating
47058** sequence pColl and finally blob's ordered by memcmp().
47059**
47060** Two NULL values are considered equal by this function.
47061*/
47062SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
47063  int rc;
47064  int f1, f2;
47065  int combined_flags;
47066
47067  f1 = pMem1->flags;
47068  f2 = pMem2->flags;
47069  combined_flags = f1|f2;
47070  assert( (combined_flags & MEM_RowSet)==0 );
47071
47072  /* If one value is NULL, it is less than the other. If both values
47073  ** are NULL, return 0.
47074  */
47075  if( combined_flags&MEM_Null ){
47076    return (f2&MEM_Null) - (f1&MEM_Null);
47077  }
47078
47079  /* If one value is a number and the other is not, the number is less.
47080  ** If both are numbers, compare as reals if one is a real, or as integers
47081  ** if both values are integers.
47082  */
47083  if( combined_flags&(MEM_Int|MEM_Real) ){
47084    if( !(f1&(MEM_Int|MEM_Real)) ){
47085      return 1;
47086    }
47087    if( !(f2&(MEM_Int|MEM_Real)) ){
47088      return -1;
47089    }
47090    if( (f1 & f2 & MEM_Int)==0 ){
47091      double r1, r2;
47092      if( (f1&MEM_Real)==0 ){
47093        r1 = (double)pMem1->u.i;
47094      }else{
47095        r1 = pMem1->r;
47096      }
47097      if( (f2&MEM_Real)==0 ){
47098        r2 = (double)pMem2->u.i;
47099      }else{
47100        r2 = pMem2->r;
47101      }
47102      if( r1<r2 ) return -1;
47103      if( r1>r2 ) return 1;
47104      return 0;
47105    }else{
47106      assert( f1&MEM_Int );
47107      assert( f2&MEM_Int );
47108      if( pMem1->u.i < pMem2->u.i ) return -1;
47109      if( pMem1->u.i > pMem2->u.i ) return 1;
47110      return 0;
47111    }
47112  }
47113
47114  /* If one value is a string and the other is a blob, the string is less.
47115  ** If both are strings, compare using the collating functions.
47116  */
47117  if( combined_flags&MEM_Str ){
47118    if( (f1 & MEM_Str)==0 ){
47119      return 1;
47120    }
47121    if( (f2 & MEM_Str)==0 ){
47122      return -1;
47123    }
47124
47125    assert( pMem1->enc==pMem2->enc );
47126    assert( pMem1->enc==SQLITE_UTF8 ||
47127            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
47128
47129    /* The collation sequence must be defined at this point, even if
47130    ** the user deletes the collation sequence after the vdbe program is
47131    ** compiled (this was not always the case).
47132    */
47133    assert( !pColl || pColl->xCmp );
47134
47135    if( pColl ){
47136      if( pMem1->enc==pColl->enc ){
47137        /* The strings are already in the correct encoding.  Call the
47138        ** comparison function directly */
47139        return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
47140      }else{
47141        const void *v1, *v2;
47142        int n1, n2;
47143        Mem c1;
47144        Mem c2;
47145        memset(&c1, 0, sizeof(c1));
47146        memset(&c2, 0, sizeof(c2));
47147        sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
47148        sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
47149        v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
47150        n1 = v1==0 ? 0 : c1.n;
47151        v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
47152        n2 = v2==0 ? 0 : c2.n;
47153        rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
47154        sqlite3VdbeMemRelease(&c1);
47155        sqlite3VdbeMemRelease(&c2);
47156        return rc;
47157      }
47158    }
47159    /* If a NULL pointer was passed as the collate function, fall through
47160    ** to the blob case and use memcmp().  */
47161  }
47162
47163  /* Both values must be blobs.  Compare using memcmp().  */
47164  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
47165  if( rc==0 ){
47166    rc = pMem1->n - pMem2->n;
47167  }
47168  return rc;
47169}
47170
47171/*
47172** Move data out of a btree key or data field and into a Mem structure.
47173** The data or key is taken from the entry that pCur is currently pointing
47174** to.  offset and amt determine what portion of the data or key to retrieve.
47175** key is true to get the key or false to get data.  The result is written
47176** into the pMem element.
47177**
47178** The pMem structure is assumed to be uninitialized.  Any prior content
47179** is overwritten without being freed.
47180**
47181** If this routine fails for any reason (malloc returns NULL or unable
47182** to read from the disk) then the pMem is left in an inconsistent state.
47183*/
47184SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
47185  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
47186  int offset,       /* Offset from the start of data to return bytes from. */
47187  int amt,          /* Number of bytes to return. */
47188  int key,          /* If true, retrieve from the btree key, not data. */
47189  Mem *pMem         /* OUT: Return data in this Mem structure. */
47190){
47191  char *zData;        /* Data from the btree layer */
47192  int available = 0;  /* Number of bytes available on the local btree page */
47193  int rc = SQLITE_OK; /* Return code */
47194
47195  assert( sqlite3BtreeCursorIsValid(pCur) );
47196
47197  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
47198  ** that both the BtShared and database handle mutexes are held. */
47199  assert( (pMem->flags & MEM_RowSet)==0 );
47200  if( key ){
47201    zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
47202  }else{
47203    zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
47204  }
47205  assert( zData!=0 );
47206
47207  if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
47208    sqlite3VdbeMemRelease(pMem);
47209    pMem->z = &zData[offset];
47210    pMem->flags = MEM_Blob|MEM_Ephem;
47211  }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
47212    pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
47213    pMem->enc = 0;
47214    pMem->type = SQLITE_BLOB;
47215    if( key ){
47216      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
47217    }else{
47218      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
47219    }
47220    pMem->z[amt] = 0;
47221    pMem->z[amt+1] = 0;
47222    if( rc!=SQLITE_OK ){
47223      sqlite3VdbeMemRelease(pMem);
47224    }
47225  }
47226  pMem->n = amt;
47227
47228  return rc;
47229}
47230
47231/* This function is only available internally, it is not part of the
47232** external API. It works in a similar way to sqlite3_value_text(),
47233** except the data returned is in the encoding specified by the second
47234** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
47235** SQLITE_UTF8.
47236**
47237** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
47238** If that is the case, then the result must be aligned on an even byte
47239** boundary.
47240*/
47241SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
47242  if( !pVal ) return 0;
47243
47244  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
47245  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
47246  assert( (pVal->flags & MEM_RowSet)==0 );
47247
47248  if( pVal->flags&MEM_Null ){
47249    return 0;
47250  }
47251  assert( (MEM_Blob>>3) == MEM_Str );
47252  pVal->flags |= (pVal->flags & MEM_Blob)>>3;
47253  expandBlob(pVal);
47254  if( pVal->flags&MEM_Str ){
47255    sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
47256    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
47257      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
47258      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
47259        return 0;
47260      }
47261    }
47262    sqlite3VdbeMemNulTerminate(pVal);
47263  }else{
47264    assert( (pVal->flags&MEM_Blob)==0 );
47265    sqlite3VdbeMemStringify(pVal, enc);
47266    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
47267  }
47268  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
47269              || pVal->db->mallocFailed );
47270  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
47271    return pVal->z;
47272  }else{
47273    return 0;
47274  }
47275}
47276
47277/*
47278** Create a new sqlite3_value object.
47279*/
47280SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
47281  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
47282  if( p ){
47283    p->flags = MEM_Null;
47284    p->type = SQLITE_NULL;
47285    p->db = db;
47286  }
47287  return p;
47288}
47289
47290/*
47291** Create a new sqlite3_value object, containing the value of pExpr.
47292**
47293** This only works for very simple expressions that consist of one constant
47294** token (i.e. "5", "5.1", "'a string'"). If the expression can
47295** be converted directly into a value, then the value is allocated and
47296** a pointer written to *ppVal. The caller is responsible for deallocating
47297** the value by passing it to sqlite3ValueFree() later on. If the expression
47298** cannot be converted to a value, then *ppVal is set to NULL.
47299*/
47300SQLITE_PRIVATE int sqlite3ValueFromExpr(
47301  sqlite3 *db,              /* The database connection */
47302  Expr *pExpr,              /* The expression to evaluate */
47303  u8 enc,                   /* Encoding to use */
47304  u8 affinity,              /* Affinity to use */
47305  sqlite3_value **ppVal     /* Write the new value here */
47306){
47307  int op;
47308  char *zVal = 0;
47309  sqlite3_value *pVal = 0;
47310
47311  if( !pExpr ){
47312    *ppVal = 0;
47313    return SQLITE_OK;
47314  }
47315  op = pExpr->op;
47316  if( op==TK_REGISTER ){
47317    op = pExpr->op2;  /* This only happens with SQLITE_ENABLE_STAT2 */
47318  }
47319
47320  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
47321    pVal = sqlite3ValueNew(db);
47322    if( pVal==0 ) goto no_mem;
47323    if( ExprHasProperty(pExpr, EP_IntValue) ){
47324      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue);
47325    }else{
47326      zVal = sqlite3DbStrDup(db, pExpr->u.zToken);
47327      if( zVal==0 ) goto no_mem;
47328      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
47329      if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
47330    }
47331    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
47332      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
47333    }else{
47334      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
47335    }
47336    if( enc!=SQLITE_UTF8 ){
47337      sqlite3VdbeChangeEncoding(pVal, enc);
47338    }
47339  }else if( op==TK_UMINUS ) {
47340    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
47341      pVal->u.i = -1 * pVal->u.i;
47342      /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
47343      pVal->r = (double)-1 * pVal->r;
47344    }
47345  }
47346#ifndef SQLITE_OMIT_BLOB_LITERAL
47347  else if( op==TK_BLOB ){
47348    int nVal;
47349    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
47350    assert( pExpr->u.zToken[1]=='\'' );
47351    pVal = sqlite3ValueNew(db);
47352    if( !pVal ) goto no_mem;
47353    zVal = &pExpr->u.zToken[2];
47354    nVal = sqlite3Strlen30(zVal)-1;
47355    assert( zVal[nVal]=='\'' );
47356    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
47357                         0, SQLITE_DYNAMIC);
47358  }
47359#endif
47360
47361  if( pVal ){
47362    sqlite3VdbeMemStoreType(pVal);
47363  }
47364  *ppVal = pVal;
47365  return SQLITE_OK;
47366
47367no_mem:
47368  db->mallocFailed = 1;
47369  sqlite3DbFree(db, zVal);
47370  sqlite3ValueFree(pVal);
47371  *ppVal = 0;
47372  return SQLITE_NOMEM;
47373}
47374
47375/*
47376** Change the string value of an sqlite3_value object
47377*/
47378SQLITE_PRIVATE void sqlite3ValueSetStr(
47379  sqlite3_value *v,     /* Value to be set */
47380  int n,                /* Length of string z */
47381  const void *z,        /* Text of the new string */
47382  u8 enc,               /* Encoding to use */
47383  void (*xDel)(void*)   /* Destructor for the string */
47384){
47385  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
47386}
47387
47388/*
47389** Free an sqlite3_value object
47390*/
47391SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
47392  if( !v ) return;
47393  sqlite3VdbeMemRelease((Mem *)v);
47394  sqlite3DbFree(((Mem*)v)->db, v);
47395}
47396
47397/*
47398** Return the number of bytes in the sqlite3_value object assuming
47399** that it uses the encoding "enc"
47400*/
47401SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
47402  Mem *p = (Mem*)pVal;
47403  if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
47404    if( p->flags & MEM_Zero ){
47405      return p->n + p->u.nZero;
47406    }else{
47407      return p->n;
47408    }
47409  }
47410  return 0;
47411}
47412
47413/************** End of vdbemem.c *********************************************/
47414/************** Begin file vdbeaux.c *****************************************/
47415/*
47416** 2003 September 6
47417**
47418** The author disclaims copyright to this source code.  In place of
47419** a legal notice, here is a blessing:
47420**
47421**    May you do good and not evil.
47422**    May you find forgiveness for yourself and forgive others.
47423**    May you share freely, never taking more than you give.
47424**
47425*************************************************************************
47426** This file contains code used for creating, destroying, and populating
47427** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
47428** to version 2.8.7, all this code was combined into the vdbe.c source file.
47429** But that file was getting too big so this subroutines were split out.
47430*/
47431
47432
47433
47434/*
47435** When debugging the code generator in a symbolic debugger, one can
47436** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
47437** as they are added to the instruction stream.
47438*/
47439#ifdef SQLITE_DEBUG
47440SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
47441#endif
47442
47443
47444/*
47445** Create a new virtual database engine.
47446*/
47447SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
47448  Vdbe *p;
47449  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
47450  if( p==0 ) return 0;
47451  p->db = db;
47452  if( db->pVdbe ){
47453    db->pVdbe->pPrev = p;
47454  }
47455  p->pNext = db->pVdbe;
47456  p->pPrev = 0;
47457  db->pVdbe = p;
47458  p->magic = VDBE_MAGIC_INIT;
47459  return p;
47460}
47461
47462/*
47463** Remember the SQL string for a prepared statement.
47464*/
47465SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
47466  assert( isPrepareV2==1 || isPrepareV2==0 );
47467  if( p==0 ) return;
47468#ifdef SQLITE_OMIT_TRACE
47469  if( !isPrepareV2 ) return;
47470#endif
47471  assert( p->zSql==0 );
47472  p->zSql = sqlite3DbStrNDup(p->db, z, n);
47473  p->isPrepareV2 = (u8)isPrepareV2;
47474}
47475
47476/*
47477** Return the SQL associated with a prepared statement
47478*/
47479SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
47480  Vdbe *p = (Vdbe *)pStmt;
47481  return (p->isPrepareV2 ? p->zSql : 0);
47482}
47483
47484/*
47485** Swap all content between two VDBE structures.
47486*/
47487SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
47488  Vdbe tmp, *pTmp;
47489  char *zTmp;
47490  tmp = *pA;
47491  *pA = *pB;
47492  *pB = tmp;
47493  pTmp = pA->pNext;
47494  pA->pNext = pB->pNext;
47495  pB->pNext = pTmp;
47496  pTmp = pA->pPrev;
47497  pA->pPrev = pB->pPrev;
47498  pB->pPrev = pTmp;
47499  zTmp = pA->zSql;
47500  pA->zSql = pB->zSql;
47501  pB->zSql = zTmp;
47502  pB->isPrepareV2 = pA->isPrepareV2;
47503}
47504
47505#ifdef SQLITE_DEBUG
47506/*
47507** Turn tracing on or off
47508*/
47509SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
47510  p->trace = trace;
47511}
47512#endif
47513
47514/*
47515** Resize the Vdbe.aOp array so that it is at least one op larger than
47516** it was.
47517**
47518** If an out-of-memory error occurs while resizing the array, return
47519** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
47520** unchanged (this is so that any opcodes already allocated can be
47521** correctly deallocated along with the rest of the Vdbe).
47522*/
47523static int growOpArray(Vdbe *p){
47524  VdbeOp *pNew;
47525  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
47526  pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
47527  if( pNew ){
47528    p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
47529    p->aOp = pNew;
47530  }
47531  return (pNew ? SQLITE_OK : SQLITE_NOMEM);
47532}
47533
47534/*
47535** Add a new instruction to the list of instructions current in the
47536** VDBE.  Return the address of the new instruction.
47537**
47538** Parameters:
47539**
47540**    p               Pointer to the VDBE
47541**
47542**    op              The opcode for this instruction
47543**
47544**    p1, p2, p3      Operands
47545**
47546** Use the sqlite3VdbeResolveLabel() function to fix an address and
47547** the sqlite3VdbeChangeP4() function to change the value of the P4
47548** operand.
47549*/
47550SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
47551  int i;
47552  VdbeOp *pOp;
47553
47554  i = p->nOp;
47555  assert( p->magic==VDBE_MAGIC_INIT );
47556  assert( op>0 && op<0xff );
47557  if( p->nOpAlloc<=i ){
47558    if( growOpArray(p) ){
47559      return 1;
47560    }
47561  }
47562  p->nOp++;
47563  pOp = &p->aOp[i];
47564  pOp->opcode = (u8)op;
47565  pOp->p5 = 0;
47566  pOp->p1 = p1;
47567  pOp->p2 = p2;
47568  pOp->p3 = p3;
47569  pOp->p4.p = 0;
47570  pOp->p4type = P4_NOTUSED;
47571  p->expired = 0;
47572#ifdef SQLITE_DEBUG
47573  pOp->zComment = 0;
47574  if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
47575#endif
47576#ifdef VDBE_PROFILE
47577  pOp->cycles = 0;
47578  pOp->cnt = 0;
47579#endif
47580  return i;
47581}
47582SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
47583  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
47584}
47585SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
47586  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
47587}
47588SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
47589  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
47590}
47591
47592
47593/*
47594** Add an opcode that includes the p4 value as a pointer.
47595*/
47596SQLITE_PRIVATE int sqlite3VdbeAddOp4(
47597  Vdbe *p,            /* Add the opcode to this VM */
47598  int op,             /* The new opcode */
47599  int p1,             /* The P1 operand */
47600  int p2,             /* The P2 operand */
47601  int p3,             /* The P3 operand */
47602  const char *zP4,    /* The P4 operand */
47603  int p4type          /* P4 operand type */
47604){
47605  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
47606  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
47607  return addr;
47608}
47609
47610/*
47611** Add an opcode that includes the p4 value as an integer.
47612*/
47613SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
47614  Vdbe *p,            /* Add the opcode to this VM */
47615  int op,             /* The new opcode */
47616  int p1,             /* The P1 operand */
47617  int p2,             /* The P2 operand */
47618  int p3,             /* The P3 operand */
47619  int p4              /* The P4 operand as an integer */
47620){
47621  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
47622  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
47623  return addr;
47624}
47625
47626/*
47627** Create a new symbolic label for an instruction that has yet to be
47628** coded.  The symbolic label is really just a negative number.  The
47629** label can be used as the P2 value of an operation.  Later, when
47630** the label is resolved to a specific address, the VDBE will scan
47631** through its operation list and change all values of P2 which match
47632** the label into the resolved address.
47633**
47634** The VDBE knows that a P2 value is a label because labels are
47635** always negative and P2 values are suppose to be non-negative.
47636** Hence, a negative P2 value is a label that has yet to be resolved.
47637**
47638** Zero is returned if a malloc() fails.
47639*/
47640SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
47641  int i;
47642  i = p->nLabel++;
47643  assert( p->magic==VDBE_MAGIC_INIT );
47644  if( i>=p->nLabelAlloc ){
47645    int n = p->nLabelAlloc*2 + 5;
47646    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
47647                                       n*sizeof(p->aLabel[0]));
47648    p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
47649  }
47650  if( p->aLabel ){
47651    p->aLabel[i] = -1;
47652  }
47653  return -1-i;
47654}
47655
47656/*
47657** Resolve label "x" to be the address of the next instruction to
47658** be inserted.  The parameter "x" must have been obtained from
47659** a prior call to sqlite3VdbeMakeLabel().
47660*/
47661SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
47662  int j = -1-x;
47663  assert( p->magic==VDBE_MAGIC_INIT );
47664  assert( j>=0 && j<p->nLabel );
47665  if( p->aLabel ){
47666    p->aLabel[j] = p->nOp;
47667  }
47668}
47669
47670/*
47671** Mark the VDBE as one that can only be run one time.
47672*/
47673SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
47674  p->runOnlyOnce = 1;
47675}
47676
47677#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
47678
47679/*
47680** The following type and function are used to iterate through all opcodes
47681** in a Vdbe main program and each of the sub-programs (triggers) it may
47682** invoke directly or indirectly. It should be used as follows:
47683**
47684**   Op *pOp;
47685**   VdbeOpIter sIter;
47686**
47687**   memset(&sIter, 0, sizeof(sIter));
47688**   sIter.v = v;                            // v is of type Vdbe*
47689**   while( (pOp = opIterNext(&sIter)) ){
47690**     // Do something with pOp
47691**   }
47692**   sqlite3DbFree(v->db, sIter.apSub);
47693**
47694*/
47695typedef struct VdbeOpIter VdbeOpIter;
47696struct VdbeOpIter {
47697  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
47698  SubProgram **apSub;        /* Array of subprograms */
47699  int nSub;                  /* Number of entries in apSub */
47700  int iAddr;                 /* Address of next instruction to return */
47701  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
47702};
47703static Op *opIterNext(VdbeOpIter *p){
47704  Vdbe *v = p->v;
47705  Op *pRet = 0;
47706  Op *aOp;
47707  int nOp;
47708
47709  if( p->iSub<=p->nSub ){
47710
47711    if( p->iSub==0 ){
47712      aOp = v->aOp;
47713      nOp = v->nOp;
47714    }else{
47715      aOp = p->apSub[p->iSub-1]->aOp;
47716      nOp = p->apSub[p->iSub-1]->nOp;
47717    }
47718    assert( p->iAddr<nOp );
47719
47720    pRet = &aOp[p->iAddr];
47721    p->iAddr++;
47722    if( p->iAddr==nOp ){
47723      p->iSub++;
47724      p->iAddr = 0;
47725    }
47726
47727    if( pRet->p4type==P4_SUBPROGRAM ){
47728      int nByte = (p->nSub+1)*sizeof(SubProgram*);
47729      int j;
47730      for(j=0; j<p->nSub; j++){
47731        if( p->apSub[j]==pRet->p4.pProgram ) break;
47732      }
47733      if( j==p->nSub ){
47734        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
47735        if( !p->apSub ){
47736          pRet = 0;
47737        }else{
47738          p->apSub[p->nSub++] = pRet->p4.pProgram;
47739        }
47740      }
47741    }
47742  }
47743
47744  return pRet;
47745}
47746
47747/*
47748** Check if the program stored in the VM associated with pParse may
47749** throw an ABORT exception (causing the statement, but not entire transaction
47750** to be rolled back). This condition is true if the main program or any
47751** sub-programs contains any of the following:
47752**
47753**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
47754**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
47755**   *  OP_Destroy
47756**   *  OP_VUpdate
47757**   *  OP_VRename
47758**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
47759**
47760** Then check that the value of Parse.mayAbort is true if an
47761** ABORT may be thrown, or false otherwise. Return true if it does
47762** match, or false otherwise. This function is intended to be used as
47763** part of an assert statement in the compiler. Similar to:
47764**
47765**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
47766*/
47767SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
47768  int hasAbort = 0;
47769  Op *pOp;
47770  VdbeOpIter sIter;
47771  memset(&sIter, 0, sizeof(sIter));
47772  sIter.v = v;
47773
47774  while( (pOp = opIterNext(&sIter))!=0 ){
47775    int opcode = pOp->opcode;
47776    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
47777#ifndef SQLITE_OMIT_FOREIGN_KEY
47778     || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
47779#endif
47780     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
47781      && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
47782    ){
47783      hasAbort = 1;
47784      break;
47785    }
47786  }
47787  sqlite3DbFree(v->db, sIter.apSub);
47788
47789  /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
47790  ** If malloc failed, then the while() loop above may not have iterated
47791  ** through all opcodes and hasAbort may be set incorrectly. Return
47792  ** true for this case to prevent the assert() in the callers frame
47793  ** from failing.  */
47794  return ( v->db->mallocFailed || hasAbort==mayAbort );
47795}
47796#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
47797
47798/*
47799** Loop through the program looking for P2 values that are negative
47800** on jump instructions.  Each such value is a label.  Resolve the
47801** label by setting the P2 value to its correct non-zero value.
47802**
47803** This routine is called once after all opcodes have been inserted.
47804**
47805** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
47806** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
47807** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
47808**
47809** The Op.opflags field is set on all opcodes.
47810*/
47811static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
47812  int i;
47813  int nMaxArgs = *pMaxFuncArgs;
47814  Op *pOp;
47815  int *aLabel = p->aLabel;
47816  p->readOnly = 1;
47817  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
47818    u8 opcode = pOp->opcode;
47819
47820    pOp->opflags = sqlite3OpcodeProperty[opcode];
47821    if( opcode==OP_Function || opcode==OP_AggStep ){
47822      if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
47823    }else if( opcode==OP_Transaction && pOp->p2!=0 ){
47824      p->readOnly = 0;
47825#ifndef SQLITE_OMIT_VIRTUALTABLE
47826    }else if( opcode==OP_VUpdate ){
47827      if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
47828    }else if( opcode==OP_VFilter ){
47829      int n;
47830      assert( p->nOp - i >= 3 );
47831      assert( pOp[-1].opcode==OP_Integer );
47832      n = pOp[-1].p1;
47833      if( n>nMaxArgs ) nMaxArgs = n;
47834#endif
47835    }
47836
47837    if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
47838      assert( -1-pOp->p2<p->nLabel );
47839      pOp->p2 = aLabel[-1-pOp->p2];
47840    }
47841  }
47842  sqlite3DbFree(p->db, p->aLabel);
47843  p->aLabel = 0;
47844
47845  *pMaxFuncArgs = nMaxArgs;
47846}
47847
47848/*
47849** Return the address of the next instruction to be inserted.
47850*/
47851SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
47852  assert( p->magic==VDBE_MAGIC_INIT );
47853  return p->nOp;
47854}
47855
47856/*
47857** This function returns a pointer to the array of opcodes associated with
47858** the Vdbe passed as the first argument. It is the callers responsibility
47859** to arrange for the returned array to be eventually freed using the
47860** vdbeFreeOpArray() function.
47861**
47862** Before returning, *pnOp is set to the number of entries in the returned
47863** array. Also, *pnMaxArg is set to the larger of its current value and
47864** the number of entries in the Vdbe.apArg[] array required to execute the
47865** returned program.
47866*/
47867SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
47868  VdbeOp *aOp = p->aOp;
47869  assert( aOp && !p->db->mallocFailed );
47870
47871  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
47872  assert( p->aMutex.nMutex==0 );
47873
47874  resolveP2Values(p, pnMaxArg);
47875  *pnOp = p->nOp;
47876  p->aOp = 0;
47877  return aOp;
47878}
47879
47880/*
47881** Add a whole list of operations to the operation stack.  Return the
47882** address of the first operation added.
47883*/
47884SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
47885  int addr;
47886  assert( p->magic==VDBE_MAGIC_INIT );
47887  if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
47888    return 0;
47889  }
47890  addr = p->nOp;
47891  if( ALWAYS(nOp>0) ){
47892    int i;
47893    VdbeOpList const *pIn = aOp;
47894    for(i=0; i<nOp; i++, pIn++){
47895      int p2 = pIn->p2;
47896      VdbeOp *pOut = &p->aOp[i+addr];
47897      pOut->opcode = pIn->opcode;
47898      pOut->p1 = pIn->p1;
47899      if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
47900        pOut->p2 = addr + ADDR(p2);
47901      }else{
47902        pOut->p2 = p2;
47903      }
47904      pOut->p3 = pIn->p3;
47905      pOut->p4type = P4_NOTUSED;
47906      pOut->p4.p = 0;
47907      pOut->p5 = 0;
47908#ifdef SQLITE_DEBUG
47909      pOut->zComment = 0;
47910      if( sqlite3VdbeAddopTrace ){
47911        sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
47912      }
47913#endif
47914    }
47915    p->nOp += nOp;
47916  }
47917  return addr;
47918}
47919
47920/*
47921** Change the value of the P1 operand for a specific instruction.
47922** This routine is useful when a large program is loaded from a
47923** static array using sqlite3VdbeAddOpList but we want to make a
47924** few minor changes to the program.
47925*/
47926SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
47927  assert( p!=0 );
47928  assert( addr>=0 );
47929  if( p->nOp>addr ){
47930    p->aOp[addr].p1 = val;
47931  }
47932}
47933
47934/*
47935** Change the value of the P2 operand for a specific instruction.
47936** This routine is useful for setting a jump destination.
47937*/
47938SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
47939  assert( p!=0 );
47940  assert( addr>=0 );
47941  if( p->nOp>addr ){
47942    p->aOp[addr].p2 = val;
47943  }
47944}
47945
47946/*
47947** Change the value of the P3 operand for a specific instruction.
47948*/
47949SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
47950  assert( p!=0 );
47951  assert( addr>=0 );
47952  if( p->nOp>addr ){
47953    p->aOp[addr].p3 = val;
47954  }
47955}
47956
47957/*
47958** Change the value of the P5 operand for the most recently
47959** added operation.
47960*/
47961SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
47962  assert( p!=0 );
47963  if( p->aOp ){
47964    assert( p->nOp>0 );
47965    p->aOp[p->nOp-1].p5 = val;
47966  }
47967}
47968
47969/*
47970** Change the P2 operand of instruction addr so that it points to
47971** the address of the next instruction to be coded.
47972*/
47973SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
47974  sqlite3VdbeChangeP2(p, addr, p->nOp);
47975}
47976
47977
47978/*
47979** If the input FuncDef structure is ephemeral, then free it.  If
47980** the FuncDef is not ephermal, then do nothing.
47981*/
47982static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
47983  if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
47984    sqlite3DbFree(db, pDef);
47985  }
47986}
47987
47988/*
47989** Delete a P4 value if necessary.
47990*/
47991static void freeP4(sqlite3 *db, int p4type, void *p4){
47992  if( p4 ){
47993    switch( p4type ){
47994      case P4_REAL:
47995      case P4_INT64:
47996      case P4_MPRINTF:
47997      case P4_DYNAMIC:
47998      case P4_KEYINFO:
47999      case P4_INTARRAY:
48000      case P4_KEYINFO_HANDOFF: {
48001        sqlite3DbFree(db, p4);
48002        break;
48003      }
48004      case P4_VDBEFUNC: {
48005        VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
48006        freeEphemeralFunction(db, pVdbeFunc->pFunc);
48007        sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
48008        sqlite3DbFree(db, pVdbeFunc);
48009        break;
48010      }
48011      case P4_FUNCDEF: {
48012        freeEphemeralFunction(db, (FuncDef*)p4);
48013        break;
48014      }
48015      case P4_MEM: {
48016        sqlite3ValueFree((sqlite3_value*)p4);
48017        break;
48018      }
48019      case P4_VTAB : {
48020        sqlite3VtabUnlock((VTable *)p4);
48021        break;
48022      }
48023      case P4_SUBPROGRAM : {
48024        sqlite3VdbeProgramDelete(db, (SubProgram *)p4, 1);
48025        break;
48026      }
48027    }
48028  }
48029}
48030
48031/*
48032** Free the space allocated for aOp and any p4 values allocated for the
48033** opcodes contained within. If aOp is not NULL it is assumed to contain
48034** nOp entries.
48035*/
48036static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
48037  if( aOp ){
48038    Op *pOp;
48039    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
48040      freeP4(db, pOp->p4type, pOp->p4.p);
48041#ifdef SQLITE_DEBUG
48042      sqlite3DbFree(db, pOp->zComment);
48043#endif
48044    }
48045  }
48046  sqlite3DbFree(db, aOp);
48047}
48048
48049/*
48050** Decrement the ref-count on the SubProgram structure passed as the
48051** second argument. If the ref-count reaches zero, free the structure.
48052**
48053** The array of VDBE opcodes stored as SubProgram.aOp is freed if
48054** either the ref-count reaches zero or parameter freeop is non-zero.
48055**
48056** Since the array of opcodes pointed to by SubProgram.aOp may directly
48057** or indirectly contain a reference to the SubProgram structure itself.
48058** By passing a non-zero freeop parameter, the caller may ensure that all
48059** SubProgram structures and their aOp arrays are freed, even when there
48060** are such circular references.
48061*/
48062SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *db, SubProgram *p, int freeop){
48063  if( p ){
48064    assert( p->nRef>0 );
48065    if( freeop || p->nRef==1 ){
48066      Op *aOp = p->aOp;
48067      p->aOp = 0;
48068      vdbeFreeOpArray(db, aOp, p->nOp);
48069      p->nOp = 0;
48070    }
48071    p->nRef--;
48072    if( p->nRef==0 ){
48073      sqlite3DbFree(db, p);
48074    }
48075  }
48076}
48077
48078
48079/*
48080** Change N opcodes starting at addr to No-ops.
48081*/
48082SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
48083  if( p->aOp ){
48084    VdbeOp *pOp = &p->aOp[addr];
48085    sqlite3 *db = p->db;
48086    while( N-- ){
48087      freeP4(db, pOp->p4type, pOp->p4.p);
48088      memset(pOp, 0, sizeof(pOp[0]));
48089      pOp->opcode = OP_Noop;
48090      pOp++;
48091    }
48092  }
48093}
48094
48095/*
48096** Change the value of the P4 operand for a specific instruction.
48097** This routine is useful when a large program is loaded from a
48098** static array using sqlite3VdbeAddOpList but we want to make a
48099** few minor changes to the program.
48100**
48101** If n>=0 then the P4 operand is dynamic, meaning that a copy of
48102** the string is made into memory obtained from sqlite3_malloc().
48103** A value of n==0 means copy bytes of zP4 up to and including the
48104** first null byte.  If n>0 then copy n+1 bytes of zP4.
48105**
48106** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
48107** A copy is made of the KeyInfo structure into memory obtained from
48108** sqlite3_malloc, to be freed when the Vdbe is finalized.
48109** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
48110** stored in memory that the caller has obtained from sqlite3_malloc. The
48111** caller should not free the allocation, it will be freed when the Vdbe is
48112** finalized.
48113**
48114** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
48115** to a string or structure that is guaranteed to exist for the lifetime of
48116** the Vdbe. In these cases we can just copy the pointer.
48117**
48118** If addr<0 then change P4 on the most recently inserted instruction.
48119*/
48120SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
48121  Op *pOp;
48122  sqlite3 *db;
48123  assert( p!=0 );
48124  db = p->db;
48125  assert( p->magic==VDBE_MAGIC_INIT );
48126  if( p->aOp==0 || db->mallocFailed ){
48127    if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
48128      freeP4(db, n, (void*)*(char**)&zP4);
48129    }
48130    return;
48131  }
48132  assert( p->nOp>0 );
48133  assert( addr<p->nOp );
48134  if( addr<0 ){
48135    addr = p->nOp - 1;
48136  }
48137  pOp = &p->aOp[addr];
48138  freeP4(db, pOp->p4type, pOp->p4.p);
48139  pOp->p4.p = 0;
48140  if( n==P4_INT32 ){
48141    /* Note: this cast is safe, because the origin data point was an int
48142    ** that was cast to a (const char *). */
48143    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
48144    pOp->p4type = P4_INT32;
48145  }else if( zP4==0 ){
48146    pOp->p4.p = 0;
48147    pOp->p4type = P4_NOTUSED;
48148  }else if( n==P4_KEYINFO ){
48149    KeyInfo *pKeyInfo;
48150    int nField, nByte;
48151
48152    nField = ((KeyInfo*)zP4)->nField;
48153    nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
48154    pKeyInfo = sqlite3Malloc( nByte );
48155    pOp->p4.pKeyInfo = pKeyInfo;
48156    if( pKeyInfo ){
48157      u8 *aSortOrder;
48158      memcpy(pKeyInfo, zP4, nByte);
48159      aSortOrder = pKeyInfo->aSortOrder;
48160      if( aSortOrder ){
48161        pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
48162        memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
48163      }
48164      pOp->p4type = P4_KEYINFO;
48165    }else{
48166      p->db->mallocFailed = 1;
48167      pOp->p4type = P4_NOTUSED;
48168    }
48169  }else if( n==P4_KEYINFO_HANDOFF ){
48170    pOp->p4.p = (void*)zP4;
48171    pOp->p4type = P4_KEYINFO;
48172  }else if( n==P4_VTAB ){
48173    pOp->p4.p = (void*)zP4;
48174    pOp->p4type = P4_VTAB;
48175    sqlite3VtabLock((VTable *)zP4);
48176    assert( ((VTable *)zP4)->db==p->db );
48177  }else if( n<0 ){
48178    pOp->p4.p = (void*)zP4;
48179    pOp->p4type = (signed char)n;
48180  }else{
48181    if( n==0 ) n = sqlite3Strlen30(zP4);
48182    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
48183    pOp->p4type = P4_DYNAMIC;
48184  }
48185}
48186
48187#ifndef NDEBUG
48188/*
48189** Change the comment on the the most recently coded instruction.  Or
48190** insert a No-op and add the comment to that new instruction.  This
48191** makes the code easier to read during debugging.  None of this happens
48192** in a production build.
48193*/
48194SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
48195  va_list ap;
48196  if( !p ) return;
48197  assert( p->nOp>0 || p->aOp==0 );
48198  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
48199  if( p->nOp ){
48200    char **pz = &p->aOp[p->nOp-1].zComment;
48201    va_start(ap, zFormat);
48202    sqlite3DbFree(p->db, *pz);
48203    *pz = sqlite3VMPrintf(p->db, zFormat, ap);
48204    va_end(ap);
48205  }
48206}
48207SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
48208  va_list ap;
48209  if( !p ) return;
48210  sqlite3VdbeAddOp0(p, OP_Noop);
48211  assert( p->nOp>0 || p->aOp==0 );
48212  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
48213  if( p->nOp ){
48214    char **pz = &p->aOp[p->nOp-1].zComment;
48215    va_start(ap, zFormat);
48216    sqlite3DbFree(p->db, *pz);
48217    *pz = sqlite3VMPrintf(p->db, zFormat, ap);
48218    va_end(ap);
48219  }
48220}
48221#endif  /* NDEBUG */
48222
48223/*
48224** Return the opcode for a given address.  If the address is -1, then
48225** return the most recently inserted opcode.
48226**
48227** If a memory allocation error has occurred prior to the calling of this
48228** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
48229** is readable and writable, but it has no effect.  The return of a dummy
48230** opcode allows the call to continue functioning after a OOM fault without
48231** having to check to see if the return from this routine is a valid pointer.
48232**
48233** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
48234** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
48235** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
48236** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
48237** having to double-check to make sure that the result is non-negative. But
48238** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
48239** check the value of p->nOp-1 before continuing.
48240*/
48241SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
48242  static VdbeOp dummy;
48243  assert( p->magic==VDBE_MAGIC_INIT );
48244  if( addr<0 ){
48245#ifdef SQLITE_OMIT_TRACE
48246    if( p->nOp==0 ) return &dummy;
48247#endif
48248    addr = p->nOp - 1;
48249  }
48250  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
48251  if( p->db->mallocFailed ){
48252    return &dummy;
48253  }else{
48254    return &p->aOp[addr];
48255  }
48256}
48257
48258#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
48259     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
48260/*
48261** Compute a string that describes the P4 parameter for an opcode.
48262** Use zTemp for any required temporary buffer space.
48263*/
48264static char *displayP4(Op *pOp, char *zTemp, int nTemp){
48265  char *zP4 = zTemp;
48266  assert( nTemp>=20 );
48267  switch( pOp->p4type ){
48268    case P4_KEYINFO_STATIC:
48269    case P4_KEYINFO: {
48270      int i, j;
48271      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
48272      sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
48273      i = sqlite3Strlen30(zTemp);
48274      for(j=0; j<pKeyInfo->nField; j++){
48275        CollSeq *pColl = pKeyInfo->aColl[j];
48276        if( pColl ){
48277          int n = sqlite3Strlen30(pColl->zName);
48278          if( i+n>nTemp-6 ){
48279            memcpy(&zTemp[i],",...",4);
48280            break;
48281          }
48282          zTemp[i++] = ',';
48283          if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
48284            zTemp[i++] = '-';
48285          }
48286          memcpy(&zTemp[i], pColl->zName,n+1);
48287          i += n;
48288        }else if( i+4<nTemp-6 ){
48289          memcpy(&zTemp[i],",nil",4);
48290          i += 4;
48291        }
48292      }
48293      zTemp[i++] = ')';
48294      zTemp[i] = 0;
48295      assert( i<nTemp );
48296      break;
48297    }
48298    case P4_COLLSEQ: {
48299      CollSeq *pColl = pOp->p4.pColl;
48300      sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
48301      break;
48302    }
48303    case P4_FUNCDEF: {
48304      FuncDef *pDef = pOp->p4.pFunc;
48305      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
48306      break;
48307    }
48308    case P4_INT64: {
48309      sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
48310      break;
48311    }
48312    case P4_INT32: {
48313      sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
48314      break;
48315    }
48316    case P4_REAL: {
48317      sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
48318      break;
48319    }
48320    case P4_MEM: {
48321      Mem *pMem = pOp->p4.pMem;
48322      assert( (pMem->flags & MEM_Null)==0 );
48323      if( pMem->flags & MEM_Str ){
48324        zP4 = pMem->z;
48325      }else if( pMem->flags & MEM_Int ){
48326        sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
48327      }else if( pMem->flags & MEM_Real ){
48328        sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
48329      }else{
48330        assert( pMem->flags & MEM_Blob );
48331        zP4 = "(blob)";
48332      }
48333      break;
48334    }
48335#ifndef SQLITE_OMIT_VIRTUALTABLE
48336    case P4_VTAB: {
48337      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
48338      sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
48339      break;
48340    }
48341#endif
48342    case P4_INTARRAY: {
48343      sqlite3_snprintf(nTemp, zTemp, "intarray");
48344      break;
48345    }
48346    case P4_SUBPROGRAM: {
48347      sqlite3_snprintf(nTemp, zTemp, "program");
48348      break;
48349    }
48350    default: {
48351      zP4 = pOp->p4.z;
48352      if( zP4==0 ){
48353        zP4 = zTemp;
48354        zTemp[0] = 0;
48355      }
48356    }
48357  }
48358  assert( zP4!=0 );
48359  return zP4;
48360}
48361#endif
48362
48363/*
48364** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
48365*/
48366SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
48367  int mask;
48368  assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
48369  assert( i<(int)sizeof(p->btreeMask)*8 );
48370  mask = ((u32)1)<<i;
48371  if( (p->btreeMask & mask)==0 ){
48372    p->btreeMask |= mask;
48373    sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
48374  }
48375}
48376
48377
48378#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
48379/*
48380** Print a single opcode.  This routine is used for debugging only.
48381*/
48382SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
48383  char *zP4;
48384  char zPtr[50];
48385  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
48386  if( pOut==0 ) pOut = stdout;
48387  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
48388  fprintf(pOut, zFormat1, pc,
48389      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
48390#ifdef SQLITE_DEBUG
48391      pOp->zComment ? pOp->zComment : ""
48392#else
48393      ""
48394#endif
48395  );
48396  fflush(pOut);
48397}
48398#endif
48399
48400/*
48401** Release an array of N Mem elements
48402*/
48403static void releaseMemArray(Mem *p, int N){
48404  if( p && N ){
48405    Mem *pEnd;
48406    sqlite3 *db = p->db;
48407    u8 malloc_failed = db->mallocFailed;
48408    for(pEnd=&p[N]; p<pEnd; p++){
48409      assert( (&p[1])==pEnd || p[0].db==p[1].db );
48410
48411      /* This block is really an inlined version of sqlite3VdbeMemRelease()
48412      ** that takes advantage of the fact that the memory cell value is
48413      ** being set to NULL after releasing any dynamic resources.
48414      **
48415      ** The justification for duplicating code is that according to
48416      ** callgrind, this causes a certain test case to hit the CPU 4.7
48417      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
48418      ** sqlite3MemRelease() were called from here. With -O2, this jumps
48419      ** to 6.6 percent. The test case is inserting 1000 rows into a table
48420      ** with no indexes using a single prepared INSERT statement, bind()
48421      ** and reset(). Inserts are grouped into a transaction.
48422      */
48423      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
48424        sqlite3VdbeMemRelease(p);
48425      }else if( p->zMalloc ){
48426        sqlite3DbFree(db, p->zMalloc);
48427        p->zMalloc = 0;
48428      }
48429
48430      p->flags = MEM_Null;
48431    }
48432    db->mallocFailed = malloc_failed;
48433  }
48434}
48435
48436/*
48437** Delete a VdbeFrame object and its contents. VdbeFrame objects are
48438** allocated by the OP_Program opcode in sqlite3VdbeExec().
48439*/
48440SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
48441  int i;
48442  Mem *aMem = VdbeFrameMem(p);
48443  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
48444  for(i=0; i<p->nChildCsr; i++){
48445    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
48446  }
48447  releaseMemArray(aMem, p->nChildMem);
48448  sqlite3DbFree(p->v->db, p);
48449}
48450
48451#ifndef SQLITE_OMIT_EXPLAIN
48452/*
48453** Give a listing of the program in the virtual machine.
48454**
48455** The interface is the same as sqlite3VdbeExec().  But instead of
48456** running the code, it invokes the callback once for each instruction.
48457** This feature is used to implement "EXPLAIN".
48458**
48459** When p->explain==1, each instruction is listed.  When
48460** p->explain==2, only OP_Explain instructions are listed and these
48461** are shown in a different format.  p->explain==2 is used to implement
48462** EXPLAIN QUERY PLAN.
48463**
48464** When p->explain==1, first the main program is listed, then each of
48465** the trigger subprograms are listed one by one.
48466*/
48467SQLITE_PRIVATE int sqlite3VdbeList(
48468  Vdbe *p                   /* The VDBE */
48469){
48470  int nRow;                            /* Stop when row count reaches this */
48471  int nSub = 0;                        /* Number of sub-vdbes seen so far */
48472  SubProgram **apSub = 0;              /* Array of sub-vdbes */
48473  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
48474  sqlite3 *db = p->db;                 /* The database connection */
48475  int i;                               /* Loop counter */
48476  int rc = SQLITE_OK;                  /* Return code */
48477  Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
48478
48479  assert( p->explain );
48480  assert( p->magic==VDBE_MAGIC_RUN );
48481  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
48482
48483  /* Even though this opcode does not use dynamic strings for
48484  ** the result, result columns may become dynamic if the user calls
48485  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
48486  */
48487  releaseMemArray(pMem, 8);
48488
48489  if( p->rc==SQLITE_NOMEM ){
48490    /* This happens if a malloc() inside a call to sqlite3_column_text() or
48491    ** sqlite3_column_text16() failed.  */
48492    db->mallocFailed = 1;
48493    return SQLITE_ERROR;
48494  }
48495
48496  /* When the number of output rows reaches nRow, that means the
48497  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
48498  ** nRow is the sum of the number of rows in the main program, plus
48499  ** the sum of the number of rows in all trigger subprograms encountered
48500  ** so far.  The nRow value will increase as new trigger subprograms are
48501  ** encountered, but p->pc will eventually catch up to nRow.
48502  */
48503  nRow = p->nOp;
48504  if( p->explain==1 ){
48505    /* The first 8 memory cells are used for the result set.  So we will
48506    ** commandeer the 9th cell to use as storage for an array of pointers
48507    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
48508    ** cells.  */
48509    assert( p->nMem>9 );
48510    pSub = &p->aMem[9];
48511    if( pSub->flags&MEM_Blob ){
48512      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
48513      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
48514      nSub = pSub->n/sizeof(Vdbe*);
48515      apSub = (SubProgram **)pSub->z;
48516    }
48517    for(i=0; i<nSub; i++){
48518      nRow += apSub[i]->nOp;
48519    }
48520  }
48521
48522  do{
48523    i = p->pc++;
48524  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
48525  if( i>=nRow ){
48526    p->rc = SQLITE_OK;
48527    rc = SQLITE_DONE;
48528  }else if( db->u1.isInterrupted ){
48529    p->rc = SQLITE_INTERRUPT;
48530    rc = SQLITE_ERROR;
48531    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
48532  }else{
48533    char *z;
48534    Op *pOp;
48535    if( i<p->nOp ){
48536      /* The output line number is small enough that we are still in the
48537      ** main program. */
48538      pOp = &p->aOp[i];
48539    }else{
48540      /* We are currently listing subprograms.  Figure out which one and
48541      ** pick up the appropriate opcode. */
48542      int j;
48543      i -= p->nOp;
48544      for(j=0; i>=apSub[j]->nOp; j++){
48545        i -= apSub[j]->nOp;
48546      }
48547      pOp = &apSub[j]->aOp[i];
48548    }
48549    if( p->explain==1 ){
48550      pMem->flags = MEM_Int;
48551      pMem->type = SQLITE_INTEGER;
48552      pMem->u.i = i;                                /* Program counter */
48553      pMem++;
48554
48555      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
48556      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
48557      assert( pMem->z!=0 );
48558      pMem->n = sqlite3Strlen30(pMem->z);
48559      pMem->type = SQLITE_TEXT;
48560      pMem->enc = SQLITE_UTF8;
48561      pMem++;
48562
48563      /* When an OP_Program opcode is encounter (the only opcode that has
48564      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
48565      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
48566      ** has not already been seen.
48567      */
48568      if( pOp->p4type==P4_SUBPROGRAM ){
48569        int nByte = (nSub+1)*sizeof(SubProgram*);
48570        int j;
48571        for(j=0; j<nSub; j++){
48572          if( apSub[j]==pOp->p4.pProgram ) break;
48573        }
48574        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
48575          apSub = (SubProgram **)pSub->z;
48576          apSub[nSub++] = pOp->p4.pProgram;
48577          pSub->flags |= MEM_Blob;
48578          pSub->n = nSub*sizeof(SubProgram*);
48579        }
48580      }
48581    }
48582
48583    pMem->flags = MEM_Int;
48584    pMem->u.i = pOp->p1;                          /* P1 */
48585    pMem->type = SQLITE_INTEGER;
48586    pMem++;
48587
48588    pMem->flags = MEM_Int;
48589    pMem->u.i = pOp->p2;                          /* P2 */
48590    pMem->type = SQLITE_INTEGER;
48591    pMem++;
48592
48593    if( p->explain==1 ){
48594      pMem->flags = MEM_Int;
48595      pMem->u.i = pOp->p3;                          /* P3 */
48596      pMem->type = SQLITE_INTEGER;
48597      pMem++;
48598    }
48599
48600    if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
48601      assert( p->db->mallocFailed );
48602      return SQLITE_ERROR;
48603    }
48604    pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
48605    z = displayP4(pOp, pMem->z, 32);
48606    if( z!=pMem->z ){
48607      sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
48608    }else{
48609      assert( pMem->z!=0 );
48610      pMem->n = sqlite3Strlen30(pMem->z);
48611      pMem->enc = SQLITE_UTF8;
48612    }
48613    pMem->type = SQLITE_TEXT;
48614    pMem++;
48615
48616    if( p->explain==1 ){
48617      if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
48618        assert( p->db->mallocFailed );
48619        return SQLITE_ERROR;
48620      }
48621      pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
48622      pMem->n = 2;
48623      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
48624      pMem->type = SQLITE_TEXT;
48625      pMem->enc = SQLITE_UTF8;
48626      pMem++;
48627
48628#ifdef SQLITE_DEBUG
48629      if( pOp->zComment ){
48630        pMem->flags = MEM_Str|MEM_Term;
48631        pMem->z = pOp->zComment;
48632        pMem->n = sqlite3Strlen30(pMem->z);
48633        pMem->enc = SQLITE_UTF8;
48634        pMem->type = SQLITE_TEXT;
48635      }else
48636#endif
48637      {
48638        pMem->flags = MEM_Null;                       /* Comment */
48639        pMem->type = SQLITE_NULL;
48640      }
48641    }
48642
48643    p->nResColumn = 8 - 5*(p->explain-1);
48644    p->rc = SQLITE_OK;
48645    rc = SQLITE_ROW;
48646  }
48647  return rc;
48648}
48649#endif /* SQLITE_OMIT_EXPLAIN */
48650
48651#ifdef SQLITE_DEBUG
48652/*
48653** Print the SQL that was used to generate a VDBE program.
48654*/
48655SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
48656  int nOp = p->nOp;
48657  VdbeOp *pOp;
48658  if( nOp<1 ) return;
48659  pOp = &p->aOp[0];
48660  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
48661    const char *z = pOp->p4.z;
48662    while( sqlite3Isspace(*z) ) z++;
48663    printf("SQL: [%s]\n", z);
48664  }
48665}
48666#endif
48667
48668#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
48669/*
48670** Print an IOTRACE message showing SQL content.
48671*/
48672SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
48673  int nOp = p->nOp;
48674  VdbeOp *pOp;
48675  if( sqlite3IoTrace==0 ) return;
48676  if( nOp<1 ) return;
48677  pOp = &p->aOp[0];
48678  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
48679    int i, j;
48680    char z[1000];
48681    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
48682    for(i=0; sqlite3Isspace(z[i]); i++){}
48683    for(j=0; z[i]; i++){
48684      if( sqlite3Isspace(z[i]) ){
48685        if( z[i-1]!=' ' ){
48686          z[j++] = ' ';
48687        }
48688      }else{
48689        z[j++] = z[i];
48690      }
48691    }
48692    z[j] = 0;
48693    sqlite3IoTrace("SQL %s\n", z);
48694  }
48695}
48696#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
48697
48698/*
48699** Allocate space from a fixed size buffer and return a pointer to
48700** that space.  If insufficient space is available, return NULL.
48701**
48702** The pBuf parameter is the initial value of a pointer which will
48703** receive the new memory.  pBuf is normally NULL.  If pBuf is not
48704** NULL, it means that memory space has already been allocated and that
48705** this routine should not allocate any new memory.  When pBuf is not
48706** NULL simply return pBuf.  Only allocate new memory space when pBuf
48707** is NULL.
48708**
48709** nByte is the number of bytes of space needed.
48710**
48711** *ppFrom points to available space and pEnd points to the end of the
48712** available space.  When space is allocated, *ppFrom is advanced past
48713** the end of the allocated space.
48714**
48715** *pnByte is a counter of the number of bytes of space that have failed
48716** to allocate.  If there is insufficient space in *ppFrom to satisfy the
48717** request, then increment *pnByte by the amount of the request.
48718*/
48719static void *allocSpace(
48720  void *pBuf,          /* Where return pointer will be stored */
48721  int nByte,           /* Number of bytes to allocate */
48722  u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
48723  u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
48724  int *pnByte          /* If allocation cannot be made, increment *pnByte */
48725){
48726  assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
48727  if( pBuf ) return pBuf;
48728  nByte = ROUND8(nByte);
48729  if( &(*ppFrom)[nByte] <= pEnd ){
48730    pBuf = (void*)*ppFrom;
48731    *ppFrom += nByte;
48732  }else{
48733    *pnByte += nByte;
48734  }
48735  return pBuf;
48736}
48737
48738/*
48739** Prepare a virtual machine for execution.  This involves things such
48740** as allocating stack space and initializing the program counter.
48741** After the VDBE has be prepped, it can be executed by one or more
48742** calls to sqlite3VdbeExec().
48743**
48744** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
48745** VDBE_MAGIC_RUN.
48746**
48747** This function may be called more than once on a single virtual machine.
48748** The first call is made while compiling the SQL statement. Subsequent
48749** calls are made as part of the process of resetting a statement to be
48750** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor
48751** and isExplain parameters are only passed correct values the first time
48752** the function is called. On subsequent calls, from sqlite3_reset(), nVar
48753** is passed -1 and nMem, nCursor and isExplain are all passed zero.
48754*/
48755SQLITE_PRIVATE void sqlite3VdbeMakeReady(
48756  Vdbe *p,                       /* The VDBE */
48757  int nVar,                      /* Number of '?' see in the SQL statement */
48758  int nMem,                      /* Number of memory cells to allocate */
48759  int nCursor,                   /* Number of cursors to allocate */
48760  int nArg,                      /* Maximum number of args in SubPrograms */
48761  int isExplain,                 /* True if the EXPLAIN keywords is present */
48762  int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
48763){
48764  int n;
48765  sqlite3 *db = p->db;
48766
48767  assert( p!=0 );
48768  assert( p->magic==VDBE_MAGIC_INIT );
48769
48770  /* There should be at least one opcode.
48771  */
48772  assert( p->nOp>0 );
48773
48774  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
48775  p->magic = VDBE_MAGIC_RUN;
48776
48777  /* For each cursor required, also allocate a memory cell. Memory
48778  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
48779  ** the vdbe program. Instead they are used to allocate space for
48780  ** VdbeCursor/BtCursor structures. The blob of memory associated with
48781  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
48782  ** stores the blob of memory associated with cursor 1, etc.
48783  **
48784  ** See also: allocateCursor().
48785  */
48786  nMem += nCursor;
48787
48788  /* Allocate space for memory registers, SQL variables, VDBE cursors and
48789  ** an array to marshal SQL function arguments in. This is only done the
48790  ** first time this function is called for a given VDBE, not when it is
48791  ** being called from sqlite3_reset() to reset the virtual machine.
48792  */
48793  if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
48794    u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
48795    u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
48796    int nByte;                              /* How much extra memory needed */
48797
48798    resolveP2Values(p, &nArg);
48799    p->usesStmtJournal = (u8)usesStmtJournal;
48800    if( isExplain && nMem<10 ){
48801      nMem = 10;
48802    }
48803    memset(zCsr, 0, zEnd-zCsr);
48804    zCsr += (zCsr - (u8*)0)&7;
48805    assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
48806
48807    /* Memory for registers, parameters, cursor, etc, is allocated in two
48808    ** passes.  On the first pass, we try to reuse unused space at the
48809    ** end of the opcode array.  If we are unable to satisfy all memory
48810    ** requirements by reusing the opcode array tail, then the second
48811    ** pass will fill in the rest using a fresh allocation.
48812    **
48813    ** This two-pass approach that reuses as much memory as possible from
48814    ** the leftover space at the end of the opcode array can significantly
48815    ** reduce the amount of memory held by a prepared statement.
48816    */
48817    do {
48818      nByte = 0;
48819      p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
48820      p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
48821      p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
48822      p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
48823      p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
48824                            &zCsr, zEnd, &nByte);
48825      if( nByte ){
48826        p->pFree = sqlite3DbMallocZero(db, nByte);
48827      }
48828      zCsr = p->pFree;
48829      zEnd = &zCsr[nByte];
48830    }while( nByte && !db->mallocFailed );
48831
48832    p->nCursor = (u16)nCursor;
48833    if( p->aVar ){
48834      p->nVar = (ynVar)nVar;
48835      for(n=0; n<nVar; n++){
48836        p->aVar[n].flags = MEM_Null;
48837        p->aVar[n].db = db;
48838      }
48839    }
48840    if( p->aMem ){
48841      p->aMem--;                      /* aMem[] goes from 1..nMem */
48842      p->nMem = nMem;                 /*       not from 0..nMem-1 */
48843      for(n=1; n<=nMem; n++){
48844        p->aMem[n].flags = MEM_Null;
48845        p->aMem[n].db = db;
48846      }
48847    }
48848  }
48849#ifdef SQLITE_DEBUG
48850  for(n=1; n<p->nMem; n++){
48851    assert( p->aMem[n].db==db );
48852  }
48853#endif
48854
48855  p->pc = -1;
48856  p->rc = SQLITE_OK;
48857  p->errorAction = OE_Abort;
48858  p->explain |= isExplain;
48859  p->magic = VDBE_MAGIC_RUN;
48860  p->nChange = 0;
48861  p->cacheCtr = 1;
48862  p->minWriteFileFormat = 255;
48863  p->iStatement = 0;
48864#ifdef VDBE_PROFILE
48865  {
48866    int i;
48867    for(i=0; i<p->nOp; i++){
48868      p->aOp[i].cnt = 0;
48869      p->aOp[i].cycles = 0;
48870    }
48871  }
48872#endif
48873}
48874
48875/*
48876** Close a VDBE cursor and release all the resources that cursor
48877** happens to hold.
48878*/
48879SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
48880  if( pCx==0 ){
48881    return;
48882  }
48883  if( pCx->pBt ){
48884    sqlite3BtreeClose(pCx->pBt);
48885    /* The pCx->pCursor will be close automatically, if it exists, by
48886    ** the call above. */
48887  }else if( pCx->pCursor ){
48888    sqlite3BtreeCloseCursor(pCx->pCursor);
48889  }
48890#ifndef SQLITE_OMIT_VIRTUALTABLE
48891  if( pCx->pVtabCursor ){
48892    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
48893    const sqlite3_module *pModule = pCx->pModule;
48894    p->inVtabMethod = 1;
48895    pModule->xClose(pVtabCursor);
48896    p->inVtabMethod = 0;
48897  }
48898#endif
48899}
48900
48901/*
48902** Copy the values stored in the VdbeFrame structure to its Vdbe. This
48903** is used, for example, when a trigger sub-program is halted to restore
48904** control to the main program.
48905*/
48906SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
48907  Vdbe *v = pFrame->v;
48908  v->aOp = pFrame->aOp;
48909  v->nOp = pFrame->nOp;
48910  v->aMem = pFrame->aMem;
48911  v->nMem = pFrame->nMem;
48912  v->apCsr = pFrame->apCsr;
48913  v->nCursor = pFrame->nCursor;
48914  v->db->lastRowid = pFrame->lastRowid;
48915  v->nChange = pFrame->nChange;
48916  return pFrame->pc;
48917}
48918
48919/*
48920** Close all cursors.
48921**
48922** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
48923** cell array. This is necessary as the memory cell array may contain
48924** pointers to VdbeFrame objects, which may in turn contain pointers to
48925** open cursors.
48926*/
48927static void closeAllCursors(Vdbe *p){
48928  if( p->pFrame ){
48929    VdbeFrame *pFrame = p->pFrame;
48930    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
48931    sqlite3VdbeFrameRestore(pFrame);
48932  }
48933  p->pFrame = 0;
48934  p->nFrame = 0;
48935
48936  if( p->apCsr ){
48937    int i;
48938    for(i=0; i<p->nCursor; i++){
48939      VdbeCursor *pC = p->apCsr[i];
48940      if( pC ){
48941        sqlite3VdbeFreeCursor(p, pC);
48942        p->apCsr[i] = 0;
48943      }
48944    }
48945  }
48946  if( p->aMem ){
48947    releaseMemArray(&p->aMem[1], p->nMem);
48948  }
48949}
48950
48951/*
48952** Clean up the VM after execution.
48953**
48954** This routine will automatically close any cursors, lists, and/or
48955** sorters that were left open.  It also deletes the values of
48956** variables in the aVar[] array.
48957*/
48958static void Cleanup(Vdbe *p){
48959  sqlite3 *db = p->db;
48960
48961#ifdef SQLITE_DEBUG
48962  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
48963  ** Vdbe.aMem[] arrays have already been cleaned up.  */
48964  int i;
48965  for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
48966  for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
48967#endif
48968
48969  sqlite3DbFree(db, p->zErrMsg);
48970  p->zErrMsg = 0;
48971  p->pResultSet = 0;
48972}
48973
48974/*
48975** Set the number of result columns that will be returned by this SQL
48976** statement. This is now set at compile time, rather than during
48977** execution of the vdbe program so that sqlite3_column_count() can
48978** be called on an SQL statement before sqlite3_step().
48979*/
48980SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
48981  Mem *pColName;
48982  int n;
48983  sqlite3 *db = p->db;
48984
48985  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
48986  sqlite3DbFree(db, p->aColName);
48987  n = nResColumn*COLNAME_N;
48988  p->nResColumn = (u16)nResColumn;
48989  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
48990  if( p->aColName==0 ) return;
48991  while( n-- > 0 ){
48992    pColName->flags = MEM_Null;
48993    pColName->db = p->db;
48994    pColName++;
48995  }
48996}
48997
48998/*
48999** Set the name of the idx'th column to be returned by the SQL statement.
49000** zName must be a pointer to a nul terminated string.
49001**
49002** This call must be made after a call to sqlite3VdbeSetNumCols().
49003**
49004** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
49005** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
49006** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
49007*/
49008SQLITE_PRIVATE int sqlite3VdbeSetColName(
49009  Vdbe *p,                         /* Vdbe being configured */
49010  int idx,                         /* Index of column zName applies to */
49011  int var,                         /* One of the COLNAME_* constants */
49012  const char *zName,               /* Pointer to buffer containing name */
49013  void (*xDel)(void*)              /* Memory management strategy for zName */
49014){
49015  int rc;
49016  Mem *pColName;
49017  assert( idx<p->nResColumn );
49018  assert( var<COLNAME_N );
49019  if( p->db->mallocFailed ){
49020    assert( !zName || xDel!=SQLITE_DYNAMIC );
49021    return SQLITE_NOMEM;
49022  }
49023  assert( p->aColName!=0 );
49024  pColName = &(p->aColName[idx+var*p->nResColumn]);
49025  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
49026  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
49027  return rc;
49028}
49029
49030/*
49031** A read or write transaction may or may not be active on database handle
49032** db. If a transaction is active, commit it. If there is a
49033** write-transaction spanning more than one database file, this routine
49034** takes care of the master journal trickery.
49035*/
49036static int vdbeCommit(sqlite3 *db, Vdbe *p){
49037  int i;
49038  int nTrans = 0;  /* Number of databases with an active write-transaction */
49039  int rc = SQLITE_OK;
49040  int needXcommit = 0;
49041
49042#ifdef SQLITE_OMIT_VIRTUALTABLE
49043  /* With this option, sqlite3VtabSync() is defined to be simply
49044  ** SQLITE_OK so p is not used.
49045  */
49046  UNUSED_PARAMETER(p);
49047#endif
49048
49049  /* Before doing anything else, call the xSync() callback for any
49050  ** virtual module tables written in this transaction. This has to
49051  ** be done before determining whether a master journal file is
49052  ** required, as an xSync() callback may add an attached database
49053  ** to the transaction.
49054  */
49055  rc = sqlite3VtabSync(db, &p->zErrMsg);
49056  if( rc!=SQLITE_OK ){
49057    return rc;
49058  }
49059
49060  /* This loop determines (a) if the commit hook should be invoked and
49061  ** (b) how many database files have open write transactions, not
49062  ** including the temp database. (b) is important because if more than
49063  ** one database file has an open write transaction, a master journal
49064  ** file is required for an atomic commit.
49065  */
49066  for(i=0; i<db->nDb; i++){
49067    Btree *pBt = db->aDb[i].pBt;
49068    if( sqlite3BtreeIsInTrans(pBt) ){
49069      needXcommit = 1;
49070      if( i!=1 ) nTrans++;
49071    }
49072  }
49073
49074  /* If there are any write-transactions at all, invoke the commit hook */
49075  if( needXcommit && db->xCommitCallback ){
49076    rc = db->xCommitCallback(db->pCommitArg);
49077    if( rc ){
49078      return SQLITE_CONSTRAINT;
49079    }
49080  }
49081
49082  /* The simple case - no more than one database file (not counting the
49083  ** TEMP database) has a transaction active.   There is no need for the
49084  ** master-journal.
49085  **
49086  ** If the return value of sqlite3BtreeGetFilename() is a zero length
49087  ** string, it means the main database is :memory: or a temp file.  In
49088  ** that case we do not support atomic multi-file commits, so use the
49089  ** simple case then too.
49090  */
49091  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
49092   || nTrans<=1
49093  ){
49094    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
49095      Btree *pBt = db->aDb[i].pBt;
49096      if( pBt ){
49097        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
49098      }
49099    }
49100
49101    /* Do the commit only if all databases successfully complete phase 1.
49102    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
49103    ** IO error while deleting or truncating a journal file. It is unlikely,
49104    ** but could happen. In this case abandon processing and return the error.
49105    */
49106    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
49107      Btree *pBt = db->aDb[i].pBt;
49108      if( pBt ){
49109        rc = sqlite3BtreeCommitPhaseTwo(pBt);
49110      }
49111    }
49112    if( rc==SQLITE_OK ){
49113      sqlite3VtabCommit(db);
49114    }
49115  }
49116
49117  /* The complex case - There is a multi-file write-transaction active.
49118  ** This requires a master journal file to ensure the transaction is
49119  ** committed atomicly.
49120  */
49121#ifndef SQLITE_OMIT_DISKIO
49122  else{
49123    sqlite3_vfs *pVfs = db->pVfs;
49124    int needSync = 0;
49125    char *zMaster = 0;   /* File-name for the master journal */
49126    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
49127    sqlite3_file *pMaster = 0;
49128    i64 offset = 0;
49129    int res;
49130
49131    /* Select a master journal file name */
49132    do {
49133      u32 iRandom;
49134      sqlite3DbFree(db, zMaster);
49135      sqlite3_randomness(sizeof(iRandom), &iRandom);
49136      zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
49137      if( !zMaster ){
49138        return SQLITE_NOMEM;
49139      }
49140      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
49141    }while( rc==SQLITE_OK && res );
49142    if( rc==SQLITE_OK ){
49143      /* Open the master journal. */
49144      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
49145          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
49146          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
49147      );
49148    }
49149    if( rc!=SQLITE_OK ){
49150      sqlite3DbFree(db, zMaster);
49151      return rc;
49152    }
49153
49154    /* Write the name of each database file in the transaction into the new
49155    ** master journal file. If an error occurs at this point close
49156    ** and delete the master journal file. All the individual journal files
49157    ** still have 'null' as the master journal pointer, so they will roll
49158    ** back independently if a failure occurs.
49159    */
49160    for(i=0; i<db->nDb; i++){
49161      Btree *pBt = db->aDb[i].pBt;
49162      if( sqlite3BtreeIsInTrans(pBt) ){
49163        char const *zFile = sqlite3BtreeGetJournalname(pBt);
49164        if( zFile==0 || zFile[0]==0 ){
49165          continue;  /* Ignore TEMP and :memory: databases */
49166        }
49167        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
49168          needSync = 1;
49169        }
49170        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
49171        offset += sqlite3Strlen30(zFile)+1;
49172        if( rc!=SQLITE_OK ){
49173          sqlite3OsCloseFree(pMaster);
49174          sqlite3OsDelete(pVfs, zMaster, 0);
49175          sqlite3DbFree(db, zMaster);
49176          return rc;
49177        }
49178      }
49179    }
49180
49181    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
49182    ** flag is set this is not required.
49183    */
49184    if( needSync
49185     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
49186     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
49187    ){
49188      sqlite3OsCloseFree(pMaster);
49189      sqlite3OsDelete(pVfs, zMaster, 0);
49190      sqlite3DbFree(db, zMaster);
49191      return rc;
49192    }
49193
49194    /* Sync all the db files involved in the transaction. The same call
49195    ** sets the master journal pointer in each individual journal. If
49196    ** an error occurs here, do not delete the master journal file.
49197    **
49198    ** If the error occurs during the first call to
49199    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
49200    ** master journal file will be orphaned. But we cannot delete it,
49201    ** in case the master journal file name was written into the journal
49202    ** file before the failure occurred.
49203    */
49204    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
49205      Btree *pBt = db->aDb[i].pBt;
49206      if( pBt ){
49207        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
49208      }
49209    }
49210    sqlite3OsCloseFree(pMaster);
49211    if( rc!=SQLITE_OK ){
49212      sqlite3DbFree(db, zMaster);
49213      return rc;
49214    }
49215
49216    /* Delete the master journal file. This commits the transaction. After
49217    ** doing this the directory is synced again before any individual
49218    ** transaction files are deleted.
49219    */
49220    rc = sqlite3OsDelete(pVfs, zMaster, 1);
49221    sqlite3DbFree(db, zMaster);
49222    zMaster = 0;
49223    if( rc ){
49224      return rc;
49225    }
49226
49227    /* All files and directories have already been synced, so the following
49228    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
49229    ** deleting or truncating journals. If something goes wrong while
49230    ** this is happening we don't really care. The integrity of the
49231    ** transaction is already guaranteed, but some stray 'cold' journals
49232    ** may be lying around. Returning an error code won't help matters.
49233    */
49234    disable_simulated_io_errors();
49235    sqlite3BeginBenignMalloc();
49236    for(i=0; i<db->nDb; i++){
49237      Btree *pBt = db->aDb[i].pBt;
49238      if( pBt ){
49239        sqlite3BtreeCommitPhaseTwo(pBt);
49240      }
49241    }
49242    sqlite3EndBenignMalloc();
49243    enable_simulated_io_errors();
49244
49245    sqlite3VtabCommit(db);
49246  }
49247#endif
49248
49249  return rc;
49250}
49251
49252/*
49253** This routine checks that the sqlite3.activeVdbeCnt count variable
49254** matches the number of vdbe's in the list sqlite3.pVdbe that are
49255** currently active. An assertion fails if the two counts do not match.
49256** This is an internal self-check only - it is not an essential processing
49257** step.
49258**
49259** This is a no-op if NDEBUG is defined.
49260*/
49261#ifndef NDEBUG
49262static void checkActiveVdbeCnt(sqlite3 *db){
49263  Vdbe *p;
49264  int cnt = 0;
49265  int nWrite = 0;
49266  p = db->pVdbe;
49267  while( p ){
49268    if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
49269      cnt++;
49270      if( p->readOnly==0 ) nWrite++;
49271    }
49272    p = p->pNext;
49273  }
49274  assert( cnt==db->activeVdbeCnt );
49275  assert( nWrite==db->writeVdbeCnt );
49276}
49277#else
49278#define checkActiveVdbeCnt(x)
49279#endif
49280
49281/*
49282** For every Btree that in database connection db which
49283** has been modified, "trip" or invalidate each cursor in
49284** that Btree might have been modified so that the cursor
49285** can never be used again.  This happens when a rollback
49286*** occurs.  We have to trip all the other cursors, even
49287** cursor from other VMs in different database connections,
49288** so that none of them try to use the data at which they
49289** were pointing and which now may have been changed due
49290** to the rollback.
49291**
49292** Remember that a rollback can delete tables complete and
49293** reorder rootpages.  So it is not sufficient just to save
49294** the state of the cursor.  We have to invalidate the cursor
49295** so that it is never used again.
49296*/
49297static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
49298  int i;
49299  for(i=0; i<db->nDb; i++){
49300    Btree *p = db->aDb[i].pBt;
49301    if( p && sqlite3BtreeIsInTrans(p) ){
49302      sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
49303    }
49304  }
49305}
49306
49307/*
49308** If the Vdbe passed as the first argument opened a statement-transaction,
49309** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
49310** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
49311** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
49312** statement transaction is commtted.
49313**
49314** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
49315** Otherwise SQLITE_OK.
49316*/
49317SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
49318  sqlite3 *const db = p->db;
49319  int rc = SQLITE_OK;
49320
49321  /* If p->iStatement is greater than zero, then this Vdbe opened a
49322  ** statement transaction that should be closed here. The only exception
49323  ** is that an IO error may have occured, causing an emergency rollback.
49324  ** In this case (db->nStatement==0), and there is nothing to do.
49325  */
49326  if( db->nStatement && p->iStatement ){
49327    int i;
49328    const int iSavepoint = p->iStatement-1;
49329
49330    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
49331    assert( db->nStatement>0 );
49332    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
49333
49334    for(i=0; i<db->nDb; i++){
49335      int rc2 = SQLITE_OK;
49336      Btree *pBt = db->aDb[i].pBt;
49337      if( pBt ){
49338        if( eOp==SAVEPOINT_ROLLBACK ){
49339          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
49340        }
49341        if( rc2==SQLITE_OK ){
49342          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
49343        }
49344        if( rc==SQLITE_OK ){
49345          rc = rc2;
49346        }
49347      }
49348    }
49349    db->nStatement--;
49350    p->iStatement = 0;
49351
49352    /* If the statement transaction is being rolled back, also restore the
49353    ** database handles deferred constraint counter to the value it had when
49354    ** the statement transaction was opened.  */
49355    if( eOp==SAVEPOINT_ROLLBACK ){
49356      db->nDeferredCons = p->nStmtDefCons;
49357    }
49358  }
49359  return rc;
49360}
49361
49362/*
49363** If SQLite is compiled to support shared-cache mode and to be threadsafe,
49364** this routine obtains the mutex associated with each BtShared structure
49365** that may be accessed by the VM passed as an argument. In doing so it
49366** sets the BtShared.db member of each of the BtShared structures, ensuring
49367** that the correct busy-handler callback is invoked if required.
49368**
49369** If SQLite is not threadsafe but does support shared-cache mode, then
49370** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
49371** of all of BtShared structures accessible via the database handle
49372** associated with the VM. Of course only a subset of these structures
49373** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
49374** that subset out, but there is no advantage to doing so.
49375**
49376** If SQLite is not threadsafe and does not support shared-cache mode, this
49377** function is a no-op.
49378*/
49379#ifndef SQLITE_OMIT_SHARED_CACHE
49380SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p){
49381#if SQLITE_THREADSAFE
49382  sqlite3BtreeMutexArrayEnter(&p->aMutex);
49383#else
49384  sqlite3BtreeEnterAll(p->db);
49385#endif
49386}
49387#endif
49388
49389/*
49390** This function is called when a transaction opened by the database
49391** handle associated with the VM passed as an argument is about to be
49392** committed. If there are outstanding deferred foreign key constraint
49393** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
49394**
49395** If there are outstanding FK violations and this function returns
49396** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
49397** an error message to it. Then return SQLITE_ERROR.
49398*/
49399#ifndef SQLITE_OMIT_FOREIGN_KEY
49400SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
49401  sqlite3 *db = p->db;
49402  if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
49403    p->rc = SQLITE_CONSTRAINT;
49404    p->errorAction = OE_Abort;
49405    sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
49406    return SQLITE_ERROR;
49407  }
49408  return SQLITE_OK;
49409}
49410#endif
49411
49412/*
49413** This routine is called the when a VDBE tries to halt.  If the VDBE
49414** has made changes and is in autocommit mode, then commit those
49415** changes.  If a rollback is needed, then do the rollback.
49416**
49417** This routine is the only way to move the state of a VM from
49418** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
49419** call this on a VM that is in the SQLITE_MAGIC_HALT state.
49420**
49421** Return an error code.  If the commit could not complete because of
49422** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
49423** means the close did not happen and needs to be repeated.
49424*/
49425SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
49426  int rc;                         /* Used to store transient return codes */
49427  sqlite3 *db = p->db;
49428
49429  /* This function contains the logic that determines if a statement or
49430  ** transaction will be committed or rolled back as a result of the
49431  ** execution of this virtual machine.
49432  **
49433  ** If any of the following errors occur:
49434  **
49435  **     SQLITE_NOMEM
49436  **     SQLITE_IOERR
49437  **     SQLITE_FULL
49438  **     SQLITE_INTERRUPT
49439  **
49440  ** Then the internal cache might have been left in an inconsistent
49441  ** state.  We need to rollback the statement transaction, if there is
49442  ** one, or the complete transaction if there is no statement transaction.
49443  */
49444
49445  if( p->db->mallocFailed ){
49446    p->rc = SQLITE_NOMEM;
49447  }
49448  closeAllCursors(p);
49449  if( p->magic!=VDBE_MAGIC_RUN ){
49450    return SQLITE_OK;
49451  }
49452  checkActiveVdbeCnt(db);
49453
49454  /* No commit or rollback needed if the program never started */
49455  if( p->pc>=0 ){
49456    int mrc;   /* Primary error code from p->rc */
49457    int eStatementOp = 0;
49458    int isSpecialError;            /* Set to true if a 'special' error */
49459
49460    /* Lock all btrees used by the statement */
49461    sqlite3VdbeMutexArrayEnter(p);
49462
49463    /* Check for one of the special errors */
49464    mrc = p->rc & 0xff;
49465    assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
49466    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
49467                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
49468    if( isSpecialError ){
49469      /* If the query was read-only, we need do no rollback at all. Otherwise,
49470      ** proceed with the special handling.
49471      */
49472      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
49473        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
49474          eStatementOp = SAVEPOINT_ROLLBACK;
49475        }else{
49476          /* We are forced to roll back the active transaction. Before doing
49477          ** so, abort any other statements this handle currently has active.
49478          */
49479          invalidateCursorsOnModifiedBtrees(db);
49480          sqlite3RollbackAll(db);
49481          sqlite3CloseSavepoints(db);
49482          db->autoCommit = 1;
49483        }
49484      }
49485    }
49486
49487    /* Check for immediate foreign key violations. */
49488    if( p->rc==SQLITE_OK ){
49489      sqlite3VdbeCheckFk(p, 0);
49490    }
49491
49492    /* If the auto-commit flag is set and this is the only active writer
49493    ** VM, then we do either a commit or rollback of the current transaction.
49494    **
49495    ** Note: This block also runs if one of the special errors handled
49496    ** above has occurred.
49497    */
49498    if( !sqlite3VtabInSync(db)
49499     && db->autoCommit
49500     && db->writeVdbeCnt==(p->readOnly==0)
49501    ){
49502      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
49503        if( sqlite3VdbeCheckFk(p, 1) ){
49504          sqlite3BtreeMutexArrayLeave(&p->aMutex);
49505          return SQLITE_ERROR;
49506        }
49507        /* The auto-commit flag is true, the vdbe program was successful
49508        ** or hit an 'OR FAIL' constraint and there are no deferred foreign
49509        ** key constraints to hold up the transaction. This means a commit
49510        ** is required.  */
49511        rc = vdbeCommit(db, p);
49512        if( rc==SQLITE_BUSY ){
49513          sqlite3BtreeMutexArrayLeave(&p->aMutex);
49514          return SQLITE_BUSY;
49515        }else if( rc!=SQLITE_OK ){
49516          p->rc = rc;
49517          sqlite3RollbackAll(db);
49518        }else{
49519          db->nDeferredCons = 0;
49520          sqlite3CommitInternalChanges(db);
49521        }
49522      }else{
49523        sqlite3RollbackAll(db);
49524      }
49525      db->nStatement = 0;
49526    }else if( eStatementOp==0 ){
49527      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
49528        eStatementOp = SAVEPOINT_RELEASE;
49529      }else if( p->errorAction==OE_Abort ){
49530        eStatementOp = SAVEPOINT_ROLLBACK;
49531      }else{
49532        invalidateCursorsOnModifiedBtrees(db);
49533        sqlite3RollbackAll(db);
49534        sqlite3CloseSavepoints(db);
49535        db->autoCommit = 1;
49536      }
49537    }
49538
49539    /* If eStatementOp is non-zero, then a statement transaction needs to
49540    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
49541    ** do so. If this operation returns an error, and the current statement
49542    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then set the error
49543    ** code to the new value.
49544    */
49545    if( eStatementOp ){
49546      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
49547      if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
49548        p->rc = rc;
49549        sqlite3DbFree(db, p->zErrMsg);
49550        p->zErrMsg = 0;
49551      }
49552    }
49553
49554    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
49555    ** has been rolled back, update the database connection change-counter.
49556    */
49557    if( p->changeCntOn ){
49558      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
49559        sqlite3VdbeSetChanges(db, p->nChange);
49560      }else{
49561        sqlite3VdbeSetChanges(db, 0);
49562      }
49563      p->nChange = 0;
49564    }
49565
49566    /* Rollback or commit any schema changes that occurred. */
49567    if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
49568      sqlite3ResetInternalSchema(db, 0);
49569      db->flags = (db->flags | SQLITE_InternChanges);
49570    }
49571
49572    /* Release the locks */
49573    sqlite3BtreeMutexArrayLeave(&p->aMutex);
49574  }
49575
49576  /* We have successfully halted and closed the VM.  Record this fact. */
49577  if( p->pc>=0 ){
49578    db->activeVdbeCnt--;
49579    if( !p->readOnly ){
49580      db->writeVdbeCnt--;
49581    }
49582    assert( db->activeVdbeCnt>=db->writeVdbeCnt );
49583  }
49584  p->magic = VDBE_MAGIC_HALT;
49585  checkActiveVdbeCnt(db);
49586  if( p->db->mallocFailed ){
49587    p->rc = SQLITE_NOMEM;
49588  }
49589
49590  /* If the auto-commit flag is set to true, then any locks that were held
49591  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
49592  ** to invoke any required unlock-notify callbacks.
49593  */
49594  if( db->autoCommit ){
49595    sqlite3ConnectionUnlocked(db);
49596  }
49597
49598  assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
49599  return SQLITE_OK;
49600}
49601
49602
49603/*
49604** Each VDBE holds the result of the most recent sqlite3_step() call
49605** in p->rc.  This routine sets that result back to SQLITE_OK.
49606*/
49607SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
49608  p->rc = SQLITE_OK;
49609}
49610
49611/*
49612** Clean up a VDBE after execution but do not delete the VDBE just yet.
49613** Write any error messages into *pzErrMsg.  Return the result code.
49614**
49615** After this routine is run, the VDBE should be ready to be executed
49616** again.
49617**
49618** To look at it another way, this routine resets the state of the
49619** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
49620** VDBE_MAGIC_INIT.
49621*/
49622SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
49623  sqlite3 *db;
49624  db = p->db;
49625
49626  /* If the VM did not run to completion or if it encountered an
49627  ** error, then it might not have been halted properly.  So halt
49628  ** it now.
49629  */
49630  sqlite3VdbeHalt(p);
49631
49632  /* If the VDBE has be run even partially, then transfer the error code
49633  ** and error message from the VDBE into the main database structure.  But
49634  ** if the VDBE has just been set to run but has not actually executed any
49635  ** instructions yet, leave the main database error information unchanged.
49636  */
49637  if( p->pc>=0 ){
49638    if( p->zErrMsg ){
49639      sqlite3BeginBenignMalloc();
49640      sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
49641      sqlite3EndBenignMalloc();
49642      db->errCode = p->rc;
49643      sqlite3DbFree(db, p->zErrMsg);
49644      p->zErrMsg = 0;
49645    }else if( p->rc ){
49646      sqlite3Error(db, p->rc, 0);
49647    }else{
49648      sqlite3Error(db, SQLITE_OK, 0);
49649    }
49650    if( p->runOnlyOnce ) p->expired = 1;
49651  }else if( p->rc && p->expired ){
49652    /* The expired flag was set on the VDBE before the first call
49653    ** to sqlite3_step(). For consistency (since sqlite3_step() was
49654    ** called), set the database error in this case as well.
49655    */
49656    sqlite3Error(db, p->rc, 0);
49657    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
49658    sqlite3DbFree(db, p->zErrMsg);
49659    p->zErrMsg = 0;
49660  }
49661
49662  /* Reclaim all memory used by the VDBE
49663  */
49664  Cleanup(p);
49665
49666  /* Save profiling information from this VDBE run.
49667  */
49668#ifdef VDBE_PROFILE
49669  {
49670    FILE *out = fopen("vdbe_profile.out", "a");
49671    if( out ){
49672      int i;
49673      fprintf(out, "---- ");
49674      for(i=0; i<p->nOp; i++){
49675        fprintf(out, "%02x", p->aOp[i].opcode);
49676      }
49677      fprintf(out, "\n");
49678      for(i=0; i<p->nOp; i++){
49679        fprintf(out, "%6d %10lld %8lld ",
49680           p->aOp[i].cnt,
49681           p->aOp[i].cycles,
49682           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
49683        );
49684        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
49685      }
49686      fclose(out);
49687    }
49688  }
49689#endif
49690  p->magic = VDBE_MAGIC_INIT;
49691  return p->rc & db->errMask;
49692}
49693
49694/*
49695** Clean up and delete a VDBE after execution.  Return an integer which is
49696** the result code.  Write any error message text into *pzErrMsg.
49697*/
49698SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
49699  int rc = SQLITE_OK;
49700  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
49701    rc = sqlite3VdbeReset(p);
49702    assert( (rc & p->db->errMask)==rc );
49703  }
49704  sqlite3VdbeDelete(p);
49705  return rc;
49706}
49707
49708/*
49709** Call the destructor for each auxdata entry in pVdbeFunc for which
49710** the corresponding bit in mask is clear.  Auxdata entries beyond 31
49711** are always destroyed.  To destroy all auxdata entries, call this
49712** routine with mask==0.
49713*/
49714SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
49715  int i;
49716  for(i=0; i<pVdbeFunc->nAux; i++){
49717    struct AuxData *pAux = &pVdbeFunc->apAux[i];
49718    if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
49719      if( pAux->xDelete ){
49720        pAux->xDelete(pAux->pAux);
49721      }
49722      pAux->pAux = 0;
49723    }
49724  }
49725}
49726
49727/*
49728** Delete an entire VDBE.
49729*/
49730SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
49731  sqlite3 *db;
49732
49733  if( NEVER(p==0) ) return;
49734  db = p->db;
49735  if( p->pPrev ){
49736    p->pPrev->pNext = p->pNext;
49737  }else{
49738    assert( db->pVdbe==p );
49739    db->pVdbe = p->pNext;
49740  }
49741  if( p->pNext ){
49742    p->pNext->pPrev = p->pPrev;
49743  }
49744  releaseMemArray(p->aVar, p->nVar);
49745  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
49746  vdbeFreeOpArray(db, p->aOp, p->nOp);
49747  sqlite3DbFree(db, p->aLabel);
49748  sqlite3DbFree(db, p->aColName);
49749  sqlite3DbFree(db, p->zSql);
49750  p->magic = VDBE_MAGIC_DEAD;
49751  sqlite3DbFree(db, p->pFree);
49752  sqlite3DbFree(db, p);
49753}
49754
49755/*
49756** Make sure the cursor p is ready to read or write the row to which it
49757** was last positioned.  Return an error code if an OOM fault or I/O error
49758** prevents us from positioning the cursor to its correct position.
49759**
49760** If a MoveTo operation is pending on the given cursor, then do that
49761** MoveTo now.  If no move is pending, check to see if the row has been
49762** deleted out from under the cursor and if it has, mark the row as
49763** a NULL row.
49764**
49765** If the cursor is already pointing to the correct row and that row has
49766** not been deleted out from under the cursor, then this routine is a no-op.
49767*/
49768SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
49769  if( p->deferredMoveto ){
49770    int res, rc;
49771#ifdef SQLITE_TEST
49772    extern int sqlite3_search_count;
49773#endif
49774    assert( p->isTable );
49775    rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
49776    if( rc ) return rc;
49777    p->lastRowid = p->movetoTarget;
49778    p->rowidIsValid = ALWAYS(res==0) ?1:0;
49779    if( NEVER(res<0) ){
49780      rc = sqlite3BtreeNext(p->pCursor, &res);
49781      if( rc ) return rc;
49782    }
49783#ifdef SQLITE_TEST
49784    sqlite3_search_count++;
49785#endif
49786    p->deferredMoveto = 0;
49787    p->cacheStatus = CACHE_STALE;
49788  }else if( ALWAYS(p->pCursor) ){
49789    int hasMoved;
49790    int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
49791    if( rc ) return rc;
49792    if( hasMoved ){
49793      p->cacheStatus = CACHE_STALE;
49794      p->nullRow = 1;
49795    }
49796  }
49797  return SQLITE_OK;
49798}
49799
49800/*
49801** The following functions:
49802**
49803** sqlite3VdbeSerialType()
49804** sqlite3VdbeSerialTypeLen()
49805** sqlite3VdbeSerialLen()
49806** sqlite3VdbeSerialPut()
49807** sqlite3VdbeSerialGet()
49808**
49809** encapsulate the code that serializes values for storage in SQLite
49810** data and index records. Each serialized value consists of a
49811** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
49812** integer, stored as a varint.
49813**
49814** In an SQLite index record, the serial type is stored directly before
49815** the blob of data that it corresponds to. In a table record, all serial
49816** types are stored at the start of the record, and the blobs of data at
49817** the end. Hence these functions allow the caller to handle the
49818** serial-type and data blob seperately.
49819**
49820** The following table describes the various storage classes for data:
49821**
49822**   serial type        bytes of data      type
49823**   --------------     ---------------    ---------------
49824**      0                     0            NULL
49825**      1                     1            signed integer
49826**      2                     2            signed integer
49827**      3                     3            signed integer
49828**      4                     4            signed integer
49829**      5                     6            signed integer
49830**      6                     8            signed integer
49831**      7                     8            IEEE float
49832**      8                     0            Integer constant 0
49833**      9                     0            Integer constant 1
49834**     10,11                               reserved for expansion
49835**    N>=12 and even       (N-12)/2        BLOB
49836**    N>=13 and odd        (N-13)/2        text
49837**
49838** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
49839** of SQLite will not understand those serial types.
49840*/
49841
49842/*
49843** Return the serial-type for the value stored in pMem.
49844*/
49845SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
49846  int flags = pMem->flags;
49847  int n;
49848
49849  if( flags&MEM_Null ){
49850    return 0;
49851  }
49852  if( flags&MEM_Int ){
49853    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
49854#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
49855    i64 i = pMem->u.i;
49856    u64 u;
49857    if( file_format>=4 && (i&1)==i ){
49858      return 8+(u32)i;
49859    }
49860    u = i<0 ? -i : i;
49861    if( u<=127 ) return 1;
49862    if( u<=32767 ) return 2;
49863    if( u<=8388607 ) return 3;
49864    if( u<=2147483647 ) return 4;
49865    if( u<=MAX_6BYTE ) return 5;
49866    return 6;
49867  }
49868  if( flags&MEM_Real ){
49869    return 7;
49870  }
49871  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
49872  n = pMem->n;
49873  if( flags & MEM_Zero ){
49874    n += pMem->u.nZero;
49875  }
49876  assert( n>=0 );
49877  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
49878}
49879
49880/*
49881** Return the length of the data corresponding to the supplied serial-type.
49882*/
49883SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
49884  if( serial_type>=12 ){
49885    return (serial_type-12)/2;
49886  }else{
49887    static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
49888    return aSize[serial_type];
49889  }
49890}
49891
49892/*
49893** If we are on an architecture with mixed-endian floating
49894** points (ex: ARM7) then swap the lower 4 bytes with the
49895** upper 4 bytes.  Return the result.
49896**
49897** For most architectures, this is a no-op.
49898**
49899** (later):  It is reported to me that the mixed-endian problem
49900** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
49901** that early versions of GCC stored the two words of a 64-bit
49902** float in the wrong order.  And that error has been propagated
49903** ever since.  The blame is not necessarily with GCC, though.
49904** GCC might have just copying the problem from a prior compiler.
49905** I am also told that newer versions of GCC that follow a different
49906** ABI get the byte order right.
49907**
49908** Developers using SQLite on an ARM7 should compile and run their
49909** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
49910** enabled, some asserts below will ensure that the byte order of
49911** floating point values is correct.
49912**
49913** (2007-08-30)  Frank van Vugt has studied this problem closely
49914** and has send his findings to the SQLite developers.  Frank
49915** writes that some Linux kernels offer floating point hardware
49916** emulation that uses only 32-bit mantissas instead of a full
49917** 48-bits as required by the IEEE standard.  (This is the
49918** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
49919** byte swapping becomes very complicated.  To avoid problems,
49920** the necessary byte swapping is carried out using a 64-bit integer
49921** rather than a 64-bit float.  Frank assures us that the code here
49922** works for him.  We, the developers, have no way to independently
49923** verify this, but Frank seems to know what he is talking about
49924** so we trust him.
49925*/
49926#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
49927static u64 floatSwap(u64 in){
49928  union {
49929    u64 r;
49930    u32 i[2];
49931  } u;
49932  u32 t;
49933
49934  u.r = in;
49935  t = u.i[0];
49936  u.i[0] = u.i[1];
49937  u.i[1] = t;
49938  return u.r;
49939}
49940# define swapMixedEndianFloat(X)  X = floatSwap(X)
49941#else
49942# define swapMixedEndianFloat(X)
49943#endif
49944
49945/*
49946** Write the serialized data blob for the value stored in pMem into
49947** buf. It is assumed that the caller has allocated sufficient space.
49948** Return the number of bytes written.
49949**
49950** nBuf is the amount of space left in buf[].  nBuf must always be
49951** large enough to hold the entire field.  Except, if the field is
49952** a blob with a zero-filled tail, then buf[] might be just the right
49953** size to hold everything except for the zero-filled tail.  If buf[]
49954** is only big enough to hold the non-zero prefix, then only write that
49955** prefix into buf[].  But if buf[] is large enough to hold both the
49956** prefix and the tail then write the prefix and set the tail to all
49957** zeros.
49958**
49959** Return the number of bytes actually written into buf[].  The number
49960** of bytes in the zero-filled tail is included in the return value only
49961** if those bytes were zeroed in buf[].
49962*/
49963SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
49964  u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
49965  u32 len;
49966
49967  /* Integer and Real */
49968  if( serial_type<=7 && serial_type>0 ){
49969    u64 v;
49970    u32 i;
49971    if( serial_type==7 ){
49972      assert( sizeof(v)==sizeof(pMem->r) );
49973      memcpy(&v, &pMem->r, sizeof(v));
49974      swapMixedEndianFloat(v);
49975    }else{
49976      v = pMem->u.i;
49977    }
49978    len = i = sqlite3VdbeSerialTypeLen(serial_type);
49979    assert( len<=(u32)nBuf );
49980    while( i-- ){
49981      buf[i] = (u8)(v&0xFF);
49982      v >>= 8;
49983    }
49984    return len;
49985  }
49986
49987  /* String or blob */
49988  if( serial_type>=12 ){
49989    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
49990             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
49991    assert( pMem->n<=nBuf );
49992    len = pMem->n;
49993    memcpy(buf, pMem->z, len);
49994    if( pMem->flags & MEM_Zero ){
49995      len += pMem->u.nZero;
49996      assert( nBuf>=0 );
49997      if( len > (u32)nBuf ){
49998        len = (u32)nBuf;
49999      }
50000      memset(&buf[pMem->n], 0, len-pMem->n);
50001    }
50002    return len;
50003  }
50004
50005  /* NULL or constants 0 or 1 */
50006  return 0;
50007}
50008
50009/*
50010** Deserialize the data blob pointed to by buf as serial type serial_type
50011** and store the result in pMem.  Return the number of bytes read.
50012*/
50013SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
50014  const unsigned char *buf,     /* Buffer to deserialize from */
50015  u32 serial_type,              /* Serial type to deserialize */
50016  Mem *pMem                     /* Memory cell to write value into */
50017){
50018  switch( serial_type ){
50019    case 10:   /* Reserved for future use */
50020    case 11:   /* Reserved for future use */
50021    case 0: {  /* NULL */
50022      pMem->flags = MEM_Null;
50023      break;
50024    }
50025    case 1: { /* 1-byte signed integer */
50026      pMem->u.i = (signed char)buf[0];
50027      pMem->flags = MEM_Int;
50028      return 1;
50029    }
50030    case 2: { /* 2-byte signed integer */
50031      pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
50032      pMem->flags = MEM_Int;
50033      return 2;
50034    }
50035    case 3: { /* 3-byte signed integer */
50036      pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
50037      pMem->flags = MEM_Int;
50038      return 3;
50039    }
50040    case 4: { /* 4-byte signed integer */
50041      pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
50042      pMem->flags = MEM_Int;
50043      return 4;
50044    }
50045    case 5: { /* 6-byte signed integer */
50046      u64 x = (((signed char)buf[0])<<8) | buf[1];
50047      u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
50048      x = (x<<32) | y;
50049      pMem->u.i = *(i64*)&x;
50050      pMem->flags = MEM_Int;
50051      return 6;
50052    }
50053    case 6:   /* 8-byte signed integer */
50054    case 7: { /* IEEE floating point */
50055      u64 x;
50056      u32 y;
50057#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
50058      /* Verify that integers and floating point values use the same
50059      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
50060      ** defined that 64-bit floating point values really are mixed
50061      ** endian.
50062      */
50063      static const u64 t1 = ((u64)0x3ff00000)<<32;
50064      static const double r1 = 1.0;
50065      u64 t2 = t1;
50066      swapMixedEndianFloat(t2);
50067      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
50068#endif
50069
50070      x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
50071      y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
50072      x = (x<<32) | y;
50073      if( serial_type==6 ){
50074        pMem->u.i = *(i64*)&x;
50075        pMem->flags = MEM_Int;
50076      }else{
50077        assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
50078        swapMixedEndianFloat(x);
50079        memcpy(&pMem->r, &x, sizeof(x));
50080        pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
50081      }
50082      return 8;
50083    }
50084    case 8:    /* Integer 0 */
50085    case 9: {  /* Integer 1 */
50086      pMem->u.i = serial_type-8;
50087      pMem->flags = MEM_Int;
50088      return 0;
50089    }
50090    default: {
50091      u32 len = (serial_type-12)/2;
50092      pMem->z = (char *)buf;
50093      pMem->n = len;
50094      pMem->xDel = 0;
50095      if( serial_type&0x01 ){
50096        pMem->flags = MEM_Str | MEM_Ephem;
50097      }else{
50098        pMem->flags = MEM_Blob | MEM_Ephem;
50099      }
50100      return len;
50101    }
50102  }
50103  return 0;
50104}
50105
50106
50107/*
50108** Given the nKey-byte encoding of a record in pKey[], parse the
50109** record into a UnpackedRecord structure.  Return a pointer to
50110** that structure.
50111**
50112** The calling function might provide szSpace bytes of memory
50113** space at pSpace.  This space can be used to hold the returned
50114** VDbeParsedRecord structure if it is large enough.  If it is
50115** not big enough, space is obtained from sqlite3_malloc().
50116**
50117** The returned structure should be closed by a call to
50118** sqlite3VdbeDeleteUnpackedRecord().
50119*/
50120SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
50121  KeyInfo *pKeyInfo,     /* Information about the record format */
50122  int nKey,              /* Size of the binary record */
50123  const void *pKey,      /* The binary record */
50124  char *pSpace,          /* Unaligned space available to hold the object */
50125  int szSpace            /* Size of pSpace[] in bytes */
50126){
50127  const unsigned char *aKey = (const unsigned char *)pKey;
50128  UnpackedRecord *p;  /* The unpacked record that we will return */
50129  int nByte;          /* Memory space needed to hold p, in bytes */
50130  int d;
50131  u32 idx;
50132  u16 u;              /* Unsigned loop counter */
50133  u32 szHdr;
50134  Mem *pMem;
50135  int nOff;           /* Increase pSpace by this much to 8-byte align it */
50136
50137  /*
50138  ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
50139  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
50140  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
50141  */
50142  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
50143  pSpace += nOff;
50144  szSpace -= nOff;
50145  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
50146  if( nByte>szSpace ){
50147    p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
50148    if( p==0 ) return 0;
50149    p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
50150  }else{
50151    p = (UnpackedRecord*)pSpace;
50152    p->flags = UNPACKED_NEED_DESTROY;
50153  }
50154  p->pKeyInfo = pKeyInfo;
50155  p->nField = pKeyInfo->nField + 1;
50156  p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
50157  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
50158  idx = getVarint32(aKey, szHdr);
50159  d = szHdr;
50160  u = 0;
50161  while( idx<szHdr && u<p->nField && d<=nKey ){
50162    u32 serial_type;
50163
50164    idx += getVarint32(&aKey[idx], serial_type);
50165    pMem->enc = pKeyInfo->enc;
50166    pMem->db = pKeyInfo->db;
50167    pMem->flags = 0;
50168    pMem->zMalloc = 0;
50169    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
50170    pMem++;
50171    u++;
50172  }
50173  assert( u<=pKeyInfo->nField + 1 );
50174  p->nField = u;
50175  return (void*)p;
50176}
50177
50178/*
50179** This routine destroys a UnpackedRecord object.
50180*/
50181SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
50182  int i;
50183  Mem *pMem;
50184
50185  assert( p!=0 );
50186  assert( p->flags & UNPACKED_NEED_DESTROY );
50187  for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
50188    /* The unpacked record is always constructed by the
50189    ** sqlite3VdbeUnpackRecord() function above, which makes all
50190    ** strings and blobs static.  And none of the elements are
50191    ** ever transformed, so there is never anything to delete.
50192    */
50193    if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
50194  }
50195  if( p->flags & UNPACKED_NEED_FREE ){
50196    sqlite3DbFree(p->pKeyInfo->db, p);
50197  }
50198}
50199
50200/*
50201** This function compares the two table rows or index records
50202** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
50203** or positive integer if key1 is less than, equal to or
50204** greater than key2.  The {nKey1, pKey1} key must be a blob
50205** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
50206** key must be a parsed key such as obtained from
50207** sqlite3VdbeParseRecord.
50208**
50209** Key1 and Key2 do not have to contain the same number of fields.
50210** The key with fewer fields is usually compares less than the
50211** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
50212** and the common prefixes are equal, then key1 is less than key2.
50213** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
50214** equal, then the keys are considered to be equal and
50215** the parts beyond the common prefix are ignored.
50216**
50217** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
50218** the header of pKey1 is ignored.  It is assumed that pKey1 is
50219** an index key, and thus ends with a rowid value.  The last byte
50220** of the header will therefore be the serial type of the rowid:
50221** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
50222** The serial type of the final rowid will always be a single byte.
50223** By ignoring this last byte of the header, we force the comparison
50224** to ignore the rowid at the end of key1.
50225*/
50226SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
50227  int nKey1, const void *pKey1, /* Left key */
50228  UnpackedRecord *pPKey2        /* Right key */
50229){
50230  int d1;            /* Offset into aKey[] of next data element */
50231  u32 idx1;          /* Offset into aKey[] of next header element */
50232  u32 szHdr1;        /* Number of bytes in header */
50233  int i = 0;
50234  int nField;
50235  int rc = 0;
50236  const unsigned char *aKey1 = (const unsigned char *)pKey1;
50237  KeyInfo *pKeyInfo;
50238  Mem mem1;
50239
50240  pKeyInfo = pPKey2->pKeyInfo;
50241  mem1.enc = pKeyInfo->enc;
50242  mem1.db = pKeyInfo->db;
50243  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
50244  VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
50245
50246  /* Compilers may complain that mem1.u.i is potentially uninitialized.
50247  ** We could initialize it, as shown here, to silence those complaints.
50248  ** But in fact, mem1.u.i will never actually be used initialized, and doing
50249  ** the unnecessary initialization has a measurable negative performance
50250  ** impact, since this routine is a very high runner.  And so, we choose
50251  ** to ignore the compiler warnings and leave this variable uninitialized.
50252  */
50253  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
50254
50255  idx1 = getVarint32(aKey1, szHdr1);
50256  d1 = szHdr1;
50257  if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
50258    szHdr1--;
50259  }
50260  nField = pKeyInfo->nField;
50261  while( idx1<szHdr1 && i<pPKey2->nField ){
50262    u32 serial_type1;
50263
50264    /* Read the serial types for the next element in each key. */
50265    idx1 += getVarint32( aKey1+idx1, serial_type1 );
50266    if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
50267
50268    /* Extract the values to be compared.
50269    */
50270    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
50271
50272    /* Do the comparison
50273    */
50274    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
50275                           i<nField ? pKeyInfo->aColl[i] : 0);
50276    if( rc!=0 ){
50277      assert( mem1.zMalloc==0 );  /* See comment below */
50278
50279      /* Invert the result if we are using DESC sort order. */
50280      if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
50281        rc = -rc;
50282      }
50283
50284      /* If the PREFIX_SEARCH flag is set and all fields except the final
50285      ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
50286      ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
50287      ** This is used by the OP_IsUnique opcode.
50288      */
50289      if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
50290        assert( idx1==szHdr1 && rc );
50291        assert( mem1.flags & MEM_Int );
50292        pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
50293        pPKey2->rowid = mem1.u.i;
50294      }
50295
50296      return rc;
50297    }
50298    i++;
50299  }
50300
50301  /* No memory allocation is ever used on mem1.  Prove this using
50302  ** the following assert().  If the assert() fails, it indicates a
50303  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
50304  */
50305  assert( mem1.zMalloc==0 );
50306
50307  /* rc==0 here means that one of the keys ran out of fields and
50308  ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
50309  ** flag is set, then break the tie by treating key2 as larger.
50310  ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
50311  ** are considered to be equal.  Otherwise, the longer key is the
50312  ** larger.  As it happens, the pPKey2 will always be the longer
50313  ** if there is a difference.
50314  */
50315  assert( rc==0 );
50316  if( pPKey2->flags & UNPACKED_INCRKEY ){
50317    rc = -1;
50318  }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
50319    /* Leave rc==0 */
50320  }else if( idx1<szHdr1 ){
50321    rc = 1;
50322  }
50323  return rc;
50324}
50325
50326
50327/*
50328** pCur points at an index entry created using the OP_MakeRecord opcode.
50329** Read the rowid (the last field in the record) and store it in *rowid.
50330** Return SQLITE_OK if everything works, or an error code otherwise.
50331**
50332** pCur might be pointing to text obtained from a corrupt database file.
50333** So the content cannot be trusted.  Do appropriate checks on the content.
50334*/
50335SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
50336  i64 nCellKey = 0;
50337  int rc;
50338  u32 szHdr;        /* Size of the header */
50339  u32 typeRowid;    /* Serial type of the rowid */
50340  u32 lenRowid;     /* Size of the rowid */
50341  Mem m, v;
50342
50343  UNUSED_PARAMETER(db);
50344
50345  /* Get the size of the index entry.  Only indices entries of less
50346  ** than 2GiB are support - anything large must be database corruption.
50347  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
50348  ** this code can safely assume that nCellKey is 32-bits
50349  */
50350  assert( sqlite3BtreeCursorIsValid(pCur) );
50351  rc = sqlite3BtreeKeySize(pCur, &nCellKey);
50352  assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
50353  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
50354
50355  /* Read in the complete content of the index entry */
50356  memset(&m, 0, sizeof(m));
50357  rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
50358  if( rc ){
50359    return rc;
50360  }
50361
50362  /* The index entry must begin with a header size */
50363  (void)getVarint32((u8*)m.z, szHdr);
50364  testcase( szHdr==3 );
50365  testcase( szHdr==m.n );
50366  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
50367    goto idx_rowid_corruption;
50368  }
50369
50370  /* The last field of the index should be an integer - the ROWID.
50371  ** Verify that the last entry really is an integer. */
50372  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
50373  testcase( typeRowid==1 );
50374  testcase( typeRowid==2 );
50375  testcase( typeRowid==3 );
50376  testcase( typeRowid==4 );
50377  testcase( typeRowid==5 );
50378  testcase( typeRowid==6 );
50379  testcase( typeRowid==8 );
50380  testcase( typeRowid==9 );
50381  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
50382    goto idx_rowid_corruption;
50383  }
50384  lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
50385  testcase( (u32)m.n==szHdr+lenRowid );
50386  if( unlikely((u32)m.n<szHdr+lenRowid) ){
50387    goto idx_rowid_corruption;
50388  }
50389
50390  /* Fetch the integer off the end of the index record */
50391  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
50392  *rowid = v.u.i;
50393  sqlite3VdbeMemRelease(&m);
50394  return SQLITE_OK;
50395
50396  /* Jump here if database corruption is detected after m has been
50397  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
50398idx_rowid_corruption:
50399  testcase( m.zMalloc!=0 );
50400  sqlite3VdbeMemRelease(&m);
50401  return SQLITE_CORRUPT_BKPT;
50402}
50403
50404/*
50405** Compare the key of the index entry that cursor pC is pointing to against
50406** the key string in pUnpacked.  Write into *pRes a number
50407** that is negative, zero, or positive if pC is less than, equal to,
50408** or greater than pUnpacked.  Return SQLITE_OK on success.
50409**
50410** pUnpacked is either created without a rowid or is truncated so that it
50411** omits the rowid at the end.  The rowid at the end of the index entry
50412** is ignored as well.  Hence, this routine only compares the prefixes
50413** of the keys prior to the final rowid, not the entire key.
50414*/
50415SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
50416  VdbeCursor *pC,             /* The cursor to compare against */
50417  UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
50418  int *res                    /* Write the comparison result here */
50419){
50420  i64 nCellKey = 0;
50421  int rc;
50422  BtCursor *pCur = pC->pCursor;
50423  Mem m;
50424
50425  assert( sqlite3BtreeCursorIsValid(pCur) );
50426  rc = sqlite3BtreeKeySize(pCur, &nCellKey);
50427  assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
50428  /* nCellKey will always be between 0 and 0xffffffff because of the say
50429  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
50430  if( nCellKey<=0 || nCellKey>0x7fffffff ){
50431    *res = 0;
50432    return SQLITE_CORRUPT_BKPT;
50433  }
50434  memset(&m, 0, sizeof(m));
50435  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
50436  if( rc ){
50437    return rc;
50438  }
50439  assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
50440  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
50441  sqlite3VdbeMemRelease(&m);
50442  return SQLITE_OK;
50443}
50444
50445/*
50446** This routine sets the value to be returned by subsequent calls to
50447** sqlite3_changes() on the database handle 'db'.
50448*/
50449SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
50450  assert( sqlite3_mutex_held(db->mutex) );
50451  db->nChange = nChange;
50452  db->nTotalChange += nChange;
50453}
50454
50455/*
50456** Set a flag in the vdbe to update the change counter when it is finalised
50457** or reset.
50458*/
50459SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
50460  v->changeCntOn = 1;
50461}
50462
50463/*
50464** Mark every prepared statement associated with a database connection
50465** as expired.
50466**
50467** An expired statement means that recompilation of the statement is
50468** recommend.  Statements expire when things happen that make their
50469** programs obsolete.  Removing user-defined functions or collating
50470** sequences, or changing an authorization function are the types of
50471** things that make prepared statements obsolete.
50472*/
50473SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
50474  Vdbe *p;
50475  for(p = db->pVdbe; p; p=p->pNext){
50476    p->expired = 1;
50477  }
50478}
50479
50480/*
50481** Return the database associated with the Vdbe.
50482*/
50483SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
50484  return v->db;
50485}
50486
50487/*
50488** Return a pointer to an sqlite3_value structure containing the value bound
50489** parameter iVar of VM v. Except, if the value is an SQL NULL, return
50490** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
50491** constants) to the value before returning it.
50492**
50493** The returned value must be freed by the caller using sqlite3ValueFree().
50494*/
50495SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
50496  assert( iVar>0 );
50497  if( v ){
50498    Mem *pMem = &v->aVar[iVar-1];
50499    if( 0==(pMem->flags & MEM_Null) ){
50500      sqlite3_value *pRet = sqlite3ValueNew(v->db);
50501      if( pRet ){
50502        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
50503        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
50504        sqlite3VdbeMemStoreType((Mem *)pRet);
50505      }
50506      return pRet;
50507    }
50508  }
50509  return 0;
50510}
50511
50512/*
50513** Configure SQL variable iVar so that binding a new value to it signals
50514** to sqlite3_reoptimize() that re-preparing the statement may result
50515** in a better query plan.
50516*/
50517SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
50518  assert( iVar>0 );
50519  if( iVar>32 ){
50520    v->expmask = 0xffffffff;
50521  }else{
50522    v->expmask |= ((u32)1 << (iVar-1));
50523  }
50524}
50525
50526/************** End of vdbeaux.c *********************************************/
50527/************** Begin file vdbeapi.c *****************************************/
50528/*
50529** 2004 May 26
50530**
50531** The author disclaims copyright to this source code.  In place of
50532** a legal notice, here is a blessing:
50533**
50534**    May you do good and not evil.
50535**    May you find forgiveness for yourself and forgive others.
50536**    May you share freely, never taking more than you give.
50537**
50538*************************************************************************
50539**
50540** This file contains code use to implement APIs that are part of the
50541** VDBE.
50542*/
50543
50544#ifndef SQLITE_OMIT_DEPRECATED
50545/*
50546** Return TRUE (non-zero) of the statement supplied as an argument needs
50547** to be recompiled.  A statement needs to be recompiled whenever the
50548** execution environment changes in a way that would alter the program
50549** that sqlite3_prepare() generates.  For example, if new functions or
50550** collating sequences are registered or if an authorizer function is
50551** added or changed.
50552*/
50553SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
50554  Vdbe *p = (Vdbe*)pStmt;
50555  return p==0 || p->expired;
50556}
50557#endif
50558
50559/*
50560** Check on a Vdbe to make sure it has not been finalized.  Log
50561** an error and return true if it has been finalized (or is otherwise
50562** invalid).  Return false if it is ok.
50563*/
50564static int vdbeSafety(Vdbe *p){
50565  if( p->db==0 ){
50566    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
50567    return 1;
50568  }else{
50569    return 0;
50570  }
50571}
50572static int vdbeSafetyNotNull(Vdbe *p){
50573  if( p==0 ){
50574    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
50575    return 1;
50576  }else{
50577    return vdbeSafety(p);
50578  }
50579}
50580
50581/*
50582** The following routine destroys a virtual machine that is created by
50583** the sqlite3_compile() routine. The integer returned is an SQLITE_
50584** success/failure code that describes the result of executing the virtual
50585** machine.
50586**
50587** This routine sets the error code and string returned by
50588** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
50589*/
50590SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
50591  int rc;
50592  if( pStmt==0 ){
50593    rc = SQLITE_OK;
50594  }else{
50595    Vdbe *v = (Vdbe*)pStmt;
50596    sqlite3 *db = v->db;
50597#if SQLITE_THREADSAFE
50598    sqlite3_mutex *mutex;
50599#endif
50600    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
50601#if SQLITE_THREADSAFE
50602    mutex = v->db->mutex;
50603#endif
50604    sqlite3_mutex_enter(mutex);
50605    rc = sqlite3VdbeFinalize(v);
50606    rc = sqlite3ApiExit(db, rc);
50607    sqlite3_mutex_leave(mutex);
50608  }
50609  return rc;
50610}
50611
50612/*
50613** Terminate the current execution of an SQL statement and reset it
50614** back to its starting state so that it can be reused. A success code from
50615** the prior execution is returned.
50616**
50617** This routine sets the error code and string returned by
50618** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
50619*/
50620SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
50621  int rc;
50622  if( pStmt==0 ){
50623    rc = SQLITE_OK;
50624  }else{
50625    Vdbe *v = (Vdbe*)pStmt;
50626    sqlite3_mutex_enter(v->db->mutex);
50627    rc = sqlite3VdbeReset(v);
50628    sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
50629    assert( (rc & (v->db->errMask))==rc );
50630    rc = sqlite3ApiExit(v->db, rc);
50631    sqlite3_mutex_leave(v->db->mutex);
50632  }
50633  return rc;
50634}
50635
50636/*
50637** Set all the parameters in the compiled SQL statement to NULL.
50638*/
50639SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
50640  int i;
50641  int rc = SQLITE_OK;
50642  Vdbe *p = (Vdbe*)pStmt;
50643#if SQLITE_THREADSAFE
50644  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
50645#endif
50646  sqlite3_mutex_enter(mutex);
50647  for(i=0; i<p->nVar; i++){
50648    sqlite3VdbeMemRelease(&p->aVar[i]);
50649    p->aVar[i].flags = MEM_Null;
50650  }
50651  if( p->isPrepareV2 && p->expmask ){
50652    p->expired = 1;
50653  }
50654  sqlite3_mutex_leave(mutex);
50655  return rc;
50656}
50657
50658
50659/**************************** sqlite3_value_  *******************************
50660** The following routines extract information from a Mem or sqlite3_value
50661** structure.
50662*/
50663SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
50664  Mem *p = (Mem*)pVal;
50665  if( p->flags & (MEM_Blob|MEM_Str) ){
50666    sqlite3VdbeMemExpandBlob(p);
50667    p->flags &= ~MEM_Str;
50668    p->flags |= MEM_Blob;
50669    return p->z;
50670  }else{
50671    return sqlite3_value_text(pVal);
50672  }
50673}
50674SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
50675  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
50676}
50677SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
50678  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
50679}
50680SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
50681  return sqlite3VdbeRealValue((Mem*)pVal);
50682}
50683SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
50684  return (int)sqlite3VdbeIntValue((Mem*)pVal);
50685}
50686SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
50687  return sqlite3VdbeIntValue((Mem*)pVal);
50688}
50689SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
50690  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
50691}
50692#ifndef SQLITE_OMIT_UTF16
50693SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
50694  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
50695}
50696SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
50697  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
50698}
50699SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
50700  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
50701}
50702#endif /* SQLITE_OMIT_UTF16 */
50703SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
50704  return pVal->type;
50705}
50706
50707/**************************** sqlite3_result_  *******************************
50708** The following routines are used by user-defined functions to specify
50709** the function result.
50710**
50711** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
50712** result as a string or blob but if the string or blob is too large, it
50713** then sets the error code to SQLITE_TOOBIG
50714*/
50715static void setResultStrOrError(
50716  sqlite3_context *pCtx,  /* Function context */
50717  const char *z,          /* String pointer */
50718  int n,                  /* Bytes in string, or negative */
50719  u8 enc,                 /* Encoding of z.  0 for BLOBs */
50720  void (*xDel)(void*)     /* Destructor function */
50721){
50722  if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
50723    sqlite3_result_error_toobig(pCtx);
50724  }
50725}
50726SQLITE_API void sqlite3_result_blob(
50727  sqlite3_context *pCtx,
50728  const void *z,
50729  int n,
50730  void (*xDel)(void *)
50731){
50732  assert( n>=0 );
50733  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50734  setResultStrOrError(pCtx, z, n, 0, xDel);
50735}
50736SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
50737  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50738  sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
50739}
50740SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
50741  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50742  pCtx->isError = SQLITE_ERROR;
50743  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
50744}
50745#ifndef SQLITE_OMIT_UTF16
50746SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
50747  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50748  pCtx->isError = SQLITE_ERROR;
50749  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
50750}
50751#endif
50752SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
50753  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50754  sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
50755}
50756SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
50757  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50758  sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
50759}
50760SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
50761  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50762  sqlite3VdbeMemSetNull(&pCtx->s);
50763}
50764SQLITE_API void sqlite3_result_text(
50765  sqlite3_context *pCtx,
50766  const char *z,
50767  int n,
50768  void (*xDel)(void *)
50769){
50770  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50771  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
50772}
50773#ifndef SQLITE_OMIT_UTF16
50774SQLITE_API void sqlite3_result_text16(
50775  sqlite3_context *pCtx,
50776  const void *z,
50777  int n,
50778  void (*xDel)(void *)
50779){
50780  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50781  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
50782}
50783SQLITE_API void sqlite3_result_text16be(
50784  sqlite3_context *pCtx,
50785  const void *z,
50786  int n,
50787  void (*xDel)(void *)
50788){
50789  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50790  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
50791}
50792SQLITE_API void sqlite3_result_text16le(
50793  sqlite3_context *pCtx,
50794  const void *z,
50795  int n,
50796  void (*xDel)(void *)
50797){
50798  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50799  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
50800}
50801#endif /* SQLITE_OMIT_UTF16 */
50802SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
50803  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50804  sqlite3VdbeMemCopy(&pCtx->s, pValue);
50805}
50806SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
50807  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50808  sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
50809}
50810SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
50811  pCtx->isError = errCode;
50812  if( pCtx->s.flags & MEM_Null ){
50813    sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
50814                         SQLITE_UTF8, SQLITE_STATIC);
50815  }
50816}
50817
50818/* Force an SQLITE_TOOBIG error. */
50819SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
50820  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50821  pCtx->isError = SQLITE_TOOBIG;
50822  sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
50823                       SQLITE_UTF8, SQLITE_STATIC);
50824}
50825
50826/* An SQLITE_NOMEM error. */
50827SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
50828  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50829  sqlite3VdbeMemSetNull(&pCtx->s);
50830  pCtx->isError = SQLITE_NOMEM;
50831  pCtx->s.db->mallocFailed = 1;
50832}
50833
50834/*
50835** Execute the statement pStmt, either until a row of data is ready, the
50836** statement is completely executed or an error occurs.
50837**
50838** This routine implements the bulk of the logic behind the sqlite_step()
50839** API.  The only thing omitted is the automatic recompile if a
50840** schema change has occurred.  That detail is handled by the
50841** outer sqlite3_step() wrapper procedure.
50842*/
50843static int sqlite3Step(Vdbe *p){
50844  sqlite3 *db;
50845  int rc;
50846
50847  assert(p);
50848  if( p->magic!=VDBE_MAGIC_RUN ){
50849    sqlite3_log(SQLITE_MISUSE,
50850          "attempt to step a halted statement: [%s]", p->zSql);
50851    return SQLITE_MISUSE_BKPT;
50852  }
50853
50854  /* Assert that malloc() has not failed */
50855  db = p->db;
50856  if( db->mallocFailed ){
50857    return SQLITE_NOMEM;
50858  }
50859
50860  if( p->pc<=0 && p->expired ){
50861    if( p->rc==SQLITE_OK ){
50862      p->rc = SQLITE_SCHEMA;
50863    }
50864    rc = SQLITE_ERROR;
50865    goto end_of_step;
50866  }
50867  if( p->pc<0 ){
50868    /* If there are no other statements currently running, then
50869    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
50870    ** from interrupting a statement that has not yet started.
50871    */
50872    if( db->activeVdbeCnt==0 ){
50873      db->u1.isInterrupted = 0;
50874    }
50875
50876    assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
50877
50878#ifndef SQLITE_OMIT_TRACE
50879    if( db->xProfile && !db->init.busy ){
50880      double rNow;
50881      sqlite3OsCurrentTime(db->pVfs, &rNow);
50882      p->startTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
50883    }
50884#endif
50885
50886    db->activeVdbeCnt++;
50887    if( p->readOnly==0 ) db->writeVdbeCnt++;
50888    p->pc = 0;
50889  }
50890#ifndef SQLITE_OMIT_EXPLAIN
50891  if( p->explain ){
50892    rc = sqlite3VdbeList(p);
50893  }else
50894#endif /* SQLITE_OMIT_EXPLAIN */
50895  {
50896    rc = sqlite3VdbeExec(p);
50897  }
50898
50899#ifndef SQLITE_OMIT_TRACE
50900  /* Invoke the profile callback if there is one
50901  */
50902  if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
50903    double rNow;
50904    u64 elapseTime;
50905
50906    sqlite3OsCurrentTime(db->pVfs, &rNow);
50907    elapseTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
50908    elapseTime -= p->startTime;
50909    db->xProfile(db->pProfileArg, p->zSql, elapseTime);
50910  }
50911#endif
50912
50913  db->errCode = rc;
50914  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
50915    p->rc = SQLITE_NOMEM;
50916  }
50917end_of_step:
50918  /* At this point local variable rc holds the value that should be
50919  ** returned if this statement was compiled using the legacy
50920  ** sqlite3_prepare() interface. According to the docs, this can only
50921  ** be one of the values in the first assert() below. Variable p->rc
50922  ** contains the value that would be returned if sqlite3_finalize()
50923  ** were called on statement p.
50924  */
50925  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
50926       || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
50927  );
50928  assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
50929  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
50930    /* If this statement was prepared using sqlite3_prepare_v2(), and an
50931    ** error has occured, then return the error code in p->rc to the
50932    ** caller. Set the error code in the database handle to the same value.
50933    */
50934    rc = db->errCode = p->rc;
50935  }
50936  return (rc&db->errMask);
50937}
50938
50939/*
50940** This is the top-level implementation of sqlite3_step().  Call
50941** sqlite3Step() to do most of the work.  If a schema error occurs,
50942** call sqlite3Reprepare() and try again.
50943*/
50944SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
50945  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
50946  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
50947  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
50948  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
50949  sqlite3 *db;             /* The database connection */
50950
50951  if( vdbeSafetyNotNull(v) ){
50952    return SQLITE_MISUSE_BKPT;
50953  }
50954  db = v->db;
50955  sqlite3_mutex_enter(db->mutex);
50956  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
50957         && cnt++ < 5
50958         && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
50959    sqlite3_reset(pStmt);
50960    v->expired = 0;
50961  }
50962  if( rc2!=SQLITE_OK && v->isPrepareV2 && db->pErr ){
50963    /* This case occurs after failing to recompile an sql statement.
50964    ** The error message from the SQL compiler has already been loaded
50965    ** into the database handle. This block copies the error message
50966    ** from the database handle into the statement and sets the statement
50967    ** program counter to 0 to ensure that when the statement is
50968    ** finalized or reset the parser error message is available via
50969    ** sqlite3_errmsg() and sqlite3_errcode().
50970    */
50971    const char *zErr = (const char *)sqlite3_value_text(db->pErr);
50972    sqlite3DbFree(db, v->zErrMsg);
50973    if( !db->mallocFailed ){
50974      v->zErrMsg = sqlite3DbStrDup(db, zErr);
50975      v->rc = rc2;
50976    } else {
50977      v->zErrMsg = 0;
50978      v->rc = rc = SQLITE_NOMEM;
50979    }
50980  }
50981  rc = sqlite3ApiExit(db, rc);
50982  sqlite3_mutex_leave(db->mutex);
50983  return rc;
50984}
50985
50986/*
50987** Extract the user data from a sqlite3_context structure and return a
50988** pointer to it.
50989*/
50990SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
50991  assert( p && p->pFunc );
50992  return p->pFunc->pUserData;
50993}
50994
50995/*
50996** Extract the user data from a sqlite3_context structure and return a
50997** pointer to it.
50998*/
50999SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
51000  assert( p && p->pFunc );
51001  return p->s.db;
51002}
51003
51004/*
51005** The following is the implementation of an SQL function that always
51006** fails with an error message stating that the function is used in the
51007** wrong context.  The sqlite3_overload_function() API might construct
51008** SQL function that use this routine so that the functions will exist
51009** for name resolution but are actually overloaded by the xFindFunction
51010** method of virtual tables.
51011*/
51012SQLITE_PRIVATE void sqlite3InvalidFunction(
51013  sqlite3_context *context,  /* The function calling context */
51014  int NotUsed,               /* Number of arguments to the function */
51015  sqlite3_value **NotUsed2   /* Value of each argument */
51016){
51017  const char *zName = context->pFunc->zName;
51018  char *zErr;
51019  UNUSED_PARAMETER2(NotUsed, NotUsed2);
51020  zErr = sqlite3_mprintf(
51021      "unable to use function %s in the requested context", zName);
51022  sqlite3_result_error(context, zErr, -1);
51023  sqlite3_free(zErr);
51024}
51025
51026/*
51027** Allocate or return the aggregate context for a user function.  A new
51028** context is allocated on the first call.  Subsequent calls return the
51029** same context that was returned on prior calls.
51030*/
51031SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
51032  Mem *pMem;
51033  assert( p && p->pFunc && p->pFunc->xStep );
51034  assert( sqlite3_mutex_held(p->s.db->mutex) );
51035  pMem = p->pMem;
51036  testcase( nByte<0 );
51037  if( (pMem->flags & MEM_Agg)==0 ){
51038    if( nByte<=0 ){
51039      sqlite3VdbeMemReleaseExternal(pMem);
51040      pMem->flags = MEM_Null;
51041      pMem->z = 0;
51042    }else{
51043      sqlite3VdbeMemGrow(pMem, nByte, 0);
51044      pMem->flags = MEM_Agg;
51045      pMem->u.pDef = p->pFunc;
51046      if( pMem->z ){
51047        memset(pMem->z, 0, nByte);
51048      }
51049    }
51050  }
51051  return (void*)pMem->z;
51052}
51053
51054/*
51055** Return the auxilary data pointer, if any, for the iArg'th argument to
51056** the user-function defined by pCtx.
51057*/
51058SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
51059  VdbeFunc *pVdbeFunc;
51060
51061  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51062  pVdbeFunc = pCtx->pVdbeFunc;
51063  if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
51064    return 0;
51065  }
51066  return pVdbeFunc->apAux[iArg].pAux;
51067}
51068
51069/*
51070** Set the auxilary data pointer and delete function, for the iArg'th
51071** argument to the user-function defined by pCtx. Any previous value is
51072** deleted by calling the delete function specified when it was set.
51073*/
51074SQLITE_API void sqlite3_set_auxdata(
51075  sqlite3_context *pCtx,
51076  int iArg,
51077  void *pAux,
51078  void (*xDelete)(void*)
51079){
51080  struct AuxData *pAuxData;
51081  VdbeFunc *pVdbeFunc;
51082  if( iArg<0 ) goto failed;
51083
51084  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51085  pVdbeFunc = pCtx->pVdbeFunc;
51086  if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
51087    int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
51088    int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
51089    pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
51090    if( !pVdbeFunc ){
51091      goto failed;
51092    }
51093    pCtx->pVdbeFunc = pVdbeFunc;
51094    memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
51095    pVdbeFunc->nAux = iArg+1;
51096    pVdbeFunc->pFunc = pCtx->pFunc;
51097  }
51098
51099  pAuxData = &pVdbeFunc->apAux[iArg];
51100  if( pAuxData->pAux && pAuxData->xDelete ){
51101    pAuxData->xDelete(pAuxData->pAux);
51102  }
51103  pAuxData->pAux = pAux;
51104  pAuxData->xDelete = xDelete;
51105  return;
51106
51107failed:
51108  if( xDelete ){
51109    xDelete(pAux);
51110  }
51111}
51112
51113#ifndef SQLITE_OMIT_DEPRECATED
51114/*
51115** Return the number of times the Step function of a aggregate has been
51116** called.
51117**
51118** This function is deprecated.  Do not use it for new code.  It is
51119** provide only to avoid breaking legacy code.  New aggregate function
51120** implementations should keep their own counts within their aggregate
51121** context.
51122*/
51123SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
51124  assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
51125  return p->pMem->n;
51126}
51127#endif
51128
51129/*
51130** Return the number of columns in the result set for the statement pStmt.
51131*/
51132SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
51133  Vdbe *pVm = (Vdbe *)pStmt;
51134  return pVm ? pVm->nResColumn : 0;
51135}
51136
51137/*
51138** Return the number of values available from the current row of the
51139** currently executing statement pStmt.
51140*/
51141SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
51142  Vdbe *pVm = (Vdbe *)pStmt;
51143  if( pVm==0 || pVm->pResultSet==0 ) return 0;
51144  return pVm->nResColumn;
51145}
51146
51147
51148/*
51149** Check to see if column iCol of the given statement is valid.  If
51150** it is, return a pointer to the Mem for the value of that column.
51151** If iCol is not valid, return a pointer to a Mem which has a value
51152** of NULL.
51153*/
51154static Mem *columnMem(sqlite3_stmt *pStmt, int i){
51155  Vdbe *pVm;
51156  int vals;
51157  Mem *pOut;
51158
51159  pVm = (Vdbe *)pStmt;
51160  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
51161    sqlite3_mutex_enter(pVm->db->mutex);
51162    vals = sqlite3_data_count(pStmt);
51163    pOut = &pVm->pResultSet[i];
51164  }else{
51165    /* If the value passed as the second argument is out of range, return
51166    ** a pointer to the following static Mem object which contains the
51167    ** value SQL NULL. Even though the Mem structure contains an element
51168    ** of type i64, on certain architecture (x86) with certain compiler
51169    ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
51170    ** instead of an 8-byte one. This all works fine, except that when
51171    ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
51172    ** that a Mem structure is located on an 8-byte boundary. To prevent
51173    ** this assert() from failing, when building with SQLITE_DEBUG defined
51174    ** using gcc, force nullMem to be 8-byte aligned using the magical
51175    ** __attribute__((aligned(8))) macro.  */
51176    static const Mem nullMem
51177#if defined(SQLITE_DEBUG) && defined(__GNUC__)
51178      __attribute__((aligned(8)))
51179#endif
51180      = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
51181
51182    if( pVm && ALWAYS(pVm->db) ){
51183      sqlite3_mutex_enter(pVm->db->mutex);
51184      sqlite3Error(pVm->db, SQLITE_RANGE, 0);
51185    }
51186    pOut = (Mem*)&nullMem;
51187  }
51188  return pOut;
51189}
51190
51191/*
51192** This function is called after invoking an sqlite3_value_XXX function on a
51193** column value (i.e. a value returned by evaluating an SQL expression in the
51194** select list of a SELECT statement) that may cause a malloc() failure. If
51195** malloc() has failed, the threads mallocFailed flag is cleared and the result
51196** code of statement pStmt set to SQLITE_NOMEM.
51197**
51198** Specifically, this is called from within:
51199**
51200**     sqlite3_column_int()
51201**     sqlite3_column_int64()
51202**     sqlite3_column_text()
51203**     sqlite3_column_text16()
51204**     sqlite3_column_real()
51205**     sqlite3_column_bytes()
51206**     sqlite3_column_bytes16()
51207**
51208** But not for sqlite3_column_blob(), which never calls malloc().
51209*/
51210static void columnMallocFailure(sqlite3_stmt *pStmt)
51211{
51212  /* If malloc() failed during an encoding conversion within an
51213  ** sqlite3_column_XXX API, then set the return code of the statement to
51214  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
51215  ** and _finalize() will return NOMEM.
51216  */
51217  Vdbe *p = (Vdbe *)pStmt;
51218  if( p ){
51219    p->rc = sqlite3ApiExit(p->db, p->rc);
51220    sqlite3_mutex_leave(p->db->mutex);
51221  }
51222}
51223
51224/**************************** sqlite3_column_  *******************************
51225** The following routines are used to access elements of the current row
51226** in the result set.
51227*/
51228SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
51229  const void *val;
51230  val = sqlite3_value_blob( columnMem(pStmt,i) );
51231  /* Even though there is no encoding conversion, value_blob() might
51232  ** need to call malloc() to expand the result of a zeroblob()
51233  ** expression.
51234  */
51235  columnMallocFailure(pStmt);
51236  return val;
51237}
51238SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
51239  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
51240  columnMallocFailure(pStmt);
51241  return val;
51242}
51243SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
51244  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
51245  columnMallocFailure(pStmt);
51246  return val;
51247}
51248SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
51249  double val = sqlite3_value_double( columnMem(pStmt,i) );
51250  columnMallocFailure(pStmt);
51251  return val;
51252}
51253SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
51254  int val = sqlite3_value_int( columnMem(pStmt,i) );
51255  columnMallocFailure(pStmt);
51256  return val;
51257}
51258SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
51259  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
51260  columnMallocFailure(pStmt);
51261  return val;
51262}
51263SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
51264  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
51265  columnMallocFailure(pStmt);
51266  return val;
51267}
51268SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
51269  Mem *pOut = columnMem(pStmt, i);
51270  if( pOut->flags&MEM_Static ){
51271    pOut->flags &= ~MEM_Static;
51272    pOut->flags |= MEM_Ephem;
51273  }
51274  columnMallocFailure(pStmt);
51275  return (sqlite3_value *)pOut;
51276}
51277#ifndef SQLITE_OMIT_UTF16
51278SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
51279  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
51280  columnMallocFailure(pStmt);
51281  return val;
51282}
51283#endif /* SQLITE_OMIT_UTF16 */
51284SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
51285  int iType = sqlite3_value_type( columnMem(pStmt,i) );
51286  columnMallocFailure(pStmt);
51287  return iType;
51288}
51289
51290/* The following function is experimental and subject to change or
51291** removal */
51292/*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
51293**  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
51294**}
51295*/
51296
51297/*
51298** Convert the N-th element of pStmt->pColName[] into a string using
51299** xFunc() then return that string.  If N is out of range, return 0.
51300**
51301** There are up to 5 names for each column.  useType determines which
51302** name is returned.  Here are the names:
51303**
51304**    0      The column name as it should be displayed for output
51305**    1      The datatype name for the column
51306**    2      The name of the database that the column derives from
51307**    3      The name of the table that the column derives from
51308**    4      The name of the table column that the result column derives from
51309**
51310** If the result is not a simple column reference (if it is an expression
51311** or a constant) then useTypes 2, 3, and 4 return NULL.
51312*/
51313static const void *columnName(
51314  sqlite3_stmt *pStmt,
51315  int N,
51316  const void *(*xFunc)(Mem*),
51317  int useType
51318){
51319  const void *ret = 0;
51320  Vdbe *p = (Vdbe *)pStmt;
51321  int n;
51322  sqlite3 *db = p->db;
51323
51324  assert( db!=0 );
51325  n = sqlite3_column_count(pStmt);
51326  if( N<n && N>=0 ){
51327    N += useType*n;
51328    sqlite3_mutex_enter(db->mutex);
51329    assert( db->mallocFailed==0 );
51330    ret = xFunc(&p->aColName[N]);
51331     /* A malloc may have failed inside of the xFunc() call. If this
51332    ** is the case, clear the mallocFailed flag and return NULL.
51333    */
51334    if( db->mallocFailed ){
51335      db->mallocFailed = 0;
51336      ret = 0;
51337    }
51338    sqlite3_mutex_leave(db->mutex);
51339  }
51340  return ret;
51341}
51342
51343/*
51344** Return the name of the Nth column of the result set returned by SQL
51345** statement pStmt.
51346*/
51347SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
51348  return columnName(
51349      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
51350}
51351#ifndef SQLITE_OMIT_UTF16
51352SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
51353  return columnName(
51354      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
51355}
51356#endif
51357
51358/*
51359** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
51360** not define OMIT_DECLTYPE.
51361*/
51362#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
51363# error "Must not define both SQLITE_OMIT_DECLTYPE \
51364         and SQLITE_ENABLE_COLUMN_METADATA"
51365#endif
51366
51367#ifndef SQLITE_OMIT_DECLTYPE
51368/*
51369** Return the column declaration type (if applicable) of the 'i'th column
51370** of the result set of SQL statement pStmt.
51371*/
51372SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
51373  return columnName(
51374      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
51375}
51376#ifndef SQLITE_OMIT_UTF16
51377SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
51378  return columnName(
51379      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
51380}
51381#endif /* SQLITE_OMIT_UTF16 */
51382#endif /* SQLITE_OMIT_DECLTYPE */
51383
51384#ifdef SQLITE_ENABLE_COLUMN_METADATA
51385/*
51386** Return the name of the database from which a result column derives.
51387** NULL is returned if the result column is an expression or constant or
51388** anything else which is not an unabiguous reference to a database column.
51389*/
51390SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
51391  return columnName(
51392      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
51393}
51394#ifndef SQLITE_OMIT_UTF16
51395SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
51396  return columnName(
51397      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
51398}
51399#endif /* SQLITE_OMIT_UTF16 */
51400
51401/*
51402** Return the name of the table from which a result column derives.
51403** NULL is returned if the result column is an expression or constant or
51404** anything else which is not an unabiguous reference to a database column.
51405*/
51406SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
51407  return columnName(
51408      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
51409}
51410#ifndef SQLITE_OMIT_UTF16
51411SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
51412  return columnName(
51413      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
51414}
51415#endif /* SQLITE_OMIT_UTF16 */
51416
51417/*
51418** Return the name of the table column from which a result column derives.
51419** NULL is returned if the result column is an expression or constant or
51420** anything else which is not an unabiguous reference to a database column.
51421*/
51422SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
51423  return columnName(
51424      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
51425}
51426#ifndef SQLITE_OMIT_UTF16
51427SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
51428  return columnName(
51429      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
51430}
51431#endif /* SQLITE_OMIT_UTF16 */
51432#endif /* SQLITE_ENABLE_COLUMN_METADATA */
51433
51434
51435/******************************* sqlite3_bind_  ***************************
51436**
51437** Routines used to attach values to wildcards in a compiled SQL statement.
51438*/
51439/*
51440** Unbind the value bound to variable i in virtual machine p. This is the
51441** the same as binding a NULL value to the column. If the "i" parameter is
51442** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
51443**
51444** A successful evaluation of this routine acquires the mutex on p.
51445** the mutex is released if any kind of error occurs.
51446**
51447** The error code stored in database p->db is overwritten with the return
51448** value in any case.
51449*/
51450static int vdbeUnbind(Vdbe *p, int i){
51451  Mem *pVar;
51452  if( vdbeSafetyNotNull(p) ){
51453    return SQLITE_MISUSE_BKPT;
51454  }
51455  sqlite3_mutex_enter(p->db->mutex);
51456  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
51457    sqlite3Error(p->db, SQLITE_MISUSE, 0);
51458    sqlite3_mutex_leave(p->db->mutex);
51459    sqlite3_log(SQLITE_MISUSE,
51460        "bind on a busy prepared statement: [%s]", p->zSql);
51461    return SQLITE_MISUSE_BKPT;
51462  }
51463  if( i<1 || i>p->nVar ){
51464    sqlite3Error(p->db, SQLITE_RANGE, 0);
51465    sqlite3_mutex_leave(p->db->mutex);
51466    return SQLITE_RANGE;
51467  }
51468  i--;
51469  pVar = &p->aVar[i];
51470  sqlite3VdbeMemRelease(pVar);
51471  pVar->flags = MEM_Null;
51472  sqlite3Error(p->db, SQLITE_OK, 0);
51473
51474  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
51475  ** binding a new value to this variable invalidates the current query plan.
51476  */
51477  if( p->isPrepareV2 &&
51478     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
51479  ){
51480    p->expired = 1;
51481  }
51482  return SQLITE_OK;
51483}
51484
51485/*
51486** Bind a text or BLOB value.
51487*/
51488static int bindText(
51489  sqlite3_stmt *pStmt,   /* The statement to bind against */
51490  int i,                 /* Index of the parameter to bind */
51491  const void *zData,     /* Pointer to the data to be bound */
51492  int nData,             /* Number of bytes of data to be bound */
51493  void (*xDel)(void*),   /* Destructor for the data */
51494  u8 encoding            /* Encoding for the data */
51495){
51496  Vdbe *p = (Vdbe *)pStmt;
51497  Mem *pVar;
51498  int rc;
51499
51500  rc = vdbeUnbind(p, i);
51501  if( rc==SQLITE_OK ){
51502    if( zData!=0 ){
51503      pVar = &p->aVar[i-1];
51504      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
51505      if( rc==SQLITE_OK && encoding!=0 ){
51506        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
51507      }
51508      sqlite3Error(p->db, rc, 0);
51509      rc = sqlite3ApiExit(p->db, rc);
51510    }
51511    sqlite3_mutex_leave(p->db->mutex);
51512  }
51513  return rc;
51514}
51515
51516
51517/*
51518** Bind a blob value to an SQL statement variable.
51519*/
51520SQLITE_API int sqlite3_bind_blob(
51521  sqlite3_stmt *pStmt,
51522  int i,
51523  const void *zData,
51524  int nData,
51525  void (*xDel)(void*)
51526){
51527  return bindText(pStmt, i, zData, nData, xDel, 0);
51528}
51529SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
51530  int rc;
51531  Vdbe *p = (Vdbe *)pStmt;
51532  rc = vdbeUnbind(p, i);
51533  if( rc==SQLITE_OK ){
51534    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
51535    sqlite3_mutex_leave(p->db->mutex);
51536  }
51537  return rc;
51538}
51539SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
51540  return sqlite3_bind_int64(p, i, (i64)iValue);
51541}
51542SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
51543  int rc;
51544  Vdbe *p = (Vdbe *)pStmt;
51545  rc = vdbeUnbind(p, i);
51546  if( rc==SQLITE_OK ){
51547    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
51548    sqlite3_mutex_leave(p->db->mutex);
51549  }
51550  return rc;
51551}
51552SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
51553  int rc;
51554  Vdbe *p = (Vdbe*)pStmt;
51555  rc = vdbeUnbind(p, i);
51556  if( rc==SQLITE_OK ){
51557    sqlite3_mutex_leave(p->db->mutex);
51558  }
51559  return rc;
51560}
51561SQLITE_API int sqlite3_bind_text(
51562  sqlite3_stmt *pStmt,
51563  int i,
51564  const char *zData,
51565  int nData,
51566  void (*xDel)(void*)
51567){
51568  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
51569}
51570#ifndef SQLITE_OMIT_UTF16
51571SQLITE_API int sqlite3_bind_text16(
51572  sqlite3_stmt *pStmt,
51573  int i,
51574  const void *zData,
51575  int nData,
51576  void (*xDel)(void*)
51577){
51578  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
51579}
51580#endif /* SQLITE_OMIT_UTF16 */
51581SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
51582  int rc;
51583  switch( pValue->type ){
51584    case SQLITE_INTEGER: {
51585      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
51586      break;
51587    }
51588    case SQLITE_FLOAT: {
51589      rc = sqlite3_bind_double(pStmt, i, pValue->r);
51590      break;
51591    }
51592    case SQLITE_BLOB: {
51593      if( pValue->flags & MEM_Zero ){
51594        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
51595      }else{
51596        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
51597      }
51598      break;
51599    }
51600    case SQLITE_TEXT: {
51601      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
51602                              pValue->enc);
51603      break;
51604    }
51605    default: {
51606      rc = sqlite3_bind_null(pStmt, i);
51607      break;
51608    }
51609  }
51610  return rc;
51611}
51612SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
51613  int rc;
51614  Vdbe *p = (Vdbe *)pStmt;
51615  rc = vdbeUnbind(p, i);
51616  if( rc==SQLITE_OK ){
51617    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
51618    sqlite3_mutex_leave(p->db->mutex);
51619  }
51620  return rc;
51621}
51622
51623/*
51624** Return the number of wildcards that can be potentially bound to.
51625** This routine is added to support DBD::SQLite.
51626*/
51627SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
51628  Vdbe *p = (Vdbe*)pStmt;
51629  return p ? p->nVar : 0;
51630}
51631
51632/*
51633** Create a mapping from variable numbers to variable names
51634** in the Vdbe.azVar[] array, if such a mapping does not already
51635** exist.
51636*/
51637static void createVarMap(Vdbe *p){
51638  if( !p->okVar ){
51639    int j;
51640    Op *pOp;
51641    sqlite3_mutex_enter(p->db->mutex);
51642    /* The race condition here is harmless.  If two threads call this
51643    ** routine on the same Vdbe at the same time, they both might end
51644    ** up initializing the Vdbe.azVar[] array.  That is a little extra
51645    ** work but it results in the same answer.
51646    */
51647    for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
51648      if( pOp->opcode==OP_Variable ){
51649        assert( pOp->p1>0 && pOp->p1<=p->nVar );
51650        p->azVar[pOp->p1-1] = pOp->p4.z;
51651      }
51652    }
51653    p->okVar = 1;
51654    sqlite3_mutex_leave(p->db->mutex);
51655  }
51656}
51657
51658/*
51659** Return the name of a wildcard parameter.  Return NULL if the index
51660** is out of range or if the wildcard is unnamed.
51661**
51662** The result is always UTF-8.
51663*/
51664SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
51665  Vdbe *p = (Vdbe*)pStmt;
51666  if( p==0 || i<1 || i>p->nVar ){
51667    return 0;
51668  }
51669  createVarMap(p);
51670  return p->azVar[i-1];
51671}
51672
51673/*
51674** Given a wildcard parameter name, return the index of the variable
51675** with that name.  If there is no variable with the given name,
51676** return 0.
51677*/
51678SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
51679  int i;
51680  if( p==0 ){
51681    return 0;
51682  }
51683  createVarMap(p);
51684  if( zName ){
51685    for(i=0; i<p->nVar; i++){
51686      const char *z = p->azVar[i];
51687      if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
51688        return i+1;
51689      }
51690    }
51691  }
51692  return 0;
51693}
51694SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
51695  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
51696}
51697
51698/*
51699** Transfer all bindings from the first statement over to the second.
51700*/
51701SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
51702  Vdbe *pFrom = (Vdbe*)pFromStmt;
51703  Vdbe *pTo = (Vdbe*)pToStmt;
51704  int i;
51705  assert( pTo->db==pFrom->db );
51706  assert( pTo->nVar==pFrom->nVar );
51707  sqlite3_mutex_enter(pTo->db->mutex);
51708  for(i=0; i<pFrom->nVar; i++){
51709    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
51710  }
51711  sqlite3_mutex_leave(pTo->db->mutex);
51712  return SQLITE_OK;
51713}
51714
51715#ifndef SQLITE_OMIT_DEPRECATED
51716/*
51717** Deprecated external interface.  Internal/core SQLite code
51718** should call sqlite3TransferBindings.
51719**
51720** Is is misuse to call this routine with statements from different
51721** database connections.  But as this is a deprecated interface, we
51722** will not bother to check for that condition.
51723**
51724** If the two statements contain a different number of bindings, then
51725** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
51726** SQLITE_OK is returned.
51727*/
51728SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
51729  Vdbe *pFrom = (Vdbe*)pFromStmt;
51730  Vdbe *pTo = (Vdbe*)pToStmt;
51731  if( pFrom->nVar!=pTo->nVar ){
51732    return SQLITE_ERROR;
51733  }
51734  if( pTo->isPrepareV2 && pTo->expmask ){
51735    pTo->expired = 1;
51736  }
51737  if( pFrom->isPrepareV2 && pFrom->expmask ){
51738    pFrom->expired = 1;
51739  }
51740  return sqlite3TransferBindings(pFromStmt, pToStmt);
51741}
51742#endif
51743
51744/*
51745** Return the sqlite3* database handle to which the prepared statement given
51746** in the argument belongs.  This is the same database handle that was
51747** the first argument to the sqlite3_prepare() that was used to create
51748** the statement in the first place.
51749*/
51750SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
51751  return pStmt ? ((Vdbe*)pStmt)->db : 0;
51752}
51753
51754/*
51755** Return a pointer to the next prepared statement after pStmt associated
51756** with database connection pDb.  If pStmt is NULL, return the first
51757** prepared statement for the database connection.  Return NULL if there
51758** are no more.
51759*/
51760SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
51761  sqlite3_stmt *pNext;
51762  sqlite3_mutex_enter(pDb->mutex);
51763  if( pStmt==0 ){
51764    pNext = (sqlite3_stmt*)pDb->pVdbe;
51765  }else{
51766    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
51767  }
51768  sqlite3_mutex_leave(pDb->mutex);
51769  return pNext;
51770}
51771
51772/*
51773** Return the value of a status counter for a prepared statement
51774*/
51775SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
51776  Vdbe *pVdbe = (Vdbe*)pStmt;
51777  int v = pVdbe->aCounter[op-1];
51778  if( resetFlag ) pVdbe->aCounter[op-1] = 0;
51779  return v;
51780}
51781
51782/************** End of vdbeapi.c *********************************************/
51783/************** Begin file vdbetrace.c ***************************************/
51784/*
51785** 2009 November 25
51786**
51787** The author disclaims copyright to this source code.  In place of
51788** a legal notice, here is a blessing:
51789**
51790**    May you do good and not evil.
51791**    May you find forgiveness for yourself and forgive others.
51792**    May you share freely, never taking more than you give.
51793**
51794*************************************************************************
51795**
51796** This file contains code used to insert the values of host parameters
51797** (aka "wildcards") into the SQL text output by sqlite3_trace().
51798*/
51799
51800#ifndef SQLITE_OMIT_TRACE
51801
51802/*
51803** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
51804** bytes in this text up to but excluding the first character in
51805** a host parameter.  If the text contains no host parameters, return
51806** the total number of bytes in the text.
51807*/
51808static int findNextHostParameter(const char *zSql, int *pnToken){
51809  int tokenType;
51810  int nTotal = 0;
51811  int n;
51812
51813  *pnToken = 0;
51814  while( zSql[0] ){
51815    n = sqlite3GetToken((u8*)zSql, &tokenType);
51816    assert( n>0 && tokenType!=TK_ILLEGAL );
51817    if( tokenType==TK_VARIABLE ){
51818      *pnToken = n;
51819      break;
51820    }
51821    nTotal += n;
51822    zSql += n;
51823  }
51824  return nTotal;
51825}
51826
51827/*
51828** Return a pointer to a string in memory obtained form sqlite3DbMalloc() which
51829** holds a copy of zRawSql but with host parameters expanded to their
51830** current bindings.
51831**
51832** The calling function is responsible for making sure the memory returned
51833** is eventually freed.
51834**
51835** ALGORITHM:  Scan the input string looking for host parameters in any of
51836** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
51837** string literals, quoted identifier names, and comments.  For text forms,
51838** the host parameter index is found by scanning the perpared
51839** statement for the corresponding OP_Variable opcode.  Once the host
51840** parameter index is known, locate the value in p->aVar[].  Then render
51841** the value as a literal in place of the host parameter name.
51842*/
51843SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
51844  Vdbe *p,                 /* The prepared statement being evaluated */
51845  const char *zRawSql      /* Raw text of the SQL statement */
51846){
51847  sqlite3 *db;             /* The database connection */
51848  int idx = 0;             /* Index of a host parameter */
51849  int nextIndex = 1;       /* Index of next ? host parameter */
51850  int n;                   /* Length of a token prefix */
51851  int nToken;              /* Length of the parameter token */
51852  int i;                   /* Loop counter */
51853  Mem *pVar;               /* Value of a host parameter */
51854  StrAccum out;            /* Accumulate the output here */
51855  char zBase[100];         /* Initial working space */
51856
51857  db = p->db;
51858  sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
51859                      db->aLimit[SQLITE_LIMIT_LENGTH]);
51860  out.db = db;
51861  while( zRawSql[0] ){
51862    n = findNextHostParameter(zRawSql, &nToken);
51863    assert( n>0 );
51864    sqlite3StrAccumAppend(&out, zRawSql, n);
51865    zRawSql += n;
51866    assert( zRawSql[0] || nToken==0 );
51867    if( nToken==0 ) break;
51868    if( zRawSql[0]=='?' ){
51869      if( nToken>1 ){
51870        assert( sqlite3Isdigit(zRawSql[1]) );
51871        sqlite3GetInt32(&zRawSql[1], &idx);
51872      }else{
51873        idx = nextIndex;
51874      }
51875    }else{
51876      assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
51877      testcase( zRawSql[0]==':' );
51878      testcase( zRawSql[0]=='$' );
51879      testcase( zRawSql[0]=='@' );
51880      idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
51881      assert( idx>0 );
51882    }
51883    zRawSql += nToken;
51884    nextIndex = idx + 1;
51885    assert( idx>0 && idx<=p->nVar );
51886    pVar = &p->aVar[idx-1];
51887    if( pVar->flags & MEM_Null ){
51888      sqlite3StrAccumAppend(&out, "NULL", 4);
51889    }else if( pVar->flags & MEM_Int ){
51890      sqlite3XPrintf(&out, "%lld", pVar->u.i);
51891    }else if( pVar->flags & MEM_Real ){
51892      sqlite3XPrintf(&out, "%!.15g", pVar->r);
51893    }else if( pVar->flags & MEM_Str ){
51894#ifndef SQLITE_OMIT_UTF16
51895      u8 enc = ENC(db);
51896      if( enc!=SQLITE_UTF8 ){
51897        Mem utf8;
51898        memset(&utf8, 0, sizeof(utf8));
51899        utf8.db = db;
51900        sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
51901        sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
51902        sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
51903        sqlite3VdbeMemRelease(&utf8);
51904      }else
51905#endif
51906      {
51907        sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
51908      }
51909    }else if( pVar->flags & MEM_Zero ){
51910      sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
51911    }else{
51912      assert( pVar->flags & MEM_Blob );
51913      sqlite3StrAccumAppend(&out, "x'", 2);
51914      for(i=0; i<pVar->n; i++){
51915        sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
51916      }
51917      sqlite3StrAccumAppend(&out, "'", 1);
51918    }
51919  }
51920  return sqlite3StrAccumFinish(&out);
51921}
51922
51923#endif /* #ifndef SQLITE_OMIT_TRACE */
51924
51925/************** End of vdbetrace.c *******************************************/
51926/************** Begin file vdbe.c ********************************************/
51927/*
51928** 2001 September 15
51929**
51930** The author disclaims copyright to this source code.  In place of
51931** a legal notice, here is a blessing:
51932**
51933**    May you do good and not evil.
51934**    May you find forgiveness for yourself and forgive others.
51935**    May you share freely, never taking more than you give.
51936**
51937*************************************************************************
51938** The code in this file implements execution method of the
51939** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
51940** handles housekeeping details such as creating and deleting
51941** VDBE instances.  This file is solely interested in executing
51942** the VDBE program.
51943**
51944** In the external interface, an "sqlite3_stmt*" is an opaque pointer
51945** to a VDBE.
51946**
51947** The SQL parser generates a program which is then executed by
51948** the VDBE to do the work of the SQL statement.  VDBE programs are
51949** similar in form to assembly language.  The program consists of
51950** a linear sequence of operations.  Each operation has an opcode
51951** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
51952** is a null-terminated string.  Operand P5 is an unsigned character.
51953** Few opcodes use all 5 operands.
51954**
51955** Computation results are stored on a set of registers numbered beginning
51956** with 1 and going up to Vdbe.nMem.  Each register can store
51957** either an integer, a null-terminated string, a floating point
51958** number, or the SQL "NULL" value.  An implicit conversion from one
51959** type to the other occurs as necessary.
51960**
51961** Most of the code in this file is taken up by the sqlite3VdbeExec()
51962** function which does the work of interpreting a VDBE program.
51963** But other routines are also provided to help in building up
51964** a program instruction by instruction.
51965**
51966** Various scripts scan this source file in order to generate HTML
51967** documentation, headers files, or other derived files.  The formatting
51968** of the code in this file is, therefore, important.  See other comments
51969** in this file for details.  If in doubt, do not deviate from existing
51970** commenting and indentation practices when changing or adding code.
51971*/
51972
51973/*
51974** The following global variable is incremented every time a cursor
51975** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
51976** procedures use this information to make sure that indices are
51977** working correctly.  This variable has no function other than to
51978** help verify the correct operation of the library.
51979*/
51980#ifdef SQLITE_TEST
51981SQLITE_API int sqlite3_search_count = 0;
51982#endif
51983
51984/*
51985** When this global variable is positive, it gets decremented once before
51986** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
51987** field of the sqlite3 structure is set in order to simulate and interrupt.
51988**
51989** This facility is used for testing purposes only.  It does not function
51990** in an ordinary build.
51991*/
51992#ifdef SQLITE_TEST
51993SQLITE_API int sqlite3_interrupt_count = 0;
51994#endif
51995
51996/*
51997** The next global variable is incremented each type the OP_Sort opcode
51998** is executed.  The test procedures use this information to make sure that
51999** sorting is occurring or not occurring at appropriate times.   This variable
52000** has no function other than to help verify the correct operation of the
52001** library.
52002*/
52003#ifdef SQLITE_TEST
52004SQLITE_API int sqlite3_sort_count = 0;
52005#endif
52006
52007/*
52008** The next global variable records the size of the largest MEM_Blob
52009** or MEM_Str that has been used by a VDBE opcode.  The test procedures
52010** use this information to make sure that the zero-blob functionality
52011** is working correctly.   This variable has no function other than to
52012** help verify the correct operation of the library.
52013*/
52014#ifdef SQLITE_TEST
52015SQLITE_API int sqlite3_max_blobsize = 0;
52016static void updateMaxBlobsize(Mem *p){
52017  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
52018    sqlite3_max_blobsize = p->n;
52019  }
52020}
52021#endif
52022
52023/*
52024** The next global variable is incremented each type the OP_Found opcode
52025** is executed. This is used to test whether or not the foreign key
52026** operation implemented using OP_FkIsZero is working. This variable
52027** has no function other than to help verify the correct operation of the
52028** library.
52029*/
52030#ifdef SQLITE_TEST
52031SQLITE_API int sqlite3_found_count = 0;
52032#endif
52033
52034/*
52035** Test a register to see if it exceeds the current maximum blob size.
52036** If it does, record the new maximum blob size.
52037*/
52038#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
52039# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
52040#else
52041# define UPDATE_MAX_BLOBSIZE(P)
52042#endif
52043
52044/*
52045** Convert the given register into a string if it isn't one
52046** already. Return non-zero if a malloc() fails.
52047*/
52048#define Stringify(P, enc) \
52049   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
52050     { goto no_mem; }
52051
52052/*
52053** An ephemeral string value (signified by the MEM_Ephem flag) contains
52054** a pointer to a dynamically allocated string where some other entity
52055** is responsible for deallocating that string.  Because the register
52056** does not control the string, it might be deleted without the register
52057** knowing it.
52058**
52059** This routine converts an ephemeral string into a dynamically allocated
52060** string that the register itself controls.  In other words, it
52061** converts an MEM_Ephem string into an MEM_Dyn string.
52062*/
52063#define Deephemeralize(P) \
52064   if( ((P)->flags&MEM_Ephem)!=0 \
52065       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
52066
52067/*
52068** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
52069** P if required.
52070*/
52071#define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
52072
52073/*
52074** Argument pMem points at a register that will be passed to a
52075** user-defined function or returned to the user as the result of a query.
52076** This routine sets the pMem->type variable used by the sqlite3_value_*()
52077** routines.
52078*/
52079SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
52080  int flags = pMem->flags;
52081  if( flags & MEM_Null ){
52082    pMem->type = SQLITE_NULL;
52083  }
52084  else if( flags & MEM_Int ){
52085    pMem->type = SQLITE_INTEGER;
52086  }
52087  else if( flags & MEM_Real ){
52088    pMem->type = SQLITE_FLOAT;
52089  }
52090  else if( flags & MEM_Str ){
52091    pMem->type = SQLITE_TEXT;
52092  }else{
52093    pMem->type = SQLITE_BLOB;
52094  }
52095}
52096
52097/*
52098** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
52099** if we run out of memory.
52100*/
52101static VdbeCursor *allocateCursor(
52102  Vdbe *p,              /* The virtual machine */
52103  int iCur,             /* Index of the new VdbeCursor */
52104  int nField,           /* Number of fields in the table or index */
52105  int iDb,              /* When database the cursor belongs to, or -1 */
52106  int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
52107){
52108  /* Find the memory cell that will be used to store the blob of memory
52109  ** required for this VdbeCursor structure. It is convenient to use a
52110  ** vdbe memory cell to manage the memory allocation required for a
52111  ** VdbeCursor structure for the following reasons:
52112  **
52113  **   * Sometimes cursor numbers are used for a couple of different
52114  **     purposes in a vdbe program. The different uses might require
52115  **     different sized allocations. Memory cells provide growable
52116  **     allocations.
52117  **
52118  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
52119  **     be freed lazily via the sqlite3_release_memory() API. This
52120  **     minimizes the number of malloc calls made by the system.
52121  **
52122  ** Memory cells for cursors are allocated at the top of the address
52123  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
52124  ** cursor 1 is managed by memory cell (p->nMem-1), etc.
52125  */
52126  Mem *pMem = &p->aMem[p->nMem-iCur];
52127
52128  int nByte;
52129  VdbeCursor *pCx = 0;
52130  nByte =
52131      ROUND8(sizeof(VdbeCursor)) +
52132      (isBtreeCursor?sqlite3BtreeCursorSize():0) +
52133      2*nField*sizeof(u32);
52134
52135  assert( iCur<p->nCursor );
52136  if( p->apCsr[iCur] ){
52137    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
52138    p->apCsr[iCur] = 0;
52139  }
52140  if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
52141    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
52142    memset(pCx, 0, sizeof(VdbeCursor));
52143    pCx->iDb = iDb;
52144    pCx->nField = nField;
52145    if( nField ){
52146      pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
52147    }
52148    if( isBtreeCursor ){
52149      pCx->pCursor = (BtCursor*)
52150          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
52151      sqlite3BtreeCursorZero(pCx->pCursor);
52152    }
52153  }
52154  return pCx;
52155}
52156
52157/*
52158** Try to convert a value into a numeric representation if we can
52159** do so without loss of information.  In other words, if the string
52160** looks like a number, convert it into a number.  If it does not
52161** look like a number, leave it alone.
52162*/
52163static void applyNumericAffinity(Mem *pRec){
52164  if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
52165    int realnum;
52166    sqlite3VdbeMemNulTerminate(pRec);
52167    if( (pRec->flags&MEM_Str)
52168         && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
52169      i64 value;
52170      sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
52171      if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
52172        pRec->u.i = value;
52173        MemSetTypeFlag(pRec, MEM_Int);
52174      }else{
52175        sqlite3VdbeMemRealify(pRec);
52176      }
52177    }
52178  }
52179}
52180
52181/*
52182** Processing is determine by the affinity parameter:
52183**
52184** SQLITE_AFF_INTEGER:
52185** SQLITE_AFF_REAL:
52186** SQLITE_AFF_NUMERIC:
52187**    Try to convert pRec to an integer representation or a
52188**    floating-point representation if an integer representation
52189**    is not possible.  Note that the integer representation is
52190**    always preferred, even if the affinity is REAL, because
52191**    an integer representation is more space efficient on disk.
52192**
52193** SQLITE_AFF_TEXT:
52194**    Convert pRec to a text representation.
52195**
52196** SQLITE_AFF_NONE:
52197**    No-op.  pRec is unchanged.
52198*/
52199static void applyAffinity(
52200  Mem *pRec,          /* The value to apply affinity to */
52201  char affinity,      /* The affinity to be applied */
52202  u8 enc              /* Use this text encoding */
52203){
52204  if( affinity==SQLITE_AFF_TEXT ){
52205    /* Only attempt the conversion to TEXT if there is an integer or real
52206    ** representation (blob and NULL do not get converted) but no string
52207    ** representation.
52208    */
52209    if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
52210      sqlite3VdbeMemStringify(pRec, enc);
52211    }
52212    pRec->flags &= ~(MEM_Real|MEM_Int);
52213  }else if( affinity!=SQLITE_AFF_NONE ){
52214    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
52215             || affinity==SQLITE_AFF_NUMERIC );
52216    applyNumericAffinity(pRec);
52217    if( pRec->flags & MEM_Real ){
52218      sqlite3VdbeIntegerAffinity(pRec);
52219    }
52220  }
52221}
52222
52223/*
52224** Try to convert the type of a function argument or a result column
52225** into a numeric representation.  Use either INTEGER or REAL whichever
52226** is appropriate.  But only do the conversion if it is possible without
52227** loss of information and return the revised type of the argument.
52228**
52229** This is an EXPERIMENTAL api and is subject to change or removal.
52230*/
52231SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
52232  Mem *pMem = (Mem*)pVal;
52233  applyNumericAffinity(pMem);
52234  sqlite3VdbeMemStoreType(pMem);
52235  return pMem->type;
52236}
52237
52238/*
52239** Exported version of applyAffinity(). This one works on sqlite3_value*,
52240** not the internal Mem* type.
52241*/
52242SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
52243  sqlite3_value *pVal,
52244  u8 affinity,
52245  u8 enc
52246){
52247  applyAffinity((Mem *)pVal, affinity, enc);
52248}
52249
52250#ifdef SQLITE_DEBUG
52251/*
52252** Write a nice string representation of the contents of cell pMem
52253** into buffer zBuf, length nBuf.
52254*/
52255SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
52256  char *zCsr = zBuf;
52257  int f = pMem->flags;
52258
52259  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
52260
52261  if( f&MEM_Blob ){
52262    int i;
52263    char c;
52264    if( f & MEM_Dyn ){
52265      c = 'z';
52266      assert( (f & (MEM_Static|MEM_Ephem))==0 );
52267    }else if( f & MEM_Static ){
52268      c = 't';
52269      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
52270    }else if( f & MEM_Ephem ){
52271      c = 'e';
52272      assert( (f & (MEM_Static|MEM_Dyn))==0 );
52273    }else{
52274      c = 's';
52275    }
52276
52277    sqlite3_snprintf(100, zCsr, "%c", c);
52278    zCsr += sqlite3Strlen30(zCsr);
52279    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
52280    zCsr += sqlite3Strlen30(zCsr);
52281    for(i=0; i<16 && i<pMem->n; i++){
52282      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
52283      zCsr += sqlite3Strlen30(zCsr);
52284    }
52285    for(i=0; i<16 && i<pMem->n; i++){
52286      char z = pMem->z[i];
52287      if( z<32 || z>126 ) *zCsr++ = '.';
52288      else *zCsr++ = z;
52289    }
52290
52291    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
52292    zCsr += sqlite3Strlen30(zCsr);
52293    if( f & MEM_Zero ){
52294      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
52295      zCsr += sqlite3Strlen30(zCsr);
52296    }
52297    *zCsr = '\0';
52298  }else if( f & MEM_Str ){
52299    int j, k;
52300    zBuf[0] = ' ';
52301    if( f & MEM_Dyn ){
52302      zBuf[1] = 'z';
52303      assert( (f & (MEM_Static|MEM_Ephem))==0 );
52304    }else if( f & MEM_Static ){
52305      zBuf[1] = 't';
52306      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
52307    }else if( f & MEM_Ephem ){
52308      zBuf[1] = 'e';
52309      assert( (f & (MEM_Static|MEM_Dyn))==0 );
52310    }else{
52311      zBuf[1] = 's';
52312    }
52313    k = 2;
52314    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
52315    k += sqlite3Strlen30(&zBuf[k]);
52316    zBuf[k++] = '[';
52317    for(j=0; j<15 && j<pMem->n; j++){
52318      u8 c = pMem->z[j];
52319      if( c>=0x20 && c<0x7f ){
52320        zBuf[k++] = c;
52321      }else{
52322        zBuf[k++] = '.';
52323      }
52324    }
52325    zBuf[k++] = ']';
52326    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
52327    k += sqlite3Strlen30(&zBuf[k]);
52328    zBuf[k++] = 0;
52329  }
52330}
52331#endif
52332
52333#ifdef SQLITE_DEBUG
52334/*
52335** Print the value of a register for tracing purposes:
52336*/
52337static void memTracePrint(FILE *out, Mem *p){
52338  if( p->flags & MEM_Null ){
52339    fprintf(out, " NULL");
52340  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
52341    fprintf(out, " si:%lld", p->u.i);
52342  }else if( p->flags & MEM_Int ){
52343    fprintf(out, " i:%lld", p->u.i);
52344#ifndef SQLITE_OMIT_FLOATING_POINT
52345  }else if( p->flags & MEM_Real ){
52346    fprintf(out, " r:%g", p->r);
52347#endif
52348  }else if( p->flags & MEM_RowSet ){
52349    fprintf(out, " (rowset)");
52350  }else{
52351    char zBuf[200];
52352    sqlite3VdbeMemPrettyPrint(p, zBuf);
52353    fprintf(out, " ");
52354    fprintf(out, "%s", zBuf);
52355  }
52356}
52357static void registerTrace(FILE *out, int iReg, Mem *p){
52358  fprintf(out, "REG[%d] = ", iReg);
52359  memTracePrint(out, p);
52360  fprintf(out, "\n");
52361}
52362#endif
52363
52364#ifdef SQLITE_DEBUG
52365#  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
52366#else
52367#  define REGISTER_TRACE(R,M)
52368#endif
52369
52370
52371#ifdef VDBE_PROFILE
52372
52373/*
52374** hwtime.h contains inline assembler code for implementing
52375** high-performance timing routines.
52376*/
52377/************** Include hwtime.h in the middle of vdbe.c *********************/
52378/************** Begin file hwtime.h ******************************************/
52379/*
52380** 2008 May 27
52381**
52382** The author disclaims copyright to this source code.  In place of
52383** a legal notice, here is a blessing:
52384**
52385**    May you do good and not evil.
52386**    May you find forgiveness for yourself and forgive others.
52387**    May you share freely, never taking more than you give.
52388**
52389******************************************************************************
52390**
52391** This file contains inline asm code for retrieving "high-performance"
52392** counters for x86 class CPUs.
52393*/
52394#ifndef _HWTIME_H_
52395#define _HWTIME_H_
52396
52397/*
52398** The following routine only works on pentium-class (or newer) processors.
52399** It uses the RDTSC opcode to read the cycle count value out of the
52400** processor and returns that value.  This can be used for high-res
52401** profiling.
52402*/
52403#if (defined(__GNUC__) || defined(_MSC_VER)) && \
52404      (defined(i386) || defined(__i386__) || defined(_M_IX86))
52405
52406  #if defined(__GNUC__)
52407
52408  __inline__ sqlite_uint64 sqlite3Hwtime(void){
52409     unsigned int lo, hi;
52410     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
52411     return (sqlite_uint64)hi << 32 | lo;
52412  }
52413
52414  #elif defined(_MSC_VER)
52415
52416  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
52417     __asm {
52418        rdtsc
52419        ret       ; return value at EDX:EAX
52420     }
52421  }
52422
52423  #endif
52424
52425#elif (defined(__GNUC__) && defined(__x86_64__))
52426
52427  __inline__ sqlite_uint64 sqlite3Hwtime(void){
52428      unsigned long val;
52429      __asm__ __volatile__ ("rdtsc" : "=A" (val));
52430      return val;
52431  }
52432
52433#elif (defined(__GNUC__) && defined(__ppc__))
52434
52435  __inline__ sqlite_uint64 sqlite3Hwtime(void){
52436      unsigned long long retval;
52437      unsigned long junk;
52438      __asm__ __volatile__ ("\n\
52439          1:      mftbu   %1\n\
52440                  mftb    %L0\n\
52441                  mftbu   %0\n\
52442                  cmpw    %0,%1\n\
52443                  bne     1b"
52444                  : "=r" (retval), "=r" (junk));
52445      return retval;
52446  }
52447
52448#else
52449
52450  #error Need implementation of sqlite3Hwtime() for your platform.
52451
52452  /*
52453  ** To compile without implementing sqlite3Hwtime() for your platform,
52454  ** you can remove the above #error and use the following
52455  ** stub function.  You will lose timing support for many
52456  ** of the debugging and testing utilities, but it should at
52457  ** least compile and run.
52458  */
52459SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
52460
52461#endif
52462
52463#endif /* !defined(_HWTIME_H_) */
52464
52465/************** End of hwtime.h **********************************************/
52466/************** Continuing where we left off in vdbe.c ***********************/
52467
52468#endif
52469
52470/*
52471** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
52472** sqlite3_interrupt() routine has been called.  If it has been, then
52473** processing of the VDBE program is interrupted.
52474**
52475** This macro added to every instruction that does a jump in order to
52476** implement a loop.  This test used to be on every single instruction,
52477** but that meant we more testing that we needed.  By only testing the
52478** flag on jump instructions, we get a (small) speed improvement.
52479*/
52480#define CHECK_FOR_INTERRUPT \
52481   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
52482
52483#ifdef SQLITE_DEBUG
52484static int fileExists(sqlite3 *db, const char *zFile){
52485  int res = 0;
52486  int rc = SQLITE_OK;
52487#ifdef SQLITE_TEST
52488  /* If we are currently testing IO errors, then do not call OsAccess() to
52489  ** test for the presence of zFile. This is because any IO error that
52490  ** occurs here will not be reported, causing the test to fail.
52491  */
52492  extern int sqlite3_io_error_pending;
52493  if( sqlite3_io_error_pending<=0 )
52494#endif
52495    rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
52496  return (res && rc==SQLITE_OK);
52497}
52498#endif
52499
52500#ifndef NDEBUG
52501/*
52502** This function is only called from within an assert() expression. It
52503** checks that the sqlite3.nTransaction variable is correctly set to
52504** the number of non-transaction savepoints currently in the
52505** linked list starting at sqlite3.pSavepoint.
52506**
52507** Usage:
52508**
52509**     assert( checkSavepointCount(db) );
52510*/
52511static int checkSavepointCount(sqlite3 *db){
52512  int n = 0;
52513  Savepoint *p;
52514  for(p=db->pSavepoint; p; p=p->pNext) n++;
52515  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
52516  return 1;
52517}
52518#endif
52519
52520/*
52521** Execute as much of a VDBE program as we can then return.
52522**
52523** sqlite3VdbeMakeReady() must be called before this routine in order to
52524** close the program with a final OP_Halt and to set up the callbacks
52525** and the error message pointer.
52526**
52527** Whenever a row or result data is available, this routine will either
52528** invoke the result callback (if there is one) or return with
52529** SQLITE_ROW.
52530**
52531** If an attempt is made to open a locked database, then this routine
52532** will either invoke the busy callback (if there is one) or it will
52533** return SQLITE_BUSY.
52534**
52535** If an error occurs, an error message is written to memory obtained
52536** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
52537** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
52538**
52539** If the callback ever returns non-zero, then the program exits
52540** immediately.  There will be no error message but the p->rc field is
52541** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
52542**
52543** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
52544** routine to return SQLITE_ERROR.
52545**
52546** Other fatal errors return SQLITE_ERROR.
52547**
52548** After this routine has finished, sqlite3VdbeFinalize() should be
52549** used to clean up the mess that was left behind.
52550*/
52551SQLITE_PRIVATE int sqlite3VdbeExec(
52552  Vdbe *p                    /* The VDBE */
52553){
52554  int pc;                    /* The program counter */
52555  Op *aOp = p->aOp;          /* Copy of p->aOp */
52556  Op *pOp;                   /* Current operation */
52557  int rc = SQLITE_OK;        /* Value to return */
52558  sqlite3 *db = p->db;       /* The database */
52559  u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */
52560  u8 encoding = ENC(db);     /* The database encoding */
52561#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
52562  int checkProgress;         /* True if progress callbacks are enabled */
52563  int nProgressOps = 0;      /* Opcodes executed since progress callback. */
52564#endif
52565  Mem *aMem = p->aMem;       /* Copy of p->aMem */
52566  Mem *pIn1 = 0;             /* 1st input operand */
52567  Mem *pIn2 = 0;             /* 2nd input operand */
52568  Mem *pIn3 = 0;             /* 3rd input operand */
52569  Mem *pOut = 0;             /* Output operand */
52570  int iCompare = 0;          /* Result of last OP_Compare operation */
52571  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
52572#ifdef VDBE_PROFILE
52573  u64 start;                 /* CPU clock count at start of opcode */
52574  int origPc;                /* Program counter at start of opcode */
52575#endif
52576  /********************************************************************
52577  ** Automatically generated code
52578  **
52579  ** The following union is automatically generated by the
52580  ** vdbe-compress.tcl script.  The purpose of this union is to
52581  ** reduce the amount of stack space required by this function.
52582  ** See comments in the vdbe-compress.tcl script for details.
52583  */
52584  union vdbeExecUnion {
52585    struct OP_Yield_stack_vars {
52586      int pcDest;
52587    } aa;
52588    struct OP_Variable_stack_vars {
52589      int p1;          /* Variable to copy from */
52590      int p2;          /* Register to copy to */
52591      int n;           /* Number of values left to copy */
52592      Mem *pVar;       /* Value being transferred */
52593    } ab;
52594    struct OP_Move_stack_vars {
52595      char *zMalloc;   /* Holding variable for allocated memory */
52596      int n;           /* Number of registers left to copy */
52597      int p1;          /* Register to copy from */
52598      int p2;          /* Register to copy to */
52599    } ac;
52600    struct OP_ResultRow_stack_vars {
52601      Mem *pMem;
52602      int i;
52603    } ad;
52604    struct OP_Concat_stack_vars {
52605      i64 nByte;
52606    } ae;
52607    struct OP_Remainder_stack_vars {
52608      int flags;      /* Combined MEM_* flags from both inputs */
52609      i64 iA;         /* Integer value of left operand */
52610      i64 iB;         /* Integer value of right operand */
52611      double rA;      /* Real value of left operand */
52612      double rB;      /* Real value of right operand */
52613    } af;
52614    struct OP_Function_stack_vars {
52615      int i;
52616      Mem *pArg;
52617      sqlite3_context ctx;
52618      sqlite3_value **apVal;
52619      int n;
52620    } ag;
52621    struct OP_ShiftRight_stack_vars {
52622      i64 a;
52623      i64 b;
52624    } ah;
52625    struct OP_Ge_stack_vars {
52626      int res;            /* Result of the comparison of pIn1 against pIn3 */
52627      char affinity;      /* Affinity to use for comparison */
52628    } ai;
52629    struct OP_Compare_stack_vars {
52630      int n;
52631      int i;
52632      int p1;
52633      int p2;
52634      const KeyInfo *pKeyInfo;
52635      int idx;
52636      CollSeq *pColl;    /* Collating sequence to use on this term */
52637      int bRev;          /* True for DESCENDING sort order */
52638    } aj;
52639    struct OP_Or_stack_vars {
52640      int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
52641      int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
52642    } ak;
52643    struct OP_IfNot_stack_vars {
52644      int c;
52645    } al;
52646    struct OP_Column_stack_vars {
52647      u32 payloadSize;   /* Number of bytes in the record */
52648      i64 payloadSize64; /* Number of bytes in the record */
52649      int p1;            /* P1 value of the opcode */
52650      int p2;            /* column number to retrieve */
52651      VdbeCursor *pC;    /* The VDBE cursor */
52652      char *zRec;        /* Pointer to complete record-data */
52653      BtCursor *pCrsr;   /* The BTree cursor */
52654      u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
52655      u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
52656      int nField;        /* number of fields in the record */
52657      int len;           /* The length of the serialized data for the column */
52658      int i;             /* Loop counter */
52659      char *zData;       /* Part of the record being decoded */
52660      Mem *pDest;        /* Where to write the extracted value */
52661      Mem sMem;          /* For storing the record being decoded */
52662      u8 *zIdx;          /* Index into header */
52663      u8 *zEndHdr;       /* Pointer to first byte after the header */
52664      u32 offset;        /* Offset into the data */
52665      u32 szField;       /* Number of bytes in the content of a field */
52666      int szHdr;         /* Size of the header size field at start of record */
52667      int avail;         /* Number of bytes of available data */
52668      Mem *pReg;         /* PseudoTable input register */
52669    } am;
52670    struct OP_Affinity_stack_vars {
52671      const char *zAffinity;   /* The affinity to be applied */
52672      char cAff;               /* A single character of affinity */
52673    } an;
52674    struct OP_MakeRecord_stack_vars {
52675      u8 *zNewRecord;        /* A buffer to hold the data for the new record */
52676      Mem *pRec;             /* The new record */
52677      u64 nData;             /* Number of bytes of data space */
52678      int nHdr;              /* Number of bytes of header space */
52679      i64 nByte;             /* Data space required for this record */
52680      int nZero;             /* Number of zero bytes at the end of the record */
52681      int nVarint;           /* Number of bytes in a varint */
52682      u32 serial_type;       /* Type field */
52683      Mem *pData0;           /* First field to be combined into the record */
52684      Mem *pLast;            /* Last field of the record */
52685      int nField;            /* Number of fields in the record */
52686      char *zAffinity;       /* The affinity string for the record */
52687      int file_format;       /* File format to use for encoding */
52688      int i;                 /* Space used in zNewRecord[] */
52689      int len;               /* Length of a field */
52690    } ao;
52691    struct OP_Count_stack_vars {
52692      i64 nEntry;
52693      BtCursor *pCrsr;
52694    } ap;
52695    struct OP_Savepoint_stack_vars {
52696      int p1;                         /* Value of P1 operand */
52697      char *zName;                    /* Name of savepoint */
52698      int nName;
52699      Savepoint *pNew;
52700      Savepoint *pSavepoint;
52701      Savepoint *pTmp;
52702      int iSavepoint;
52703      int ii;
52704    } aq;
52705    struct OP_AutoCommit_stack_vars {
52706      int desiredAutoCommit;
52707      int iRollback;
52708      int turnOnAC;
52709    } ar;
52710    struct OP_Transaction_stack_vars {
52711      Btree *pBt;
52712    } as;
52713    struct OP_ReadCookie_stack_vars {
52714      int iMeta;
52715      int iDb;
52716      int iCookie;
52717    } at;
52718    struct OP_SetCookie_stack_vars {
52719      Db *pDb;
52720    } au;
52721    struct OP_VerifyCookie_stack_vars {
52722      int iMeta;
52723      Btree *pBt;
52724    } av;
52725    struct OP_OpenWrite_stack_vars {
52726      int nField;
52727      KeyInfo *pKeyInfo;
52728      int p2;
52729      int iDb;
52730      int wrFlag;
52731      Btree *pX;
52732      VdbeCursor *pCur;
52733      Db *pDb;
52734    } aw;
52735    struct OP_OpenEphemeral_stack_vars {
52736      VdbeCursor *pCx;
52737    } ax;
52738    struct OP_OpenPseudo_stack_vars {
52739      VdbeCursor *pCx;
52740    } ay;
52741    struct OP_SeekGt_stack_vars {
52742      int res;
52743      int oc;
52744      VdbeCursor *pC;
52745      UnpackedRecord r;
52746      int nField;
52747      i64 iKey;      /* The rowid we are to seek to */
52748    } az;
52749    struct OP_Seek_stack_vars {
52750      VdbeCursor *pC;
52751    } ba;
52752    struct OP_Found_stack_vars {
52753      int alreadyExists;
52754      VdbeCursor *pC;
52755      int res;
52756      UnpackedRecord *pIdxKey;
52757      UnpackedRecord r;
52758      char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
52759    } bb;
52760    struct OP_IsUnique_stack_vars {
52761      u16 ii;
52762      VdbeCursor *pCx;
52763      BtCursor *pCrsr;
52764      u16 nField;
52765      Mem *aMx;
52766      UnpackedRecord r;                  /* B-Tree index search key */
52767      i64 R;                             /* Rowid stored in register P3 */
52768    } bc;
52769    struct OP_NotExists_stack_vars {
52770      VdbeCursor *pC;
52771      BtCursor *pCrsr;
52772      int res;
52773      u64 iKey;
52774    } bd;
52775    struct OP_NewRowid_stack_vars {
52776      i64 v;                 /* The new rowid */
52777      VdbeCursor *pC;        /* Cursor of table to get the new rowid */
52778      int res;               /* Result of an sqlite3BtreeLast() */
52779      int cnt;               /* Counter to limit the number of searches */
52780      Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
52781      VdbeFrame *pFrame;     /* Root frame of VDBE */
52782    } be;
52783    struct OP_InsertInt_stack_vars {
52784      Mem *pData;       /* MEM cell holding data for the record to be inserted */
52785      Mem *pKey;        /* MEM cell holding key  for the record */
52786      i64 iKey;         /* The integer ROWID or key for the record to be inserted */
52787      VdbeCursor *pC;   /* Cursor to table into which insert is written */
52788      int nZero;        /* Number of zero-bytes to append */
52789      int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
52790      const char *zDb;  /* database name - used by the update hook */
52791      const char *zTbl; /* Table name - used by the opdate hook */
52792      int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
52793    } bf;
52794    struct OP_Delete_stack_vars {
52795      i64 iKey;
52796      VdbeCursor *pC;
52797    } bg;
52798    struct OP_RowData_stack_vars {
52799      VdbeCursor *pC;
52800      BtCursor *pCrsr;
52801      u32 n;
52802      i64 n64;
52803    } bh;
52804    struct OP_Rowid_stack_vars {
52805      VdbeCursor *pC;
52806      i64 v;
52807      sqlite3_vtab *pVtab;
52808      const sqlite3_module *pModule;
52809    } bi;
52810    struct OP_NullRow_stack_vars {
52811      VdbeCursor *pC;
52812    } bj;
52813    struct OP_Last_stack_vars {
52814      VdbeCursor *pC;
52815      BtCursor *pCrsr;
52816      int res;
52817    } bk;
52818    struct OP_Rewind_stack_vars {
52819      VdbeCursor *pC;
52820      BtCursor *pCrsr;
52821      int res;
52822    } bl;
52823    struct OP_Next_stack_vars {
52824      VdbeCursor *pC;
52825      BtCursor *pCrsr;
52826      int res;
52827    } bm;
52828    struct OP_IdxInsert_stack_vars {
52829      VdbeCursor *pC;
52830      BtCursor *pCrsr;
52831      int nKey;
52832      const char *zKey;
52833    } bn;
52834    struct OP_IdxDelete_stack_vars {
52835      VdbeCursor *pC;
52836      BtCursor *pCrsr;
52837      int res;
52838      UnpackedRecord r;
52839    } bo;
52840    struct OP_IdxRowid_stack_vars {
52841      BtCursor *pCrsr;
52842      VdbeCursor *pC;
52843      i64 rowid;
52844    } bp;
52845    struct OP_IdxGE_stack_vars {
52846      VdbeCursor *pC;
52847      int res;
52848      UnpackedRecord r;
52849    } bq;
52850    struct OP_Destroy_stack_vars {
52851      int iMoved;
52852      int iCnt;
52853      Vdbe *pVdbe;
52854      int iDb;
52855    } br;
52856    struct OP_Clear_stack_vars {
52857      int nChange;
52858    } bs;
52859    struct OP_CreateTable_stack_vars {
52860      int pgno;
52861      int flags;
52862      Db *pDb;
52863    } bt;
52864    struct OP_ParseSchema_stack_vars {
52865      int iDb;
52866      const char *zMaster;
52867      char *zSql;
52868      InitData initData;
52869    } bu;
52870    struct OP_IntegrityCk_stack_vars {
52871      int nRoot;      /* Number of tables to check.  (Number of root pages.) */
52872      int *aRoot;     /* Array of rootpage numbers for tables to be checked */
52873      int j;          /* Loop counter */
52874      int nErr;       /* Number of errors reported */
52875      char *z;        /* Text of the error report */
52876      Mem *pnErr;     /* Register keeping track of errors remaining */
52877    } bv;
52878    struct OP_RowSetRead_stack_vars {
52879      i64 val;
52880    } bw;
52881    struct OP_RowSetTest_stack_vars {
52882      int iSet;
52883      int exists;
52884    } bx;
52885    struct OP_Program_stack_vars {
52886      int nMem;               /* Number of memory registers for sub-program */
52887      int nByte;              /* Bytes of runtime space required for sub-program */
52888      Mem *pRt;               /* Register to allocate runtime space */
52889      Mem *pMem;              /* Used to iterate through memory cells */
52890      Mem *pEnd;              /* Last memory cell in new array */
52891      VdbeFrame *pFrame;      /* New vdbe frame to execute in */
52892      SubProgram *pProgram;   /* Sub-program to execute */
52893      void *t;                /* Token identifying trigger */
52894    } by;
52895    struct OP_Param_stack_vars {
52896      VdbeFrame *pFrame;
52897      Mem *pIn;
52898    } bz;
52899    struct OP_MemMax_stack_vars {
52900      Mem *pIn1;
52901      VdbeFrame *pFrame;
52902    } ca;
52903    struct OP_AggStep_stack_vars {
52904      int n;
52905      int i;
52906      Mem *pMem;
52907      Mem *pRec;
52908      sqlite3_context ctx;
52909      sqlite3_value **apVal;
52910    } cb;
52911    struct OP_AggFinal_stack_vars {
52912      Mem *pMem;
52913    } cc;
52914    struct OP_IncrVacuum_stack_vars {
52915      Btree *pBt;
52916    } cd;
52917    struct OP_VBegin_stack_vars {
52918      VTable *pVTab;
52919    } ce;
52920    struct OP_VOpen_stack_vars {
52921      VdbeCursor *pCur;
52922      sqlite3_vtab_cursor *pVtabCursor;
52923      sqlite3_vtab *pVtab;
52924      sqlite3_module *pModule;
52925    } cf;
52926    struct OP_VFilter_stack_vars {
52927      int nArg;
52928      int iQuery;
52929      const sqlite3_module *pModule;
52930      Mem *pQuery;
52931      Mem *pArgc;
52932      sqlite3_vtab_cursor *pVtabCursor;
52933      sqlite3_vtab *pVtab;
52934      VdbeCursor *pCur;
52935      int res;
52936      int i;
52937      Mem **apArg;
52938    } cg;
52939    struct OP_VColumn_stack_vars {
52940      sqlite3_vtab *pVtab;
52941      const sqlite3_module *pModule;
52942      Mem *pDest;
52943      sqlite3_context sContext;
52944    } ch;
52945    struct OP_VNext_stack_vars {
52946      sqlite3_vtab *pVtab;
52947      const sqlite3_module *pModule;
52948      int res;
52949      VdbeCursor *pCur;
52950    } ci;
52951    struct OP_VRename_stack_vars {
52952      sqlite3_vtab *pVtab;
52953      Mem *pName;
52954    } cj;
52955    struct OP_VUpdate_stack_vars {
52956      sqlite3_vtab *pVtab;
52957      sqlite3_module *pModule;
52958      int nArg;
52959      int i;
52960      sqlite_int64 rowid;
52961      Mem **apArg;
52962      Mem *pX;
52963    } ck;
52964    struct OP_Pagecount_stack_vars {
52965      int p1;
52966      int nPage;
52967      Pager *pPager;
52968    } cl;
52969    struct OP_Trace_stack_vars {
52970      char *zTrace;
52971    } cm;
52972  } u;
52973  /* End automatically generated code
52974  ********************************************************************/
52975
52976  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
52977  sqlite3VdbeMutexArrayEnter(p);
52978  if( p->rc==SQLITE_NOMEM ){
52979    /* This happens if a malloc() inside a call to sqlite3_column_text() or
52980    ** sqlite3_column_text16() failed.  */
52981    goto no_mem;
52982  }
52983  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
52984  p->rc = SQLITE_OK;
52985  assert( p->explain==0 );
52986  p->pResultSet = 0;
52987  db->busyHandler.nBusy = 0;
52988  CHECK_FOR_INTERRUPT;
52989  sqlite3VdbeIOTraceSql(p);
52990#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
52991  checkProgress = db->xProgress!=0;
52992#endif
52993#ifdef SQLITE_DEBUG
52994  sqlite3BeginBenignMalloc();
52995  if( p->pc==0
52996   && ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
52997  ){
52998    int i;
52999    printf("VDBE Program Listing:\n");
53000    sqlite3VdbePrintSql(p);
53001    for(i=0; i<p->nOp; i++){
53002      sqlite3VdbePrintOp(stdout, i, &aOp[i]);
53003    }
53004  }
53005  if( fileExists(db, "vdbe_trace") ){
53006    p->trace = stdout;
53007  }
53008  sqlite3EndBenignMalloc();
53009#endif
53010  for(pc=p->pc; rc==SQLITE_OK; pc++){
53011    assert( pc>=0 && pc<p->nOp );
53012    if( db->mallocFailed ) goto no_mem;
53013#ifdef VDBE_PROFILE
53014    origPc = pc;
53015    start = sqlite3Hwtime();
53016#endif
53017    pOp = &aOp[pc];
53018
53019    /* Only allow tracing if SQLITE_DEBUG is defined.
53020    */
53021#ifdef SQLITE_DEBUG
53022    if( p->trace ){
53023      if( pc==0 ){
53024        printf("VDBE Execution Trace:\n");
53025        sqlite3VdbePrintSql(p);
53026      }
53027      sqlite3VdbePrintOp(p->trace, pc, pOp);
53028    }
53029    if( p->trace==0 && pc==0 ){
53030      sqlite3BeginBenignMalloc();
53031      if( fileExists(db, "vdbe_sqltrace") ){
53032        sqlite3VdbePrintSql(p);
53033      }
53034      sqlite3EndBenignMalloc();
53035    }
53036#endif
53037
53038
53039    /* Check to see if we need to simulate an interrupt.  This only happens
53040    ** if we have a special test build.
53041    */
53042#ifdef SQLITE_TEST
53043    if( sqlite3_interrupt_count>0 ){
53044      sqlite3_interrupt_count--;
53045      if( sqlite3_interrupt_count==0 ){
53046        sqlite3_interrupt(db);
53047      }
53048    }
53049#endif
53050
53051#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
53052    /* Call the progress callback if it is configured and the required number
53053    ** of VDBE ops have been executed (either since this invocation of
53054    ** sqlite3VdbeExec() or since last time the progress callback was called).
53055    ** If the progress callback returns non-zero, exit the virtual machine with
53056    ** a return code SQLITE_ABORT.
53057    */
53058    if( checkProgress ){
53059      if( db->nProgressOps==nProgressOps ){
53060        int prc;
53061        prc = db->xProgress(db->pProgressArg);
53062        if( prc!=0 ){
53063          rc = SQLITE_INTERRUPT;
53064          goto vdbe_error_halt;
53065        }
53066        nProgressOps = 0;
53067      }
53068      nProgressOps++;
53069    }
53070#endif
53071
53072    /* On any opcode with the "out2-prerelase" tag, free any
53073    ** external allocations out of mem[p2] and set mem[p2] to be
53074    ** an undefined integer.  Opcodes will either fill in the integer
53075    ** value or convert mem[p2] to a different type.
53076    */
53077    assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
53078    if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
53079      assert( pOp->p2>0 );
53080      assert( pOp->p2<=p->nMem );
53081      pOut = &aMem[pOp->p2];
53082      sqlite3VdbeMemReleaseExternal(pOut);
53083      pOut->flags = MEM_Int;
53084    }
53085
53086    /* Sanity checking on other operands */
53087#ifdef SQLITE_DEBUG
53088    if( (pOp->opflags & OPFLG_IN1)!=0 ){
53089      assert( pOp->p1>0 );
53090      assert( pOp->p1<=p->nMem );
53091      REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
53092    }
53093    if( (pOp->opflags & OPFLG_IN2)!=0 ){
53094      assert( pOp->p2>0 );
53095      assert( pOp->p2<=p->nMem );
53096      REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
53097    }
53098    if( (pOp->opflags & OPFLG_IN3)!=0 ){
53099      assert( pOp->p3>0 );
53100      assert( pOp->p3<=p->nMem );
53101      REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
53102    }
53103    if( (pOp->opflags & OPFLG_OUT2)!=0 ){
53104      assert( pOp->p2>0 );
53105      assert( pOp->p2<=p->nMem );
53106    }
53107    if( (pOp->opflags & OPFLG_OUT3)!=0 ){
53108      assert( pOp->p3>0 );
53109      assert( pOp->p3<=p->nMem );
53110    }
53111#endif
53112
53113    switch( pOp->opcode ){
53114
53115/*****************************************************************************
53116** What follows is a massive switch statement where each case implements a
53117** separate instruction in the virtual machine.  If we follow the usual
53118** indentation conventions, each case should be indented by 6 spaces.  But
53119** that is a lot of wasted space on the left margin.  So the code within
53120** the switch statement will break with convention and be flush-left. Another
53121** big comment (similar to this one) will mark the point in the code where
53122** we transition back to normal indentation.
53123**
53124** The formatting of each case is important.  The makefile for SQLite
53125** generates two C files "opcodes.h" and "opcodes.c" by scanning this
53126** file looking for lines that begin with "case OP_".  The opcodes.h files
53127** will be filled with #defines that give unique integer values to each
53128** opcode and the opcodes.c file is filled with an array of strings where
53129** each string is the symbolic name for the corresponding opcode.  If the
53130** case statement is followed by a comment of the form "/# same as ... #/"
53131** that comment is used to determine the particular value of the opcode.
53132**
53133** Other keywords in the comment that follows each case are used to
53134** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
53135** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
53136** the mkopcodeh.awk script for additional information.
53137**
53138** Documentation about VDBE opcodes is generated by scanning this file
53139** for lines of that contain "Opcode:".  That line and all subsequent
53140** comment lines are used in the generation of the opcode.html documentation
53141** file.
53142**
53143** SUMMARY:
53144**
53145**     Formatting is important to scripts that scan this file.
53146**     Do not deviate from the formatting style currently in use.
53147**
53148*****************************************************************************/
53149
53150/* Opcode:  Goto * P2 * * *
53151**
53152** An unconditional jump to address P2.
53153** The next instruction executed will be
53154** the one at index P2 from the beginning of
53155** the program.
53156*/
53157case OP_Goto: {             /* jump */
53158  CHECK_FOR_INTERRUPT;
53159  pc = pOp->p2 - 1;
53160  break;
53161}
53162
53163/* Opcode:  Gosub P1 P2 * * *
53164**
53165** Write the current address onto register P1
53166** and then jump to address P2.
53167*/
53168case OP_Gosub: {            /* jump, in1 */
53169  pIn1 = &aMem[pOp->p1];
53170  assert( (pIn1->flags & MEM_Dyn)==0 );
53171  pIn1->flags = MEM_Int;
53172  pIn1->u.i = pc;
53173  REGISTER_TRACE(pOp->p1, pIn1);
53174  pc = pOp->p2 - 1;
53175  break;
53176}
53177
53178/* Opcode:  Return P1 * * * *
53179**
53180** Jump to the next instruction after the address in register P1.
53181*/
53182case OP_Return: {           /* in1 */
53183  pIn1 = &aMem[pOp->p1];
53184  assert( pIn1->flags & MEM_Int );
53185  pc = (int)pIn1->u.i;
53186  break;
53187}
53188
53189/* Opcode:  Yield P1 * * * *
53190**
53191** Swap the program counter with the value in register P1.
53192*/
53193case OP_Yield: {            /* in1 */
53194#if 0  /* local variables moved into u.aa */
53195  int pcDest;
53196#endif /* local variables moved into u.aa */
53197  pIn1 = &aMem[pOp->p1];
53198  assert( (pIn1->flags & MEM_Dyn)==0 );
53199  pIn1->flags = MEM_Int;
53200  u.aa.pcDest = (int)pIn1->u.i;
53201  pIn1->u.i = pc;
53202  REGISTER_TRACE(pOp->p1, pIn1);
53203  pc = u.aa.pcDest;
53204  break;
53205}
53206
53207/* Opcode:  HaltIfNull  P1 P2 P3 P4 *
53208**
53209** Check the value in register P3.  If is is NULL then Halt using
53210** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
53211** value in register P3 is not NULL, then this routine is a no-op.
53212*/
53213case OP_HaltIfNull: {      /* in3 */
53214  pIn3 = &aMem[pOp->p3];
53215  if( (pIn3->flags & MEM_Null)==0 ) break;
53216  /* Fall through into OP_Halt */
53217}
53218
53219/* Opcode:  Halt P1 P2 * P4 *
53220**
53221** Exit immediately.  All open cursors, etc are closed
53222** automatically.
53223**
53224** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
53225** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
53226** For errors, it can be some other value.  If P1!=0 then P2 will determine
53227** whether or not to rollback the current transaction.  Do not rollback
53228** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
53229** then back out all changes that have occurred during this execution of the
53230** VDBE, but do not rollback the transaction.
53231**
53232** If P4 is not null then it is an error message string.
53233**
53234** There is an implied "Halt 0 0 0" instruction inserted at the very end of
53235** every program.  So a jump past the last instruction of the program
53236** is the same as executing Halt.
53237*/
53238case OP_Halt: {
53239  if( pOp->p1==SQLITE_OK && p->pFrame ){
53240    /* Halt the sub-program. Return control to the parent frame. */
53241    VdbeFrame *pFrame = p->pFrame;
53242    p->pFrame = pFrame->pParent;
53243    p->nFrame--;
53244    sqlite3VdbeSetChanges(db, p->nChange);
53245    pc = sqlite3VdbeFrameRestore(pFrame);
53246    if( pOp->p2==OE_Ignore ){
53247      /* Instruction pc is the OP_Program that invoked the sub-program
53248      ** currently being halted. If the p2 instruction of this OP_Halt
53249      ** instruction is set to OE_Ignore, then the sub-program is throwing
53250      ** an IGNORE exception. In this case jump to the address specified
53251      ** as the p2 of the calling OP_Program.  */
53252      pc = p->aOp[pc].p2-1;
53253    }
53254    aOp = p->aOp;
53255    aMem = p->aMem;
53256    break;
53257  }
53258
53259  p->rc = pOp->p1;
53260  p->errorAction = (u8)pOp->p2;
53261  p->pc = pc;
53262  if( pOp->p4.z ){
53263    assert( p->rc!=SQLITE_OK );
53264    sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
53265    testcase( sqlite3GlobalConfig.xLog!=0 );
53266    sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
53267  }else if( p->rc ){
53268    testcase( sqlite3GlobalConfig.xLog!=0 );
53269    sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
53270  }
53271  rc = sqlite3VdbeHalt(p);
53272  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
53273  if( rc==SQLITE_BUSY ){
53274    p->rc = rc = SQLITE_BUSY;
53275  }else{
53276    assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
53277    assert( rc==SQLITE_OK || db->nDeferredCons>0 );
53278    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
53279  }
53280  goto vdbe_return;
53281}
53282
53283/* Opcode: Integer P1 P2 * * *
53284**
53285** The 32-bit integer value P1 is written into register P2.
53286*/
53287case OP_Integer: {         /* out2-prerelease */
53288  pOut->u.i = pOp->p1;
53289  break;
53290}
53291
53292/* Opcode: Int64 * P2 * P4 *
53293**
53294** P4 is a pointer to a 64-bit integer value.
53295** Write that value into register P2.
53296*/
53297case OP_Int64: {           /* out2-prerelease */
53298  assert( pOp->p4.pI64!=0 );
53299  pOut->u.i = *pOp->p4.pI64;
53300  break;
53301}
53302
53303/* Opcode: Real * P2 * P4 *
53304**
53305** P4 is a pointer to a 64-bit floating point value.
53306** Write that value into register P2.
53307*/
53308case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
53309  pOut->flags = MEM_Real;
53310  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
53311  pOut->r = *pOp->p4.pReal;
53312  break;
53313}
53314
53315/* Opcode: String8 * P2 * P4 *
53316**
53317** P4 points to a nul terminated UTF-8 string. This opcode is transformed
53318** into an OP_String before it is executed for the first time.
53319*/
53320case OP_String8: {         /* same as TK_STRING, out2-prerelease */
53321  assert( pOp->p4.z!=0 );
53322  pOp->opcode = OP_String;
53323  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
53324
53325#ifndef SQLITE_OMIT_UTF16
53326  if( encoding!=SQLITE_UTF8 ){
53327    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
53328    if( rc==SQLITE_TOOBIG ) goto too_big;
53329    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
53330    assert( pOut->zMalloc==pOut->z );
53331    assert( pOut->flags & MEM_Dyn );
53332    pOut->zMalloc = 0;
53333    pOut->flags |= MEM_Static;
53334    pOut->flags &= ~MEM_Dyn;
53335    if( pOp->p4type==P4_DYNAMIC ){
53336      sqlite3DbFree(db, pOp->p4.z);
53337    }
53338    pOp->p4type = P4_DYNAMIC;
53339    pOp->p4.z = pOut->z;
53340    pOp->p1 = pOut->n;
53341  }
53342#endif
53343  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
53344    goto too_big;
53345  }
53346  /* Fall through to the next case, OP_String */
53347}
53348
53349/* Opcode: String P1 P2 * P4 *
53350**
53351** The string value P4 of length P1 (bytes) is stored in register P2.
53352*/
53353case OP_String: {          /* out2-prerelease */
53354  assert( pOp->p4.z!=0 );
53355  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
53356  pOut->z = pOp->p4.z;
53357  pOut->n = pOp->p1;
53358  pOut->enc = encoding;
53359  UPDATE_MAX_BLOBSIZE(pOut);
53360  break;
53361}
53362
53363/* Opcode: Null * P2 * * *
53364**
53365** Write a NULL into register P2.
53366*/
53367case OP_Null: {           /* out2-prerelease */
53368  pOut->flags = MEM_Null;
53369  break;
53370}
53371
53372
53373/* Opcode: Blob P1 P2 * P4
53374**
53375** P4 points to a blob of data P1 bytes long.  Store this
53376** blob in register P2. This instruction is not coded directly
53377** by the compiler. Instead, the compiler layer specifies
53378** an OP_HexBlob opcode, with the hex string representation of
53379** the blob as P4. This opcode is transformed to an OP_Blob
53380** the first time it is executed.
53381*/
53382case OP_Blob: {                /* out2-prerelease */
53383  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
53384  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
53385  pOut->enc = encoding;
53386  UPDATE_MAX_BLOBSIZE(pOut);
53387  break;
53388}
53389
53390/* Opcode: Variable P1 P2 P3 P4 *
53391**
53392** Transfer the values of bound parameters P1..P1+P3-1 into registers
53393** P2..P2+P3-1.
53394**
53395** If the parameter is named, then its name appears in P4 and P3==1.
53396** The P4 value is used by sqlite3_bind_parameter_name().
53397*/
53398case OP_Variable: {
53399#if 0  /* local variables moved into u.ab */
53400  int p1;          /* Variable to copy from */
53401  int p2;          /* Register to copy to */
53402  int n;           /* Number of values left to copy */
53403  Mem *pVar;       /* Value being transferred */
53404#endif /* local variables moved into u.ab */
53405
53406  u.ab.p1 = pOp->p1 - 1;
53407  u.ab.p2 = pOp->p2;
53408  u.ab.n = pOp->p3;
53409  assert( u.ab.p1>=0 && u.ab.p1+u.ab.n<=p->nVar );
53410  assert( u.ab.p2>=1 && u.ab.p2+u.ab.n-1<=p->nMem );
53411  assert( pOp->p4.z==0 || pOp->p3==1 || pOp->p3==0 );
53412
53413  while( u.ab.n-- > 0 ){
53414    u.ab.pVar = &p->aVar[u.ab.p1++];
53415    if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
53416      goto too_big;
53417    }
53418    pOut = &aMem[u.ab.p2++];
53419    sqlite3VdbeMemReleaseExternal(pOut);
53420    pOut->flags = MEM_Null;
53421    sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
53422    UPDATE_MAX_BLOBSIZE(pOut);
53423  }
53424  break;
53425}
53426
53427/* Opcode: Move P1 P2 P3 * *
53428**
53429** Move the values in register P1..P1+P3-1 over into
53430** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
53431** left holding a NULL.  It is an error for register ranges
53432** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
53433*/
53434case OP_Move: {
53435#if 0  /* local variables moved into u.ac */
53436  char *zMalloc;   /* Holding variable for allocated memory */
53437  int n;           /* Number of registers left to copy */
53438  int p1;          /* Register to copy from */
53439  int p2;          /* Register to copy to */
53440#endif /* local variables moved into u.ac */
53441
53442  u.ac.n = pOp->p3;
53443  u.ac.p1 = pOp->p1;
53444  u.ac.p2 = pOp->p2;
53445  assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
53446  assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
53447
53448  pIn1 = &aMem[u.ac.p1];
53449  pOut = &aMem[u.ac.p2];
53450  while( u.ac.n-- ){
53451    assert( pOut<=&aMem[p->nMem] );
53452    assert( pIn1<=&aMem[p->nMem] );
53453    u.ac.zMalloc = pOut->zMalloc;
53454    pOut->zMalloc = 0;
53455    sqlite3VdbeMemMove(pOut, pIn1);
53456    pIn1->zMalloc = u.ac.zMalloc;
53457    REGISTER_TRACE(u.ac.p2++, pOut);
53458    pIn1++;
53459    pOut++;
53460  }
53461  break;
53462}
53463
53464/* Opcode: Copy P1 P2 * * *
53465**
53466** Make a copy of register P1 into register P2.
53467**
53468** This instruction makes a deep copy of the value.  A duplicate
53469** is made of any string or blob constant.  See also OP_SCopy.
53470*/
53471case OP_Copy: {             /* in1, out2 */
53472  pIn1 = &aMem[pOp->p1];
53473  pOut = &aMem[pOp->p2];
53474  assert( pOut!=pIn1 );
53475  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
53476  Deephemeralize(pOut);
53477  REGISTER_TRACE(pOp->p2, pOut);
53478  break;
53479}
53480
53481/* Opcode: SCopy P1 P2 * * *
53482**
53483** Make a shallow copy of register P1 into register P2.
53484**
53485** This instruction makes a shallow copy of the value.  If the value
53486** is a string or blob, then the copy is only a pointer to the
53487** original and hence if the original changes so will the copy.
53488** Worse, if the original is deallocated, the copy becomes invalid.
53489** Thus the program must guarantee that the original will not change
53490** during the lifetime of the copy.  Use OP_Copy to make a complete
53491** copy.
53492*/
53493case OP_SCopy: {            /* in1, out2 */
53494  pIn1 = &aMem[pOp->p1];
53495  pOut = &aMem[pOp->p2];
53496  assert( pOut!=pIn1 );
53497  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
53498  REGISTER_TRACE(pOp->p2, pOut);
53499  break;
53500}
53501
53502/* Opcode: ResultRow P1 P2 * * *
53503**
53504** The registers P1 through P1+P2-1 contain a single row of
53505** results. This opcode causes the sqlite3_step() call to terminate
53506** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
53507** structure to provide access to the top P1 values as the result
53508** row.
53509*/
53510case OP_ResultRow: {
53511#if 0  /* local variables moved into u.ad */
53512  Mem *pMem;
53513  int i;
53514#endif /* local variables moved into u.ad */
53515  assert( p->nResColumn==pOp->p2 );
53516  assert( pOp->p1>0 );
53517  assert( pOp->p1+pOp->p2<=p->nMem+1 );
53518
53519  /* If this statement has violated immediate foreign key constraints, do
53520  ** not return the number of rows modified. And do not RELEASE the statement
53521  ** transaction. It needs to be rolled back.  */
53522  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
53523    assert( db->flags&SQLITE_CountRows );
53524    assert( p->usesStmtJournal );
53525    break;
53526  }
53527
53528  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
53529  ** DML statements invoke this opcode to return the number of rows
53530  ** modified to the user. This is the only way that a VM that
53531  ** opens a statement transaction may invoke this opcode.
53532  **
53533  ** In case this is such a statement, close any statement transaction
53534  ** opened by this VM before returning control to the user. This is to
53535  ** ensure that statement-transactions are always nested, not overlapping.
53536  ** If the open statement-transaction is not closed here, then the user
53537  ** may step another VM that opens its own statement transaction. This
53538  ** may lead to overlapping statement transactions.
53539  **
53540  ** The statement transaction is never a top-level transaction.  Hence
53541  ** the RELEASE call below can never fail.
53542  */
53543  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
53544  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
53545  if( NEVER(rc!=SQLITE_OK) ){
53546    break;
53547  }
53548
53549  /* Invalidate all ephemeral cursor row caches */
53550  p->cacheCtr = (p->cacheCtr + 2)|1;
53551
53552  /* Make sure the results of the current row are \000 terminated
53553  ** and have an assigned type.  The results are de-ephemeralized as
53554  ** as side effect.
53555  */
53556  u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
53557  for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
53558    sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
53559    sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
53560    REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
53561  }
53562  if( db->mallocFailed ) goto no_mem;
53563
53564  /* Return SQLITE_ROW
53565  */
53566  p->pc = pc + 1;
53567  rc = SQLITE_ROW;
53568  goto vdbe_return;
53569}
53570
53571/* Opcode: Concat P1 P2 P3 * *
53572**
53573** Add the text in register P1 onto the end of the text in
53574** register P2 and store the result in register P3.
53575** If either the P1 or P2 text are NULL then store NULL in P3.
53576**
53577**   P3 = P2 || P1
53578**
53579** It is illegal for P1 and P3 to be the same register. Sometimes,
53580** if P3 is the same register as P2, the implementation is able
53581** to avoid a memcpy().
53582*/
53583case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
53584#if 0  /* local variables moved into u.ae */
53585  i64 nByte;
53586#endif /* local variables moved into u.ae */
53587
53588  pIn1 = &aMem[pOp->p1];
53589  pIn2 = &aMem[pOp->p2];
53590  pOut = &aMem[pOp->p3];
53591  assert( pIn1!=pOut );
53592  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
53593    sqlite3VdbeMemSetNull(pOut);
53594    break;
53595  }
53596  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
53597  Stringify(pIn1, encoding);
53598  Stringify(pIn2, encoding);
53599  u.ae.nByte = pIn1->n + pIn2->n;
53600  if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
53601    goto too_big;
53602  }
53603  MemSetTypeFlag(pOut, MEM_Str);
53604  if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
53605    goto no_mem;
53606  }
53607  if( pOut!=pIn2 ){
53608    memcpy(pOut->z, pIn2->z, pIn2->n);
53609  }
53610  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
53611  pOut->z[u.ae.nByte] = 0;
53612  pOut->z[u.ae.nByte+1] = 0;
53613  pOut->flags |= MEM_Term;
53614  pOut->n = (int)u.ae.nByte;
53615  pOut->enc = encoding;
53616  UPDATE_MAX_BLOBSIZE(pOut);
53617  break;
53618}
53619
53620/* Opcode: Add P1 P2 P3 * *
53621**
53622** Add the value in register P1 to the value in register P2
53623** and store the result in register P3.
53624** If either input is NULL, the result is NULL.
53625*/
53626/* Opcode: Multiply P1 P2 P3 * *
53627**
53628**
53629** Multiply the value in register P1 by the value in register P2
53630** and store the result in register P3.
53631** If either input is NULL, the result is NULL.
53632*/
53633/* Opcode: Subtract P1 P2 P3 * *
53634**
53635** Subtract the value in register P1 from the value in register P2
53636** and store the result in register P3.
53637** If either input is NULL, the result is NULL.
53638*/
53639/* Opcode: Divide P1 P2 P3 * *
53640**
53641** Divide the value in register P1 by the value in register P2
53642** and store the result in register P3 (P3=P2/P1). If the value in
53643** register P1 is zero, then the result is NULL. If either input is
53644** NULL, the result is NULL.
53645*/
53646/* Opcode: Remainder P1 P2 P3 * *
53647**
53648** Compute the remainder after integer division of the value in
53649** register P1 by the value in register P2 and store the result in P3.
53650** If the value in register P2 is zero the result is NULL.
53651** If either operand is NULL, the result is NULL.
53652*/
53653case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
53654case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
53655case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
53656case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
53657case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
53658#if 0  /* local variables moved into u.af */
53659  int flags;      /* Combined MEM_* flags from both inputs */
53660  i64 iA;         /* Integer value of left operand */
53661  i64 iB;         /* Integer value of right operand */
53662  double rA;      /* Real value of left operand */
53663  double rB;      /* Real value of right operand */
53664#endif /* local variables moved into u.af */
53665
53666  pIn1 = &aMem[pOp->p1];
53667  applyNumericAffinity(pIn1);
53668  pIn2 = &aMem[pOp->p2];
53669  applyNumericAffinity(pIn2);
53670  pOut = &aMem[pOp->p3];
53671  u.af.flags = pIn1->flags | pIn2->flags;
53672  if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
53673  if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
53674    u.af.iA = pIn1->u.i;
53675    u.af.iB = pIn2->u.i;
53676    switch( pOp->opcode ){
53677      case OP_Add:         u.af.iB += u.af.iA;       break;
53678      case OP_Subtract:    u.af.iB -= u.af.iA;       break;
53679      case OP_Multiply:    u.af.iB *= u.af.iA;       break;
53680      case OP_Divide: {
53681        if( u.af.iA==0 ) goto arithmetic_result_is_null;
53682        /* Dividing the largest possible negative 64-bit integer (1<<63) by
53683        ** -1 returns an integer too large to store in a 64-bit data-type. On
53684        ** some architectures, the value overflows to (1<<63). On others,
53685        ** a SIGFPE is issued. The following statement normalizes this
53686        ** behavior so that all architectures behave as if integer
53687        ** overflow occurred.
53688        */
53689        if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) u.af.iA = 1;
53690        u.af.iB /= u.af.iA;
53691        break;
53692      }
53693      default: {
53694        if( u.af.iA==0 ) goto arithmetic_result_is_null;
53695        if( u.af.iA==-1 ) u.af.iA = 1;
53696        u.af.iB %= u.af.iA;
53697        break;
53698      }
53699    }
53700    pOut->u.i = u.af.iB;
53701    MemSetTypeFlag(pOut, MEM_Int);
53702  }else{
53703    u.af.rA = sqlite3VdbeRealValue(pIn1);
53704    u.af.rB = sqlite3VdbeRealValue(pIn2);
53705    switch( pOp->opcode ){
53706      case OP_Add:         u.af.rB += u.af.rA;       break;
53707      case OP_Subtract:    u.af.rB -= u.af.rA;       break;
53708      case OP_Multiply:    u.af.rB *= u.af.rA;       break;
53709      case OP_Divide: {
53710        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
53711        if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
53712        u.af.rB /= u.af.rA;
53713        break;
53714      }
53715      default: {
53716        u.af.iA = (i64)u.af.rA;
53717        u.af.iB = (i64)u.af.rB;
53718        if( u.af.iA==0 ) goto arithmetic_result_is_null;
53719        if( u.af.iA==-1 ) u.af.iA = 1;
53720        u.af.rB = (double)(u.af.iB % u.af.iA);
53721        break;
53722      }
53723    }
53724    if( sqlite3IsNaN(u.af.rB) ){
53725      goto arithmetic_result_is_null;
53726    }
53727    pOut->r = u.af.rB;
53728    MemSetTypeFlag(pOut, MEM_Real);
53729    if( (u.af.flags & MEM_Real)==0 ){
53730      sqlite3VdbeIntegerAffinity(pOut);
53731    }
53732  }
53733  break;
53734
53735arithmetic_result_is_null:
53736  sqlite3VdbeMemSetNull(pOut);
53737  break;
53738}
53739
53740/* Opcode: CollSeq * * P4
53741**
53742** P4 is a pointer to a CollSeq struct. If the next call to a user function
53743** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
53744** be returned. This is used by the built-in min(), max() and nullif()
53745** functions.
53746**
53747** The interface used by the implementation of the aforementioned functions
53748** to retrieve the collation sequence set by this opcode is not available
53749** publicly, only to user functions defined in func.c.
53750*/
53751case OP_CollSeq: {
53752  assert( pOp->p4type==P4_COLLSEQ );
53753  break;
53754}
53755
53756/* Opcode: Function P1 P2 P3 P4 P5
53757**
53758** Invoke a user function (P4 is a pointer to a Function structure that
53759** defines the function) with P5 arguments taken from register P2 and
53760** successors.  The result of the function is stored in register P3.
53761** Register P3 must not be one of the function inputs.
53762**
53763** P1 is a 32-bit bitmask indicating whether or not each argument to the
53764** function was determined to be constant at compile time. If the first
53765** argument was constant then bit 0 of P1 is set. This is used to determine
53766** whether meta data associated with a user function argument using the
53767** sqlite3_set_auxdata() API may be safely retained until the next
53768** invocation of this opcode.
53769**
53770** See also: AggStep and AggFinal
53771*/
53772case OP_Function: {
53773#if 0  /* local variables moved into u.ag */
53774  int i;
53775  Mem *pArg;
53776  sqlite3_context ctx;
53777  sqlite3_value **apVal;
53778  int n;
53779#endif /* local variables moved into u.ag */
53780
53781  u.ag.n = pOp->p5;
53782  u.ag.apVal = p->apArg;
53783  assert( u.ag.apVal || u.ag.n==0 );
53784
53785  assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
53786  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
53787  u.ag.pArg = &aMem[pOp->p2];
53788  for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
53789    u.ag.apVal[u.ag.i] = u.ag.pArg;
53790    sqlite3VdbeMemStoreType(u.ag.pArg);
53791    REGISTER_TRACE(pOp->p2, u.ag.pArg);
53792  }
53793
53794  assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
53795  if( pOp->p4type==P4_FUNCDEF ){
53796    u.ag.ctx.pFunc = pOp->p4.pFunc;
53797    u.ag.ctx.pVdbeFunc = 0;
53798  }else{
53799    u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
53800    u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
53801  }
53802
53803  assert( pOp->p3>0 && pOp->p3<=p->nMem );
53804  pOut = &aMem[pOp->p3];
53805  u.ag.ctx.s.flags = MEM_Null;
53806  u.ag.ctx.s.db = db;
53807  u.ag.ctx.s.xDel = 0;
53808  u.ag.ctx.s.zMalloc = 0;
53809
53810  /* The output cell may already have a buffer allocated. Move
53811  ** the pointer to u.ag.ctx.s so in case the user-function can use
53812  ** the already allocated buffer instead of allocating a new one.
53813  */
53814  sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
53815  MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
53816
53817  u.ag.ctx.isError = 0;
53818  if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
53819    assert( pOp>aOp );
53820    assert( pOp[-1].p4type==P4_COLLSEQ );
53821    assert( pOp[-1].opcode==OP_CollSeq );
53822    u.ag.ctx.pColl = pOp[-1].p4.pColl;
53823  }
53824  (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal);
53825  if( db->mallocFailed ){
53826    /* Even though a malloc() has failed, the implementation of the
53827    ** user function may have called an sqlite3_result_XXX() function
53828    ** to return a value. The following call releases any resources
53829    ** associated with such a value.
53830    */
53831    sqlite3VdbeMemRelease(&u.ag.ctx.s);
53832    goto no_mem;
53833  }
53834
53835  /* If any auxiliary data functions have been called by this user function,
53836  ** immediately call the destructor for any non-static values.
53837  */
53838  if( u.ag.ctx.pVdbeFunc ){
53839    sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
53840    pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
53841    pOp->p4type = P4_VDBEFUNC;
53842  }
53843
53844  /* If the function returned an error, throw an exception */
53845  if( u.ag.ctx.isError ){
53846    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
53847    rc = u.ag.ctx.isError;
53848  }
53849
53850  /* Copy the result of the function into register P3 */
53851  sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
53852  sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
53853  if( sqlite3VdbeMemTooBig(pOut) ){
53854    goto too_big;
53855  }
53856  REGISTER_TRACE(pOp->p3, pOut);
53857  UPDATE_MAX_BLOBSIZE(pOut);
53858  break;
53859}
53860
53861/* Opcode: BitAnd P1 P2 P3 * *
53862**
53863** Take the bit-wise AND of the values in register P1 and P2 and
53864** store the result in register P3.
53865** If either input is NULL, the result is NULL.
53866*/
53867/* Opcode: BitOr P1 P2 P3 * *
53868**
53869** Take the bit-wise OR of the values in register P1 and P2 and
53870** store the result in register P3.
53871** If either input is NULL, the result is NULL.
53872*/
53873/* Opcode: ShiftLeft P1 P2 P3 * *
53874**
53875** Shift the integer value in register P2 to the left by the
53876** number of bits specified by the integer in regiser P1.
53877** Store the result in register P3.
53878** If either input is NULL, the result is NULL.
53879*/
53880/* Opcode: ShiftRight P1 P2 P3 * *
53881**
53882** Shift the integer value in register P2 to the right by the
53883** number of bits specified by the integer in register P1.
53884** Store the result in register P3.
53885** If either input is NULL, the result is NULL.
53886*/
53887case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
53888case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
53889case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
53890case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
53891#if 0  /* local variables moved into u.ah */
53892  i64 a;
53893  i64 b;
53894#endif /* local variables moved into u.ah */
53895
53896  pIn1 = &aMem[pOp->p1];
53897  pIn2 = &aMem[pOp->p2];
53898  pOut = &aMem[pOp->p3];
53899  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
53900    sqlite3VdbeMemSetNull(pOut);
53901    break;
53902  }
53903  u.ah.a = sqlite3VdbeIntValue(pIn2);
53904  u.ah.b = sqlite3VdbeIntValue(pIn1);
53905  switch( pOp->opcode ){
53906    case OP_BitAnd:      u.ah.a &= u.ah.b;     break;
53907    case OP_BitOr:       u.ah.a |= u.ah.b;     break;
53908    case OP_ShiftLeft:   u.ah.a <<= u.ah.b;    break;
53909    default:  assert( pOp->opcode==OP_ShiftRight );
53910                         u.ah.a >>= u.ah.b;    break;
53911  }
53912  pOut->u.i = u.ah.a;
53913  MemSetTypeFlag(pOut, MEM_Int);
53914  break;
53915}
53916
53917/* Opcode: AddImm  P1 P2 * * *
53918**
53919** Add the constant P2 to the value in register P1.
53920** The result is always an integer.
53921**
53922** To force any register to be an integer, just add 0.
53923*/
53924case OP_AddImm: {            /* in1 */
53925  pIn1 = &aMem[pOp->p1];
53926  sqlite3VdbeMemIntegerify(pIn1);
53927  pIn1->u.i += pOp->p2;
53928  break;
53929}
53930
53931/* Opcode: MustBeInt P1 P2 * * *
53932**
53933** Force the value in register P1 to be an integer.  If the value
53934** in P1 is not an integer and cannot be converted into an integer
53935** without data loss, then jump immediately to P2, or if P2==0
53936** raise an SQLITE_MISMATCH exception.
53937*/
53938case OP_MustBeInt: {            /* jump, in1 */
53939  pIn1 = &aMem[pOp->p1];
53940  applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
53941  if( (pIn1->flags & MEM_Int)==0 ){
53942    if( pOp->p2==0 ){
53943      rc = SQLITE_MISMATCH;
53944      goto abort_due_to_error;
53945    }else{
53946      pc = pOp->p2 - 1;
53947    }
53948  }else{
53949    MemSetTypeFlag(pIn1, MEM_Int);
53950  }
53951  break;
53952}
53953
53954/* Opcode: RealAffinity P1 * * * *
53955**
53956** If register P1 holds an integer convert it to a real value.
53957**
53958** This opcode is used when extracting information from a column that
53959** has REAL affinity.  Such column values may still be stored as
53960** integers, for space efficiency, but after extraction we want them
53961** to have only a real value.
53962*/
53963case OP_RealAffinity: {                  /* in1 */
53964  pIn1 = &aMem[pOp->p1];
53965  if( pIn1->flags & MEM_Int ){
53966    sqlite3VdbeMemRealify(pIn1);
53967  }
53968  break;
53969}
53970
53971#ifndef SQLITE_OMIT_CAST
53972/* Opcode: ToText P1 * * * *
53973**
53974** Force the value in register P1 to be text.
53975** If the value is numeric, convert it to a string using the
53976** equivalent of printf().  Blob values are unchanged and
53977** are afterwards simply interpreted as text.
53978**
53979** A NULL value is not changed by this routine.  It remains NULL.
53980*/
53981case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
53982  pIn1 = &aMem[pOp->p1];
53983  if( pIn1->flags & MEM_Null ) break;
53984  assert( MEM_Str==(MEM_Blob>>3) );
53985  pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
53986  applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
53987  rc = ExpandBlob(pIn1);
53988  assert( pIn1->flags & MEM_Str || db->mallocFailed );
53989  pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
53990  UPDATE_MAX_BLOBSIZE(pIn1);
53991  break;
53992}
53993
53994/* Opcode: ToBlob P1 * * * *
53995**
53996** Force the value in register P1 to be a BLOB.
53997** If the value is numeric, convert it to a string first.
53998** Strings are simply reinterpreted as blobs with no change
53999** to the underlying data.
54000**
54001** A NULL value is not changed by this routine.  It remains NULL.
54002*/
54003case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
54004  pIn1 = &aMem[pOp->p1];
54005  if( pIn1->flags & MEM_Null ) break;
54006  if( (pIn1->flags & MEM_Blob)==0 ){
54007    applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
54008    assert( pIn1->flags & MEM_Str || db->mallocFailed );
54009    MemSetTypeFlag(pIn1, MEM_Blob);
54010  }else{
54011    pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
54012  }
54013  UPDATE_MAX_BLOBSIZE(pIn1);
54014  break;
54015}
54016
54017/* Opcode: ToNumeric P1 * * * *
54018**
54019** Force the value in register P1 to be numeric (either an
54020** integer or a floating-point number.)
54021** If the value is text or blob, try to convert it to an using the
54022** equivalent of atoi() or atof() and store 0 if no such conversion
54023** is possible.
54024**
54025** A NULL value is not changed by this routine.  It remains NULL.
54026*/
54027case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
54028  pIn1 = &aMem[pOp->p1];
54029  if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
54030    sqlite3VdbeMemNumerify(pIn1);
54031  }
54032  break;
54033}
54034#endif /* SQLITE_OMIT_CAST */
54035
54036/* Opcode: ToInt P1 * * * *
54037**
54038** Force the value in register P1 be an integer.  If
54039** The value is currently a real number, drop its fractional part.
54040** If the value is text or blob, try to convert it to an integer using the
54041** equivalent of atoi() and store 0 if no such conversion is possible.
54042**
54043** A NULL value is not changed by this routine.  It remains NULL.
54044*/
54045case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
54046  pIn1 = &aMem[pOp->p1];
54047  if( (pIn1->flags & MEM_Null)==0 ){
54048    sqlite3VdbeMemIntegerify(pIn1);
54049  }
54050  break;
54051}
54052
54053#ifndef SQLITE_OMIT_CAST
54054/* Opcode: ToReal P1 * * * *
54055**
54056** Force the value in register P1 to be a floating point number.
54057** If The value is currently an integer, convert it.
54058** If the value is text or blob, try to convert it to an integer using the
54059** equivalent of atoi() and store 0.0 if no such conversion is possible.
54060**
54061** A NULL value is not changed by this routine.  It remains NULL.
54062*/
54063case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
54064  pIn1 = &aMem[pOp->p1];
54065  if( (pIn1->flags & MEM_Null)==0 ){
54066    sqlite3VdbeMemRealify(pIn1);
54067  }
54068  break;
54069}
54070#endif /* SQLITE_OMIT_CAST */
54071
54072/* Opcode: Lt P1 P2 P3 P4 P5
54073**
54074** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
54075** jump to address P2.
54076**
54077** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
54078** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
54079** bit is clear then fall thru if either operand is NULL.
54080**
54081** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
54082** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
54083** to coerce both inputs according to this affinity before the
54084** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
54085** affinity is used. Note that the affinity conversions are stored
54086** back into the input registers P1 and P3.  So this opcode can cause
54087** persistent changes to registers P1 and P3.
54088**
54089** Once any conversions have taken place, and neither value is NULL,
54090** the values are compared. If both values are blobs then memcmp() is
54091** used to determine the results of the comparison.  If both values
54092** are text, then the appropriate collating function specified in
54093** P4 is  used to do the comparison.  If P4 is not specified then
54094** memcmp() is used to compare text string.  If both values are
54095** numeric, then a numeric comparison is used. If the two values
54096** are of different types, then numbers are considered less than
54097** strings and strings are considered less than blobs.
54098**
54099** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
54100** store a boolean result (either 0, or 1, or NULL) in register P2.
54101*/
54102/* Opcode: Ne P1 P2 P3 P4 P5
54103**
54104** This works just like the Lt opcode except that the jump is taken if
54105** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
54106** additional information.
54107**
54108** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
54109** true or false and is never NULL.  If both operands are NULL then the result
54110** of comparison is false.  If either operand is NULL then the result is true.
54111** If neither operand is NULL the the result is the same as it would be if
54112** the SQLITE_NULLEQ flag were omitted from P5.
54113*/
54114/* Opcode: Eq P1 P2 P3 P4 P5
54115**
54116** This works just like the Lt opcode except that the jump is taken if
54117** the operands in registers P1 and P3 are equal.
54118** See the Lt opcode for additional information.
54119**
54120** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
54121** true or false and is never NULL.  If both operands are NULL then the result
54122** of comparison is true.  If either operand is NULL then the result is false.
54123** If neither operand is NULL the the result is the same as it would be if
54124** the SQLITE_NULLEQ flag were omitted from P5.
54125*/
54126/* Opcode: Le P1 P2 P3 P4 P5
54127**
54128** This works just like the Lt opcode except that the jump is taken if
54129** the content of register P3 is less than or equal to the content of
54130** register P1.  See the Lt opcode for additional information.
54131*/
54132/* Opcode: Gt P1 P2 P3 P4 P5
54133**
54134** This works just like the Lt opcode except that the jump is taken if
54135** the content of register P3 is greater than the content of
54136** register P1.  See the Lt opcode for additional information.
54137*/
54138/* Opcode: Ge P1 P2 P3 P4 P5
54139**
54140** This works just like the Lt opcode except that the jump is taken if
54141** the content of register P3 is greater than or equal to the content of
54142** register P1.  See the Lt opcode for additional information.
54143*/
54144case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
54145case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
54146case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
54147case OP_Le:               /* same as TK_LE, jump, in1, in3 */
54148case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
54149case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
54150#if 0  /* local variables moved into u.ai */
54151  int res;            /* Result of the comparison of pIn1 against pIn3 */
54152  char affinity;      /* Affinity to use for comparison */
54153#endif /* local variables moved into u.ai */
54154
54155  pIn1 = &aMem[pOp->p1];
54156  pIn3 = &aMem[pOp->p3];
54157  if( (pIn1->flags | pIn3->flags)&MEM_Null ){
54158    /* One or both operands are NULL */
54159    if( pOp->p5 & SQLITE_NULLEQ ){
54160      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
54161      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
54162      ** or not both operands are null.
54163      */
54164      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
54165      u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
54166    }else{
54167      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
54168      ** then the result is always NULL.
54169      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
54170      */
54171      if( pOp->p5 & SQLITE_STOREP2 ){
54172        pOut = &aMem[pOp->p2];
54173        MemSetTypeFlag(pOut, MEM_Null);
54174        REGISTER_TRACE(pOp->p2, pOut);
54175      }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
54176        pc = pOp->p2-1;
54177      }
54178      break;
54179    }
54180  }else{
54181    /* Neither operand is NULL.  Do a comparison. */
54182    u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
54183    if( u.ai.affinity ){
54184      applyAffinity(pIn1, u.ai.affinity, encoding);
54185      applyAffinity(pIn3, u.ai.affinity, encoding);
54186      if( db->mallocFailed ) goto no_mem;
54187    }
54188
54189    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
54190    ExpandBlob(pIn1);
54191    ExpandBlob(pIn3);
54192    u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
54193  }
54194  switch( pOp->opcode ){
54195    case OP_Eq:    u.ai.res = u.ai.res==0;     break;
54196    case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
54197    case OP_Lt:    u.ai.res = u.ai.res<0;      break;
54198    case OP_Le:    u.ai.res = u.ai.res<=0;     break;
54199    case OP_Gt:    u.ai.res = u.ai.res>0;      break;
54200    default:       u.ai.res = u.ai.res>=0;     break;
54201  }
54202
54203  if( pOp->p5 & SQLITE_STOREP2 ){
54204    pOut = &aMem[pOp->p2];
54205    MemSetTypeFlag(pOut, MEM_Int);
54206    pOut->u.i = u.ai.res;
54207    REGISTER_TRACE(pOp->p2, pOut);
54208  }else if( u.ai.res ){
54209    pc = pOp->p2-1;
54210  }
54211  break;
54212}
54213
54214/* Opcode: Permutation * * * P4 *
54215**
54216** Set the permutation used by the OP_Compare operator to be the array
54217** of integers in P4.
54218**
54219** The permutation is only valid until the next OP_Permutation, OP_Compare,
54220** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
54221** immediately prior to the OP_Compare.
54222*/
54223case OP_Permutation: {
54224  assert( pOp->p4type==P4_INTARRAY );
54225  assert( pOp->p4.ai );
54226  aPermute = pOp->p4.ai;
54227  break;
54228}
54229
54230/* Opcode: Compare P1 P2 P3 P4 *
54231**
54232** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
54233** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
54234** the comparison for use by the next OP_Jump instruct.
54235**
54236** P4 is a KeyInfo structure that defines collating sequences and sort
54237** orders for the comparison.  The permutation applies to registers
54238** only.  The KeyInfo elements are used sequentially.
54239**
54240** The comparison is a sort comparison, so NULLs compare equal,
54241** NULLs are less than numbers, numbers are less than strings,
54242** and strings are less than blobs.
54243*/
54244case OP_Compare: {
54245#if 0  /* local variables moved into u.aj */
54246  int n;
54247  int i;
54248  int p1;
54249  int p2;
54250  const KeyInfo *pKeyInfo;
54251  int idx;
54252  CollSeq *pColl;    /* Collating sequence to use on this term */
54253  int bRev;          /* True for DESCENDING sort order */
54254#endif /* local variables moved into u.aj */
54255
54256  u.aj.n = pOp->p3;
54257  u.aj.pKeyInfo = pOp->p4.pKeyInfo;
54258  assert( u.aj.n>0 );
54259  assert( u.aj.pKeyInfo!=0 );
54260  u.aj.p1 = pOp->p1;
54261  u.aj.p2 = pOp->p2;
54262#if SQLITE_DEBUG
54263  if( aPermute ){
54264    int k, mx = 0;
54265    for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
54266    assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
54267    assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
54268  }else{
54269    assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
54270    assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
54271  }
54272#endif /* SQLITE_DEBUG */
54273  for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
54274    u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
54275    REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
54276    REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
54277    assert( u.aj.i<u.aj.pKeyInfo->nField );
54278    u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
54279    u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
54280    iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
54281    if( iCompare ){
54282      if( u.aj.bRev ) iCompare = -iCompare;
54283      break;
54284    }
54285  }
54286  aPermute = 0;
54287  break;
54288}
54289
54290/* Opcode: Jump P1 P2 P3 * *
54291**
54292** Jump to the instruction at address P1, P2, or P3 depending on whether
54293** in the most recent OP_Compare instruction the P1 vector was less than
54294** equal to, or greater than the P2 vector, respectively.
54295*/
54296case OP_Jump: {             /* jump */
54297  if( iCompare<0 ){
54298    pc = pOp->p1 - 1;
54299  }else if( iCompare==0 ){
54300    pc = pOp->p2 - 1;
54301  }else{
54302    pc = pOp->p3 - 1;
54303  }
54304  break;
54305}
54306
54307/* Opcode: And P1 P2 P3 * *
54308**
54309** Take the logical AND of the values in registers P1 and P2 and
54310** write the result into register P3.
54311**
54312** If either P1 or P2 is 0 (false) then the result is 0 even if
54313** the other input is NULL.  A NULL and true or two NULLs give
54314** a NULL output.
54315*/
54316/* Opcode: Or P1 P2 P3 * *
54317**
54318** Take the logical OR of the values in register P1 and P2 and
54319** store the answer in register P3.
54320**
54321** If either P1 or P2 is nonzero (true) then the result is 1 (true)
54322** even if the other input is NULL.  A NULL and false or two NULLs
54323** give a NULL output.
54324*/
54325case OP_And:              /* same as TK_AND, in1, in2, out3 */
54326case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
54327#if 0  /* local variables moved into u.ak */
54328  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
54329  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
54330#endif /* local variables moved into u.ak */
54331
54332  pIn1 = &aMem[pOp->p1];
54333  if( pIn1->flags & MEM_Null ){
54334    u.ak.v1 = 2;
54335  }else{
54336    u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
54337  }
54338  pIn2 = &aMem[pOp->p2];
54339  if( pIn2->flags & MEM_Null ){
54340    u.ak.v2 = 2;
54341  }else{
54342    u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
54343  }
54344  if( pOp->opcode==OP_And ){
54345    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
54346    u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
54347  }else{
54348    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
54349    u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
54350  }
54351  pOut = &aMem[pOp->p3];
54352  if( u.ak.v1==2 ){
54353    MemSetTypeFlag(pOut, MEM_Null);
54354  }else{
54355    pOut->u.i = u.ak.v1;
54356    MemSetTypeFlag(pOut, MEM_Int);
54357  }
54358  break;
54359}
54360
54361/* Opcode: Not P1 P2 * * *
54362**
54363** Interpret the value in register P1 as a boolean value.  Store the
54364** boolean complement in register P2.  If the value in register P1 is
54365** NULL, then a NULL is stored in P2.
54366*/
54367case OP_Not: {                /* same as TK_NOT, in1, out2 */
54368  pIn1 = &aMem[pOp->p1];
54369  pOut = &aMem[pOp->p2];
54370  if( pIn1->flags & MEM_Null ){
54371    sqlite3VdbeMemSetNull(pOut);
54372  }else{
54373    sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
54374  }
54375  break;
54376}
54377
54378/* Opcode: BitNot P1 P2 * * *
54379**
54380** Interpret the content of register P1 as an integer.  Store the
54381** ones-complement of the P1 value into register P2.  If P1 holds
54382** a NULL then store a NULL in P2.
54383*/
54384case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
54385  pIn1 = &aMem[pOp->p1];
54386  pOut = &aMem[pOp->p2];
54387  if( pIn1->flags & MEM_Null ){
54388    sqlite3VdbeMemSetNull(pOut);
54389  }else{
54390    sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
54391  }
54392  break;
54393}
54394
54395/* Opcode: If P1 P2 P3 * *
54396**
54397** Jump to P2 if the value in register P1 is true.  The value is
54398** is considered true if it is numeric and non-zero.  If the value
54399** in P1 is NULL then take the jump if P3 is true.
54400*/
54401/* Opcode: IfNot P1 P2 P3 * *
54402**
54403** Jump to P2 if the value in register P1 is False.  The value is
54404** is considered true if it has a numeric value of zero.  If the value
54405** in P1 is NULL then take the jump if P3 is true.
54406*/
54407case OP_If:                 /* jump, in1 */
54408case OP_IfNot: {            /* jump, in1 */
54409#if 0  /* local variables moved into u.al */
54410  int c;
54411#endif /* local variables moved into u.al */
54412  pIn1 = &aMem[pOp->p1];
54413  if( pIn1->flags & MEM_Null ){
54414    u.al.c = pOp->p3;
54415  }else{
54416#ifdef SQLITE_OMIT_FLOATING_POINT
54417    u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
54418#else
54419    u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
54420#endif
54421    if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
54422  }
54423  if( u.al.c ){
54424    pc = pOp->p2-1;
54425  }
54426  break;
54427}
54428
54429/* Opcode: IsNull P1 P2 * * *
54430**
54431** Jump to P2 if the value in register P1 is NULL.
54432*/
54433case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
54434  pIn1 = &aMem[pOp->p1];
54435  if( (pIn1->flags & MEM_Null)!=0 ){
54436    pc = pOp->p2 - 1;
54437  }
54438  break;
54439}
54440
54441/* Opcode: NotNull P1 P2 * * *
54442**
54443** Jump to P2 if the value in register P1 is not NULL.
54444*/
54445case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
54446  pIn1 = &aMem[pOp->p1];
54447  if( (pIn1->flags & MEM_Null)==0 ){
54448    pc = pOp->p2 - 1;
54449  }
54450  break;
54451}
54452
54453/* Opcode: Column P1 P2 P3 P4 P5
54454**
54455** Interpret the data that cursor P1 points to as a structure built using
54456** the MakeRecord instruction.  (See the MakeRecord opcode for additional
54457** information about the format of the data.)  Extract the P2-th column
54458** from this record.  If there are less that (P2+1)
54459** values in the record, extract a NULL.
54460**
54461** The value extracted is stored in register P3.
54462**
54463** If the column contains fewer than P2 fields, then extract a NULL.  Or,
54464** if the P4 argument is a P4_MEM use the value of the P4 argument as
54465** the result.
54466**
54467** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
54468** then the cache of the cursor is reset prior to extracting the column.
54469** The first OP_Column against a pseudo-table after the value of the content
54470** register has changed should have this bit set.
54471*/
54472case OP_Column: {
54473#if 0  /* local variables moved into u.am */
54474  u32 payloadSize;   /* Number of bytes in the record */
54475  i64 payloadSize64; /* Number of bytes in the record */
54476  int p1;            /* P1 value of the opcode */
54477  int p2;            /* column number to retrieve */
54478  VdbeCursor *pC;    /* The VDBE cursor */
54479  char *zRec;        /* Pointer to complete record-data */
54480  BtCursor *pCrsr;   /* The BTree cursor */
54481  u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
54482  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
54483  int nField;        /* number of fields in the record */
54484  int len;           /* The length of the serialized data for the column */
54485  int i;             /* Loop counter */
54486  char *zData;       /* Part of the record being decoded */
54487  Mem *pDest;        /* Where to write the extracted value */
54488  Mem sMem;          /* For storing the record being decoded */
54489  u8 *zIdx;          /* Index into header */
54490  u8 *zEndHdr;       /* Pointer to first byte after the header */
54491  u32 offset;        /* Offset into the data */
54492  u32 szField;       /* Number of bytes in the content of a field */
54493  int szHdr;         /* Size of the header size field at start of record */
54494  int avail;         /* Number of bytes of available data */
54495  Mem *pReg;         /* PseudoTable input register */
54496#endif /* local variables moved into u.am */
54497
54498
54499  u.am.p1 = pOp->p1;
54500  u.am.p2 = pOp->p2;
54501  u.am.pC = 0;
54502  memset(&u.am.sMem, 0, sizeof(u.am.sMem));
54503  assert( u.am.p1<p->nCursor );
54504  assert( pOp->p3>0 && pOp->p3<=p->nMem );
54505  u.am.pDest = &aMem[pOp->p3];
54506  MemSetTypeFlag(u.am.pDest, MEM_Null);
54507  u.am.zRec = 0;
54508
54509  /* This block sets the variable u.am.payloadSize to be the total number of
54510  ** bytes in the record.
54511  **
54512  ** u.am.zRec is set to be the complete text of the record if it is available.
54513  ** The complete record text is always available for pseudo-tables
54514  ** If the record is stored in a cursor, the complete record text
54515  ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
54516  ** If the data is unavailable,  u.am.zRec is set to NULL.
54517  **
54518  ** We also compute the number of columns in the record.  For cursors,
54519  ** the number of columns is stored in the VdbeCursor.nField element.
54520  */
54521  u.am.pC = p->apCsr[u.am.p1];
54522  assert( u.am.pC!=0 );
54523#ifndef SQLITE_OMIT_VIRTUALTABLE
54524  assert( u.am.pC->pVtabCursor==0 );
54525#endif
54526  u.am.pCrsr = u.am.pC->pCursor;
54527  if( u.am.pCrsr!=0 ){
54528    /* The record is stored in a B-Tree */
54529    rc = sqlite3VdbeCursorMoveto(u.am.pC);
54530    if( rc ) goto abort_due_to_error;
54531    if( u.am.pC->nullRow ){
54532      u.am.payloadSize = 0;
54533    }else if( u.am.pC->cacheStatus==p->cacheCtr ){
54534      u.am.payloadSize = u.am.pC->payloadSize;
54535      u.am.zRec = (char*)u.am.pC->aRow;
54536    }else if( u.am.pC->isIndex ){
54537      assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
54538      rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
54539      assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
54540      /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
54541      ** payload size, so it is impossible for u.am.payloadSize64 to be
54542      ** larger than 32 bits. */
54543      assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
54544      u.am.payloadSize = (u32)u.am.payloadSize64;
54545    }else{
54546      assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
54547      rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
54548      assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
54549    }
54550  }else if( u.am.pC->pseudoTableReg>0 ){
54551    u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
54552    assert( u.am.pReg->flags & MEM_Blob );
54553    u.am.payloadSize = u.am.pReg->n;
54554    u.am.zRec = u.am.pReg->z;
54555    u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
54556    assert( u.am.payloadSize==0 || u.am.zRec!=0 );
54557  }else{
54558    /* Consider the row to be NULL */
54559    u.am.payloadSize = 0;
54560  }
54561
54562  /* If u.am.payloadSize is 0, then just store a NULL */
54563  if( u.am.payloadSize==0 ){
54564    assert( u.am.pDest->flags&MEM_Null );
54565    goto op_column_out;
54566  }
54567  assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
54568  if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
54569    goto too_big;
54570  }
54571
54572  u.am.nField = u.am.pC->nField;
54573  assert( u.am.p2<u.am.nField );
54574
54575  /* Read and parse the table header.  Store the results of the parse
54576  ** into the record header cache fields of the cursor.
54577  */
54578  u.am.aType = u.am.pC->aType;
54579  if( u.am.pC->cacheStatus==p->cacheCtr ){
54580    u.am.aOffset = u.am.pC->aOffset;
54581  }else{
54582    assert(u.am.aType);
54583    u.am.avail = 0;
54584    u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
54585    u.am.pC->payloadSize = u.am.payloadSize;
54586    u.am.pC->cacheStatus = p->cacheCtr;
54587
54588    /* Figure out how many bytes are in the header */
54589    if( u.am.zRec ){
54590      u.am.zData = u.am.zRec;
54591    }else{
54592      if( u.am.pC->isIndex ){
54593        u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
54594      }else{
54595        u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
54596      }
54597      /* If KeyFetch()/DataFetch() managed to get the entire payload,
54598      ** save the payload in the u.am.pC->aRow cache.  That will save us from
54599      ** having to make additional calls to fetch the content portion of
54600      ** the record.
54601      */
54602      assert( u.am.avail>=0 );
54603      if( u.am.payloadSize <= (u32)u.am.avail ){
54604        u.am.zRec = u.am.zData;
54605        u.am.pC->aRow = (u8*)u.am.zData;
54606      }else{
54607        u.am.pC->aRow = 0;
54608      }
54609    }
54610    /* The following assert is true in all cases accept when
54611    ** the database file has been corrupted externally.
54612    **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
54613    u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
54614
54615    /* Make sure a corrupt database has not given us an oversize header.
54616    ** Do this now to avoid an oversize memory allocation.
54617    **
54618    ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
54619    ** types use so much data space that there can only be 4096 and 32 of
54620    ** them, respectively.  So the maximum header length results from a
54621    ** 3-byte type for each of the maximum of 32768 columns plus three
54622    ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
54623    */
54624    if( u.am.offset > 98307 ){
54625      rc = SQLITE_CORRUPT_BKPT;
54626      goto op_column_out;
54627    }
54628
54629    /* Compute in u.am.len the number of bytes of data we need to read in order
54630    ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
54631    ** u.am.nField might be significantly less than the true number of columns
54632    ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
54633    ** We want to minimize u.am.len in order to limit the size of the memory
54634    ** allocation, especially if a corrupt database file has caused u.am.offset
54635    ** to be oversized. Offset is limited to 98307 above.  But 98307 might
54636    ** still exceed Robson memory allocation limits on some configurations.
54637    ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
54638    ** will likely be much smaller since u.am.nField will likely be less than
54639    ** 20 or so.  This insures that Robson memory allocation limits are
54640    ** not exceeded even for corrupt database files.
54641    */
54642    u.am.len = u.am.nField*5 + 3;
54643    if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
54644
54645    /* The KeyFetch() or DataFetch() above are fast and will get the entire
54646    ** record header in most cases.  But they will fail to get the complete
54647    ** record header if the record header does not fit on a single page
54648    ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
54649    ** acquire the complete header text.
54650    */
54651    if( !u.am.zRec && u.am.avail<u.am.len ){
54652      u.am.sMem.flags = 0;
54653      u.am.sMem.db = 0;
54654      rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
54655      if( rc!=SQLITE_OK ){
54656        goto op_column_out;
54657      }
54658      u.am.zData = u.am.sMem.z;
54659    }
54660    u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
54661    u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
54662
54663    /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
54664    ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
54665    ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
54666    ** of the record to the start of the data for the u.am.i-th column
54667    */
54668    for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
54669      if( u.am.zIdx<u.am.zEndHdr ){
54670        u.am.aOffset[u.am.i] = u.am.offset;
54671        u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
54672        u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
54673        u.am.offset += u.am.szField;
54674        if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
54675          u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
54676          break;
54677        }
54678      }else{
54679        /* If u.am.i is less that u.am.nField, then there are less fields in this
54680        ** record than SetNumColumns indicated there are columns in the
54681        ** table. Set the u.am.offset for any extra columns not present in
54682        ** the record to 0. This tells code below to store a NULL
54683        ** instead of deserializing a value from the record.
54684        */
54685        u.am.aOffset[u.am.i] = 0;
54686      }
54687    }
54688    sqlite3VdbeMemRelease(&u.am.sMem);
54689    u.am.sMem.flags = MEM_Null;
54690
54691    /* If we have read more header data than was contained in the header,
54692    ** or if the end of the last field appears to be past the end of the
54693    ** record, or if the end of the last field appears to be before the end
54694    ** of the record (when all fields present), then we must be dealing
54695    ** with a corrupt database.
54696    */
54697    if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
54698         || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
54699      rc = SQLITE_CORRUPT_BKPT;
54700      goto op_column_out;
54701    }
54702  }
54703
54704  /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
54705  ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
54706  ** then there are not enough fields in the record to satisfy the
54707  ** request.  In this case, set the value NULL or to P4 if P4 is
54708  ** a pointer to a Mem object.
54709  */
54710  if( u.am.aOffset[u.am.p2] ){
54711    assert( rc==SQLITE_OK );
54712    if( u.am.zRec ){
54713      sqlite3VdbeMemReleaseExternal(u.am.pDest);
54714      sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
54715    }else{
54716      u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
54717      sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
54718      rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
54719      if( rc!=SQLITE_OK ){
54720        goto op_column_out;
54721      }
54722      u.am.zData = u.am.sMem.z;
54723      sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
54724    }
54725    u.am.pDest->enc = encoding;
54726  }else{
54727    if( pOp->p4type==P4_MEM ){
54728      sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
54729    }else{
54730      assert( u.am.pDest->flags&MEM_Null );
54731    }
54732  }
54733
54734  /* If we dynamically allocated space to hold the data (in the
54735  ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
54736  ** dynamically allocated space over to the u.am.pDest structure.
54737  ** This prevents a memory copy.
54738  */
54739  if( u.am.sMem.zMalloc ){
54740    assert( u.am.sMem.z==u.am.sMem.zMalloc );
54741    assert( !(u.am.pDest->flags & MEM_Dyn) );
54742    assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
54743    u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
54744    u.am.pDest->flags |= MEM_Term;
54745    u.am.pDest->z = u.am.sMem.z;
54746    u.am.pDest->zMalloc = u.am.sMem.zMalloc;
54747  }
54748
54749  rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
54750
54751op_column_out:
54752  UPDATE_MAX_BLOBSIZE(u.am.pDest);
54753  REGISTER_TRACE(pOp->p3, u.am.pDest);
54754  break;
54755}
54756
54757/* Opcode: Affinity P1 P2 * P4 *
54758**
54759** Apply affinities to a range of P2 registers starting with P1.
54760**
54761** P4 is a string that is P2 characters long. The nth character of the
54762** string indicates the column affinity that should be used for the nth
54763** memory cell in the range.
54764*/
54765case OP_Affinity: {
54766#if 0  /* local variables moved into u.an */
54767  const char *zAffinity;   /* The affinity to be applied */
54768  char cAff;               /* A single character of affinity */
54769#endif /* local variables moved into u.an */
54770
54771  u.an.zAffinity = pOp->p4.z;
54772  assert( u.an.zAffinity!=0 );
54773  assert( u.an.zAffinity[pOp->p2]==0 );
54774  pIn1 = &aMem[pOp->p1];
54775  while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
54776    assert( pIn1 <= &p->aMem[p->nMem] );
54777    ExpandBlob(pIn1);
54778    applyAffinity(pIn1, u.an.cAff, encoding);
54779    pIn1++;
54780  }
54781  break;
54782}
54783
54784/* Opcode: MakeRecord P1 P2 P3 P4 *
54785**
54786** Convert P2 registers beginning with P1 into a single entry
54787** suitable for use as a data record in a database table or as a key
54788** in an index.  The details of the format are irrelevant as long as
54789** the OP_Column opcode can decode the record later.
54790** Refer to source code comments for the details of the record
54791** format.
54792**
54793** P4 may be a string that is P2 characters long.  The nth character of the
54794** string indicates the column affinity that should be used for the nth
54795** field of the index key.
54796**
54797** The mapping from character to affinity is given by the SQLITE_AFF_
54798** macros defined in sqliteInt.h.
54799**
54800** If P4 is NULL then all index fields have the affinity NONE.
54801*/
54802case OP_MakeRecord: {
54803#if 0  /* local variables moved into u.ao */
54804  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
54805  Mem *pRec;             /* The new record */
54806  u64 nData;             /* Number of bytes of data space */
54807  int nHdr;              /* Number of bytes of header space */
54808  i64 nByte;             /* Data space required for this record */
54809  int nZero;             /* Number of zero bytes at the end of the record */
54810  int nVarint;           /* Number of bytes in a varint */
54811  u32 serial_type;       /* Type field */
54812  Mem *pData0;           /* First field to be combined into the record */
54813  Mem *pLast;            /* Last field of the record */
54814  int nField;            /* Number of fields in the record */
54815  char *zAffinity;       /* The affinity string for the record */
54816  int file_format;       /* File format to use for encoding */
54817  int i;                 /* Space used in zNewRecord[] */
54818  int len;               /* Length of a field */
54819#endif /* local variables moved into u.ao */
54820
54821  /* Assuming the record contains N fields, the record format looks
54822  ** like this:
54823  **
54824  ** ------------------------------------------------------------------------
54825  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
54826  ** ------------------------------------------------------------------------
54827  **
54828  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
54829  ** and so froth.
54830  **
54831  ** Each type field is a varint representing the serial type of the
54832  ** corresponding data element (see sqlite3VdbeSerialType()). The
54833  ** hdr-size field is also a varint which is the offset from the beginning
54834  ** of the record to data0.
54835  */
54836  u.ao.nData = 0;         /* Number of bytes of data space */
54837  u.ao.nHdr = 0;          /* Number of bytes of header space */
54838  u.ao.nByte = 0;         /* Data space required for this record */
54839  u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
54840  u.ao.nField = pOp->p1;
54841  u.ao.zAffinity = pOp->p4.z;
54842  assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
54843  u.ao.pData0 = &aMem[u.ao.nField];
54844  u.ao.nField = pOp->p2;
54845  u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
54846  u.ao.file_format = p->minWriteFileFormat;
54847
54848  /* Loop through the elements that will make up the record to figure
54849  ** out how much space is required for the new record.
54850  */
54851  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
54852    if( u.ao.zAffinity ){
54853      applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
54854    }
54855    if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
54856      sqlite3VdbeMemExpandBlob(u.ao.pRec);
54857    }
54858    u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
54859    u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
54860    u.ao.nData += u.ao.len;
54861    u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
54862    if( u.ao.pRec->flags & MEM_Zero ){
54863      /* Only pure zero-filled BLOBs can be input to this Opcode.
54864      ** We do not allow blobs with a prefix and a zero-filled tail. */
54865      u.ao.nZero += u.ao.pRec->u.nZero;
54866    }else if( u.ao.len ){
54867      u.ao.nZero = 0;
54868    }
54869  }
54870
54871  /* Add the initial header varint and total the size */
54872  u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
54873  if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
54874    u.ao.nHdr++;
54875  }
54876  u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
54877  if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
54878    goto too_big;
54879  }
54880
54881  /* Make sure the output register has a buffer large enough to store
54882  ** the new record. The output register (pOp->p3) is not allowed to
54883  ** be one of the input registers (because the following call to
54884  ** sqlite3VdbeMemGrow() could clobber the value before it is used).
54885  */
54886  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
54887  pOut = &aMem[pOp->p3];
54888  if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
54889    goto no_mem;
54890  }
54891  u.ao.zNewRecord = (u8 *)pOut->z;
54892
54893  /* Write the record */
54894  u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
54895  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
54896    u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
54897    u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
54898  }
54899  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
54900    u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
54901  }
54902  assert( u.ao.i==u.ao.nByte );
54903
54904  assert( pOp->p3>0 && pOp->p3<=p->nMem );
54905  pOut->n = (int)u.ao.nByte;
54906  pOut->flags = MEM_Blob | MEM_Dyn;
54907  pOut->xDel = 0;
54908  if( u.ao.nZero ){
54909    pOut->u.nZero = u.ao.nZero;
54910    pOut->flags |= MEM_Zero;
54911  }
54912  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
54913  REGISTER_TRACE(pOp->p3, pOut);
54914  UPDATE_MAX_BLOBSIZE(pOut);
54915  break;
54916}
54917
54918/* Opcode: Count P1 P2 * * *
54919**
54920** Store the number of entries (an integer value) in the table or index
54921** opened by cursor P1 in register P2
54922*/
54923#ifndef SQLITE_OMIT_BTREECOUNT
54924case OP_Count: {         /* out2-prerelease */
54925#if 0  /* local variables moved into u.ap */
54926  i64 nEntry;
54927  BtCursor *pCrsr;
54928#endif /* local variables moved into u.ap */
54929
54930  u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
54931  if( u.ap.pCrsr ){
54932    rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
54933  }else{
54934    u.ap.nEntry = 0;
54935  }
54936  pOut->u.i = u.ap.nEntry;
54937  break;
54938}
54939#endif
54940
54941/* Opcode: Savepoint P1 * * P4 *
54942**
54943** Open, release or rollback the savepoint named by parameter P4, depending
54944** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
54945** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
54946*/
54947case OP_Savepoint: {
54948#if 0  /* local variables moved into u.aq */
54949  int p1;                         /* Value of P1 operand */
54950  char *zName;                    /* Name of savepoint */
54951  int nName;
54952  Savepoint *pNew;
54953  Savepoint *pSavepoint;
54954  Savepoint *pTmp;
54955  int iSavepoint;
54956  int ii;
54957#endif /* local variables moved into u.aq */
54958
54959  u.aq.p1 = pOp->p1;
54960  u.aq.zName = pOp->p4.z;
54961
54962  /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
54963  ** transaction, then there cannot be any savepoints.
54964  */
54965  assert( db->pSavepoint==0 || db->autoCommit==0 );
54966  assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
54967  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
54968  assert( checkSavepointCount(db) );
54969
54970  if( u.aq.p1==SAVEPOINT_BEGIN ){
54971    if( db->writeVdbeCnt>0 ){
54972      /* A new savepoint cannot be created if there are active write
54973      ** statements (i.e. open read/write incremental blob handles).
54974      */
54975      sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
54976        "SQL statements in progress");
54977      rc = SQLITE_BUSY;
54978    }else{
54979      u.aq.nName = sqlite3Strlen30(u.aq.zName);
54980
54981      /* Create a new savepoint structure. */
54982      u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
54983      if( u.aq.pNew ){
54984        u.aq.pNew->zName = (char *)&u.aq.pNew[1];
54985        memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
54986
54987        /* If there is no open transaction, then mark this as a special
54988        ** "transaction savepoint". */
54989        if( db->autoCommit ){
54990          db->autoCommit = 0;
54991          db->isTransactionSavepoint = 1;
54992        }else{
54993          db->nSavepoint++;
54994        }
54995
54996        /* Link the new savepoint into the database handle's list. */
54997        u.aq.pNew->pNext = db->pSavepoint;
54998        db->pSavepoint = u.aq.pNew;
54999        u.aq.pNew->nDeferredCons = db->nDeferredCons;
55000      }
55001    }
55002  }else{
55003    u.aq.iSavepoint = 0;
55004
55005    /* Find the named savepoint. If there is no such savepoint, then an
55006    ** an error is returned to the user.  */
55007    for(
55008      u.aq.pSavepoint = db->pSavepoint;
55009      u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
55010      u.aq.pSavepoint = u.aq.pSavepoint->pNext
55011    ){
55012      u.aq.iSavepoint++;
55013    }
55014    if( !u.aq.pSavepoint ){
55015      sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
55016      rc = SQLITE_ERROR;
55017    }else if(
55018        db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
55019    ){
55020      /* It is not possible to release (commit) a savepoint if there are
55021      ** active write statements. It is not possible to rollback a savepoint
55022      ** if there are any active statements at all.
55023      */
55024      sqlite3SetString(&p->zErrMsg, db,
55025        "cannot %s savepoint - SQL statements in progress",
55026        (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
55027      );
55028      rc = SQLITE_BUSY;
55029    }else{
55030
55031      /* Determine whether or not this is a transaction savepoint. If so,
55032      ** and this is a RELEASE command, then the current transaction
55033      ** is committed.
55034      */
55035      int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
55036      if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
55037        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
55038          goto vdbe_return;
55039        }
55040        db->autoCommit = 1;
55041        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
55042          p->pc = pc;
55043          db->autoCommit = 0;
55044          p->rc = rc = SQLITE_BUSY;
55045          goto vdbe_return;
55046        }
55047        db->isTransactionSavepoint = 0;
55048        rc = p->rc;
55049      }else{
55050        u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
55051        for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
55052          rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
55053          if( rc!=SQLITE_OK ){
55054            goto abort_due_to_error;
55055          }
55056        }
55057        if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
55058          sqlite3ExpirePreparedStatements(db);
55059          sqlite3ResetInternalSchema(db, 0);
55060        }
55061      }
55062
55063      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
55064      ** savepoints nested inside of the savepoint being operated on. */
55065      while( db->pSavepoint!=u.aq.pSavepoint ){
55066        u.aq.pTmp = db->pSavepoint;
55067        db->pSavepoint = u.aq.pTmp->pNext;
55068        sqlite3DbFree(db, u.aq.pTmp);
55069        db->nSavepoint--;
55070      }
55071
55072      /* If it is a RELEASE, then destroy the savepoint being operated on
55073      ** too. If it is a ROLLBACK TO, then set the number of deferred
55074      ** constraint violations present in the database to the value stored
55075      ** when the savepoint was created.  */
55076      if( u.aq.p1==SAVEPOINT_RELEASE ){
55077        assert( u.aq.pSavepoint==db->pSavepoint );
55078        db->pSavepoint = u.aq.pSavepoint->pNext;
55079        sqlite3DbFree(db, u.aq.pSavepoint);
55080        if( !isTransaction ){
55081          db->nSavepoint--;
55082        }
55083      }else{
55084        db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
55085      }
55086    }
55087  }
55088
55089  break;
55090}
55091
55092/* Opcode: AutoCommit P1 P2 * * *
55093**
55094** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
55095** back any currently active btree transactions. If there are any active
55096** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
55097** there are active writing VMs or active VMs that use shared cache.
55098**
55099** This instruction causes the VM to halt.
55100*/
55101case OP_AutoCommit: {
55102#if 0  /* local variables moved into u.ar */
55103  int desiredAutoCommit;
55104  int iRollback;
55105  int turnOnAC;
55106#endif /* local variables moved into u.ar */
55107
55108  u.ar.desiredAutoCommit = pOp->p1;
55109  u.ar.iRollback = pOp->p2;
55110  u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
55111  assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
55112  assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
55113  assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
55114
55115  if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
55116    /* If this instruction implements a ROLLBACK and other VMs are
55117    ** still running, and a transaction is active, return an error indicating
55118    ** that the other VMs must complete first.
55119    */
55120    sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
55121        "SQL statements in progress");
55122    rc = SQLITE_BUSY;
55123  }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
55124    /* If this instruction implements a COMMIT and other VMs are writing
55125    ** return an error indicating that the other VMs must complete first.
55126    */
55127    sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
55128        "SQL statements in progress");
55129    rc = SQLITE_BUSY;
55130  }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
55131    if( u.ar.iRollback ){
55132      assert( u.ar.desiredAutoCommit==1 );
55133      sqlite3RollbackAll(db);
55134      db->autoCommit = 1;
55135    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
55136      goto vdbe_return;
55137    }else{
55138      db->autoCommit = (u8)u.ar.desiredAutoCommit;
55139      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
55140        p->pc = pc;
55141        db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
55142        p->rc = rc = SQLITE_BUSY;
55143        goto vdbe_return;
55144      }
55145    }
55146    assert( db->nStatement==0 );
55147    sqlite3CloseSavepoints(db);
55148    if( p->rc==SQLITE_OK ){
55149      rc = SQLITE_DONE;
55150    }else{
55151      rc = SQLITE_ERROR;
55152    }
55153    goto vdbe_return;
55154  }else{
55155    sqlite3SetString(&p->zErrMsg, db,
55156        (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
55157        (u.ar.iRollback)?"cannot rollback - no transaction is active":
55158                   "cannot commit - no transaction is active"));
55159
55160    rc = SQLITE_ERROR;
55161  }
55162  break;
55163}
55164
55165/* Opcode: Transaction P1 P2 * * *
55166**
55167** Begin a transaction.  The transaction ends when a Commit or Rollback
55168** opcode is encountered.  Depending on the ON CONFLICT setting, the
55169** transaction might also be rolled back if an error is encountered.
55170**
55171** P1 is the index of the database file on which the transaction is
55172** started.  Index 0 is the main database file and index 1 is the
55173** file used for temporary tables.  Indices of 2 or more are used for
55174** attached databases.
55175**
55176** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
55177** obtained on the database file when a write-transaction is started.  No
55178** other process can start another write transaction while this transaction is
55179** underway.  Starting a write transaction also creates a rollback journal. A
55180** write transaction must be started before any changes can be made to the
55181** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
55182** on the file.
55183**
55184** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
55185** true (this flag is set if the Vdbe may modify more than one row and may
55186** throw an ABORT exception), a statement transaction may also be opened.
55187** More specifically, a statement transaction is opened iff the database
55188** connection is currently not in autocommit mode, or if there are other
55189** active statements. A statement transaction allows the affects of this
55190** VDBE to be rolled back after an error without having to roll back the
55191** entire transaction. If no error is encountered, the statement transaction
55192** will automatically commit when the VDBE halts.
55193**
55194** If P2 is zero, then a read-lock is obtained on the database file.
55195*/
55196case OP_Transaction: {
55197#if 0  /* local variables moved into u.as */
55198  Btree *pBt;
55199#endif /* local variables moved into u.as */
55200
55201  assert( pOp->p1>=0 && pOp->p1<db->nDb );
55202  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
55203  u.as.pBt = db->aDb[pOp->p1].pBt;
55204
55205  if( u.as.pBt ){
55206    rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
55207    if( rc==SQLITE_BUSY ){
55208      p->pc = pc;
55209      p->rc = rc = SQLITE_BUSY;
55210      goto vdbe_return;
55211    }
55212    if( rc!=SQLITE_OK ){
55213      goto abort_due_to_error;
55214    }
55215
55216    if( pOp->p2 && p->usesStmtJournal
55217     && (db->autoCommit==0 || db->activeVdbeCnt>1)
55218    ){
55219      assert( sqlite3BtreeIsInTrans(u.as.pBt) );
55220      if( p->iStatement==0 ){
55221        assert( db->nStatement>=0 && db->nSavepoint>=0 );
55222        db->nStatement++;
55223        p->iStatement = db->nSavepoint + db->nStatement;
55224      }
55225      rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
55226
55227      /* Store the current value of the database handles deferred constraint
55228      ** counter. If the statement transaction needs to be rolled back,
55229      ** the value of this counter needs to be restored too.  */
55230      p->nStmtDefCons = db->nDeferredCons;
55231    }
55232  }
55233  break;
55234}
55235
55236/* Opcode: ReadCookie P1 P2 P3 * *
55237**
55238** Read cookie number P3 from database P1 and write it into register P2.
55239** P3==1 is the schema version.  P3==2 is the database format.
55240** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
55241** the main database file and P1==1 is the database file used to store
55242** temporary tables.
55243**
55244** There must be a read-lock on the database (either a transaction
55245** must be started or there must be an open cursor) before
55246** executing this instruction.
55247*/
55248case OP_ReadCookie: {               /* out2-prerelease */
55249#if 0  /* local variables moved into u.at */
55250  int iMeta;
55251  int iDb;
55252  int iCookie;
55253#endif /* local variables moved into u.at */
55254
55255  u.at.iDb = pOp->p1;
55256  u.at.iCookie = pOp->p3;
55257  assert( pOp->p3<SQLITE_N_BTREE_META );
55258  assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
55259  assert( db->aDb[u.at.iDb].pBt!=0 );
55260  assert( (p->btreeMask & (1<<u.at.iDb))!=0 );
55261
55262  sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
55263  pOut->u.i = u.at.iMeta;
55264  break;
55265}
55266
55267/* Opcode: SetCookie P1 P2 P3 * *
55268**
55269** Write the content of register P3 (interpreted as an integer)
55270** into cookie number P2 of database P1.  P2==1 is the schema version.
55271** P2==2 is the database format. P2==3 is the recommended pager cache
55272** size, and so forth.  P1==0 is the main database file and P1==1 is the
55273** database file used to store temporary tables.
55274**
55275** A transaction must be started before executing this opcode.
55276*/
55277case OP_SetCookie: {       /* in3 */
55278#if 0  /* local variables moved into u.au */
55279  Db *pDb;
55280#endif /* local variables moved into u.au */
55281  assert( pOp->p2<SQLITE_N_BTREE_META );
55282  assert( pOp->p1>=0 && pOp->p1<db->nDb );
55283  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
55284  u.au.pDb = &db->aDb[pOp->p1];
55285  assert( u.au.pDb->pBt!=0 );
55286  pIn3 = &aMem[pOp->p3];
55287  sqlite3VdbeMemIntegerify(pIn3);
55288  /* See note about index shifting on OP_ReadCookie */
55289  rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
55290  if( pOp->p2==BTREE_SCHEMA_VERSION ){
55291    /* When the schema cookie changes, record the new cookie internally */
55292    u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
55293    db->flags |= SQLITE_InternChanges;
55294  }else if( pOp->p2==BTREE_FILE_FORMAT ){
55295    /* Record changes in the file format */
55296    u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
55297  }
55298  if( pOp->p1==1 ){
55299    /* Invalidate all prepared statements whenever the TEMP database
55300    ** schema is changed.  Ticket #1644 */
55301    sqlite3ExpirePreparedStatements(db);
55302    p->expired = 0;
55303  }
55304  break;
55305}
55306
55307/* Opcode: VerifyCookie P1 P2 *
55308**
55309** Check the value of global database parameter number 0 (the
55310** schema version) and make sure it is equal to P2.
55311** P1 is the database number which is 0 for the main database file
55312** and 1 for the file holding temporary tables and some higher number
55313** for auxiliary databases.
55314**
55315** The cookie changes its value whenever the database schema changes.
55316** This operation is used to detect when that the cookie has changed
55317** and that the current process needs to reread the schema.
55318**
55319** Either a transaction needs to have been started or an OP_Open needs
55320** to be executed (to establish a read lock) before this opcode is
55321** invoked.
55322*/
55323case OP_VerifyCookie: {
55324#if 0  /* local variables moved into u.av */
55325  int iMeta;
55326  Btree *pBt;
55327#endif /* local variables moved into u.av */
55328  assert( pOp->p1>=0 && pOp->p1<db->nDb );
55329  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
55330  u.av.pBt = db->aDb[pOp->p1].pBt;
55331  if( u.av.pBt ){
55332    sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
55333  }else{
55334    u.av.iMeta = 0;
55335  }
55336  if( u.av.iMeta!=pOp->p2 ){
55337    sqlite3DbFree(db, p->zErrMsg);
55338    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
55339    /* If the schema-cookie from the database file matches the cookie
55340    ** stored with the in-memory representation of the schema, do
55341    ** not reload the schema from the database file.
55342    **
55343    ** If virtual-tables are in use, this is not just an optimization.
55344    ** Often, v-tables store their data in other SQLite tables, which
55345    ** are queried from within xNext() and other v-table methods using
55346    ** prepared queries. If such a query is out-of-date, we do not want to
55347    ** discard the database schema, as the user code implementing the
55348    ** v-table would have to be ready for the sqlite3_vtab structure itself
55349    ** to be invalidated whenever sqlite3_step() is called from within
55350    ** a v-table method.
55351    */
55352    if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
55353      sqlite3ResetInternalSchema(db, pOp->p1);
55354    }
55355
55356    sqlite3ExpirePreparedStatements(db);
55357    rc = SQLITE_SCHEMA;
55358  }
55359  break;
55360}
55361
55362/* Opcode: OpenRead P1 P2 P3 P4 P5
55363**
55364** Open a read-only cursor for the database table whose root page is
55365** P2 in a database file.  The database file is determined by P3.
55366** P3==0 means the main database, P3==1 means the database used for
55367** temporary tables, and P3>1 means used the corresponding attached
55368** database.  Give the new cursor an identifier of P1.  The P1
55369** values need not be contiguous but all P1 values should be small integers.
55370** It is an error for P1 to be negative.
55371**
55372** If P5!=0 then use the content of register P2 as the root page, not
55373** the value of P2 itself.
55374**
55375** There will be a read lock on the database whenever there is an
55376** open cursor.  If the database was unlocked prior to this instruction
55377** then a read lock is acquired as part of this instruction.  A read
55378** lock allows other processes to read the database but prohibits
55379** any other process from modifying the database.  The read lock is
55380** released when all cursors are closed.  If this instruction attempts
55381** to get a read lock but fails, the script terminates with an
55382** SQLITE_BUSY error code.
55383**
55384** The P4 value may be either an integer (P4_INT32) or a pointer to
55385** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
55386** structure, then said structure defines the content and collating
55387** sequence of the index being opened. Otherwise, if P4 is an integer
55388** value, it is set to the number of columns in the table.
55389**
55390** See also OpenWrite.
55391*/
55392/* Opcode: OpenWrite P1 P2 P3 P4 P5
55393**
55394** Open a read/write cursor named P1 on the table or index whose root
55395** page is P2.  Or if P5!=0 use the content of register P2 to find the
55396** root page.
55397**
55398** The P4 value may be either an integer (P4_INT32) or a pointer to
55399** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
55400** structure, then said structure defines the content and collating
55401** sequence of the index being opened. Otherwise, if P4 is an integer
55402** value, it is set to the number of columns in the table, or to the
55403** largest index of any column of the table that is actually used.
55404**
55405** This instruction works just like OpenRead except that it opens the cursor
55406** in read/write mode.  For a given table, there can be one or more read-only
55407** cursors or a single read/write cursor but not both.
55408**
55409** See also OpenRead.
55410*/
55411case OP_OpenRead:
55412case OP_OpenWrite: {
55413#if 0  /* local variables moved into u.aw */
55414  int nField;
55415  KeyInfo *pKeyInfo;
55416  int p2;
55417  int iDb;
55418  int wrFlag;
55419  Btree *pX;
55420  VdbeCursor *pCur;
55421  Db *pDb;
55422#endif /* local variables moved into u.aw */
55423
55424  if( p->expired ){
55425    rc = SQLITE_ABORT;
55426    break;
55427  }
55428
55429  u.aw.nField = 0;
55430  u.aw.pKeyInfo = 0;
55431  u.aw.p2 = pOp->p2;
55432  u.aw.iDb = pOp->p3;
55433  assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
55434  assert( (p->btreeMask & (1<<u.aw.iDb))!=0 );
55435  u.aw.pDb = &db->aDb[u.aw.iDb];
55436  u.aw.pX = u.aw.pDb->pBt;
55437  assert( u.aw.pX!=0 );
55438  if( pOp->opcode==OP_OpenWrite ){
55439    u.aw.wrFlag = 1;
55440    if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
55441      p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
55442    }
55443  }else{
55444    u.aw.wrFlag = 0;
55445  }
55446  if( pOp->p5 ){
55447    assert( u.aw.p2>0 );
55448    assert( u.aw.p2<=p->nMem );
55449    pIn2 = &aMem[u.aw.p2];
55450    sqlite3VdbeMemIntegerify(pIn2);
55451    u.aw.p2 = (int)pIn2->u.i;
55452    /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
55453    ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
55454    ** If there were a failure, the prepared statement would have halted
55455    ** before reaching this instruction. */
55456    if( NEVER(u.aw.p2<2) ) {
55457      rc = SQLITE_CORRUPT_BKPT;
55458      goto abort_due_to_error;
55459    }
55460  }
55461  if( pOp->p4type==P4_KEYINFO ){
55462    u.aw.pKeyInfo = pOp->p4.pKeyInfo;
55463    u.aw.pKeyInfo->enc = ENC(p->db);
55464    u.aw.nField = u.aw.pKeyInfo->nField+1;
55465  }else if( pOp->p4type==P4_INT32 ){
55466    u.aw.nField = pOp->p4.i;
55467  }
55468  assert( pOp->p1>=0 );
55469  u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
55470  if( u.aw.pCur==0 ) goto no_mem;
55471  u.aw.pCur->nullRow = 1;
55472  rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
55473  u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
55474
55475  /* Since it performs no memory allocation or IO, the only values that
55476  ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
55477  ** SQLITE_EMPTY is only returned when attempting to open the table
55478  ** rooted at page 1 of a zero-byte database.  */
55479  assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
55480  if( rc==SQLITE_EMPTY ){
55481    u.aw.pCur->pCursor = 0;
55482    rc = SQLITE_OK;
55483  }
55484
55485  /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
55486  ** SQLite used to check if the root-page flags were sane at this point
55487  ** and report database corruption if they were not, but this check has
55488  ** since moved into the btree layer.  */
55489  u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
55490  u.aw.pCur->isIndex = !u.aw.pCur->isTable;
55491  break;
55492}
55493
55494/* Opcode: OpenEphemeral P1 P2 * P4 *
55495**
55496** Open a new cursor P1 to a transient table.
55497** The cursor is always opened read/write even if
55498** the main database is read-only.  The transient or virtual
55499** table is deleted automatically when the cursor is closed.
55500**
55501** P2 is the number of columns in the virtual table.
55502** The cursor points to a BTree table if P4==0 and to a BTree index
55503** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
55504** that defines the format of keys in the index.
55505**
55506** This opcode was once called OpenTemp.  But that created
55507** confusion because the term "temp table", might refer either
55508** to a TEMP table at the SQL level, or to a table opened by
55509** this opcode.  Then this opcode was call OpenVirtual.  But
55510** that created confusion with the whole virtual-table idea.
55511*/
55512case OP_OpenEphemeral: {
55513#if 0  /* local variables moved into u.ax */
55514  VdbeCursor *pCx;
55515#endif /* local variables moved into u.ax */
55516  static const int openFlags =
55517      SQLITE_OPEN_READWRITE |
55518      SQLITE_OPEN_CREATE |
55519      SQLITE_OPEN_EXCLUSIVE |
55520      SQLITE_OPEN_DELETEONCLOSE |
55521      SQLITE_OPEN_TRANSIENT_DB;
55522
55523  assert( pOp->p1>=0 );
55524  u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
55525  if( u.ax.pCx==0 ) goto no_mem;
55526  u.ax.pCx->nullRow = 1;
55527  rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
55528                           &u.ax.pCx->pBt);
55529  if( rc==SQLITE_OK ){
55530    rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
55531  }
55532  if( rc==SQLITE_OK ){
55533    /* If a transient index is required, create it by calling
55534    ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
55535    ** opening it. If a transient table is required, just use the
55536    ** automatically created table with root-page 1 (an INTKEY table).
55537    */
55538    if( pOp->p4.pKeyInfo ){
55539      int pgno;
55540      assert( pOp->p4type==P4_KEYINFO );
55541      rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_ZERODATA);
55542      if( rc==SQLITE_OK ){
55543        assert( pgno==MASTER_ROOT+1 );
55544        rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
55545                                (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
55546        u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
55547        u.ax.pCx->pKeyInfo->enc = ENC(p->db);
55548      }
55549      u.ax.pCx->isTable = 0;
55550    }else{
55551      rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
55552      u.ax.pCx->isTable = 1;
55553    }
55554  }
55555  u.ax.pCx->isIndex = !u.ax.pCx->isTable;
55556  break;
55557}
55558
55559/* Opcode: OpenPseudo P1 P2 P3 * *
55560**
55561** Open a new cursor that points to a fake table that contains a single
55562** row of data.  The content of that one row in the content of memory
55563** register P2.  In other words, cursor P1 becomes an alias for the
55564** MEM_Blob content contained in register P2.
55565**
55566** A pseudo-table created by this opcode is used to hold the a single
55567** row output from the sorter so that the row can be decomposed into
55568** individual columns using the OP_Column opcode.  The OP_Column opcode
55569** is the only cursor opcode that works with a pseudo-table.
55570**
55571** P3 is the number of fields in the records that will be stored by
55572** the pseudo-table.
55573*/
55574case OP_OpenPseudo: {
55575#if 0  /* local variables moved into u.ay */
55576  VdbeCursor *pCx;
55577#endif /* local variables moved into u.ay */
55578
55579  assert( pOp->p1>=0 );
55580  u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
55581  if( u.ay.pCx==0 ) goto no_mem;
55582  u.ay.pCx->nullRow = 1;
55583  u.ay.pCx->pseudoTableReg = pOp->p2;
55584  u.ay.pCx->isTable = 1;
55585  u.ay.pCx->isIndex = 0;
55586  break;
55587}
55588
55589/* Opcode: Close P1 * * * *
55590**
55591** Close a cursor previously opened as P1.  If P1 is not
55592** currently open, this instruction is a no-op.
55593*/
55594case OP_Close: {
55595  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55596  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
55597  p->apCsr[pOp->p1] = 0;
55598  break;
55599}
55600
55601/* Opcode: SeekGe P1 P2 P3 P4 *
55602**
55603** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
55604** use the value in register P3 as the key.  If cursor P1 refers
55605** to an SQL index, then P3 is the first in an array of P4 registers
55606** that are used as an unpacked index key.
55607**
55608** Reposition cursor P1 so that  it points to the smallest entry that
55609** is greater than or equal to the key value. If there are no records
55610** greater than or equal to the key and P2 is not zero, then jump to P2.
55611**
55612** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
55613*/
55614/* Opcode: SeekGt P1 P2 P3 P4 *
55615**
55616** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
55617** use the value in register P3 as a key. If cursor P1 refers
55618** to an SQL index, then P3 is the first in an array of P4 registers
55619** that are used as an unpacked index key.
55620**
55621** Reposition cursor P1 so that  it points to the smallest entry that
55622** is greater than the key value. If there are no records greater than
55623** the key and P2 is not zero, then jump to P2.
55624**
55625** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
55626*/
55627/* Opcode: SeekLt P1 P2 P3 P4 *
55628**
55629** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
55630** use the value in register P3 as a key. If cursor P1 refers
55631** to an SQL index, then P3 is the first in an array of P4 registers
55632** that are used as an unpacked index key.
55633**
55634** Reposition cursor P1 so that  it points to the largest entry that
55635** is less than the key value. If there are no records less than
55636** the key and P2 is not zero, then jump to P2.
55637**
55638** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
55639*/
55640/* Opcode: SeekLe P1 P2 P3 P4 *
55641**
55642** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
55643** use the value in register P3 as a key. If cursor P1 refers
55644** to an SQL index, then P3 is the first in an array of P4 registers
55645** that are used as an unpacked index key.
55646**
55647** Reposition cursor P1 so that it points to the largest entry that
55648** is less than or equal to the key value. If there are no records
55649** less than or equal to the key and P2 is not zero, then jump to P2.
55650**
55651** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
55652*/
55653case OP_SeekLt:         /* jump, in3 */
55654case OP_SeekLe:         /* jump, in3 */
55655case OP_SeekGe:         /* jump, in3 */
55656case OP_SeekGt: {       /* jump, in3 */
55657#if 0  /* local variables moved into u.az */
55658  int res;
55659  int oc;
55660  VdbeCursor *pC;
55661  UnpackedRecord r;
55662  int nField;
55663  i64 iKey;      /* The rowid we are to seek to */
55664#endif /* local variables moved into u.az */
55665
55666  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55667  assert( pOp->p2!=0 );
55668  u.az.pC = p->apCsr[pOp->p1];
55669  assert( u.az.pC!=0 );
55670  assert( u.az.pC->pseudoTableReg==0 );
55671  assert( OP_SeekLe == OP_SeekLt+1 );
55672  assert( OP_SeekGe == OP_SeekLt+2 );
55673  assert( OP_SeekGt == OP_SeekLt+3 );
55674  if( u.az.pC->pCursor!=0 ){
55675    u.az.oc = pOp->opcode;
55676    u.az.pC->nullRow = 0;
55677    if( u.az.pC->isTable ){
55678      /* The input value in P3 might be of any type: integer, real, string,
55679      ** blob, or NULL.  But it needs to be an integer before we can do
55680      ** the seek, so covert it. */
55681      pIn3 = &aMem[pOp->p3];
55682      applyNumericAffinity(pIn3);
55683      u.az.iKey = sqlite3VdbeIntValue(pIn3);
55684      u.az.pC->rowidIsValid = 0;
55685
55686      /* If the P3 value could not be converted into an integer without
55687      ** loss of information, then special processing is required... */
55688      if( (pIn3->flags & MEM_Int)==0 ){
55689        if( (pIn3->flags & MEM_Real)==0 ){
55690          /* If the P3 value cannot be converted into any kind of a number,
55691          ** then the seek is not possible, so jump to P2 */
55692          pc = pOp->p2 - 1;
55693          break;
55694        }
55695        /* If we reach this point, then the P3 value must be a floating
55696        ** point number. */
55697        assert( (pIn3->flags & MEM_Real)!=0 );
55698
55699        if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
55700          /* The P3 value is too large in magnitude to be expressed as an
55701          ** integer. */
55702          u.az.res = 1;
55703          if( pIn3->r<0 ){
55704            if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
55705              rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
55706              if( rc!=SQLITE_OK ) goto abort_due_to_error;
55707            }
55708          }else{
55709            if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
55710              rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
55711              if( rc!=SQLITE_OK ) goto abort_due_to_error;
55712            }
55713          }
55714          if( u.az.res ){
55715            pc = pOp->p2 - 1;
55716          }
55717          break;
55718        }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
55719          /* Use the ceiling() function to convert real->int */
55720          if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
55721        }else{
55722          /* Use the floor() function to convert real->int */
55723          assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
55724          if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
55725        }
55726      }
55727      rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
55728      if( rc!=SQLITE_OK ){
55729        goto abort_due_to_error;
55730      }
55731      if( u.az.res==0 ){
55732        u.az.pC->rowidIsValid = 1;
55733        u.az.pC->lastRowid = u.az.iKey;
55734      }
55735    }else{
55736      u.az.nField = pOp->p4.i;
55737      assert( pOp->p4type==P4_INT32 );
55738      assert( u.az.nField>0 );
55739      u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
55740      u.az.r.nField = (u16)u.az.nField;
55741
55742      /* The next line of code computes as follows, only faster:
55743      **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
55744      **     u.az.r.flags = UNPACKED_INCRKEY;
55745      **   }else{
55746      **     u.az.r.flags = 0;
55747      **   }
55748      */
55749      u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
55750      assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
55751      assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
55752      assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
55753      assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
55754
55755      u.az.r.aMem = &aMem[pOp->p3];
55756      ExpandBlob(u.az.r.aMem);
55757      rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
55758      if( rc!=SQLITE_OK ){
55759        goto abort_due_to_error;
55760      }
55761      u.az.pC->rowidIsValid = 0;
55762    }
55763    u.az.pC->deferredMoveto = 0;
55764    u.az.pC->cacheStatus = CACHE_STALE;
55765#ifdef SQLITE_TEST
55766    sqlite3_search_count++;
55767#endif
55768    if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
55769      if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
55770        rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
55771        if( rc!=SQLITE_OK ) goto abort_due_to_error;
55772        u.az.pC->rowidIsValid = 0;
55773      }else{
55774        u.az.res = 0;
55775      }
55776    }else{
55777      assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
55778      if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
55779        rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
55780        if( rc!=SQLITE_OK ) goto abort_due_to_error;
55781        u.az.pC->rowidIsValid = 0;
55782      }else{
55783        /* u.az.res might be negative because the table is empty.  Check to
55784        ** see if this is the case.
55785        */
55786        u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
55787      }
55788    }
55789    assert( pOp->p2>0 );
55790    if( u.az.res ){
55791      pc = pOp->p2 - 1;
55792    }
55793  }else{
55794    /* This happens when attempting to open the sqlite3_master table
55795    ** for read access returns SQLITE_EMPTY. In this case always
55796    ** take the jump (since there are no records in the table).
55797    */
55798    pc = pOp->p2 - 1;
55799  }
55800  break;
55801}
55802
55803/* Opcode: Seek P1 P2 * * *
55804**
55805** P1 is an open table cursor and P2 is a rowid integer.  Arrange
55806** for P1 to move so that it points to the rowid given by P2.
55807**
55808** This is actually a deferred seek.  Nothing actually happens until
55809** the cursor is used to read a record.  That way, if no reads
55810** occur, no unnecessary I/O happens.
55811*/
55812case OP_Seek: {    /* in2 */
55813#if 0  /* local variables moved into u.ba */
55814  VdbeCursor *pC;
55815#endif /* local variables moved into u.ba */
55816
55817  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55818  u.ba.pC = p->apCsr[pOp->p1];
55819  assert( u.ba.pC!=0 );
55820  if( ALWAYS(u.ba.pC->pCursor!=0) ){
55821    assert( u.ba.pC->isTable );
55822    u.ba.pC->nullRow = 0;
55823    pIn2 = &aMem[pOp->p2];
55824    u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
55825    u.ba.pC->rowidIsValid = 0;
55826    u.ba.pC->deferredMoveto = 1;
55827  }
55828  break;
55829}
55830
55831
55832/* Opcode: Found P1 P2 P3 P4 *
55833**
55834** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
55835** P4>0 then register P3 is the first of P4 registers that form an unpacked
55836** record.
55837**
55838** Cursor P1 is on an index btree.  If the record identified by P3 and P4
55839** is a prefix of any entry in P1 then a jump is made to P2 and
55840** P1 is left pointing at the matching entry.
55841*/
55842/* Opcode: NotFound P1 P2 P3 P4 *
55843**
55844** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
55845** P4>0 then register P3 is the first of P4 registers that form an unpacked
55846** record.
55847**
55848** Cursor P1 is on an index btree.  If the record identified by P3 and P4
55849** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
55850** does contain an entry whose prefix matches the P3/P4 record then control
55851** falls through to the next instruction and P1 is left pointing at the
55852** matching entry.
55853**
55854** See also: Found, NotExists, IsUnique
55855*/
55856case OP_NotFound:       /* jump, in3 */
55857case OP_Found: {        /* jump, in3 */
55858#if 0  /* local variables moved into u.bb */
55859  int alreadyExists;
55860  VdbeCursor *pC;
55861  int res;
55862  UnpackedRecord *pIdxKey;
55863  UnpackedRecord r;
55864  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
55865#endif /* local variables moved into u.bb */
55866
55867#ifdef SQLITE_TEST
55868  sqlite3_found_count++;
55869#endif
55870
55871  u.bb.alreadyExists = 0;
55872  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55873  assert( pOp->p4type==P4_INT32 );
55874  u.bb.pC = p->apCsr[pOp->p1];
55875  assert( u.bb.pC!=0 );
55876  pIn3 = &aMem[pOp->p3];
55877  if( ALWAYS(u.bb.pC->pCursor!=0) ){
55878
55879    assert( u.bb.pC->isTable==0 );
55880    if( pOp->p4.i>0 ){
55881      u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
55882      u.bb.r.nField = (u16)pOp->p4.i;
55883      u.bb.r.aMem = pIn3;
55884      u.bb.r.flags = UNPACKED_PREFIX_MATCH;
55885      u.bb.pIdxKey = &u.bb.r;
55886    }else{
55887      assert( pIn3->flags & MEM_Blob );
55888      ExpandBlob(pIn3);
55889      u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
55890                                        u.bb.aTempRec, sizeof(u.bb.aTempRec));
55891      if( u.bb.pIdxKey==0 ){
55892        goto no_mem;
55893      }
55894      u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
55895    }
55896    rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
55897    if( pOp->p4.i==0 ){
55898      sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
55899    }
55900    if( rc!=SQLITE_OK ){
55901      break;
55902    }
55903    u.bb.alreadyExists = (u.bb.res==0);
55904    u.bb.pC->deferredMoveto = 0;
55905    u.bb.pC->cacheStatus = CACHE_STALE;
55906  }
55907  if( pOp->opcode==OP_Found ){
55908    if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
55909  }else{
55910    if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
55911  }
55912  break;
55913}
55914
55915/* Opcode: IsUnique P1 P2 P3 P4 *
55916**
55917** Cursor P1 is open on an index b-tree - that is to say, a btree which
55918** no data and where the key are records generated by OP_MakeRecord with
55919** the list field being the integer ROWID of the entry that the index
55920** entry refers to.
55921**
55922** The P3 register contains an integer record number. Call this record
55923** number R. Register P4 is the first in a set of N contiguous registers
55924** that make up an unpacked index key that can be used with cursor P1.
55925** The value of N can be inferred from the cursor. N includes the rowid
55926** value appended to the end of the index record. This rowid value may
55927** or may not be the same as R.
55928**
55929** If any of the N registers beginning with register P4 contains a NULL
55930** value, jump immediately to P2.
55931**
55932** Otherwise, this instruction checks if cursor P1 contains an entry
55933** where the first (N-1) fields match but the rowid value at the end
55934** of the index entry is not R. If there is no such entry, control jumps
55935** to instruction P2. Otherwise, the rowid of the conflicting index
55936** entry is copied to register P3 and control falls through to the next
55937** instruction.
55938**
55939** See also: NotFound, NotExists, Found
55940*/
55941case OP_IsUnique: {        /* jump, in3 */
55942#if 0  /* local variables moved into u.bc */
55943  u16 ii;
55944  VdbeCursor *pCx;
55945  BtCursor *pCrsr;
55946  u16 nField;
55947  Mem *aMx;
55948  UnpackedRecord r;                  /* B-Tree index search key */
55949  i64 R;                             /* Rowid stored in register P3 */
55950#endif /* local variables moved into u.bc */
55951
55952  pIn3 = &aMem[pOp->p3];
55953  u.bc.aMx = &aMem[pOp->p4.i];
55954  /* Assert that the values of parameters P1 and P4 are in range. */
55955  assert( pOp->p4type==P4_INT32 );
55956  assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
55957  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55958
55959  /* Find the index cursor. */
55960  u.bc.pCx = p->apCsr[pOp->p1];
55961  assert( u.bc.pCx->deferredMoveto==0 );
55962  u.bc.pCx->seekResult = 0;
55963  u.bc.pCx->cacheStatus = CACHE_STALE;
55964  u.bc.pCrsr = u.bc.pCx->pCursor;
55965
55966  /* If any of the values are NULL, take the jump. */
55967  u.bc.nField = u.bc.pCx->pKeyInfo->nField;
55968  for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
55969    if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
55970      pc = pOp->p2 - 1;
55971      u.bc.pCrsr = 0;
55972      break;
55973    }
55974  }
55975  assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
55976
55977  if( u.bc.pCrsr!=0 ){
55978    /* Populate the index search key. */
55979    u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
55980    u.bc.r.nField = u.bc.nField + 1;
55981    u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
55982    u.bc.r.aMem = u.bc.aMx;
55983
55984    /* Extract the value of u.bc.R from register P3. */
55985    sqlite3VdbeMemIntegerify(pIn3);
55986    u.bc.R = pIn3->u.i;
55987
55988    /* Search the B-Tree index. If no conflicting record is found, jump
55989    ** to P2. Otherwise, copy the rowid of the conflicting record to
55990    ** register P3 and fall through to the next instruction.  */
55991    rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
55992    if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
55993      pc = pOp->p2 - 1;
55994    }else{
55995      pIn3->u.i = u.bc.r.rowid;
55996    }
55997  }
55998  break;
55999}
56000
56001/* Opcode: NotExists P1 P2 P3 * *
56002**
56003** Use the content of register P3 as a integer key.  If a record
56004** with that key does not exist in table of P1, then jump to P2.
56005** If the record does exist, then fall thru.  The cursor is left
56006** pointing to the record if it exists.
56007**
56008** The difference between this operation and NotFound is that this
56009** operation assumes the key is an integer and that P1 is a table whereas
56010** NotFound assumes key is a blob constructed from MakeRecord and
56011** P1 is an index.
56012**
56013** See also: Found, NotFound, IsUnique
56014*/
56015case OP_NotExists: {        /* jump, in3 */
56016#if 0  /* local variables moved into u.bd */
56017  VdbeCursor *pC;
56018  BtCursor *pCrsr;
56019  int res;
56020  u64 iKey;
56021#endif /* local variables moved into u.bd */
56022
56023  pIn3 = &aMem[pOp->p3];
56024  assert( pIn3->flags & MEM_Int );
56025  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56026  u.bd.pC = p->apCsr[pOp->p1];
56027  assert( u.bd.pC!=0 );
56028  assert( u.bd.pC->isTable );
56029  assert( u.bd.pC->pseudoTableReg==0 );
56030  u.bd.pCrsr = u.bd.pC->pCursor;
56031  if( u.bd.pCrsr!=0 ){
56032    u.bd.res = 0;
56033    u.bd.iKey = pIn3->u.i;
56034    rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
56035    u.bd.pC->lastRowid = pIn3->u.i;
56036    u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
56037    u.bd.pC->nullRow = 0;
56038    u.bd.pC->cacheStatus = CACHE_STALE;
56039    u.bd.pC->deferredMoveto = 0;
56040    if( u.bd.res!=0 ){
56041      pc = pOp->p2 - 1;
56042      assert( u.bd.pC->rowidIsValid==0 );
56043    }
56044    u.bd.pC->seekResult = u.bd.res;
56045  }else{
56046    /* This happens when an attempt to open a read cursor on the
56047    ** sqlite_master table returns SQLITE_EMPTY.
56048    */
56049    pc = pOp->p2 - 1;
56050    assert( u.bd.pC->rowidIsValid==0 );
56051    u.bd.pC->seekResult = 0;
56052  }
56053  break;
56054}
56055
56056/* Opcode: Sequence P1 P2 * * *
56057**
56058** Find the next available sequence number for cursor P1.
56059** Write the sequence number into register P2.
56060** The sequence number on the cursor is incremented after this
56061** instruction.
56062*/
56063case OP_Sequence: {           /* out2-prerelease */
56064  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56065  assert( p->apCsr[pOp->p1]!=0 );
56066  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
56067  break;
56068}
56069
56070
56071/* Opcode: NewRowid P1 P2 P3 * *
56072**
56073** Get a new integer record number (a.k.a "rowid") used as the key to a table.
56074** The record number is not previously used as a key in the database
56075** table that cursor P1 points to.  The new record number is written
56076** written to register P2.
56077**
56078** If P3>0 then P3 is a register in the root frame of this VDBE that holds
56079** the largest previously generated record number. No new record numbers are
56080** allowed to be less than this value. When this value reaches its maximum,
56081** a SQLITE_FULL error is generated. The P3 register is updated with the '
56082** generated record number. This P3 mechanism is used to help implement the
56083** AUTOINCREMENT feature.
56084*/
56085case OP_NewRowid: {           /* out2-prerelease */
56086#if 0  /* local variables moved into u.be */
56087  i64 v;                 /* The new rowid */
56088  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
56089  int res;               /* Result of an sqlite3BtreeLast() */
56090  int cnt;               /* Counter to limit the number of searches */
56091  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
56092  VdbeFrame *pFrame;     /* Root frame of VDBE */
56093#endif /* local variables moved into u.be */
56094
56095  u.be.v = 0;
56096  u.be.res = 0;
56097  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56098  u.be.pC = p->apCsr[pOp->p1];
56099  assert( u.be.pC!=0 );
56100  if( NEVER(u.be.pC->pCursor==0) ){
56101    /* The zero initialization above is all that is needed */
56102  }else{
56103    /* The next rowid or record number (different terms for the same
56104    ** thing) is obtained in a two-step algorithm.
56105    **
56106    ** First we attempt to find the largest existing rowid and add one
56107    ** to that.  But if the largest existing rowid is already the maximum
56108    ** positive integer, we have to fall through to the second
56109    ** probabilistic algorithm
56110    **
56111    ** The second algorithm is to select a rowid at random and see if
56112    ** it already exists in the table.  If it does not exist, we have
56113    ** succeeded.  If the random rowid does exist, we select a new one
56114    ** and try again, up to 100 times.
56115    */
56116    assert( u.be.pC->isTable );
56117    u.be.cnt = 0;
56118
56119#ifdef SQLITE_32BIT_ROWID
56120#   define MAX_ROWID 0x7fffffff
56121#else
56122    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
56123    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
56124    ** to provide the constant while making all compilers happy.
56125    */
56126#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
56127#endif
56128
56129    if( !u.be.pC->useRandomRowid ){
56130      u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
56131      if( u.be.v==0 ){
56132        rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
56133        if( rc!=SQLITE_OK ){
56134          goto abort_due_to_error;
56135        }
56136        if( u.be.res ){
56137          u.be.v = 1;   /* IMP: R-61914-48074 */
56138        }else{
56139          assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
56140          rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
56141          assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
56142          if( u.be.v==MAX_ROWID ){
56143            u.be.pC->useRandomRowid = 1;
56144          }else{
56145            u.be.v++;   /* IMP: R-29538-34987 */
56146          }
56147        }
56148      }
56149
56150#ifndef SQLITE_OMIT_AUTOINCREMENT
56151      if( pOp->p3 ){
56152        /* Assert that P3 is a valid memory cell. */
56153        assert( pOp->p3>0 );
56154        if( p->pFrame ){
56155          for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
56156          /* Assert that P3 is a valid memory cell. */
56157          assert( pOp->p3<=u.be.pFrame->nMem );
56158          u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
56159        }else{
56160          /* Assert that P3 is a valid memory cell. */
56161          assert( pOp->p3<=p->nMem );
56162          u.be.pMem = &aMem[pOp->p3];
56163        }
56164
56165        REGISTER_TRACE(pOp->p3, u.be.pMem);
56166        sqlite3VdbeMemIntegerify(u.be.pMem);
56167        assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
56168        if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
56169          rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
56170          goto abort_due_to_error;
56171        }
56172        if( u.be.v<u.be.pMem->u.i+1 ){
56173          u.be.v = u.be.pMem->u.i + 1;
56174        }
56175        u.be.pMem->u.i = u.be.v;
56176      }
56177#endif
56178
56179      sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
56180    }
56181    if( u.be.pC->useRandomRowid ){
56182      /* IMPLEMENTATION-OF: R-48598-02938 If the largest ROWID is equal to the
56183      ** largest possible integer (9223372036854775807) then the database
56184      ** engine starts picking candidate ROWIDs at random until it finds one
56185      ** that is not previously used.
56186      */
56187      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
56188                             ** an AUTOINCREMENT table. */
56189      u.be.v = db->lastRowid;
56190      u.be.cnt = 0;
56191      do{
56192        if( u.be.cnt==0 && (u.be.v&0xffffff)==u.be.v ){
56193          u.be.v++;
56194        }else{
56195          sqlite3_randomness(sizeof(u.be.v), &u.be.v);
56196          if( u.be.cnt<5 ) u.be.v &= 0xffffff;
56197        }
56198        rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v, 0, &u.be.res);
56199        u.be.cnt++;
56200      }while( u.be.cnt<100 && rc==SQLITE_OK && u.be.res==0 );
56201      if( rc==SQLITE_OK && u.be.res==0 ){
56202        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
56203        goto abort_due_to_error;
56204      }
56205    }
56206    u.be.pC->rowidIsValid = 0;
56207    u.be.pC->deferredMoveto = 0;
56208    u.be.pC->cacheStatus = CACHE_STALE;
56209  }
56210  pOut->u.i = u.be.v;
56211  break;
56212}
56213
56214/* Opcode: Insert P1 P2 P3 P4 P5
56215**
56216** Write an entry into the table of cursor P1.  A new entry is
56217** created if it doesn't already exist or the data for an existing
56218** entry is overwritten.  The data is the value MEM_Blob stored in register
56219** number P2. The key is stored in register P3. The key must
56220** be a MEM_Int.
56221**
56222** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
56223** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
56224** then rowid is stored for subsequent return by the
56225** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
56226**
56227** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
56228** the last seek operation (OP_NotExists) was a success, then this
56229** operation will not attempt to find the appropriate row before doing
56230** the insert but will instead overwrite the row that the cursor is
56231** currently pointing to.  Presumably, the prior OP_NotExists opcode
56232** has already positioned the cursor correctly.  This is an optimization
56233** that boosts performance by avoiding redundant seeks.
56234**
56235** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
56236** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
56237** is part of an INSERT operation.  The difference is only important to
56238** the update hook.
56239**
56240** Parameter P4 may point to a string containing the table-name, or
56241** may be NULL. If it is not NULL, then the update-hook
56242** (sqlite3.xUpdateCallback) is invoked following a successful insert.
56243**
56244** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
56245** allocated, then ownership of P2 is transferred to the pseudo-cursor
56246** and register P2 becomes ephemeral.  If the cursor is changed, the
56247** value of register P2 will then change.  Make sure this does not
56248** cause any problems.)
56249**
56250** This instruction only works on tables.  The equivalent instruction
56251** for indices is OP_IdxInsert.
56252*/
56253/* Opcode: InsertInt P1 P2 P3 P4 P5
56254**
56255** This works exactly like OP_Insert except that the key is the
56256** integer value P3, not the value of the integer stored in register P3.
56257*/
56258case OP_Insert:
56259case OP_InsertInt: {
56260#if 0  /* local variables moved into u.bf */
56261  Mem *pData;       /* MEM cell holding data for the record to be inserted */
56262  Mem *pKey;        /* MEM cell holding key  for the record */
56263  i64 iKey;         /* The integer ROWID or key for the record to be inserted */
56264  VdbeCursor *pC;   /* Cursor to table into which insert is written */
56265  int nZero;        /* Number of zero-bytes to append */
56266  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
56267  const char *zDb;  /* database name - used by the update hook */
56268  const char *zTbl; /* Table name - used by the opdate hook */
56269  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
56270#endif /* local variables moved into u.bf */
56271
56272  u.bf.pData = &aMem[pOp->p2];
56273  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56274  u.bf.pC = p->apCsr[pOp->p1];
56275  assert( u.bf.pC!=0 );
56276  assert( u.bf.pC->pCursor!=0 );
56277  assert( u.bf.pC->pseudoTableReg==0 );
56278  assert( u.bf.pC->isTable );
56279  REGISTER_TRACE(pOp->p2, u.bf.pData);
56280
56281  if( pOp->opcode==OP_Insert ){
56282    u.bf.pKey = &aMem[pOp->p3];
56283    assert( u.bf.pKey->flags & MEM_Int );
56284    REGISTER_TRACE(pOp->p3, u.bf.pKey);
56285    u.bf.iKey = u.bf.pKey->u.i;
56286  }else{
56287    assert( pOp->opcode==OP_InsertInt );
56288    u.bf.iKey = pOp->p3;
56289  }
56290
56291  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
56292  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
56293  if( u.bf.pData->flags & MEM_Null ){
56294    u.bf.pData->z = 0;
56295    u.bf.pData->n = 0;
56296  }else{
56297    assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
56298  }
56299  u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
56300  if( u.bf.pData->flags & MEM_Zero ){
56301    u.bf.nZero = u.bf.pData->u.nZero;
56302  }else{
56303    u.bf.nZero = 0;
56304  }
56305  sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
56306  rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
56307                          u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
56308                          pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
56309  );
56310  u.bf.pC->rowidIsValid = 0;
56311  u.bf.pC->deferredMoveto = 0;
56312  u.bf.pC->cacheStatus = CACHE_STALE;
56313
56314  /* Invoke the update-hook if required. */
56315  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
56316    u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
56317    u.bf.zTbl = pOp->p4.z;
56318    u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
56319    assert( u.bf.pC->isTable );
56320    db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
56321    assert( u.bf.pC->iDb>=0 );
56322  }
56323  break;
56324}
56325
56326/* Opcode: Delete P1 P2 * P4 *
56327**
56328** Delete the record at which the P1 cursor is currently pointing.
56329**
56330** The cursor will be left pointing at either the next or the previous
56331** record in the table. If it is left pointing at the next record, then
56332** the next Next instruction will be a no-op.  Hence it is OK to delete
56333** a record from within an Next loop.
56334**
56335** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
56336** incremented (otherwise not).
56337**
56338** P1 must not be pseudo-table.  It has to be a real table with
56339** multiple rows.
56340**
56341** If P4 is not NULL, then it is the name of the table that P1 is
56342** pointing to.  The update hook will be invoked, if it exists.
56343** If P4 is not NULL then the P1 cursor must have been positioned
56344** using OP_NotFound prior to invoking this opcode.
56345*/
56346case OP_Delete: {
56347#if 0  /* local variables moved into u.bg */
56348  i64 iKey;
56349  VdbeCursor *pC;
56350#endif /* local variables moved into u.bg */
56351
56352  u.bg.iKey = 0;
56353  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56354  u.bg.pC = p->apCsr[pOp->p1];
56355  assert( u.bg.pC!=0 );
56356  assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
56357
56358  /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
56359  ** row being deleted.
56360  */
56361  if( db->xUpdateCallback && pOp->p4.z ){
56362    assert( u.bg.pC->isTable );
56363    assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
56364    u.bg.iKey = u.bg.pC->lastRowid;
56365  }
56366
56367  /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
56368  ** OP_Column on the same table without any intervening operations that
56369  ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
56370  ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
56371  ** below is always a no-op and cannot fail.  We will run it anyhow, though,
56372  ** to guard against future changes to the code generator.
56373  **/
56374  assert( u.bg.pC->deferredMoveto==0 );
56375  rc = sqlite3VdbeCursorMoveto(u.bg.pC);
56376  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
56377
56378  sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
56379  rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
56380  u.bg.pC->cacheStatus = CACHE_STALE;
56381
56382  /* Invoke the update-hook if required. */
56383  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
56384    const char *zDb = db->aDb[u.bg.pC->iDb].zName;
56385    const char *zTbl = pOp->p4.z;
56386    db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
56387    assert( u.bg.pC->iDb>=0 );
56388  }
56389  if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
56390  break;
56391}
56392/* Opcode: ResetCount * * * * *
56393**
56394** The value of the change counter is copied to the database handle
56395** change counter (returned by subsequent calls to sqlite3_changes()).
56396** Then the VMs internal change counter resets to 0.
56397** This is used by trigger programs.
56398*/
56399case OP_ResetCount: {
56400  sqlite3VdbeSetChanges(db, p->nChange);
56401  p->nChange = 0;
56402  break;
56403}
56404
56405/* Opcode: RowData P1 P2 * * *
56406**
56407** Write into register P2 the complete row data for cursor P1.
56408** There is no interpretation of the data.
56409** It is just copied onto the P2 register exactly as
56410** it is found in the database file.
56411**
56412** If the P1 cursor must be pointing to a valid row (not a NULL row)
56413** of a real table, not a pseudo-table.
56414*/
56415/* Opcode: RowKey P1 P2 * * *
56416**
56417** Write into register P2 the complete row key for cursor P1.
56418** There is no interpretation of the data.
56419** The key is copied onto the P3 register exactly as
56420** it is found in the database file.
56421**
56422** If the P1 cursor must be pointing to a valid row (not a NULL row)
56423** of a real table, not a pseudo-table.
56424*/
56425case OP_RowKey:
56426case OP_RowData: {
56427#if 0  /* local variables moved into u.bh */
56428  VdbeCursor *pC;
56429  BtCursor *pCrsr;
56430  u32 n;
56431  i64 n64;
56432#endif /* local variables moved into u.bh */
56433
56434  pOut = &aMem[pOp->p2];
56435
56436  /* Note that RowKey and RowData are really exactly the same instruction */
56437  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56438  u.bh.pC = p->apCsr[pOp->p1];
56439  assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
56440  assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
56441  assert( u.bh.pC!=0 );
56442  assert( u.bh.pC->nullRow==0 );
56443  assert( u.bh.pC->pseudoTableReg==0 );
56444  assert( u.bh.pC->pCursor!=0 );
56445  u.bh.pCrsr = u.bh.pC->pCursor;
56446  assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
56447
56448  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
56449  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
56450  ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
56451  ** a no-op and can never fail.  But we leave it in place as a safety.
56452  */
56453  assert( u.bh.pC->deferredMoveto==0 );
56454  rc = sqlite3VdbeCursorMoveto(u.bh.pC);
56455  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
56456
56457  if( u.bh.pC->isIndex ){
56458    assert( !u.bh.pC->isTable );
56459    rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
56460    assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
56461    if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
56462      goto too_big;
56463    }
56464    u.bh.n = (u32)u.bh.n64;
56465  }else{
56466    rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
56467    assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
56468    if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
56469      goto too_big;
56470    }
56471  }
56472  if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
56473    goto no_mem;
56474  }
56475  pOut->n = u.bh.n;
56476  MemSetTypeFlag(pOut, MEM_Blob);
56477  if( u.bh.pC->isIndex ){
56478    rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
56479  }else{
56480    rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
56481  }
56482  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
56483  UPDATE_MAX_BLOBSIZE(pOut);
56484  break;
56485}
56486
56487/* Opcode: Rowid P1 P2 * * *
56488**
56489** Store in register P2 an integer which is the key of the table entry that
56490** P1 is currently point to.
56491**
56492** P1 can be either an ordinary table or a virtual table.  There used to
56493** be a separate OP_VRowid opcode for use with virtual tables, but this
56494** one opcode now works for both table types.
56495*/
56496case OP_Rowid: {                 /* out2-prerelease */
56497#if 0  /* local variables moved into u.bi */
56498  VdbeCursor *pC;
56499  i64 v;
56500  sqlite3_vtab *pVtab;
56501  const sqlite3_module *pModule;
56502#endif /* local variables moved into u.bi */
56503
56504  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56505  u.bi.pC = p->apCsr[pOp->p1];
56506  assert( u.bi.pC!=0 );
56507  assert( u.bi.pC->pseudoTableReg==0 );
56508  if( u.bi.pC->nullRow ){
56509    pOut->flags = MEM_Null;
56510    break;
56511  }else if( u.bi.pC->deferredMoveto ){
56512    u.bi.v = u.bi.pC->movetoTarget;
56513#ifndef SQLITE_OMIT_VIRTUALTABLE
56514  }else if( u.bi.pC->pVtabCursor ){
56515    u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
56516    u.bi.pModule = u.bi.pVtab->pModule;
56517    assert( u.bi.pModule->xRowid );
56518    rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
56519    sqlite3DbFree(db, p->zErrMsg);
56520    p->zErrMsg = u.bi.pVtab->zErrMsg;
56521    u.bi.pVtab->zErrMsg = 0;
56522#endif /* SQLITE_OMIT_VIRTUALTABLE */
56523  }else{
56524    assert( u.bi.pC->pCursor!=0 );
56525    rc = sqlite3VdbeCursorMoveto(u.bi.pC);
56526    if( rc ) goto abort_due_to_error;
56527    if( u.bi.pC->rowidIsValid ){
56528      u.bi.v = u.bi.pC->lastRowid;
56529    }else{
56530      rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
56531      assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
56532    }
56533  }
56534  pOut->u.i = u.bi.v;
56535  break;
56536}
56537
56538/* Opcode: NullRow P1 * * * *
56539**
56540** Move the cursor P1 to a null row.  Any OP_Column operations
56541** that occur while the cursor is on the null row will always
56542** write a NULL.
56543*/
56544case OP_NullRow: {
56545#if 0  /* local variables moved into u.bj */
56546  VdbeCursor *pC;
56547#endif /* local variables moved into u.bj */
56548
56549  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56550  u.bj.pC = p->apCsr[pOp->p1];
56551  assert( u.bj.pC!=0 );
56552  u.bj.pC->nullRow = 1;
56553  u.bj.pC->rowidIsValid = 0;
56554  if( u.bj.pC->pCursor ){
56555    sqlite3BtreeClearCursor(u.bj.pC->pCursor);
56556  }
56557  break;
56558}
56559
56560/* Opcode: Last P1 P2 * * *
56561**
56562** The next use of the Rowid or Column or Next instruction for P1
56563** will refer to the last entry in the database table or index.
56564** If the table or index is empty and P2>0, then jump immediately to P2.
56565** If P2 is 0 or if the table or index is not empty, fall through
56566** to the following instruction.
56567*/
56568case OP_Last: {        /* jump */
56569#if 0  /* local variables moved into u.bk */
56570  VdbeCursor *pC;
56571  BtCursor *pCrsr;
56572  int res;
56573#endif /* local variables moved into u.bk */
56574
56575  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56576  u.bk.pC = p->apCsr[pOp->p1];
56577  assert( u.bk.pC!=0 );
56578  u.bk.pCrsr = u.bk.pC->pCursor;
56579  if( u.bk.pCrsr==0 ){
56580    u.bk.res = 1;
56581  }else{
56582    rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
56583  }
56584  u.bk.pC->nullRow = (u8)u.bk.res;
56585  u.bk.pC->deferredMoveto = 0;
56586  u.bk.pC->rowidIsValid = 0;
56587  u.bk.pC->cacheStatus = CACHE_STALE;
56588  if( pOp->p2>0 && u.bk.res ){
56589    pc = pOp->p2 - 1;
56590  }
56591  break;
56592}
56593
56594
56595/* Opcode: Sort P1 P2 * * *
56596**
56597** This opcode does exactly the same thing as OP_Rewind except that
56598** it increments an undocumented global variable used for testing.
56599**
56600** Sorting is accomplished by writing records into a sorting index,
56601** then rewinding that index and playing it back from beginning to
56602** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
56603** rewinding so that the global variable will be incremented and
56604** regression tests can determine whether or not the optimizer is
56605** correctly optimizing out sorts.
56606*/
56607case OP_Sort: {        /* jump */
56608#ifdef SQLITE_TEST
56609  sqlite3_sort_count++;
56610  sqlite3_search_count--;
56611#endif
56612  p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
56613  /* Fall through into OP_Rewind */
56614}
56615/* Opcode: Rewind P1 P2 * * *
56616**
56617** The next use of the Rowid or Column or Next instruction for P1
56618** will refer to the first entry in the database table or index.
56619** If the table or index is empty and P2>0, then jump immediately to P2.
56620** If P2 is 0 or if the table or index is not empty, fall through
56621** to the following instruction.
56622*/
56623case OP_Rewind: {        /* jump */
56624#if 0  /* local variables moved into u.bl */
56625  VdbeCursor *pC;
56626  BtCursor *pCrsr;
56627  int res;
56628#endif /* local variables moved into u.bl */
56629
56630  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56631  u.bl.pC = p->apCsr[pOp->p1];
56632  assert( u.bl.pC!=0 );
56633  if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
56634    rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
56635    u.bl.pC->atFirst = u.bl.res==0 ?1:0;
56636    u.bl.pC->deferredMoveto = 0;
56637    u.bl.pC->cacheStatus = CACHE_STALE;
56638    u.bl.pC->rowidIsValid = 0;
56639  }else{
56640    u.bl.res = 1;
56641  }
56642  u.bl.pC->nullRow = (u8)u.bl.res;
56643  assert( pOp->p2>0 && pOp->p2<p->nOp );
56644  if( u.bl.res ){
56645    pc = pOp->p2 - 1;
56646  }
56647  break;
56648}
56649
56650/* Opcode: Next P1 P2 * * *
56651**
56652** Advance cursor P1 so that it points to the next key/data pair in its
56653** table or index.  If there are no more key/value pairs then fall through
56654** to the following instruction.  But if the cursor advance was successful,
56655** jump immediately to P2.
56656**
56657** The P1 cursor must be for a real table, not a pseudo-table.
56658**
56659** See also: Prev
56660*/
56661/* Opcode: Prev P1 P2 * * *
56662**
56663** Back up cursor P1 so that it points to the previous key/data pair in its
56664** table or index.  If there is no previous key/value pairs then fall through
56665** to the following instruction.  But if the cursor backup was successful,
56666** jump immediately to P2.
56667**
56668** The P1 cursor must be for a real table, not a pseudo-table.
56669*/
56670case OP_Prev:          /* jump */
56671case OP_Next: {        /* jump */
56672#if 0  /* local variables moved into u.bm */
56673  VdbeCursor *pC;
56674  BtCursor *pCrsr;
56675  int res;
56676#endif /* local variables moved into u.bm */
56677
56678  CHECK_FOR_INTERRUPT;
56679  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56680  u.bm.pC = p->apCsr[pOp->p1];
56681  if( u.bm.pC==0 ){
56682    break;  /* See ticket #2273 */
56683  }
56684  u.bm.pCrsr = u.bm.pC->pCursor;
56685  if( u.bm.pCrsr==0 ){
56686    u.bm.pC->nullRow = 1;
56687    break;
56688  }
56689  u.bm.res = 1;
56690  assert( u.bm.pC->deferredMoveto==0 );
56691  rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
56692                              sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
56693  u.bm.pC->nullRow = (u8)u.bm.res;
56694  u.bm.pC->cacheStatus = CACHE_STALE;
56695  if( u.bm.res==0 ){
56696    pc = pOp->p2 - 1;
56697    if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
56698#ifdef SQLITE_TEST
56699    sqlite3_search_count++;
56700#endif
56701  }
56702  u.bm.pC->rowidIsValid = 0;
56703  break;
56704}
56705
56706/* Opcode: IdxInsert P1 P2 P3 * P5
56707**
56708** Register P2 holds a SQL index key made using the
56709** MakeRecord instructions.  This opcode writes that key
56710** into the index P1.  Data for the entry is nil.
56711**
56712** P3 is a flag that provides a hint to the b-tree layer that this
56713** insert is likely to be an append.
56714**
56715** This instruction only works for indices.  The equivalent instruction
56716** for tables is OP_Insert.
56717*/
56718case OP_IdxInsert: {        /* in2 */
56719#if 0  /* local variables moved into u.bn */
56720  VdbeCursor *pC;
56721  BtCursor *pCrsr;
56722  int nKey;
56723  const char *zKey;
56724#endif /* local variables moved into u.bn */
56725
56726  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56727  u.bn.pC = p->apCsr[pOp->p1];
56728  assert( u.bn.pC!=0 );
56729  pIn2 = &aMem[pOp->p2];
56730  assert( pIn2->flags & MEM_Blob );
56731  u.bn.pCrsr = u.bn.pC->pCursor;
56732  if( ALWAYS(u.bn.pCrsr!=0) ){
56733    assert( u.bn.pC->isTable==0 );
56734    rc = ExpandBlob(pIn2);
56735    if( rc==SQLITE_OK ){
56736      u.bn.nKey = pIn2->n;
56737      u.bn.zKey = pIn2->z;
56738      rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
56739          ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
56740      );
56741      assert( u.bn.pC->deferredMoveto==0 );
56742      u.bn.pC->cacheStatus = CACHE_STALE;
56743    }
56744  }
56745  break;
56746}
56747
56748/* Opcode: IdxDelete P1 P2 P3 * *
56749**
56750** The content of P3 registers starting at register P2 form
56751** an unpacked index key. This opcode removes that entry from the
56752** index opened by cursor P1.
56753*/
56754case OP_IdxDelete: {
56755#if 0  /* local variables moved into u.bo */
56756  VdbeCursor *pC;
56757  BtCursor *pCrsr;
56758  int res;
56759  UnpackedRecord r;
56760#endif /* local variables moved into u.bo */
56761
56762  assert( pOp->p3>0 );
56763  assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
56764  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56765  u.bo.pC = p->apCsr[pOp->p1];
56766  assert( u.bo.pC!=0 );
56767  u.bo.pCrsr = u.bo.pC->pCursor;
56768  if( ALWAYS(u.bo.pCrsr!=0) ){
56769    u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
56770    u.bo.r.nField = (u16)pOp->p3;
56771    u.bo.r.flags = 0;
56772    u.bo.r.aMem = &aMem[pOp->p2];
56773    rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
56774    if( rc==SQLITE_OK && u.bo.res==0 ){
56775      rc = sqlite3BtreeDelete(u.bo.pCrsr);
56776    }
56777    assert( u.bo.pC->deferredMoveto==0 );
56778    u.bo.pC->cacheStatus = CACHE_STALE;
56779  }
56780  break;
56781}
56782
56783/* Opcode: IdxRowid P1 P2 * * *
56784**
56785** Write into register P2 an integer which is the last entry in the record at
56786** the end of the index key pointed to by cursor P1.  This integer should be
56787** the rowid of the table entry to which this index entry points.
56788**
56789** See also: Rowid, MakeRecord.
56790*/
56791case OP_IdxRowid: {              /* out2-prerelease */
56792#if 0  /* local variables moved into u.bp */
56793  BtCursor *pCrsr;
56794  VdbeCursor *pC;
56795  i64 rowid;
56796#endif /* local variables moved into u.bp */
56797
56798  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56799  u.bp.pC = p->apCsr[pOp->p1];
56800  assert( u.bp.pC!=0 );
56801  u.bp.pCrsr = u.bp.pC->pCursor;
56802  pOut->flags = MEM_Null;
56803  if( ALWAYS(u.bp.pCrsr!=0) ){
56804    rc = sqlite3VdbeCursorMoveto(u.bp.pC);
56805    if( NEVER(rc) ) goto abort_due_to_error;
56806    assert( u.bp.pC->deferredMoveto==0 );
56807    assert( u.bp.pC->isTable==0 );
56808    if( !u.bp.pC->nullRow ){
56809      rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
56810      if( rc!=SQLITE_OK ){
56811        goto abort_due_to_error;
56812      }
56813      pOut->u.i = u.bp.rowid;
56814      pOut->flags = MEM_Int;
56815    }
56816  }
56817  break;
56818}
56819
56820/* Opcode: IdxGE P1 P2 P3 P4 P5
56821**
56822** The P4 register values beginning with P3 form an unpacked index
56823** key that omits the ROWID.  Compare this key value against the index
56824** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
56825**
56826** If the P1 index entry is greater than or equal to the key value
56827** then jump to P2.  Otherwise fall through to the next instruction.
56828**
56829** If P5 is non-zero then the key value is increased by an epsilon
56830** prior to the comparison.  This make the opcode work like IdxGT except
56831** that if the key from register P3 is a prefix of the key in the cursor,
56832** the result is false whereas it would be true with IdxGT.
56833*/
56834/* Opcode: IdxLT P1 P2 P3 * P5
56835**
56836** The P4 register values beginning with P3 form an unpacked index
56837** key that omits the ROWID.  Compare this key value against the index
56838** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
56839**
56840** If the P1 index entry is less than the key value then jump to P2.
56841** Otherwise fall through to the next instruction.
56842**
56843** If P5 is non-zero then the key value is increased by an epsilon prior
56844** to the comparison.  This makes the opcode work like IdxLE.
56845*/
56846case OP_IdxLT:          /* jump */
56847case OP_IdxGE: {        /* jump */
56848#if 0  /* local variables moved into u.bq */
56849  VdbeCursor *pC;
56850  int res;
56851  UnpackedRecord r;
56852#endif /* local variables moved into u.bq */
56853
56854  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56855  u.bq.pC = p->apCsr[pOp->p1];
56856  assert( u.bq.pC!=0 );
56857  if( ALWAYS(u.bq.pC->pCursor!=0) ){
56858    assert( u.bq.pC->deferredMoveto==0 );
56859    assert( pOp->p5==0 || pOp->p5==1 );
56860    assert( pOp->p4type==P4_INT32 );
56861    u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
56862    u.bq.r.nField = (u16)pOp->p4.i;
56863    if( pOp->p5 ){
56864      u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
56865    }else{
56866      u.bq.r.flags = UNPACKED_IGNORE_ROWID;
56867    }
56868    u.bq.r.aMem = &aMem[pOp->p3];
56869    rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
56870    if( pOp->opcode==OP_IdxLT ){
56871      u.bq.res = -u.bq.res;
56872    }else{
56873      assert( pOp->opcode==OP_IdxGE );
56874      u.bq.res++;
56875    }
56876    if( u.bq.res>0 ){
56877      pc = pOp->p2 - 1 ;
56878    }
56879  }
56880  break;
56881}
56882
56883/* Opcode: Destroy P1 P2 P3 * *
56884**
56885** Delete an entire database table or index whose root page in the database
56886** file is given by P1.
56887**
56888** The table being destroyed is in the main database file if P3==0.  If
56889** P3==1 then the table to be clear is in the auxiliary database file
56890** that is used to store tables create using CREATE TEMPORARY TABLE.
56891**
56892** If AUTOVACUUM is enabled then it is possible that another root page
56893** might be moved into the newly deleted root page in order to keep all
56894** root pages contiguous at the beginning of the database.  The former
56895** value of the root page that moved - its value before the move occurred -
56896** is stored in register P2.  If no page
56897** movement was required (because the table being dropped was already
56898** the last one in the database) then a zero is stored in register P2.
56899** If AUTOVACUUM is disabled then a zero is stored in register P2.
56900**
56901** See also: Clear
56902*/
56903case OP_Destroy: {     /* out2-prerelease */
56904#if 0  /* local variables moved into u.br */
56905  int iMoved;
56906  int iCnt;
56907  Vdbe *pVdbe;
56908  int iDb;
56909#endif /* local variables moved into u.br */
56910#ifndef SQLITE_OMIT_VIRTUALTABLE
56911  u.br.iCnt = 0;
56912  for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
56913    if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
56914      u.br.iCnt++;
56915    }
56916  }
56917#else
56918  u.br.iCnt = db->activeVdbeCnt;
56919#endif
56920  pOut->flags = MEM_Null;
56921  if( u.br.iCnt>1 ){
56922    rc = SQLITE_LOCKED;
56923    p->errorAction = OE_Abort;
56924  }else{
56925    u.br.iDb = pOp->p3;
56926    assert( u.br.iCnt==1 );
56927    assert( (p->btreeMask & (1<<u.br.iDb))!=0 );
56928    rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
56929    pOut->flags = MEM_Int;
56930    pOut->u.i = u.br.iMoved;
56931#ifndef SQLITE_OMIT_AUTOVACUUM
56932    if( rc==SQLITE_OK && u.br.iMoved!=0 ){
56933      sqlite3RootPageMoved(&db->aDb[u.br.iDb], u.br.iMoved, pOp->p1);
56934      resetSchemaOnFault = 1;
56935    }
56936#endif
56937  }
56938  break;
56939}
56940
56941/* Opcode: Clear P1 P2 P3
56942**
56943** Delete all contents of the database table or index whose root page
56944** in the database file is given by P1.  But, unlike Destroy, do not
56945** remove the table or index from the database file.
56946**
56947** The table being clear is in the main database file if P2==0.  If
56948** P2==1 then the table to be clear is in the auxiliary database file
56949** that is used to store tables create using CREATE TEMPORARY TABLE.
56950**
56951** If the P3 value is non-zero, then the table referred to must be an
56952** intkey table (an SQL table, not an index). In this case the row change
56953** count is incremented by the number of rows in the table being cleared.
56954** If P3 is greater than zero, then the value stored in register P3 is
56955** also incremented by the number of rows in the table being cleared.
56956**
56957** See also: Destroy
56958*/
56959case OP_Clear: {
56960#if 0  /* local variables moved into u.bs */
56961  int nChange;
56962#endif /* local variables moved into u.bs */
56963
56964  u.bs.nChange = 0;
56965  assert( (p->btreeMask & (1<<pOp->p2))!=0 );
56966  rc = sqlite3BtreeClearTable(
56967      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
56968  );
56969  if( pOp->p3 ){
56970    p->nChange += u.bs.nChange;
56971    if( pOp->p3>0 ){
56972      aMem[pOp->p3].u.i += u.bs.nChange;
56973    }
56974  }
56975  break;
56976}
56977
56978/* Opcode: CreateTable P1 P2 * * *
56979**
56980** Allocate a new table in the main database file if P1==0 or in the
56981** auxiliary database file if P1==1 or in an attached database if
56982** P1>1.  Write the root page number of the new table into
56983** register P2
56984**
56985** The difference between a table and an index is this:  A table must
56986** have a 4-byte integer key and can have arbitrary data.  An index
56987** has an arbitrary key but no data.
56988**
56989** See also: CreateIndex
56990*/
56991/* Opcode: CreateIndex P1 P2 * * *
56992**
56993** Allocate a new index in the main database file if P1==0 or in the
56994** auxiliary database file if P1==1 or in an attached database if
56995** P1>1.  Write the root page number of the new table into
56996** register P2.
56997**
56998** See documentation on OP_CreateTable for additional information.
56999*/
57000case OP_CreateIndex:            /* out2-prerelease */
57001case OP_CreateTable: {          /* out2-prerelease */
57002#if 0  /* local variables moved into u.bt */
57003  int pgno;
57004  int flags;
57005  Db *pDb;
57006#endif /* local variables moved into u.bt */
57007
57008  u.bt.pgno = 0;
57009  assert( pOp->p1>=0 && pOp->p1<db->nDb );
57010  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
57011  u.bt.pDb = &db->aDb[pOp->p1];
57012  assert( u.bt.pDb->pBt!=0 );
57013  if( pOp->opcode==OP_CreateTable ){
57014    /* u.bt.flags = BTREE_INTKEY; */
57015    u.bt.flags = BTREE_LEAFDATA|BTREE_INTKEY;
57016  }else{
57017    u.bt.flags = BTREE_ZERODATA;
57018  }
57019  rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
57020  pOut->u.i = u.bt.pgno;
57021  break;
57022}
57023
57024/* Opcode: ParseSchema P1 P2 * P4 *
57025**
57026** Read and parse all entries from the SQLITE_MASTER table of database P1
57027** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
57028** the parsing if P2 is true.  If P2 is false, then this routine is a
57029** no-op if the schema is not currently loaded.  In other words, if P2
57030** is false, the SQLITE_MASTER table is only parsed if the rest of the
57031** schema is already loaded into the symbol table.
57032**
57033** This opcode invokes the parser to create a new virtual machine,
57034** then runs the new virtual machine.  It is thus a re-entrant opcode.
57035*/
57036case OP_ParseSchema: {
57037#if 0  /* local variables moved into u.bu */
57038  int iDb;
57039  const char *zMaster;
57040  char *zSql;
57041  InitData initData;
57042#endif /* local variables moved into u.bu */
57043
57044  u.bu.iDb = pOp->p1;
57045  assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
57046
57047  /* If pOp->p2 is 0, then this opcode is being executed to read a
57048  ** single row, for example the row corresponding to a new index
57049  ** created by this VDBE, from the sqlite_master table. It only
57050  ** does this if the corresponding in-memory schema is currently
57051  ** loaded. Otherwise, the new index definition can be loaded along
57052  ** with the rest of the schema when it is required.
57053  **
57054  ** Although the mutex on the BtShared object that corresponds to
57055  ** database u.bu.iDb (the database containing the sqlite_master table
57056  ** read by this instruction) is currently held, it is necessary to
57057  ** obtain the mutexes on all attached databases before checking if
57058  ** the schema of u.bu.iDb is loaded. This is because, at the start of
57059  ** the sqlite3_exec() call below, SQLite will invoke
57060  ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
57061  ** u.bu.iDb mutex may be temporarily released to avoid deadlock. If
57062  ** this happens, then some other thread may delete the in-memory
57063  ** schema of database u.bu.iDb before the SQL statement runs. The schema
57064  ** will not be reloaded becuase the db->init.busy flag is set. This
57065  ** can result in a "no such table: sqlite_master" or "malformed
57066  ** database schema" error being returned to the user.
57067  */
57068  assert( sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
57069  sqlite3BtreeEnterAll(db);
57070  if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){
57071    u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
57072    u.bu.initData.db = db;
57073    u.bu.initData.iDb = pOp->p1;
57074    u.bu.initData.pzErrMsg = &p->zErrMsg;
57075    u.bu.zSql = sqlite3MPrintf(db,
57076       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
57077       db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
57078    if( u.bu.zSql==0 ){
57079      rc = SQLITE_NOMEM;
57080    }else{
57081      assert( db->init.busy==0 );
57082      db->init.busy = 1;
57083      u.bu.initData.rc = SQLITE_OK;
57084      assert( !db->mallocFailed );
57085      rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
57086      if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
57087      sqlite3DbFree(db, u.bu.zSql);
57088      db->init.busy = 0;
57089    }
57090  }
57091  sqlite3BtreeLeaveAll(db);
57092  if( rc==SQLITE_NOMEM ){
57093    goto no_mem;
57094  }
57095  break;
57096}
57097
57098#if !defined(SQLITE_OMIT_ANALYZE)
57099/* Opcode: LoadAnalysis P1 * * * *
57100**
57101** Read the sqlite_stat1 table for database P1 and load the content
57102** of that table into the internal index hash table.  This will cause
57103** the analysis to be used when preparing all subsequent queries.
57104*/
57105case OP_LoadAnalysis: {
57106  assert( pOp->p1>=0 && pOp->p1<db->nDb );
57107  rc = sqlite3AnalysisLoad(db, pOp->p1);
57108  break;
57109}
57110#endif /* !defined(SQLITE_OMIT_ANALYZE) */
57111
57112/* Opcode: DropTable P1 * * P4 *
57113**
57114** Remove the internal (in-memory) data structures that describe
57115** the table named P4 in database P1.  This is called after a table
57116** is dropped in order to keep the internal representation of the
57117** schema consistent with what is on disk.
57118*/
57119case OP_DropTable: {
57120  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
57121  break;
57122}
57123
57124/* Opcode: DropIndex P1 * * P4 *
57125**
57126** Remove the internal (in-memory) data structures that describe
57127** the index named P4 in database P1.  This is called after an index
57128** is dropped in order to keep the internal representation of the
57129** schema consistent with what is on disk.
57130*/
57131case OP_DropIndex: {
57132  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
57133  break;
57134}
57135
57136/* Opcode: DropTrigger P1 * * P4 *
57137**
57138** Remove the internal (in-memory) data structures that describe
57139** the trigger named P4 in database P1.  This is called after a trigger
57140** is dropped in order to keep the internal representation of the
57141** schema consistent with what is on disk.
57142*/
57143case OP_DropTrigger: {
57144  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
57145  break;
57146}
57147
57148
57149#ifndef SQLITE_OMIT_INTEGRITY_CHECK
57150/* Opcode: IntegrityCk P1 P2 P3 * P5
57151**
57152** Do an analysis of the currently open database.  Store in
57153** register P1 the text of an error message describing any problems.
57154** If no problems are found, store a NULL in register P1.
57155**
57156** The register P3 contains the maximum number of allowed errors.
57157** At most reg(P3) errors will be reported.
57158** In other words, the analysis stops as soon as reg(P1) errors are
57159** seen.  Reg(P1) is updated with the number of errors remaining.
57160**
57161** The root page numbers of all tables in the database are integer
57162** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
57163** total.
57164**
57165** If P5 is not zero, the check is done on the auxiliary database
57166** file, not the main database file.
57167**
57168** This opcode is used to implement the integrity_check pragma.
57169*/
57170case OP_IntegrityCk: {
57171#if 0  /* local variables moved into u.bv */
57172  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
57173  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
57174  int j;          /* Loop counter */
57175  int nErr;       /* Number of errors reported */
57176  char *z;        /* Text of the error report */
57177  Mem *pnErr;     /* Register keeping track of errors remaining */
57178#endif /* local variables moved into u.bv */
57179
57180  u.bv.nRoot = pOp->p2;
57181  assert( u.bv.nRoot>0 );
57182  u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
57183  if( u.bv.aRoot==0 ) goto no_mem;
57184  assert( pOp->p3>0 && pOp->p3<=p->nMem );
57185  u.bv.pnErr = &aMem[pOp->p3];
57186  assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
57187  assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
57188  pIn1 = &aMem[pOp->p1];
57189  for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
57190    u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
57191  }
57192  u.bv.aRoot[u.bv.j] = 0;
57193  assert( pOp->p5<db->nDb );
57194  assert( (p->btreeMask & (1<<pOp->p5))!=0 );
57195  u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
57196                                 (int)u.bv.pnErr->u.i, &u.bv.nErr);
57197  sqlite3DbFree(db, u.bv.aRoot);
57198  u.bv.pnErr->u.i -= u.bv.nErr;
57199  sqlite3VdbeMemSetNull(pIn1);
57200  if( u.bv.nErr==0 ){
57201    assert( u.bv.z==0 );
57202  }else if( u.bv.z==0 ){
57203    goto no_mem;
57204  }else{
57205    sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
57206  }
57207  UPDATE_MAX_BLOBSIZE(pIn1);
57208  sqlite3VdbeChangeEncoding(pIn1, encoding);
57209  break;
57210}
57211#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57212
57213/* Opcode: RowSetAdd P1 P2 * * *
57214**
57215** Insert the integer value held by register P2 into a boolean index
57216** held in register P1.
57217**
57218** An assertion fails if P2 is not an integer.
57219*/
57220case OP_RowSetAdd: {       /* in1, in2 */
57221  pIn1 = &aMem[pOp->p1];
57222  pIn2 = &aMem[pOp->p2];
57223  assert( (pIn2->flags & MEM_Int)!=0 );
57224  if( (pIn1->flags & MEM_RowSet)==0 ){
57225    sqlite3VdbeMemSetRowSet(pIn1);
57226    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
57227  }
57228  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
57229  break;
57230}
57231
57232/* Opcode: RowSetRead P1 P2 P3 * *
57233**
57234** Extract the smallest value from boolean index P1 and put that value into
57235** register P3.  Or, if boolean index P1 is initially empty, leave P3
57236** unchanged and jump to instruction P2.
57237*/
57238case OP_RowSetRead: {       /* jump, in1, out3 */
57239#if 0  /* local variables moved into u.bw */
57240  i64 val;
57241#endif /* local variables moved into u.bw */
57242  CHECK_FOR_INTERRUPT;
57243  pIn1 = &aMem[pOp->p1];
57244  if( (pIn1->flags & MEM_RowSet)==0
57245   || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
57246  ){
57247    /* The boolean index is empty */
57248    sqlite3VdbeMemSetNull(pIn1);
57249    pc = pOp->p2 - 1;
57250  }else{
57251    /* A value was pulled from the index */
57252    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
57253  }
57254  break;
57255}
57256
57257/* Opcode: RowSetTest P1 P2 P3 P4
57258**
57259** Register P3 is assumed to hold a 64-bit integer value. If register P1
57260** contains a RowSet object and that RowSet object contains
57261** the value held in P3, jump to register P2. Otherwise, insert the
57262** integer in P3 into the RowSet and continue on to the
57263** next opcode.
57264**
57265** The RowSet object is optimized for the case where successive sets
57266** of integers, where each set contains no duplicates. Each set
57267** of values is identified by a unique P4 value. The first set
57268** must have P4==0, the final set P4=-1.  P4 must be either -1 or
57269** non-negative.  For non-negative values of P4 only the lower 4
57270** bits are significant.
57271**
57272** This allows optimizations: (a) when P4==0 there is no need to test
57273** the rowset object for P3, as it is guaranteed not to contain it,
57274** (b) when P4==-1 there is no need to insert the value, as it will
57275** never be tested for, and (c) when a value that is part of set X is
57276** inserted, there is no need to search to see if the same value was
57277** previously inserted as part of set X (only if it was previously
57278** inserted as part of some other set).
57279*/
57280case OP_RowSetTest: {                     /* jump, in1, in3 */
57281#if 0  /* local variables moved into u.bx */
57282  int iSet;
57283  int exists;
57284#endif /* local variables moved into u.bx */
57285
57286  pIn1 = &aMem[pOp->p1];
57287  pIn3 = &aMem[pOp->p3];
57288  u.bx.iSet = pOp->p4.i;
57289  assert( pIn3->flags&MEM_Int );
57290
57291  /* If there is anything other than a rowset object in memory cell P1,
57292  ** delete it now and initialize P1 with an empty rowset
57293  */
57294  if( (pIn1->flags & MEM_RowSet)==0 ){
57295    sqlite3VdbeMemSetRowSet(pIn1);
57296    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
57297  }
57298
57299  assert( pOp->p4type==P4_INT32 );
57300  assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
57301  if( u.bx.iSet ){
57302    u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
57303                               (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
57304                               pIn3->u.i);
57305    if( u.bx.exists ){
57306      pc = pOp->p2 - 1;
57307      break;
57308    }
57309  }
57310  if( u.bx.iSet>=0 ){
57311    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
57312  }
57313  break;
57314}
57315
57316
57317#ifndef SQLITE_OMIT_TRIGGER
57318
57319/* Opcode: Program P1 P2 P3 P4 *
57320**
57321** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
57322**
57323** P1 contains the address of the memory cell that contains the first memory
57324** cell in an array of values used as arguments to the sub-program. P2
57325** contains the address to jump to if the sub-program throws an IGNORE
57326** exception using the RAISE() function. Register P3 contains the address
57327** of a memory cell in this (the parent) VM that is used to allocate the
57328** memory required by the sub-vdbe at runtime.
57329**
57330** P4 is a pointer to the VM containing the trigger program.
57331*/
57332case OP_Program: {        /* jump */
57333#if 0  /* local variables moved into u.by */
57334  int nMem;               /* Number of memory registers for sub-program */
57335  int nByte;              /* Bytes of runtime space required for sub-program */
57336  Mem *pRt;               /* Register to allocate runtime space */
57337  Mem *pMem;              /* Used to iterate through memory cells */
57338  Mem *pEnd;              /* Last memory cell in new array */
57339  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
57340  SubProgram *pProgram;   /* Sub-program to execute */
57341  void *t;                /* Token identifying trigger */
57342#endif /* local variables moved into u.by */
57343
57344  u.by.pProgram = pOp->p4.pProgram;
57345  u.by.pRt = &aMem[pOp->p3];
57346  assert( u.by.pProgram->nOp>0 );
57347
57348  /* If the p5 flag is clear, then recursive invocation of triggers is
57349  ** disabled for backwards compatibility (p5 is set if this sub-program
57350  ** is really a trigger, not a foreign key action, and the flag set
57351  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
57352  **
57353  ** It is recursive invocation of triggers, at the SQL level, that is
57354  ** disabled. In some cases a single trigger may generate more than one
57355  ** SubProgram (if the trigger may be executed with more than one different
57356  ** ON CONFLICT algorithm). SubProgram structures associated with a
57357  ** single trigger all have the same value for the SubProgram.token
57358  ** variable.  */
57359  if( pOp->p5 ){
57360    u.by.t = u.by.pProgram->token;
57361    for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
57362    if( u.by.pFrame ) break;
57363  }
57364
57365  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
57366    rc = SQLITE_ERROR;
57367    sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
57368    break;
57369  }
57370
57371  /* Register u.by.pRt is used to store the memory required to save the state
57372  ** of the current program, and the memory required at runtime to execute
57373  ** the trigger program. If this trigger has been fired before, then u.by.pRt
57374  ** is already allocated. Otherwise, it must be initialized.  */
57375  if( (u.by.pRt->flags&MEM_Frame)==0 ){
57376    /* SubProgram.nMem is set to the number of memory cells used by the
57377    ** program stored in SubProgram.aOp. As well as these, one memory
57378    ** cell is required for each cursor used by the program. Set local
57379    ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
57380    */
57381    u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
57382    u.by.nByte = ROUND8(sizeof(VdbeFrame))
57383              + u.by.nMem * sizeof(Mem)
57384              + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
57385    u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
57386    if( !u.by.pFrame ){
57387      goto no_mem;
57388    }
57389    sqlite3VdbeMemRelease(u.by.pRt);
57390    u.by.pRt->flags = MEM_Frame;
57391    u.by.pRt->u.pFrame = u.by.pFrame;
57392
57393    u.by.pFrame->v = p;
57394    u.by.pFrame->nChildMem = u.by.nMem;
57395    u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
57396    u.by.pFrame->pc = pc;
57397    u.by.pFrame->aMem = p->aMem;
57398    u.by.pFrame->nMem = p->nMem;
57399    u.by.pFrame->apCsr = p->apCsr;
57400    u.by.pFrame->nCursor = p->nCursor;
57401    u.by.pFrame->aOp = p->aOp;
57402    u.by.pFrame->nOp = p->nOp;
57403    u.by.pFrame->token = u.by.pProgram->token;
57404
57405    u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
57406    for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
57407      u.by.pMem->flags = MEM_Null;
57408      u.by.pMem->db = db;
57409    }
57410  }else{
57411    u.by.pFrame = u.by.pRt->u.pFrame;
57412    assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
57413    assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
57414    assert( pc==u.by.pFrame->pc );
57415  }
57416
57417  p->nFrame++;
57418  u.by.pFrame->pParent = p->pFrame;
57419  u.by.pFrame->lastRowid = db->lastRowid;
57420  u.by.pFrame->nChange = p->nChange;
57421  p->nChange = 0;
57422  p->pFrame = u.by.pFrame;
57423  p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
57424  p->nMem = u.by.pFrame->nChildMem;
57425  p->nCursor = (u16)u.by.pFrame->nChildCsr;
57426  p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
57427  p->aOp = aOp = u.by.pProgram->aOp;
57428  p->nOp = u.by.pProgram->nOp;
57429  pc = -1;
57430
57431  break;
57432}
57433
57434/* Opcode: Param P1 P2 * * *
57435**
57436** This opcode is only ever present in sub-programs called via the
57437** OP_Program instruction. Copy a value currently stored in a memory
57438** cell of the calling (parent) frame to cell P2 in the current frames
57439** address space. This is used by trigger programs to access the new.*
57440** and old.* values.
57441**
57442** The address of the cell in the parent frame is determined by adding
57443** the value of the P1 argument to the value of the P1 argument to the
57444** calling OP_Program instruction.
57445*/
57446case OP_Param: {           /* out2-prerelease */
57447#if 0  /* local variables moved into u.bz */
57448  VdbeFrame *pFrame;
57449  Mem *pIn;
57450#endif /* local variables moved into u.bz */
57451  u.bz.pFrame = p->pFrame;
57452  u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
57453  sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
57454  break;
57455}
57456
57457#endif /* #ifndef SQLITE_OMIT_TRIGGER */
57458
57459#ifndef SQLITE_OMIT_FOREIGN_KEY
57460/* Opcode: FkCounter P1 P2 * * *
57461**
57462** Increment a "constraint counter" by P2 (P2 may be negative or positive).
57463** If P1 is non-zero, the database constraint counter is incremented
57464** (deferred foreign key constraints). Otherwise, if P1 is zero, the
57465** statement counter is incremented (immediate foreign key constraints).
57466*/
57467case OP_FkCounter: {
57468  if( pOp->p1 ){
57469    db->nDeferredCons += pOp->p2;
57470  }else{
57471    p->nFkConstraint += pOp->p2;
57472  }
57473  break;
57474}
57475
57476/* Opcode: FkIfZero P1 P2 * * *
57477**
57478** This opcode tests if a foreign key constraint-counter is currently zero.
57479** If so, jump to instruction P2. Otherwise, fall through to the next
57480** instruction.
57481**
57482** If P1 is non-zero, then the jump is taken if the database constraint-counter
57483** is zero (the one that counts deferred constraint violations). If P1 is
57484** zero, the jump is taken if the statement constraint-counter is zero
57485** (immediate foreign key constraint violations).
57486*/
57487case OP_FkIfZero: {         /* jump */
57488  if( pOp->p1 ){
57489    if( db->nDeferredCons==0 ) pc = pOp->p2-1;
57490  }else{
57491    if( p->nFkConstraint==0 ) pc = pOp->p2-1;
57492  }
57493  break;
57494}
57495#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
57496
57497#ifndef SQLITE_OMIT_AUTOINCREMENT
57498/* Opcode: MemMax P1 P2 * * *
57499**
57500** P1 is a register in the root frame of this VM (the root frame is
57501** different from the current frame if this instruction is being executed
57502** within a sub-program). Set the value of register P1 to the maximum of
57503** its current value and the value in register P2.
57504**
57505** This instruction throws an error if the memory cell is not initially
57506** an integer.
57507*/
57508case OP_MemMax: {        /* in2 */
57509#if 0  /* local variables moved into u.ca */
57510  Mem *pIn1;
57511  VdbeFrame *pFrame;
57512#endif /* local variables moved into u.ca */
57513  if( p->pFrame ){
57514    for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
57515    u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
57516  }else{
57517    u.ca.pIn1 = &aMem[pOp->p1];
57518  }
57519  sqlite3VdbeMemIntegerify(u.ca.pIn1);
57520  pIn2 = &aMem[pOp->p2];
57521  sqlite3VdbeMemIntegerify(pIn2);
57522  if( u.ca.pIn1->u.i<pIn2->u.i){
57523    u.ca.pIn1->u.i = pIn2->u.i;
57524  }
57525  break;
57526}
57527#endif /* SQLITE_OMIT_AUTOINCREMENT */
57528
57529/* Opcode: IfPos P1 P2 * * *
57530**
57531** If the value of register P1 is 1 or greater, jump to P2.
57532**
57533** It is illegal to use this instruction on a register that does
57534** not contain an integer.  An assertion fault will result if you try.
57535*/
57536case OP_IfPos: {        /* jump, in1 */
57537  pIn1 = &aMem[pOp->p1];
57538  assert( pIn1->flags&MEM_Int );
57539  if( pIn1->u.i>0 ){
57540     pc = pOp->p2 - 1;
57541  }
57542  break;
57543}
57544
57545/* Opcode: IfNeg P1 P2 * * *
57546**
57547** If the value of register P1 is less than zero, jump to P2.
57548**
57549** It is illegal to use this instruction on a register that does
57550** not contain an integer.  An assertion fault will result if you try.
57551*/
57552case OP_IfNeg: {        /* jump, in1 */
57553  pIn1 = &aMem[pOp->p1];
57554  assert( pIn1->flags&MEM_Int );
57555  if( pIn1->u.i<0 ){
57556     pc = pOp->p2 - 1;
57557  }
57558  break;
57559}
57560
57561/* Opcode: IfZero P1 P2 P3 * *
57562**
57563** The register P1 must contain an integer.  Add literal P3 to the
57564** value in register P1.  If the result is exactly 0, jump to P2.
57565**
57566** It is illegal to use this instruction on a register that does
57567** not contain an integer.  An assertion fault will result if you try.
57568*/
57569case OP_IfZero: {        /* jump, in1 */
57570  pIn1 = &aMem[pOp->p1];
57571  assert( pIn1->flags&MEM_Int );
57572  pIn1->u.i += pOp->p3;
57573  if( pIn1->u.i==0 ){
57574     pc = pOp->p2 - 1;
57575  }
57576  break;
57577}
57578
57579/* Opcode: AggStep * P2 P3 P4 P5
57580**
57581** Execute the step function for an aggregate.  The
57582** function has P5 arguments.   P4 is a pointer to the FuncDef
57583** structure that specifies the function.  Use register
57584** P3 as the accumulator.
57585**
57586** The P5 arguments are taken from register P2 and its
57587** successors.
57588*/
57589case OP_AggStep: {
57590#if 0  /* local variables moved into u.cb */
57591  int n;
57592  int i;
57593  Mem *pMem;
57594  Mem *pRec;
57595  sqlite3_context ctx;
57596  sqlite3_value **apVal;
57597#endif /* local variables moved into u.cb */
57598
57599  u.cb.n = pOp->p5;
57600  assert( u.cb.n>=0 );
57601  u.cb.pRec = &aMem[pOp->p2];
57602  u.cb.apVal = p->apArg;
57603  assert( u.cb.apVal || u.cb.n==0 );
57604  for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
57605    u.cb.apVal[u.cb.i] = u.cb.pRec;
57606    sqlite3VdbeMemStoreType(u.cb.pRec);
57607  }
57608  u.cb.ctx.pFunc = pOp->p4.pFunc;
57609  assert( pOp->p3>0 && pOp->p3<=p->nMem );
57610  u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
57611  u.cb.pMem->n++;
57612  u.cb.ctx.s.flags = MEM_Null;
57613  u.cb.ctx.s.z = 0;
57614  u.cb.ctx.s.zMalloc = 0;
57615  u.cb.ctx.s.xDel = 0;
57616  u.cb.ctx.s.db = db;
57617  u.cb.ctx.isError = 0;
57618  u.cb.ctx.pColl = 0;
57619  if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
57620    assert( pOp>p->aOp );
57621    assert( pOp[-1].p4type==P4_COLLSEQ );
57622    assert( pOp[-1].opcode==OP_CollSeq );
57623    u.cb.ctx.pColl = pOp[-1].p4.pColl;
57624  }
57625  (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal);
57626  if( u.cb.ctx.isError ){
57627    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
57628    rc = u.cb.ctx.isError;
57629  }
57630  sqlite3VdbeMemRelease(&u.cb.ctx.s);
57631  break;
57632}
57633
57634/* Opcode: AggFinal P1 P2 * P4 *
57635**
57636** Execute the finalizer function for an aggregate.  P1 is
57637** the memory location that is the accumulator for the aggregate.
57638**
57639** P2 is the number of arguments that the step function takes and
57640** P4 is a pointer to the FuncDef for this function.  The P2
57641** argument is not used by this opcode.  It is only there to disambiguate
57642** functions that can take varying numbers of arguments.  The
57643** P4 argument is only needed for the degenerate case where
57644** the step function was not previously called.
57645*/
57646case OP_AggFinal: {
57647#if 0  /* local variables moved into u.cc */
57648  Mem *pMem;
57649#endif /* local variables moved into u.cc */
57650  assert( pOp->p1>0 && pOp->p1<=p->nMem );
57651  u.cc.pMem = &aMem[pOp->p1];
57652  assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
57653  rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
57654  if( rc ){
57655    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
57656  }
57657  sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
57658  UPDATE_MAX_BLOBSIZE(u.cc.pMem);
57659  if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
57660    goto too_big;
57661  }
57662  break;
57663}
57664
57665
57666#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
57667/* Opcode: Vacuum * * * * *
57668**
57669** Vacuum the entire database.  This opcode will cause other virtual
57670** machines to be created and run.  It may not be called from within
57671** a transaction.
57672*/
57673case OP_Vacuum: {
57674  rc = sqlite3RunVacuum(&p->zErrMsg, db);
57675  break;
57676}
57677#endif
57678
57679#if !defined(SQLITE_OMIT_AUTOVACUUM)
57680/* Opcode: IncrVacuum P1 P2 * * *
57681**
57682** Perform a single step of the incremental vacuum procedure on
57683** the P1 database. If the vacuum has finished, jump to instruction
57684** P2. Otherwise, fall through to the next instruction.
57685*/
57686case OP_IncrVacuum: {        /* jump */
57687#if 0  /* local variables moved into u.cd */
57688  Btree *pBt;
57689#endif /* local variables moved into u.cd */
57690
57691  assert( pOp->p1>=0 && pOp->p1<db->nDb );
57692  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
57693  u.cd.pBt = db->aDb[pOp->p1].pBt;
57694  rc = sqlite3BtreeIncrVacuum(u.cd.pBt);
57695  if( rc==SQLITE_DONE ){
57696    pc = pOp->p2 - 1;
57697    rc = SQLITE_OK;
57698  }
57699  break;
57700}
57701#endif
57702
57703/* Opcode: Expire P1 * * * *
57704**
57705** Cause precompiled statements to become expired. An expired statement
57706** fails with an error code of SQLITE_SCHEMA if it is ever executed
57707** (via sqlite3_step()).
57708**
57709** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
57710** then only the currently executing statement is affected.
57711*/
57712case OP_Expire: {
57713  if( !pOp->p1 ){
57714    sqlite3ExpirePreparedStatements(db);
57715  }else{
57716    p->expired = 1;
57717  }
57718  break;
57719}
57720
57721#ifndef SQLITE_OMIT_SHARED_CACHE
57722/* Opcode: TableLock P1 P2 P3 P4 *
57723**
57724** Obtain a lock on a particular table. This instruction is only used when
57725** the shared-cache feature is enabled.
57726**
57727** P1 is the index of the database in sqlite3.aDb[] of the database
57728** on which the lock is acquired.  A readlock is obtained if P3==0 or
57729** a write lock if P3==1.
57730**
57731** P2 contains the root-page of the table to lock.
57732**
57733** P4 contains a pointer to the name of the table being locked. This is only
57734** used to generate an error message if the lock cannot be obtained.
57735*/
57736case OP_TableLock: {
57737  u8 isWriteLock = (u8)pOp->p3;
57738  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
57739    int p1 = pOp->p1;
57740    assert( p1>=0 && p1<db->nDb );
57741    assert( (p->btreeMask & (1<<p1))!=0 );
57742    assert( isWriteLock==0 || isWriteLock==1 );
57743    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
57744    if( (rc&0xFF)==SQLITE_LOCKED ){
57745      const char *z = pOp->p4.z;
57746      sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
57747    }
57748  }
57749  break;
57750}
57751#endif /* SQLITE_OMIT_SHARED_CACHE */
57752
57753#ifndef SQLITE_OMIT_VIRTUALTABLE
57754/* Opcode: VBegin * * * P4 *
57755**
57756** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
57757** xBegin method for that table.
57758**
57759** Also, whether or not P4 is set, check that this is not being called from
57760** within a callback to a virtual table xSync() method. If it is, the error
57761** code will be set to SQLITE_LOCKED.
57762*/
57763case OP_VBegin: {
57764#if 0  /* local variables moved into u.ce */
57765  VTable *pVTab;
57766#endif /* local variables moved into u.ce */
57767  u.ce.pVTab = pOp->p4.pVtab;
57768  rc = sqlite3VtabBegin(db, u.ce.pVTab);
57769  if( u.ce.pVTab ){
57770    sqlite3DbFree(db, p->zErrMsg);
57771    p->zErrMsg = u.ce.pVTab->pVtab->zErrMsg;
57772    u.ce.pVTab->pVtab->zErrMsg = 0;
57773  }
57774  break;
57775}
57776#endif /* SQLITE_OMIT_VIRTUALTABLE */
57777
57778#ifndef SQLITE_OMIT_VIRTUALTABLE
57779/* Opcode: VCreate P1 * * P4 *
57780**
57781** P4 is the name of a virtual table in database P1. Call the xCreate method
57782** for that table.
57783*/
57784case OP_VCreate: {
57785  rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
57786  break;
57787}
57788#endif /* SQLITE_OMIT_VIRTUALTABLE */
57789
57790#ifndef SQLITE_OMIT_VIRTUALTABLE
57791/* Opcode: VDestroy P1 * * P4 *
57792**
57793** P4 is the name of a virtual table in database P1.  Call the xDestroy method
57794** of that table.
57795*/
57796case OP_VDestroy: {
57797  p->inVtabMethod = 2;
57798  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
57799  p->inVtabMethod = 0;
57800  break;
57801}
57802#endif /* SQLITE_OMIT_VIRTUALTABLE */
57803
57804#ifndef SQLITE_OMIT_VIRTUALTABLE
57805/* Opcode: VOpen P1 * * P4 *
57806**
57807** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
57808** P1 is a cursor number.  This opcode opens a cursor to the virtual
57809** table and stores that cursor in P1.
57810*/
57811case OP_VOpen: {
57812#if 0  /* local variables moved into u.cf */
57813  VdbeCursor *pCur;
57814  sqlite3_vtab_cursor *pVtabCursor;
57815  sqlite3_vtab *pVtab;
57816  sqlite3_module *pModule;
57817#endif /* local variables moved into u.cf */
57818
57819  u.cf.pCur = 0;
57820  u.cf.pVtabCursor = 0;
57821  u.cf.pVtab = pOp->p4.pVtab->pVtab;
57822  u.cf.pModule = (sqlite3_module *)u.cf.pVtab->pModule;
57823  assert(u.cf.pVtab && u.cf.pModule);
57824  rc = u.cf.pModule->xOpen(u.cf.pVtab, &u.cf.pVtabCursor);
57825  sqlite3DbFree(db, p->zErrMsg);
57826  p->zErrMsg = u.cf.pVtab->zErrMsg;
57827  u.cf.pVtab->zErrMsg = 0;
57828  if( SQLITE_OK==rc ){
57829    /* Initialize sqlite3_vtab_cursor base class */
57830    u.cf.pVtabCursor->pVtab = u.cf.pVtab;
57831
57832    /* Initialise vdbe cursor object */
57833    u.cf.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
57834    if( u.cf.pCur ){
57835      u.cf.pCur->pVtabCursor = u.cf.pVtabCursor;
57836      u.cf.pCur->pModule = u.cf.pVtabCursor->pVtab->pModule;
57837    }else{
57838      db->mallocFailed = 1;
57839      u.cf.pModule->xClose(u.cf.pVtabCursor);
57840    }
57841  }
57842  break;
57843}
57844#endif /* SQLITE_OMIT_VIRTUALTABLE */
57845
57846#ifndef SQLITE_OMIT_VIRTUALTABLE
57847/* Opcode: VFilter P1 P2 P3 P4 *
57848**
57849** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
57850** the filtered result set is empty.
57851**
57852** P4 is either NULL or a string that was generated by the xBestIndex
57853** method of the module.  The interpretation of the P4 string is left
57854** to the module implementation.
57855**
57856** This opcode invokes the xFilter method on the virtual table specified
57857** by P1.  The integer query plan parameter to xFilter is stored in register
57858** P3. Register P3+1 stores the argc parameter to be passed to the
57859** xFilter method. Registers P3+2..P3+1+argc are the argc
57860** additional parameters which are passed to
57861** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
57862**
57863** A jump is made to P2 if the result set after filtering would be empty.
57864*/
57865case OP_VFilter: {   /* jump */
57866#if 0  /* local variables moved into u.cg */
57867  int nArg;
57868  int iQuery;
57869  const sqlite3_module *pModule;
57870  Mem *pQuery;
57871  Mem *pArgc;
57872  sqlite3_vtab_cursor *pVtabCursor;
57873  sqlite3_vtab *pVtab;
57874  VdbeCursor *pCur;
57875  int res;
57876  int i;
57877  Mem **apArg;
57878#endif /* local variables moved into u.cg */
57879
57880  u.cg.pQuery = &aMem[pOp->p3];
57881  u.cg.pArgc = &u.cg.pQuery[1];
57882  u.cg.pCur = p->apCsr[pOp->p1];
57883  REGISTER_TRACE(pOp->p3, u.cg.pQuery);
57884  assert( u.cg.pCur->pVtabCursor );
57885  u.cg.pVtabCursor = u.cg.pCur->pVtabCursor;
57886  u.cg.pVtab = u.cg.pVtabCursor->pVtab;
57887  u.cg.pModule = u.cg.pVtab->pModule;
57888
57889  /* Grab the index number and argc parameters */
57890  assert( (u.cg.pQuery->flags&MEM_Int)!=0 && u.cg.pArgc->flags==MEM_Int );
57891  u.cg.nArg = (int)u.cg.pArgc->u.i;
57892  u.cg.iQuery = (int)u.cg.pQuery->u.i;
57893
57894  /* Invoke the xFilter method */
57895  {
57896    u.cg.res = 0;
57897    u.cg.apArg = p->apArg;
57898    for(u.cg.i = 0; u.cg.i<u.cg.nArg; u.cg.i++){
57899      u.cg.apArg[u.cg.i] = &u.cg.pArgc[u.cg.i+1];
57900      sqlite3VdbeMemStoreType(u.cg.apArg[u.cg.i]);
57901    }
57902
57903    p->inVtabMethod = 1;
57904    rc = u.cg.pModule->xFilter(u.cg.pVtabCursor, u.cg.iQuery, pOp->p4.z, u.cg.nArg, u.cg.apArg);
57905    p->inVtabMethod = 0;
57906    sqlite3DbFree(db, p->zErrMsg);
57907    p->zErrMsg = u.cg.pVtab->zErrMsg;
57908    u.cg.pVtab->zErrMsg = 0;
57909    if( rc==SQLITE_OK ){
57910      u.cg.res = u.cg.pModule->xEof(u.cg.pVtabCursor);
57911    }
57912
57913    if( u.cg.res ){
57914      pc = pOp->p2 - 1;
57915    }
57916  }
57917  u.cg.pCur->nullRow = 0;
57918
57919  break;
57920}
57921#endif /* SQLITE_OMIT_VIRTUALTABLE */
57922
57923#ifndef SQLITE_OMIT_VIRTUALTABLE
57924/* Opcode: VColumn P1 P2 P3 * *
57925**
57926** Store the value of the P2-th column of
57927** the row of the virtual-table that the
57928** P1 cursor is pointing to into register P3.
57929*/
57930case OP_VColumn: {
57931#if 0  /* local variables moved into u.ch */
57932  sqlite3_vtab *pVtab;
57933  const sqlite3_module *pModule;
57934  Mem *pDest;
57935  sqlite3_context sContext;
57936#endif /* local variables moved into u.ch */
57937
57938  VdbeCursor *pCur = p->apCsr[pOp->p1];
57939  assert( pCur->pVtabCursor );
57940  assert( pOp->p3>0 && pOp->p3<=p->nMem );
57941  u.ch.pDest = &aMem[pOp->p3];
57942  if( pCur->nullRow ){
57943    sqlite3VdbeMemSetNull(u.ch.pDest);
57944    break;
57945  }
57946  u.ch.pVtab = pCur->pVtabCursor->pVtab;
57947  u.ch.pModule = u.ch.pVtab->pModule;
57948  assert( u.ch.pModule->xColumn );
57949  memset(&u.ch.sContext, 0, sizeof(u.ch.sContext));
57950
57951  /* The output cell may already have a buffer allocated. Move
57952  ** the current contents to u.ch.sContext.s so in case the user-function
57953  ** can use the already allocated buffer instead of allocating a
57954  ** new one.
57955  */
57956  sqlite3VdbeMemMove(&u.ch.sContext.s, u.ch.pDest);
57957  MemSetTypeFlag(&u.ch.sContext.s, MEM_Null);
57958
57959  rc = u.ch.pModule->xColumn(pCur->pVtabCursor, &u.ch.sContext, pOp->p2);
57960  sqlite3DbFree(db, p->zErrMsg);
57961  p->zErrMsg = u.ch.pVtab->zErrMsg;
57962  u.ch.pVtab->zErrMsg = 0;
57963  if( u.ch.sContext.isError ){
57964    rc = u.ch.sContext.isError;
57965  }
57966
57967  /* Copy the result of the function to the P3 register. We
57968  ** do this regardless of whether or not an error occurred to ensure any
57969  ** dynamic allocation in u.ch.sContext.s (a Mem struct) is  released.
57970  */
57971  sqlite3VdbeChangeEncoding(&u.ch.sContext.s, encoding);
57972  sqlite3VdbeMemMove(u.ch.pDest, &u.ch.sContext.s);
57973  REGISTER_TRACE(pOp->p3, u.ch.pDest);
57974  UPDATE_MAX_BLOBSIZE(u.ch.pDest);
57975
57976  if( sqlite3VdbeMemTooBig(u.ch.pDest) ){
57977    goto too_big;
57978  }
57979  break;
57980}
57981#endif /* SQLITE_OMIT_VIRTUALTABLE */
57982
57983#ifndef SQLITE_OMIT_VIRTUALTABLE
57984/* Opcode: VNext P1 P2 * * *
57985**
57986** Advance virtual table P1 to the next row in its result set and
57987** jump to instruction P2.  Or, if the virtual table has reached
57988** the end of its result set, then fall through to the next instruction.
57989*/
57990case OP_VNext: {   /* jump */
57991#if 0  /* local variables moved into u.ci */
57992  sqlite3_vtab *pVtab;
57993  const sqlite3_module *pModule;
57994  int res;
57995  VdbeCursor *pCur;
57996#endif /* local variables moved into u.ci */
57997
57998  u.ci.res = 0;
57999  u.ci.pCur = p->apCsr[pOp->p1];
58000  assert( u.ci.pCur->pVtabCursor );
58001  if( u.ci.pCur->nullRow ){
58002    break;
58003  }
58004  u.ci.pVtab = u.ci.pCur->pVtabCursor->pVtab;
58005  u.ci.pModule = u.ci.pVtab->pModule;
58006  assert( u.ci.pModule->xNext );
58007
58008  /* Invoke the xNext() method of the module. There is no way for the
58009  ** underlying implementation to return an error if one occurs during
58010  ** xNext(). Instead, if an error occurs, true is returned (indicating that
58011  ** data is available) and the error code returned when xColumn or
58012  ** some other method is next invoked on the save virtual table cursor.
58013  */
58014  p->inVtabMethod = 1;
58015  rc = u.ci.pModule->xNext(u.ci.pCur->pVtabCursor);
58016  p->inVtabMethod = 0;
58017  sqlite3DbFree(db, p->zErrMsg);
58018  p->zErrMsg = u.ci.pVtab->zErrMsg;
58019  u.ci.pVtab->zErrMsg = 0;
58020  if( rc==SQLITE_OK ){
58021    u.ci.res = u.ci.pModule->xEof(u.ci.pCur->pVtabCursor);
58022  }
58023
58024  if( !u.ci.res ){
58025    /* If there is data, jump to P2 */
58026    pc = pOp->p2 - 1;
58027  }
58028  break;
58029}
58030#endif /* SQLITE_OMIT_VIRTUALTABLE */
58031
58032#ifndef SQLITE_OMIT_VIRTUALTABLE
58033/* Opcode: VRename P1 * * P4 *
58034**
58035** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
58036** This opcode invokes the corresponding xRename method. The value
58037** in register P1 is passed as the zName argument to the xRename method.
58038*/
58039case OP_VRename: {
58040#if 0  /* local variables moved into u.cj */
58041  sqlite3_vtab *pVtab;
58042  Mem *pName;
58043#endif /* local variables moved into u.cj */
58044
58045  u.cj.pVtab = pOp->p4.pVtab->pVtab;
58046  u.cj.pName = &aMem[pOp->p1];
58047  assert( u.cj.pVtab->pModule->xRename );
58048  REGISTER_TRACE(pOp->p1, u.cj.pName);
58049  assert( u.cj.pName->flags & MEM_Str );
58050  rc = u.cj.pVtab->pModule->xRename(u.cj.pVtab, u.cj.pName->z);
58051  sqlite3DbFree(db, p->zErrMsg);
58052  p->zErrMsg = u.cj.pVtab->zErrMsg;
58053  u.cj.pVtab->zErrMsg = 0;
58054
58055  break;
58056}
58057#endif
58058
58059#ifndef SQLITE_OMIT_VIRTUALTABLE
58060/* Opcode: VUpdate P1 P2 P3 P4 *
58061**
58062** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
58063** This opcode invokes the corresponding xUpdate method. P2 values
58064** are contiguous memory cells starting at P3 to pass to the xUpdate
58065** invocation. The value in register (P3+P2-1) corresponds to the
58066** p2th element of the argv array passed to xUpdate.
58067**
58068** The xUpdate method will do a DELETE or an INSERT or both.
58069** The argv[0] element (which corresponds to memory cell P3)
58070** is the rowid of a row to delete.  If argv[0] is NULL then no
58071** deletion occurs.  The argv[1] element is the rowid of the new
58072** row.  This can be NULL to have the virtual table select the new
58073** rowid for itself.  The subsequent elements in the array are
58074** the values of columns in the new row.
58075**
58076** If P2==1 then no insert is performed.  argv[0] is the rowid of
58077** a row to delete.
58078**
58079** P1 is a boolean flag. If it is set to true and the xUpdate call
58080** is successful, then the value returned by sqlite3_last_insert_rowid()
58081** is set to the value of the rowid for the row just inserted.
58082*/
58083case OP_VUpdate: {
58084#if 0  /* local variables moved into u.ck */
58085  sqlite3_vtab *pVtab;
58086  sqlite3_module *pModule;
58087  int nArg;
58088  int i;
58089  sqlite_int64 rowid;
58090  Mem **apArg;
58091  Mem *pX;
58092#endif /* local variables moved into u.ck */
58093
58094  u.ck.pVtab = pOp->p4.pVtab->pVtab;
58095  u.ck.pModule = (sqlite3_module *)u.ck.pVtab->pModule;
58096  u.ck.nArg = pOp->p2;
58097  assert( pOp->p4type==P4_VTAB );
58098  if( ALWAYS(u.ck.pModule->xUpdate) ){
58099    u.ck.apArg = p->apArg;
58100    u.ck.pX = &aMem[pOp->p3];
58101    for(u.ck.i=0; u.ck.i<u.ck.nArg; u.ck.i++){
58102      sqlite3VdbeMemStoreType(u.ck.pX);
58103      u.ck.apArg[u.ck.i] = u.ck.pX;
58104      u.ck.pX++;
58105    }
58106    rc = u.ck.pModule->xUpdate(u.ck.pVtab, u.ck.nArg, u.ck.apArg, &u.ck.rowid);
58107    sqlite3DbFree(db, p->zErrMsg);
58108    p->zErrMsg = u.ck.pVtab->zErrMsg;
58109    u.ck.pVtab->zErrMsg = 0;
58110    if( rc==SQLITE_OK && pOp->p1 ){
58111      assert( u.ck.nArg>1 && u.ck.apArg[0] && (u.ck.apArg[0]->flags&MEM_Null) );
58112      db->lastRowid = u.ck.rowid;
58113    }
58114    p->nChange++;
58115  }
58116  break;
58117}
58118#endif /* SQLITE_OMIT_VIRTUALTABLE */
58119
58120#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
58121/* Opcode: Pagecount P1 P2 * * *
58122**
58123** Write the current number of pages in database P1 to memory cell P2.
58124*/
58125case OP_Pagecount: {            /* out2-prerelease */
58126#if 0  /* local variables moved into u.cl */
58127  int p1;
58128  int nPage;
58129  Pager *pPager;
58130#endif /* local variables moved into u.cl */
58131
58132  u.cl.p1 = pOp->p1;
58133  u.cl.pPager = sqlite3BtreePager(db->aDb[u.cl.p1].pBt);
58134  rc = sqlite3PagerPagecount(u.cl.pPager, &u.cl.nPage);
58135  /* OP_Pagecount is always called from within a read transaction.  The
58136  ** page count has already been successfully read and cached.  So the
58137  ** sqlite3PagerPagecount() call above cannot fail. */
58138  if( ALWAYS(rc==SQLITE_OK) ){
58139    pOut->u.i = u.cl.nPage;
58140  }
58141  break;
58142}
58143#endif
58144
58145#ifndef SQLITE_OMIT_TRACE
58146/* Opcode: Trace * * * P4 *
58147**
58148** If tracing is enabled (by the sqlite3_trace()) interface, then
58149** the UTF-8 string contained in P4 is emitted on the trace callback.
58150*/
58151case OP_Trace: {
58152#if 0  /* local variables moved into u.cm */
58153  char *zTrace;
58154#endif /* local variables moved into u.cm */
58155
58156  u.cm.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
58157  if( u.cm.zTrace ){
58158    if( db->xTrace ){
58159      char *z = sqlite3VdbeExpandSql(p, u.cm.zTrace);
58160      db->xTrace(db->pTraceArg, z);
58161      sqlite3DbFree(db, z);
58162    }
58163#ifdef SQLITE_DEBUG
58164    if( (db->flags & SQLITE_SqlTrace)!=0 ){
58165      sqlite3DebugPrintf("SQL-trace: %s\n", u.cm.zTrace);
58166    }
58167#endif /* SQLITE_DEBUG */
58168  }
58169  break;
58170}
58171#endif
58172
58173
58174/* Opcode: Noop * * * * *
58175**
58176** Do nothing.  This instruction is often useful as a jump
58177** destination.
58178*/
58179/*
58180** The magic Explain opcode are only inserted when explain==2 (which
58181** is to say when the EXPLAIN QUERY PLAN syntax is used.)
58182** This opcode records information from the optimizer.  It is the
58183** the same as a no-op.  This opcodesnever appears in a real VM program.
58184*/
58185default: {          /* This is really OP_Noop and OP_Explain */
58186  break;
58187}
58188
58189/*****************************************************************************
58190** The cases of the switch statement above this line should all be indented
58191** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
58192** readability.  From this point on down, the normal indentation rules are
58193** restored.
58194*****************************************************************************/
58195    }
58196
58197#ifdef VDBE_PROFILE
58198    {
58199      u64 elapsed = sqlite3Hwtime() - start;
58200      pOp->cycles += elapsed;
58201      pOp->cnt++;
58202#if 0
58203        fprintf(stdout, "%10llu ", elapsed);
58204        sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
58205#endif
58206    }
58207#endif
58208
58209    /* The following code adds nothing to the actual functionality
58210    ** of the program.  It is only here for testing and debugging.
58211    ** On the other hand, it does burn CPU cycles every time through
58212    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
58213    */
58214#ifndef NDEBUG
58215    assert( pc>=-1 && pc<p->nOp );
58216
58217#ifdef SQLITE_DEBUG
58218    if( p->trace ){
58219      if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
58220      if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
58221        registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
58222      }
58223      if( pOp->opflags & OPFLG_OUT3 ){
58224        registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
58225      }
58226    }
58227#endif  /* SQLITE_DEBUG */
58228#endif  /* NDEBUG */
58229  }  /* The end of the for(;;) loop the loops through opcodes */
58230
58231  /* If we reach this point, it means that execution is finished with
58232  ** an error of some kind.
58233  */
58234vdbe_error_halt:
58235  assert( rc );
58236  p->rc = rc;
58237  sqlite3_log(rc, "prepared statement aborts at %d: [%s]", pc, p->zSql);
58238  sqlite3VdbeHalt(p);
58239  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
58240  rc = SQLITE_ERROR;
58241  if( resetSchemaOnFault ) sqlite3ResetInternalSchema(db, 0);
58242
58243  /* This is the only way out of this procedure.  We have to
58244  ** release the mutexes on btrees that were acquired at the
58245  ** top. */
58246vdbe_return:
58247  sqlite3BtreeMutexArrayLeave(&p->aMutex);
58248  return rc;
58249
58250  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
58251  ** is encountered.
58252  */
58253too_big:
58254  sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
58255  rc = SQLITE_TOOBIG;
58256  goto vdbe_error_halt;
58257
58258  /* Jump to here if a malloc() fails.
58259  */
58260no_mem:
58261  db->mallocFailed = 1;
58262  sqlite3SetString(&p->zErrMsg, db, "out of memory");
58263  rc = SQLITE_NOMEM;
58264  goto vdbe_error_halt;
58265
58266  /* Jump to here for any other kind of fatal error.  The "rc" variable
58267  ** should hold the error number.
58268  */
58269abort_due_to_error:
58270  assert( p->zErrMsg==0 );
58271  if( db->mallocFailed ) rc = SQLITE_NOMEM;
58272  if( rc!=SQLITE_IOERR_NOMEM ){
58273    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
58274  }
58275  goto vdbe_error_halt;
58276
58277  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
58278  ** flag.
58279  */
58280abort_due_to_interrupt:
58281  assert( db->u1.isInterrupted );
58282  rc = SQLITE_INTERRUPT;
58283  p->rc = rc;
58284  sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
58285  goto vdbe_error_halt;
58286}
58287
58288/************** End of vdbe.c ************************************************/
58289/************** Begin file vdbeblob.c ****************************************/
58290/*
58291** 2007 May 1
58292**
58293** The author disclaims copyright to this source code.  In place of
58294** a legal notice, here is a blessing:
58295**
58296**    May you do good and not evil.
58297**    May you find forgiveness for yourself and forgive others.
58298**    May you share freely, never taking more than you give.
58299**
58300*************************************************************************
58301**
58302** This file contains code used to implement incremental BLOB I/O.
58303*/
58304
58305
58306#ifndef SQLITE_OMIT_INCRBLOB
58307
58308/*
58309** Valid sqlite3_blob* handles point to Incrblob structures.
58310*/
58311typedef struct Incrblob Incrblob;
58312struct Incrblob {
58313  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
58314  int nByte;              /* Size of open blob, in bytes */
58315  int iOffset;            /* Byte offset of blob in cursor data */
58316  BtCursor *pCsr;         /* Cursor pointing at blob row */
58317  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
58318  sqlite3 *db;            /* The associated database */
58319};
58320
58321/*
58322** Open a blob handle.
58323*/
58324SQLITE_API int sqlite3_blob_open(
58325  sqlite3* db,            /* The database connection */
58326  const char *zDb,        /* The attached database containing the blob */
58327  const char *zTable,     /* The table containing the blob */
58328  const char *zColumn,    /* The column containing the blob */
58329  sqlite_int64 iRow,      /* The row containing the glob */
58330  int flags,              /* True -> read/write access, false -> read-only */
58331  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
58332){
58333  int nAttempt = 0;
58334  int iCol;               /* Index of zColumn in row-record */
58335
58336  /* This VDBE program seeks a btree cursor to the identified
58337  ** db/table/row entry. The reason for using a vdbe program instead
58338  ** of writing code to use the b-tree layer directly is that the
58339  ** vdbe program will take advantage of the various transaction,
58340  ** locking and error handling infrastructure built into the vdbe.
58341  **
58342  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
58343  ** Code external to the Vdbe then "borrows" the b-tree cursor and
58344  ** uses it to implement the blob_read(), blob_write() and
58345  ** blob_bytes() functions.
58346  **
58347  ** The sqlite3_blob_close() function finalizes the vdbe program,
58348  ** which closes the b-tree cursor and (possibly) commits the
58349  ** transaction.
58350  */
58351  static const VdbeOpList openBlob[] = {
58352    {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
58353    {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
58354    {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
58355
58356    /* One of the following two instructions is replaced by an OP_Noop. */
58357    {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
58358    {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
58359
58360    {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
58361    {OP_NotExists, 0, 9, 1},       /* 6: Seek the cursor */
58362    {OP_Column, 0, 0, 1},          /* 7  */
58363    {OP_ResultRow, 1, 0, 0},       /* 8  */
58364    {OP_Close, 0, 0, 0},           /* 9  */
58365    {OP_Halt, 0, 0, 0},            /* 10 */
58366  };
58367
58368  Vdbe *v = 0;
58369  int rc = SQLITE_OK;
58370  char *zErr = 0;
58371  Table *pTab;
58372  Parse *pParse;
58373
58374  *ppBlob = 0;
58375  sqlite3_mutex_enter(db->mutex);
58376  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
58377  if( pParse==0 ){
58378    rc = SQLITE_NOMEM;
58379    goto blob_open_out;
58380  }
58381  do {
58382    memset(pParse, 0, sizeof(Parse));
58383    pParse->db = db;
58384
58385    sqlite3BtreeEnterAll(db);
58386    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
58387    if( pTab && IsVirtual(pTab) ){
58388      pTab = 0;
58389      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
58390    }
58391#ifndef SQLITE_OMIT_VIEW
58392    if( pTab && pTab->pSelect ){
58393      pTab = 0;
58394      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
58395    }
58396#endif
58397    if( !pTab ){
58398      if( pParse->zErrMsg ){
58399        sqlite3DbFree(db, zErr);
58400        zErr = pParse->zErrMsg;
58401        pParse->zErrMsg = 0;
58402      }
58403      rc = SQLITE_ERROR;
58404      sqlite3BtreeLeaveAll(db);
58405      goto blob_open_out;
58406    }
58407
58408    /* Now search pTab for the exact column. */
58409    for(iCol=0; iCol < pTab->nCol; iCol++) {
58410      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
58411        break;
58412      }
58413    }
58414    if( iCol==pTab->nCol ){
58415      sqlite3DbFree(db, zErr);
58416      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
58417      rc = SQLITE_ERROR;
58418      sqlite3BtreeLeaveAll(db);
58419      goto blob_open_out;
58420    }
58421
58422    /* If the value is being opened for writing, check that the
58423    ** column is not indexed, and that it is not part of a foreign key.
58424    ** It is against the rules to open a column to which either of these
58425    ** descriptions applies for writing.  */
58426    if( flags ){
58427      const char *zFault = 0;
58428      Index *pIdx;
58429#ifndef SQLITE_OMIT_FOREIGN_KEY
58430      if( db->flags&SQLITE_ForeignKeys ){
58431        /* Check that the column is not part of an FK child key definition. It
58432        ** is not necessary to check if it is part of a parent key, as parent
58433        ** key columns must be indexed. The check below will pick up this
58434        ** case.  */
58435        FKey *pFKey;
58436        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
58437          int j;
58438          for(j=0; j<pFKey->nCol; j++){
58439            if( pFKey->aCol[j].iFrom==iCol ){
58440              zFault = "foreign key";
58441            }
58442          }
58443        }
58444      }
58445#endif
58446      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
58447        int j;
58448        for(j=0; j<pIdx->nColumn; j++){
58449          if( pIdx->aiColumn[j]==iCol ){
58450            zFault = "indexed";
58451          }
58452        }
58453      }
58454      if( zFault ){
58455        sqlite3DbFree(db, zErr);
58456        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
58457        rc = SQLITE_ERROR;
58458        sqlite3BtreeLeaveAll(db);
58459        goto blob_open_out;
58460      }
58461    }
58462
58463    v = sqlite3VdbeCreate(db);
58464    if( v ){
58465      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
58466      sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
58467      flags = !!flags;                 /* flags = (flags ? 1 : 0); */
58468
58469      /* Configure the OP_Transaction */
58470      sqlite3VdbeChangeP1(v, 0, iDb);
58471      sqlite3VdbeChangeP2(v, 0, flags);
58472
58473      /* Configure the OP_VerifyCookie */
58474      sqlite3VdbeChangeP1(v, 1, iDb);
58475      sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
58476
58477      /* Make sure a mutex is held on the table to be accessed */
58478      sqlite3VdbeUsesBtree(v, iDb);
58479
58480      /* Configure the OP_TableLock instruction */
58481      sqlite3VdbeChangeP1(v, 2, iDb);
58482      sqlite3VdbeChangeP2(v, 2, pTab->tnum);
58483      sqlite3VdbeChangeP3(v, 2, flags);
58484      sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
58485
58486      /* Remove either the OP_OpenWrite or OpenRead. Set the P2
58487      ** parameter of the other to pTab->tnum.  */
58488      sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
58489      sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
58490      sqlite3VdbeChangeP3(v, 3 + flags, iDb);
58491
58492      /* Configure the number of columns. Configure the cursor to
58493      ** think that the table has one more column than it really
58494      ** does. An OP_Column to retrieve this imaginary column will
58495      ** always return an SQL NULL. This is useful because it means
58496      ** we can invoke OP_Column to fill in the vdbe cursors type
58497      ** and offset cache without causing any IO.
58498      */
58499      sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
58500      sqlite3VdbeChangeP2(v, 7, pTab->nCol);
58501      if( !db->mallocFailed ){
58502        sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
58503      }
58504    }
58505
58506    sqlite3BtreeLeaveAll(db);
58507    if( db->mallocFailed ){
58508      goto blob_open_out;
58509    }
58510
58511    sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
58512    rc = sqlite3_step((sqlite3_stmt *)v);
58513    if( rc!=SQLITE_ROW ){
58514      nAttempt++;
58515      rc = sqlite3_finalize((sqlite3_stmt *)v);
58516      sqlite3DbFree(db, zErr);
58517      zErr = sqlite3MPrintf(db, sqlite3_errmsg(db));
58518      v = 0;
58519    }
58520  } while( nAttempt<5 && rc==SQLITE_SCHEMA );
58521
58522  if( rc==SQLITE_ROW ){
58523    /* The row-record has been opened successfully. Check that the
58524    ** column in question contains text or a blob. If it contains
58525    ** text, it is up to the caller to get the encoding right.
58526    */
58527    Incrblob *pBlob;
58528    u32 type = v->apCsr[0]->aType[iCol];
58529
58530    if( type<12 ){
58531      sqlite3DbFree(db, zErr);
58532      zErr = sqlite3MPrintf(db, "cannot open value of type %s",
58533          type==0?"null": type==7?"real": "integer"
58534      );
58535      rc = SQLITE_ERROR;
58536      goto blob_open_out;
58537    }
58538    pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
58539    if( db->mallocFailed ){
58540      sqlite3DbFree(db, pBlob);
58541      goto blob_open_out;
58542    }
58543    pBlob->flags = flags;
58544    pBlob->pCsr =  v->apCsr[0]->pCursor;
58545    sqlite3BtreeEnterCursor(pBlob->pCsr);
58546    sqlite3BtreeCacheOverflow(pBlob->pCsr);
58547    sqlite3BtreeLeaveCursor(pBlob->pCsr);
58548    pBlob->pStmt = (sqlite3_stmt *)v;
58549    pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
58550    pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
58551    pBlob->db = db;
58552    *ppBlob = (sqlite3_blob *)pBlob;
58553    rc = SQLITE_OK;
58554  }else if( rc==SQLITE_OK ){
58555    sqlite3DbFree(db, zErr);
58556    zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow);
58557    rc = SQLITE_ERROR;
58558  }
58559
58560blob_open_out:
58561  if( v && (rc!=SQLITE_OK || db->mallocFailed) ){
58562    sqlite3VdbeFinalize(v);
58563  }
58564  sqlite3Error(db, rc, zErr);
58565  sqlite3DbFree(db, zErr);
58566  sqlite3StackFree(db, pParse);
58567  rc = sqlite3ApiExit(db, rc);
58568  sqlite3_mutex_leave(db->mutex);
58569  return rc;
58570}
58571
58572/*
58573** Close a blob handle that was previously created using
58574** sqlite3_blob_open().
58575*/
58576SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
58577  Incrblob *p = (Incrblob *)pBlob;
58578  int rc;
58579  sqlite3 *db;
58580
58581  if( p ){
58582    db = p->db;
58583    sqlite3_mutex_enter(db->mutex);
58584    rc = sqlite3_finalize(p->pStmt);
58585    sqlite3DbFree(db, p);
58586    sqlite3_mutex_leave(db->mutex);
58587  }else{
58588    rc = SQLITE_OK;
58589  }
58590  return rc;
58591}
58592
58593/*
58594** Perform a read or write operation on a blob
58595*/
58596static int blobReadWrite(
58597  sqlite3_blob *pBlob,
58598  void *z,
58599  int n,
58600  int iOffset,
58601  int (*xCall)(BtCursor*, u32, u32, void*)
58602){
58603  int rc;
58604  Incrblob *p = (Incrblob *)pBlob;
58605  Vdbe *v;
58606  sqlite3 *db;
58607
58608  if( p==0 ) return SQLITE_MISUSE_BKPT;
58609  db = p->db;
58610  sqlite3_mutex_enter(db->mutex);
58611  v = (Vdbe*)p->pStmt;
58612
58613  if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
58614    /* Request is out of range. Return a transient error. */
58615    rc = SQLITE_ERROR;
58616    sqlite3Error(db, SQLITE_ERROR, 0);
58617  } else if( v==0 ){
58618    /* If there is no statement handle, then the blob-handle has
58619    ** already been invalidated. Return SQLITE_ABORT in this case.
58620    */
58621    rc = SQLITE_ABORT;
58622  }else{
58623    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
58624    ** returned, clean-up the statement handle.
58625    */
58626    assert( db == v->db );
58627    sqlite3BtreeEnterCursor(p->pCsr);
58628    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
58629    sqlite3BtreeLeaveCursor(p->pCsr);
58630    if( rc==SQLITE_ABORT ){
58631      sqlite3VdbeFinalize(v);
58632      p->pStmt = 0;
58633    }else{
58634      db->errCode = rc;
58635      v->rc = rc;
58636    }
58637  }
58638  rc = sqlite3ApiExit(db, rc);
58639  sqlite3_mutex_leave(db->mutex);
58640  return rc;
58641}
58642
58643/*
58644** Read data from a blob handle.
58645*/
58646SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
58647  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
58648}
58649
58650/*
58651** Write data to a blob handle.
58652*/
58653SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
58654  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
58655}
58656
58657/*
58658** Query a blob handle for the size of the data.
58659**
58660** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
58661** so no mutex is required for access.
58662*/
58663SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
58664  Incrblob *p = (Incrblob *)pBlob;
58665  return p ? p->nByte : 0;
58666}
58667
58668#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
58669
58670/************** End of vdbeblob.c ********************************************/
58671/************** Begin file journal.c *****************************************/
58672/*
58673** 2007 August 22
58674**
58675** The author disclaims copyright to this source code.  In place of
58676** a legal notice, here is a blessing:
58677**
58678**    May you do good and not evil.
58679**    May you find forgiveness for yourself and forgive others.
58680**    May you share freely, never taking more than you give.
58681**
58682*************************************************************************
58683**
58684** This file implements a special kind of sqlite3_file object used
58685** by SQLite to create journal files if the atomic-write optimization
58686** is enabled.
58687**
58688** The distinctive characteristic of this sqlite3_file is that the
58689** actual on disk file is created lazily. When the file is created,
58690** the caller specifies a buffer size for an in-memory buffer to
58691** be used to service read() and write() requests. The actual file
58692** on disk is not created or populated until either:
58693**
58694**   1) The in-memory representation grows too large for the allocated
58695**      buffer, or
58696**   2) The sqlite3JournalCreate() function is called.
58697*/
58698#ifdef SQLITE_ENABLE_ATOMIC_WRITE
58699
58700
58701/*
58702** A JournalFile object is a subclass of sqlite3_file used by
58703** as an open file handle for journal files.
58704*/
58705struct JournalFile {
58706  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
58707  int nBuf;                       /* Size of zBuf[] in bytes */
58708  char *zBuf;                     /* Space to buffer journal writes */
58709  int iSize;                      /* Amount of zBuf[] currently used */
58710  int flags;                      /* xOpen flags */
58711  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
58712  sqlite3_file *pReal;            /* The "real" underlying file descriptor */
58713  const char *zJournal;           /* Name of the journal file */
58714};
58715typedef struct JournalFile JournalFile;
58716
58717/*
58718** If it does not already exists, create and populate the on-disk file
58719** for JournalFile p.
58720*/
58721static int createFile(JournalFile *p){
58722  int rc = SQLITE_OK;
58723  if( !p->pReal ){
58724    sqlite3_file *pReal = (sqlite3_file *)&p[1];
58725    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
58726    if( rc==SQLITE_OK ){
58727      p->pReal = pReal;
58728      if( p->iSize>0 ){
58729        assert(p->iSize<=p->nBuf);
58730        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
58731      }
58732    }
58733  }
58734  return rc;
58735}
58736
58737/*
58738** Close the file.
58739*/
58740static int jrnlClose(sqlite3_file *pJfd){
58741  JournalFile *p = (JournalFile *)pJfd;
58742  if( p->pReal ){
58743    sqlite3OsClose(p->pReal);
58744  }
58745  sqlite3_free(p->zBuf);
58746  return SQLITE_OK;
58747}
58748
58749/*
58750** Read data from the file.
58751*/
58752static int jrnlRead(
58753  sqlite3_file *pJfd,    /* The journal file from which to read */
58754  void *zBuf,            /* Put the results here */
58755  int iAmt,              /* Number of bytes to read */
58756  sqlite_int64 iOfst     /* Begin reading at this offset */
58757){
58758  int rc = SQLITE_OK;
58759  JournalFile *p = (JournalFile *)pJfd;
58760  if( p->pReal ){
58761    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
58762  }else if( (iAmt+iOfst)>p->iSize ){
58763    rc = SQLITE_IOERR_SHORT_READ;
58764  }else{
58765    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
58766  }
58767  return rc;
58768}
58769
58770/*
58771** Write data to the file.
58772*/
58773static int jrnlWrite(
58774  sqlite3_file *pJfd,    /* The journal file into which to write */
58775  const void *zBuf,      /* Take data to be written from here */
58776  int iAmt,              /* Number of bytes to write */
58777  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
58778){
58779  int rc = SQLITE_OK;
58780  JournalFile *p = (JournalFile *)pJfd;
58781  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
58782    rc = createFile(p);
58783  }
58784  if( rc==SQLITE_OK ){
58785    if( p->pReal ){
58786      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
58787    }else{
58788      memcpy(&p->zBuf[iOfst], zBuf, iAmt);
58789      if( p->iSize<(iOfst+iAmt) ){
58790        p->iSize = (iOfst+iAmt);
58791      }
58792    }
58793  }
58794  return rc;
58795}
58796
58797/*
58798** Truncate the file.
58799*/
58800static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
58801  int rc = SQLITE_OK;
58802  JournalFile *p = (JournalFile *)pJfd;
58803  if( p->pReal ){
58804    rc = sqlite3OsTruncate(p->pReal, size);
58805  }else if( size<p->iSize ){
58806    p->iSize = size;
58807  }
58808  return rc;
58809}
58810
58811/*
58812** Sync the file.
58813*/
58814static int jrnlSync(sqlite3_file *pJfd, int flags){
58815  int rc;
58816  JournalFile *p = (JournalFile *)pJfd;
58817  if( p->pReal ){
58818    rc = sqlite3OsSync(p->pReal, flags);
58819  }else{
58820    rc = SQLITE_OK;
58821  }
58822  return rc;
58823}
58824
58825/*
58826** Query the size of the file in bytes.
58827*/
58828static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
58829  int rc = SQLITE_OK;
58830  JournalFile *p = (JournalFile *)pJfd;
58831  if( p->pReal ){
58832    rc = sqlite3OsFileSize(p->pReal, pSize);
58833  }else{
58834    *pSize = (sqlite_int64) p->iSize;
58835  }
58836  return rc;
58837}
58838
58839/*
58840** Table of methods for JournalFile sqlite3_file object.
58841*/
58842static struct sqlite3_io_methods JournalFileMethods = {
58843  1,             /* iVersion */
58844  jrnlClose,     /* xClose */
58845  jrnlRead,      /* xRead */
58846  jrnlWrite,     /* xWrite */
58847  jrnlTruncate,  /* xTruncate */
58848  jrnlSync,      /* xSync */
58849  jrnlFileSize,  /* xFileSize */
58850  0,             /* xLock */
58851  0,             /* xUnlock */
58852  0,             /* xCheckReservedLock */
58853  0,             /* xFileControl */
58854  0,             /* xSectorSize */
58855  0              /* xDeviceCharacteristics */
58856};
58857
58858/*
58859** Open a journal file.
58860*/
58861SQLITE_PRIVATE int sqlite3JournalOpen(
58862  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
58863  const char *zName,         /* Name of the journal file */
58864  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
58865  int flags,                 /* Opening flags */
58866  int nBuf                   /* Bytes buffered before opening the file */
58867){
58868  JournalFile *p = (JournalFile *)pJfd;
58869  memset(p, 0, sqlite3JournalSize(pVfs));
58870  if( nBuf>0 ){
58871    p->zBuf = sqlite3MallocZero(nBuf);
58872    if( !p->zBuf ){
58873      return SQLITE_NOMEM;
58874    }
58875  }else{
58876    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
58877  }
58878  p->pMethod = &JournalFileMethods;
58879  p->nBuf = nBuf;
58880  p->flags = flags;
58881  p->zJournal = zName;
58882  p->pVfs = pVfs;
58883  return SQLITE_OK;
58884}
58885
58886/*
58887** If the argument p points to a JournalFile structure, and the underlying
58888** file has not yet been created, create it now.
58889*/
58890SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
58891  if( p->pMethods!=&JournalFileMethods ){
58892    return SQLITE_OK;
58893  }
58894  return createFile((JournalFile *)p);
58895}
58896
58897/*
58898** Return the number of bytes required to store a JournalFile that uses vfs
58899** pVfs to create the underlying on-disk files.
58900*/
58901SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
58902  return (pVfs->szOsFile+sizeof(JournalFile));
58903}
58904#endif
58905
58906/************** End of journal.c *********************************************/
58907/************** Begin file memjournal.c **************************************/
58908/*
58909** 2008 October 7
58910**
58911** The author disclaims copyright to this source code.  In place of
58912** a legal notice, here is a blessing:
58913**
58914**    May you do good and not evil.
58915**    May you find forgiveness for yourself and forgive others.
58916**    May you share freely, never taking more than you give.
58917**
58918*************************************************************************
58919**
58920** This file contains code use to implement an in-memory rollback journal.
58921** The in-memory rollback journal is used to journal transactions for
58922** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
58923*/
58924
58925/* Forward references to internal structures */
58926typedef struct MemJournal MemJournal;
58927typedef struct FilePoint FilePoint;
58928typedef struct FileChunk FileChunk;
58929
58930/* Space to hold the rollback journal is allocated in increments of
58931** this many bytes.
58932**
58933** The size chosen is a little less than a power of two.  That way,
58934** the FileChunk object will have a size that almost exactly fills
58935** a power-of-two allocation.  This mimimizes wasted space in power-of-two
58936** memory allocators.
58937*/
58938#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
58939
58940/* Macro to find the minimum of two numeric values.
58941*/
58942#ifndef MIN
58943# define MIN(x,y) ((x)<(y)?(x):(y))
58944#endif
58945
58946/*
58947** The rollback journal is composed of a linked list of these structures.
58948*/
58949struct FileChunk {
58950  FileChunk *pNext;               /* Next chunk in the journal */
58951  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
58952};
58953
58954/*
58955** An instance of this object serves as a cursor into the rollback journal.
58956** The cursor can be either for reading or writing.
58957*/
58958struct FilePoint {
58959  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
58960  FileChunk *pChunk;              /* Specific chunk into which cursor points */
58961};
58962
58963/*
58964** This subclass is a subclass of sqlite3_file.  Each open memory-journal
58965** is an instance of this class.
58966*/
58967struct MemJournal {
58968  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
58969  FileChunk *pFirst;              /* Head of in-memory chunk-list */
58970  FilePoint endpoint;             /* Pointer to the end of the file */
58971  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
58972};
58973
58974/*
58975** Read data from the in-memory journal file.  This is the implementation
58976** of the sqlite3_vfs.xRead method.
58977*/
58978static int memjrnlRead(
58979  sqlite3_file *pJfd,    /* The journal file from which to read */
58980  void *zBuf,            /* Put the results here */
58981  int iAmt,              /* Number of bytes to read */
58982  sqlite_int64 iOfst     /* Begin reading at this offset */
58983){
58984  MemJournal *p = (MemJournal *)pJfd;
58985  u8 *zOut = zBuf;
58986  int nRead = iAmt;
58987  int iChunkOffset;
58988  FileChunk *pChunk;
58989
58990  /* SQLite never tries to read past the end of a rollback journal file */
58991  assert( iOfst+iAmt<=p->endpoint.iOffset );
58992
58993  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
58994    sqlite3_int64 iOff = 0;
58995    for(pChunk=p->pFirst;
58996        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
58997        pChunk=pChunk->pNext
58998    ){
58999      iOff += JOURNAL_CHUNKSIZE;
59000    }
59001  }else{
59002    pChunk = p->readpoint.pChunk;
59003  }
59004
59005  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
59006  do {
59007    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
59008    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
59009    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
59010    zOut += nCopy;
59011    nRead -= iSpace;
59012    iChunkOffset = 0;
59013  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
59014  p->readpoint.iOffset = iOfst+iAmt;
59015  p->readpoint.pChunk = pChunk;
59016
59017  return SQLITE_OK;
59018}
59019
59020/*
59021** Write data to the file.
59022*/
59023static int memjrnlWrite(
59024  sqlite3_file *pJfd,    /* The journal file into which to write */
59025  const void *zBuf,      /* Take data to be written from here */
59026  int iAmt,              /* Number of bytes to write */
59027  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
59028){
59029  MemJournal *p = (MemJournal *)pJfd;
59030  int nWrite = iAmt;
59031  u8 *zWrite = (u8 *)zBuf;
59032
59033  /* An in-memory journal file should only ever be appended to. Random
59034  ** access writes are not required by sqlite.
59035  */
59036  assert( iOfst==p->endpoint.iOffset );
59037  UNUSED_PARAMETER(iOfst);
59038
59039  while( nWrite>0 ){
59040    FileChunk *pChunk = p->endpoint.pChunk;
59041    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
59042    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
59043
59044    if( iChunkOffset==0 ){
59045      /* New chunk is required to extend the file. */
59046      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
59047      if( !pNew ){
59048        return SQLITE_IOERR_NOMEM;
59049      }
59050      pNew->pNext = 0;
59051      if( pChunk ){
59052        assert( p->pFirst );
59053        pChunk->pNext = pNew;
59054      }else{
59055        assert( !p->pFirst );
59056        p->pFirst = pNew;
59057      }
59058      p->endpoint.pChunk = pNew;
59059    }
59060
59061    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
59062    zWrite += iSpace;
59063    nWrite -= iSpace;
59064    p->endpoint.iOffset += iSpace;
59065  }
59066
59067  return SQLITE_OK;
59068}
59069
59070/*
59071** Truncate the file.
59072*/
59073static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
59074  MemJournal *p = (MemJournal *)pJfd;
59075  FileChunk *pChunk;
59076  assert(size==0);
59077  UNUSED_PARAMETER(size);
59078  pChunk = p->pFirst;
59079  while( pChunk ){
59080    FileChunk *pTmp = pChunk;
59081    pChunk = pChunk->pNext;
59082    sqlite3_free(pTmp);
59083  }
59084  sqlite3MemJournalOpen(pJfd);
59085  return SQLITE_OK;
59086}
59087
59088/*
59089** Close the file.
59090*/
59091static int memjrnlClose(sqlite3_file *pJfd){
59092  memjrnlTruncate(pJfd, 0);
59093  return SQLITE_OK;
59094}
59095
59096
59097/*
59098** Sync the file.
59099**
59100** Syncing an in-memory journal is a no-op.  And, in fact, this routine
59101** is never called in a working implementation.  This implementation
59102** exists purely as a contingency, in case some malfunction in some other
59103** part of SQLite causes Sync to be called by mistake.
59104*/
59105static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){   /*NO_TEST*/
59106  UNUSED_PARAMETER2(NotUsed, NotUsed2);                        /*NO_TEST*/
59107  assert( 0 );                                                 /*NO_TEST*/
59108  return SQLITE_OK;                                            /*NO_TEST*/
59109}                                                              /*NO_TEST*/
59110
59111/*
59112** Query the size of the file in bytes.
59113*/
59114static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
59115  MemJournal *p = (MemJournal *)pJfd;
59116  *pSize = (sqlite_int64) p->endpoint.iOffset;
59117  return SQLITE_OK;
59118}
59119
59120/*
59121** Table of methods for MemJournal sqlite3_file object.
59122*/
59123static struct sqlite3_io_methods MemJournalMethods = {
59124  1,                /* iVersion */
59125  memjrnlClose,     /* xClose */
59126  memjrnlRead,      /* xRead */
59127  memjrnlWrite,     /* xWrite */
59128  memjrnlTruncate,  /* xTruncate */
59129  memjrnlSync,      /* xSync */
59130  memjrnlFileSize,  /* xFileSize */
59131  0,                /* xLock */
59132  0,                /* xUnlock */
59133  0,                /* xCheckReservedLock */
59134  0,                /* xFileControl */
59135  0,                /* xSectorSize */
59136  0                 /* xDeviceCharacteristics */
59137};
59138
59139/*
59140** Open a journal file.
59141*/
59142SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
59143  MemJournal *p = (MemJournal *)pJfd;
59144  assert( EIGHT_BYTE_ALIGNMENT(p) );
59145  memset(p, 0, sqlite3MemJournalSize());
59146  p->pMethod = &MemJournalMethods;
59147}
59148
59149/*
59150** Return true if the file-handle passed as an argument is
59151** an in-memory journal
59152*/
59153SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
59154  return pJfd->pMethods==&MemJournalMethods;
59155}
59156
59157/*
59158** Return the number of bytes required to store a MemJournal that uses vfs
59159** pVfs to create the underlying on-disk files.
59160*/
59161SQLITE_PRIVATE int sqlite3MemJournalSize(void){
59162  return sizeof(MemJournal);
59163}
59164
59165/************** End of memjournal.c ******************************************/
59166/************** Begin file walker.c ******************************************/
59167/*
59168** 2008 August 16
59169**
59170** The author disclaims copyright to this source code.  In place of
59171** a legal notice, here is a blessing:
59172**
59173**    May you do good and not evil.
59174**    May you find forgiveness for yourself and forgive others.
59175**    May you share freely, never taking more than you give.
59176**
59177*************************************************************************
59178** This file contains routines used for walking the parser tree for
59179** an SQL statement.
59180*/
59181
59182
59183/*
59184** Walk an expression tree.  Invoke the callback once for each node
59185** of the expression, while decending.  (In other words, the callback
59186** is invoked before visiting children.)
59187**
59188** The return value from the callback should be one of the WRC_*
59189** constants to specify how to proceed with the walk.
59190**
59191**    WRC_Continue      Continue descending down the tree.
59192**
59193**    WRC_Prune         Do not descend into child nodes.  But allow
59194**                      the walk to continue with sibling nodes.
59195**
59196**    WRC_Abort         Do no more callbacks.  Unwind the stack and
59197**                      return the top-level walk call.
59198**
59199** The return value from this routine is WRC_Abort to abandon the tree walk
59200** and WRC_Continue to continue.
59201*/
59202SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
59203  int rc;
59204  if( pExpr==0 ) return WRC_Continue;
59205  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
59206  testcase( ExprHasProperty(pExpr, EP_Reduced) );
59207  rc = pWalker->xExprCallback(pWalker, pExpr);
59208  if( rc==WRC_Continue
59209              && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
59210    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
59211    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
59212    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
59213      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
59214    }else{
59215      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
59216    }
59217  }
59218  return rc & WRC_Abort;
59219}
59220
59221/*
59222** Call sqlite3WalkExpr() for every expression in list p or until
59223** an abort request is seen.
59224*/
59225SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
59226  int i;
59227  struct ExprList_item *pItem;
59228  if( p ){
59229    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
59230      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
59231    }
59232  }
59233  return WRC_Continue;
59234}
59235
59236/*
59237** Walk all expressions associated with SELECT statement p.  Do
59238** not invoke the SELECT callback on p, but do (of course) invoke
59239** any expr callbacks and SELECT callbacks that come from subqueries.
59240** Return WRC_Abort or WRC_Continue.
59241*/
59242SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
59243  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
59244  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
59245  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
59246  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
59247  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
59248  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
59249  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
59250  return WRC_Continue;
59251}
59252
59253/*
59254** Walk the parse trees associated with all subqueries in the
59255** FROM clause of SELECT statement p.  Do not invoke the select
59256** callback on p, but do invoke it on each FROM clause subquery
59257** and on any subqueries further down in the tree.  Return
59258** WRC_Abort or WRC_Continue;
59259*/
59260SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
59261  SrcList *pSrc;
59262  int i;
59263  struct SrcList_item *pItem;
59264
59265  pSrc = p->pSrc;
59266  if( ALWAYS(pSrc) ){
59267    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
59268      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
59269        return WRC_Abort;
59270      }
59271    }
59272  }
59273  return WRC_Continue;
59274}
59275
59276/*
59277** Call sqlite3WalkExpr() for every expression in Select statement p.
59278** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
59279** on the compound select chain, p->pPrior.
59280**
59281** Return WRC_Continue under normal conditions.  Return WRC_Abort if
59282** there is an abort request.
59283**
59284** If the Walker does not have an xSelectCallback() then this routine
59285** is a no-op returning WRC_Continue.
59286*/
59287SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
59288  int rc;
59289  if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
59290  rc = WRC_Continue;
59291  while( p  ){
59292    rc = pWalker->xSelectCallback(pWalker, p);
59293    if( rc ) break;
59294    if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
59295    if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
59296    p = p->pPrior;
59297  }
59298  return rc & WRC_Abort;
59299}
59300
59301/************** End of walker.c **********************************************/
59302/************** Begin file resolve.c *****************************************/
59303/*
59304** 2008 August 18
59305**
59306** The author disclaims copyright to this source code.  In place of
59307** a legal notice, here is a blessing:
59308**
59309**    May you do good and not evil.
59310**    May you find forgiveness for yourself and forgive others.
59311**    May you share freely, never taking more than you give.
59312**
59313*************************************************************************
59314**
59315** This file contains routines used for walking the parser tree and
59316** resolve all identifiers by associating them with a particular
59317** table and column.
59318*/
59319
59320/*
59321** Turn the pExpr expression into an alias for the iCol-th column of the
59322** result set in pEList.
59323**
59324** If the result set column is a simple column reference, then this routine
59325** makes an exact copy.  But for any other kind of expression, this
59326** routine make a copy of the result set column as the argument to the
59327** TK_AS operator.  The TK_AS operator causes the expression to be
59328** evaluated just once and then reused for each alias.
59329**
59330** The reason for suppressing the TK_AS term when the expression is a simple
59331** column reference is so that the column reference will be recognized as
59332** usable by indices within the WHERE clause processing logic.
59333**
59334** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
59335** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
59336**
59337**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
59338**
59339** Is equivalent to:
59340**
59341**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
59342**
59343** The result of random()%5 in the GROUP BY clause is probably different
59344** from the result in the result-set.  We might fix this someday.  Or
59345** then again, we might not...
59346*/
59347static void resolveAlias(
59348  Parse *pParse,         /* Parsing context */
59349  ExprList *pEList,      /* A result set */
59350  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
59351  Expr *pExpr,           /* Transform this into an alias to the result set */
59352  const char *zType      /* "GROUP" or "ORDER" or "" */
59353){
59354  Expr *pOrig;           /* The iCol-th column of the result set */
59355  Expr *pDup;            /* Copy of pOrig */
59356  sqlite3 *db;           /* The database connection */
59357
59358  assert( iCol>=0 && iCol<pEList->nExpr );
59359  pOrig = pEList->a[iCol].pExpr;
59360  assert( pOrig!=0 );
59361  assert( pOrig->flags & EP_Resolved );
59362  db = pParse->db;
59363  if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
59364    pDup = sqlite3ExprDup(db, pOrig, 0);
59365    pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
59366    if( pDup==0 ) return;
59367    if( pEList->a[iCol].iAlias==0 ){
59368      pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
59369    }
59370    pDup->iTable = pEList->a[iCol].iAlias;
59371  }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
59372    pDup = sqlite3ExprDup(db, pOrig, 0);
59373    if( pDup==0 ) return;
59374  }else{
59375    char *zToken = pOrig->u.zToken;
59376    assert( zToken!=0 );
59377    pOrig->u.zToken = 0;
59378    pDup = sqlite3ExprDup(db, pOrig, 0);
59379    pOrig->u.zToken = zToken;
59380    if( pDup==0 ) return;
59381    assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
59382    pDup->flags2 |= EP2_MallocedToken;
59383    pDup->u.zToken = sqlite3DbStrDup(db, zToken);
59384  }
59385  if( pExpr->flags & EP_ExpCollate ){
59386    pDup->pColl = pExpr->pColl;
59387    pDup->flags |= EP_ExpCollate;
59388  }
59389
59390  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
59391  ** prevents ExprDelete() from deleting the Expr structure itself,
59392  ** allowing it to be repopulated by the memcpy() on the following line.
59393  */
59394  ExprSetProperty(pExpr, EP_Static);
59395  sqlite3ExprDelete(db, pExpr);
59396  memcpy(pExpr, pDup, sizeof(*pExpr));
59397  sqlite3DbFree(db, pDup);
59398}
59399
59400/*
59401** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
59402** that name in the set of source tables in pSrcList and make the pExpr
59403** expression node refer back to that source column.  The following changes
59404** are made to pExpr:
59405**
59406**    pExpr->iDb           Set the index in db->aDb[] of the database X
59407**                         (even if X is implied).
59408**    pExpr->iTable        Set to the cursor number for the table obtained
59409**                         from pSrcList.
59410**    pExpr->pTab          Points to the Table structure of X.Y (even if
59411**                         X and/or Y are implied.)
59412**    pExpr->iColumn       Set to the column number within the table.
59413**    pExpr->op            Set to TK_COLUMN.
59414**    pExpr->pLeft         Any expression this points to is deleted
59415**    pExpr->pRight        Any expression this points to is deleted.
59416**
59417** The zDb variable is the name of the database (the "X").  This value may be
59418** NULL meaning that name is of the form Y.Z or Z.  Any available database
59419** can be used.  The zTable variable is the name of the table (the "Y").  This
59420** value can be NULL if zDb is also NULL.  If zTable is NULL it
59421** means that the form of the name is Z and that columns from any table
59422** can be used.
59423**
59424** If the name cannot be resolved unambiguously, leave an error message
59425** in pParse and return WRC_Abort.  Return WRC_Prune on success.
59426*/
59427static int lookupName(
59428  Parse *pParse,       /* The parsing context */
59429  const char *zDb,     /* Name of the database containing table, or NULL */
59430  const char *zTab,    /* Name of table containing column, or NULL */
59431  const char *zCol,    /* Name of the column. */
59432  NameContext *pNC,    /* The name context used to resolve the name */
59433  Expr *pExpr          /* Make this EXPR node point to the selected column */
59434){
59435  int i, j;            /* Loop counters */
59436  int cnt = 0;                      /* Number of matching column names */
59437  int cntTab = 0;                   /* Number of matching table names */
59438  sqlite3 *db = pParse->db;         /* The database connection */
59439  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
59440  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
59441  NameContext *pTopNC = pNC;        /* First namecontext in the list */
59442  Schema *pSchema = 0;              /* Schema of the expression */
59443  int isTrigger = 0;
59444
59445  assert( pNC );     /* the name context cannot be NULL. */
59446  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
59447  assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
59448
59449  /* Initialize the node to no-match */
59450  pExpr->iTable = -1;
59451  pExpr->pTab = 0;
59452  ExprSetIrreducible(pExpr);
59453
59454  /* Start at the inner-most context and move outward until a match is found */
59455  while( pNC && cnt==0 ){
59456    ExprList *pEList;
59457    SrcList *pSrcList = pNC->pSrcList;
59458
59459    if( pSrcList ){
59460      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
59461        Table *pTab;
59462        int iDb;
59463        Column *pCol;
59464
59465        pTab = pItem->pTab;
59466        assert( pTab!=0 && pTab->zName!=0 );
59467        iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
59468        assert( pTab->nCol>0 );
59469        if( zTab ){
59470          if( pItem->zAlias ){
59471            char *zTabName = pItem->zAlias;
59472            if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
59473          }else{
59474            char *zTabName = pTab->zName;
59475            if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
59476              continue;
59477            }
59478            if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
59479              continue;
59480            }
59481          }
59482        }
59483        if( 0==(cntTab++) ){
59484          pExpr->iTable = pItem->iCursor;
59485          pExpr->pTab = pTab;
59486          pSchema = pTab->pSchema;
59487          pMatch = pItem;
59488        }
59489        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
59490          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
59491            IdList *pUsing;
59492            cnt++;
59493            pExpr->iTable = pItem->iCursor;
59494            pExpr->pTab = pTab;
59495            pMatch = pItem;
59496            pSchema = pTab->pSchema;
59497            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
59498            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
59499            if( i<pSrcList->nSrc-1 ){
59500              if( pItem[1].jointype & JT_NATURAL ){
59501                /* If this match occurred in the left table of a natural join,
59502                ** then skip the right table to avoid a duplicate match */
59503                pItem++;
59504                i++;
59505              }else if( (pUsing = pItem[1].pUsing)!=0 ){
59506                /* If this match occurs on a column that is in the USING clause
59507                ** of a join, skip the search of the right table of the join
59508                ** to avoid a duplicate match there. */
59509                int k;
59510                for(k=0; k<pUsing->nId; k++){
59511                  if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
59512                    pItem++;
59513                    i++;
59514                    break;
59515                  }
59516                }
59517              }
59518            }
59519            break;
59520          }
59521        }
59522      }
59523    }
59524
59525#ifndef SQLITE_OMIT_TRIGGER
59526    /* If we have not already resolved the name, then maybe
59527    ** it is a new.* or old.* trigger argument reference
59528    */
59529    if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
59530      int op = pParse->eTriggerOp;
59531      Table *pTab = 0;
59532      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
59533      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
59534        pExpr->iTable = 1;
59535        pTab = pParse->pTriggerTab;
59536      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
59537        pExpr->iTable = 0;
59538        pTab = pParse->pTriggerTab;
59539      }
59540
59541      if( pTab ){
59542        int iCol;
59543        pSchema = pTab->pSchema;
59544        cntTab++;
59545        for(iCol=0; iCol<pTab->nCol; iCol++){
59546          Column *pCol = &pTab->aCol[iCol];
59547          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
59548            if( iCol==pTab->iPKey ){
59549              iCol = -1;
59550            }
59551            break;
59552          }
59553        }
59554        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
59555          iCol = -1;        /* IMP: R-44911-55124 */
59556        }
59557        if( iCol<pTab->nCol ){
59558          cnt++;
59559          if( iCol<0 ){
59560            pExpr->affinity = SQLITE_AFF_INTEGER;
59561          }else if( pExpr->iTable==0 ){
59562            testcase( iCol==31 );
59563            testcase( iCol==32 );
59564            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
59565          }else{
59566            testcase( iCol==31 );
59567            testcase( iCol==32 );
59568            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
59569          }
59570          pExpr->iColumn = (i16)iCol;
59571          pExpr->pTab = pTab;
59572          isTrigger = 1;
59573        }
59574      }
59575    }
59576#endif /* !defined(SQLITE_OMIT_TRIGGER) */
59577
59578    /*
59579    ** Perhaps the name is a reference to the ROWID
59580    */
59581    if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
59582      cnt = 1;
59583      pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
59584      pExpr->affinity = SQLITE_AFF_INTEGER;
59585    }
59586
59587    /*
59588    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
59589    ** might refer to an result-set alias.  This happens, for example, when
59590    ** we are resolving names in the WHERE clause of the following command:
59591    **
59592    **     SELECT a+b AS x FROM table WHERE x<10;
59593    **
59594    ** In cases like this, replace pExpr with a copy of the expression that
59595    ** forms the result set entry ("a+b" in the example) and return immediately.
59596    ** Note that the expression in the result set should have already been
59597    ** resolved by the time the WHERE clause is resolved.
59598    */
59599    if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
59600      for(j=0; j<pEList->nExpr; j++){
59601        char *zAs = pEList->a[j].zName;
59602        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
59603          Expr *pOrig;
59604          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
59605          assert( pExpr->x.pList==0 );
59606          assert( pExpr->x.pSelect==0 );
59607          pOrig = pEList->a[j].pExpr;
59608          if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
59609            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
59610            return WRC_Abort;
59611          }
59612          resolveAlias(pParse, pEList, j, pExpr, "");
59613          cnt = 1;
59614          pMatch = 0;
59615          assert( zTab==0 && zDb==0 );
59616          goto lookupname_end;
59617        }
59618      }
59619    }
59620
59621    /* Advance to the next name context.  The loop will exit when either
59622    ** we have a match (cnt>0) or when we run out of name contexts.
59623    */
59624    if( cnt==0 ){
59625      pNC = pNC->pNext;
59626    }
59627  }
59628
59629  /*
59630  ** If X and Y are NULL (in other words if only the column name Z is
59631  ** supplied) and the value of Z is enclosed in double-quotes, then
59632  ** Z is a string literal if it doesn't match any column names.  In that
59633  ** case, we need to return right away and not make any changes to
59634  ** pExpr.
59635  **
59636  ** Because no reference was made to outer contexts, the pNC->nRef
59637  ** fields are not changed in any context.
59638  */
59639  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
59640    pExpr->op = TK_STRING;
59641    pExpr->pTab = 0;
59642    return WRC_Prune;
59643  }
59644
59645  /*
59646  ** cnt==0 means there was not match.  cnt>1 means there were two or
59647  ** more matches.  Either way, we have an error.
59648  */
59649  if( cnt!=1 ){
59650    const char *zErr;
59651    zErr = cnt==0 ? "no such column" : "ambiguous column name";
59652    if( zDb ){
59653      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
59654    }else if( zTab ){
59655      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
59656    }else{
59657      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
59658    }
59659    pTopNC->nErr++;
59660  }
59661
59662  /* If a column from a table in pSrcList is referenced, then record
59663  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
59664  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
59665  ** column number is greater than the number of bits in the bitmask
59666  ** then set the high-order bit of the bitmask.
59667  */
59668  if( pExpr->iColumn>=0 && pMatch!=0 ){
59669    int n = pExpr->iColumn;
59670    testcase( n==BMS-1 );
59671    if( n>=BMS ){
59672      n = BMS-1;
59673    }
59674    assert( pMatch->iCursor==pExpr->iTable );
59675    pMatch->colUsed |= ((Bitmask)1)<<n;
59676  }
59677
59678  /* Clean up and return
59679  */
59680  sqlite3ExprDelete(db, pExpr->pLeft);
59681  pExpr->pLeft = 0;
59682  sqlite3ExprDelete(db, pExpr->pRight);
59683  pExpr->pRight = 0;
59684  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
59685lookupname_end:
59686  if( cnt==1 ){
59687    assert( pNC!=0 );
59688    sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
59689    /* Increment the nRef value on all name contexts from TopNC up to
59690    ** the point where the name matched. */
59691    for(;;){
59692      assert( pTopNC!=0 );
59693      pTopNC->nRef++;
59694      if( pTopNC==pNC ) break;
59695      pTopNC = pTopNC->pNext;
59696    }
59697    return WRC_Prune;
59698  } else {
59699    return WRC_Abort;
59700  }
59701}
59702
59703/*
59704** Allocate and return a pointer to an expression to load the column iCol
59705** from datasource iSrc datasource in SrcList pSrc.
59706*/
59707SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
59708  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
59709  if( p ){
59710    struct SrcList_item *pItem = &pSrc->a[iSrc];
59711    p->pTab = pItem->pTab;
59712    p->iTable = pItem->iCursor;
59713    if( p->pTab->iPKey==iCol ){
59714      p->iColumn = -1;
59715    }else{
59716      p->iColumn = (ynVar)iCol;
59717      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
59718    }
59719    ExprSetProperty(p, EP_Resolved);
59720  }
59721  return p;
59722}
59723
59724/*
59725** This routine is callback for sqlite3WalkExpr().
59726**
59727** Resolve symbolic names into TK_COLUMN operators for the current
59728** node in the expression tree.  Return 0 to continue the search down
59729** the tree or 2 to abort the tree walk.
59730**
59731** This routine also does error checking and name resolution for
59732** function names.  The operator for aggregate functions is changed
59733** to TK_AGG_FUNCTION.
59734*/
59735static int resolveExprStep(Walker *pWalker, Expr *pExpr){
59736  NameContext *pNC;
59737  Parse *pParse;
59738
59739  pNC = pWalker->u.pNC;
59740  assert( pNC!=0 );
59741  pParse = pNC->pParse;
59742  assert( pParse==pWalker->pParse );
59743
59744  if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
59745  ExprSetProperty(pExpr, EP_Resolved);
59746#ifndef NDEBUG
59747  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
59748    SrcList *pSrcList = pNC->pSrcList;
59749    int i;
59750    for(i=0; i<pNC->pSrcList->nSrc; i++){
59751      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
59752    }
59753  }
59754#endif
59755  switch( pExpr->op ){
59756
59757#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
59758    /* The special operator TK_ROW means use the rowid for the first
59759    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
59760    ** clause processing on UPDATE and DELETE statements.
59761    */
59762    case TK_ROW: {
59763      SrcList *pSrcList = pNC->pSrcList;
59764      struct SrcList_item *pItem;
59765      assert( pSrcList && pSrcList->nSrc==1 );
59766      pItem = pSrcList->a;
59767      pExpr->op = TK_COLUMN;
59768      pExpr->pTab = pItem->pTab;
59769      pExpr->iTable = pItem->iCursor;
59770      pExpr->iColumn = -1;
59771      pExpr->affinity = SQLITE_AFF_INTEGER;
59772      break;
59773    }
59774#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
59775
59776    /* A lone identifier is the name of a column.
59777    */
59778    case TK_ID: {
59779      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
59780    }
59781
59782    /* A table name and column name:     ID.ID
59783    ** Or a database, table and column:  ID.ID.ID
59784    */
59785    case TK_DOT: {
59786      const char *zColumn;
59787      const char *zTable;
59788      const char *zDb;
59789      Expr *pRight;
59790
59791      /* if( pSrcList==0 ) break; */
59792      pRight = pExpr->pRight;
59793      if( pRight->op==TK_ID ){
59794        zDb = 0;
59795        zTable = pExpr->pLeft->u.zToken;
59796        zColumn = pRight->u.zToken;
59797      }else{
59798        assert( pRight->op==TK_DOT );
59799        zDb = pExpr->pLeft->u.zToken;
59800        zTable = pRight->pLeft->u.zToken;
59801        zColumn = pRight->pRight->u.zToken;
59802      }
59803      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
59804    }
59805
59806    /* Resolve function names
59807    */
59808    case TK_CONST_FUNC:
59809    case TK_FUNCTION: {
59810      ExprList *pList = pExpr->x.pList;    /* The argument list */
59811      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
59812      int no_such_func = 0;       /* True if no such function exists */
59813      int wrong_num_args = 0;     /* True if wrong number of arguments */
59814      int is_agg = 0;             /* True if is an aggregate function */
59815      int auth;                   /* Authorization to use the function */
59816      int nId;                    /* Number of characters in function name */
59817      const char *zId;            /* The function name. */
59818      FuncDef *pDef;              /* Information about the function */
59819      u8 enc = ENC(pParse->db);   /* The database encoding */
59820
59821      testcase( pExpr->op==TK_CONST_FUNC );
59822      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
59823      zId = pExpr->u.zToken;
59824      nId = sqlite3Strlen30(zId);
59825      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
59826      if( pDef==0 ){
59827        pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
59828        if( pDef==0 ){
59829          no_such_func = 1;
59830        }else{
59831          wrong_num_args = 1;
59832        }
59833      }else{
59834        is_agg = pDef->xFunc==0;
59835      }
59836#ifndef SQLITE_OMIT_AUTHORIZATION
59837      if( pDef ){
59838        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
59839        if( auth!=SQLITE_OK ){
59840          if( auth==SQLITE_DENY ){
59841            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
59842                                    pDef->zName);
59843            pNC->nErr++;
59844          }
59845          pExpr->op = TK_NULL;
59846          return WRC_Prune;
59847        }
59848      }
59849#endif
59850      if( is_agg && !pNC->allowAgg ){
59851        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
59852        pNC->nErr++;
59853        is_agg = 0;
59854      }else if( no_such_func ){
59855        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
59856        pNC->nErr++;
59857      }else if( wrong_num_args ){
59858        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
59859             nId, zId);
59860        pNC->nErr++;
59861      }
59862      if( is_agg ){
59863        pExpr->op = TK_AGG_FUNCTION;
59864        pNC->hasAgg = 1;
59865      }
59866      if( is_agg ) pNC->allowAgg = 0;
59867      sqlite3WalkExprList(pWalker, pList);
59868      if( is_agg ) pNC->allowAgg = 1;
59869      /* FIX ME:  Compute pExpr->affinity based on the expected return
59870      ** type of the function
59871      */
59872      return WRC_Prune;
59873    }
59874#ifndef SQLITE_OMIT_SUBQUERY
59875    case TK_SELECT:
59876    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
59877#endif
59878    case TK_IN: {
59879      testcase( pExpr->op==TK_IN );
59880      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
59881        int nRef = pNC->nRef;
59882#ifndef SQLITE_OMIT_CHECK
59883        if( pNC->isCheck ){
59884          sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
59885        }
59886#endif
59887        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
59888        assert( pNC->nRef>=nRef );
59889        if( nRef!=pNC->nRef ){
59890          ExprSetProperty(pExpr, EP_VarSelect);
59891        }
59892      }
59893      break;
59894    }
59895#ifndef SQLITE_OMIT_CHECK
59896    case TK_VARIABLE: {
59897      if( pNC->isCheck ){
59898        sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
59899      }
59900      break;
59901    }
59902#endif
59903  }
59904  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
59905}
59906
59907/*
59908** pEList is a list of expressions which are really the result set of the
59909** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
59910** This routine checks to see if pE is a simple identifier which corresponds
59911** to the AS-name of one of the terms of the expression list.  If it is,
59912** this routine return an integer between 1 and N where N is the number of
59913** elements in pEList, corresponding to the matching entry.  If there is
59914** no match, or if pE is not a simple identifier, then this routine
59915** return 0.
59916**
59917** pEList has been resolved.  pE has not.
59918*/
59919static int resolveAsName(
59920  Parse *pParse,     /* Parsing context for error messages */
59921  ExprList *pEList,  /* List of expressions to scan */
59922  Expr *pE           /* Expression we are trying to match */
59923){
59924  int i;             /* Loop counter */
59925
59926  UNUSED_PARAMETER(pParse);
59927
59928  if( pE->op==TK_ID ){
59929    char *zCol = pE->u.zToken;
59930    for(i=0; i<pEList->nExpr; i++){
59931      char *zAs = pEList->a[i].zName;
59932      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
59933        return i+1;
59934      }
59935    }
59936  }
59937  return 0;
59938}
59939
59940/*
59941** pE is a pointer to an expression which is a single term in the
59942** ORDER BY of a compound SELECT.  The expression has not been
59943** name resolved.
59944**
59945** At the point this routine is called, we already know that the
59946** ORDER BY term is not an integer index into the result set.  That
59947** case is handled by the calling routine.
59948**
59949** Attempt to match pE against result set columns in the left-most
59950** SELECT statement.  Return the index i of the matching column,
59951** as an indication to the caller that it should sort by the i-th column.
59952** The left-most column is 1.  In other words, the value returned is the
59953** same integer value that would be used in the SQL statement to indicate
59954** the column.
59955**
59956** If there is no match, return 0.  Return -1 if an error occurs.
59957*/
59958static int resolveOrderByTermToExprList(
59959  Parse *pParse,     /* Parsing context for error messages */
59960  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
59961  Expr *pE           /* The specific ORDER BY term */
59962){
59963  int i;             /* Loop counter */
59964  ExprList *pEList;  /* The columns of the result set */
59965  NameContext nc;    /* Name context for resolving pE */
59966  sqlite3 *db;       /* Database connection */
59967  int rc;            /* Return code from subprocedures */
59968  u8 savedSuppErr;   /* Saved value of db->suppressErr */
59969
59970  assert( sqlite3ExprIsInteger(pE, &i)==0 );
59971  pEList = pSelect->pEList;
59972
59973  /* Resolve all names in the ORDER BY term expression
59974  */
59975  memset(&nc, 0, sizeof(nc));
59976  nc.pParse = pParse;
59977  nc.pSrcList = pSelect->pSrc;
59978  nc.pEList = pEList;
59979  nc.allowAgg = 1;
59980  nc.nErr = 0;
59981  db = pParse->db;
59982  savedSuppErr = db->suppressErr;
59983  db->suppressErr = 1;
59984  rc = sqlite3ResolveExprNames(&nc, pE);
59985  db->suppressErr = savedSuppErr;
59986  if( rc ) return 0;
59987
59988  /* Try to match the ORDER BY expression against an expression
59989  ** in the result set.  Return an 1-based index of the matching
59990  ** result-set entry.
59991  */
59992  for(i=0; i<pEList->nExpr; i++){
59993    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
59994      return i+1;
59995    }
59996  }
59997
59998  /* If no match, return 0. */
59999  return 0;
60000}
60001
60002/*
60003** Generate an ORDER BY or GROUP BY term out-of-range error.
60004*/
60005static void resolveOutOfRangeError(
60006  Parse *pParse,         /* The error context into which to write the error */
60007  const char *zType,     /* "ORDER" or "GROUP" */
60008  int i,                 /* The index (1-based) of the term out of range */
60009  int mx                 /* Largest permissible value of i */
60010){
60011  sqlite3ErrorMsg(pParse,
60012    "%r %s BY term out of range - should be "
60013    "between 1 and %d", i, zType, mx);
60014}
60015
60016/*
60017** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
60018** each term of the ORDER BY clause is a constant integer between 1
60019** and N where N is the number of columns in the compound SELECT.
60020**
60021** ORDER BY terms that are already an integer between 1 and N are
60022** unmodified.  ORDER BY terms that are integers outside the range of
60023** 1 through N generate an error.  ORDER BY terms that are expressions
60024** are matched against result set expressions of compound SELECT
60025** beginning with the left-most SELECT and working toward the right.
60026** At the first match, the ORDER BY expression is transformed into
60027** the integer column number.
60028**
60029** Return the number of errors seen.
60030*/
60031static int resolveCompoundOrderBy(
60032  Parse *pParse,        /* Parsing context.  Leave error messages here */
60033  Select *pSelect       /* The SELECT statement containing the ORDER BY */
60034){
60035  int i;
60036  ExprList *pOrderBy;
60037  ExprList *pEList;
60038  sqlite3 *db;
60039  int moreToDo = 1;
60040
60041  pOrderBy = pSelect->pOrderBy;
60042  if( pOrderBy==0 ) return 0;
60043  db = pParse->db;
60044#if SQLITE_MAX_COLUMN
60045  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
60046    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
60047    return 1;
60048  }
60049#endif
60050  for(i=0; i<pOrderBy->nExpr; i++){
60051    pOrderBy->a[i].done = 0;
60052  }
60053  pSelect->pNext = 0;
60054  while( pSelect->pPrior ){
60055    pSelect->pPrior->pNext = pSelect;
60056    pSelect = pSelect->pPrior;
60057  }
60058  while( pSelect && moreToDo ){
60059    struct ExprList_item *pItem;
60060    moreToDo = 0;
60061    pEList = pSelect->pEList;
60062    assert( pEList!=0 );
60063    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
60064      int iCol = -1;
60065      Expr *pE, *pDup;
60066      if( pItem->done ) continue;
60067      pE = pItem->pExpr;
60068      if( sqlite3ExprIsInteger(pE, &iCol) ){
60069        if( iCol<=0 || iCol>pEList->nExpr ){
60070          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
60071          return 1;
60072        }
60073      }else{
60074        iCol = resolveAsName(pParse, pEList, pE);
60075        if( iCol==0 ){
60076          pDup = sqlite3ExprDup(db, pE, 0);
60077          if( !db->mallocFailed ){
60078            assert(pDup);
60079            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
60080          }
60081          sqlite3ExprDelete(db, pDup);
60082        }
60083      }
60084      if( iCol>0 ){
60085        CollSeq *pColl = pE->pColl;
60086        int flags = pE->flags & EP_ExpCollate;
60087        sqlite3ExprDelete(db, pE);
60088        pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
60089        if( pE==0 ) return 1;
60090        pE->pColl = pColl;
60091        pE->flags |= EP_IntValue | flags;
60092        pE->u.iValue = iCol;
60093        pItem->iCol = (u16)iCol;
60094        pItem->done = 1;
60095      }else{
60096        moreToDo = 1;
60097      }
60098    }
60099    pSelect = pSelect->pNext;
60100  }
60101  for(i=0; i<pOrderBy->nExpr; i++){
60102    if( pOrderBy->a[i].done==0 ){
60103      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
60104            "column in the result set", i+1);
60105      return 1;
60106    }
60107  }
60108  return 0;
60109}
60110
60111/*
60112** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
60113** the SELECT statement pSelect.  If any term is reference to a
60114** result set expression (as determined by the ExprList.a.iCol field)
60115** then convert that term into a copy of the corresponding result set
60116** column.
60117**
60118** If any errors are detected, add an error message to pParse and
60119** return non-zero.  Return zero if no errors are seen.
60120*/
60121SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
60122  Parse *pParse,        /* Parsing context.  Leave error messages here */
60123  Select *pSelect,      /* The SELECT statement containing the clause */
60124  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
60125  const char *zType     /* "ORDER" or "GROUP" */
60126){
60127  int i;
60128  sqlite3 *db = pParse->db;
60129  ExprList *pEList;
60130  struct ExprList_item *pItem;
60131
60132  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
60133#if SQLITE_MAX_COLUMN
60134  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
60135    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
60136    return 1;
60137  }
60138#endif
60139  pEList = pSelect->pEList;
60140  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
60141  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
60142    if( pItem->iCol ){
60143      if( pItem->iCol>pEList->nExpr ){
60144        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
60145        return 1;
60146      }
60147      resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
60148    }
60149  }
60150  return 0;
60151}
60152
60153/*
60154** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
60155** The Name context of the SELECT statement is pNC.  zType is either
60156** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
60157**
60158** This routine resolves each term of the clause into an expression.
60159** If the order-by term is an integer I between 1 and N (where N is the
60160** number of columns in the result set of the SELECT) then the expression
60161** in the resolution is a copy of the I-th result-set expression.  If
60162** the order-by term is an identify that corresponds to the AS-name of
60163** a result-set expression, then the term resolves to a copy of the
60164** result-set expression.  Otherwise, the expression is resolved in
60165** the usual way - using sqlite3ResolveExprNames().
60166**
60167** This routine returns the number of errors.  If errors occur, then
60168** an appropriate error message might be left in pParse.  (OOM errors
60169** excepted.)
60170*/
60171static int resolveOrderGroupBy(
60172  NameContext *pNC,     /* The name context of the SELECT statement */
60173  Select *pSelect,      /* The SELECT statement holding pOrderBy */
60174  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
60175  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
60176){
60177  int i;                         /* Loop counter */
60178  int iCol;                      /* Column number */
60179  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
60180  Parse *pParse;                 /* Parsing context */
60181  int nResult;                   /* Number of terms in the result set */
60182
60183  if( pOrderBy==0 ) return 0;
60184  nResult = pSelect->pEList->nExpr;
60185  pParse = pNC->pParse;
60186  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
60187    Expr *pE = pItem->pExpr;
60188    iCol = resolveAsName(pParse, pSelect->pEList, pE);
60189    if( iCol>0 ){
60190      /* If an AS-name match is found, mark this ORDER BY column as being
60191      ** a copy of the iCol-th result-set column.  The subsequent call to
60192      ** sqlite3ResolveOrderGroupBy() will convert the expression to a
60193      ** copy of the iCol-th result-set expression. */
60194      pItem->iCol = (u16)iCol;
60195      continue;
60196    }
60197    if( sqlite3ExprIsInteger(pE, &iCol) ){
60198      /* The ORDER BY term is an integer constant.  Again, set the column
60199      ** number so that sqlite3ResolveOrderGroupBy() will convert the
60200      ** order-by term to a copy of the result-set expression */
60201      if( iCol<1 ){
60202        resolveOutOfRangeError(pParse, zType, i+1, nResult);
60203        return 1;
60204      }
60205      pItem->iCol = (u16)iCol;
60206      continue;
60207    }
60208
60209    /* Otherwise, treat the ORDER BY term as an ordinary expression */
60210    pItem->iCol = 0;
60211    if( sqlite3ResolveExprNames(pNC, pE) ){
60212      return 1;
60213    }
60214  }
60215  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
60216}
60217
60218/*
60219** Resolve names in the SELECT statement p and all of its descendents.
60220*/
60221static int resolveSelectStep(Walker *pWalker, Select *p){
60222  NameContext *pOuterNC;  /* Context that contains this SELECT */
60223  NameContext sNC;        /* Name context of this SELECT */
60224  int isCompound;         /* True if p is a compound select */
60225  int nCompound;          /* Number of compound terms processed so far */
60226  Parse *pParse;          /* Parsing context */
60227  ExprList *pEList;       /* Result set expression list */
60228  int i;                  /* Loop counter */
60229  ExprList *pGroupBy;     /* The GROUP BY clause */
60230  Select *pLeftmost;      /* Left-most of SELECT of a compound */
60231  sqlite3 *db;            /* Database connection */
60232
60233
60234  assert( p!=0 );
60235  if( p->selFlags & SF_Resolved ){
60236    return WRC_Prune;
60237  }
60238  pOuterNC = pWalker->u.pNC;
60239  pParse = pWalker->pParse;
60240  db = pParse->db;
60241
60242  /* Normally sqlite3SelectExpand() will be called first and will have
60243  ** already expanded this SELECT.  However, if this is a subquery within
60244  ** an expression, sqlite3ResolveExprNames() will be called without a
60245  ** prior call to sqlite3SelectExpand().  When that happens, let
60246  ** sqlite3SelectPrep() do all of the processing for this SELECT.
60247  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
60248  ** this routine in the correct order.
60249  */
60250  if( (p->selFlags & SF_Expanded)==0 ){
60251    sqlite3SelectPrep(pParse, p, pOuterNC);
60252    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
60253  }
60254
60255  isCompound = p->pPrior!=0;
60256  nCompound = 0;
60257  pLeftmost = p;
60258  while( p ){
60259    assert( (p->selFlags & SF_Expanded)!=0 );
60260    assert( (p->selFlags & SF_Resolved)==0 );
60261    p->selFlags |= SF_Resolved;
60262
60263    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
60264    ** are not allowed to refer to any names, so pass an empty NameContext.
60265    */
60266    memset(&sNC, 0, sizeof(sNC));
60267    sNC.pParse = pParse;
60268    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
60269        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
60270      return WRC_Abort;
60271    }
60272
60273    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
60274    ** resolve the result-set expression list.
60275    */
60276    sNC.allowAgg = 1;
60277    sNC.pSrcList = p->pSrc;
60278    sNC.pNext = pOuterNC;
60279
60280    /* Resolve names in the result set. */
60281    pEList = p->pEList;
60282    assert( pEList!=0 );
60283    for(i=0; i<pEList->nExpr; i++){
60284      Expr *pX = pEList->a[i].pExpr;
60285      if( sqlite3ResolveExprNames(&sNC, pX) ){
60286        return WRC_Abort;
60287      }
60288    }
60289
60290    /* Recursively resolve names in all subqueries
60291    */
60292    for(i=0; i<p->pSrc->nSrc; i++){
60293      struct SrcList_item *pItem = &p->pSrc->a[i];
60294      if( pItem->pSelect ){
60295        const char *zSavedContext = pParse->zAuthContext;
60296        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
60297        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
60298        pParse->zAuthContext = zSavedContext;
60299        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
60300      }
60301    }
60302
60303    /* If there are no aggregate functions in the result-set, and no GROUP BY
60304    ** expression, do not allow aggregates in any of the other expressions.
60305    */
60306    assert( (p->selFlags & SF_Aggregate)==0 );
60307    pGroupBy = p->pGroupBy;
60308    if( pGroupBy || sNC.hasAgg ){
60309      p->selFlags |= SF_Aggregate;
60310    }else{
60311      sNC.allowAgg = 0;
60312    }
60313
60314    /* If a HAVING clause is present, then there must be a GROUP BY clause.
60315    */
60316    if( p->pHaving && !pGroupBy ){
60317      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
60318      return WRC_Abort;
60319    }
60320
60321    /* Add the expression list to the name-context before parsing the
60322    ** other expressions in the SELECT statement. This is so that
60323    ** expressions in the WHERE clause (etc.) can refer to expressions by
60324    ** aliases in the result set.
60325    **
60326    ** Minor point: If this is the case, then the expression will be
60327    ** re-evaluated for each reference to it.
60328    */
60329    sNC.pEList = p->pEList;
60330    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
60331       sqlite3ResolveExprNames(&sNC, p->pHaving)
60332    ){
60333      return WRC_Abort;
60334    }
60335
60336    /* The ORDER BY and GROUP BY clauses may not refer to terms in
60337    ** outer queries
60338    */
60339    sNC.pNext = 0;
60340    sNC.allowAgg = 1;
60341
60342    /* Process the ORDER BY clause for singleton SELECT statements.
60343    ** The ORDER BY clause for compounds SELECT statements is handled
60344    ** below, after all of the result-sets for all of the elements of
60345    ** the compound have been resolved.
60346    */
60347    if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
60348      return WRC_Abort;
60349    }
60350    if( db->mallocFailed ){
60351      return WRC_Abort;
60352    }
60353
60354    /* Resolve the GROUP BY clause.  At the same time, make sure
60355    ** the GROUP BY clause does not contain aggregate functions.
60356    */
60357    if( pGroupBy ){
60358      struct ExprList_item *pItem;
60359
60360      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
60361        return WRC_Abort;
60362      }
60363      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
60364        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
60365          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
60366              "the GROUP BY clause");
60367          return WRC_Abort;
60368        }
60369      }
60370    }
60371
60372    /* Advance to the next term of the compound
60373    */
60374    p = p->pPrior;
60375    nCompound++;
60376  }
60377
60378  /* Resolve the ORDER BY on a compound SELECT after all terms of
60379  ** the compound have been resolved.
60380  */
60381  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
60382    return WRC_Abort;
60383  }
60384
60385  return WRC_Prune;
60386}
60387
60388/*
60389** This routine walks an expression tree and resolves references to
60390** table columns and result-set columns.  At the same time, do error
60391** checking on function usage and set a flag if any aggregate functions
60392** are seen.
60393**
60394** To resolve table columns references we look for nodes (or subtrees) of the
60395** form X.Y.Z or Y.Z or just Z where
60396**
60397**      X:   The name of a database.  Ex:  "main" or "temp" or
60398**           the symbolic name assigned to an ATTACH-ed database.
60399**
60400**      Y:   The name of a table in a FROM clause.  Or in a trigger
60401**           one of the special names "old" or "new".
60402**
60403**      Z:   The name of a column in table Y.
60404**
60405** The node at the root of the subtree is modified as follows:
60406**
60407**    Expr.op        Changed to TK_COLUMN
60408**    Expr.pTab      Points to the Table object for X.Y
60409**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
60410**    Expr.iTable    The VDBE cursor number for X.Y
60411**
60412**
60413** To resolve result-set references, look for expression nodes of the
60414** form Z (with no X and Y prefix) where the Z matches the right-hand
60415** size of an AS clause in the result-set of a SELECT.  The Z expression
60416** is replaced by a copy of the left-hand side of the result-set expression.
60417** Table-name and function resolution occurs on the substituted expression
60418** tree.  For example, in:
60419**
60420**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
60421**
60422** The "x" term of the order by is replaced by "a+b" to render:
60423**
60424**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
60425**
60426** Function calls are checked to make sure that the function is
60427** defined and that the correct number of arguments are specified.
60428** If the function is an aggregate function, then the pNC->hasAgg is
60429** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
60430** If an expression contains aggregate functions then the EP_Agg
60431** property on the expression is set.
60432**
60433** An error message is left in pParse if anything is amiss.  The number
60434** if errors is returned.
60435*/
60436SQLITE_PRIVATE int sqlite3ResolveExprNames(
60437  NameContext *pNC,       /* Namespace to resolve expressions in. */
60438  Expr *pExpr             /* The expression to be analyzed. */
60439){
60440  int savedHasAgg;
60441  Walker w;
60442
60443  if( pExpr==0 ) return 0;
60444#if SQLITE_MAX_EXPR_DEPTH>0
60445  {
60446    Parse *pParse = pNC->pParse;
60447    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
60448      return 1;
60449    }
60450    pParse->nHeight += pExpr->nHeight;
60451  }
60452#endif
60453  savedHasAgg = pNC->hasAgg;
60454  pNC->hasAgg = 0;
60455  w.xExprCallback = resolveExprStep;
60456  w.xSelectCallback = resolveSelectStep;
60457  w.pParse = pNC->pParse;
60458  w.u.pNC = pNC;
60459  sqlite3WalkExpr(&w, pExpr);
60460#if SQLITE_MAX_EXPR_DEPTH>0
60461  pNC->pParse->nHeight -= pExpr->nHeight;
60462#endif
60463  if( pNC->nErr>0 || w.pParse->nErr>0 ){
60464    ExprSetProperty(pExpr, EP_Error);
60465  }
60466  if( pNC->hasAgg ){
60467    ExprSetProperty(pExpr, EP_Agg);
60468  }else if( savedHasAgg ){
60469    pNC->hasAgg = 1;
60470  }
60471  return ExprHasProperty(pExpr, EP_Error);
60472}
60473
60474
60475/*
60476** Resolve all names in all expressions of a SELECT and in all
60477** decendents of the SELECT, including compounds off of p->pPrior,
60478** subqueries in expressions, and subqueries used as FROM clause
60479** terms.
60480**
60481** See sqlite3ResolveExprNames() for a description of the kinds of
60482** transformations that occur.
60483**
60484** All SELECT statements should have been expanded using
60485** sqlite3SelectExpand() prior to invoking this routine.
60486*/
60487SQLITE_PRIVATE void sqlite3ResolveSelectNames(
60488  Parse *pParse,         /* The parser context */
60489  Select *p,             /* The SELECT statement being coded. */
60490  NameContext *pOuterNC  /* Name context for parent SELECT statement */
60491){
60492  Walker w;
60493
60494  assert( p!=0 );
60495  w.xExprCallback = resolveExprStep;
60496  w.xSelectCallback = resolveSelectStep;
60497  w.pParse = pParse;
60498  w.u.pNC = pOuterNC;
60499  sqlite3WalkSelect(&w, p);
60500}
60501
60502/************** End of resolve.c *********************************************/
60503/************** Begin file expr.c ********************************************/
60504/*
60505** 2001 September 15
60506**
60507** The author disclaims copyright to this source code.  In place of
60508** a legal notice, here is a blessing:
60509**
60510**    May you do good and not evil.
60511**    May you find forgiveness for yourself and forgive others.
60512**    May you share freely, never taking more than you give.
60513**
60514*************************************************************************
60515** This file contains routines used for analyzing expressions and
60516** for generating VDBE code that evaluates expressions in SQLite.
60517*/
60518
60519/*
60520** Return the 'affinity' of the expression pExpr if any.
60521**
60522** If pExpr is a column, a reference to a column via an 'AS' alias,
60523** or a sub-select with a column as the return value, then the
60524** affinity of that column is returned. Otherwise, 0x00 is returned,
60525** indicating no affinity for the expression.
60526**
60527** i.e. the WHERE clause expresssions in the following statements all
60528** have an affinity:
60529**
60530** CREATE TABLE t1(a);
60531** SELECT * FROM t1 WHERE a;
60532** SELECT a AS b FROM t1 WHERE b;
60533** SELECT * FROM t1 WHERE (select a from t1);
60534*/
60535SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
60536  int op = pExpr->op;
60537  if( op==TK_SELECT ){
60538    assert( pExpr->flags&EP_xIsSelect );
60539    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
60540  }
60541#ifndef SQLITE_OMIT_CAST
60542  if( op==TK_CAST ){
60543    assert( !ExprHasProperty(pExpr, EP_IntValue) );
60544    return sqlite3AffinityType(pExpr->u.zToken);
60545  }
60546#endif
60547  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
60548   && pExpr->pTab!=0
60549  ){
60550    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
60551    ** a TK_COLUMN but was previously evaluated and cached in a register */
60552    int j = pExpr->iColumn;
60553    if( j<0 ) return SQLITE_AFF_INTEGER;
60554    assert( pExpr->pTab && j<pExpr->pTab->nCol );
60555    return pExpr->pTab->aCol[j].affinity;
60556  }
60557  return pExpr->affinity;
60558}
60559
60560/*
60561** Set the collating sequence for expression pExpr to be the collating
60562** sequence named by pToken.   Return a pointer to the revised expression.
60563** The collating sequence is marked as "explicit" using the EP_ExpCollate
60564** flag.  An explicit collating sequence will override implicit
60565** collating sequences.
60566*/
60567SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
60568  char *zColl = 0;            /* Dequoted name of collation sequence */
60569  CollSeq *pColl;
60570  sqlite3 *db = pParse->db;
60571  zColl = sqlite3NameFromToken(db, pCollName);
60572  if( pExpr && zColl ){
60573    pColl = sqlite3LocateCollSeq(pParse, zColl);
60574    if( pColl ){
60575      pExpr->pColl = pColl;
60576      pExpr->flags |= EP_ExpCollate;
60577    }
60578  }
60579  sqlite3DbFree(db, zColl);
60580  return pExpr;
60581}
60582
60583/*
60584** Return the default collation sequence for the expression pExpr. If
60585** there is no default collation type, return 0.
60586*/
60587SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
60588  CollSeq *pColl = 0;
60589  Expr *p = pExpr;
60590  while( ALWAYS(p) ){
60591    int op;
60592    pColl = p->pColl;
60593    if( pColl ) break;
60594    op = p->op;
60595    if( p->pTab!=0 && (
60596        op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
60597    )){
60598      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
60599      ** a TK_COLUMN but was previously evaluated and cached in a register */
60600      const char *zColl;
60601      int j = p->iColumn;
60602      if( j>=0 ){
60603        sqlite3 *db = pParse->db;
60604        zColl = p->pTab->aCol[j].zColl;
60605        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
60606        pExpr->pColl = pColl;
60607      }
60608      break;
60609    }
60610    if( op!=TK_CAST && op!=TK_UPLUS ){
60611      break;
60612    }
60613    p = p->pLeft;
60614  }
60615  if( sqlite3CheckCollSeq(pParse, pColl) ){
60616    pColl = 0;
60617  }
60618  return pColl;
60619}
60620
60621/*
60622** pExpr is an operand of a comparison operator.  aff2 is the
60623** type affinity of the other operand.  This routine returns the
60624** type affinity that should be used for the comparison operator.
60625*/
60626SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
60627  char aff1 = sqlite3ExprAffinity(pExpr);
60628  if( aff1 && aff2 ){
60629    /* Both sides of the comparison are columns. If one has numeric
60630    ** affinity, use that. Otherwise use no affinity.
60631    */
60632    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
60633      return SQLITE_AFF_NUMERIC;
60634    }else{
60635      return SQLITE_AFF_NONE;
60636    }
60637  }else if( !aff1 && !aff2 ){
60638    /* Neither side of the comparison is a column.  Compare the
60639    ** results directly.
60640    */
60641    return SQLITE_AFF_NONE;
60642  }else{
60643    /* One side is a column, the other is not. Use the columns affinity. */
60644    assert( aff1==0 || aff2==0 );
60645    return (aff1 + aff2);
60646  }
60647}
60648
60649/*
60650** pExpr is a comparison operator.  Return the type affinity that should
60651** be applied to both operands prior to doing the comparison.
60652*/
60653static char comparisonAffinity(Expr *pExpr){
60654  char aff;
60655  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
60656          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
60657          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
60658  assert( pExpr->pLeft );
60659  aff = sqlite3ExprAffinity(pExpr->pLeft);
60660  if( pExpr->pRight ){
60661    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
60662  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
60663    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
60664  }else if( !aff ){
60665    aff = SQLITE_AFF_NONE;
60666  }
60667  return aff;
60668}
60669
60670/*
60671** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
60672** idx_affinity is the affinity of an indexed column. Return true
60673** if the index with affinity idx_affinity may be used to implement
60674** the comparison in pExpr.
60675*/
60676SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
60677  char aff = comparisonAffinity(pExpr);
60678  switch( aff ){
60679    case SQLITE_AFF_NONE:
60680      return 1;
60681    case SQLITE_AFF_TEXT:
60682      return idx_affinity==SQLITE_AFF_TEXT;
60683    default:
60684      return sqlite3IsNumericAffinity(idx_affinity);
60685  }
60686}
60687
60688/*
60689** Return the P5 value that should be used for a binary comparison
60690** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
60691*/
60692static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
60693  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
60694  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
60695  return aff;
60696}
60697
60698/*
60699** Return a pointer to the collation sequence that should be used by
60700** a binary comparison operator comparing pLeft and pRight.
60701**
60702** If the left hand expression has a collating sequence type, then it is
60703** used. Otherwise the collation sequence for the right hand expression
60704** is used, or the default (BINARY) if neither expression has a collating
60705** type.
60706**
60707** Argument pRight (but not pLeft) may be a null pointer. In this case,
60708** it is not considered.
60709*/
60710SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
60711  Parse *pParse,
60712  Expr *pLeft,
60713  Expr *pRight
60714){
60715  CollSeq *pColl;
60716  assert( pLeft );
60717  if( pLeft->flags & EP_ExpCollate ){
60718    assert( pLeft->pColl );
60719    pColl = pLeft->pColl;
60720  }else if( pRight && pRight->flags & EP_ExpCollate ){
60721    assert( pRight->pColl );
60722    pColl = pRight->pColl;
60723  }else{
60724    pColl = sqlite3ExprCollSeq(pParse, pLeft);
60725    if( !pColl ){
60726      pColl = sqlite3ExprCollSeq(pParse, pRight);
60727    }
60728  }
60729  return pColl;
60730}
60731
60732/*
60733** Generate code for a comparison operator.
60734*/
60735static int codeCompare(
60736  Parse *pParse,    /* The parsing (and code generating) context */
60737  Expr *pLeft,      /* The left operand */
60738  Expr *pRight,     /* The right operand */
60739  int opcode,       /* The comparison opcode */
60740  int in1, int in2, /* Register holding operands */
60741  int dest,         /* Jump here if true.  */
60742  int jumpIfNull    /* If true, jump if either operand is NULL */
60743){
60744  int p5;
60745  int addr;
60746  CollSeq *p4;
60747
60748  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
60749  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
60750  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
60751                           (void*)p4, P4_COLLSEQ);
60752  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
60753  if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
60754    sqlite3ExprCacheAffinityChange(pParse, in1, 1);
60755    sqlite3ExprCacheAffinityChange(pParse, in2, 1);
60756  }
60757  return addr;
60758}
60759
60760#if SQLITE_MAX_EXPR_DEPTH>0
60761/*
60762** Check that argument nHeight is less than or equal to the maximum
60763** expression depth allowed. If it is not, leave an error message in
60764** pParse.
60765*/
60766SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
60767  int rc = SQLITE_OK;
60768  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
60769  if( nHeight>mxHeight ){
60770    sqlite3ErrorMsg(pParse,
60771       "Expression tree is too large (maximum depth %d)", mxHeight
60772    );
60773    rc = SQLITE_ERROR;
60774  }
60775  return rc;
60776}
60777
60778/* The following three functions, heightOfExpr(), heightOfExprList()
60779** and heightOfSelect(), are used to determine the maximum height
60780** of any expression tree referenced by the structure passed as the
60781** first argument.
60782**
60783** If this maximum height is greater than the current value pointed
60784** to by pnHeight, the second parameter, then set *pnHeight to that
60785** value.
60786*/
60787static void heightOfExpr(Expr *p, int *pnHeight){
60788  if( p ){
60789    if( p->nHeight>*pnHeight ){
60790      *pnHeight = p->nHeight;
60791    }
60792  }
60793}
60794static void heightOfExprList(ExprList *p, int *pnHeight){
60795  if( p ){
60796    int i;
60797    for(i=0; i<p->nExpr; i++){
60798      heightOfExpr(p->a[i].pExpr, pnHeight);
60799    }
60800  }
60801}
60802static void heightOfSelect(Select *p, int *pnHeight){
60803  if( p ){
60804    heightOfExpr(p->pWhere, pnHeight);
60805    heightOfExpr(p->pHaving, pnHeight);
60806    heightOfExpr(p->pLimit, pnHeight);
60807    heightOfExpr(p->pOffset, pnHeight);
60808    heightOfExprList(p->pEList, pnHeight);
60809    heightOfExprList(p->pGroupBy, pnHeight);
60810    heightOfExprList(p->pOrderBy, pnHeight);
60811    heightOfSelect(p->pPrior, pnHeight);
60812  }
60813}
60814
60815/*
60816** Set the Expr.nHeight variable in the structure passed as an
60817** argument. An expression with no children, Expr.pList or
60818** Expr.pSelect member has a height of 1. Any other expression
60819** has a height equal to the maximum height of any other
60820** referenced Expr plus one.
60821*/
60822static void exprSetHeight(Expr *p){
60823  int nHeight = 0;
60824  heightOfExpr(p->pLeft, &nHeight);
60825  heightOfExpr(p->pRight, &nHeight);
60826  if( ExprHasProperty(p, EP_xIsSelect) ){
60827    heightOfSelect(p->x.pSelect, &nHeight);
60828  }else{
60829    heightOfExprList(p->x.pList, &nHeight);
60830  }
60831  p->nHeight = nHeight + 1;
60832}
60833
60834/*
60835** Set the Expr.nHeight variable using the exprSetHeight() function. If
60836** the height is greater than the maximum allowed expression depth,
60837** leave an error in pParse.
60838*/
60839SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
60840  exprSetHeight(p);
60841  sqlite3ExprCheckHeight(pParse, p->nHeight);
60842}
60843
60844/*
60845** Return the maximum height of any expression tree referenced
60846** by the select statement passed as an argument.
60847*/
60848SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
60849  int nHeight = 0;
60850  heightOfSelect(p, &nHeight);
60851  return nHeight;
60852}
60853#else
60854  #define exprSetHeight(y)
60855#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
60856
60857/*
60858** This routine is the core allocator for Expr nodes.
60859**
60860** Construct a new expression node and return a pointer to it.  Memory
60861** for this node and for the pToken argument is a single allocation
60862** obtained from sqlite3DbMalloc().  The calling function
60863** is responsible for making sure the node eventually gets freed.
60864**
60865** If dequote is true, then the token (if it exists) is dequoted.
60866** If dequote is false, no dequoting is performance.  The deQuote
60867** parameter is ignored if pToken is NULL or if the token does not
60868** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
60869** then the EP_DblQuoted flag is set on the expression node.
60870**
60871** Special case:  If op==TK_INTEGER and pToken points to a string that
60872** can be translated into a 32-bit integer, then the token is not
60873** stored in u.zToken.  Instead, the integer values is written
60874** into u.iValue and the EP_IntValue flag is set.  No extra storage
60875** is allocated to hold the integer text and the dequote flag is ignored.
60876*/
60877SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
60878  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
60879  int op,                 /* Expression opcode */
60880  const Token *pToken,    /* Token argument.  Might be NULL */
60881  int dequote             /* True to dequote */
60882){
60883  Expr *pNew;
60884  int nExtra = 0;
60885  int iValue = 0;
60886
60887  if( pToken ){
60888    if( op!=TK_INTEGER || pToken->z==0
60889          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
60890      nExtra = pToken->n+1;
60891    }
60892  }
60893  pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
60894  if( pNew ){
60895    pNew->op = (u8)op;
60896    pNew->iAgg = -1;
60897    if( pToken ){
60898      if( nExtra==0 ){
60899        pNew->flags |= EP_IntValue;
60900        pNew->u.iValue = iValue;
60901      }else{
60902        int c;
60903        pNew->u.zToken = (char*)&pNew[1];
60904        memcpy(pNew->u.zToken, pToken->z, pToken->n);
60905        pNew->u.zToken[pToken->n] = 0;
60906        if( dequote && nExtra>=3
60907             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
60908          sqlite3Dequote(pNew->u.zToken);
60909          if( c=='"' ) pNew->flags |= EP_DblQuoted;
60910        }
60911      }
60912    }
60913#if SQLITE_MAX_EXPR_DEPTH>0
60914    pNew->nHeight = 1;
60915#endif
60916  }
60917  return pNew;
60918}
60919
60920/*
60921** Allocate a new expression node from a zero-terminated token that has
60922** already been dequoted.
60923*/
60924SQLITE_PRIVATE Expr *sqlite3Expr(
60925  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
60926  int op,                 /* Expression opcode */
60927  const char *zToken      /* Token argument.  Might be NULL */
60928){
60929  Token x;
60930  x.z = zToken;
60931  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
60932  return sqlite3ExprAlloc(db, op, &x, 0);
60933}
60934
60935/*
60936** Attach subtrees pLeft and pRight to the Expr node pRoot.
60937**
60938** If pRoot==NULL that means that a memory allocation error has occurred.
60939** In that case, delete the subtrees pLeft and pRight.
60940*/
60941SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
60942  sqlite3 *db,
60943  Expr *pRoot,
60944  Expr *pLeft,
60945  Expr *pRight
60946){
60947  if( pRoot==0 ){
60948    assert( db->mallocFailed );
60949    sqlite3ExprDelete(db, pLeft);
60950    sqlite3ExprDelete(db, pRight);
60951  }else{
60952    if( pRight ){
60953      pRoot->pRight = pRight;
60954      if( pRight->flags & EP_ExpCollate ){
60955        pRoot->flags |= EP_ExpCollate;
60956        pRoot->pColl = pRight->pColl;
60957      }
60958    }
60959    if( pLeft ){
60960      pRoot->pLeft = pLeft;
60961      if( pLeft->flags & EP_ExpCollate ){
60962        pRoot->flags |= EP_ExpCollate;
60963        pRoot->pColl = pLeft->pColl;
60964      }
60965    }
60966    exprSetHeight(pRoot);
60967  }
60968}
60969
60970/*
60971** Allocate a Expr node which joins as many as two subtrees.
60972**
60973** One or both of the subtrees can be NULL.  Return a pointer to the new
60974** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
60975** free the subtrees and return NULL.
60976*/
60977SQLITE_PRIVATE Expr *sqlite3PExpr(
60978  Parse *pParse,          /* Parsing context */
60979  int op,                 /* Expression opcode */
60980  Expr *pLeft,            /* Left operand */
60981  Expr *pRight,           /* Right operand */
60982  const Token *pToken     /* Argument token */
60983){
60984  Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
60985  sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
60986  return p;
60987}
60988
60989/*
60990** Join two expressions using an AND operator.  If either expression is
60991** NULL, then just return the other expression.
60992*/
60993SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
60994  if( pLeft==0 ){
60995    return pRight;
60996  }else if( pRight==0 ){
60997    return pLeft;
60998  }else{
60999    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
61000    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
61001    return pNew;
61002  }
61003}
61004
61005/*
61006** Construct a new expression node for a function with multiple
61007** arguments.
61008*/
61009SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
61010  Expr *pNew;
61011  sqlite3 *db = pParse->db;
61012  assert( pToken );
61013  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
61014  if( pNew==0 ){
61015    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
61016    return 0;
61017  }
61018  pNew->x.pList = pList;
61019  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
61020  sqlite3ExprSetHeight(pParse, pNew);
61021  return pNew;
61022}
61023
61024/*
61025** Assign a variable number to an expression that encodes a wildcard
61026** in the original SQL statement.
61027**
61028** Wildcards consisting of a single "?" are assigned the next sequential
61029** variable number.
61030**
61031** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
61032** sure "nnn" is not too be to avoid a denial of service attack when
61033** the SQL statement comes from an external source.
61034**
61035** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
61036** as the previous instance of the same wildcard.  Or if this is the first
61037** instance of the wildcard, the next sequenial variable number is
61038** assigned.
61039*/
61040SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
61041  sqlite3 *db = pParse->db;
61042  const char *z;
61043
61044  if( pExpr==0 ) return;
61045  assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
61046  z = pExpr->u.zToken;
61047  assert( z!=0 );
61048  assert( z[0]!=0 );
61049  if( z[1]==0 ){
61050    /* Wildcard of the form "?".  Assign the next variable number */
61051    assert( z[0]=='?' );
61052    pExpr->iColumn = (ynVar)(++pParse->nVar);
61053  }else if( z[0]=='?' ){
61054    /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
61055    ** use it as the variable number */
61056    int i = atoi((char*)&z[1]);
61057    pExpr->iColumn = (ynVar)i;
61058    testcase( i==0 );
61059    testcase( i==1 );
61060    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
61061    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
61062    if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
61063      sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
61064          db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
61065    }
61066    if( i>pParse->nVar ){
61067      pParse->nVar = i;
61068    }
61069  }else{
61070    /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
61071    ** number as the prior appearance of the same name, or if the name
61072    ** has never appeared before, reuse the same variable number
61073    */
61074    int i;
61075    u32 n;
61076    n = sqlite3Strlen30(z);
61077    for(i=0; i<pParse->nVarExpr; i++){
61078      Expr *pE = pParse->apVarExpr[i];
61079      assert( pE!=0 );
61080      if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
61081        pExpr->iColumn = pE->iColumn;
61082        break;
61083      }
61084    }
61085    if( i>=pParse->nVarExpr ){
61086      pExpr->iColumn = (ynVar)(++pParse->nVar);
61087      if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
61088        pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
61089        pParse->apVarExpr =
61090            sqlite3DbReallocOrFree(
61091              db,
61092              pParse->apVarExpr,
61093              pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
61094            );
61095      }
61096      if( !db->mallocFailed ){
61097        assert( pParse->apVarExpr!=0 );
61098        pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
61099      }
61100    }
61101  }
61102  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
61103    sqlite3ErrorMsg(pParse, "too many SQL variables");
61104  }
61105}
61106
61107/*
61108** Recursively delete an expression tree.
61109*/
61110SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
61111  if( p==0 ) return;
61112  if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
61113    sqlite3ExprDelete(db, p->pLeft);
61114    sqlite3ExprDelete(db, p->pRight);
61115    if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
61116      sqlite3DbFree(db, p->u.zToken);
61117    }
61118    if( ExprHasProperty(p, EP_xIsSelect) ){
61119      sqlite3SelectDelete(db, p->x.pSelect);
61120    }else{
61121      sqlite3ExprListDelete(db, p->x.pList);
61122    }
61123  }
61124  if( !ExprHasProperty(p, EP_Static) ){
61125    sqlite3DbFree(db, p);
61126  }
61127}
61128
61129/*
61130** Return the number of bytes allocated for the expression structure
61131** passed as the first argument. This is always one of EXPR_FULLSIZE,
61132** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
61133*/
61134static int exprStructSize(Expr *p){
61135  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
61136  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
61137  return EXPR_FULLSIZE;
61138}
61139
61140/*
61141** The dupedExpr*Size() routines each return the number of bytes required
61142** to store a copy of an expression or expression tree.  They differ in
61143** how much of the tree is measured.
61144**
61145**     dupedExprStructSize()     Size of only the Expr structure
61146**     dupedExprNodeSize()       Size of Expr + space for token
61147**     dupedExprSize()           Expr + token + subtree components
61148**
61149***************************************************************************
61150**
61151** The dupedExprStructSize() function returns two values OR-ed together:
61152** (1) the space required for a copy of the Expr structure only and
61153** (2) the EP_xxx flags that indicate what the structure size should be.
61154** The return values is always one of:
61155**
61156**      EXPR_FULLSIZE
61157**      EXPR_REDUCEDSIZE   | EP_Reduced
61158**      EXPR_TOKENONLYSIZE | EP_TokenOnly
61159**
61160** The size of the structure can be found by masking the return value
61161** of this routine with 0xfff.  The flags can be found by masking the
61162** return value with EP_Reduced|EP_TokenOnly.
61163**
61164** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
61165** (unreduced) Expr objects as they or originally constructed by the parser.
61166** During expression analysis, extra information is computed and moved into
61167** later parts of teh Expr object and that extra information might get chopped
61168** off if the expression is reduced.  Note also that it does not work to
61169** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
61170** to reduce a pristine expression tree from the parser.  The implementation
61171** of dupedExprStructSize() contain multiple assert() statements that attempt
61172** to enforce this constraint.
61173*/
61174static int dupedExprStructSize(Expr *p, int flags){
61175  int nSize;
61176  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
61177  if( 0==(flags&EXPRDUP_REDUCE) ){
61178    nSize = EXPR_FULLSIZE;
61179  }else{
61180    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
61181    assert( !ExprHasProperty(p, EP_FromJoin) );
61182    assert( (p->flags2 & EP2_MallocedToken)==0 );
61183    assert( (p->flags2 & EP2_Irreducible)==0 );
61184    if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
61185      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
61186    }else{
61187      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
61188    }
61189  }
61190  return nSize;
61191}
61192
61193/*
61194** This function returns the space in bytes required to store the copy
61195** of the Expr structure and a copy of the Expr.u.zToken string (if that
61196** string is defined.)
61197*/
61198static int dupedExprNodeSize(Expr *p, int flags){
61199  int nByte = dupedExprStructSize(p, flags) & 0xfff;
61200  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
61201    nByte += sqlite3Strlen30(p->u.zToken)+1;
61202  }
61203  return ROUND8(nByte);
61204}
61205
61206/*
61207** Return the number of bytes required to create a duplicate of the
61208** expression passed as the first argument. The second argument is a
61209** mask containing EXPRDUP_XXX flags.
61210**
61211** The value returned includes space to create a copy of the Expr struct
61212** itself and the buffer referred to by Expr.u.zToken, if any.
61213**
61214** If the EXPRDUP_REDUCE flag is set, then the return value includes
61215** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
61216** and Expr.pRight variables (but not for any structures pointed to or
61217** descended from the Expr.x.pList or Expr.x.pSelect variables).
61218*/
61219static int dupedExprSize(Expr *p, int flags){
61220  int nByte = 0;
61221  if( p ){
61222    nByte = dupedExprNodeSize(p, flags);
61223    if( flags&EXPRDUP_REDUCE ){
61224      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
61225    }
61226  }
61227  return nByte;
61228}
61229
61230/*
61231** This function is similar to sqlite3ExprDup(), except that if pzBuffer
61232** is not NULL then *pzBuffer is assumed to point to a buffer large enough
61233** to store the copy of expression p, the copies of p->u.zToken
61234** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
61235** if any. Before returning, *pzBuffer is set to the first byte passed the
61236** portion of the buffer copied into by this function.
61237*/
61238static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
61239  Expr *pNew = 0;                      /* Value to return */
61240  if( p ){
61241    const int isReduced = (flags&EXPRDUP_REDUCE);
61242    u8 *zAlloc;
61243    u32 staticFlag = 0;
61244
61245    assert( pzBuffer==0 || isReduced );
61246
61247    /* Figure out where to write the new Expr structure. */
61248    if( pzBuffer ){
61249      zAlloc = *pzBuffer;
61250      staticFlag = EP_Static;
61251    }else{
61252      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
61253    }
61254    pNew = (Expr *)zAlloc;
61255
61256    if( pNew ){
61257      /* Set nNewSize to the size allocated for the structure pointed to
61258      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
61259      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
61260      ** by the copy of the p->u.zToken string (if any).
61261      */
61262      const unsigned nStructSize = dupedExprStructSize(p, flags);
61263      const int nNewSize = nStructSize & 0xfff;
61264      int nToken;
61265      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
61266        nToken = sqlite3Strlen30(p->u.zToken) + 1;
61267      }else{
61268        nToken = 0;
61269      }
61270      if( isReduced ){
61271        assert( ExprHasProperty(p, EP_Reduced)==0 );
61272        memcpy(zAlloc, p, nNewSize);
61273      }else{
61274        int nSize = exprStructSize(p);
61275        memcpy(zAlloc, p, nSize);
61276        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
61277      }
61278
61279      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
61280      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
61281      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
61282      pNew->flags |= staticFlag;
61283
61284      /* Copy the p->u.zToken string, if any. */
61285      if( nToken ){
61286        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
61287        memcpy(zToken, p->u.zToken, nToken);
61288      }
61289
61290      if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
61291        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
61292        if( ExprHasProperty(p, EP_xIsSelect) ){
61293          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
61294        }else{
61295          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
61296        }
61297      }
61298
61299      /* Fill in pNew->pLeft and pNew->pRight. */
61300      if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
61301        zAlloc += dupedExprNodeSize(p, flags);
61302        if( ExprHasProperty(pNew, EP_Reduced) ){
61303          pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
61304          pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
61305        }
61306        if( pzBuffer ){
61307          *pzBuffer = zAlloc;
61308        }
61309      }else{
61310        pNew->flags2 = 0;
61311        if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
61312          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
61313          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
61314        }
61315      }
61316
61317    }
61318  }
61319  return pNew;
61320}
61321
61322/*
61323** The following group of routines make deep copies of expressions,
61324** expression lists, ID lists, and select statements.  The copies can
61325** be deleted (by being passed to their respective ...Delete() routines)
61326** without effecting the originals.
61327**
61328** The expression list, ID, and source lists return by sqlite3ExprListDup(),
61329** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
61330** by subsequent calls to sqlite*ListAppend() routines.
61331**
61332** Any tables that the SrcList might point to are not duplicated.
61333**
61334** The flags parameter contains a combination of the EXPRDUP_XXX flags.
61335** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
61336** truncated version of the usual Expr structure that will be stored as
61337** part of the in-memory representation of the database schema.
61338*/
61339SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
61340  return exprDup(db, p, flags, 0);
61341}
61342SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
61343  ExprList *pNew;
61344  struct ExprList_item *pItem, *pOldItem;
61345  int i;
61346  if( p==0 ) return 0;
61347  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
61348  if( pNew==0 ) return 0;
61349  pNew->iECursor = 0;
61350  pNew->nExpr = pNew->nAlloc = p->nExpr;
61351  pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
61352  if( pItem==0 ){
61353    sqlite3DbFree(db, pNew);
61354    return 0;
61355  }
61356  pOldItem = p->a;
61357  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
61358    Expr *pOldExpr = pOldItem->pExpr;
61359    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
61360    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
61361    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
61362    pItem->sortOrder = pOldItem->sortOrder;
61363    pItem->done = 0;
61364    pItem->iCol = pOldItem->iCol;
61365    pItem->iAlias = pOldItem->iAlias;
61366  }
61367  return pNew;
61368}
61369
61370/*
61371** If cursors, triggers, views and subqueries are all omitted from
61372** the build, then none of the following routines, except for
61373** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
61374** called with a NULL argument.
61375*/
61376#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
61377 || !defined(SQLITE_OMIT_SUBQUERY)
61378SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
61379  SrcList *pNew;
61380  int i;
61381  int nByte;
61382  if( p==0 ) return 0;
61383  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
61384  pNew = sqlite3DbMallocRaw(db, nByte );
61385  if( pNew==0 ) return 0;
61386  pNew->nSrc = pNew->nAlloc = p->nSrc;
61387  for(i=0; i<p->nSrc; i++){
61388    struct SrcList_item *pNewItem = &pNew->a[i];
61389    struct SrcList_item *pOldItem = &p->a[i];
61390    Table *pTab;
61391    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
61392    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
61393    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
61394    pNewItem->jointype = pOldItem->jointype;
61395    pNewItem->iCursor = pOldItem->iCursor;
61396    pNewItem->isPopulated = pOldItem->isPopulated;
61397    pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
61398    pNewItem->notIndexed = pOldItem->notIndexed;
61399    pNewItem->pIndex = pOldItem->pIndex;
61400    pTab = pNewItem->pTab = pOldItem->pTab;
61401    if( pTab ){
61402      pTab->nRef++;
61403    }
61404    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
61405    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
61406    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
61407    pNewItem->colUsed = pOldItem->colUsed;
61408  }
61409  return pNew;
61410}
61411SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
61412  IdList *pNew;
61413  int i;
61414  if( p==0 ) return 0;
61415  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
61416  if( pNew==0 ) return 0;
61417  pNew->nId = pNew->nAlloc = p->nId;
61418  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
61419  if( pNew->a==0 ){
61420    sqlite3DbFree(db, pNew);
61421    return 0;
61422  }
61423  for(i=0; i<p->nId; i++){
61424    struct IdList_item *pNewItem = &pNew->a[i];
61425    struct IdList_item *pOldItem = &p->a[i];
61426    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
61427    pNewItem->idx = pOldItem->idx;
61428  }
61429  return pNew;
61430}
61431SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
61432  Select *pNew;
61433  if( p==0 ) return 0;
61434  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
61435  if( pNew==0 ) return 0;
61436  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
61437  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
61438  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
61439  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
61440  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
61441  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
61442  pNew->op = p->op;
61443  pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
61444  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
61445  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
61446  pNew->iLimit = 0;
61447  pNew->iOffset = 0;
61448  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
61449  pNew->pRightmost = 0;
61450  pNew->addrOpenEphm[0] = -1;
61451  pNew->addrOpenEphm[1] = -1;
61452  pNew->addrOpenEphm[2] = -1;
61453  return pNew;
61454}
61455#else
61456SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
61457  assert( p==0 );
61458  return 0;
61459}
61460#endif
61461
61462
61463/*
61464** Add a new element to the end of an expression list.  If pList is
61465** initially NULL, then create a new expression list.
61466**
61467** If a memory allocation error occurs, the entire list is freed and
61468** NULL is returned.  If non-NULL is returned, then it is guaranteed
61469** that the new entry was successfully appended.
61470*/
61471SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
61472  Parse *pParse,          /* Parsing context */
61473  ExprList *pList,        /* List to which to append. Might be NULL */
61474  Expr *pExpr             /* Expression to be appended. Might be NULL */
61475){
61476  sqlite3 *db = pParse->db;
61477  if( pList==0 ){
61478    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
61479    if( pList==0 ){
61480      goto no_mem;
61481    }
61482    assert( pList->nAlloc==0 );
61483  }
61484  if( pList->nAlloc<=pList->nExpr ){
61485    struct ExprList_item *a;
61486    int n = pList->nAlloc*2 + 4;
61487    a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
61488    if( a==0 ){
61489      goto no_mem;
61490    }
61491    pList->a = a;
61492    pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
61493  }
61494  assert( pList->a!=0 );
61495  if( 1 ){
61496    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
61497    memset(pItem, 0, sizeof(*pItem));
61498    pItem->pExpr = pExpr;
61499  }
61500  return pList;
61501
61502no_mem:
61503  /* Avoid leaking memory if malloc has failed. */
61504  sqlite3ExprDelete(db, pExpr);
61505  sqlite3ExprListDelete(db, pList);
61506  return 0;
61507}
61508
61509/*
61510** Set the ExprList.a[].zName element of the most recently added item
61511** on the expression list.
61512**
61513** pList might be NULL following an OOM error.  But pName should never be
61514** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
61515** is set.
61516*/
61517SQLITE_PRIVATE void sqlite3ExprListSetName(
61518  Parse *pParse,          /* Parsing context */
61519  ExprList *pList,        /* List to which to add the span. */
61520  Token *pName,           /* Name to be added */
61521  int dequote             /* True to cause the name to be dequoted */
61522){
61523  assert( pList!=0 || pParse->db->mallocFailed!=0 );
61524  if( pList ){
61525    struct ExprList_item *pItem;
61526    assert( pList->nExpr>0 );
61527    pItem = &pList->a[pList->nExpr-1];
61528    assert( pItem->zName==0 );
61529    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
61530    if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
61531  }
61532}
61533
61534/*
61535** Set the ExprList.a[].zSpan element of the most recently added item
61536** on the expression list.
61537**
61538** pList might be NULL following an OOM error.  But pSpan should never be
61539** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
61540** is set.
61541*/
61542SQLITE_PRIVATE void sqlite3ExprListSetSpan(
61543  Parse *pParse,          /* Parsing context */
61544  ExprList *pList,        /* List to which to add the span. */
61545  ExprSpan *pSpan         /* The span to be added */
61546){
61547  sqlite3 *db = pParse->db;
61548  assert( pList!=0 || db->mallocFailed!=0 );
61549  if( pList ){
61550    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
61551    assert( pList->nExpr>0 );
61552    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
61553    sqlite3DbFree(db, pItem->zSpan);
61554    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
61555                                    (int)(pSpan->zEnd - pSpan->zStart));
61556  }
61557}
61558
61559/*
61560** If the expression list pEList contains more than iLimit elements,
61561** leave an error message in pParse.
61562*/
61563SQLITE_PRIVATE void sqlite3ExprListCheckLength(
61564  Parse *pParse,
61565  ExprList *pEList,
61566  const char *zObject
61567){
61568  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
61569  testcase( pEList && pEList->nExpr==mx );
61570  testcase( pEList && pEList->nExpr==mx+1 );
61571  if( pEList && pEList->nExpr>mx ){
61572    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
61573  }
61574}
61575
61576/*
61577** Delete an entire expression list.
61578*/
61579SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
61580  int i;
61581  struct ExprList_item *pItem;
61582  if( pList==0 ) return;
61583  assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
61584  assert( pList->nExpr<=pList->nAlloc );
61585  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
61586    sqlite3ExprDelete(db, pItem->pExpr);
61587    sqlite3DbFree(db, pItem->zName);
61588    sqlite3DbFree(db, pItem->zSpan);
61589  }
61590  sqlite3DbFree(db, pList->a);
61591  sqlite3DbFree(db, pList);
61592}
61593
61594/*
61595** These routines are Walker callbacks.  Walker.u.pi is a pointer
61596** to an integer.  These routines are checking an expression to see
61597** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
61598** not constant.
61599**
61600** These callback routines are used to implement the following:
61601**
61602**     sqlite3ExprIsConstant()
61603**     sqlite3ExprIsConstantNotJoin()
61604**     sqlite3ExprIsConstantOrFunction()
61605**
61606*/
61607static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
61608
61609  /* If pWalker->u.i is 3 then any term of the expression that comes from
61610  ** the ON or USING clauses of a join disqualifies the expression
61611  ** from being considered constant. */
61612  if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
61613    pWalker->u.i = 0;
61614    return WRC_Abort;
61615  }
61616
61617  switch( pExpr->op ){
61618    /* Consider functions to be constant if all their arguments are constant
61619    ** and pWalker->u.i==2 */
61620    case TK_FUNCTION:
61621      if( pWalker->u.i==2 ) return 0;
61622      /* Fall through */
61623    case TK_ID:
61624    case TK_COLUMN:
61625    case TK_AGG_FUNCTION:
61626    case TK_AGG_COLUMN:
61627      testcase( pExpr->op==TK_ID );
61628      testcase( pExpr->op==TK_COLUMN );
61629      testcase( pExpr->op==TK_AGG_FUNCTION );
61630      testcase( pExpr->op==TK_AGG_COLUMN );
61631      pWalker->u.i = 0;
61632      return WRC_Abort;
61633    default:
61634      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
61635      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
61636      return WRC_Continue;
61637  }
61638}
61639static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
61640  UNUSED_PARAMETER(NotUsed);
61641  pWalker->u.i = 0;
61642  return WRC_Abort;
61643}
61644static int exprIsConst(Expr *p, int initFlag){
61645  Walker w;
61646  w.u.i = initFlag;
61647  w.xExprCallback = exprNodeIsConstant;
61648  w.xSelectCallback = selectNodeIsConstant;
61649  sqlite3WalkExpr(&w, p);
61650  return w.u.i;
61651}
61652
61653/*
61654** Walk an expression tree.  Return 1 if the expression is constant
61655** and 0 if it involves variables or function calls.
61656**
61657** For the purposes of this function, a double-quoted string (ex: "abc")
61658** is considered a variable but a single-quoted string (ex: 'abc') is
61659** a constant.
61660*/
61661SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
61662  return exprIsConst(p, 1);
61663}
61664
61665/*
61666** Walk an expression tree.  Return 1 if the expression is constant
61667** that does no originate from the ON or USING clauses of a join.
61668** Return 0 if it involves variables or function calls or terms from
61669** an ON or USING clause.
61670*/
61671SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
61672  return exprIsConst(p, 3);
61673}
61674
61675/*
61676** Walk an expression tree.  Return 1 if the expression is constant
61677** or a function call with constant arguments.  Return and 0 if there
61678** are any variables.
61679**
61680** For the purposes of this function, a double-quoted string (ex: "abc")
61681** is considered a variable but a single-quoted string (ex: 'abc') is
61682** a constant.
61683*/
61684SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
61685  return exprIsConst(p, 2);
61686}
61687
61688/*
61689** If the expression p codes a constant integer that is small enough
61690** to fit in a 32-bit integer, return 1 and put the value of the integer
61691** in *pValue.  If the expression is not an integer or if it is too big
61692** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
61693*/
61694SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
61695  int rc = 0;
61696  if( p->flags & EP_IntValue ){
61697    *pValue = p->u.iValue;
61698    return 1;
61699  }
61700  switch( p->op ){
61701    case TK_INTEGER: {
61702      rc = sqlite3GetInt32(p->u.zToken, pValue);
61703      assert( rc==0 );
61704      break;
61705    }
61706    case TK_UPLUS: {
61707      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
61708      break;
61709    }
61710    case TK_UMINUS: {
61711      int v;
61712      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
61713        *pValue = -v;
61714        rc = 1;
61715      }
61716      break;
61717    }
61718    default: break;
61719  }
61720  if( rc ){
61721    assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
61722               || (p->flags2 & EP2_MallocedToken)==0 );
61723    p->op = TK_INTEGER;
61724    p->flags |= EP_IntValue;
61725    p->u.iValue = *pValue;
61726  }
61727  return rc;
61728}
61729
61730/*
61731** Return FALSE if there is no chance that the expression can be NULL.
61732**
61733** If the expression might be NULL or if the expression is too complex
61734** to tell return TRUE.
61735**
61736** This routine is used as an optimization, to skip OP_IsNull opcodes
61737** when we know that a value cannot be NULL.  Hence, a false positive
61738** (returning TRUE when in fact the expression can never be NULL) might
61739** be a small performance hit but is otherwise harmless.  On the other
61740** hand, a false negative (returning FALSE when the result could be NULL)
61741** will likely result in an incorrect answer.  So when in doubt, return
61742** TRUE.
61743*/
61744SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
61745  u8 op;
61746  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
61747  op = p->op;
61748  if( op==TK_REGISTER ) op = p->op2;
61749  switch( op ){
61750    case TK_INTEGER:
61751    case TK_STRING:
61752    case TK_FLOAT:
61753    case TK_BLOB:
61754      return 0;
61755    default:
61756      return 1;
61757  }
61758}
61759
61760/*
61761** Generate an OP_IsNull instruction that tests register iReg and jumps
61762** to location iDest if the value in iReg is NULL.  The value in iReg
61763** was computed by pExpr.  If we can look at pExpr at compile-time and
61764** determine that it can never generate a NULL, then the OP_IsNull operation
61765** can be omitted.
61766*/
61767SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
61768  Vdbe *v,            /* The VDBE under construction */
61769  const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
61770  int iReg,           /* Test the value in this register for NULL */
61771  int iDest           /* Jump here if the value is null */
61772){
61773  if( sqlite3ExprCanBeNull(pExpr) ){
61774    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
61775  }
61776}
61777
61778/*
61779** Return TRUE if the given expression is a constant which would be
61780** unchanged by OP_Affinity with the affinity given in the second
61781** argument.
61782**
61783** This routine is used to determine if the OP_Affinity operation
61784** can be omitted.  When in doubt return FALSE.  A false negative
61785** is harmless.  A false positive, however, can result in the wrong
61786** answer.
61787*/
61788SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
61789  u8 op;
61790  if( aff==SQLITE_AFF_NONE ) return 1;
61791  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
61792  op = p->op;
61793  if( op==TK_REGISTER ) op = p->op2;
61794  switch( op ){
61795    case TK_INTEGER: {
61796      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
61797    }
61798    case TK_FLOAT: {
61799      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
61800    }
61801    case TK_STRING: {
61802      return aff==SQLITE_AFF_TEXT;
61803    }
61804    case TK_BLOB: {
61805      return 1;
61806    }
61807    case TK_COLUMN: {
61808      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
61809      return p->iColumn<0
61810          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
61811    }
61812    default: {
61813      return 0;
61814    }
61815  }
61816}
61817
61818/*
61819** Return TRUE if the given string is a row-id column name.
61820*/
61821SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
61822  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
61823  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
61824  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
61825  return 0;
61826}
61827
61828/*
61829** Return true if we are able to the IN operator optimization on a
61830** query of the form
61831**
61832**       x IN (SELECT ...)
61833**
61834** Where the SELECT... clause is as specified by the parameter to this
61835** routine.
61836**
61837** The Select object passed in has already been preprocessed and no
61838** errors have been found.
61839*/
61840#ifndef SQLITE_OMIT_SUBQUERY
61841static int isCandidateForInOpt(Select *p){
61842  SrcList *pSrc;
61843  ExprList *pEList;
61844  Table *pTab;
61845  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
61846  if( p->pPrior ) return 0;              /* Not a compound SELECT */
61847  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
61848    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
61849    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
61850    return 0; /* No DISTINCT keyword and no aggregate functions */
61851  }
61852  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
61853  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
61854  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
61855  if( p->pWhere ) return 0;              /* Has no WHERE clause */
61856  pSrc = p->pSrc;
61857  assert( pSrc!=0 );
61858  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
61859  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
61860  pTab = pSrc->a[0].pTab;
61861  if( NEVER(pTab==0) ) return 0;
61862  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
61863  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
61864  pEList = p->pEList;
61865  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
61866  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
61867  return 1;
61868}
61869#endif /* SQLITE_OMIT_SUBQUERY */
61870
61871/*
61872** This function is used by the implementation of the IN (...) operator.
61873** It's job is to find or create a b-tree structure that may be used
61874** either to test for membership of the (...) set or to iterate through
61875** its members, skipping duplicates.
61876**
61877** The index of the cursor opened on the b-tree (database table, database index
61878** or ephermal table) is stored in pX->iTable before this function returns.
61879** The returned value of this function indicates the b-tree type, as follows:
61880**
61881**   IN_INDEX_ROWID - The cursor was opened on a database table.
61882**   IN_INDEX_INDEX - The cursor was opened on a database index.
61883**   IN_INDEX_EPH -   The cursor was opened on a specially created and
61884**                    populated epheremal table.
61885**
61886** An existing b-tree may only be used if the SELECT is of the simple
61887** form:
61888**
61889**     SELECT <column> FROM <table>
61890**
61891** If the prNotFound parameter is 0, then the b-tree will be used to iterate
61892** through the set members, skipping any duplicates. In this case an
61893** epheremal table must be used unless the selected <column> is guaranteed
61894** to be unique - either because it is an INTEGER PRIMARY KEY or it
61895** has a UNIQUE constraint or UNIQUE index.
61896**
61897** If the prNotFound parameter is not 0, then the b-tree will be used
61898** for fast set membership tests. In this case an epheremal table must
61899** be used unless <column> is an INTEGER PRIMARY KEY or an index can
61900** be found with <column> as its left-most column.
61901**
61902** When the b-tree is being used for membership tests, the calling function
61903** needs to know whether or not the structure contains an SQL NULL
61904** value in order to correctly evaluate expressions like "X IN (Y, Z)".
61905** If there is any chance that the (...) might contain a NULL value at
61906** runtime, then a register is allocated and the register number written
61907** to *prNotFound. If there is no chance that the (...) contains a
61908** NULL value, then *prNotFound is left unchanged.
61909**
61910** If a register is allocated and its location stored in *prNotFound, then
61911** its initial value is NULL.  If the (...) does not remain constant
61912** for the duration of the query (i.e. the SELECT within the (...)
61913** is a correlated subquery) then the value of the allocated register is
61914** reset to NULL each time the subquery is rerun. This allows the
61915** caller to use vdbe code equivalent to the following:
61916**
61917**   if( register==NULL ){
61918**     has_null = <test if data structure contains null>
61919**     register = 1
61920**   }
61921**
61922** in order to avoid running the <test if data structure contains null>
61923** test more often than is necessary.
61924*/
61925#ifndef SQLITE_OMIT_SUBQUERY
61926SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
61927  Select *p;                            /* SELECT to the right of IN operator */
61928  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
61929  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
61930  int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
61931
61932  assert( pX->op==TK_IN );
61933
61934  /* Check to see if an existing table or index can be used to
61935  ** satisfy the query.  This is preferable to generating a new
61936  ** ephemeral table.
61937  */
61938  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
61939  if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
61940    sqlite3 *db = pParse->db;              /* Database connection */
61941    Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
61942    int iCol = pExpr->iColumn;             /* Index of column <column> */
61943    Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
61944    Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
61945    int iDb;                               /* Database idx for pTab */
61946
61947    /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
61948    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
61949    sqlite3CodeVerifySchema(pParse, iDb);
61950    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
61951
61952    /* This function is only called from two places. In both cases the vdbe
61953    ** has already been allocated. So assume sqlite3GetVdbe() is always
61954    ** successful here.
61955    */
61956    assert(v);
61957    if( iCol<0 ){
61958      int iMem = ++pParse->nMem;
61959      int iAddr;
61960
61961      iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
61962      sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
61963
61964      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
61965      eType = IN_INDEX_ROWID;
61966
61967      sqlite3VdbeJumpHere(v, iAddr);
61968    }else{
61969      Index *pIdx;                         /* Iterator variable */
61970
61971      /* The collation sequence used by the comparison. If an index is to
61972      ** be used in place of a temp-table, it must be ordered according
61973      ** to this collation sequence.  */
61974      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
61975
61976      /* Check that the affinity that will be used to perform the
61977      ** comparison is the same as the affinity of the column. If
61978      ** it is not, it is not possible to use any index.
61979      */
61980      char aff = comparisonAffinity(pX);
61981      int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
61982
61983      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
61984        if( (pIdx->aiColumn[0]==iCol)
61985         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
61986         && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
61987        ){
61988          int iMem = ++pParse->nMem;
61989          int iAddr;
61990          char *pKey;
61991
61992          pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
61993          iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
61994          sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
61995
61996          sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
61997                               pKey,P4_KEYINFO_HANDOFF);
61998          VdbeComment((v, "%s", pIdx->zName));
61999          eType = IN_INDEX_INDEX;
62000
62001          sqlite3VdbeJumpHere(v, iAddr);
62002          if( prNotFound && !pTab->aCol[iCol].notNull ){
62003            *prNotFound = ++pParse->nMem;
62004          }
62005        }
62006      }
62007    }
62008  }
62009
62010  if( eType==0 ){
62011    /* Could not found an existing table or index to use as the RHS b-tree.
62012    ** We will have to generate an ephemeral table to do the job.
62013    */
62014    int rMayHaveNull = 0;
62015    eType = IN_INDEX_EPH;
62016    if( prNotFound ){
62017      *prNotFound = rMayHaveNull = ++pParse->nMem;
62018    }else if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
62019      eType = IN_INDEX_ROWID;
62020    }
62021    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
62022  }else{
62023    pX->iTable = iTab;
62024  }
62025  return eType;
62026}
62027#endif
62028
62029/*
62030** Generate code for scalar subqueries used as an expression
62031** and IN operators.  Examples:
62032**
62033**     (SELECT a FROM b)          -- subquery
62034**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
62035**     x IN (4,5,11)              -- IN operator with list on right-hand side
62036**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
62037**
62038** The pExpr parameter describes the expression that contains the IN
62039** operator or subquery.
62040**
62041** If parameter isRowid is non-zero, then expression pExpr is guaranteed
62042** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
62043** to some integer key column of a table B-Tree. In this case, use an
62044** intkey B-Tree to store the set of IN(...) values instead of the usual
62045** (slower) variable length keys B-Tree.
62046**
62047** If rMayHaveNull is non-zero, that means that the operation is an IN
62048** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
62049** Furthermore, the IN is in a WHERE clause and that we really want
62050** to iterate over the RHS of the IN operator in order to quickly locate
62051** all corresponding LHS elements.  All this routine does is initialize
62052** the register given by rMayHaveNull to NULL.  Calling routines will take
62053** care of changing this register value to non-NULL if the RHS is NULL-free.
62054**
62055** If rMayHaveNull is zero, that means that the subquery is being used
62056** for membership testing only.  There is no need to initialize any
62057** registers to indicate the presense or absence of NULLs on the RHS.
62058**
62059** For a SELECT or EXISTS operator, return the register that holds the
62060** result.  For IN operators or if an error occurs, the return value is 0.
62061*/
62062#ifndef SQLITE_OMIT_SUBQUERY
62063SQLITE_PRIVATE int sqlite3CodeSubselect(
62064  Parse *pParse,          /* Parsing context */
62065  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
62066  int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
62067  int isRowid             /* If true, LHS of IN operator is a rowid */
62068){
62069  int testAddr = 0;                       /* One-time test address */
62070  int rReg = 0;                           /* Register storing resulting */
62071  Vdbe *v = sqlite3GetVdbe(pParse);
62072  if( NEVER(v==0) ) return 0;
62073  sqlite3ExprCachePush(pParse);
62074
62075  /* This code must be run in its entirety every time it is encountered
62076  ** if any of the following is true:
62077  **
62078  **    *  The right-hand side is a correlated subquery
62079  **    *  The right-hand side is an expression list containing variables
62080  **    *  We are inside a trigger
62081  **
62082  ** If all of the above are false, then we can run this code just once
62083  ** save the results, and reuse the same result on subsequent invocations.
62084  */
62085  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
62086    int mem = ++pParse->nMem;
62087    sqlite3VdbeAddOp1(v, OP_If, mem);
62088    testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
62089    assert( testAddr>0 || pParse->db->mallocFailed );
62090  }
62091
62092  switch( pExpr->op ){
62093    case TK_IN: {
62094      char affinity;
62095      KeyInfo keyInfo;
62096      int addr;        /* Address of OP_OpenEphemeral instruction */
62097      Expr *pLeft = pExpr->pLeft;
62098
62099      if( rMayHaveNull ){
62100        sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
62101      }
62102
62103      affinity = sqlite3ExprAffinity(pLeft);
62104
62105      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
62106      ** expression it is handled the same way.  An ephemeral table is
62107      ** filled with single-field index keys representing the results
62108      ** from the SELECT or the <exprlist>.
62109      **
62110      ** If the 'x' expression is a column value, or the SELECT...
62111      ** statement returns a column value, then the affinity of that
62112      ** column is used to build the index keys. If both 'x' and the
62113      ** SELECT... statement are columns, then numeric affinity is used
62114      ** if either column has NUMERIC or INTEGER affinity. If neither
62115      ** 'x' nor the SELECT... statement are columns, then numeric affinity
62116      ** is used.
62117      */
62118      pExpr->iTable = pParse->nTab++;
62119      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
62120      memset(&keyInfo, 0, sizeof(keyInfo));
62121      keyInfo.nField = 1;
62122
62123      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
62124        /* Case 1:     expr IN (SELECT ...)
62125        **
62126        ** Generate code to write the results of the select into the temporary
62127        ** table allocated and opened above.
62128        */
62129        SelectDest dest;
62130        ExprList *pEList;
62131
62132        assert( !isRowid );
62133        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
62134        dest.affinity = (u8)affinity;
62135        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
62136        if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
62137          return 0;
62138        }
62139        pEList = pExpr->x.pSelect->pEList;
62140        if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
62141          keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
62142              pEList->a[0].pExpr);
62143        }
62144      }else if( pExpr->x.pList!=0 ){
62145        /* Case 2:     expr IN (exprlist)
62146        **
62147        ** For each expression, build an index key from the evaluation and
62148        ** store it in the temporary table. If <expr> is a column, then use
62149        ** that columns affinity when building index keys. If <expr> is not
62150        ** a column, use numeric affinity.
62151        */
62152        int i;
62153        ExprList *pList = pExpr->x.pList;
62154        struct ExprList_item *pItem;
62155        int r1, r2, r3;
62156
62157        if( !affinity ){
62158          affinity = SQLITE_AFF_NONE;
62159        }
62160        keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
62161
62162        /* Loop through each expression in <exprlist>. */
62163        r1 = sqlite3GetTempReg(pParse);
62164        r2 = sqlite3GetTempReg(pParse);
62165        sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
62166        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
62167          Expr *pE2 = pItem->pExpr;
62168          int iValToIns;
62169
62170          /* If the expression is not constant then we will need to
62171          ** disable the test that was generated above that makes sure
62172          ** this code only executes once.  Because for a non-constant
62173          ** expression we need to rerun this code each time.
62174          */
62175          if( testAddr && !sqlite3ExprIsConstant(pE2) ){
62176            sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
62177            testAddr = 0;
62178          }
62179
62180          /* Evaluate the expression and insert it into the temp table */
62181          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
62182            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
62183          }else{
62184            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
62185            if( isRowid ){
62186              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
62187                                sqlite3VdbeCurrentAddr(v)+2);
62188              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
62189            }else{
62190              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
62191              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
62192              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
62193            }
62194          }
62195        }
62196        sqlite3ReleaseTempReg(pParse, r1);
62197        sqlite3ReleaseTempReg(pParse, r2);
62198      }
62199      if( !isRowid ){
62200        sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
62201      }
62202      break;
62203    }
62204
62205    case TK_EXISTS:
62206    case TK_SELECT:
62207    default: {
62208      /* If this has to be a scalar SELECT.  Generate code to put the
62209      ** value of this select in a memory cell and record the number
62210      ** of the memory cell in iColumn.  If this is an EXISTS, write
62211      ** an integer 0 (not exists) or 1 (exists) into a memory cell
62212      ** and record that memory cell in iColumn.
62213      */
62214      static const Token one = { "1", 1 };  /* Token for literal value 1 */
62215      Select *pSel;                         /* SELECT statement to encode */
62216      SelectDest dest;                      /* How to deal with SELECt result */
62217
62218      testcase( pExpr->op==TK_EXISTS );
62219      testcase( pExpr->op==TK_SELECT );
62220      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
62221
62222      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
62223      pSel = pExpr->x.pSelect;
62224      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
62225      if( pExpr->op==TK_SELECT ){
62226        dest.eDest = SRT_Mem;
62227        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
62228        VdbeComment((v, "Init subquery result"));
62229      }else{
62230        dest.eDest = SRT_Exists;
62231        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
62232        VdbeComment((v, "Init EXISTS result"));
62233      }
62234      sqlite3ExprDelete(pParse->db, pSel->pLimit);
62235      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
62236      if( sqlite3Select(pParse, pSel, &dest) ){
62237        return 0;
62238      }
62239      rReg = dest.iParm;
62240      ExprSetIrreducible(pExpr);
62241      break;
62242    }
62243  }
62244
62245  if( testAddr ){
62246    sqlite3VdbeJumpHere(v, testAddr-1);
62247  }
62248  sqlite3ExprCachePop(pParse, 1);
62249
62250  return rReg;
62251}
62252#endif /* SQLITE_OMIT_SUBQUERY */
62253
62254#ifndef SQLITE_OMIT_SUBQUERY
62255/*
62256** Generate code for an IN expression.
62257**
62258**      x IN (SELECT ...)
62259**      x IN (value, value, ...)
62260**
62261** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
62262** is an array of zero or more values.  The expression is true if the LHS is
62263** contained within the RHS.  The value of the expression is unknown (NULL)
62264** if the LHS is NULL or if the LHS is not contained within the RHS and the
62265** RHS contains one or more NULL values.
62266**
62267** This routine generates code will jump to destIfFalse if the LHS is not
62268** contained within the RHS.  If due to NULLs we cannot determine if the LHS
62269** is contained in the RHS then jump to destIfNull.  If the LHS is contained
62270** within the RHS then fall through.
62271*/
62272static void sqlite3ExprCodeIN(
62273  Parse *pParse,        /* Parsing and code generating context */
62274  Expr *pExpr,          /* The IN expression */
62275  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
62276  int destIfNull        /* Jump here if the results are unknown due to NULLs */
62277){
62278  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
62279  char affinity;        /* Comparison affinity to use */
62280  int eType;            /* Type of the RHS */
62281  int r1;               /* Temporary use register */
62282  Vdbe *v;              /* Statement under construction */
62283
62284  /* Compute the RHS.   After this step, the table with cursor
62285  ** pExpr->iTable will contains the values that make up the RHS.
62286  */
62287  v = pParse->pVdbe;
62288  assert( v!=0 );       /* OOM detected prior to this routine */
62289  VdbeNoopComment((v, "begin IN expr"));
62290  eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
62291
62292  /* Figure out the affinity to use to create a key from the results
62293  ** of the expression. affinityStr stores a static string suitable for
62294  ** P4 of OP_MakeRecord.
62295  */
62296  affinity = comparisonAffinity(pExpr);
62297
62298  /* Code the LHS, the <expr> from "<expr> IN (...)".
62299  */
62300  sqlite3ExprCachePush(pParse);
62301  r1 = sqlite3GetTempReg(pParse);
62302  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
62303  sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
62304
62305
62306  if( eType==IN_INDEX_ROWID ){
62307    /* In this case, the RHS is the ROWID of table b-tree
62308    */
62309    sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
62310    sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
62311  }else{
62312    /* In this case, the RHS is an index b-tree.
62313    */
62314    sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
62315
62316    /* If the set membership test fails, then the result of the
62317    ** "x IN (...)" expression must be either 0 or NULL. If the set
62318    ** contains no NULL values, then the result is 0. If the set
62319    ** contains one or more NULL values, then the result of the
62320    ** expression is also NULL.
62321    */
62322    if( rRhsHasNull==0 || destIfFalse==destIfNull ){
62323      /* This branch runs if it is known at compile time that the RHS
62324      ** cannot contain NULL values. This happens as the result
62325      ** of a "NOT NULL" constraint in the database schema.
62326      **
62327      ** Also run this branch if NULL is equivalent to FALSE
62328      ** for this particular IN operator.
62329      */
62330      sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
62331
62332    }else{
62333      /* In this branch, the RHS of the IN might contain a NULL and
62334      ** the presence of a NULL on the RHS makes a difference in the
62335      ** outcome.
62336      */
62337      int j1, j2, j3;
62338
62339      /* First check to see if the LHS is contained in the RHS.  If so,
62340      ** then the presence of NULLs in the RHS does not matter, so jump
62341      ** over all of the code that follows.
62342      */
62343      j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
62344
62345      /* Here we begin generating code that runs if the LHS is not
62346      ** contained within the RHS.  Generate additional code that
62347      ** tests the RHS for NULLs.  If the RHS contains a NULL then
62348      ** jump to destIfNull.  If there are no NULLs in the RHS then
62349      ** jump to destIfFalse.
62350      */
62351      j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
62352      j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
62353      sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
62354      sqlite3VdbeJumpHere(v, j3);
62355      sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
62356      sqlite3VdbeJumpHere(v, j2);
62357
62358      /* Jump to the appropriate target depending on whether or not
62359      ** the RHS contains a NULL
62360      */
62361      sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
62362      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
62363
62364      /* The OP_Found at the top of this branch jumps here when true,
62365      ** causing the overall IN expression evaluation to fall through.
62366      */
62367      sqlite3VdbeJumpHere(v, j1);
62368    }
62369  }
62370  sqlite3ReleaseTempReg(pParse, r1);
62371  sqlite3ExprCachePop(pParse, 1);
62372  VdbeComment((v, "end IN expr"));
62373}
62374#endif /* SQLITE_OMIT_SUBQUERY */
62375
62376/*
62377** Duplicate an 8-byte value
62378*/
62379static char *dup8bytes(Vdbe *v, const char *in){
62380  char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
62381  if( out ){
62382    memcpy(out, in, 8);
62383  }
62384  return out;
62385}
62386
62387/*
62388** Generate an instruction that will put the floating point
62389** value described by z[0..n-1] into register iMem.
62390**
62391** The z[] string will probably not be zero-terminated.  But the
62392** z[n] character is guaranteed to be something that does not look
62393** like the continuation of the number.
62394*/
62395static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
62396  if( ALWAYS(z!=0) ){
62397    double value;
62398    char *zV;
62399    sqlite3AtoF(z, &value);
62400    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
62401    if( negateFlag ) value = -value;
62402    zV = dup8bytes(v, (char*)&value);
62403    sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
62404  }
62405}
62406
62407
62408/*
62409** Generate an instruction that will put the integer describe by
62410** text z[0..n-1] into register iMem.
62411**
62412** The z[] string will probably not be zero-terminated.  But the
62413** z[n] character is guaranteed to be something that does not look
62414** like the continuation of the number.
62415*/
62416static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
62417  if( pExpr->flags & EP_IntValue ){
62418    int i = pExpr->u.iValue;
62419    if( negFlag ) i = -i;
62420    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
62421  }else{
62422    const char *z = pExpr->u.zToken;
62423    assert( z!=0 );
62424    if( sqlite3FitsIn64Bits(z, negFlag) ){
62425      i64 value;
62426      char *zV;
62427      sqlite3Atoi64(z, &value);
62428      if( negFlag ) value = -value;
62429      zV = dup8bytes(v, (char*)&value);
62430      sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
62431    }else{
62432      codeReal(v, z, negFlag, iMem);
62433    }
62434  }
62435}
62436
62437/*
62438** Clear a cache entry.
62439*/
62440static void cacheEntryClear(Parse *pParse, struct yColCache *p){
62441  if( p->tempReg ){
62442    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
62443      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
62444    }
62445    p->tempReg = 0;
62446  }
62447}
62448
62449
62450/*
62451** Record in the column cache that a particular column from a
62452** particular table is stored in a particular register.
62453*/
62454SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
62455  int i;
62456  int minLru;
62457  int idxLru;
62458  struct yColCache *p;
62459
62460  assert( iReg>0 );  /* Register numbers are always positive */
62461  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
62462
62463  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
62464  ** for testing only - to verify that SQLite always gets the same answer
62465  ** with and without the column cache.
62466  */
62467  if( pParse->db->flags & SQLITE_ColumnCache ) return;
62468
62469  /* First replace any existing entry.
62470  **
62471  ** Actually, the way the column cache is currently used, we are guaranteed
62472  ** that the object will never already be in cache.  Verify this guarantee.
62473  */
62474#ifndef NDEBUG
62475  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62476#if 0 /* This code wold remove the entry from the cache if it existed */
62477    if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
62478      cacheEntryClear(pParse, p);
62479      p->iLevel = pParse->iCacheLevel;
62480      p->iReg = iReg;
62481      p->lru = pParse->iCacheCnt++;
62482      return;
62483    }
62484#endif
62485    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
62486  }
62487#endif
62488
62489  /* Find an empty slot and replace it */
62490  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62491    if( p->iReg==0 ){
62492      p->iLevel = pParse->iCacheLevel;
62493      p->iTable = iTab;
62494      p->iColumn = iCol;
62495      p->iReg = iReg;
62496      p->tempReg = 0;
62497      p->lru = pParse->iCacheCnt++;
62498      return;
62499    }
62500  }
62501
62502  /* Replace the last recently used */
62503  minLru = 0x7fffffff;
62504  idxLru = -1;
62505  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62506    if( p->lru<minLru ){
62507      idxLru = i;
62508      minLru = p->lru;
62509    }
62510  }
62511  if( ALWAYS(idxLru>=0) ){
62512    p = &pParse->aColCache[idxLru];
62513    p->iLevel = pParse->iCacheLevel;
62514    p->iTable = iTab;
62515    p->iColumn = iCol;
62516    p->iReg = iReg;
62517    p->tempReg = 0;
62518    p->lru = pParse->iCacheCnt++;
62519    return;
62520  }
62521}
62522
62523/*
62524** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
62525** Purge the range of registers from the column cache.
62526*/
62527SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
62528  int i;
62529  int iLast = iReg + nReg - 1;
62530  struct yColCache *p;
62531  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62532    int r = p->iReg;
62533    if( r>=iReg && r<=iLast ){
62534      cacheEntryClear(pParse, p);
62535      p->iReg = 0;
62536    }
62537  }
62538}
62539
62540/*
62541** Remember the current column cache context.  Any new entries added
62542** added to the column cache after this call are removed when the
62543** corresponding pop occurs.
62544*/
62545SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
62546  pParse->iCacheLevel++;
62547}
62548
62549/*
62550** Remove from the column cache any entries that were added since the
62551** the previous N Push operations.  In other words, restore the cache
62552** to the state it was in N Pushes ago.
62553*/
62554SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
62555  int i;
62556  struct yColCache *p;
62557  assert( N>0 );
62558  assert( pParse->iCacheLevel>=N );
62559  pParse->iCacheLevel -= N;
62560  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62561    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
62562      cacheEntryClear(pParse, p);
62563      p->iReg = 0;
62564    }
62565  }
62566}
62567
62568/*
62569** When a cached column is reused, make sure that its register is
62570** no longer available as a temp register.  ticket #3879:  that same
62571** register might be in the cache in multiple places, so be sure to
62572** get them all.
62573*/
62574static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
62575  int i;
62576  struct yColCache *p;
62577  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62578    if( p->iReg==iReg ){
62579      p->tempReg = 0;
62580    }
62581  }
62582}
62583
62584/*
62585** Generate code that will extract the iColumn-th column from
62586** table pTab and store the column value in a register.  An effort
62587** is made to store the column value in register iReg, but this is
62588** not guaranteed.  The location of the column value is returned.
62589**
62590** There must be an open cursor to pTab in iTable when this routine
62591** is called.  If iColumn<0 then code is generated that extracts the rowid.
62592*/
62593SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
62594  Parse *pParse,   /* Parsing and code generating context */
62595  Table *pTab,     /* Description of the table we are reading from */
62596  int iColumn,     /* Index of the table column */
62597  int iTable,      /* The cursor pointing to the table */
62598  int iReg         /* Store results here */
62599){
62600  Vdbe *v = pParse->pVdbe;
62601  int i;
62602  struct yColCache *p;
62603
62604  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62605    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
62606      p->lru = pParse->iCacheCnt++;
62607      sqlite3ExprCachePinRegister(pParse, p->iReg);
62608      return p->iReg;
62609    }
62610  }
62611  assert( v!=0 );
62612  if( iColumn<0 ){
62613    sqlite3VdbeAddOp2(v, OP_Rowid, iTable, iReg);
62614  }else if( ALWAYS(pTab!=0) ){
62615    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
62616    sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
62617    sqlite3ColumnDefault(v, pTab, iColumn, iReg);
62618  }
62619  sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
62620  return iReg;
62621}
62622
62623/*
62624** Clear all column cache entries.
62625*/
62626SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
62627  int i;
62628  struct yColCache *p;
62629
62630  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62631    if( p->iReg ){
62632      cacheEntryClear(pParse, p);
62633      p->iReg = 0;
62634    }
62635  }
62636}
62637
62638/*
62639** Record the fact that an affinity change has occurred on iCount
62640** registers starting with iStart.
62641*/
62642SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
62643  sqlite3ExprCacheRemove(pParse, iStart, iCount);
62644}
62645
62646/*
62647** Generate code to move content from registers iFrom...iFrom+nReg-1
62648** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
62649*/
62650SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
62651  int i;
62652  struct yColCache *p;
62653  if( NEVER(iFrom==iTo) ) return;
62654  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
62655  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62656    int x = p->iReg;
62657    if( x>=iFrom && x<iFrom+nReg ){
62658      p->iReg += iTo-iFrom;
62659    }
62660  }
62661}
62662
62663/*
62664** Generate code to copy content from registers iFrom...iFrom+nReg-1
62665** over to iTo..iTo+nReg-1.
62666*/
62667SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
62668  int i;
62669  if( NEVER(iFrom==iTo) ) return;
62670  for(i=0; i<nReg; i++){
62671    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
62672  }
62673}
62674
62675#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
62676/*
62677** Return true if any register in the range iFrom..iTo (inclusive)
62678** is used as part of the column cache.
62679**
62680** This routine is used within assert() and testcase() macros only
62681** and does not appear in a normal build.
62682*/
62683static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
62684  int i;
62685  struct yColCache *p;
62686  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62687    int r = p->iReg;
62688    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
62689  }
62690  return 0;
62691}
62692#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
62693
62694/*
62695** If the last instruction coded is an ephemeral copy of any of
62696** the registers in the nReg registers beginning with iReg, then
62697** convert the last instruction from OP_SCopy to OP_Copy.
62698*/
62699SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
62700  VdbeOp *pOp;
62701  Vdbe *v;
62702
62703  assert( pParse->db->mallocFailed==0 );
62704  v = pParse->pVdbe;
62705  assert( v!=0 );
62706  pOp = sqlite3VdbeGetOp(v, -1);
62707  assert( pOp!=0 );
62708  if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
62709    pOp->opcode = OP_Copy;
62710  }
62711}
62712
62713/*
62714** Generate code to store the value of the iAlias-th alias in register
62715** target.  The first time this is called, pExpr is evaluated to compute
62716** the value of the alias.  The value is stored in an auxiliary register
62717** and the number of that register is returned.  On subsequent calls,
62718** the register number is returned without generating any code.
62719**
62720** Note that in order for this to work, code must be generated in the
62721** same order that it is executed.
62722**
62723** Aliases are numbered starting with 1.  So iAlias is in the range
62724** of 1 to pParse->nAlias inclusive.
62725**
62726** pParse->aAlias[iAlias-1] records the register number where the value
62727** of the iAlias-th alias is stored.  If zero, that means that the
62728** alias has not yet been computed.
62729*/
62730static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
62731#if 0
62732  sqlite3 *db = pParse->db;
62733  int iReg;
62734  if( pParse->nAliasAlloc<pParse->nAlias ){
62735    pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
62736                                 sizeof(pParse->aAlias[0])*pParse->nAlias );
62737    testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
62738    if( db->mallocFailed ) return 0;
62739    memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
62740           (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
62741    pParse->nAliasAlloc = pParse->nAlias;
62742  }
62743  assert( iAlias>0 && iAlias<=pParse->nAlias );
62744  iReg = pParse->aAlias[iAlias-1];
62745  if( iReg==0 ){
62746    if( pParse->iCacheLevel>0 ){
62747      iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
62748    }else{
62749      iReg = ++pParse->nMem;
62750      sqlite3ExprCode(pParse, pExpr, iReg);
62751      pParse->aAlias[iAlias-1] = iReg;
62752    }
62753  }
62754  return iReg;
62755#else
62756  UNUSED_PARAMETER(iAlias);
62757  return sqlite3ExprCodeTarget(pParse, pExpr, target);
62758#endif
62759}
62760
62761/*
62762** Generate code into the current Vdbe to evaluate the given
62763** expression.  Attempt to store the results in register "target".
62764** Return the register where results are stored.
62765**
62766** With this routine, there is no guarantee that results will
62767** be stored in target.  The result might be stored in some other
62768** register if it is convenient to do so.  The calling function
62769** must check the return code and move the results to the desired
62770** register.
62771*/
62772SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
62773  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
62774  int op;                   /* The opcode being coded */
62775  int inReg = target;       /* Results stored in register inReg */
62776  int regFree1 = 0;         /* If non-zero free this temporary register */
62777  int regFree2 = 0;         /* If non-zero free this temporary register */
62778  int r1, r2, r3, r4;       /* Various register numbers */
62779  sqlite3 *db = pParse->db; /* The database connection */
62780
62781  assert( target>0 && target<=pParse->nMem );
62782  if( v==0 ){
62783    assert( pParse->db->mallocFailed );
62784    return 0;
62785  }
62786
62787  if( pExpr==0 ){
62788    op = TK_NULL;
62789  }else{
62790    op = pExpr->op;
62791  }
62792  switch( op ){
62793    case TK_AGG_COLUMN: {
62794      AggInfo *pAggInfo = pExpr->pAggInfo;
62795      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
62796      if( !pAggInfo->directMode ){
62797        assert( pCol->iMem>0 );
62798        inReg = pCol->iMem;
62799        break;
62800      }else if( pAggInfo->useSortingIdx ){
62801        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
62802                              pCol->iSorterColumn, target);
62803        break;
62804      }
62805      /* Otherwise, fall thru into the TK_COLUMN case */
62806    }
62807    case TK_COLUMN: {
62808      if( pExpr->iTable<0 ){
62809        /* This only happens when coding check constraints */
62810        assert( pParse->ckBase>0 );
62811        inReg = pExpr->iColumn + pParse->ckBase;
62812      }else{
62813        inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
62814                                 pExpr->iColumn, pExpr->iTable, target);
62815      }
62816      break;
62817    }
62818    case TK_INTEGER: {
62819      codeInteger(v, pExpr, 0, target);
62820      break;
62821    }
62822    case TK_FLOAT: {
62823      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62824      codeReal(v, pExpr->u.zToken, 0, target);
62825      break;
62826    }
62827    case TK_STRING: {
62828      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62829      sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
62830      break;
62831    }
62832    case TK_NULL: {
62833      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
62834      break;
62835    }
62836#ifndef SQLITE_OMIT_BLOB_LITERAL
62837    case TK_BLOB: {
62838      int n;
62839      const char *z;
62840      char *zBlob;
62841      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62842      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
62843      assert( pExpr->u.zToken[1]=='\'' );
62844      z = &pExpr->u.zToken[2];
62845      n = sqlite3Strlen30(z) - 1;
62846      assert( z[n]=='\'' );
62847      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
62848      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
62849      break;
62850    }
62851#endif
62852    case TK_VARIABLE: {
62853      VdbeOp *pOp;
62854      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62855      assert( pExpr->u.zToken!=0 );
62856      assert( pExpr->u.zToken[0]!=0 );
62857      if( pExpr->u.zToken[1]==0
62858         && (pOp = sqlite3VdbeGetOp(v, -1))->opcode==OP_Variable
62859         && pOp->p1+pOp->p3==pExpr->iColumn
62860         && pOp->p2+pOp->p3==target
62861         && pOp->p4.z==0
62862      ){
62863        /* If the previous instruction was a copy of the previous unnamed
62864        ** parameter into the previous register, then simply increment the
62865        ** repeat count on the prior instruction rather than making a new
62866        ** instruction.
62867        */
62868        pOp->p3++;
62869      }else{
62870        sqlite3VdbeAddOp3(v, OP_Variable, pExpr->iColumn, target, 1);
62871        if( pExpr->u.zToken[1]!=0 ){
62872          sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
62873        }
62874      }
62875      break;
62876    }
62877    case TK_REGISTER: {
62878      inReg = pExpr->iTable;
62879      break;
62880    }
62881    case TK_AS: {
62882      inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
62883      break;
62884    }
62885#ifndef SQLITE_OMIT_CAST
62886    case TK_CAST: {
62887      /* Expressions of the form:   CAST(pLeft AS token) */
62888      int aff, to_op;
62889      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
62890      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62891      aff = sqlite3AffinityType(pExpr->u.zToken);
62892      to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
62893      assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
62894      assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
62895      assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
62896      assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
62897      assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
62898      testcase( to_op==OP_ToText );
62899      testcase( to_op==OP_ToBlob );
62900      testcase( to_op==OP_ToNumeric );
62901      testcase( to_op==OP_ToInt );
62902      testcase( to_op==OP_ToReal );
62903      if( inReg!=target ){
62904        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
62905        inReg = target;
62906      }
62907      sqlite3VdbeAddOp1(v, to_op, inReg);
62908      testcase( usedAsColumnCache(pParse, inReg, inReg) );
62909      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
62910      break;
62911    }
62912#endif /* SQLITE_OMIT_CAST */
62913    case TK_LT:
62914    case TK_LE:
62915    case TK_GT:
62916    case TK_GE:
62917    case TK_NE:
62918    case TK_EQ: {
62919      assert( TK_LT==OP_Lt );
62920      assert( TK_LE==OP_Le );
62921      assert( TK_GT==OP_Gt );
62922      assert( TK_GE==OP_Ge );
62923      assert( TK_EQ==OP_Eq );
62924      assert( TK_NE==OP_Ne );
62925      testcase( op==TK_LT );
62926      testcase( op==TK_LE );
62927      testcase( op==TK_GT );
62928      testcase( op==TK_GE );
62929      testcase( op==TK_EQ );
62930      testcase( op==TK_NE );
62931      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62932      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
62933      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
62934                  r1, r2, inReg, SQLITE_STOREP2);
62935      testcase( regFree1==0 );
62936      testcase( regFree2==0 );
62937      break;
62938    }
62939    case TK_IS:
62940    case TK_ISNOT: {
62941      testcase( op==TK_IS );
62942      testcase( op==TK_ISNOT );
62943      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62944      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
62945      op = (op==TK_IS) ? TK_EQ : TK_NE;
62946      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
62947                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
62948      testcase( regFree1==0 );
62949      testcase( regFree2==0 );
62950      break;
62951    }
62952    case TK_AND:
62953    case TK_OR:
62954    case TK_PLUS:
62955    case TK_STAR:
62956    case TK_MINUS:
62957    case TK_REM:
62958    case TK_BITAND:
62959    case TK_BITOR:
62960    case TK_SLASH:
62961    case TK_LSHIFT:
62962    case TK_RSHIFT:
62963    case TK_CONCAT: {
62964      assert( TK_AND==OP_And );
62965      assert( TK_OR==OP_Or );
62966      assert( TK_PLUS==OP_Add );
62967      assert( TK_MINUS==OP_Subtract );
62968      assert( TK_REM==OP_Remainder );
62969      assert( TK_BITAND==OP_BitAnd );
62970      assert( TK_BITOR==OP_BitOr );
62971      assert( TK_SLASH==OP_Divide );
62972      assert( TK_LSHIFT==OP_ShiftLeft );
62973      assert( TK_RSHIFT==OP_ShiftRight );
62974      assert( TK_CONCAT==OP_Concat );
62975      testcase( op==TK_AND );
62976      testcase( op==TK_OR );
62977      testcase( op==TK_PLUS );
62978      testcase( op==TK_MINUS );
62979      testcase( op==TK_REM );
62980      testcase( op==TK_BITAND );
62981      testcase( op==TK_BITOR );
62982      testcase( op==TK_SLASH );
62983      testcase( op==TK_LSHIFT );
62984      testcase( op==TK_RSHIFT );
62985      testcase( op==TK_CONCAT );
62986      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62987      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
62988      sqlite3VdbeAddOp3(v, op, r2, r1, target);
62989      testcase( regFree1==0 );
62990      testcase( regFree2==0 );
62991      break;
62992    }
62993    case TK_UMINUS: {
62994      Expr *pLeft = pExpr->pLeft;
62995      assert( pLeft );
62996      if( pLeft->op==TK_FLOAT ){
62997        assert( !ExprHasProperty(pExpr, EP_IntValue) );
62998        codeReal(v, pLeft->u.zToken, 1, target);
62999      }else if( pLeft->op==TK_INTEGER ){
63000        codeInteger(v, pLeft, 1, target);
63001      }else{
63002        regFree1 = r1 = sqlite3GetTempReg(pParse);
63003        sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
63004        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
63005        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
63006        testcase( regFree2==0 );
63007      }
63008      inReg = target;
63009      break;
63010    }
63011    case TK_BITNOT:
63012    case TK_NOT: {
63013      assert( TK_BITNOT==OP_BitNot );
63014      assert( TK_NOT==OP_Not );
63015      testcase( op==TK_BITNOT );
63016      testcase( op==TK_NOT );
63017      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63018      testcase( regFree1==0 );
63019      inReg = target;
63020      sqlite3VdbeAddOp2(v, op, r1, inReg);
63021      break;
63022    }
63023    case TK_ISNULL:
63024    case TK_NOTNULL: {
63025      int addr;
63026      assert( TK_ISNULL==OP_IsNull );
63027      assert( TK_NOTNULL==OP_NotNull );
63028      testcase( op==TK_ISNULL );
63029      testcase( op==TK_NOTNULL );
63030      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
63031      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63032      testcase( regFree1==0 );
63033      addr = sqlite3VdbeAddOp1(v, op, r1);
63034      sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
63035      sqlite3VdbeJumpHere(v, addr);
63036      break;
63037    }
63038    case TK_AGG_FUNCTION: {
63039      AggInfo *pInfo = pExpr->pAggInfo;
63040      if( pInfo==0 ){
63041        assert( !ExprHasProperty(pExpr, EP_IntValue) );
63042        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
63043      }else{
63044        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
63045      }
63046      break;
63047    }
63048    case TK_CONST_FUNC:
63049    case TK_FUNCTION: {
63050      ExprList *pFarg;       /* List of function arguments */
63051      int nFarg;             /* Number of function arguments */
63052      FuncDef *pDef;         /* The function definition object */
63053      int nId;               /* Length of the function name in bytes */
63054      const char *zId;       /* The function name */
63055      int constMask = 0;     /* Mask of function arguments that are constant */
63056      int i;                 /* Loop counter */
63057      u8 enc = ENC(db);      /* The text encoding used by this database */
63058      CollSeq *pColl = 0;    /* A collating sequence */
63059
63060      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
63061      testcase( op==TK_CONST_FUNC );
63062      testcase( op==TK_FUNCTION );
63063      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
63064        pFarg = 0;
63065      }else{
63066        pFarg = pExpr->x.pList;
63067      }
63068      nFarg = pFarg ? pFarg->nExpr : 0;
63069      assert( !ExprHasProperty(pExpr, EP_IntValue) );
63070      zId = pExpr->u.zToken;
63071      nId = sqlite3Strlen30(zId);
63072      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
63073      if( pDef==0 ){
63074        sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
63075        break;
63076      }
63077
63078      /* Attempt a direct implementation of the built-in COALESCE() and
63079      ** IFNULL() functions.  This avoids unnecessary evalation of
63080      ** arguments past the first non-NULL argument.
63081      */
63082      if( pDef->flags & SQLITE_FUNC_COALESCE ){
63083        int endCoalesce = sqlite3VdbeMakeLabel(v);
63084        assert( nFarg>=2 );
63085        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
63086        for(i=1; i<nFarg; i++){
63087          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
63088          sqlite3ExprCacheRemove(pParse, target, 1);
63089          sqlite3ExprCachePush(pParse);
63090          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
63091          sqlite3ExprCachePop(pParse, 1);
63092        }
63093        sqlite3VdbeResolveLabel(v, endCoalesce);
63094        break;
63095      }
63096
63097
63098      if( pFarg ){
63099        r1 = sqlite3GetTempRange(pParse, nFarg);
63100        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
63101        sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
63102        sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
63103      }else{
63104        r1 = 0;
63105      }
63106#ifndef SQLITE_OMIT_VIRTUALTABLE
63107      /* Possibly overload the function if the first argument is
63108      ** a virtual table column.
63109      **
63110      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
63111      ** second argument, not the first, as the argument to test to
63112      ** see if it is a column in a virtual table.  This is done because
63113      ** the left operand of infix functions (the operand we want to
63114      ** control overloading) ends up as the second argument to the
63115      ** function.  The expression "A glob B" is equivalent to
63116      ** "glob(B,A).  We want to use the A in "A glob B" to test
63117      ** for function overloading.  But we use the B term in "glob(B,A)".
63118      */
63119      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
63120        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
63121      }else if( nFarg>0 ){
63122        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
63123      }
63124#endif
63125      for(i=0; i<nFarg; i++){
63126        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
63127          constMask |= (1<<i);
63128        }
63129        if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
63130          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
63131        }
63132      }
63133      if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
63134        if( !pColl ) pColl = db->pDfltColl;
63135        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
63136      }
63137      sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
63138                        (char*)pDef, P4_FUNCDEF);
63139      sqlite3VdbeChangeP5(v, (u8)nFarg);
63140      if( nFarg ){
63141        sqlite3ReleaseTempRange(pParse, r1, nFarg);
63142      }
63143      break;
63144    }
63145#ifndef SQLITE_OMIT_SUBQUERY
63146    case TK_EXISTS:
63147    case TK_SELECT: {
63148      testcase( op==TK_EXISTS );
63149      testcase( op==TK_SELECT );
63150      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
63151      break;
63152    }
63153    case TK_IN: {
63154      int destIfFalse = sqlite3VdbeMakeLabel(v);
63155      int destIfNull = sqlite3VdbeMakeLabel(v);
63156      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
63157      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
63158      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
63159      sqlite3VdbeResolveLabel(v, destIfFalse);
63160      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
63161      sqlite3VdbeResolveLabel(v, destIfNull);
63162      break;
63163    }
63164#endif /* SQLITE_OMIT_SUBQUERY */
63165
63166
63167    /*
63168    **    x BETWEEN y AND z
63169    **
63170    ** This is equivalent to
63171    **
63172    **    x>=y AND x<=z
63173    **
63174    ** X is stored in pExpr->pLeft.
63175    ** Y is stored in pExpr->pList->a[0].pExpr.
63176    ** Z is stored in pExpr->pList->a[1].pExpr.
63177    */
63178    case TK_BETWEEN: {
63179      Expr *pLeft = pExpr->pLeft;
63180      struct ExprList_item *pLItem = pExpr->x.pList->a;
63181      Expr *pRight = pLItem->pExpr;
63182
63183      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
63184      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
63185      testcase( regFree1==0 );
63186      testcase( regFree2==0 );
63187      r3 = sqlite3GetTempReg(pParse);
63188      r4 = sqlite3GetTempReg(pParse);
63189      codeCompare(pParse, pLeft, pRight, OP_Ge,
63190                  r1, r2, r3, SQLITE_STOREP2);
63191      pLItem++;
63192      pRight = pLItem->pExpr;
63193      sqlite3ReleaseTempReg(pParse, regFree2);
63194      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
63195      testcase( regFree2==0 );
63196      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
63197      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
63198      sqlite3ReleaseTempReg(pParse, r3);
63199      sqlite3ReleaseTempReg(pParse, r4);
63200      break;
63201    }
63202    case TK_UPLUS: {
63203      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
63204      break;
63205    }
63206
63207    case TK_TRIGGER: {
63208      /* If the opcode is TK_TRIGGER, then the expression is a reference
63209      ** to a column in the new.* or old.* pseudo-tables available to
63210      ** trigger programs. In this case Expr.iTable is set to 1 for the
63211      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
63212      ** is set to the column of the pseudo-table to read, or to -1 to
63213      ** read the rowid field.
63214      **
63215      ** The expression is implemented using an OP_Param opcode. The p1
63216      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
63217      ** to reference another column of the old.* pseudo-table, where
63218      ** i is the index of the column. For a new.rowid reference, p1 is
63219      ** set to (n+1), where n is the number of columns in each pseudo-table.
63220      ** For a reference to any other column in the new.* pseudo-table, p1
63221      ** is set to (n+2+i), where n and i are as defined previously. For
63222      ** example, if the table on which triggers are being fired is
63223      ** declared as:
63224      **
63225      **   CREATE TABLE t1(a, b);
63226      **
63227      ** Then p1 is interpreted as follows:
63228      **
63229      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
63230      **   p1==1   ->    old.a         p1==4   ->    new.a
63231      **   p1==2   ->    old.b         p1==5   ->    new.b
63232      */
63233      Table *pTab = pExpr->pTab;
63234      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
63235
63236      assert( pExpr->iTable==0 || pExpr->iTable==1 );
63237      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
63238      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
63239      assert( p1>=0 && p1<(pTab->nCol*2+2) );
63240
63241      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
63242      VdbeComment((v, "%s.%s -> $%d",
63243        (pExpr->iTable ? "new" : "old"),
63244        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
63245        target
63246      ));
63247
63248      /* If the column has REAL affinity, it may currently be stored as an
63249      ** integer. Use OP_RealAffinity to make sure it is really real.  */
63250      if( pExpr->iColumn>=0
63251       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
63252      ){
63253        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
63254      }
63255      break;
63256    }
63257
63258
63259    /*
63260    ** Form A:
63261    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
63262    **
63263    ** Form B:
63264    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
63265    **
63266    ** Form A is can be transformed into the equivalent form B as follows:
63267    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
63268    **        WHEN x=eN THEN rN ELSE y END
63269    **
63270    ** X (if it exists) is in pExpr->pLeft.
63271    ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
63272    ** ELSE clause and no other term matches, then the result of the
63273    ** exprssion is NULL.
63274    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
63275    **
63276    ** The result of the expression is the Ri for the first matching Ei,
63277    ** or if there is no matching Ei, the ELSE term Y, or if there is
63278    ** no ELSE term, NULL.
63279    */
63280    default: assert( op==TK_CASE ); {
63281      int endLabel;                     /* GOTO label for end of CASE stmt */
63282      int nextCase;                     /* GOTO label for next WHEN clause */
63283      int nExpr;                        /* 2x number of WHEN terms */
63284      int i;                            /* Loop counter */
63285      ExprList *pEList;                 /* List of WHEN terms */
63286      struct ExprList_item *aListelem;  /* Array of WHEN terms */
63287      Expr opCompare;                   /* The X==Ei expression */
63288      Expr cacheX;                      /* Cached expression X */
63289      Expr *pX;                         /* The X expression */
63290      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
63291      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
63292
63293      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
63294      assert((pExpr->x.pList->nExpr % 2) == 0);
63295      assert(pExpr->x.pList->nExpr > 0);
63296      pEList = pExpr->x.pList;
63297      aListelem = pEList->a;
63298      nExpr = pEList->nExpr;
63299      endLabel = sqlite3VdbeMakeLabel(v);
63300      if( (pX = pExpr->pLeft)!=0 ){
63301        cacheX = *pX;
63302        testcase( pX->op==TK_COLUMN );
63303        testcase( pX->op==TK_REGISTER );
63304        cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
63305        testcase( regFree1==0 );
63306        cacheX.op = TK_REGISTER;
63307        opCompare.op = TK_EQ;
63308        opCompare.pLeft = &cacheX;
63309        pTest = &opCompare;
63310      }
63311      for(i=0; i<nExpr; i=i+2){
63312        sqlite3ExprCachePush(pParse);
63313        if( pX ){
63314          assert( pTest!=0 );
63315          opCompare.pRight = aListelem[i].pExpr;
63316        }else{
63317          pTest = aListelem[i].pExpr;
63318        }
63319        nextCase = sqlite3VdbeMakeLabel(v);
63320        testcase( pTest->op==TK_COLUMN );
63321        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
63322        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
63323        testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
63324        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
63325        sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
63326        sqlite3ExprCachePop(pParse, 1);
63327        sqlite3VdbeResolveLabel(v, nextCase);
63328      }
63329      if( pExpr->pRight ){
63330        sqlite3ExprCachePush(pParse);
63331        sqlite3ExprCode(pParse, pExpr->pRight, target);
63332        sqlite3ExprCachePop(pParse, 1);
63333      }else{
63334        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
63335      }
63336      assert( db->mallocFailed || pParse->nErr>0
63337           || pParse->iCacheLevel==iCacheLevel );
63338      sqlite3VdbeResolveLabel(v, endLabel);
63339      break;
63340    }
63341#ifndef SQLITE_OMIT_TRIGGER
63342    case TK_RAISE: {
63343      assert( pExpr->affinity==OE_Rollback
63344           || pExpr->affinity==OE_Abort
63345           || pExpr->affinity==OE_Fail
63346           || pExpr->affinity==OE_Ignore
63347      );
63348      if( !pParse->pTriggerTab ){
63349        sqlite3ErrorMsg(pParse,
63350                       "RAISE() may only be used within a trigger-program");
63351        return 0;
63352      }
63353      if( pExpr->affinity==OE_Abort ){
63354        sqlite3MayAbort(pParse);
63355      }
63356      assert( !ExprHasProperty(pExpr, EP_IntValue) );
63357      if( pExpr->affinity==OE_Ignore ){
63358        sqlite3VdbeAddOp4(
63359            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
63360      }else{
63361        sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
63362      }
63363
63364      break;
63365    }
63366#endif
63367  }
63368  sqlite3ReleaseTempReg(pParse, regFree1);
63369  sqlite3ReleaseTempReg(pParse, regFree2);
63370  return inReg;
63371}
63372
63373/*
63374** Generate code to evaluate an expression and store the results
63375** into a register.  Return the register number where the results
63376** are stored.
63377**
63378** If the register is a temporary register that can be deallocated,
63379** then write its number into *pReg.  If the result register is not
63380** a temporary, then set *pReg to zero.
63381*/
63382SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
63383  int r1 = sqlite3GetTempReg(pParse);
63384  int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
63385  if( r2==r1 ){
63386    *pReg = r1;
63387  }else{
63388    sqlite3ReleaseTempReg(pParse, r1);
63389    *pReg = 0;
63390  }
63391  return r2;
63392}
63393
63394/*
63395** Generate code that will evaluate expression pExpr and store the
63396** results in register target.  The results are guaranteed to appear
63397** in register target.
63398*/
63399SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
63400  int inReg;
63401
63402  assert( target>0 && target<=pParse->nMem );
63403  inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
63404  assert( pParse->pVdbe || pParse->db->mallocFailed );
63405  if( inReg!=target && pParse->pVdbe ){
63406    sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
63407  }
63408  return target;
63409}
63410
63411/*
63412** Generate code that evalutes the given expression and puts the result
63413** in register target.
63414**
63415** Also make a copy of the expression results into another "cache" register
63416** and modify the expression so that the next time it is evaluated,
63417** the result is a copy of the cache register.
63418**
63419** This routine is used for expressions that are used multiple
63420** times.  They are evaluated once and the results of the expression
63421** are reused.
63422*/
63423SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
63424  Vdbe *v = pParse->pVdbe;
63425  int inReg;
63426  inReg = sqlite3ExprCode(pParse, pExpr, target);
63427  assert( target>0 );
63428  /* This routine is called for terms to INSERT or UPDATE.  And the only
63429  ** other place where expressions can be converted into TK_REGISTER is
63430  ** in WHERE clause processing.  So as currently implemented, there is
63431  ** no way for a TK_REGISTER to exist here.  But it seems prudent to
63432  ** keep the ALWAYS() in case the conditions above change with future
63433  ** modifications or enhancements. */
63434  if( ALWAYS(pExpr->op!=TK_REGISTER) ){
63435    int iMem;
63436    iMem = ++pParse->nMem;
63437    sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
63438    pExpr->iTable = iMem;
63439    pExpr->op2 = pExpr->op;
63440    pExpr->op = TK_REGISTER;
63441  }
63442  return inReg;
63443}
63444
63445/*
63446** Return TRUE if pExpr is an constant expression that is appropriate
63447** for factoring out of a loop.  Appropriate expressions are:
63448**
63449**    *  Any expression that evaluates to two or more opcodes.
63450**
63451**    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
63452**       or OP_Variable that does not need to be placed in a
63453**       specific register.
63454**
63455** There is no point in factoring out single-instruction constant
63456** expressions that need to be placed in a particular register.
63457** We could factor them out, but then we would end up adding an
63458** OP_SCopy instruction to move the value into the correct register
63459** later.  We might as well just use the original instruction and
63460** avoid the OP_SCopy.
63461*/
63462static int isAppropriateForFactoring(Expr *p){
63463  if( !sqlite3ExprIsConstantNotJoin(p) ){
63464    return 0;  /* Only constant expressions are appropriate for factoring */
63465  }
63466  if( (p->flags & EP_FixedDest)==0 ){
63467    return 1;  /* Any constant without a fixed destination is appropriate */
63468  }
63469  while( p->op==TK_UPLUS ) p = p->pLeft;
63470  switch( p->op ){
63471#ifndef SQLITE_OMIT_BLOB_LITERAL
63472    case TK_BLOB:
63473#endif
63474    case TK_VARIABLE:
63475    case TK_INTEGER:
63476    case TK_FLOAT:
63477    case TK_NULL:
63478    case TK_STRING: {
63479      testcase( p->op==TK_BLOB );
63480      testcase( p->op==TK_VARIABLE );
63481      testcase( p->op==TK_INTEGER );
63482      testcase( p->op==TK_FLOAT );
63483      testcase( p->op==TK_NULL );
63484      testcase( p->op==TK_STRING );
63485      /* Single-instruction constants with a fixed destination are
63486      ** better done in-line.  If we factor them, they will just end
63487      ** up generating an OP_SCopy to move the value to the destination
63488      ** register. */
63489      return 0;
63490    }
63491    case TK_UMINUS: {
63492      if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
63493        return 0;
63494      }
63495      break;
63496    }
63497    default: {
63498      break;
63499    }
63500  }
63501  return 1;
63502}
63503
63504/*
63505** If pExpr is a constant expression that is appropriate for
63506** factoring out of a loop, then evaluate the expression
63507** into a register and convert the expression into a TK_REGISTER
63508** expression.
63509*/
63510static int evalConstExpr(Walker *pWalker, Expr *pExpr){
63511  Parse *pParse = pWalker->pParse;
63512  switch( pExpr->op ){
63513    case TK_IN:
63514    case TK_REGISTER: {
63515      return WRC_Prune;
63516    }
63517    case TK_FUNCTION:
63518    case TK_AGG_FUNCTION:
63519    case TK_CONST_FUNC: {
63520      /* The arguments to a function have a fixed destination.
63521      ** Mark them this way to avoid generated unneeded OP_SCopy
63522      ** instructions.
63523      */
63524      ExprList *pList = pExpr->x.pList;
63525      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
63526      if( pList ){
63527        int i = pList->nExpr;
63528        struct ExprList_item *pItem = pList->a;
63529        for(; i>0; i--, pItem++){
63530          if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
63531        }
63532      }
63533      break;
63534    }
63535  }
63536  if( isAppropriateForFactoring(pExpr) ){
63537    int r1 = ++pParse->nMem;
63538    int r2;
63539    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
63540    if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
63541    pExpr->op2 = pExpr->op;
63542    pExpr->op = TK_REGISTER;
63543    pExpr->iTable = r2;
63544    return WRC_Prune;
63545  }
63546  return WRC_Continue;
63547}
63548
63549/*
63550** Preevaluate constant subexpressions within pExpr and store the
63551** results in registers.  Modify pExpr so that the constant subexpresions
63552** are TK_REGISTER opcodes that refer to the precomputed values.
63553*/
63554SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
63555  Walker w;
63556  w.xExprCallback = evalConstExpr;
63557  w.xSelectCallback = 0;
63558  w.pParse = pParse;
63559  sqlite3WalkExpr(&w, pExpr);
63560}
63561
63562
63563/*
63564** Generate code that pushes the value of every element of the given
63565** expression list into a sequence of registers beginning at target.
63566**
63567** Return the number of elements evaluated.
63568*/
63569SQLITE_PRIVATE int sqlite3ExprCodeExprList(
63570  Parse *pParse,     /* Parsing context */
63571  ExprList *pList,   /* The expression list to be coded */
63572  int target,        /* Where to write results */
63573  int doHardCopy     /* Make a hard copy of every element */
63574){
63575  struct ExprList_item *pItem;
63576  int i, n;
63577  assert( pList!=0 );
63578  assert( target>0 );
63579  n = pList->nExpr;
63580  for(pItem=pList->a, i=0; i<n; i++, pItem++){
63581    if( pItem->iAlias ){
63582      int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
63583      Vdbe *v = sqlite3GetVdbe(pParse);
63584      if( iReg!=target+i ){
63585        sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
63586      }
63587    }else{
63588      sqlite3ExprCode(pParse, pItem->pExpr, target+i);
63589    }
63590    if( doHardCopy && !pParse->db->mallocFailed ){
63591      sqlite3ExprHardCopy(pParse, target, n);
63592    }
63593  }
63594  return n;
63595}
63596
63597/*
63598** Generate code for a BETWEEN operator.
63599**
63600**    x BETWEEN y AND z
63601**
63602** The above is equivalent to
63603**
63604**    x>=y AND x<=z
63605**
63606** Code it as such, taking care to do the common subexpression
63607** elementation of x.
63608*/
63609static void exprCodeBetween(
63610  Parse *pParse,    /* Parsing and code generating context */
63611  Expr *pExpr,      /* The BETWEEN expression */
63612  int dest,         /* Jump here if the jump is taken */
63613  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
63614  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
63615){
63616  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
63617  Expr compLeft;    /* The  x>=y  term */
63618  Expr compRight;   /* The  x<=z  term */
63619  Expr exprX;       /* The  x  subexpression */
63620  int regFree1 = 0; /* Temporary use register */
63621
63622  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
63623  exprX = *pExpr->pLeft;
63624  exprAnd.op = TK_AND;
63625  exprAnd.pLeft = &compLeft;
63626  exprAnd.pRight = &compRight;
63627  compLeft.op = TK_GE;
63628  compLeft.pLeft = &exprX;
63629  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
63630  compRight.op = TK_LE;
63631  compRight.pLeft = &exprX;
63632  compRight.pRight = pExpr->x.pList->a[1].pExpr;
63633  exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
63634  exprX.op = TK_REGISTER;
63635  if( jumpIfTrue ){
63636    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
63637  }else{
63638    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
63639  }
63640  sqlite3ReleaseTempReg(pParse, regFree1);
63641
63642  /* Ensure adequate test coverage */
63643  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
63644  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
63645  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
63646  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
63647  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
63648  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
63649  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
63650  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
63651}
63652
63653/*
63654** Generate code for a boolean expression such that a jump is made
63655** to the label "dest" if the expression is true but execution
63656** continues straight thru if the expression is false.
63657**
63658** If the expression evaluates to NULL (neither true nor false), then
63659** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
63660**
63661** This code depends on the fact that certain token values (ex: TK_EQ)
63662** are the same as opcode values (ex: OP_Eq) that implement the corresponding
63663** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
63664** the make process cause these values to align.  Assert()s in the code
63665** below verify that the numbers are aligned correctly.
63666*/
63667SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
63668  Vdbe *v = pParse->pVdbe;
63669  int op = 0;
63670  int regFree1 = 0;
63671  int regFree2 = 0;
63672  int r1, r2;
63673
63674  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
63675  if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
63676  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
63677  op = pExpr->op;
63678  switch( op ){
63679    case TK_AND: {
63680      int d2 = sqlite3VdbeMakeLabel(v);
63681      testcase( jumpIfNull==0 );
63682      sqlite3ExprCachePush(pParse);
63683      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
63684      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
63685      sqlite3VdbeResolveLabel(v, d2);
63686      sqlite3ExprCachePop(pParse, 1);
63687      break;
63688    }
63689    case TK_OR: {
63690      testcase( jumpIfNull==0 );
63691      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
63692      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
63693      break;
63694    }
63695    case TK_NOT: {
63696      testcase( jumpIfNull==0 );
63697      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
63698      break;
63699    }
63700    case TK_LT:
63701    case TK_LE:
63702    case TK_GT:
63703    case TK_GE:
63704    case TK_NE:
63705    case TK_EQ: {
63706      assert( TK_LT==OP_Lt );
63707      assert( TK_LE==OP_Le );
63708      assert( TK_GT==OP_Gt );
63709      assert( TK_GE==OP_Ge );
63710      assert( TK_EQ==OP_Eq );
63711      assert( TK_NE==OP_Ne );
63712      testcase( op==TK_LT );
63713      testcase( op==TK_LE );
63714      testcase( op==TK_GT );
63715      testcase( op==TK_GE );
63716      testcase( op==TK_EQ );
63717      testcase( op==TK_NE );
63718      testcase( jumpIfNull==0 );
63719      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63720      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63721      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63722                  r1, r2, dest, jumpIfNull);
63723      testcase( regFree1==0 );
63724      testcase( regFree2==0 );
63725      break;
63726    }
63727    case TK_IS:
63728    case TK_ISNOT: {
63729      testcase( op==TK_IS );
63730      testcase( op==TK_ISNOT );
63731      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63732      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63733      op = (op==TK_IS) ? TK_EQ : TK_NE;
63734      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63735                  r1, r2, dest, SQLITE_NULLEQ);
63736      testcase( regFree1==0 );
63737      testcase( regFree2==0 );
63738      break;
63739    }
63740    case TK_ISNULL:
63741    case TK_NOTNULL: {
63742      assert( TK_ISNULL==OP_IsNull );
63743      assert( TK_NOTNULL==OP_NotNull );
63744      testcase( op==TK_ISNULL );
63745      testcase( op==TK_NOTNULL );
63746      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63747      sqlite3VdbeAddOp2(v, op, r1, dest);
63748      testcase( regFree1==0 );
63749      break;
63750    }
63751    case TK_BETWEEN: {
63752      testcase( jumpIfNull==0 );
63753      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
63754      break;
63755    }
63756    case TK_IN: {
63757      int destIfFalse = sqlite3VdbeMakeLabel(v);
63758      int destIfNull = jumpIfNull ? dest : destIfFalse;
63759      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
63760      sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
63761      sqlite3VdbeResolveLabel(v, destIfFalse);
63762      break;
63763    }
63764    default: {
63765      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
63766      sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
63767      testcase( regFree1==0 );
63768      testcase( jumpIfNull==0 );
63769      break;
63770    }
63771  }
63772  sqlite3ReleaseTempReg(pParse, regFree1);
63773  sqlite3ReleaseTempReg(pParse, regFree2);
63774}
63775
63776/*
63777** Generate code for a boolean expression such that a jump is made
63778** to the label "dest" if the expression is false but execution
63779** continues straight thru if the expression is true.
63780**
63781** If the expression evaluates to NULL (neither true nor false) then
63782** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
63783** is 0.
63784*/
63785SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
63786  Vdbe *v = pParse->pVdbe;
63787  int op = 0;
63788  int regFree1 = 0;
63789  int regFree2 = 0;
63790  int r1, r2;
63791
63792  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
63793  if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
63794  if( pExpr==0 )    return;
63795
63796  /* The value of pExpr->op and op are related as follows:
63797  **
63798  **       pExpr->op            op
63799  **       ---------          ----------
63800  **       TK_ISNULL          OP_NotNull
63801  **       TK_NOTNULL         OP_IsNull
63802  **       TK_NE              OP_Eq
63803  **       TK_EQ              OP_Ne
63804  **       TK_GT              OP_Le
63805  **       TK_LE              OP_Gt
63806  **       TK_GE              OP_Lt
63807  **       TK_LT              OP_Ge
63808  **
63809  ** For other values of pExpr->op, op is undefined and unused.
63810  ** The value of TK_ and OP_ constants are arranged such that we
63811  ** can compute the mapping above using the following expression.
63812  ** Assert()s verify that the computation is correct.
63813  */
63814  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
63815
63816  /* Verify correct alignment of TK_ and OP_ constants
63817  */
63818  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
63819  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
63820  assert( pExpr->op!=TK_NE || op==OP_Eq );
63821  assert( pExpr->op!=TK_EQ || op==OP_Ne );
63822  assert( pExpr->op!=TK_LT || op==OP_Ge );
63823  assert( pExpr->op!=TK_LE || op==OP_Gt );
63824  assert( pExpr->op!=TK_GT || op==OP_Le );
63825  assert( pExpr->op!=TK_GE || op==OP_Lt );
63826
63827  switch( pExpr->op ){
63828    case TK_AND: {
63829      testcase( jumpIfNull==0 );
63830      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
63831      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
63832      break;
63833    }
63834    case TK_OR: {
63835      int d2 = sqlite3VdbeMakeLabel(v);
63836      testcase( jumpIfNull==0 );
63837      sqlite3ExprCachePush(pParse);
63838      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
63839      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
63840      sqlite3VdbeResolveLabel(v, d2);
63841      sqlite3ExprCachePop(pParse, 1);
63842      break;
63843    }
63844    case TK_NOT: {
63845      testcase( jumpIfNull==0 );
63846      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
63847      break;
63848    }
63849    case TK_LT:
63850    case TK_LE:
63851    case TK_GT:
63852    case TK_GE:
63853    case TK_NE:
63854    case TK_EQ: {
63855      testcase( op==TK_LT );
63856      testcase( op==TK_LE );
63857      testcase( op==TK_GT );
63858      testcase( op==TK_GE );
63859      testcase( op==TK_EQ );
63860      testcase( op==TK_NE );
63861      testcase( jumpIfNull==0 );
63862      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63863      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63864      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63865                  r1, r2, dest, jumpIfNull);
63866      testcase( regFree1==0 );
63867      testcase( regFree2==0 );
63868      break;
63869    }
63870    case TK_IS:
63871    case TK_ISNOT: {
63872      testcase( pExpr->op==TK_IS );
63873      testcase( pExpr->op==TK_ISNOT );
63874      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63875      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63876      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
63877      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63878                  r1, r2, dest, SQLITE_NULLEQ);
63879      testcase( regFree1==0 );
63880      testcase( regFree2==0 );
63881      break;
63882    }
63883    case TK_ISNULL:
63884    case TK_NOTNULL: {
63885      testcase( op==TK_ISNULL );
63886      testcase( op==TK_NOTNULL );
63887      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63888      sqlite3VdbeAddOp2(v, op, r1, dest);
63889      testcase( regFree1==0 );
63890      break;
63891    }
63892    case TK_BETWEEN: {
63893      testcase( jumpIfNull==0 );
63894      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
63895      break;
63896    }
63897    case TK_IN: {
63898      if( jumpIfNull ){
63899        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
63900      }else{
63901        int destIfNull = sqlite3VdbeMakeLabel(v);
63902        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
63903        sqlite3VdbeResolveLabel(v, destIfNull);
63904      }
63905      break;
63906    }
63907    default: {
63908      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
63909      sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
63910      testcase( regFree1==0 );
63911      testcase( jumpIfNull==0 );
63912      break;
63913    }
63914  }
63915  sqlite3ReleaseTempReg(pParse, regFree1);
63916  sqlite3ReleaseTempReg(pParse, regFree2);
63917}
63918
63919/*
63920** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
63921** if they are identical and return FALSE if they differ in any way.
63922**
63923** Sometimes this routine will return FALSE even if the two expressions
63924** really are equivalent.  If we cannot prove that the expressions are
63925** identical, we return FALSE just to be safe.  So if this routine
63926** returns false, then you do not really know for certain if the two
63927** expressions are the same.  But if you get a TRUE return, then you
63928** can be sure the expressions are the same.  In the places where
63929** this routine is used, it does not hurt to get an extra FALSE - that
63930** just might result in some slightly slower code.  But returning
63931** an incorrect TRUE could lead to a malfunction.
63932*/
63933SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
63934  int i;
63935  if( pA==0||pB==0 ){
63936    return pB==pA;
63937  }
63938  assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
63939  assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
63940  if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
63941    return 0;
63942  }
63943  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
63944  if( pA->op!=pB->op ) return 0;
63945  if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
63946  if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
63947
63948  if( pA->x.pList && pB->x.pList ){
63949    if( pA->x.pList->nExpr!=pB->x.pList->nExpr ) return 0;
63950    for(i=0; i<pA->x.pList->nExpr; i++){
63951      Expr *pExprA = pA->x.pList->a[i].pExpr;
63952      Expr *pExprB = pB->x.pList->a[i].pExpr;
63953      if( !sqlite3ExprCompare(pExprA, pExprB) ) return 0;
63954    }
63955  }else if( pA->x.pList || pB->x.pList ){
63956    return 0;
63957  }
63958
63959  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
63960  if( ExprHasProperty(pA, EP_IntValue) ){
63961    if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
63962      return 0;
63963    }
63964  }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
63965    if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 0;
63966    if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
63967      return 0;
63968    }
63969  }
63970  return 1;
63971}
63972
63973
63974/*
63975** Add a new element to the pAggInfo->aCol[] array.  Return the index of
63976** the new element.  Return a negative number if malloc fails.
63977*/
63978static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
63979  int i;
63980  pInfo->aCol = sqlite3ArrayAllocate(
63981       db,
63982       pInfo->aCol,
63983       sizeof(pInfo->aCol[0]),
63984       3,
63985       &pInfo->nColumn,
63986       &pInfo->nColumnAlloc,
63987       &i
63988  );
63989  return i;
63990}
63991
63992/*
63993** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
63994** the new element.  Return a negative number if malloc fails.
63995*/
63996static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
63997  int i;
63998  pInfo->aFunc = sqlite3ArrayAllocate(
63999       db,
64000       pInfo->aFunc,
64001       sizeof(pInfo->aFunc[0]),
64002       3,
64003       &pInfo->nFunc,
64004       &pInfo->nFuncAlloc,
64005       &i
64006  );
64007  return i;
64008}
64009
64010/*
64011** This is the xExprCallback for a tree walker.  It is used to
64012** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
64013** for additional information.
64014*/
64015static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
64016  int i;
64017  NameContext *pNC = pWalker->u.pNC;
64018  Parse *pParse = pNC->pParse;
64019  SrcList *pSrcList = pNC->pSrcList;
64020  AggInfo *pAggInfo = pNC->pAggInfo;
64021
64022  switch( pExpr->op ){
64023    case TK_AGG_COLUMN:
64024    case TK_COLUMN: {
64025      testcase( pExpr->op==TK_AGG_COLUMN );
64026      testcase( pExpr->op==TK_COLUMN );
64027      /* Check to see if the column is in one of the tables in the FROM
64028      ** clause of the aggregate query */
64029      if( ALWAYS(pSrcList!=0) ){
64030        struct SrcList_item *pItem = pSrcList->a;
64031        for(i=0; i<pSrcList->nSrc; i++, pItem++){
64032          struct AggInfo_col *pCol;
64033          assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
64034          if( pExpr->iTable==pItem->iCursor ){
64035            /* If we reach this point, it means that pExpr refers to a table
64036            ** that is in the FROM clause of the aggregate query.
64037            **
64038            ** Make an entry for the column in pAggInfo->aCol[] if there
64039            ** is not an entry there already.
64040            */
64041            int k;
64042            pCol = pAggInfo->aCol;
64043            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
64044              if( pCol->iTable==pExpr->iTable &&
64045                  pCol->iColumn==pExpr->iColumn ){
64046                break;
64047              }
64048            }
64049            if( (k>=pAggInfo->nColumn)
64050             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
64051            ){
64052              pCol = &pAggInfo->aCol[k];
64053              pCol->pTab = pExpr->pTab;
64054              pCol->iTable = pExpr->iTable;
64055              pCol->iColumn = pExpr->iColumn;
64056              pCol->iMem = ++pParse->nMem;
64057              pCol->iSorterColumn = -1;
64058              pCol->pExpr = pExpr;
64059              if( pAggInfo->pGroupBy ){
64060                int j, n;
64061                ExprList *pGB = pAggInfo->pGroupBy;
64062                struct ExprList_item *pTerm = pGB->a;
64063                n = pGB->nExpr;
64064                for(j=0; j<n; j++, pTerm++){
64065                  Expr *pE = pTerm->pExpr;
64066                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
64067                      pE->iColumn==pExpr->iColumn ){
64068                    pCol->iSorterColumn = j;
64069                    break;
64070                  }
64071                }
64072              }
64073              if( pCol->iSorterColumn<0 ){
64074                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
64075              }
64076            }
64077            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
64078            ** because it was there before or because we just created it).
64079            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
64080            ** pAggInfo->aCol[] entry.
64081            */
64082            ExprSetIrreducible(pExpr);
64083            pExpr->pAggInfo = pAggInfo;
64084            pExpr->op = TK_AGG_COLUMN;
64085            pExpr->iAgg = (i16)k;
64086            break;
64087          } /* endif pExpr->iTable==pItem->iCursor */
64088        } /* end loop over pSrcList */
64089      }
64090      return WRC_Prune;
64091    }
64092    case TK_AGG_FUNCTION: {
64093      /* The pNC->nDepth==0 test causes aggregate functions in subqueries
64094      ** to be ignored */
64095      if( pNC->nDepth==0 ){
64096        /* Check to see if pExpr is a duplicate of another aggregate
64097        ** function that is already in the pAggInfo structure
64098        */
64099        struct AggInfo_func *pItem = pAggInfo->aFunc;
64100        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
64101          if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
64102            break;
64103          }
64104        }
64105        if( i>=pAggInfo->nFunc ){
64106          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
64107          */
64108          u8 enc = ENC(pParse->db);
64109          i = addAggInfoFunc(pParse->db, pAggInfo);
64110          if( i>=0 ){
64111            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
64112            pItem = &pAggInfo->aFunc[i];
64113            pItem->pExpr = pExpr;
64114            pItem->iMem = ++pParse->nMem;
64115            assert( !ExprHasProperty(pExpr, EP_IntValue) );
64116            pItem->pFunc = sqlite3FindFunction(pParse->db,
64117                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
64118                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
64119            if( pExpr->flags & EP_Distinct ){
64120              pItem->iDistinct = pParse->nTab++;
64121            }else{
64122              pItem->iDistinct = -1;
64123            }
64124          }
64125        }
64126        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
64127        */
64128        assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
64129        ExprSetIrreducible(pExpr);
64130        pExpr->iAgg = (i16)i;
64131        pExpr->pAggInfo = pAggInfo;
64132        return WRC_Prune;
64133      }
64134    }
64135  }
64136  return WRC_Continue;
64137}
64138static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
64139  NameContext *pNC = pWalker->u.pNC;
64140  if( pNC->nDepth==0 ){
64141    pNC->nDepth++;
64142    sqlite3WalkSelect(pWalker, pSelect);
64143    pNC->nDepth--;
64144    return WRC_Prune;
64145  }else{
64146    return WRC_Continue;
64147  }
64148}
64149
64150/*
64151** Analyze the given expression looking for aggregate functions and
64152** for variables that need to be added to the pParse->aAgg[] array.
64153** Make additional entries to the pParse->aAgg[] array as necessary.
64154**
64155** This routine should only be called after the expression has been
64156** analyzed by sqlite3ResolveExprNames().
64157*/
64158SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
64159  Walker w;
64160  w.xExprCallback = analyzeAggregate;
64161  w.xSelectCallback = analyzeAggregatesInSelect;
64162  w.u.pNC = pNC;
64163  assert( pNC->pSrcList!=0 );
64164  sqlite3WalkExpr(&w, pExpr);
64165}
64166
64167/*
64168** Call sqlite3ExprAnalyzeAggregates() for every expression in an
64169** expression list.  Return the number of errors.
64170**
64171** If an error is found, the analysis is cut short.
64172*/
64173SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
64174  struct ExprList_item *pItem;
64175  int i;
64176  if( pList ){
64177    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
64178      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
64179    }
64180  }
64181}
64182
64183/*
64184** Allocate a single new register for use to hold some intermediate result.
64185*/
64186SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
64187  if( pParse->nTempReg==0 ){
64188    return ++pParse->nMem;
64189  }
64190  return pParse->aTempReg[--pParse->nTempReg];
64191}
64192
64193/*
64194** Deallocate a register, making available for reuse for some other
64195** purpose.
64196**
64197** If a register is currently being used by the column cache, then
64198** the dallocation is deferred until the column cache line that uses
64199** the register becomes stale.
64200*/
64201SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
64202  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
64203    int i;
64204    struct yColCache *p;
64205    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
64206      if( p->iReg==iReg ){
64207        p->tempReg = 1;
64208        return;
64209      }
64210    }
64211    pParse->aTempReg[pParse->nTempReg++] = iReg;
64212  }
64213}
64214
64215/*
64216** Allocate or deallocate a block of nReg consecutive registers
64217*/
64218SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
64219  int i, n;
64220  i = pParse->iRangeReg;
64221  n = pParse->nRangeReg;
64222  if( nReg<=n ){
64223    assert( !usedAsColumnCache(pParse, i, i+n-1) );
64224    pParse->iRangeReg += nReg;
64225    pParse->nRangeReg -= nReg;
64226  }else{
64227    i = pParse->nMem+1;
64228    pParse->nMem += nReg;
64229  }
64230  return i;
64231}
64232SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
64233  sqlite3ExprCacheRemove(pParse, iReg, nReg);
64234  if( nReg>pParse->nRangeReg ){
64235    pParse->nRangeReg = nReg;
64236    pParse->iRangeReg = iReg;
64237  }
64238}
64239
64240/************** End of expr.c ************************************************/
64241/************** Begin file alter.c *******************************************/
64242/*
64243** 2005 February 15
64244**
64245** The author disclaims copyright to this source code.  In place of
64246** a legal notice, here is a blessing:
64247**
64248**    May you do good and not evil.
64249**    May you find forgiveness for yourself and forgive others.
64250**    May you share freely, never taking more than you give.
64251**
64252*************************************************************************
64253** This file contains C code routines that used to generate VDBE code
64254** that implements the ALTER TABLE command.
64255*/
64256
64257/*
64258** The code in this file only exists if we are not omitting the
64259** ALTER TABLE logic from the build.
64260*/
64261#ifndef SQLITE_OMIT_ALTERTABLE
64262
64263
64264/*
64265** This function is used by SQL generated to implement the
64266** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
64267** CREATE INDEX command. The second is a table name. The table name in
64268** the CREATE TABLE or CREATE INDEX statement is replaced with the third
64269** argument and the result returned. Examples:
64270**
64271** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
64272**     -> 'CREATE TABLE def(a, b, c)'
64273**
64274** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
64275**     -> 'CREATE INDEX i ON def(a, b, c)'
64276*/
64277static void renameTableFunc(
64278  sqlite3_context *context,
64279  int NotUsed,
64280  sqlite3_value **argv
64281){
64282  unsigned char const *zSql = sqlite3_value_text(argv[0]);
64283  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
64284
64285  int token;
64286  Token tname;
64287  unsigned char const *zCsr = zSql;
64288  int len = 0;
64289  char *zRet;
64290
64291  sqlite3 *db = sqlite3_context_db_handle(context);
64292
64293  UNUSED_PARAMETER(NotUsed);
64294
64295  /* The principle used to locate the table name in the CREATE TABLE
64296  ** statement is that the table name is the first non-space token that
64297  ** is immediately followed by a TK_LP or TK_USING token.
64298  */
64299  if( zSql ){
64300    do {
64301      if( !*zCsr ){
64302        /* Ran out of input before finding an opening bracket. Return NULL. */
64303        return;
64304      }
64305
64306      /* Store the token that zCsr points to in tname. */
64307      tname.z = (char*)zCsr;
64308      tname.n = len;
64309
64310      /* Advance zCsr to the next token. Store that token type in 'token',
64311      ** and its length in 'len' (to be used next iteration of this loop).
64312      */
64313      do {
64314        zCsr += len;
64315        len = sqlite3GetToken(zCsr, &token);
64316      } while( token==TK_SPACE );
64317      assert( len>0 );
64318    } while( token!=TK_LP && token!=TK_USING );
64319
64320    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
64321       zTableName, tname.z+tname.n);
64322    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
64323  }
64324}
64325
64326/*
64327** This C function implements an SQL user function that is used by SQL code
64328** generated by the ALTER TABLE ... RENAME command to modify the definition
64329** of any foreign key constraints that use the table being renamed as the
64330** parent table. It is passed three arguments:
64331**
64332**   1) The complete text of the CREATE TABLE statement being modified,
64333**   2) The old name of the table being renamed, and
64334**   3) The new name of the table being renamed.
64335**
64336** It returns the new CREATE TABLE statement. For example:
64337**
64338**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
64339**       -> 'CREATE TABLE t1(a REFERENCES t3)'
64340*/
64341#ifndef SQLITE_OMIT_FOREIGN_KEY
64342static void renameParentFunc(
64343  sqlite3_context *context,
64344  int NotUsed,
64345  sqlite3_value **argv
64346){
64347  sqlite3 *db = sqlite3_context_db_handle(context);
64348  char *zOutput = 0;
64349  char *zResult;
64350  unsigned char const *zInput = sqlite3_value_text(argv[0]);
64351  unsigned char const *zOld = sqlite3_value_text(argv[1]);
64352  unsigned char const *zNew = sqlite3_value_text(argv[2]);
64353
64354  unsigned const char *z;         /* Pointer to token */
64355  int n;                          /* Length of token z */
64356  int token;                      /* Type of token */
64357
64358  UNUSED_PARAMETER(NotUsed);
64359  for(z=zInput; *z; z=z+n){
64360    n = sqlite3GetToken(z, &token);
64361    if( token==TK_REFERENCES ){
64362      char *zParent;
64363      do {
64364        z += n;
64365        n = sqlite3GetToken(z, &token);
64366      }while( token==TK_SPACE );
64367
64368      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
64369      if( zParent==0 ) break;
64370      sqlite3Dequote(zParent);
64371      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
64372        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
64373            (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
64374        );
64375        sqlite3DbFree(db, zOutput);
64376        zOutput = zOut;
64377        zInput = &z[n];
64378      }
64379      sqlite3DbFree(db, zParent);
64380    }
64381  }
64382
64383  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
64384  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
64385  sqlite3DbFree(db, zOutput);
64386}
64387#endif
64388
64389#ifndef SQLITE_OMIT_TRIGGER
64390/* This function is used by SQL generated to implement the
64391** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
64392** statement. The second is a table name. The table name in the CREATE
64393** TRIGGER statement is replaced with the third argument and the result
64394** returned. This is analagous to renameTableFunc() above, except for CREATE
64395** TRIGGER, not CREATE INDEX and CREATE TABLE.
64396*/
64397static void renameTriggerFunc(
64398  sqlite3_context *context,
64399  int NotUsed,
64400  sqlite3_value **argv
64401){
64402  unsigned char const *zSql = sqlite3_value_text(argv[0]);
64403  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
64404
64405  int token;
64406  Token tname;
64407  int dist = 3;
64408  unsigned char const *zCsr = zSql;
64409  int len = 0;
64410  char *zRet;
64411  sqlite3 *db = sqlite3_context_db_handle(context);
64412
64413  UNUSED_PARAMETER(NotUsed);
64414
64415  /* The principle used to locate the table name in the CREATE TRIGGER
64416  ** statement is that the table name is the first token that is immediatedly
64417  ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
64418  ** of TK_WHEN, TK_BEGIN or TK_FOR.
64419  */
64420  if( zSql ){
64421    do {
64422
64423      if( !*zCsr ){
64424        /* Ran out of input before finding the table name. Return NULL. */
64425        return;
64426      }
64427
64428      /* Store the token that zCsr points to in tname. */
64429      tname.z = (char*)zCsr;
64430      tname.n = len;
64431
64432      /* Advance zCsr to the next token. Store that token type in 'token',
64433      ** and its length in 'len' (to be used next iteration of this loop).
64434      */
64435      do {
64436        zCsr += len;
64437        len = sqlite3GetToken(zCsr, &token);
64438      }while( token==TK_SPACE );
64439      assert( len>0 );
64440
64441      /* Variable 'dist' stores the number of tokens read since the most
64442      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
64443      ** token is read and 'dist' equals 2, the condition stated above
64444      ** to be met.
64445      **
64446      ** Note that ON cannot be a database, table or column name, so
64447      ** there is no need to worry about syntax like
64448      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
64449      */
64450      dist++;
64451      if( token==TK_DOT || token==TK_ON ){
64452        dist = 0;
64453      }
64454    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
64455
64456    /* Variable tname now contains the token that is the old table-name
64457    ** in the CREATE TRIGGER statement.
64458    */
64459    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
64460       zTableName, tname.z+tname.n);
64461    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
64462  }
64463}
64464#endif   /* !SQLITE_OMIT_TRIGGER */
64465
64466/*
64467** Register built-in functions used to help implement ALTER TABLE
64468*/
64469SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
64470  sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
64471                         renameTableFunc, 0, 0);
64472#ifndef SQLITE_OMIT_TRIGGER
64473  sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
64474                         renameTriggerFunc, 0, 0);
64475#endif
64476#ifndef SQLITE_OMIT_FOREIGN_KEY
64477  sqlite3CreateFunc(db, "sqlite_rename_parent", 3, SQLITE_UTF8, 0,
64478                         renameParentFunc, 0, 0);
64479#endif
64480}
64481
64482/*
64483** This function is used to create the text of expressions of the form:
64484**
64485**   name=<constant1> OR name=<constant2> OR ...
64486**
64487** If argument zWhere is NULL, then a pointer string containing the text
64488** "name=<constant>" is returned, where <constant> is the quoted version
64489** of the string passed as argument zConstant. The returned buffer is
64490** allocated using sqlite3DbMalloc(). It is the responsibility of the
64491** caller to ensure that it is eventually freed.
64492**
64493** If argument zWhere is not NULL, then the string returned is
64494** "<where> OR name=<constant>", where <where> is the contents of zWhere.
64495** In this case zWhere is passed to sqlite3DbFree() before returning.
64496**
64497*/
64498static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
64499  char *zNew;
64500  if( !zWhere ){
64501    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
64502  }else{
64503    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
64504    sqlite3DbFree(db, zWhere);
64505  }
64506  return zNew;
64507}
64508
64509#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
64510/*
64511** Generate the text of a WHERE expression which can be used to select all
64512** tables that have foreign key constraints that refer to table pTab (i.e.
64513** constraints for which pTab is the parent table) from the sqlite_master
64514** table.
64515*/
64516static char *whereForeignKeys(Parse *pParse, Table *pTab){
64517  FKey *p;
64518  char *zWhere = 0;
64519  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
64520    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
64521  }
64522  return zWhere;
64523}
64524#endif
64525
64526/*
64527** Generate the text of a WHERE expression which can be used to select all
64528** temporary triggers on table pTab from the sqlite_temp_master table. If
64529** table pTab has no temporary triggers, or is itself stored in the
64530** temporary database, NULL is returned.
64531*/
64532static char *whereTempTriggers(Parse *pParse, Table *pTab){
64533  Trigger *pTrig;
64534  char *zWhere = 0;
64535  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
64536
64537  /* If the table is not located in the temp-db (in which case NULL is
64538  ** returned, loop through the tables list of triggers. For each trigger
64539  ** that is not part of the temp-db schema, add a clause to the WHERE
64540  ** expression being built up in zWhere.
64541  */
64542  if( pTab->pSchema!=pTempSchema ){
64543    sqlite3 *db = pParse->db;
64544    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
64545      if( pTrig->pSchema==pTempSchema ){
64546        zWhere = whereOrName(db, zWhere, pTrig->zName);
64547      }
64548    }
64549  }
64550  return zWhere;
64551}
64552
64553/*
64554** Generate code to drop and reload the internal representation of table
64555** pTab from the database, including triggers and temporary triggers.
64556** Argument zName is the name of the table in the database schema at
64557** the time the generated code is executed. This can be different from
64558** pTab->zName if this function is being called to code part of an
64559** "ALTER TABLE RENAME TO" statement.
64560*/
64561static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
64562  Vdbe *v;
64563  char *zWhere;
64564  int iDb;                   /* Index of database containing pTab */
64565#ifndef SQLITE_OMIT_TRIGGER
64566  Trigger *pTrig;
64567#endif
64568
64569  v = sqlite3GetVdbe(pParse);
64570  if( NEVER(v==0) ) return;
64571  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
64572  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
64573  assert( iDb>=0 );
64574
64575#ifndef SQLITE_OMIT_TRIGGER
64576  /* Drop any table triggers from the internal schema. */
64577  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
64578    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
64579    assert( iTrigDb==iDb || iTrigDb==1 );
64580    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
64581  }
64582#endif
64583
64584  /* Drop the table and index from the internal schema.  */
64585  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
64586
64587  /* Reload the table, index and permanent trigger schemas. */
64588  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
64589  if( !zWhere ) return;
64590  sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
64591
64592#ifndef SQLITE_OMIT_TRIGGER
64593  /* Now, if the table is not stored in the temp database, reload any temp
64594  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
64595  */
64596  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
64597    sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
64598  }
64599#endif
64600}
64601
64602/*
64603** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
64604** command.
64605*/
64606SQLITE_PRIVATE void sqlite3AlterRenameTable(
64607  Parse *pParse,            /* Parser context. */
64608  SrcList *pSrc,            /* The table to rename. */
64609  Token *pName              /* The new table name. */
64610){
64611  int iDb;                  /* Database that contains the table */
64612  char *zDb;                /* Name of database iDb */
64613  Table *pTab;              /* Table being renamed */
64614  char *zName = 0;          /* NULL-terminated version of pName */
64615  sqlite3 *db = pParse->db; /* Database connection */
64616  int nTabName;             /* Number of UTF-8 characters in zTabName */
64617  const char *zTabName;     /* Original name of the table */
64618  Vdbe *v;
64619#ifndef SQLITE_OMIT_TRIGGER
64620  char *zWhere = 0;         /* Where clause to locate temp triggers */
64621#endif
64622  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
64623
64624  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
64625  assert( pSrc->nSrc==1 );
64626  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
64627
64628  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
64629  if( !pTab ) goto exit_rename_table;
64630  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
64631  zDb = db->aDb[iDb].zName;
64632
64633  /* Get a NULL terminated version of the new table name. */
64634  zName = sqlite3NameFromToken(db, pName);
64635  if( !zName ) goto exit_rename_table;
64636
64637  /* Check that a table or index named 'zName' does not already exist
64638  ** in database iDb. If so, this is an error.
64639  */
64640  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
64641    sqlite3ErrorMsg(pParse,
64642        "there is already another table or index with this name: %s", zName);
64643    goto exit_rename_table;
64644  }
64645
64646  /* Make sure it is not a system table being altered, or a reserved name
64647  ** that the table is being renamed to.
64648  */
64649  if( sqlite3Strlen30(pTab->zName)>6
64650   && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
64651  ){
64652    sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
64653    goto exit_rename_table;
64654  }
64655  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
64656    goto exit_rename_table;
64657  }
64658
64659#ifndef SQLITE_OMIT_VIEW
64660  if( pTab->pSelect ){
64661    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
64662    goto exit_rename_table;
64663  }
64664#endif
64665
64666#ifndef SQLITE_OMIT_AUTHORIZATION
64667  /* Invoke the authorization callback. */
64668  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
64669    goto exit_rename_table;
64670  }
64671#endif
64672
64673#ifndef SQLITE_OMIT_VIRTUALTABLE
64674  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
64675    goto exit_rename_table;
64676  }
64677  if( IsVirtual(pTab) ){
64678    pVTab = sqlite3GetVTable(db, pTab);
64679    if( pVTab->pVtab->pModule->xRename==0 ){
64680      pVTab = 0;
64681    }
64682  }
64683#endif
64684
64685  /* Begin a transaction and code the VerifyCookie for database iDb.
64686  ** Then modify the schema cookie (since the ALTER TABLE modifies the
64687  ** schema). Open a statement transaction if the table is a virtual
64688  ** table.
64689  */
64690  v = sqlite3GetVdbe(pParse);
64691  if( v==0 ){
64692    goto exit_rename_table;
64693  }
64694  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
64695  sqlite3ChangeCookie(pParse, iDb);
64696
64697  /* If this is a virtual table, invoke the xRename() function if
64698  ** one is defined. The xRename() callback will modify the names
64699  ** of any resources used by the v-table implementation (including other
64700  ** SQLite tables) that are identified by the name of the virtual table.
64701  */
64702#ifndef SQLITE_OMIT_VIRTUALTABLE
64703  if( pVTab ){
64704    int i = ++pParse->nMem;
64705    sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
64706    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
64707    sqlite3MayAbort(pParse);
64708  }
64709#endif
64710
64711  /* figure out how many UTF-8 characters are in zName */
64712  zTabName = pTab->zName;
64713  nTabName = sqlite3Utf8CharLen(zTabName, -1);
64714
64715#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
64716  if( db->flags&SQLITE_ForeignKeys ){
64717    /* If foreign-key support is enabled, rewrite the CREATE TABLE
64718    ** statements corresponding to all child tables of foreign key constraints
64719    ** for which the renamed table is the parent table.  */
64720    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
64721      sqlite3NestedParse(pParse,
64722          "UPDATE sqlite_master SET "
64723              "sql = sqlite_rename_parent(sql, %Q, %Q) "
64724              "WHERE %s;", zTabName, zName, zWhere);
64725      sqlite3DbFree(db, zWhere);
64726    }
64727  }
64728#endif
64729
64730  /* Modify the sqlite_master table to use the new table name. */
64731  sqlite3NestedParse(pParse,
64732      "UPDATE %Q.%s SET "
64733#ifdef SQLITE_OMIT_TRIGGER
64734          "sql = sqlite_rename_table(sql, %Q), "
64735#else
64736          "sql = CASE "
64737            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
64738            "ELSE sqlite_rename_table(sql, %Q) END, "
64739#endif
64740          "tbl_name = %Q, "
64741          "name = CASE "
64742            "WHEN type='table' THEN %Q "
64743            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
64744             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
64745            "ELSE name END "
64746      "WHERE tbl_name=%Q AND "
64747          "(type='table' OR type='index' OR type='trigger');",
64748      zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
64749#ifndef SQLITE_OMIT_TRIGGER
64750      zName,
64751#endif
64752      zName, nTabName, zTabName
64753  );
64754
64755#ifndef SQLITE_OMIT_AUTOINCREMENT
64756  /* If the sqlite_sequence table exists in this database, then update
64757  ** it with the new table name.
64758  */
64759  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
64760    sqlite3NestedParse(pParse,
64761        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
64762        zDb, zName, pTab->zName);
64763  }
64764#endif
64765
64766#ifndef SQLITE_OMIT_TRIGGER
64767  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
64768  ** table. Don't do this if the table being ALTERed is itself located in
64769  ** the temp database.
64770  */
64771  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
64772    sqlite3NestedParse(pParse,
64773        "UPDATE sqlite_temp_master SET "
64774            "sql = sqlite_rename_trigger(sql, %Q), "
64775            "tbl_name = %Q "
64776            "WHERE %s;", zName, zName, zWhere);
64777    sqlite3DbFree(db, zWhere);
64778  }
64779#endif
64780
64781#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
64782  if( db->flags&SQLITE_ForeignKeys ){
64783    FKey *p;
64784    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
64785      Table *pFrom = p->pFrom;
64786      if( pFrom!=pTab ){
64787        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
64788      }
64789    }
64790  }
64791#endif
64792
64793  /* Drop and reload the internal table schema. */
64794  reloadTableSchema(pParse, pTab, zName);
64795
64796exit_rename_table:
64797  sqlite3SrcListDelete(db, pSrc);
64798  sqlite3DbFree(db, zName);
64799}
64800
64801
64802/*
64803** Generate code to make sure the file format number is at least minFormat.
64804** The generated code will increase the file format number if necessary.
64805*/
64806SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
64807  Vdbe *v;
64808  v = sqlite3GetVdbe(pParse);
64809  /* The VDBE should have been allocated before this routine is called.
64810  ** If that allocation failed, we would have quit before reaching this
64811  ** point */
64812  if( ALWAYS(v) ){
64813    int r1 = sqlite3GetTempReg(pParse);
64814    int r2 = sqlite3GetTempReg(pParse);
64815    int j1;
64816    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
64817    sqlite3VdbeUsesBtree(v, iDb);
64818    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
64819    j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
64820    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
64821    sqlite3VdbeJumpHere(v, j1);
64822    sqlite3ReleaseTempReg(pParse, r1);
64823    sqlite3ReleaseTempReg(pParse, r2);
64824  }
64825}
64826
64827/*
64828** This function is called after an "ALTER TABLE ... ADD" statement
64829** has been parsed. Argument pColDef contains the text of the new
64830** column definition.
64831**
64832** The Table structure pParse->pNewTable was extended to include
64833** the new column during parsing.
64834*/
64835SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
64836  Table *pNew;              /* Copy of pParse->pNewTable */
64837  Table *pTab;              /* Table being altered */
64838  int iDb;                  /* Database number */
64839  const char *zDb;          /* Database name */
64840  const char *zTab;         /* Table name */
64841  char *zCol;               /* Null-terminated column definition */
64842  Column *pCol;             /* The new column */
64843  Expr *pDflt;              /* Default value for the new column */
64844  sqlite3 *db;              /* The database connection; */
64845
64846  db = pParse->db;
64847  if( pParse->nErr || db->mallocFailed ) return;
64848  pNew = pParse->pNewTable;
64849  assert( pNew );
64850
64851  assert( sqlite3BtreeHoldsAllMutexes(db) );
64852  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
64853  zDb = db->aDb[iDb].zName;
64854  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
64855  pCol = &pNew->aCol[pNew->nCol-1];
64856  pDflt = pCol->pDflt;
64857  pTab = sqlite3FindTable(db, zTab, zDb);
64858  assert( pTab );
64859
64860#ifndef SQLITE_OMIT_AUTHORIZATION
64861  /* Invoke the authorization callback. */
64862  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
64863    return;
64864  }
64865#endif
64866
64867  /* If the default value for the new column was specified with a
64868  ** literal NULL, then set pDflt to 0. This simplifies checking
64869  ** for an SQL NULL default below.
64870  */
64871  if( pDflt && pDflt->op==TK_NULL ){
64872    pDflt = 0;
64873  }
64874
64875  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
64876  ** If there is a NOT NULL constraint, then the default value for the
64877  ** column must not be NULL.
64878  */
64879  if( pCol->isPrimKey ){
64880    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
64881    return;
64882  }
64883  if( pNew->pIndex ){
64884    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
64885    return;
64886  }
64887  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
64888    sqlite3ErrorMsg(pParse,
64889        "Cannot add a REFERENCES column with non-NULL default value");
64890    return;
64891  }
64892  if( pCol->notNull && !pDflt ){
64893    sqlite3ErrorMsg(pParse,
64894        "Cannot add a NOT NULL column with default value NULL");
64895    return;
64896  }
64897
64898  /* Ensure the default expression is something that sqlite3ValueFromExpr()
64899  ** can handle (i.e. not CURRENT_TIME etc.)
64900  */
64901  if( pDflt ){
64902    sqlite3_value *pVal;
64903    if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
64904      db->mallocFailed = 1;
64905      return;
64906    }
64907    if( !pVal ){
64908      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
64909      return;
64910    }
64911    sqlite3ValueFree(pVal);
64912  }
64913
64914  /* Modify the CREATE TABLE statement. */
64915  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
64916  if( zCol ){
64917    char *zEnd = &zCol[pColDef->n-1];
64918    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
64919      *zEnd-- = '\0';
64920    }
64921    sqlite3NestedParse(pParse,
64922        "UPDATE \"%w\".%s SET "
64923          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
64924        "WHERE type = 'table' AND name = %Q",
64925      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
64926      zTab
64927    );
64928    sqlite3DbFree(db, zCol);
64929  }
64930
64931  /* If the default value of the new column is NULL, then set the file
64932  ** format to 2. If the default value of the new column is not NULL,
64933  ** the file format becomes 3.
64934  */
64935  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
64936
64937  /* Reload the schema of the modified table. */
64938  reloadTableSchema(pParse, pTab, pTab->zName);
64939}
64940
64941/*
64942** This function is called by the parser after the table-name in
64943** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
64944** pSrc is the full-name of the table being altered.
64945**
64946** This routine makes a (partial) copy of the Table structure
64947** for the table being altered and sets Parse.pNewTable to point
64948** to it. Routines called by the parser as the column definition
64949** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
64950** the copy. The copy of the Table structure is deleted by tokenize.c
64951** after parsing is finished.
64952**
64953** Routine sqlite3AlterFinishAddColumn() will be called to complete
64954** coding the "ALTER TABLE ... ADD" statement.
64955*/
64956SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
64957  Table *pNew;
64958  Table *pTab;
64959  Vdbe *v;
64960  int iDb;
64961  int i;
64962  int nAlloc;
64963  sqlite3 *db = pParse->db;
64964
64965  /* Look up the table being altered. */
64966  assert( pParse->pNewTable==0 );
64967  assert( sqlite3BtreeHoldsAllMutexes(db) );
64968  if( db->mallocFailed ) goto exit_begin_add_column;
64969  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
64970  if( !pTab ) goto exit_begin_add_column;
64971
64972#ifndef SQLITE_OMIT_VIRTUALTABLE
64973  if( IsVirtual(pTab) ){
64974    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
64975    goto exit_begin_add_column;
64976  }
64977#endif
64978
64979  /* Make sure this is not an attempt to ALTER a view. */
64980  if( pTab->pSelect ){
64981    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
64982    goto exit_begin_add_column;
64983  }
64984
64985  assert( pTab->addColOffset>0 );
64986  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
64987
64988  /* Put a copy of the Table struct in Parse.pNewTable for the
64989  ** sqlite3AddColumn() function and friends to modify.  But modify
64990  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
64991  ** prefix, we insure that the name will not collide with an existing
64992  ** table because user table are not allowed to have the "sqlite_"
64993  ** prefix on their name.
64994  */
64995  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
64996  if( !pNew ) goto exit_begin_add_column;
64997  pParse->pNewTable = pNew;
64998  pNew->nRef = 1;
64999  pNew->dbMem = pTab->dbMem;
65000  pNew->nCol = pTab->nCol;
65001  assert( pNew->nCol>0 );
65002  nAlloc = (((pNew->nCol-1)/8)*8)+8;
65003  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
65004  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
65005  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
65006  if( !pNew->aCol || !pNew->zName ){
65007    db->mallocFailed = 1;
65008    goto exit_begin_add_column;
65009  }
65010  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
65011  for(i=0; i<pNew->nCol; i++){
65012    Column *pCol = &pNew->aCol[i];
65013    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
65014    pCol->zColl = 0;
65015    pCol->zType = 0;
65016    pCol->pDflt = 0;
65017    pCol->zDflt = 0;
65018  }
65019  pNew->pSchema = db->aDb[iDb].pSchema;
65020  pNew->addColOffset = pTab->addColOffset;
65021  pNew->nRef = 1;
65022
65023  /* Begin a transaction and increment the schema cookie.  */
65024  sqlite3BeginWriteOperation(pParse, 0, iDb);
65025  v = sqlite3GetVdbe(pParse);
65026  if( !v ) goto exit_begin_add_column;
65027  sqlite3ChangeCookie(pParse, iDb);
65028
65029exit_begin_add_column:
65030  sqlite3SrcListDelete(db, pSrc);
65031  return;
65032}
65033#endif  /* SQLITE_ALTER_TABLE */
65034
65035/************** End of alter.c ***********************************************/
65036/************** Begin file analyze.c *****************************************/
65037/*
65038** 2005 July 8
65039**
65040** The author disclaims copyright to this source code.  In place of
65041** a legal notice, here is a blessing:
65042**
65043**    May you do good and not evil.
65044**    May you find forgiveness for yourself and forgive others.
65045**    May you share freely, never taking more than you give.
65046**
65047*************************************************************************
65048** This file contains code associated with the ANALYZE command.
65049*/
65050#ifndef SQLITE_OMIT_ANALYZE
65051
65052/*
65053** This routine generates code that opens the sqlite_stat1 table for
65054** writing with cursor iStatCur. If the library was built with the
65055** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
65056** opened for writing using cursor (iStatCur+1)
65057**
65058** If the sqlite_stat1 tables does not previously exist, it is created.
65059** Similarly, if the sqlite_stat2 table does not exist and the library
65060** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
65061**
65062** Argument zWhere may be a pointer to a buffer containing a table name,
65063** or it may be a NULL pointer. If it is not NULL, then all entries in
65064** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
65065** with the named table are deleted. If zWhere==0, then code is generated
65066** to delete all stat table entries.
65067*/
65068static void openStatTable(
65069  Parse *pParse,          /* Parsing context */
65070  int iDb,                /* The database we are looking in */
65071  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
65072  const char *zWhere      /* Delete entries associated with this table */
65073){
65074  static struct {
65075    const char *zName;
65076    const char *zCols;
65077  } aTable[] = {
65078    { "sqlite_stat1", "tbl,idx,stat" },
65079#ifdef SQLITE_ENABLE_STAT2
65080    { "sqlite_stat2", "tbl,idx,sampleno,sample" },
65081#endif
65082  };
65083
65084  int aRoot[] = {0, 0};
65085  u8 aCreateTbl[] = {0, 0};
65086
65087  int i;
65088  sqlite3 *db = pParse->db;
65089  Db *pDb;
65090  Vdbe *v = sqlite3GetVdbe(pParse);
65091  if( v==0 ) return;
65092  assert( sqlite3BtreeHoldsAllMutexes(db) );
65093  assert( sqlite3VdbeDb(v)==db );
65094  pDb = &db->aDb[iDb];
65095
65096  for(i=0; i<ArraySize(aTable); i++){
65097    const char *zTab = aTable[i].zName;
65098    Table *pStat;
65099    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
65100      /* The sqlite_stat[12] table does not exist. Create it. Note that a
65101      ** side-effect of the CREATE TABLE statement is to leave the rootpage
65102      ** of the new table in register pParse->regRoot. This is important
65103      ** because the OpenWrite opcode below will be needing it. */
65104      sqlite3NestedParse(pParse,
65105          "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
65106      );
65107      aRoot[i] = pParse->regRoot;
65108      aCreateTbl[i] = 1;
65109    }else{
65110      /* The table already exists. If zWhere is not NULL, delete all entries
65111      ** associated with the table zWhere. If zWhere is NULL, delete the
65112      ** entire contents of the table. */
65113      aRoot[i] = pStat->tnum;
65114      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
65115      if( zWhere ){
65116        sqlite3NestedParse(pParse,
65117           "DELETE FROM %Q.%s WHERE tbl=%Q", pDb->zName, zTab, zWhere
65118        );
65119      }else{
65120        /* The sqlite_stat[12] table already exists.  Delete all rows. */
65121        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
65122      }
65123    }
65124  }
65125
65126  /* Open the sqlite_stat[12] tables for writing. */
65127  for(i=0; i<ArraySize(aTable); i++){
65128    sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
65129    sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
65130    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
65131  }
65132}
65133
65134/*
65135** Generate code to do an analysis of all indices associated with
65136** a single table.
65137*/
65138static void analyzeOneTable(
65139  Parse *pParse,   /* Parser context */
65140  Table *pTab,     /* Table whose indices are to be analyzed */
65141  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
65142  int iMem         /* Available memory locations begin here */
65143){
65144  sqlite3 *db = pParse->db;    /* Database handle */
65145  Index *pIdx;                 /* An index to being analyzed */
65146  int iIdxCur;                 /* Cursor open on index being analyzed */
65147  Vdbe *v;                     /* The virtual machine being built up */
65148  int i;                       /* Loop counter */
65149  int topOfLoop;               /* The top of the loop */
65150  int endOfLoop;               /* The end of the loop */
65151  int addr;                    /* The address of an instruction */
65152  int iDb;                     /* Index of database containing pTab */
65153  int regTabname = iMem++;     /* Register containing table name */
65154  int regIdxname = iMem++;     /* Register containing index name */
65155  int regSampleno = iMem++;    /* Register containing next sample number */
65156  int regCol = iMem++;         /* Content of a column analyzed table */
65157  int regRec = iMem++;         /* Register holding completed record */
65158  int regTemp = iMem++;        /* Temporary use register */
65159  int regRowid = iMem++;       /* Rowid for the inserted record */
65160
65161#ifdef SQLITE_ENABLE_STAT2
65162  int regTemp2 = iMem++;       /* Temporary use register */
65163  int regSamplerecno = iMem++; /* Index of next sample to record */
65164  int regRecno = iMem++;       /* Current sample index */
65165  int regLast = iMem++;        /* Index of last sample to record */
65166  int regFirst = iMem++;       /* Index of first sample to record */
65167#endif
65168
65169  v = sqlite3GetVdbe(pParse);
65170  if( v==0 || NEVER(pTab==0) || pTab->pIndex==0 ){
65171    /* Do no analysis for tables that have no indices */
65172    return;
65173  }
65174  assert( sqlite3BtreeHoldsAllMutexes(db) );
65175  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
65176  assert( iDb>=0 );
65177#ifndef SQLITE_OMIT_AUTHORIZATION
65178  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
65179      db->aDb[iDb].zName ) ){
65180    return;
65181  }
65182#endif
65183
65184  /* Establish a read-lock on the table at the shared-cache level. */
65185  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
65186
65187  iIdxCur = pParse->nTab++;
65188  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
65189    int nCol = pIdx->nColumn;
65190    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
65191
65192    if( iMem+1+(nCol*2)>pParse->nMem ){
65193      pParse->nMem = iMem+1+(nCol*2);
65194    }
65195
65196    /* Open a cursor to the index to be analyzed. */
65197    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
65198    sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
65199        (char *)pKey, P4_KEYINFO_HANDOFF);
65200    VdbeComment((v, "%s", pIdx->zName));
65201
65202    /* Populate the registers containing the table and index names. */
65203    if( pTab->pIndex==pIdx ){
65204      sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
65205    }
65206    sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
65207
65208#ifdef SQLITE_ENABLE_STAT2
65209
65210    /* If this iteration of the loop is generating code to analyze the
65211    ** first index in the pTab->pIndex list, then register regLast has
65212    ** not been populated. In this case populate it now.  */
65213    if( pTab->pIndex==pIdx ){
65214      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
65215      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
65216      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
65217
65218      sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
65219      sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
65220      addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
65221      sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
65222      sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
65223      sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
65224      sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
65225      sqlite3VdbeJumpHere(v, addr);
65226    }
65227
65228    /* Zero the regSampleno and regRecno registers. */
65229    sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
65230    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
65231    sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
65232#endif
65233
65234    /* The block of memory cells initialized here is used as follows.
65235    **
65236    **    iMem:
65237    **        The total number of rows in the table.
65238    **
65239    **    iMem+1 .. iMem+nCol:
65240    **        Number of distinct entries in index considering the
65241    **        left-most N columns only, where N is between 1 and nCol,
65242    **        inclusive.
65243    **
65244    **    iMem+nCol+1 .. Mem+2*nCol:
65245    **        Previous value of indexed columns, from left to right.
65246    **
65247    ** Cells iMem through iMem+nCol are initialized to 0. The others are
65248    ** initialized to contain an SQL NULL.
65249    */
65250    for(i=0; i<=nCol; i++){
65251      sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
65252    }
65253    for(i=0; i<nCol; i++){
65254      sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
65255    }
65256
65257    /* Start the analysis loop. This loop runs through all the entries in
65258    ** the index b-tree.  */
65259    endOfLoop = sqlite3VdbeMakeLabel(v);
65260    sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
65261    topOfLoop = sqlite3VdbeCurrentAddr(v);
65262    sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
65263
65264    for(i=0; i<nCol; i++){
65265      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
65266#ifdef SQLITE_ENABLE_STAT2
65267      if( i==0 ){
65268        /* Check if the record that cursor iIdxCur points to contains a
65269        ** value that should be stored in the sqlite_stat2 table. If so,
65270        ** store it.  */
65271        int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
65272        assert( regTabname+1==regIdxname
65273             && regTabname+2==regSampleno
65274             && regTabname+3==regCol
65275        );
65276        sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
65277        sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
65278        sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
65279        sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
65280
65281        /* Calculate new values for regSamplerecno and regSampleno.
65282        **
65283        **   sampleno = sampleno + 1
65284        **   samplerecno = samplerecno+(remaining records)/(remaining samples)
65285        */
65286        sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
65287        sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
65288        sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
65289        sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
65290        sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
65291        sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
65292        sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
65293
65294        sqlite3VdbeJumpHere(v, ne);
65295        sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
65296      }
65297#endif
65298
65299      sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
65300      /**** TODO:  add collating sequence *****/
65301      sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
65302    }
65303    if( db->mallocFailed ){
65304      /* If a malloc failure has occurred, then the result of the expression
65305      ** passed as the second argument to the call to sqlite3VdbeJumpHere()
65306      ** below may be negative. Which causes an assert() to fail (or an
65307      ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
65308      return;
65309    }
65310    sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
65311    for(i=0; i<nCol; i++){
65312      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-(nCol*2));
65313      sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
65314      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
65315    }
65316
65317    /* End of the analysis loop. */
65318    sqlite3VdbeResolveLabel(v, endOfLoop);
65319    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
65320    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
65321
65322    /* Store the results in sqlite_stat1.
65323    **
65324    ** The result is a single row of the sqlite_stat1 table.  The first
65325    ** two columns are the names of the table and index.  The third column
65326    ** is a string composed of a list of integer statistics about the
65327    ** index.  The first integer in the list is the total number of entries
65328    ** in the index.  There is one additional integer in the list for each
65329    ** column of the table.  This additional integer is a guess of how many
65330    ** rows of the table the index will select.  If D is the count of distinct
65331    ** values and K is the total number of rows, then the integer is computed
65332    ** as:
65333    **
65334    **        I = (K+D-1)/D
65335    **
65336    ** If K==0 then no entry is made into the sqlite_stat1 table.
65337    ** If K>0 then it is always the case the D>0 so division by zero
65338    ** is never possible.
65339    */
65340    addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
65341    sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
65342    for(i=0; i<nCol; i++){
65343      sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
65344      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
65345      sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
65346      sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
65347      sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
65348      sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
65349      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
65350    }
65351    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
65352    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
65353    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
65354    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
65355    sqlite3VdbeJumpHere(v, addr);
65356  }
65357}
65358
65359/*
65360** Generate code that will cause the most recent index analysis to
65361** be laoded into internal hash tables where is can be used.
65362*/
65363static void loadAnalysis(Parse *pParse, int iDb){
65364  Vdbe *v = sqlite3GetVdbe(pParse);
65365  if( v ){
65366    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
65367  }
65368}
65369
65370/*
65371** Generate code that will do an analysis of an entire database
65372*/
65373static void analyzeDatabase(Parse *pParse, int iDb){
65374  sqlite3 *db = pParse->db;
65375  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
65376  HashElem *k;
65377  int iStatCur;
65378  int iMem;
65379
65380  sqlite3BeginWriteOperation(pParse, 0, iDb);
65381  iStatCur = pParse->nTab;
65382  pParse->nTab += 2;
65383  openStatTable(pParse, iDb, iStatCur, 0);
65384  iMem = pParse->nMem+1;
65385  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
65386    Table *pTab = (Table*)sqliteHashData(k);
65387    analyzeOneTable(pParse, pTab, iStatCur, iMem);
65388  }
65389  loadAnalysis(pParse, iDb);
65390}
65391
65392/*
65393** Generate code that will do an analysis of a single table in
65394** a database.
65395*/
65396static void analyzeTable(Parse *pParse, Table *pTab){
65397  int iDb;
65398  int iStatCur;
65399
65400  assert( pTab!=0 );
65401  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
65402  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
65403  sqlite3BeginWriteOperation(pParse, 0, iDb);
65404  iStatCur = pParse->nTab;
65405  pParse->nTab += 2;
65406  openStatTable(pParse, iDb, iStatCur, pTab->zName);
65407  analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
65408  loadAnalysis(pParse, iDb);
65409}
65410
65411/*
65412** Generate code for the ANALYZE command.  The parser calls this routine
65413** when it recognizes an ANALYZE command.
65414**
65415**        ANALYZE                            -- 1
65416**        ANALYZE  <database>                -- 2
65417**        ANALYZE  ?<database>.?<tablename>  -- 3
65418**
65419** Form 1 causes all indices in all attached databases to be analyzed.
65420** Form 2 analyzes all indices the single database named.
65421** Form 3 analyzes all indices associated with the named table.
65422*/
65423SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
65424  sqlite3 *db = pParse->db;
65425  int iDb;
65426  int i;
65427  char *z, *zDb;
65428  Table *pTab;
65429  Token *pTableName;
65430
65431  /* Read the database schema. If an error occurs, leave an error message
65432  ** and code in pParse and return NULL. */
65433  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
65434  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
65435    return;
65436  }
65437
65438  assert( pName2!=0 || pName1==0 );
65439  if( pName1==0 ){
65440    /* Form 1:  Analyze everything */
65441    for(i=0; i<db->nDb; i++){
65442      if( i==1 ) continue;  /* Do not analyze the TEMP database */
65443      analyzeDatabase(pParse, i);
65444    }
65445  }else if( pName2->n==0 ){
65446    /* Form 2:  Analyze the database or table named */
65447    iDb = sqlite3FindDb(db, pName1);
65448    if( iDb>=0 ){
65449      analyzeDatabase(pParse, iDb);
65450    }else{
65451      z = sqlite3NameFromToken(db, pName1);
65452      if( z ){
65453        pTab = sqlite3LocateTable(pParse, 0, z, 0);
65454        sqlite3DbFree(db, z);
65455        if( pTab ){
65456          analyzeTable(pParse, pTab);
65457        }
65458      }
65459    }
65460  }else{
65461    /* Form 3: Analyze the fully qualified table name */
65462    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
65463    if( iDb>=0 ){
65464      zDb = db->aDb[iDb].zName;
65465      z = sqlite3NameFromToken(db, pTableName);
65466      if( z ){
65467        pTab = sqlite3LocateTable(pParse, 0, z, zDb);
65468        sqlite3DbFree(db, z);
65469        if( pTab ){
65470          analyzeTable(pParse, pTab);
65471        }
65472      }
65473    }
65474  }
65475}
65476
65477/*
65478** Used to pass information from the analyzer reader through to the
65479** callback routine.
65480*/
65481typedef struct analysisInfo analysisInfo;
65482struct analysisInfo {
65483  sqlite3 *db;
65484  const char *zDatabase;
65485};
65486
65487/*
65488** This callback is invoked once for each index when reading the
65489** sqlite_stat1 table.
65490**
65491**     argv[0] = name of the index
65492**     argv[1] = results of analysis - on integer for each column
65493*/
65494static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
65495  analysisInfo *pInfo = (analysisInfo*)pData;
65496  Index *pIndex;
65497  int i, c;
65498  unsigned int v;
65499  const char *z;
65500
65501  assert( argc==2 );
65502  UNUSED_PARAMETER2(NotUsed, argc);
65503
65504  if( argv==0 || argv[0]==0 || argv[1]==0 ){
65505    return 0;
65506  }
65507  pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
65508  if( pIndex==0 ){
65509    return 0;
65510  }
65511  z = argv[1];
65512  for(i=0; *z && i<=pIndex->nColumn; i++){
65513    v = 0;
65514    while( (c=z[0])>='0' && c<='9' ){
65515      v = v*10 + c - '0';
65516      z++;
65517    }
65518    pIndex->aiRowEst[i] = v;
65519    if( *z==' ' ) z++;
65520  }
65521  return 0;
65522}
65523
65524/*
65525** If the Index.aSample variable is not NULL, delete the aSample[] array
65526** and its contents.
65527*/
65528SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index *pIdx){
65529#ifdef SQLITE_ENABLE_STAT2
65530  if( pIdx->aSample ){
65531    int j;
65532    sqlite3 *dbMem = pIdx->pTable->dbMem;
65533    for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
65534      IndexSample *p = &pIdx->aSample[j];
65535      if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
65536        sqlite3DbFree(pIdx->pTable->dbMem, p->u.z);
65537      }
65538    }
65539    sqlite3DbFree(dbMem, pIdx->aSample);
65540    pIdx->aSample = 0;
65541  }
65542#else
65543  UNUSED_PARAMETER(pIdx);
65544#endif
65545}
65546
65547/*
65548** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
65549** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
65550** arrays. The contents of sqlite_stat2 are used to populate the
65551** Index.aSample[] arrays.
65552**
65553** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
65554** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
65555** during compilation and the sqlite_stat2 table is present, no data is
65556** read from it.
65557**
65558** If SQLITE_ENABLE_STAT2 was defined during compilation and the
65559** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
65560** returned. However, in this case, data is read from the sqlite_stat1
65561** table (if it is present) before returning.
65562**
65563** If an OOM error occurs, this function always sets db->mallocFailed.
65564** This means if the caller does not care about other errors, the return
65565** code may be ignored.
65566*/
65567SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
65568  analysisInfo sInfo;
65569  HashElem *i;
65570  char *zSql;
65571  int rc;
65572
65573  assert( iDb>=0 && iDb<db->nDb );
65574  assert( db->aDb[iDb].pBt!=0 );
65575  assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
65576
65577  /* Clear any prior statistics */
65578  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
65579    Index *pIdx = sqliteHashData(i);
65580    sqlite3DefaultRowEst(pIdx);
65581    sqlite3DeleteIndexSamples(pIdx);
65582  }
65583
65584  /* Check to make sure the sqlite_stat1 table exists */
65585  sInfo.db = db;
65586  sInfo.zDatabase = db->aDb[iDb].zName;
65587  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
65588    return SQLITE_ERROR;
65589  }
65590
65591  /* Load new statistics out of the sqlite_stat1 table */
65592  zSql = sqlite3MPrintf(db,
65593      "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
65594  if( zSql==0 ){
65595    rc = SQLITE_NOMEM;
65596  }else{
65597    rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
65598    sqlite3DbFree(db, zSql);
65599  }
65600
65601
65602  /* Load the statistics from the sqlite_stat2 table. */
65603#ifdef SQLITE_ENABLE_STAT2
65604  if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
65605    rc = SQLITE_ERROR;
65606  }
65607  if( rc==SQLITE_OK ){
65608    sqlite3_stmt *pStmt = 0;
65609
65610    zSql = sqlite3MPrintf(db,
65611        "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
65612    if( !zSql ){
65613      rc = SQLITE_NOMEM;
65614    }else{
65615      rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
65616      sqlite3DbFree(db, zSql);
65617    }
65618
65619    if( rc==SQLITE_OK ){
65620      while( sqlite3_step(pStmt)==SQLITE_ROW ){
65621        char *zIndex = (char *)sqlite3_column_text(pStmt, 0);
65622        Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
65623        if( pIdx ){
65624          int iSample = sqlite3_column_int(pStmt, 1);
65625          sqlite3 *dbMem = pIdx->pTable->dbMem;
65626          assert( dbMem==db || dbMem==0 );
65627          if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
65628            int eType = sqlite3_column_type(pStmt, 2);
65629
65630            if( pIdx->aSample==0 ){
65631              static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
65632              pIdx->aSample = (IndexSample *)sqlite3DbMallocZero(dbMem, sz);
65633              if( pIdx->aSample==0 ){
65634                db->mallocFailed = 1;
65635                break;
65636              }
65637            }
65638
65639            assert( pIdx->aSample );
65640            {
65641              IndexSample *pSample = &pIdx->aSample[iSample];
65642              pSample->eType = (u8)eType;
65643              if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
65644                pSample->u.r = sqlite3_column_double(pStmt, 2);
65645              }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
65646                const char *z = (const char *)(
65647                    (eType==SQLITE_BLOB) ?
65648                    sqlite3_column_blob(pStmt, 2):
65649                    sqlite3_column_text(pStmt, 2)
65650                );
65651                int n = sqlite3_column_bytes(pStmt, 2);
65652                if( n>24 ){
65653                  n = 24;
65654                }
65655                pSample->nByte = (u8)n;
65656                pSample->u.z = sqlite3DbMallocRaw(dbMem, n);
65657                if( pSample->u.z ){
65658                  memcpy(pSample->u.z, z, n);
65659                }else{
65660                  db->mallocFailed = 1;
65661                  break;
65662                }
65663              }
65664            }
65665          }
65666        }
65667      }
65668      rc = sqlite3_finalize(pStmt);
65669    }
65670  }
65671#endif
65672
65673  if( rc==SQLITE_NOMEM ){
65674    db->mallocFailed = 1;
65675  }
65676  return rc;
65677}
65678
65679
65680#endif /* SQLITE_OMIT_ANALYZE */
65681
65682/************** End of analyze.c *********************************************/
65683/************** Begin file attach.c ******************************************/
65684/*
65685** 2003 April 6
65686**
65687** The author disclaims copyright to this source code.  In place of
65688** a legal notice, here is a blessing:
65689**
65690**    May you do good and not evil.
65691**    May you find forgiveness for yourself and forgive others.
65692**    May you share freely, never taking more than you give.
65693**
65694*************************************************************************
65695** This file contains code used to implement the ATTACH and DETACH commands.
65696*/
65697
65698#ifndef SQLITE_OMIT_ATTACH
65699/*
65700** Resolve an expression that was part of an ATTACH or DETACH statement. This
65701** is slightly different from resolving a normal SQL expression, because simple
65702** identifiers are treated as strings, not possible column names or aliases.
65703**
65704** i.e. if the parser sees:
65705**
65706**     ATTACH DATABASE abc AS def
65707**
65708** it treats the two expressions as literal strings 'abc' and 'def' instead of
65709** looking for columns of the same name.
65710**
65711** This only applies to the root node of pExpr, so the statement:
65712**
65713**     ATTACH DATABASE abc||def AS 'db2'
65714**
65715** will fail because neither abc or def can be resolved.
65716*/
65717static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
65718{
65719  int rc = SQLITE_OK;
65720  if( pExpr ){
65721    if( pExpr->op!=TK_ID ){
65722      rc = sqlite3ResolveExprNames(pName, pExpr);
65723      if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
65724        sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
65725        return SQLITE_ERROR;
65726      }
65727    }else{
65728      pExpr->op = TK_STRING;
65729    }
65730  }
65731  return rc;
65732}
65733
65734/*
65735** An SQL user-function registered to do the work of an ATTACH statement. The
65736** three arguments to the function come directly from an attach statement:
65737**
65738**     ATTACH DATABASE x AS y KEY z
65739**
65740**     SELECT sqlite_attach(x, y, z)
65741**
65742** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
65743** third argument.
65744*/
65745static void attachFunc(
65746  sqlite3_context *context,
65747  int NotUsed,
65748  sqlite3_value **argv
65749){
65750  int i;
65751  int rc = 0;
65752  sqlite3 *db = sqlite3_context_db_handle(context);
65753  const char *zName;
65754  const char *zFile;
65755  Db *aNew;
65756  char *zErrDyn = 0;
65757
65758  UNUSED_PARAMETER(NotUsed);
65759
65760  zFile = (const char *)sqlite3_value_text(argv[0]);
65761  zName = (const char *)sqlite3_value_text(argv[1]);
65762  if( zFile==0 ) zFile = "";
65763  if( zName==0 ) zName = "";
65764
65765  /* Check for the following errors:
65766  **
65767  **     * Too many attached databases,
65768  **     * Transaction currently open
65769  **     * Specified database name already being used.
65770  */
65771  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
65772    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
65773      db->aLimit[SQLITE_LIMIT_ATTACHED]
65774    );
65775    goto attach_error;
65776  }
65777  if( !db->autoCommit ){
65778    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
65779    goto attach_error;
65780  }
65781  for(i=0; i<db->nDb; i++){
65782    char *z = db->aDb[i].zName;
65783    assert( z && zName );
65784    if( sqlite3StrICmp(z, zName)==0 ){
65785      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
65786      goto attach_error;
65787    }
65788  }
65789
65790  /* Allocate the new entry in the db->aDb[] array and initialise the schema
65791  ** hash tables.
65792  */
65793  if( db->aDb==db->aDbStatic ){
65794    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
65795    if( aNew==0 ) return;
65796    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
65797  }else{
65798    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
65799    if( aNew==0 ) return;
65800  }
65801  db->aDb = aNew;
65802  aNew = &db->aDb[db->nDb];
65803  memset(aNew, 0, sizeof(*aNew));
65804
65805  /* Open the database file. If the btree is successfully opened, use
65806  ** it to obtain the database schema. At this point the schema may
65807  ** or may not be initialised.
65808  */
65809  rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
65810                           db->openFlags | SQLITE_OPEN_MAIN_DB,
65811                           &aNew->pBt);
65812  db->nDb++;
65813  if( rc==SQLITE_CONSTRAINT ){
65814    rc = SQLITE_ERROR;
65815    zErrDyn = sqlite3MPrintf(db, "database is already attached");
65816  }else if( rc==SQLITE_OK ){
65817    Pager *pPager;
65818    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
65819    if( !aNew->pSchema ){
65820      rc = SQLITE_NOMEM;
65821    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
65822      zErrDyn = sqlite3MPrintf(db,
65823        "attached databases must use the same text encoding as main database");
65824      rc = SQLITE_ERROR;
65825    }
65826    pPager = sqlite3BtreePager(aNew->pBt);
65827    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
65828    sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
65829  }
65830  aNew->safety_level = 3;
65831  aNew->zName = sqlite3DbStrDup(db, zName);
65832  if( rc==SQLITE_OK && aNew->zName==0 ){
65833    rc = SQLITE_NOMEM;
65834  }
65835
65836
65837#if SQLITE_HAS_CODEC
65838  if( rc==SQLITE_OK ){
65839    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
65840    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
65841    int nKey;
65842    char *zKey;
65843    int t = sqlite3_value_type(argv[2]);
65844    switch( t ){
65845      case SQLITE_INTEGER:
65846      case SQLITE_FLOAT:
65847        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
65848        rc = SQLITE_ERROR;
65849        break;
65850
65851      case SQLITE_TEXT:
65852      case SQLITE_BLOB:
65853        nKey = sqlite3_value_bytes(argv[2]);
65854        zKey = (char *)sqlite3_value_blob(argv[2]);
65855        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
65856        break;
65857
65858      case SQLITE_NULL:
65859        /* No key specified.  Use the key from the main database */
65860        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
65861        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
65862        break;
65863    }
65864  }
65865#endif
65866
65867  /* If the file was opened successfully, read the schema for the new database.
65868  ** If this fails, or if opening the file failed, then close the file and
65869  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
65870  ** we found it.
65871  */
65872  if( rc==SQLITE_OK ){
65873    sqlite3BtreeEnterAll(db);
65874    rc = sqlite3Init(db, &zErrDyn);
65875    sqlite3BtreeLeaveAll(db);
65876  }
65877  if( rc ){
65878    int iDb = db->nDb - 1;
65879    assert( iDb>=2 );
65880    if( db->aDb[iDb].pBt ){
65881      sqlite3BtreeClose(db->aDb[iDb].pBt);
65882      db->aDb[iDb].pBt = 0;
65883      db->aDb[iDb].pSchema = 0;
65884    }
65885    sqlite3ResetInternalSchema(db, 0);
65886    db->nDb = iDb;
65887    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
65888      db->mallocFailed = 1;
65889      sqlite3DbFree(db, zErrDyn);
65890      zErrDyn = sqlite3MPrintf(db, "out of memory");
65891    }else if( zErrDyn==0 ){
65892      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
65893    }
65894    goto attach_error;
65895  }
65896
65897  return;
65898
65899attach_error:
65900  /* Return an error if we get here */
65901  if( zErrDyn ){
65902    sqlite3_result_error(context, zErrDyn, -1);
65903    sqlite3DbFree(db, zErrDyn);
65904  }
65905  if( rc ) sqlite3_result_error_code(context, rc);
65906}
65907
65908/*
65909** An SQL user-function registered to do the work of an DETACH statement. The
65910** three arguments to the function come directly from a detach statement:
65911**
65912**     DETACH DATABASE x
65913**
65914**     SELECT sqlite_detach(x)
65915*/
65916static void detachFunc(
65917  sqlite3_context *context,
65918  int NotUsed,
65919  sqlite3_value **argv
65920){
65921  const char *zName = (const char *)sqlite3_value_text(argv[0]);
65922  sqlite3 *db = sqlite3_context_db_handle(context);
65923  int i;
65924  Db *pDb = 0;
65925  char zErr[128];
65926
65927  UNUSED_PARAMETER(NotUsed);
65928
65929  if( zName==0 ) zName = "";
65930  for(i=0; i<db->nDb; i++){
65931    pDb = &db->aDb[i];
65932    if( pDb->pBt==0 ) continue;
65933    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
65934  }
65935
65936  if( i>=db->nDb ){
65937    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
65938    goto detach_error;
65939  }
65940  if( i<2 ){
65941    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
65942    goto detach_error;
65943  }
65944  if( !db->autoCommit ){
65945    sqlite3_snprintf(sizeof(zErr), zErr,
65946                     "cannot DETACH database within transaction");
65947    goto detach_error;
65948  }
65949  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
65950    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
65951    goto detach_error;
65952  }
65953
65954  sqlite3BtreeClose(pDb->pBt);
65955  pDb->pBt = 0;
65956  pDb->pSchema = 0;
65957  sqlite3ResetInternalSchema(db, 0);
65958  return;
65959
65960detach_error:
65961  sqlite3_result_error(context, zErr, -1);
65962}
65963
65964/*
65965** This procedure generates VDBE code for a single invocation of either the
65966** sqlite_detach() or sqlite_attach() SQL user functions.
65967*/
65968static void codeAttach(
65969  Parse *pParse,       /* The parser context */
65970  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
65971  FuncDef *pFunc,      /* FuncDef wrapper for detachFunc() or attachFunc() */
65972  Expr *pAuthArg,      /* Expression to pass to authorization callback */
65973  Expr *pFilename,     /* Name of database file */
65974  Expr *pDbname,       /* Name of the database to use internally */
65975  Expr *pKey           /* Database key for encryption extension */
65976){
65977  int rc;
65978  NameContext sName;
65979  Vdbe *v;
65980  sqlite3* db = pParse->db;
65981  int regArgs;
65982
65983  memset(&sName, 0, sizeof(NameContext));
65984  sName.pParse = pParse;
65985
65986  if(
65987      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
65988      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
65989      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
65990  ){
65991    pParse->nErr++;
65992    goto attach_end;
65993  }
65994
65995#ifndef SQLITE_OMIT_AUTHORIZATION
65996  if( pAuthArg ){
65997    char *zAuthArg = pAuthArg->u.zToken;
65998    if( NEVER(zAuthArg==0) ){
65999      goto attach_end;
66000    }
66001    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
66002    if(rc!=SQLITE_OK ){
66003      goto attach_end;
66004    }
66005  }
66006#endif /* SQLITE_OMIT_AUTHORIZATION */
66007
66008
66009  v = sqlite3GetVdbe(pParse);
66010  regArgs = sqlite3GetTempRange(pParse, 4);
66011  sqlite3ExprCode(pParse, pFilename, regArgs);
66012  sqlite3ExprCode(pParse, pDbname, regArgs+1);
66013  sqlite3ExprCode(pParse, pKey, regArgs+2);
66014
66015  assert( v || db->mallocFailed );
66016  if( v ){
66017    sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
66018    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
66019    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
66020    sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
66021
66022    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
66023    ** statement only). For DETACH, set it to false (expire all existing
66024    ** statements).
66025    */
66026    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
66027  }
66028
66029attach_end:
66030  sqlite3ExprDelete(db, pFilename);
66031  sqlite3ExprDelete(db, pDbname);
66032  sqlite3ExprDelete(db, pKey);
66033}
66034
66035/*
66036** Called by the parser to compile a DETACH statement.
66037**
66038**     DETACH pDbname
66039*/
66040SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
66041  static FuncDef detach_func = {
66042    1,                /* nArg */
66043    SQLITE_UTF8,      /* iPrefEnc */
66044    0,                /* flags */
66045    0,                /* pUserData */
66046    0,                /* pNext */
66047    detachFunc,       /* xFunc */
66048    0,                /* xStep */
66049    0,                /* xFinalize */
66050    "sqlite_detach",  /* zName */
66051    0                 /* pHash */
66052  };
66053  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
66054}
66055
66056/*
66057** Called by the parser to compile an ATTACH statement.
66058**
66059**     ATTACH p AS pDbname KEY pKey
66060*/
66061SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
66062  static FuncDef attach_func = {
66063    3,                /* nArg */
66064    SQLITE_UTF8,      /* iPrefEnc */
66065    0,                /* flags */
66066    0,                /* pUserData */
66067    0,                /* pNext */
66068    attachFunc,       /* xFunc */
66069    0,                /* xStep */
66070    0,                /* xFinalize */
66071    "sqlite_attach",  /* zName */
66072    0                 /* pHash */
66073  };
66074  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
66075}
66076#endif /* SQLITE_OMIT_ATTACH */
66077
66078/*
66079** Initialize a DbFixer structure.  This routine must be called prior
66080** to passing the structure to one of the sqliteFixAAAA() routines below.
66081**
66082** The return value indicates whether or not fixation is required.  TRUE
66083** means we do need to fix the database references, FALSE means we do not.
66084*/
66085SQLITE_PRIVATE int sqlite3FixInit(
66086  DbFixer *pFix,      /* The fixer to be initialized */
66087  Parse *pParse,      /* Error messages will be written here */
66088  int iDb,            /* This is the database that must be used */
66089  const char *zType,  /* "view", "trigger", or "index" */
66090  const Token *pName  /* Name of the view, trigger, or index */
66091){
66092  sqlite3 *db;
66093
66094  if( NEVER(iDb<0) || iDb==1 ) return 0;
66095  db = pParse->db;
66096  assert( db->nDb>iDb );
66097  pFix->pParse = pParse;
66098  pFix->zDb = db->aDb[iDb].zName;
66099  pFix->zType = zType;
66100  pFix->pName = pName;
66101  return 1;
66102}
66103
66104/*
66105** The following set of routines walk through the parse tree and assign
66106** a specific database to all table references where the database name
66107** was left unspecified in the original SQL statement.  The pFix structure
66108** must have been initialized by a prior call to sqlite3FixInit().
66109**
66110** These routines are used to make sure that an index, trigger, or
66111** view in one database does not refer to objects in a different database.
66112** (Exception: indices, triggers, and views in the TEMP database are
66113** allowed to refer to anything.)  If a reference is explicitly made
66114** to an object in a different database, an error message is added to
66115** pParse->zErrMsg and these routines return non-zero.  If everything
66116** checks out, these routines return 0.
66117*/
66118SQLITE_PRIVATE int sqlite3FixSrcList(
66119  DbFixer *pFix,       /* Context of the fixation */
66120  SrcList *pList       /* The Source list to check and modify */
66121){
66122  int i;
66123  const char *zDb;
66124  struct SrcList_item *pItem;
66125
66126  if( NEVER(pList==0) ) return 0;
66127  zDb = pFix->zDb;
66128  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
66129    if( pItem->zDatabase==0 ){
66130      pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
66131    }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
66132      sqlite3ErrorMsg(pFix->pParse,
66133         "%s %T cannot reference objects in database %s",
66134         pFix->zType, pFix->pName, pItem->zDatabase);
66135      return 1;
66136    }
66137#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
66138    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
66139    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
66140#endif
66141  }
66142  return 0;
66143}
66144#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
66145SQLITE_PRIVATE int sqlite3FixSelect(
66146  DbFixer *pFix,       /* Context of the fixation */
66147  Select *pSelect      /* The SELECT statement to be fixed to one database */
66148){
66149  while( pSelect ){
66150    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
66151      return 1;
66152    }
66153    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
66154      return 1;
66155    }
66156    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
66157      return 1;
66158    }
66159    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
66160      return 1;
66161    }
66162    pSelect = pSelect->pPrior;
66163  }
66164  return 0;
66165}
66166SQLITE_PRIVATE int sqlite3FixExpr(
66167  DbFixer *pFix,     /* Context of the fixation */
66168  Expr *pExpr        /* The expression to be fixed to one database */
66169){
66170  while( pExpr ){
66171    if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
66172    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
66173      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
66174    }else{
66175      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
66176    }
66177    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
66178      return 1;
66179    }
66180    pExpr = pExpr->pLeft;
66181  }
66182  return 0;
66183}
66184SQLITE_PRIVATE int sqlite3FixExprList(
66185  DbFixer *pFix,     /* Context of the fixation */
66186  ExprList *pList    /* The expression to be fixed to one database */
66187){
66188  int i;
66189  struct ExprList_item *pItem;
66190  if( pList==0 ) return 0;
66191  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
66192    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
66193      return 1;
66194    }
66195  }
66196  return 0;
66197}
66198#endif
66199
66200#ifndef SQLITE_OMIT_TRIGGER
66201SQLITE_PRIVATE int sqlite3FixTriggerStep(
66202  DbFixer *pFix,     /* Context of the fixation */
66203  TriggerStep *pStep /* The trigger step be fixed to one database */
66204){
66205  while( pStep ){
66206    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
66207      return 1;
66208    }
66209    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
66210      return 1;
66211    }
66212    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
66213      return 1;
66214    }
66215    pStep = pStep->pNext;
66216  }
66217  return 0;
66218}
66219#endif
66220
66221/************** End of attach.c **********************************************/
66222/************** Begin file auth.c ********************************************/
66223/*
66224** 2003 January 11
66225**
66226** The author disclaims copyright to this source code.  In place of
66227** a legal notice, here is a blessing:
66228**
66229**    May you do good and not evil.
66230**    May you find forgiveness for yourself and forgive others.
66231**    May you share freely, never taking more than you give.
66232**
66233*************************************************************************
66234** This file contains code used to implement the sqlite3_set_authorizer()
66235** API.  This facility is an optional feature of the library.  Embedded
66236** systems that do not need this facility may omit it by recompiling
66237** the library with -DSQLITE_OMIT_AUTHORIZATION=1
66238*/
66239
66240/*
66241** All of the code in this file may be omitted by defining a single
66242** macro.
66243*/
66244#ifndef SQLITE_OMIT_AUTHORIZATION
66245
66246/*
66247** Set or clear the access authorization function.
66248**
66249** The access authorization function is be called during the compilation
66250** phase to verify that the user has read and/or write access permission on
66251** various fields of the database.  The first argument to the auth function
66252** is a copy of the 3rd argument to this routine.  The second argument
66253** to the auth function is one of these constants:
66254**
66255**       SQLITE_CREATE_INDEX
66256**       SQLITE_CREATE_TABLE
66257**       SQLITE_CREATE_TEMP_INDEX
66258**       SQLITE_CREATE_TEMP_TABLE
66259**       SQLITE_CREATE_TEMP_TRIGGER
66260**       SQLITE_CREATE_TEMP_VIEW
66261**       SQLITE_CREATE_TRIGGER
66262**       SQLITE_CREATE_VIEW
66263**       SQLITE_DELETE
66264**       SQLITE_DROP_INDEX
66265**       SQLITE_DROP_TABLE
66266**       SQLITE_DROP_TEMP_INDEX
66267**       SQLITE_DROP_TEMP_TABLE
66268**       SQLITE_DROP_TEMP_TRIGGER
66269**       SQLITE_DROP_TEMP_VIEW
66270**       SQLITE_DROP_TRIGGER
66271**       SQLITE_DROP_VIEW
66272**       SQLITE_INSERT
66273**       SQLITE_PRAGMA
66274**       SQLITE_READ
66275**       SQLITE_SELECT
66276**       SQLITE_TRANSACTION
66277**       SQLITE_UPDATE
66278**
66279** The third and fourth arguments to the auth function are the name of
66280** the table and the column that are being accessed.  The auth function
66281** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
66282** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
66283** means that the SQL statement will never-run - the sqlite3_exec() call
66284** will return with an error.  SQLITE_IGNORE means that the SQL statement
66285** should run but attempts to read the specified column will return NULL
66286** and attempts to write the column will be ignored.
66287**
66288** Setting the auth function to NULL disables this hook.  The default
66289** setting of the auth function is NULL.
66290*/
66291SQLITE_API int sqlite3_set_authorizer(
66292  sqlite3 *db,
66293  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
66294  void *pArg
66295){
66296  sqlite3_mutex_enter(db->mutex);
66297  db->xAuth = xAuth;
66298  db->pAuthArg = pArg;
66299  sqlite3ExpirePreparedStatements(db);
66300  sqlite3_mutex_leave(db->mutex);
66301  return SQLITE_OK;
66302}
66303
66304/*
66305** Write an error message into pParse->zErrMsg that explains that the
66306** user-supplied authorization function returned an illegal value.
66307*/
66308static void sqliteAuthBadReturnCode(Parse *pParse){
66309  sqlite3ErrorMsg(pParse, "authorizer malfunction");
66310  pParse->rc = SQLITE_ERROR;
66311}
66312
66313/*
66314** Invoke the authorization callback for permission to read column zCol from
66315** table zTab in database zDb. This function assumes that an authorization
66316** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
66317**
66318** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
66319** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
66320** is treated as SQLITE_DENY. In this case an error is left in pParse.
66321*/
66322SQLITE_PRIVATE int sqlite3AuthReadCol(
66323  Parse *pParse,                  /* The parser context */
66324  const char *zTab,               /* Table name */
66325  const char *zCol,               /* Column name */
66326  int iDb                         /* Index of containing database. */
66327){
66328  sqlite3 *db = pParse->db;       /* Database handle */
66329  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
66330  int rc;                         /* Auth callback return code */
66331
66332  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
66333  if( rc==SQLITE_DENY ){
66334    if( db->nDb>2 || iDb!=0 ){
66335      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
66336    }else{
66337      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
66338    }
66339    pParse->rc = SQLITE_AUTH;
66340  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
66341    sqliteAuthBadReturnCode(pParse);
66342  }
66343  return rc;
66344}
66345
66346/*
66347** The pExpr should be a TK_COLUMN expression.  The table referred to
66348** is in pTabList or else it is the NEW or OLD table of a trigger.
66349** Check to see if it is OK to read this particular column.
66350**
66351** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
66352** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
66353** then generate an error.
66354*/
66355SQLITE_PRIVATE void sqlite3AuthRead(
66356  Parse *pParse,        /* The parser context */
66357  Expr *pExpr,          /* The expression to check authorization on */
66358  Schema *pSchema,      /* The schema of the expression */
66359  SrcList *pTabList     /* All table that pExpr might refer to */
66360){
66361  sqlite3 *db = pParse->db;
66362  Table *pTab = 0;      /* The table being read */
66363  const char *zCol;     /* Name of the column of the table */
66364  int iSrc;             /* Index in pTabList->a[] of table being read */
66365  int iDb;              /* The index of the database the expression refers to */
66366  int iCol;             /* Index of column in table */
66367
66368  if( db->xAuth==0 ) return;
66369  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
66370  if( iDb<0 ){
66371    /* An attempt to read a column out of a subquery or other
66372    ** temporary table. */
66373    return;
66374  }
66375
66376  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
66377  if( pExpr->op==TK_TRIGGER ){
66378    pTab = pParse->pTriggerTab;
66379  }else{
66380    assert( pTabList );
66381    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
66382      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
66383        pTab = pTabList->a[iSrc].pTab;
66384        break;
66385      }
66386    }
66387  }
66388  iCol = pExpr->iColumn;
66389  if( NEVER(pTab==0) ) return;
66390
66391  if( iCol>=0 ){
66392    assert( iCol<pTab->nCol );
66393    zCol = pTab->aCol[iCol].zName;
66394  }else if( pTab->iPKey>=0 ){
66395    assert( pTab->iPKey<pTab->nCol );
66396    zCol = pTab->aCol[pTab->iPKey].zName;
66397  }else{
66398    zCol = "ROWID";
66399  }
66400  assert( iDb>=0 && iDb<db->nDb );
66401  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
66402    pExpr->op = TK_NULL;
66403  }
66404}
66405
66406/*
66407** Do an authorization check using the code and arguments given.  Return
66408** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
66409** is returned, then the error count and error message in pParse are
66410** modified appropriately.
66411*/
66412SQLITE_PRIVATE int sqlite3AuthCheck(
66413  Parse *pParse,
66414  int code,
66415  const char *zArg1,
66416  const char *zArg2,
66417  const char *zArg3
66418){
66419  sqlite3 *db = pParse->db;
66420  int rc;
66421
66422  /* Don't do any authorization checks if the database is initialising
66423  ** or if the parser is being invoked from within sqlite3_declare_vtab.
66424  */
66425  if( db->init.busy || IN_DECLARE_VTAB ){
66426    return SQLITE_OK;
66427  }
66428
66429  if( db->xAuth==0 ){
66430    return SQLITE_OK;
66431  }
66432  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
66433  if( rc==SQLITE_DENY ){
66434    sqlite3ErrorMsg(pParse, "not authorized");
66435    pParse->rc = SQLITE_AUTH;
66436  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
66437    rc = SQLITE_DENY;
66438    sqliteAuthBadReturnCode(pParse);
66439  }
66440  return rc;
66441}
66442
66443/*
66444** Push an authorization context.  After this routine is called, the
66445** zArg3 argument to authorization callbacks will be zContext until
66446** popped.  Or if pParse==0, this routine is a no-op.
66447*/
66448SQLITE_PRIVATE void sqlite3AuthContextPush(
66449  Parse *pParse,
66450  AuthContext *pContext,
66451  const char *zContext
66452){
66453  assert( pParse );
66454  pContext->pParse = pParse;
66455  pContext->zAuthContext = pParse->zAuthContext;
66456  pParse->zAuthContext = zContext;
66457}
66458
66459/*
66460** Pop an authorization context that was previously pushed
66461** by sqlite3AuthContextPush
66462*/
66463SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
66464  if( pContext->pParse ){
66465    pContext->pParse->zAuthContext = pContext->zAuthContext;
66466    pContext->pParse = 0;
66467  }
66468}
66469
66470#endif /* SQLITE_OMIT_AUTHORIZATION */
66471
66472/************** End of auth.c ************************************************/
66473/************** Begin file build.c *******************************************/
66474/*
66475** 2001 September 15
66476**
66477** The author disclaims copyright to this source code.  In place of
66478** a legal notice, here is a blessing:
66479**
66480**    May you do good and not evil.
66481**    May you find forgiveness for yourself and forgive others.
66482**    May you share freely, never taking more than you give.
66483**
66484*************************************************************************
66485** This file contains C code routines that are called by the SQLite parser
66486** when syntax rules are reduced.  The routines in this file handle the
66487** following kinds of SQL syntax:
66488**
66489**     CREATE TABLE
66490**     DROP TABLE
66491**     CREATE INDEX
66492**     DROP INDEX
66493**     creating ID lists
66494**     BEGIN TRANSACTION
66495**     COMMIT
66496**     ROLLBACK
66497*/
66498
66499/*
66500** This routine is called when a new SQL statement is beginning to
66501** be parsed.  Initialize the pParse structure as needed.
66502*/
66503SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
66504  pParse->explain = (u8)explainFlag;
66505  pParse->nVar = 0;
66506}
66507
66508#ifndef SQLITE_OMIT_SHARED_CACHE
66509/*
66510** The TableLock structure is only used by the sqlite3TableLock() and
66511** codeTableLocks() functions.
66512*/
66513struct TableLock {
66514  int iDb;             /* The database containing the table to be locked */
66515  int iTab;            /* The root page of the table to be locked */
66516  u8 isWriteLock;      /* True for write lock.  False for a read lock */
66517  const char *zName;   /* Name of the table */
66518};
66519
66520/*
66521** Record the fact that we want to lock a table at run-time.
66522**
66523** The table to be locked has root page iTab and is found in database iDb.
66524** A read or a write lock can be taken depending on isWritelock.
66525**
66526** This routine just records the fact that the lock is desired.  The
66527** code to make the lock occur is generated by a later call to
66528** codeTableLocks() which occurs during sqlite3FinishCoding().
66529*/
66530SQLITE_PRIVATE void sqlite3TableLock(
66531  Parse *pParse,     /* Parsing context */
66532  int iDb,           /* Index of the database containing the table to lock */
66533  int iTab,          /* Root page number of the table to be locked */
66534  u8 isWriteLock,    /* True for a write lock */
66535  const char *zName  /* Name of the table to be locked */
66536){
66537  Parse *pToplevel = sqlite3ParseToplevel(pParse);
66538  int i;
66539  int nBytes;
66540  TableLock *p;
66541  assert( iDb>=0 );
66542
66543  for(i=0; i<pToplevel->nTableLock; i++){
66544    p = &pToplevel->aTableLock[i];
66545    if( p->iDb==iDb && p->iTab==iTab ){
66546      p->isWriteLock = (p->isWriteLock || isWriteLock);
66547      return;
66548    }
66549  }
66550
66551  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
66552  pToplevel->aTableLock =
66553      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
66554  if( pToplevel->aTableLock ){
66555    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
66556    p->iDb = iDb;
66557    p->iTab = iTab;
66558    p->isWriteLock = isWriteLock;
66559    p->zName = zName;
66560  }else{
66561    pToplevel->nTableLock = 0;
66562    pToplevel->db->mallocFailed = 1;
66563  }
66564}
66565
66566/*
66567** Code an OP_TableLock instruction for each table locked by the
66568** statement (configured by calls to sqlite3TableLock()).
66569*/
66570static void codeTableLocks(Parse *pParse){
66571  int i;
66572  Vdbe *pVdbe;
66573
66574  pVdbe = sqlite3GetVdbe(pParse);
66575  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
66576
66577  for(i=0; i<pParse->nTableLock; i++){
66578    TableLock *p = &pParse->aTableLock[i];
66579    int p1 = p->iDb;
66580    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
66581                      p->zName, P4_STATIC);
66582  }
66583}
66584#else
66585  #define codeTableLocks(x)
66586#endif
66587
66588/*
66589** This routine is called after a single SQL statement has been
66590** parsed and a VDBE program to execute that statement has been
66591** prepared.  This routine puts the finishing touches on the
66592** VDBE program and resets the pParse structure for the next
66593** parse.
66594**
66595** Note that if an error occurred, it might be the case that
66596** no VDBE code was generated.
66597*/
66598SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
66599  sqlite3 *db;
66600  Vdbe *v;
66601
66602  db = pParse->db;
66603  if( db->mallocFailed ) return;
66604  if( pParse->nested ) return;
66605  if( pParse->nErr ) return;
66606
66607  /* Begin by generating some termination code at the end of the
66608  ** vdbe program
66609  */
66610  v = sqlite3GetVdbe(pParse);
66611  assert( !pParse->isMultiWrite
66612       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
66613  if( v ){
66614    sqlite3VdbeAddOp0(v, OP_Halt);
66615
66616    /* The cookie mask contains one bit for each database file open.
66617    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
66618    ** set for each database that is used.  Generate code to start a
66619    ** transaction on each used database and to verify the schema cookie
66620    ** on each used database.
66621    */
66622    if( pParse->cookieGoto>0 ){
66623      u32 mask;
66624      int iDb;
66625      sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
66626      for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
66627        if( (mask & pParse->cookieMask)==0 ) continue;
66628        sqlite3VdbeUsesBtree(v, iDb);
66629        sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
66630        if( db->init.busy==0 ){
66631          sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
66632        }
66633      }
66634#ifndef SQLITE_OMIT_VIRTUALTABLE
66635      {
66636        int i;
66637        for(i=0; i<pParse->nVtabLock; i++){
66638          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
66639          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
66640        }
66641        pParse->nVtabLock = 0;
66642      }
66643#endif
66644
66645      /* Once all the cookies have been verified and transactions opened,
66646      ** obtain the required table-locks. This is a no-op unless the
66647      ** shared-cache feature is enabled.
66648      */
66649      codeTableLocks(pParse);
66650
66651      /* Initialize any AUTOINCREMENT data structures required.
66652      */
66653      sqlite3AutoincrementBegin(pParse);
66654
66655      /* Finally, jump back to the beginning of the executable code. */
66656      sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
66657    }
66658  }
66659
66660
66661  /* Get the VDBE program ready for execution
66662  */
66663  if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
66664#ifdef SQLITE_DEBUG
66665    FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
66666    sqlite3VdbeTrace(v, trace);
66667#endif
66668    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
66669    /* A minimum of one cursor is required if autoincrement is used
66670    *  See ticket [a696379c1f08866] */
66671    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
66672    sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
66673                         pParse->nTab, pParse->nMaxArg, pParse->explain,
66674                         pParse->isMultiWrite && pParse->mayAbort);
66675    pParse->rc = SQLITE_DONE;
66676    pParse->colNamesSet = 0;
66677  }else if( pParse->rc==SQLITE_OK ){
66678    pParse->rc = SQLITE_ERROR;
66679  }
66680  pParse->nTab = 0;
66681  pParse->nMem = 0;
66682  pParse->nSet = 0;
66683  pParse->nVar = 0;
66684  pParse->cookieMask = 0;
66685  pParse->cookieGoto = 0;
66686}
66687
66688/*
66689** Run the parser and code generator recursively in order to generate
66690** code for the SQL statement given onto the end of the pParse context
66691** currently under construction.  When the parser is run recursively
66692** this way, the final OP_Halt is not appended and other initialization
66693** and finalization steps are omitted because those are handling by the
66694** outermost parser.
66695**
66696** Not everything is nestable.  This facility is designed to permit
66697** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
66698** care if you decide to try to use this routine for some other purposes.
66699*/
66700SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
66701  va_list ap;
66702  char *zSql;
66703  char *zErrMsg = 0;
66704  sqlite3 *db = pParse->db;
66705# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
66706  char saveBuf[SAVE_SZ];
66707
66708  if( pParse->nErr ) return;
66709  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
66710  va_start(ap, zFormat);
66711  zSql = sqlite3VMPrintf(db, zFormat, ap);
66712  va_end(ap);
66713  if( zSql==0 ){
66714    return;   /* A malloc must have failed */
66715  }
66716  pParse->nested++;
66717  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
66718  memset(&pParse->nVar, 0, SAVE_SZ);
66719  sqlite3RunParser(pParse, zSql, &zErrMsg);
66720  sqlite3DbFree(db, zErrMsg);
66721  sqlite3DbFree(db, zSql);
66722  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
66723  pParse->nested--;
66724}
66725
66726/*
66727** Locate the in-memory structure that describes a particular database
66728** table given the name of that table and (optionally) the name of the
66729** database containing the table.  Return NULL if not found.
66730**
66731** If zDatabase is 0, all databases are searched for the table and the
66732** first matching table is returned.  (No checking for duplicate table
66733** names is done.)  The search order is TEMP first, then MAIN, then any
66734** auxiliary databases added using the ATTACH command.
66735**
66736** See also sqlite3LocateTable().
66737*/
66738SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
66739  Table *p = 0;
66740  int i;
66741  int nName;
66742  assert( zName!=0 );
66743  nName = sqlite3Strlen30(zName);
66744  for(i=OMIT_TEMPDB; i<db->nDb; i++){
66745    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
66746    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
66747    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
66748    if( p ) break;
66749  }
66750  return p;
66751}
66752
66753/*
66754** Locate the in-memory structure that describes a particular database
66755** table given the name of that table and (optionally) the name of the
66756** database containing the table.  Return NULL if not found.  Also leave an
66757** error message in pParse->zErrMsg.
66758**
66759** The difference between this routine and sqlite3FindTable() is that this
66760** routine leaves an error message in pParse->zErrMsg where
66761** sqlite3FindTable() does not.
66762*/
66763SQLITE_PRIVATE Table *sqlite3LocateTable(
66764  Parse *pParse,         /* context in which to report errors */
66765  int isView,            /* True if looking for a VIEW rather than a TABLE */
66766  const char *zName,     /* Name of the table we are looking for */
66767  const char *zDbase     /* Name of the database.  Might be NULL */
66768){
66769  Table *p;
66770
66771  /* Read the database schema. If an error occurs, leave an error message
66772  ** and code in pParse and return NULL. */
66773  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
66774    return 0;
66775  }
66776
66777  p = sqlite3FindTable(pParse->db, zName, zDbase);
66778  if( p==0 ){
66779    const char *zMsg = isView ? "no such view" : "no such table";
66780    if( zDbase ){
66781      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
66782    }else{
66783      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
66784    }
66785    pParse->checkSchema = 1;
66786  }
66787  return p;
66788}
66789
66790/*
66791** Locate the in-memory structure that describes
66792** a particular index given the name of that index
66793** and the name of the database that contains the index.
66794** Return NULL if not found.
66795**
66796** If zDatabase is 0, all databases are searched for the
66797** table and the first matching index is returned.  (No checking
66798** for duplicate index names is done.)  The search order is
66799** TEMP first, then MAIN, then any auxiliary databases added
66800** using the ATTACH command.
66801*/
66802SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
66803  Index *p = 0;
66804  int i;
66805  int nName = sqlite3Strlen30(zName);
66806  for(i=OMIT_TEMPDB; i<db->nDb; i++){
66807    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
66808    Schema *pSchema = db->aDb[j].pSchema;
66809    assert( pSchema );
66810    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
66811    p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
66812    if( p ) break;
66813  }
66814  return p;
66815}
66816
66817/*
66818** Reclaim the memory used by an index
66819*/
66820static void freeIndex(Index *p){
66821  sqlite3 *db = p->pTable->dbMem;
66822#ifndef SQLITE_OMIT_ANALYZE
66823  sqlite3DeleteIndexSamples(p);
66824#endif
66825  sqlite3DbFree(db, p->zColAff);
66826  sqlite3DbFree(db, p);
66827}
66828
66829/*
66830** Remove the given index from the index hash table, and free
66831** its memory structures.
66832**
66833** The index is removed from the database hash tables but
66834** it is not unlinked from the Table that it indexes.
66835** Unlinking from the Table must be done by the calling function.
66836*/
66837static void sqlite3DeleteIndex(Index *p){
66838  Index *pOld;
66839  const char *zName = p->zName;
66840
66841  pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
66842                           sqlite3Strlen30(zName), 0);
66843  assert( pOld==0 || pOld==p );
66844  freeIndex(p);
66845}
66846
66847/*
66848** For the index called zIdxName which is found in the database iDb,
66849** unlike that index from its Table then remove the index from
66850** the index hash table and free all memory structures associated
66851** with the index.
66852*/
66853SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
66854  Index *pIndex;
66855  int len;
66856  Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
66857
66858  len = sqlite3Strlen30(zIdxName);
66859  pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
66860  if( pIndex ){
66861    if( pIndex->pTable->pIndex==pIndex ){
66862      pIndex->pTable->pIndex = pIndex->pNext;
66863    }else{
66864      Index *p;
66865      /* Justification of ALWAYS();  The index must be on the list of
66866      ** indices. */
66867      p = pIndex->pTable->pIndex;
66868      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
66869      if( ALWAYS(p && p->pNext==pIndex) ){
66870        p->pNext = pIndex->pNext;
66871      }
66872    }
66873    freeIndex(pIndex);
66874  }
66875  db->flags |= SQLITE_InternChanges;
66876}
66877
66878/*
66879** Erase all schema information from the in-memory hash tables of
66880** a single database.  This routine is called to reclaim memory
66881** before the database closes.  It is also called during a rollback
66882** if there were schema changes during the transaction or if a
66883** schema-cookie mismatch occurs.
66884**
66885** If iDb==0 then reset the internal schema tables for all database
66886** files.  If iDb>=1 then reset the internal schema for only the
66887** single file indicated.
66888*/
66889SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
66890  int i, j;
66891  assert( iDb>=0 && iDb<db->nDb );
66892
66893  if( iDb==0 ){
66894    sqlite3BtreeEnterAll(db);
66895  }
66896  for(i=iDb; i<db->nDb; i++){
66897    Db *pDb = &db->aDb[i];
66898    if( pDb->pSchema ){
66899      assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
66900      sqlite3SchemaFree(pDb->pSchema);
66901    }
66902    if( iDb>0 ) return;
66903  }
66904  assert( iDb==0 );
66905  db->flags &= ~SQLITE_InternChanges;
66906  sqlite3VtabUnlockList(db);
66907  sqlite3BtreeLeaveAll(db);
66908
66909  /* If one or more of the auxiliary database files has been closed,
66910  ** then remove them from the auxiliary database list.  We take the
66911  ** opportunity to do this here since we have just deleted all of the
66912  ** schema hash tables and therefore do not have to make any changes
66913  ** to any of those tables.
66914  */
66915  for(i=j=2; i<db->nDb; i++){
66916    struct Db *pDb = &db->aDb[i];
66917    if( pDb->pBt==0 ){
66918      sqlite3DbFree(db, pDb->zName);
66919      pDb->zName = 0;
66920      continue;
66921    }
66922    if( j<i ){
66923      db->aDb[j] = db->aDb[i];
66924    }
66925    j++;
66926  }
66927  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
66928  db->nDb = j;
66929  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
66930    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
66931    sqlite3DbFree(db, db->aDb);
66932    db->aDb = db->aDbStatic;
66933  }
66934}
66935
66936/*
66937** This routine is called when a commit occurs.
66938*/
66939SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
66940  db->flags &= ~SQLITE_InternChanges;
66941}
66942
66943/*
66944** Clear the column names from a table or view.
66945*/
66946static void sqliteResetColumnNames(Table *pTable){
66947  int i;
66948  Column *pCol;
66949  sqlite3 *db = pTable->dbMem;
66950  testcase( db==0 );
66951  assert( pTable!=0 );
66952  if( (pCol = pTable->aCol)!=0 ){
66953    for(i=0; i<pTable->nCol; i++, pCol++){
66954      sqlite3DbFree(db, pCol->zName);
66955      sqlite3ExprDelete(db, pCol->pDflt);
66956      sqlite3DbFree(db, pCol->zDflt);
66957      sqlite3DbFree(db, pCol->zType);
66958      sqlite3DbFree(db, pCol->zColl);
66959    }
66960    sqlite3DbFree(db, pTable->aCol);
66961  }
66962  pTable->aCol = 0;
66963  pTable->nCol = 0;
66964}
66965
66966/*
66967** Remove the memory data structures associated with the given
66968** Table.  No changes are made to disk by this routine.
66969**
66970** This routine just deletes the data structure.  It does not unlink
66971** the table data structure from the hash table.  But it does destroy
66972** memory structures of the indices and foreign keys associated with
66973** the table.
66974*/
66975SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
66976  Index *pIndex, *pNext;
66977  sqlite3 *db;
66978
66979  if( pTable==0 ) return;
66980  db = pTable->dbMem;
66981  testcase( db==0 );
66982
66983  /* Do not delete the table until the reference count reaches zero. */
66984  pTable->nRef--;
66985  if( pTable->nRef>0 ){
66986    return;
66987  }
66988  assert( pTable->nRef==0 );
66989
66990  /* Delete all indices associated with this table
66991  */
66992  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
66993    pNext = pIndex->pNext;
66994    assert( pIndex->pSchema==pTable->pSchema );
66995    sqlite3DeleteIndex(pIndex);
66996  }
66997
66998  /* Delete any foreign keys attached to this table. */
66999  sqlite3FkDelete(pTable);
67000
67001  /* Delete the Table structure itself.
67002  */
67003  sqliteResetColumnNames(pTable);
67004  sqlite3DbFree(db, pTable->zName);
67005  sqlite3DbFree(db, pTable->zColAff);
67006  sqlite3SelectDelete(db, pTable->pSelect);
67007#ifndef SQLITE_OMIT_CHECK
67008  sqlite3ExprDelete(db, pTable->pCheck);
67009#endif
67010  sqlite3VtabClear(pTable);
67011  sqlite3DbFree(db, pTable);
67012}
67013
67014/*
67015** Unlink the given table from the hash tables and the delete the
67016** table structure with all its indices and foreign keys.
67017*/
67018SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
67019  Table *p;
67020  Db *pDb;
67021
67022  assert( db!=0 );
67023  assert( iDb>=0 && iDb<db->nDb );
67024  assert( zTabName );
67025  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
67026  pDb = &db->aDb[iDb];
67027  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
67028                        sqlite3Strlen30(zTabName),0);
67029  sqlite3DeleteTable(p);
67030  db->flags |= SQLITE_InternChanges;
67031}
67032
67033/*
67034** Given a token, return a string that consists of the text of that
67035** token.  Space to hold the returned string
67036** is obtained from sqliteMalloc() and must be freed by the calling
67037** function.
67038**
67039** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
67040** surround the body of the token are removed.
67041**
67042** Tokens are often just pointers into the original SQL text and so
67043** are not \000 terminated and are not persistent.  The returned string
67044** is \000 terminated and is persistent.
67045*/
67046SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
67047  char *zName;
67048  if( pName ){
67049    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
67050    sqlite3Dequote(zName);
67051  }else{
67052    zName = 0;
67053  }
67054  return zName;
67055}
67056
67057/*
67058** Open the sqlite_master table stored in database number iDb for
67059** writing. The table is opened using cursor 0.
67060*/
67061SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
67062  Vdbe *v = sqlite3GetVdbe(p);
67063  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
67064  sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
67065  sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
67066  if( p->nTab==0 ){
67067    p->nTab = 1;
67068  }
67069}
67070
67071/*
67072** Parameter zName points to a nul-terminated buffer containing the name
67073** of a database ("main", "temp" or the name of an attached db). This
67074** function returns the index of the named database in db->aDb[], or
67075** -1 if the named db cannot be found.
67076*/
67077SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
67078  int i = -1;         /* Database number */
67079  if( zName ){
67080    Db *pDb;
67081    int n = sqlite3Strlen30(zName);
67082    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
67083      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
67084          0==sqlite3StrICmp(pDb->zName, zName) ){
67085        break;
67086      }
67087    }
67088  }
67089  return i;
67090}
67091
67092/*
67093** The token *pName contains the name of a database (either "main" or
67094** "temp" or the name of an attached db). This routine returns the
67095** index of the named database in db->aDb[], or -1 if the named db
67096** does not exist.
67097*/
67098SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
67099  int i;                               /* Database number */
67100  char *zName;                         /* Name we are searching for */
67101  zName = sqlite3NameFromToken(db, pName);
67102  i = sqlite3FindDbName(db, zName);
67103  sqlite3DbFree(db, zName);
67104  return i;
67105}
67106
67107/* The table or view or trigger name is passed to this routine via tokens
67108** pName1 and pName2. If the table name was fully qualified, for example:
67109**
67110** CREATE TABLE xxx.yyy (...);
67111**
67112** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
67113** the table name is not fully qualified, i.e.:
67114**
67115** CREATE TABLE yyy(...);
67116**
67117** Then pName1 is set to "yyy" and pName2 is "".
67118**
67119** This routine sets the *ppUnqual pointer to point at the token (pName1 or
67120** pName2) that stores the unqualified table name.  The index of the
67121** database "xxx" is returned.
67122*/
67123SQLITE_PRIVATE int sqlite3TwoPartName(
67124  Parse *pParse,      /* Parsing and code generating context */
67125  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
67126  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
67127  Token **pUnqual     /* Write the unqualified object name here */
67128){
67129  int iDb;                    /* Database holding the object */
67130  sqlite3 *db = pParse->db;
67131
67132  if( ALWAYS(pName2!=0) && pName2->n>0 ){
67133    if( db->init.busy ) {
67134      sqlite3ErrorMsg(pParse, "corrupt database");
67135      pParse->nErr++;
67136      return -1;
67137    }
67138    *pUnqual = pName2;
67139    iDb = sqlite3FindDb(db, pName1);
67140    if( iDb<0 ){
67141      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
67142      pParse->nErr++;
67143      return -1;
67144    }
67145  }else{
67146    assert( db->init.iDb==0 || db->init.busy );
67147    iDb = db->init.iDb;
67148    *pUnqual = pName1;
67149  }
67150  return iDb;
67151}
67152
67153/*
67154** This routine is used to check if the UTF-8 string zName is a legal
67155** unqualified name for a new schema object (table, index, view or
67156** trigger). All names are legal except those that begin with the string
67157** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
67158** is reserved for internal use.
67159*/
67160SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
67161  if( !pParse->db->init.busy && pParse->nested==0
67162          && (pParse->db->flags & SQLITE_WriteSchema)==0
67163          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
67164    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
67165    return SQLITE_ERROR;
67166  }
67167  return SQLITE_OK;
67168}
67169
67170/*
67171** Begin constructing a new table representation in memory.  This is
67172** the first of several action routines that get called in response
67173** to a CREATE TABLE statement.  In particular, this routine is called
67174** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
67175** flag is true if the table should be stored in the auxiliary database
67176** file instead of in the main database file.  This is normally the case
67177** when the "TEMP" or "TEMPORARY" keyword occurs in between
67178** CREATE and TABLE.
67179**
67180** The new table record is initialized and put in pParse->pNewTable.
67181** As more of the CREATE TABLE statement is parsed, additional action
67182** routines will be called to add more information to this record.
67183** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
67184** is called to complete the construction of the new table record.
67185*/
67186SQLITE_PRIVATE void sqlite3StartTable(
67187  Parse *pParse,   /* Parser context */
67188  Token *pName1,   /* First part of the name of the table or view */
67189  Token *pName2,   /* Second part of the name of the table or view */
67190  int isTemp,      /* True if this is a TEMP table */
67191  int isView,      /* True if this is a VIEW */
67192  int isVirtual,   /* True if this is a VIRTUAL table */
67193  int noErr        /* Do nothing if table already exists */
67194){
67195  Table *pTable;
67196  char *zName = 0; /* The name of the new table */
67197  sqlite3 *db = pParse->db;
67198  Vdbe *v;
67199  int iDb;         /* Database number to create the table in */
67200  Token *pName;    /* Unqualified name of the table to create */
67201
67202  /* The table or view name to create is passed to this routine via tokens
67203  ** pName1 and pName2. If the table name was fully qualified, for example:
67204  **
67205  ** CREATE TABLE xxx.yyy (...);
67206  **
67207  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
67208  ** the table name is not fully qualified, i.e.:
67209  **
67210  ** CREATE TABLE yyy(...);
67211  **
67212  ** Then pName1 is set to "yyy" and pName2 is "".
67213  **
67214  ** The call below sets the pName pointer to point at the token (pName1 or
67215  ** pName2) that stores the unqualified table name. The variable iDb is
67216  ** set to the index of the database that the table or view is to be
67217  ** created in.
67218  */
67219  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
67220  if( iDb<0 ) return;
67221  if( !OMIT_TEMPDB && isTemp && iDb>1 ){
67222    /* If creating a temp table, the name may not be qualified */
67223    sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
67224    return;
67225  }
67226  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
67227
67228  pParse->sNameToken = *pName;
67229  zName = sqlite3NameFromToken(db, pName);
67230  if( zName==0 ) return;
67231  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
67232    goto begin_table_error;
67233  }
67234  if( db->init.iDb==1 ) isTemp = 1;
67235#ifndef SQLITE_OMIT_AUTHORIZATION
67236  assert( (isTemp & 1)==isTemp );
67237  {
67238    int code;
67239    char *zDb = db->aDb[iDb].zName;
67240    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
67241      goto begin_table_error;
67242    }
67243    if( isView ){
67244      if( !OMIT_TEMPDB && isTemp ){
67245        code = SQLITE_CREATE_TEMP_VIEW;
67246      }else{
67247        code = SQLITE_CREATE_VIEW;
67248      }
67249    }else{
67250      if( !OMIT_TEMPDB && isTemp ){
67251        code = SQLITE_CREATE_TEMP_TABLE;
67252      }else{
67253        code = SQLITE_CREATE_TABLE;
67254      }
67255    }
67256    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
67257      goto begin_table_error;
67258    }
67259  }
67260#endif
67261
67262  /* Make sure the new table name does not collide with an existing
67263  ** index or table name in the same database.  Issue an error message if
67264  ** it does. The exception is if the statement being parsed was passed
67265  ** to an sqlite3_declare_vtab() call. In that case only the column names
67266  ** and types will be used, so there is no need to test for namespace
67267  ** collisions.
67268  */
67269  if( !IN_DECLARE_VTAB ){
67270    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
67271      goto begin_table_error;
67272    }
67273    pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
67274    if( pTable ){
67275      if( !noErr ){
67276        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
67277      }
67278      goto begin_table_error;
67279    }
67280    if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
67281      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
67282      goto begin_table_error;
67283    }
67284  }
67285
67286  pTable = sqlite3DbMallocZero(db, sizeof(Table));
67287  if( pTable==0 ){
67288    db->mallocFailed = 1;
67289    pParse->rc = SQLITE_NOMEM;
67290    pParse->nErr++;
67291    goto begin_table_error;
67292  }
67293  pTable->zName = zName;
67294  pTable->iPKey = -1;
67295  pTable->pSchema = db->aDb[iDb].pSchema;
67296  pTable->nRef = 1;
67297  pTable->dbMem = 0;
67298  assert( pParse->pNewTable==0 );
67299  pParse->pNewTable = pTable;
67300
67301  /* If this is the magic sqlite_sequence table used by autoincrement,
67302  ** then record a pointer to this table in the main database structure
67303  ** so that INSERT can find the table easily.
67304  */
67305#ifndef SQLITE_OMIT_AUTOINCREMENT
67306  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
67307    pTable->pSchema->pSeqTab = pTable;
67308  }
67309#endif
67310
67311  /* Begin generating the code that will insert the table record into
67312  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
67313  ** and allocate the record number for the table entry now.  Before any
67314  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
67315  ** indices to be created and the table record must come before the
67316  ** indices.  Hence, the record number for the table must be allocated
67317  ** now.
67318  */
67319  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
67320    int j1;
67321    int fileFormat;
67322    int reg1, reg2, reg3;
67323    sqlite3BeginWriteOperation(pParse, 0, iDb);
67324
67325#ifndef SQLITE_OMIT_VIRTUALTABLE
67326    if( isVirtual ){
67327      sqlite3VdbeAddOp0(v, OP_VBegin);
67328    }
67329#endif
67330
67331    /* If the file format and encoding in the database have not been set,
67332    ** set them now.
67333    */
67334    reg1 = pParse->regRowid = ++pParse->nMem;
67335    reg2 = pParse->regRoot = ++pParse->nMem;
67336    reg3 = ++pParse->nMem;
67337    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
67338    sqlite3VdbeUsesBtree(v, iDb);
67339    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
67340    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
67341                  1 : SQLITE_MAX_FILE_FORMAT;
67342    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
67343    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
67344    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
67345    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
67346    sqlite3VdbeJumpHere(v, j1);
67347
67348    /* This just creates a place-holder record in the sqlite_master table.
67349    ** The record created does not contain anything yet.  It will be replaced
67350    ** by the real entry in code generated at sqlite3EndTable().
67351    **
67352    ** The rowid for the new entry is left in register pParse->regRowid.
67353    ** The root page number of the new table is left in reg pParse->regRoot.
67354    ** The rowid and root page number values are needed by the code that
67355    ** sqlite3EndTable will generate.
67356    */
67357#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
67358    if( isView || isVirtual ){
67359      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
67360    }else
67361#endif
67362    {
67363      sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
67364    }
67365    sqlite3OpenMasterTable(pParse, iDb);
67366    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
67367    sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
67368    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
67369    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
67370    sqlite3VdbeAddOp0(v, OP_Close);
67371  }
67372
67373  /* Normal (non-error) return. */
67374  return;
67375
67376  /* If an error occurs, we jump here */
67377begin_table_error:
67378  sqlite3DbFree(db, zName);
67379  return;
67380}
67381
67382/*
67383** This macro is used to compare two strings in a case-insensitive manner.
67384** It is slightly faster than calling sqlite3StrICmp() directly, but
67385** produces larger code.
67386**
67387** WARNING: This macro is not compatible with the strcmp() family. It
67388** returns true if the two strings are equal, otherwise false.
67389*/
67390#define STRICMP(x, y) (\
67391sqlite3UpperToLower[*(unsigned char *)(x)]==   \
67392sqlite3UpperToLower[*(unsigned char *)(y)]     \
67393&& sqlite3StrICmp((x)+1,(y)+1)==0 )
67394
67395/*
67396** Add a new column to the table currently being constructed.
67397**
67398** The parser calls this routine once for each column declaration
67399** in a CREATE TABLE statement.  sqlite3StartTable() gets called
67400** first to get things going.  Then this routine is called for each
67401** column.
67402*/
67403SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
67404  Table *p;
67405  int i;
67406  char *z;
67407  Column *pCol;
67408  sqlite3 *db = pParse->db;
67409  if( (p = pParse->pNewTable)==0 ) return;
67410#if SQLITE_MAX_COLUMN
67411  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
67412    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
67413    return;
67414  }
67415#endif
67416  z = sqlite3NameFromToken(db, pName);
67417  if( z==0 ) return;
67418  for(i=0; i<p->nCol; i++){
67419    if( STRICMP(z, p->aCol[i].zName) ){
67420      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
67421      sqlite3DbFree(db, z);
67422      return;
67423    }
67424  }
67425  if( (p->nCol & 0x7)==0 ){
67426    Column *aNew;
67427    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
67428    if( aNew==0 ){
67429      sqlite3DbFree(db, z);
67430      return;
67431    }
67432    p->aCol = aNew;
67433  }
67434  pCol = &p->aCol[p->nCol];
67435  memset(pCol, 0, sizeof(p->aCol[0]));
67436  pCol->zName = z;
67437
67438  /* If there is no type specified, columns have the default affinity
67439  ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
67440  ** be called next to set pCol->affinity correctly.
67441  */
67442  pCol->affinity = SQLITE_AFF_NONE;
67443  p->nCol++;
67444}
67445
67446/*
67447** This routine is called by the parser while in the middle of
67448** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
67449** been seen on a column.  This routine sets the notNull flag on
67450** the column currently under construction.
67451*/
67452SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
67453  Table *p;
67454  p = pParse->pNewTable;
67455  if( p==0 || NEVER(p->nCol<1) ) return;
67456  p->aCol[p->nCol-1].notNull = (u8)onError;
67457}
67458
67459/*
67460** Scan the column type name zType (length nType) and return the
67461** associated affinity type.
67462**
67463** This routine does a case-independent search of zType for the
67464** substrings in the following table. If one of the substrings is
67465** found, the corresponding affinity is returned. If zType contains
67466** more than one of the substrings, entries toward the top of
67467** the table take priority. For example, if zType is 'BLOBINT',
67468** SQLITE_AFF_INTEGER is returned.
67469**
67470** Substring     | Affinity
67471** --------------------------------
67472** 'INT'         | SQLITE_AFF_INTEGER
67473** 'CHAR'        | SQLITE_AFF_TEXT
67474** 'CLOB'        | SQLITE_AFF_TEXT
67475** 'TEXT'        | SQLITE_AFF_TEXT
67476** 'BLOB'        | SQLITE_AFF_NONE
67477** 'REAL'        | SQLITE_AFF_REAL
67478** 'FLOA'        | SQLITE_AFF_REAL
67479** 'DOUB'        | SQLITE_AFF_REAL
67480**
67481** If none of the substrings in the above table are found,
67482** SQLITE_AFF_NUMERIC is returned.
67483*/
67484SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
67485  u32 h = 0;
67486  char aff = SQLITE_AFF_NUMERIC;
67487
67488  if( zIn ) while( zIn[0] ){
67489    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
67490    zIn++;
67491    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
67492      aff = SQLITE_AFF_TEXT;
67493    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
67494      aff = SQLITE_AFF_TEXT;
67495    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
67496      aff = SQLITE_AFF_TEXT;
67497    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
67498        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
67499      aff = SQLITE_AFF_NONE;
67500#ifndef SQLITE_OMIT_FLOATING_POINT
67501    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
67502        && aff==SQLITE_AFF_NUMERIC ){
67503      aff = SQLITE_AFF_REAL;
67504    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
67505        && aff==SQLITE_AFF_NUMERIC ){
67506      aff = SQLITE_AFF_REAL;
67507    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
67508        && aff==SQLITE_AFF_NUMERIC ){
67509      aff = SQLITE_AFF_REAL;
67510#endif
67511    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
67512      aff = SQLITE_AFF_INTEGER;
67513      break;
67514    }
67515  }
67516
67517  return aff;
67518}
67519
67520/*
67521** This routine is called by the parser while in the middle of
67522** parsing a CREATE TABLE statement.  The pFirst token is the first
67523** token in the sequence of tokens that describe the type of the
67524** column currently under construction.   pLast is the last token
67525** in the sequence.  Use this information to construct a string
67526** that contains the typename of the column and store that string
67527** in zType.
67528*/
67529SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
67530  Table *p;
67531  Column *pCol;
67532
67533  p = pParse->pNewTable;
67534  if( p==0 || NEVER(p->nCol<1) ) return;
67535  pCol = &p->aCol[p->nCol-1];
67536  assert( pCol->zType==0 );
67537  pCol->zType = sqlite3NameFromToken(pParse->db, pType);
67538  pCol->affinity = sqlite3AffinityType(pCol->zType);
67539}
67540
67541/*
67542** The expression is the default value for the most recently added column
67543** of the table currently under construction.
67544**
67545** Default value expressions must be constant.  Raise an exception if this
67546** is not the case.
67547**
67548** This routine is called by the parser while in the middle of
67549** parsing a CREATE TABLE statement.
67550*/
67551SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
67552  Table *p;
67553  Column *pCol;
67554  sqlite3 *db = pParse->db;
67555  p = pParse->pNewTable;
67556  if( p!=0 ){
67557    pCol = &(p->aCol[p->nCol-1]);
67558    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
67559      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
67560          pCol->zName);
67561    }else{
67562      /* A copy of pExpr is used instead of the original, as pExpr contains
67563      ** tokens that point to volatile memory. The 'span' of the expression
67564      ** is required by pragma table_info.
67565      */
67566      sqlite3ExprDelete(db, pCol->pDflt);
67567      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
67568      sqlite3DbFree(db, pCol->zDflt);
67569      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
67570                                     (int)(pSpan->zEnd - pSpan->zStart));
67571    }
67572  }
67573  sqlite3ExprDelete(db, pSpan->pExpr);
67574}
67575
67576/*
67577** Designate the PRIMARY KEY for the table.  pList is a list of names
67578** of columns that form the primary key.  If pList is NULL, then the
67579** most recently added column of the table is the primary key.
67580**
67581** A table can have at most one primary key.  If the table already has
67582** a primary key (and this is the second primary key) then create an
67583** error.
67584**
67585** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
67586** then we will try to use that column as the rowid.  Set the Table.iPKey
67587** field of the table under construction to be the index of the
67588** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
67589** no INTEGER PRIMARY KEY.
67590**
67591** If the key is not an INTEGER PRIMARY KEY, then create a unique
67592** index for the key.  No index is created for INTEGER PRIMARY KEYs.
67593*/
67594SQLITE_PRIVATE void sqlite3AddPrimaryKey(
67595  Parse *pParse,    /* Parsing context */
67596  ExprList *pList,  /* List of field names to be indexed */
67597  int onError,      /* What to do with a uniqueness conflict */
67598  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
67599  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
67600){
67601  Table *pTab = pParse->pNewTable;
67602  char *zType = 0;
67603  int iCol = -1, i;
67604  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
67605  if( pTab->tabFlags & TF_HasPrimaryKey ){
67606    sqlite3ErrorMsg(pParse,
67607      "table \"%s\" has more than one primary key", pTab->zName);
67608    goto primary_key_exit;
67609  }
67610  pTab->tabFlags |= TF_HasPrimaryKey;
67611  if( pList==0 ){
67612    iCol = pTab->nCol - 1;
67613    pTab->aCol[iCol].isPrimKey = 1;
67614  }else{
67615    for(i=0; i<pList->nExpr; i++){
67616      for(iCol=0; iCol<pTab->nCol; iCol++){
67617        if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
67618          break;
67619        }
67620      }
67621      if( iCol<pTab->nCol ){
67622        pTab->aCol[iCol].isPrimKey = 1;
67623      }
67624    }
67625    if( pList->nExpr>1 ) iCol = -1;
67626  }
67627  if( iCol>=0 && iCol<pTab->nCol ){
67628    zType = pTab->aCol[iCol].zType;
67629  }
67630  if( zType && sqlite3StrICmp(zType, "INTEGER")==0
67631        && sortOrder==SQLITE_SO_ASC ){
67632    pTab->iPKey = iCol;
67633    pTab->keyConf = (u8)onError;
67634    assert( autoInc==0 || autoInc==1 );
67635    pTab->tabFlags |= autoInc*TF_Autoincrement;
67636  }else if( autoInc ){
67637#ifndef SQLITE_OMIT_AUTOINCREMENT
67638    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
67639       "INTEGER PRIMARY KEY");
67640#endif
67641  }else{
67642    Index *p;
67643    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
67644    if( p ){
67645      p->autoIndex = 2;
67646    }
67647    pList = 0;
67648  }
67649
67650primary_key_exit:
67651  sqlite3ExprListDelete(pParse->db, pList);
67652  return;
67653}
67654
67655/*
67656** Add a new CHECK constraint to the table currently under construction.
67657*/
67658SQLITE_PRIVATE void sqlite3AddCheckConstraint(
67659  Parse *pParse,    /* Parsing context */
67660  Expr *pCheckExpr  /* The check expression */
67661){
67662  sqlite3 *db = pParse->db;
67663#ifndef SQLITE_OMIT_CHECK
67664  Table *pTab = pParse->pNewTable;
67665  if( pTab && !IN_DECLARE_VTAB ){
67666    pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
67667  }else
67668#endif
67669  {
67670    sqlite3ExprDelete(db, pCheckExpr);
67671  }
67672}
67673
67674/*
67675** Set the collation function of the most recently parsed table column
67676** to the CollSeq given.
67677*/
67678SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
67679  Table *p;
67680  int i;
67681  char *zColl;              /* Dequoted name of collation sequence */
67682  sqlite3 *db;
67683
67684  if( (p = pParse->pNewTable)==0 ) return;
67685  i = p->nCol-1;
67686  db = pParse->db;
67687  zColl = sqlite3NameFromToken(db, pToken);
67688  if( !zColl ) return;
67689
67690  if( sqlite3LocateCollSeq(pParse, zColl) ){
67691    Index *pIdx;
67692    p->aCol[i].zColl = zColl;
67693
67694    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
67695    ** then an index may have been created on this column before the
67696    ** collation type was added. Correct this if it is the case.
67697    */
67698    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
67699      assert( pIdx->nColumn==1 );
67700      if( pIdx->aiColumn[0]==i ){
67701        pIdx->azColl[0] = p->aCol[i].zColl;
67702      }
67703    }
67704  }else{
67705    sqlite3DbFree(db, zColl);
67706  }
67707}
67708
67709/*
67710** This function returns the collation sequence for database native text
67711** encoding identified by the string zName, length nName.
67712**
67713** If the requested collation sequence is not available, or not available
67714** in the database native encoding, the collation factory is invoked to
67715** request it. If the collation factory does not supply such a sequence,
67716** and the sequence is available in another text encoding, then that is
67717** returned instead.
67718**
67719** If no versions of the requested collations sequence are available, or
67720** another error occurs, NULL is returned and an error message written into
67721** pParse.
67722**
67723** This routine is a wrapper around sqlite3FindCollSeq().  This routine
67724** invokes the collation factory if the named collation cannot be found
67725** and generates an error message.
67726**
67727** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
67728*/
67729SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
67730  sqlite3 *db = pParse->db;
67731  u8 enc = ENC(db);
67732  u8 initbusy = db->init.busy;
67733  CollSeq *pColl;
67734
67735  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
67736  if( !initbusy && (!pColl || !pColl->xCmp) ){
67737    pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
67738    if( !pColl ){
67739      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
67740    }
67741  }
67742
67743  return pColl;
67744}
67745
67746
67747/*
67748** Generate code that will increment the schema cookie.
67749**
67750** The schema cookie is used to determine when the schema for the
67751** database changes.  After each schema change, the cookie value
67752** changes.  When a process first reads the schema it records the
67753** cookie.  Thereafter, whenever it goes to access the database,
67754** it checks the cookie to make sure the schema has not changed
67755** since it was last read.
67756**
67757** This plan is not completely bullet-proof.  It is possible for
67758** the schema to change multiple times and for the cookie to be
67759** set back to prior value.  But schema changes are infrequent
67760** and the probability of hitting the same cookie value is only
67761** 1 chance in 2^32.  So we're safe enough.
67762*/
67763SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
67764  int r1 = sqlite3GetTempReg(pParse);
67765  sqlite3 *db = pParse->db;
67766  Vdbe *v = pParse->pVdbe;
67767  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
67768  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
67769  sqlite3ReleaseTempReg(pParse, r1);
67770}
67771
67772/*
67773** Measure the number of characters needed to output the given
67774** identifier.  The number returned includes any quotes used
67775** but does not include the null terminator.
67776**
67777** The estimate is conservative.  It might be larger that what is
67778** really needed.
67779*/
67780static int identLength(const char *z){
67781  int n;
67782  for(n=0; *z; n++, z++){
67783    if( *z=='"' ){ n++; }
67784  }
67785  return n + 2;
67786}
67787
67788/*
67789** The first parameter is a pointer to an output buffer. The second
67790** parameter is a pointer to an integer that contains the offset at
67791** which to write into the output buffer. This function copies the
67792** nul-terminated string pointed to by the third parameter, zSignedIdent,
67793** to the specified offset in the buffer and updates *pIdx to refer
67794** to the first byte after the last byte written before returning.
67795**
67796** If the string zSignedIdent consists entirely of alpha-numeric
67797** characters, does not begin with a digit and is not an SQL keyword,
67798** then it is copied to the output buffer exactly as it is. Otherwise,
67799** it is quoted using double-quotes.
67800*/
67801static void identPut(char *z, int *pIdx, char *zSignedIdent){
67802  unsigned char *zIdent = (unsigned char*)zSignedIdent;
67803  int i, j, needQuote;
67804  i = *pIdx;
67805
67806  for(j=0; zIdent[j]; j++){
67807    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
67808  }
67809  needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
67810  if( !needQuote ){
67811    needQuote = zIdent[j];
67812  }
67813
67814  if( needQuote ) z[i++] = '"';
67815  for(j=0; zIdent[j]; j++){
67816    z[i++] = zIdent[j];
67817    if( zIdent[j]=='"' ) z[i++] = '"';
67818  }
67819  if( needQuote ) z[i++] = '"';
67820  z[i] = 0;
67821  *pIdx = i;
67822}
67823
67824/*
67825** Generate a CREATE TABLE statement appropriate for the given
67826** table.  Memory to hold the text of the statement is obtained
67827** from sqliteMalloc() and must be freed by the calling function.
67828*/
67829static char *createTableStmt(sqlite3 *db, Table *p){
67830  int i, k, n;
67831  char *zStmt;
67832  char *zSep, *zSep2, *zEnd;
67833  Column *pCol;
67834  n = 0;
67835  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
67836    n += identLength(pCol->zName) + 5;
67837  }
67838  n += identLength(p->zName);
67839  if( n<50 ){
67840    zSep = "";
67841    zSep2 = ",";
67842    zEnd = ")";
67843  }else{
67844    zSep = "\n  ";
67845    zSep2 = ",\n  ";
67846    zEnd = "\n)";
67847  }
67848  n += 35 + 6*p->nCol;
67849  zStmt = sqlite3Malloc( n );
67850  if( zStmt==0 ){
67851    db->mallocFailed = 1;
67852    return 0;
67853  }
67854  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
67855  k = sqlite3Strlen30(zStmt);
67856  identPut(zStmt, &k, p->zName);
67857  zStmt[k++] = '(';
67858  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
67859    static const char * const azType[] = {
67860        /* SQLITE_AFF_TEXT    */ " TEXT",
67861        /* SQLITE_AFF_NONE    */ "",
67862        /* SQLITE_AFF_NUMERIC */ " NUM",
67863        /* SQLITE_AFF_INTEGER */ " INT",
67864        /* SQLITE_AFF_REAL    */ " REAL"
67865    };
67866    int len;
67867    const char *zType;
67868
67869    sqlite3_snprintf(n-k, &zStmt[k], zSep);
67870    k += sqlite3Strlen30(&zStmt[k]);
67871    zSep = zSep2;
67872    identPut(zStmt, &k, pCol->zName);
67873    assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
67874    assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
67875    testcase( pCol->affinity==SQLITE_AFF_TEXT );
67876    testcase( pCol->affinity==SQLITE_AFF_NONE );
67877    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
67878    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
67879    testcase( pCol->affinity==SQLITE_AFF_REAL );
67880
67881    zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
67882    len = sqlite3Strlen30(zType);
67883    assert( pCol->affinity==SQLITE_AFF_NONE
67884            || pCol->affinity==sqlite3AffinityType(zType) );
67885    memcpy(&zStmt[k], zType, len);
67886    k += len;
67887    assert( k<=n );
67888  }
67889  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
67890  return zStmt;
67891}
67892
67893/*
67894** This routine is called to report the final ")" that terminates
67895** a CREATE TABLE statement.
67896**
67897** The table structure that other action routines have been building
67898** is added to the internal hash tables, assuming no errors have
67899** occurred.
67900**
67901** An entry for the table is made in the master table on disk, unless
67902** this is a temporary table or db->init.busy==1.  When db->init.busy==1
67903** it means we are reading the sqlite_master table because we just
67904** connected to the database or because the sqlite_master table has
67905** recently changed, so the entry for this table already exists in
67906** the sqlite_master table.  We do not want to create it again.
67907**
67908** If the pSelect argument is not NULL, it means that this routine
67909** was called to create a table generated from a
67910** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
67911** the new table will match the result set of the SELECT.
67912*/
67913SQLITE_PRIVATE void sqlite3EndTable(
67914  Parse *pParse,          /* Parse context */
67915  Token *pCons,           /* The ',' token after the last column defn. */
67916  Token *pEnd,            /* The final ')' token in the CREATE TABLE */
67917  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
67918){
67919  Table *p;
67920  sqlite3 *db = pParse->db;
67921  int iDb;
67922
67923  if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
67924    return;
67925  }
67926  p = pParse->pNewTable;
67927  if( p==0 ) return;
67928
67929  assert( !db->init.busy || !pSelect );
67930
67931  iDb = sqlite3SchemaToIndex(db, p->pSchema);
67932
67933#ifndef SQLITE_OMIT_CHECK
67934  /* Resolve names in all CHECK constraint expressions.
67935  */
67936  if( p->pCheck ){
67937    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
67938    NameContext sNC;                /* Name context for pParse->pNewTable */
67939
67940    memset(&sNC, 0, sizeof(sNC));
67941    memset(&sSrc, 0, sizeof(sSrc));
67942    sSrc.nSrc = 1;
67943    sSrc.a[0].zName = p->zName;
67944    sSrc.a[0].pTab = p;
67945    sSrc.a[0].iCursor = -1;
67946    sNC.pParse = pParse;
67947    sNC.pSrcList = &sSrc;
67948    sNC.isCheck = 1;
67949    if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
67950      return;
67951    }
67952  }
67953#endif /* !defined(SQLITE_OMIT_CHECK) */
67954
67955  /* If the db->init.busy is 1 it means we are reading the SQL off the
67956  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
67957  ** So do not write to the disk again.  Extract the root page number
67958  ** for the table from the db->init.newTnum field.  (The page number
67959  ** should have been put there by the sqliteOpenCb routine.)
67960  */
67961  if( db->init.busy ){
67962    p->tnum = db->init.newTnum;
67963  }
67964
67965  /* If not initializing, then create a record for the new table
67966  ** in the SQLITE_MASTER table of the database.
67967  **
67968  ** If this is a TEMPORARY table, write the entry into the auxiliary
67969  ** file instead of into the main database file.
67970  */
67971  if( !db->init.busy ){
67972    int n;
67973    Vdbe *v;
67974    char *zType;    /* "view" or "table" */
67975    char *zType2;   /* "VIEW" or "TABLE" */
67976    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
67977
67978    v = sqlite3GetVdbe(pParse);
67979    if( NEVER(v==0) ) return;
67980
67981    sqlite3VdbeAddOp1(v, OP_Close, 0);
67982
67983    /*
67984    ** Initialize zType for the new view or table.
67985    */
67986    if( p->pSelect==0 ){
67987      /* A regular table */
67988      zType = "table";
67989      zType2 = "TABLE";
67990#ifndef SQLITE_OMIT_VIEW
67991    }else{
67992      /* A view */
67993      zType = "view";
67994      zType2 = "VIEW";
67995#endif
67996    }
67997
67998    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
67999    ** statement to populate the new table. The root-page number for the
68000    ** new table is in register pParse->regRoot.
68001    **
68002    ** Once the SELECT has been coded by sqlite3Select(), it is in a
68003    ** suitable state to query for the column names and types to be used
68004    ** by the new table.
68005    **
68006    ** A shared-cache write-lock is not required to write to the new table,
68007    ** as a schema-lock must have already been obtained to create it. Since
68008    ** a schema-lock excludes all other database users, the write-lock would
68009    ** be redundant.
68010    */
68011    if( pSelect ){
68012      SelectDest dest;
68013      Table *pSelTab;
68014
68015      assert(pParse->nTab==1);
68016      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
68017      sqlite3VdbeChangeP5(v, 1);
68018      pParse->nTab = 2;
68019      sqlite3SelectDestInit(&dest, SRT_Table, 1);
68020      sqlite3Select(pParse, pSelect, &dest);
68021      sqlite3VdbeAddOp1(v, OP_Close, 1);
68022      if( pParse->nErr==0 ){
68023        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
68024        if( pSelTab==0 ) return;
68025        assert( p->aCol==0 );
68026        p->nCol = pSelTab->nCol;
68027        p->aCol = pSelTab->aCol;
68028        pSelTab->nCol = 0;
68029        pSelTab->aCol = 0;
68030        sqlite3DeleteTable(pSelTab);
68031      }
68032    }
68033
68034    /* Compute the complete text of the CREATE statement */
68035    if( pSelect ){
68036      zStmt = createTableStmt(db, p);
68037    }else{
68038      n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
68039      zStmt = sqlite3MPrintf(db,
68040          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
68041      );
68042    }
68043
68044    /* A slot for the record has already been allocated in the
68045    ** SQLITE_MASTER table.  We just need to update that slot with all
68046    ** the information we've collected.
68047    */
68048    sqlite3NestedParse(pParse,
68049      "UPDATE %Q.%s "
68050         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
68051       "WHERE rowid=#%d",
68052      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
68053      zType,
68054      p->zName,
68055      p->zName,
68056      pParse->regRoot,
68057      zStmt,
68058      pParse->regRowid
68059    );
68060    sqlite3DbFree(db, zStmt);
68061    sqlite3ChangeCookie(pParse, iDb);
68062
68063#ifndef SQLITE_OMIT_AUTOINCREMENT
68064    /* Check to see if we need to create an sqlite_sequence table for
68065    ** keeping track of autoincrement keys.
68066    */
68067    if( p->tabFlags & TF_Autoincrement ){
68068      Db *pDb = &db->aDb[iDb];
68069      if( pDb->pSchema->pSeqTab==0 ){
68070        sqlite3NestedParse(pParse,
68071          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
68072          pDb->zName
68073        );
68074      }
68075    }
68076#endif
68077
68078    /* Reparse everything to update our internal data structures */
68079    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
68080        sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
68081  }
68082
68083
68084  /* Add the table to the in-memory representation of the database.
68085  */
68086  if( db->init.busy ){
68087    Table *pOld;
68088    Schema *pSchema = p->pSchema;
68089    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
68090                             sqlite3Strlen30(p->zName),p);
68091    if( pOld ){
68092      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
68093      db->mallocFailed = 1;
68094      return;
68095    }
68096    pParse->pNewTable = 0;
68097    db->nTable++;
68098    db->flags |= SQLITE_InternChanges;
68099
68100#ifndef SQLITE_OMIT_ALTERTABLE
68101    if( !p->pSelect ){
68102      const char *zName = (const char *)pParse->sNameToken.z;
68103      int nName;
68104      assert( !pSelect && pCons && pEnd );
68105      if( pCons->z==0 ){
68106        pCons = pEnd;
68107      }
68108      nName = (int)((const char *)pCons->z - zName);
68109      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
68110    }
68111#endif
68112  }
68113}
68114
68115#ifndef SQLITE_OMIT_VIEW
68116/*
68117** The parser calls this routine in order to create a new VIEW
68118*/
68119SQLITE_PRIVATE void sqlite3CreateView(
68120  Parse *pParse,     /* The parsing context */
68121  Token *pBegin,     /* The CREATE token that begins the statement */
68122  Token *pName1,     /* The token that holds the name of the view */
68123  Token *pName2,     /* The token that holds the name of the view */
68124  Select *pSelect,   /* A SELECT statement that will become the new view */
68125  int isTemp,        /* TRUE for a TEMPORARY view */
68126  int noErr          /* Suppress error messages if VIEW already exists */
68127){
68128  Table *p;
68129  int n;
68130  const char *z;
68131  Token sEnd;
68132  DbFixer sFix;
68133  Token *pName;
68134  int iDb;
68135  sqlite3 *db = pParse->db;
68136
68137  if( pParse->nVar>0 ){
68138    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
68139    sqlite3SelectDelete(db, pSelect);
68140    return;
68141  }
68142  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
68143  p = pParse->pNewTable;
68144  if( p==0 ){
68145    sqlite3SelectDelete(db, pSelect);
68146    return;
68147  }
68148  assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
68149                             ** there could not have been an error */
68150  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
68151  iDb = sqlite3SchemaToIndex(db, p->pSchema);
68152  if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
68153    && sqlite3FixSelect(&sFix, pSelect)
68154  ){
68155    sqlite3SelectDelete(db, pSelect);
68156    return;
68157  }
68158
68159  /* Make a copy of the entire SELECT statement that defines the view.
68160  ** This will force all the Expr.token.z values to be dynamically
68161  ** allocated rather than point to the input string - which means that
68162  ** they will persist after the current sqlite3_exec() call returns.
68163  */
68164  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
68165  sqlite3SelectDelete(db, pSelect);
68166  if( db->mallocFailed ){
68167    return;
68168  }
68169  if( !db->init.busy ){
68170    sqlite3ViewGetColumnNames(pParse, p);
68171  }
68172
68173  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
68174  ** the end.
68175  */
68176  sEnd = pParse->sLastToken;
68177  if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
68178    sEnd.z += sEnd.n;
68179  }
68180  sEnd.n = 0;
68181  n = (int)(sEnd.z - pBegin->z);
68182  z = pBegin->z;
68183  while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
68184  sEnd.z = &z[n-1];
68185  sEnd.n = 1;
68186
68187  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
68188  sqlite3EndTable(pParse, 0, &sEnd, 0);
68189  return;
68190}
68191#endif /* SQLITE_OMIT_VIEW */
68192
68193#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
68194/*
68195** The Table structure pTable is really a VIEW.  Fill in the names of
68196** the columns of the view in the pTable structure.  Return the number
68197** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
68198*/
68199SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
68200  Table *pSelTab;   /* A fake table from which we get the result set */
68201  Select *pSel;     /* Copy of the SELECT that implements the view */
68202  int nErr = 0;     /* Number of errors encountered */
68203  int n;            /* Temporarily holds the number of cursors assigned */
68204  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
68205  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
68206
68207  assert( pTable );
68208
68209#ifndef SQLITE_OMIT_VIRTUALTABLE
68210  if( sqlite3VtabCallConnect(pParse, pTable) ){
68211    return SQLITE_ERROR;
68212  }
68213  if( IsVirtual(pTable) ) return 0;
68214#endif
68215
68216#ifndef SQLITE_OMIT_VIEW
68217  /* A positive nCol means the columns names for this view are
68218  ** already known.
68219  */
68220  if( pTable->nCol>0 ) return 0;
68221
68222  /* A negative nCol is a special marker meaning that we are currently
68223  ** trying to compute the column names.  If we enter this routine with
68224  ** a negative nCol, it means two or more views form a loop, like this:
68225  **
68226  **     CREATE VIEW one AS SELECT * FROM two;
68227  **     CREATE VIEW two AS SELECT * FROM one;
68228  **
68229  ** Actually, the error above is now caught prior to reaching this point.
68230  ** But the following test is still important as it does come up
68231  ** in the following:
68232  **
68233  **     CREATE TABLE main.ex1(a);
68234  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
68235  **     SELECT * FROM temp.ex1;
68236  */
68237  if( pTable->nCol<0 ){
68238    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
68239    return 1;
68240  }
68241  assert( pTable->nCol>=0 );
68242
68243  /* If we get this far, it means we need to compute the table names.
68244  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
68245  ** "*" elements in the results set of the view and will assign cursors
68246  ** to the elements of the FROM clause.  But we do not want these changes
68247  ** to be permanent.  So the computation is done on a copy of the SELECT
68248  ** statement that defines the view.
68249  */
68250  assert( pTable->pSelect );
68251  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
68252  if( pSel ){
68253    u8 enableLookaside = db->lookaside.bEnabled;
68254    n = pParse->nTab;
68255    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
68256    pTable->nCol = -1;
68257    db->lookaside.bEnabled = 0;
68258#ifndef SQLITE_OMIT_AUTHORIZATION
68259    xAuth = db->xAuth;
68260    db->xAuth = 0;
68261    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
68262    db->xAuth = xAuth;
68263#else
68264    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
68265#endif
68266    db->lookaside.bEnabled = enableLookaside;
68267    pParse->nTab = n;
68268    if( pSelTab ){
68269      assert( pTable->aCol==0 );
68270      pTable->nCol = pSelTab->nCol;
68271      pTable->aCol = pSelTab->aCol;
68272      pSelTab->nCol = 0;
68273      pSelTab->aCol = 0;
68274      sqlite3DeleteTable(pSelTab);
68275      pTable->pSchema->flags |= DB_UnresetViews;
68276    }else{
68277      pTable->nCol = 0;
68278      nErr++;
68279    }
68280    sqlite3SelectDelete(db, pSel);
68281  } else {
68282    nErr++;
68283  }
68284#endif /* SQLITE_OMIT_VIEW */
68285  return nErr;
68286}
68287#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
68288
68289#ifndef SQLITE_OMIT_VIEW
68290/*
68291** Clear the column names from every VIEW in database idx.
68292*/
68293static void sqliteViewResetAll(sqlite3 *db, int idx){
68294  HashElem *i;
68295  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
68296  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
68297    Table *pTab = sqliteHashData(i);
68298    if( pTab->pSelect ){
68299      sqliteResetColumnNames(pTab);
68300    }
68301  }
68302  DbClearProperty(db, idx, DB_UnresetViews);
68303}
68304#else
68305# define sqliteViewResetAll(A,B)
68306#endif /* SQLITE_OMIT_VIEW */
68307
68308/*
68309** This function is called by the VDBE to adjust the internal schema
68310** used by SQLite when the btree layer moves a table root page. The
68311** root-page of a table or index in database iDb has changed from iFrom
68312** to iTo.
68313**
68314** Ticket #1728:  The symbol table might still contain information
68315** on tables and/or indices that are the process of being deleted.
68316** If you are unlucky, one of those deleted indices or tables might
68317** have the same rootpage number as the real table or index that is
68318** being moved.  So we cannot stop searching after the first match
68319** because the first match might be for one of the deleted indices
68320** or tables and not the table/index that is actually being moved.
68321** We must continue looping until all tables and indices with
68322** rootpage==iFrom have been converted to have a rootpage of iTo
68323** in order to be certain that we got the right one.
68324*/
68325#ifndef SQLITE_OMIT_AUTOVACUUM
68326SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
68327  HashElem *pElem;
68328  Hash *pHash;
68329
68330  pHash = &pDb->pSchema->tblHash;
68331  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
68332    Table *pTab = sqliteHashData(pElem);
68333    if( pTab->tnum==iFrom ){
68334      pTab->tnum = iTo;
68335    }
68336  }
68337  pHash = &pDb->pSchema->idxHash;
68338  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
68339    Index *pIdx = sqliteHashData(pElem);
68340    if( pIdx->tnum==iFrom ){
68341      pIdx->tnum = iTo;
68342    }
68343  }
68344}
68345#endif
68346
68347/*
68348** Write code to erase the table with root-page iTable from database iDb.
68349** Also write code to modify the sqlite_master table and internal schema
68350** if a root-page of another table is moved by the btree-layer whilst
68351** erasing iTable (this can happen with an auto-vacuum database).
68352*/
68353static void destroyRootPage(Parse *pParse, int iTable, int iDb){
68354  Vdbe *v = sqlite3GetVdbe(pParse);
68355  int r1 = sqlite3GetTempReg(pParse);
68356  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
68357  sqlite3MayAbort(pParse);
68358#ifndef SQLITE_OMIT_AUTOVACUUM
68359  /* OP_Destroy stores an in integer r1. If this integer
68360  ** is non-zero, then it is the root page number of a table moved to
68361  ** location iTable. The following code modifies the sqlite_master table to
68362  ** reflect this.
68363  **
68364  ** The "#NNN" in the SQL is a special constant that means whatever value
68365  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
68366  ** token for additional information.
68367  */
68368  sqlite3NestedParse(pParse,
68369     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
68370     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
68371#endif
68372  sqlite3ReleaseTempReg(pParse, r1);
68373}
68374
68375/*
68376** Write VDBE code to erase table pTab and all associated indices on disk.
68377** Code to update the sqlite_master tables and internal schema definitions
68378** in case a root-page belonging to another table is moved by the btree layer
68379** is also added (this can happen with an auto-vacuum database).
68380*/
68381static void destroyTable(Parse *pParse, Table *pTab){
68382#ifdef SQLITE_OMIT_AUTOVACUUM
68383  Index *pIdx;
68384  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
68385  destroyRootPage(pParse, pTab->tnum, iDb);
68386  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68387    destroyRootPage(pParse, pIdx->tnum, iDb);
68388  }
68389#else
68390  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
68391  ** is not defined), then it is important to call OP_Destroy on the
68392  ** table and index root-pages in order, starting with the numerically
68393  ** largest root-page number. This guarantees that none of the root-pages
68394  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
68395  ** following were coded:
68396  **
68397  ** OP_Destroy 4 0
68398  ** ...
68399  ** OP_Destroy 5 0
68400  **
68401  ** and root page 5 happened to be the largest root-page number in the
68402  ** database, then root page 5 would be moved to page 4 by the
68403  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
68404  ** a free-list page.
68405  */
68406  int iTab = pTab->tnum;
68407  int iDestroyed = 0;
68408
68409  while( 1 ){
68410    Index *pIdx;
68411    int iLargest = 0;
68412
68413    if( iDestroyed==0 || iTab<iDestroyed ){
68414      iLargest = iTab;
68415    }
68416    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68417      int iIdx = pIdx->tnum;
68418      assert( pIdx->pSchema==pTab->pSchema );
68419      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
68420        iLargest = iIdx;
68421      }
68422    }
68423    if( iLargest==0 ){
68424      return;
68425    }else{
68426      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
68427      destroyRootPage(pParse, iLargest, iDb);
68428      iDestroyed = iLargest;
68429    }
68430  }
68431#endif
68432}
68433
68434/*
68435** This routine is called to do the work of a DROP TABLE statement.
68436** pName is the name of the table to be dropped.
68437*/
68438SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
68439  Table *pTab;
68440  Vdbe *v;
68441  sqlite3 *db = pParse->db;
68442  int iDb;
68443
68444  if( db->mallocFailed ){
68445    goto exit_drop_table;
68446  }
68447  assert( pParse->nErr==0 );
68448  assert( pName->nSrc==1 );
68449  if( noErr ) db->suppressErr++;
68450  pTab = sqlite3LocateTable(pParse, isView,
68451                            pName->a[0].zName, pName->a[0].zDatabase);
68452  if( noErr ) db->suppressErr--;
68453
68454  if( pTab==0 ){
68455    goto exit_drop_table;
68456  }
68457  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68458  assert( iDb>=0 && iDb<db->nDb );
68459
68460  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
68461  ** it is initialized.
68462  */
68463  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
68464    goto exit_drop_table;
68465  }
68466#ifndef SQLITE_OMIT_AUTHORIZATION
68467  {
68468    int code;
68469    const char *zTab = SCHEMA_TABLE(iDb);
68470    const char *zDb = db->aDb[iDb].zName;
68471    const char *zArg2 = 0;
68472    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
68473      goto exit_drop_table;
68474    }
68475    if( isView ){
68476      if( !OMIT_TEMPDB && iDb==1 ){
68477        code = SQLITE_DROP_TEMP_VIEW;
68478      }else{
68479        code = SQLITE_DROP_VIEW;
68480      }
68481#ifndef SQLITE_OMIT_VIRTUALTABLE
68482    }else if( IsVirtual(pTab) ){
68483      code = SQLITE_DROP_VTABLE;
68484      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
68485#endif
68486    }else{
68487      if( !OMIT_TEMPDB && iDb==1 ){
68488        code = SQLITE_DROP_TEMP_TABLE;
68489      }else{
68490        code = SQLITE_DROP_TABLE;
68491      }
68492    }
68493    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
68494      goto exit_drop_table;
68495    }
68496    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
68497      goto exit_drop_table;
68498    }
68499  }
68500#endif
68501  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
68502    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
68503    goto exit_drop_table;
68504  }
68505
68506#ifndef SQLITE_OMIT_VIEW
68507  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
68508  ** on a table.
68509  */
68510  if( isView && pTab->pSelect==0 ){
68511    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
68512    goto exit_drop_table;
68513  }
68514  if( !isView && pTab->pSelect ){
68515    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
68516    goto exit_drop_table;
68517  }
68518#endif
68519
68520  /* Generate code to remove the table from the master table
68521  ** on disk.
68522  */
68523  v = sqlite3GetVdbe(pParse);
68524  if( v ){
68525    Trigger *pTrigger;
68526    Db *pDb = &db->aDb[iDb];
68527    sqlite3BeginWriteOperation(pParse, 1, iDb);
68528
68529#ifndef SQLITE_OMIT_VIRTUALTABLE
68530    if( IsVirtual(pTab) ){
68531      sqlite3VdbeAddOp0(v, OP_VBegin);
68532    }
68533#endif
68534    sqlite3FkDropTable(pParse, pName, pTab);
68535
68536    /* Drop all triggers associated with the table being dropped. Code
68537    ** is generated to remove entries from sqlite_master and/or
68538    ** sqlite_temp_master if required.
68539    */
68540    pTrigger = sqlite3TriggerList(pParse, pTab);
68541    while( pTrigger ){
68542      assert( pTrigger->pSchema==pTab->pSchema ||
68543          pTrigger->pSchema==db->aDb[1].pSchema );
68544      sqlite3DropTriggerPtr(pParse, pTrigger);
68545      pTrigger = pTrigger->pNext;
68546    }
68547
68548#ifndef SQLITE_OMIT_AUTOINCREMENT
68549    /* Remove any entries of the sqlite_sequence table associated with
68550    ** the table being dropped. This is done before the table is dropped
68551    ** at the btree level, in case the sqlite_sequence table needs to
68552    ** move as a result of the drop (can happen in auto-vacuum mode).
68553    */
68554    if( pTab->tabFlags & TF_Autoincrement ){
68555      sqlite3NestedParse(pParse,
68556        "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
68557        pDb->zName, pTab->zName
68558      );
68559    }
68560#endif
68561
68562    /* Drop all SQLITE_MASTER table and index entries that refer to the
68563    ** table. The program name loops through the master table and deletes
68564    ** every row that refers to a table of the same name as the one being
68565    ** dropped. Triggers are handled seperately because a trigger can be
68566    ** created in the temp database that refers to a table in another
68567    ** database.
68568    */
68569    sqlite3NestedParse(pParse,
68570        "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
68571        pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
68572
68573    /* Drop any statistics from the sqlite_stat1 table, if it exists */
68574    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
68575      sqlite3NestedParse(pParse,
68576        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
68577      );
68578    }
68579
68580    if( !isView && !IsVirtual(pTab) ){
68581      destroyTable(pParse, pTab);
68582    }
68583
68584    /* Remove the table entry from SQLite's internal schema and modify
68585    ** the schema cookie.
68586    */
68587    if( IsVirtual(pTab) ){
68588      sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
68589    }
68590    sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
68591    sqlite3ChangeCookie(pParse, iDb);
68592  }
68593  sqliteViewResetAll(db, iDb);
68594
68595exit_drop_table:
68596  sqlite3SrcListDelete(db, pName);
68597}
68598
68599/*
68600** This routine is called to create a new foreign key on the table
68601** currently under construction.  pFromCol determines which columns
68602** in the current table point to the foreign key.  If pFromCol==0 then
68603** connect the key to the last column inserted.  pTo is the name of
68604** the table referred to.  pToCol is a list of tables in the other
68605** pTo table that the foreign key points to.  flags contains all
68606** information about the conflict resolution algorithms specified
68607** in the ON DELETE, ON UPDATE and ON INSERT clauses.
68608**
68609** An FKey structure is created and added to the table currently
68610** under construction in the pParse->pNewTable field.
68611**
68612** The foreign key is set for IMMEDIATE processing.  A subsequent call
68613** to sqlite3DeferForeignKey() might change this to DEFERRED.
68614*/
68615SQLITE_PRIVATE void sqlite3CreateForeignKey(
68616  Parse *pParse,       /* Parsing context */
68617  ExprList *pFromCol,  /* Columns in this table that point to other table */
68618  Token *pTo,          /* Name of the other table */
68619  ExprList *pToCol,    /* Columns in the other table */
68620  int flags            /* Conflict resolution algorithms. */
68621){
68622  sqlite3 *db = pParse->db;
68623#ifndef SQLITE_OMIT_FOREIGN_KEY
68624  FKey *pFKey = 0;
68625  FKey *pNextTo;
68626  Table *p = pParse->pNewTable;
68627  int nByte;
68628  int i;
68629  int nCol;
68630  char *z;
68631
68632  assert( pTo!=0 );
68633  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
68634  if( pFromCol==0 ){
68635    int iCol = p->nCol-1;
68636    if( NEVER(iCol<0) ) goto fk_end;
68637    if( pToCol && pToCol->nExpr!=1 ){
68638      sqlite3ErrorMsg(pParse, "foreign key on %s"
68639         " should reference only one column of table %T",
68640         p->aCol[iCol].zName, pTo);
68641      goto fk_end;
68642    }
68643    nCol = 1;
68644  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
68645    sqlite3ErrorMsg(pParse,
68646        "number of columns in foreign key does not match the number of "
68647        "columns in the referenced table");
68648    goto fk_end;
68649  }else{
68650    nCol = pFromCol->nExpr;
68651  }
68652  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
68653  if( pToCol ){
68654    for(i=0; i<pToCol->nExpr; i++){
68655      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
68656    }
68657  }
68658  pFKey = sqlite3DbMallocZero(db, nByte );
68659  if( pFKey==0 ){
68660    goto fk_end;
68661  }
68662  pFKey->pFrom = p;
68663  pFKey->pNextFrom = p->pFKey;
68664  z = (char*)&pFKey->aCol[nCol];
68665  pFKey->zTo = z;
68666  memcpy(z, pTo->z, pTo->n);
68667  z[pTo->n] = 0;
68668  sqlite3Dequote(z);
68669  z += pTo->n+1;
68670  pFKey->nCol = nCol;
68671  if( pFromCol==0 ){
68672    pFKey->aCol[0].iFrom = p->nCol-1;
68673  }else{
68674    for(i=0; i<nCol; i++){
68675      int j;
68676      for(j=0; j<p->nCol; j++){
68677        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
68678          pFKey->aCol[i].iFrom = j;
68679          break;
68680        }
68681      }
68682      if( j>=p->nCol ){
68683        sqlite3ErrorMsg(pParse,
68684          "unknown column \"%s\" in foreign key definition",
68685          pFromCol->a[i].zName);
68686        goto fk_end;
68687      }
68688    }
68689  }
68690  if( pToCol ){
68691    for(i=0; i<nCol; i++){
68692      int n = sqlite3Strlen30(pToCol->a[i].zName);
68693      pFKey->aCol[i].zCol = z;
68694      memcpy(z, pToCol->a[i].zName, n);
68695      z[n] = 0;
68696      z += n+1;
68697    }
68698  }
68699  pFKey->isDeferred = 0;
68700  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
68701  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
68702
68703  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
68704      pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
68705  );
68706  if( pNextTo==pFKey ){
68707    db->mallocFailed = 1;
68708    goto fk_end;
68709  }
68710  if( pNextTo ){
68711    assert( pNextTo->pPrevTo==0 );
68712    pFKey->pNextTo = pNextTo;
68713    pNextTo->pPrevTo = pFKey;
68714  }
68715
68716  /* Link the foreign key to the table as the last step.
68717  */
68718  p->pFKey = pFKey;
68719  pFKey = 0;
68720
68721fk_end:
68722  sqlite3DbFree(db, pFKey);
68723#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
68724  sqlite3ExprListDelete(db, pFromCol);
68725  sqlite3ExprListDelete(db, pToCol);
68726}
68727
68728/*
68729** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
68730** clause is seen as part of a foreign key definition.  The isDeferred
68731** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
68732** The behavior of the most recently created foreign key is adjusted
68733** accordingly.
68734*/
68735SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
68736#ifndef SQLITE_OMIT_FOREIGN_KEY
68737  Table *pTab;
68738  FKey *pFKey;
68739  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
68740  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
68741  pFKey->isDeferred = (u8)isDeferred;
68742#endif
68743}
68744
68745/*
68746** Generate code that will erase and refill index *pIdx.  This is
68747** used to initialize a newly created index or to recompute the
68748** content of an index in response to a REINDEX command.
68749**
68750** if memRootPage is not negative, it means that the index is newly
68751** created.  The register specified by memRootPage contains the
68752** root page number of the index.  If memRootPage is negative, then
68753** the index already exists and must be cleared before being refilled and
68754** the root page number of the index is taken from pIndex->tnum.
68755*/
68756static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
68757  Table *pTab = pIndex->pTable;  /* The table that is indexed */
68758  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
68759  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
68760  int addr1;                     /* Address of top of loop */
68761  int tnum;                      /* Root page of index */
68762  Vdbe *v;                       /* Generate code into this virtual machine */
68763  KeyInfo *pKey;                 /* KeyInfo for index */
68764  int regIdxKey;                 /* Registers containing the index key */
68765  int regRecord;                 /* Register holding assemblied index record */
68766  sqlite3 *db = pParse->db;      /* The database connection */
68767  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
68768
68769#ifndef SQLITE_OMIT_AUTHORIZATION
68770  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
68771      db->aDb[iDb].zName ) ){
68772    return;
68773  }
68774#endif
68775
68776  /* Require a write-lock on the table to perform this operation */
68777  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
68778
68779  v = sqlite3GetVdbe(pParse);
68780  if( v==0 ) return;
68781  if( memRootPage>=0 ){
68782    tnum = memRootPage;
68783  }else{
68784    tnum = pIndex->tnum;
68785    sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
68786  }
68787  pKey = sqlite3IndexKeyinfo(pParse, pIndex);
68788  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
68789                    (char *)pKey, P4_KEYINFO_HANDOFF);
68790  if( memRootPage>=0 ){
68791    sqlite3VdbeChangeP5(v, 1);
68792  }
68793  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
68794  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
68795  regRecord = sqlite3GetTempReg(pParse);
68796  regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
68797  if( pIndex->onError!=OE_None ){
68798    const int regRowid = regIdxKey + pIndex->nColumn;
68799    const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
68800    void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
68801
68802    /* The registers accessed by the OP_IsUnique opcode were allocated
68803    ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
68804    ** call above. Just before that function was freed they were released
68805    ** (made available to the compiler for reuse) using
68806    ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
68807    ** opcode use the values stored within seems dangerous. However, since
68808    ** we can be sure that no other temp registers have been allocated
68809    ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
68810    */
68811    sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
68812    sqlite3HaltConstraint(
68813        pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
68814  }
68815  sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
68816  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
68817  sqlite3ReleaseTempReg(pParse, regRecord);
68818  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
68819  sqlite3VdbeJumpHere(v, addr1);
68820  sqlite3VdbeAddOp1(v, OP_Close, iTab);
68821  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
68822}
68823
68824/*
68825** Create a new index for an SQL table.  pName1.pName2 is the name of the index
68826** and pTblList is the name of the table that is to be indexed.  Both will
68827** be NULL for a primary key or an index that is created to satisfy a
68828** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
68829** as the table to be indexed.  pParse->pNewTable is a table that is
68830** currently being constructed by a CREATE TABLE statement.
68831**
68832** pList is a list of columns to be indexed.  pList will be NULL if this
68833** is a primary key or unique-constraint on the most recent column added
68834** to the table currently under construction.
68835**
68836** If the index is created successfully, return a pointer to the new Index
68837** structure. This is used by sqlite3AddPrimaryKey() to mark the index
68838** as the tables primary key (Index.autoIndex==2).
68839*/
68840SQLITE_PRIVATE Index *sqlite3CreateIndex(
68841  Parse *pParse,     /* All information about this parse */
68842  Token *pName1,     /* First part of index name. May be NULL */
68843  Token *pName2,     /* Second part of index name. May be NULL */
68844  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
68845  ExprList *pList,   /* A list of columns to be indexed */
68846  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
68847  Token *pStart,     /* The CREATE token that begins this statement */
68848  Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
68849  int sortOrder,     /* Sort order of primary key when pList==NULL */
68850  int ifNotExist     /* Omit error if index already exists */
68851){
68852  Index *pRet = 0;     /* Pointer to return */
68853  Table *pTab = 0;     /* Table to be indexed */
68854  Index *pIndex = 0;   /* The index to be created */
68855  char *zName = 0;     /* Name of the index */
68856  int nName;           /* Number of characters in zName */
68857  int i, j;
68858  Token nullId;        /* Fake token for an empty ID list */
68859  DbFixer sFix;        /* For assigning database names to pTable */
68860  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
68861  sqlite3 *db = pParse->db;
68862  Db *pDb;             /* The specific table containing the indexed database */
68863  int iDb;             /* Index of the database that is being written */
68864  Token *pName = 0;    /* Unqualified name of the index to create */
68865  struct ExprList_item *pListItem; /* For looping over pList */
68866  int nCol;
68867  int nExtra = 0;
68868  char *zExtra;
68869
68870  assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
68871  assert( pParse->nErr==0 );      /* Never called with prior errors */
68872  if( db->mallocFailed || IN_DECLARE_VTAB ){
68873    goto exit_create_index;
68874  }
68875  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
68876    goto exit_create_index;
68877  }
68878
68879  /*
68880  ** Find the table that is to be indexed.  Return early if not found.
68881  */
68882  if( pTblName!=0 ){
68883
68884    /* Use the two-part index name to determine the database
68885    ** to search for the table. 'Fix' the table name to this db
68886    ** before looking up the table.
68887    */
68888    assert( pName1 && pName2 );
68889    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
68890    if( iDb<0 ) goto exit_create_index;
68891
68892#ifndef SQLITE_OMIT_TEMPDB
68893    /* If the index name was unqualified, check if the the table
68894    ** is a temp table. If so, set the database to 1. Do not do this
68895    ** if initialising a database schema.
68896    */
68897    if( !db->init.busy ){
68898      pTab = sqlite3SrcListLookup(pParse, pTblName);
68899      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
68900        iDb = 1;
68901      }
68902    }
68903#endif
68904
68905    if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
68906        sqlite3FixSrcList(&sFix, pTblName)
68907    ){
68908      /* Because the parser constructs pTblName from a single identifier,
68909      ** sqlite3FixSrcList can never fail. */
68910      assert(0);
68911    }
68912    pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
68913        pTblName->a[0].zDatabase);
68914    if( !pTab || db->mallocFailed ) goto exit_create_index;
68915    assert( db->aDb[iDb].pSchema==pTab->pSchema );
68916  }else{
68917    assert( pName==0 );
68918    pTab = pParse->pNewTable;
68919    if( !pTab ) goto exit_create_index;
68920    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68921  }
68922  pDb = &db->aDb[iDb];
68923
68924  assert( pTab!=0 );
68925  assert( pParse->nErr==0 );
68926  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
68927       && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
68928    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
68929    goto exit_create_index;
68930  }
68931#ifndef SQLITE_OMIT_VIEW
68932  if( pTab->pSelect ){
68933    sqlite3ErrorMsg(pParse, "views may not be indexed");
68934    goto exit_create_index;
68935  }
68936#endif
68937#ifndef SQLITE_OMIT_VIRTUALTABLE
68938  if( IsVirtual(pTab) ){
68939    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
68940    goto exit_create_index;
68941  }
68942#endif
68943
68944  /*
68945  ** Find the name of the index.  Make sure there is not already another
68946  ** index or table with the same name.
68947  **
68948  ** Exception:  If we are reading the names of permanent indices from the
68949  ** sqlite_master table (because some other process changed the schema) and
68950  ** one of the index names collides with the name of a temporary table or
68951  ** index, then we will continue to process this index.
68952  **
68953  ** If pName==0 it means that we are
68954  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
68955  ** own name.
68956  */
68957  if( pName ){
68958    zName = sqlite3NameFromToken(db, pName);
68959    if( zName==0 ) goto exit_create_index;
68960    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
68961      goto exit_create_index;
68962    }
68963    if( !db->init.busy ){
68964      if( sqlite3FindTable(db, zName, 0)!=0 ){
68965        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
68966        goto exit_create_index;
68967      }
68968    }
68969    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
68970      if( !ifNotExist ){
68971        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
68972      }
68973      goto exit_create_index;
68974    }
68975  }else{
68976    int n;
68977    Index *pLoop;
68978    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
68979    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
68980    if( zName==0 ){
68981      goto exit_create_index;
68982    }
68983  }
68984
68985  /* Check for authorization to create an index.
68986  */
68987#ifndef SQLITE_OMIT_AUTHORIZATION
68988  {
68989    const char *zDb = pDb->zName;
68990    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
68991      goto exit_create_index;
68992    }
68993    i = SQLITE_CREATE_INDEX;
68994    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
68995    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
68996      goto exit_create_index;
68997    }
68998  }
68999#endif
69000
69001  /* If pList==0, it means this routine was called to make a primary
69002  ** key out of the last column added to the table under construction.
69003  ** So create a fake list to simulate this.
69004  */
69005  if( pList==0 ){
69006    nullId.z = pTab->aCol[pTab->nCol-1].zName;
69007    nullId.n = sqlite3Strlen30((char*)nullId.z);
69008    pList = sqlite3ExprListAppend(pParse, 0, 0);
69009    if( pList==0 ) goto exit_create_index;
69010    sqlite3ExprListSetName(pParse, pList, &nullId, 0);
69011    pList->a[0].sortOrder = (u8)sortOrder;
69012  }
69013
69014  /* Figure out how many bytes of space are required to store explicitly
69015  ** specified collation sequence names.
69016  */
69017  for(i=0; i<pList->nExpr; i++){
69018    Expr *pExpr = pList->a[i].pExpr;
69019    if( pExpr ){
69020      CollSeq *pColl = pExpr->pColl;
69021      /* Either pColl!=0 or there was an OOM failure.  But if an OOM
69022      ** failure we have quit before reaching this point. */
69023      if( ALWAYS(pColl) ){
69024        nExtra += (1 + sqlite3Strlen30(pColl->zName));
69025      }
69026    }
69027  }
69028
69029  /*
69030  ** Allocate the index structure.
69031  */
69032  nName = sqlite3Strlen30(zName);
69033  nCol = pList->nExpr;
69034  pIndex = sqlite3DbMallocZero(db,
69035      sizeof(Index) +              /* Index structure  */
69036      sizeof(int)*nCol +           /* Index.aiColumn   */
69037      sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
69038      sizeof(char *)*nCol +        /* Index.azColl     */
69039      sizeof(u8)*nCol +            /* Index.aSortOrder */
69040      nName + 1 +                  /* Index.zName      */
69041      nExtra                       /* Collation sequence names */
69042  );
69043  if( db->mallocFailed ){
69044    goto exit_create_index;
69045  }
69046  pIndex->azColl = (char**)(&pIndex[1]);
69047  pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
69048  pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
69049  pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
69050  pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
69051  zExtra = (char *)(&pIndex->zName[nName+1]);
69052  memcpy(pIndex->zName, zName, nName+1);
69053  pIndex->pTable = pTab;
69054  pIndex->nColumn = pList->nExpr;
69055  pIndex->onError = (u8)onError;
69056  pIndex->autoIndex = (u8)(pName==0);
69057  pIndex->pSchema = db->aDb[iDb].pSchema;
69058
69059  /* Check to see if we should honor DESC requests on index columns
69060  */
69061  if( pDb->pSchema->file_format>=4 ){
69062    sortOrderMask = -1;   /* Honor DESC */
69063  }else{
69064    sortOrderMask = 0;    /* Ignore DESC */
69065  }
69066
69067  /* Scan the names of the columns of the table to be indexed and
69068  ** load the column indices into the Index structure.  Report an error
69069  ** if any column is not found.
69070  **
69071  ** TODO:  Add a test to make sure that the same column is not named
69072  ** more than once within the same index.  Only the first instance of
69073  ** the column will ever be used by the optimizer.  Note that using the
69074  ** same column more than once cannot be an error because that would
69075  ** break backwards compatibility - it needs to be a warning.
69076  */
69077  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
69078    const char *zColName = pListItem->zName;
69079    Column *pTabCol;
69080    int requestedSortOrder;
69081    char *zColl;                   /* Collation sequence name */
69082
69083    for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
69084      if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
69085    }
69086    if( j>=pTab->nCol ){
69087      sqlite3ErrorMsg(pParse, "table %s has no column named %s",
69088        pTab->zName, zColName);
69089      goto exit_create_index;
69090    }
69091    pIndex->aiColumn[i] = j;
69092    /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
69093    ** the way the "idxlist" non-terminal is constructed by the parser,
69094    ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
69095    ** must exist or else there must have been an OOM error.  But if there
69096    ** was an OOM error, we would never reach this point. */
69097    if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
69098      int nColl;
69099      zColl = pListItem->pExpr->pColl->zName;
69100      nColl = sqlite3Strlen30(zColl) + 1;
69101      assert( nExtra>=nColl );
69102      memcpy(zExtra, zColl, nColl);
69103      zColl = zExtra;
69104      zExtra += nColl;
69105      nExtra -= nColl;
69106    }else{
69107      zColl = pTab->aCol[j].zColl;
69108      if( !zColl ){
69109        zColl = db->pDfltColl->zName;
69110      }
69111    }
69112    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
69113      goto exit_create_index;
69114    }
69115    pIndex->azColl[i] = zColl;
69116    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
69117    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
69118  }
69119  sqlite3DefaultRowEst(pIndex);
69120
69121  if( pTab==pParse->pNewTable ){
69122    /* This routine has been called to create an automatic index as a
69123    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
69124    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
69125    ** i.e. one of:
69126    **
69127    ** CREATE TABLE t(x PRIMARY KEY, y);
69128    ** CREATE TABLE t(x, y, UNIQUE(x, y));
69129    **
69130    ** Either way, check to see if the table already has such an index. If
69131    ** so, don't bother creating this one. This only applies to
69132    ** automatically created indices. Users can do as they wish with
69133    ** explicit indices.
69134    **
69135    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
69136    ** (and thus suppressing the second one) even if they have different
69137    ** sort orders.
69138    **
69139    ** If there are different collating sequences or if the columns of
69140    ** the constraint occur in different orders, then the constraints are
69141    ** considered distinct and both result in separate indices.
69142    */
69143    Index *pIdx;
69144    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
69145      int k;
69146      assert( pIdx->onError!=OE_None );
69147      assert( pIdx->autoIndex );
69148      assert( pIndex->onError!=OE_None );
69149
69150      if( pIdx->nColumn!=pIndex->nColumn ) continue;
69151      for(k=0; k<pIdx->nColumn; k++){
69152        const char *z1;
69153        const char *z2;
69154        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
69155        z1 = pIdx->azColl[k];
69156        z2 = pIndex->azColl[k];
69157        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
69158      }
69159      if( k==pIdx->nColumn ){
69160        if( pIdx->onError!=pIndex->onError ){
69161          /* This constraint creates the same index as a previous
69162          ** constraint specified somewhere in the CREATE TABLE statement.
69163          ** However the ON CONFLICT clauses are different. If both this
69164          ** constraint and the previous equivalent constraint have explicit
69165          ** ON CONFLICT clauses this is an error. Otherwise, use the
69166          ** explicitly specified behaviour for the index.
69167          */
69168          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
69169            sqlite3ErrorMsg(pParse,
69170                "conflicting ON CONFLICT clauses specified", 0);
69171          }
69172          if( pIdx->onError==OE_Default ){
69173            pIdx->onError = pIndex->onError;
69174          }
69175        }
69176        goto exit_create_index;
69177      }
69178    }
69179  }
69180
69181  /* Link the new Index structure to its table and to the other
69182  ** in-memory database structures.
69183  */
69184  if( db->init.busy ){
69185    Index *p;
69186    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
69187                          pIndex->zName, sqlite3Strlen30(pIndex->zName),
69188                          pIndex);
69189    if( p ){
69190      assert( p==pIndex );  /* Malloc must have failed */
69191      db->mallocFailed = 1;
69192      goto exit_create_index;
69193    }
69194    db->flags |= SQLITE_InternChanges;
69195    if( pTblName!=0 ){
69196      pIndex->tnum = db->init.newTnum;
69197    }
69198  }
69199
69200  /* If the db->init.busy is 0 then create the index on disk.  This
69201  ** involves writing the index into the master table and filling in the
69202  ** index with the current table contents.
69203  **
69204  ** The db->init.busy is 0 when the user first enters a CREATE INDEX
69205  ** command.  db->init.busy is 1 when a database is opened and
69206  ** CREATE INDEX statements are read out of the master table.  In
69207  ** the latter case the index already exists on disk, which is why
69208  ** we don't want to recreate it.
69209  **
69210  ** If pTblName==0 it means this index is generated as a primary key
69211  ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
69212  ** has just been created, it contains no data and the index initialization
69213  ** step can be skipped.
69214  */
69215  else{ /* if( db->init.busy==0 ) */
69216    Vdbe *v;
69217    char *zStmt;
69218    int iMem = ++pParse->nMem;
69219
69220    v = sqlite3GetVdbe(pParse);
69221    if( v==0 ) goto exit_create_index;
69222
69223
69224    /* Create the rootpage for the index
69225    */
69226    sqlite3BeginWriteOperation(pParse, 1, iDb);
69227    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
69228
69229    /* Gather the complete text of the CREATE INDEX statement into
69230    ** the zStmt variable
69231    */
69232    if( pStart ){
69233      assert( pEnd!=0 );
69234      /* A named index with an explicit CREATE INDEX statement */
69235      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
69236        onError==OE_None ? "" : " UNIQUE",
69237        pEnd->z - pName->z + 1,
69238        pName->z);
69239    }else{
69240      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
69241      /* zStmt = sqlite3MPrintf(""); */
69242      zStmt = 0;
69243    }
69244
69245    /* Add an entry in sqlite_master for this index
69246    */
69247    sqlite3NestedParse(pParse,
69248        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
69249        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
69250        pIndex->zName,
69251        pTab->zName,
69252        iMem,
69253        zStmt
69254    );
69255    sqlite3DbFree(db, zStmt);
69256
69257    /* Fill the index with data and reparse the schema. Code an OP_Expire
69258    ** to invalidate all pre-compiled statements.
69259    */
69260    if( pTblName ){
69261      sqlite3RefillIndex(pParse, pIndex, iMem);
69262      sqlite3ChangeCookie(pParse, iDb);
69263      sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
69264         sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
69265      sqlite3VdbeAddOp1(v, OP_Expire, 0);
69266    }
69267  }
69268
69269  /* When adding an index to the list of indices for a table, make
69270  ** sure all indices labeled OE_Replace come after all those labeled
69271  ** OE_Ignore.  This is necessary for the correct constraint check
69272  ** processing (in sqlite3GenerateConstraintChecks()) as part of
69273  ** UPDATE and INSERT statements.
69274  */
69275  if( db->init.busy || pTblName==0 ){
69276    if( onError!=OE_Replace || pTab->pIndex==0
69277         || pTab->pIndex->onError==OE_Replace){
69278      pIndex->pNext = pTab->pIndex;
69279      pTab->pIndex = pIndex;
69280    }else{
69281      Index *pOther = pTab->pIndex;
69282      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
69283        pOther = pOther->pNext;
69284      }
69285      pIndex->pNext = pOther->pNext;
69286      pOther->pNext = pIndex;
69287    }
69288    pRet = pIndex;
69289    pIndex = 0;
69290  }
69291
69292  /* Clean up before exiting */
69293exit_create_index:
69294  if( pIndex ){
69295    sqlite3_free(pIndex->zColAff);
69296    sqlite3DbFree(db, pIndex);
69297  }
69298  sqlite3ExprListDelete(db, pList);
69299  sqlite3SrcListDelete(db, pTblName);
69300  sqlite3DbFree(db, zName);
69301  return pRet;
69302}
69303
69304/*
69305** Fill the Index.aiRowEst[] array with default information - information
69306** to be used when we have not run the ANALYZE command.
69307**
69308** aiRowEst[0] is suppose to contain the number of elements in the index.
69309** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
69310** number of rows in the table that match any particular value of the
69311** first column of the index.  aiRowEst[2] is an estimate of the number
69312** of rows that match any particular combiniation of the first 2 columns
69313** of the index.  And so forth.  It must always be the case that
69314*
69315**           aiRowEst[N]<=aiRowEst[N-1]
69316**           aiRowEst[N]>=1
69317**
69318** Apart from that, we have little to go on besides intuition as to
69319** how aiRowEst[] should be initialized.  The numbers generated here
69320** are based on typical values found in actual indices.
69321*/
69322SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
69323  unsigned *a = pIdx->aiRowEst;
69324  int i;
69325  assert( a!=0 );
69326  a[0] = 1000000;
69327  for(i=pIdx->nColumn; i>=5; i--){
69328    a[i] = 5;
69329  }
69330  while( i>=1 ){
69331    a[i] = 11 - i;
69332    i--;
69333  }
69334  if( pIdx->onError!=OE_None ){
69335    a[pIdx->nColumn] = 1;
69336  }
69337}
69338
69339/*
69340** This routine will drop an existing named index.  This routine
69341** implements the DROP INDEX statement.
69342*/
69343SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
69344  Index *pIndex;
69345  Vdbe *v;
69346  sqlite3 *db = pParse->db;
69347  int iDb;
69348
69349  assert( pParse->nErr==0 );   /* Never called with prior errors */
69350  if( db->mallocFailed ){
69351    goto exit_drop_index;
69352  }
69353  assert( pName->nSrc==1 );
69354  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
69355    goto exit_drop_index;
69356  }
69357  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
69358  if( pIndex==0 ){
69359    if( !ifExists ){
69360      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
69361    }
69362    pParse->checkSchema = 1;
69363    goto exit_drop_index;
69364  }
69365  if( pIndex->autoIndex ){
69366    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
69367      "or PRIMARY KEY constraint cannot be dropped", 0);
69368    goto exit_drop_index;
69369  }
69370  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
69371#ifndef SQLITE_OMIT_AUTHORIZATION
69372  {
69373    int code = SQLITE_DROP_INDEX;
69374    Table *pTab = pIndex->pTable;
69375    const char *zDb = db->aDb[iDb].zName;
69376    const char *zTab = SCHEMA_TABLE(iDb);
69377    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
69378      goto exit_drop_index;
69379    }
69380    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
69381    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
69382      goto exit_drop_index;
69383    }
69384  }
69385#endif
69386
69387  /* Generate code to remove the index and from the master table */
69388  v = sqlite3GetVdbe(pParse);
69389  if( v ){
69390    sqlite3BeginWriteOperation(pParse, 1, iDb);
69391    sqlite3NestedParse(pParse,
69392       "DELETE FROM %Q.%s WHERE name=%Q",
69393       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
69394       pIndex->zName
69395    );
69396    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
69397      sqlite3NestedParse(pParse,
69398        "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
69399        db->aDb[iDb].zName, pIndex->zName
69400      );
69401    }
69402    sqlite3ChangeCookie(pParse, iDb);
69403    destroyRootPage(pParse, pIndex->tnum, iDb);
69404    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
69405  }
69406
69407exit_drop_index:
69408  sqlite3SrcListDelete(db, pName);
69409}
69410
69411/*
69412** pArray is a pointer to an array of objects.  Each object in the
69413** array is szEntry bytes in size.  This routine allocates a new
69414** object on the end of the array.
69415**
69416** *pnEntry is the number of entries already in use.  *pnAlloc is
69417** the previously allocated size of the array.  initSize is the
69418** suggested initial array size allocation.
69419**
69420** The index of the new entry is returned in *pIdx.
69421**
69422** This routine returns a pointer to the array of objects.  This
69423** might be the same as the pArray parameter or it might be a different
69424** pointer if the array was resized.
69425*/
69426SQLITE_PRIVATE void *sqlite3ArrayAllocate(
69427  sqlite3 *db,      /* Connection to notify of malloc failures */
69428  void *pArray,     /* Array of objects.  Might be reallocated */
69429  int szEntry,      /* Size of each object in the array */
69430  int initSize,     /* Suggested initial allocation, in elements */
69431  int *pnEntry,     /* Number of objects currently in use */
69432  int *pnAlloc,     /* Current size of the allocation, in elements */
69433  int *pIdx         /* Write the index of a new slot here */
69434){
69435  char *z;
69436  if( *pnEntry >= *pnAlloc ){
69437    void *pNew;
69438    int newSize;
69439    newSize = (*pnAlloc)*2 + initSize;
69440    pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
69441    if( pNew==0 ){
69442      *pIdx = -1;
69443      return pArray;
69444    }
69445    *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
69446    pArray = pNew;
69447  }
69448  z = (char*)pArray;
69449  memset(&z[*pnEntry * szEntry], 0, szEntry);
69450  *pIdx = *pnEntry;
69451  ++*pnEntry;
69452  return pArray;
69453}
69454
69455/*
69456** Append a new element to the given IdList.  Create a new IdList if
69457** need be.
69458**
69459** A new IdList is returned, or NULL if malloc() fails.
69460*/
69461SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
69462  int i;
69463  if( pList==0 ){
69464    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
69465    if( pList==0 ) return 0;
69466    pList->nAlloc = 0;
69467  }
69468  pList->a = sqlite3ArrayAllocate(
69469      db,
69470      pList->a,
69471      sizeof(pList->a[0]),
69472      5,
69473      &pList->nId,
69474      &pList->nAlloc,
69475      &i
69476  );
69477  if( i<0 ){
69478    sqlite3IdListDelete(db, pList);
69479    return 0;
69480  }
69481  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
69482  return pList;
69483}
69484
69485/*
69486** Delete an IdList.
69487*/
69488SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
69489  int i;
69490  if( pList==0 ) return;
69491  for(i=0; i<pList->nId; i++){
69492    sqlite3DbFree(db, pList->a[i].zName);
69493  }
69494  sqlite3DbFree(db, pList->a);
69495  sqlite3DbFree(db, pList);
69496}
69497
69498/*
69499** Return the index in pList of the identifier named zId.  Return -1
69500** if not found.
69501*/
69502SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
69503  int i;
69504  if( pList==0 ) return -1;
69505  for(i=0; i<pList->nId; i++){
69506    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
69507  }
69508  return -1;
69509}
69510
69511/*
69512** Expand the space allocated for the given SrcList object by
69513** creating nExtra new slots beginning at iStart.  iStart is zero based.
69514** New slots are zeroed.
69515**
69516** For example, suppose a SrcList initially contains two entries: A,B.
69517** To append 3 new entries onto the end, do this:
69518**
69519**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
69520**
69521** After the call above it would contain:  A, B, nil, nil, nil.
69522** If the iStart argument had been 1 instead of 2, then the result
69523** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
69524** the iStart value would be 0.  The result then would
69525** be: nil, nil, nil, A, B.
69526**
69527** If a memory allocation fails the SrcList is unchanged.  The
69528** db->mallocFailed flag will be set to true.
69529*/
69530SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
69531  sqlite3 *db,       /* Database connection to notify of OOM errors */
69532  SrcList *pSrc,     /* The SrcList to be enlarged */
69533  int nExtra,        /* Number of new slots to add to pSrc->a[] */
69534  int iStart         /* Index in pSrc->a[] of first new slot */
69535){
69536  int i;
69537
69538  /* Sanity checking on calling parameters */
69539  assert( iStart>=0 );
69540  assert( nExtra>=1 );
69541  assert( pSrc!=0 );
69542  assert( iStart<=pSrc->nSrc );
69543
69544  /* Allocate additional space if needed */
69545  if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
69546    SrcList *pNew;
69547    int nAlloc = pSrc->nSrc+nExtra;
69548    int nGot;
69549    pNew = sqlite3DbRealloc(db, pSrc,
69550               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
69551    if( pNew==0 ){
69552      assert( db->mallocFailed );
69553      return pSrc;
69554    }
69555    pSrc = pNew;
69556    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
69557    pSrc->nAlloc = (u16)nGot;
69558  }
69559
69560  /* Move existing slots that come after the newly inserted slots
69561  ** out of the way */
69562  for(i=pSrc->nSrc-1; i>=iStart; i--){
69563    pSrc->a[i+nExtra] = pSrc->a[i];
69564  }
69565  pSrc->nSrc += (i16)nExtra;
69566
69567  /* Zero the newly allocated slots */
69568  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
69569  for(i=iStart; i<iStart+nExtra; i++){
69570    pSrc->a[i].iCursor = -1;
69571  }
69572
69573  /* Return a pointer to the enlarged SrcList */
69574  return pSrc;
69575}
69576
69577
69578/*
69579** Append a new table name to the given SrcList.  Create a new SrcList if
69580** need be.  A new entry is created in the SrcList even if pTable is NULL.
69581**
69582** A SrcList is returned, or NULL if there is an OOM error.  The returned
69583** SrcList might be the same as the SrcList that was input or it might be
69584** a new one.  If an OOM error does occurs, then the prior value of pList
69585** that is input to this routine is automatically freed.
69586**
69587** If pDatabase is not null, it means that the table has an optional
69588** database name prefix.  Like this:  "database.table".  The pDatabase
69589** points to the table name and the pTable points to the database name.
69590** The SrcList.a[].zName field is filled with the table name which might
69591** come from pTable (if pDatabase is NULL) or from pDatabase.
69592** SrcList.a[].zDatabase is filled with the database name from pTable,
69593** or with NULL if no database is specified.
69594**
69595** In other words, if call like this:
69596**
69597**         sqlite3SrcListAppend(D,A,B,0);
69598**
69599** Then B is a table name and the database name is unspecified.  If called
69600** like this:
69601**
69602**         sqlite3SrcListAppend(D,A,B,C);
69603**
69604** Then C is the table name and B is the database name.  If C is defined
69605** then so is B.  In other words, we never have a case where:
69606**
69607**         sqlite3SrcListAppend(D,A,0,C);
69608**
69609** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
69610** before being added to the SrcList.
69611*/
69612SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
69613  sqlite3 *db,        /* Connection to notify of malloc failures */
69614  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
69615  Token *pTable,      /* Table to append */
69616  Token *pDatabase    /* Database of the table */
69617){
69618  struct SrcList_item *pItem;
69619  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
69620  if( pList==0 ){
69621    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
69622    if( pList==0 ) return 0;
69623    pList->nAlloc = 1;
69624  }
69625  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
69626  if( db->mallocFailed ){
69627    sqlite3SrcListDelete(db, pList);
69628    return 0;
69629  }
69630  pItem = &pList->a[pList->nSrc-1];
69631  if( pDatabase && pDatabase->z==0 ){
69632    pDatabase = 0;
69633  }
69634  if( pDatabase ){
69635    Token *pTemp = pDatabase;
69636    pDatabase = pTable;
69637    pTable = pTemp;
69638  }
69639  pItem->zName = sqlite3NameFromToken(db, pTable);
69640  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
69641  return pList;
69642}
69643
69644/*
69645** Assign VdbeCursor index numbers to all tables in a SrcList
69646*/
69647SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
69648  int i;
69649  struct SrcList_item *pItem;
69650  assert(pList || pParse->db->mallocFailed );
69651  if( pList ){
69652    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
69653      if( pItem->iCursor>=0 ) break;
69654      pItem->iCursor = pParse->nTab++;
69655      if( pItem->pSelect ){
69656        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
69657      }
69658    }
69659  }
69660}
69661
69662/*
69663** Delete an entire SrcList including all its substructure.
69664*/
69665SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
69666  int i;
69667  struct SrcList_item *pItem;
69668  if( pList==0 ) return;
69669  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
69670    sqlite3DbFree(db, pItem->zDatabase);
69671    sqlite3DbFree(db, pItem->zName);
69672    sqlite3DbFree(db, pItem->zAlias);
69673    sqlite3DbFree(db, pItem->zIndex);
69674    sqlite3DeleteTable(pItem->pTab);
69675    sqlite3SelectDelete(db, pItem->pSelect);
69676    sqlite3ExprDelete(db, pItem->pOn);
69677    sqlite3IdListDelete(db, pItem->pUsing);
69678  }
69679  sqlite3DbFree(db, pList);
69680}
69681
69682/*
69683** This routine is called by the parser to add a new term to the
69684** end of a growing FROM clause.  The "p" parameter is the part of
69685** the FROM clause that has already been constructed.  "p" is NULL
69686** if this is the first term of the FROM clause.  pTable and pDatabase
69687** are the name of the table and database named in the FROM clause term.
69688** pDatabase is NULL if the database name qualifier is missing - the
69689** usual case.  If the term has a alias, then pAlias points to the
69690** alias token.  If the term is a subquery, then pSubquery is the
69691** SELECT statement that the subquery encodes.  The pTable and
69692** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
69693** parameters are the content of the ON and USING clauses.
69694**
69695** Return a new SrcList which encodes is the FROM with the new
69696** term added.
69697*/
69698SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
69699  Parse *pParse,          /* Parsing context */
69700  SrcList *p,             /* The left part of the FROM clause already seen */
69701  Token *pTable,          /* Name of the table to add to the FROM clause */
69702  Token *pDatabase,       /* Name of the database containing pTable */
69703  Token *pAlias,          /* The right-hand side of the AS subexpression */
69704  Select *pSubquery,      /* A subquery used in place of a table name */
69705  Expr *pOn,              /* The ON clause of a join */
69706  IdList *pUsing          /* The USING clause of a join */
69707){
69708  struct SrcList_item *pItem;
69709  sqlite3 *db = pParse->db;
69710  if( !p && (pOn || pUsing) ){
69711    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
69712      (pOn ? "ON" : "USING")
69713    );
69714    goto append_from_error;
69715  }
69716  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
69717  if( p==0 || NEVER(p->nSrc==0) ){
69718    goto append_from_error;
69719  }
69720  pItem = &p->a[p->nSrc-1];
69721  assert( pAlias!=0 );
69722  if( pAlias->n ){
69723    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
69724  }
69725  pItem->pSelect = pSubquery;
69726  pItem->pOn = pOn;
69727  pItem->pUsing = pUsing;
69728  return p;
69729
69730 append_from_error:
69731  assert( p==0 );
69732  sqlite3ExprDelete(db, pOn);
69733  sqlite3IdListDelete(db, pUsing);
69734  sqlite3SelectDelete(db, pSubquery);
69735  return 0;
69736}
69737
69738/*
69739** Add an INDEXED BY or NOT INDEXED clause to the most recently added
69740** element of the source-list passed as the second argument.
69741*/
69742SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
69743  assert( pIndexedBy!=0 );
69744  if( p && ALWAYS(p->nSrc>0) ){
69745    struct SrcList_item *pItem = &p->a[p->nSrc-1];
69746    assert( pItem->notIndexed==0 && pItem->zIndex==0 );
69747    if( pIndexedBy->n==1 && !pIndexedBy->z ){
69748      /* A "NOT INDEXED" clause was supplied. See parse.y
69749      ** construct "indexed_opt" for details. */
69750      pItem->notIndexed = 1;
69751    }else{
69752      pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
69753    }
69754  }
69755}
69756
69757/*
69758** When building up a FROM clause in the parser, the join operator
69759** is initially attached to the left operand.  But the code generator
69760** expects the join operator to be on the right operand.  This routine
69761** Shifts all join operators from left to right for an entire FROM
69762** clause.
69763**
69764** Example: Suppose the join is like this:
69765**
69766**           A natural cross join B
69767**
69768** The operator is "natural cross join".  The A and B operands are stored
69769** in p->a[0] and p->a[1], respectively.  The parser initially stores the
69770** operator with A.  This routine shifts that operator over to B.
69771*/
69772SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
69773  if( p && p->a ){
69774    int i;
69775    for(i=p->nSrc-1; i>0; i--){
69776      p->a[i].jointype = p->a[i-1].jointype;
69777    }
69778    p->a[0].jointype = 0;
69779  }
69780}
69781
69782/*
69783** Begin a transaction
69784*/
69785SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
69786  sqlite3 *db;
69787  Vdbe *v;
69788  int i;
69789
69790  assert( pParse!=0 );
69791  db = pParse->db;
69792  assert( db!=0 );
69793/*  if( db->aDb[0].pBt==0 ) return; */
69794  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
69795    return;
69796  }
69797  v = sqlite3GetVdbe(pParse);
69798  if( !v ) return;
69799  if( type!=TK_DEFERRED ){
69800    for(i=0; i<db->nDb; i++){
69801      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
69802      sqlite3VdbeUsesBtree(v, i);
69803    }
69804  }
69805  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
69806}
69807
69808/*
69809** Commit a transaction
69810*/
69811SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
69812  sqlite3 *db;
69813  Vdbe *v;
69814
69815  assert( pParse!=0 );
69816  db = pParse->db;
69817  assert( db!=0 );
69818/*  if( db->aDb[0].pBt==0 ) return; */
69819  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
69820    return;
69821  }
69822  v = sqlite3GetVdbe(pParse);
69823  if( v ){
69824    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
69825  }
69826}
69827
69828/*
69829** Rollback a transaction
69830*/
69831SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
69832  sqlite3 *db;
69833  Vdbe *v;
69834
69835  assert( pParse!=0 );
69836  db = pParse->db;
69837  assert( db!=0 );
69838/*  if( db->aDb[0].pBt==0 ) return; */
69839  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
69840    return;
69841  }
69842  v = sqlite3GetVdbe(pParse);
69843  if( v ){
69844    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
69845  }
69846}
69847
69848/*
69849** This function is called by the parser when it parses a command to create,
69850** release or rollback an SQL savepoint.
69851*/
69852SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
69853  char *zName = sqlite3NameFromToken(pParse->db, pName);
69854  if( zName ){
69855    Vdbe *v = sqlite3GetVdbe(pParse);
69856#ifndef SQLITE_OMIT_AUTHORIZATION
69857    static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
69858    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
69859#endif
69860    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
69861      sqlite3DbFree(pParse->db, zName);
69862      return;
69863    }
69864    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
69865  }
69866}
69867
69868/*
69869** Make sure the TEMP database is open and available for use.  Return
69870** the number of errors.  Leave any error messages in the pParse structure.
69871*/
69872SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
69873  sqlite3 *db = pParse->db;
69874  if( db->aDb[1].pBt==0 && !pParse->explain ){
69875    int rc;
69876    static const int flags =
69877          SQLITE_OPEN_READWRITE |
69878          SQLITE_OPEN_CREATE |
69879          SQLITE_OPEN_EXCLUSIVE |
69880          SQLITE_OPEN_DELETEONCLOSE |
69881          SQLITE_OPEN_TEMP_DB;
69882
69883    rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
69884                                 &db->aDb[1].pBt);
69885    if( rc!=SQLITE_OK ){
69886      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
69887        "file for storing temporary tables");
69888      pParse->rc = rc;
69889      return 1;
69890    }
69891    assert( db->aDb[1].pSchema );
69892    sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
69893                            db->dfltJournalMode);
69894  }
69895  return 0;
69896}
69897
69898/*
69899** Generate VDBE code that will verify the schema cookie and start
69900** a read-transaction for all named database files.
69901**
69902** It is important that all schema cookies be verified and all
69903** read transactions be started before anything else happens in
69904** the VDBE program.  But this routine can be called after much other
69905** code has been generated.  So here is what we do:
69906**
69907** The first time this routine is called, we code an OP_Goto that
69908** will jump to a subroutine at the end of the program.  Then we
69909** record every database that needs its schema verified in the
69910** pParse->cookieMask field.  Later, after all other code has been
69911** generated, the subroutine that does the cookie verifications and
69912** starts the transactions will be coded and the OP_Goto P2 value
69913** will be made to point to that subroutine.  The generation of the
69914** cookie verification subroutine code happens in sqlite3FinishCoding().
69915**
69916** If iDb<0 then code the OP_Goto only - don't set flag to verify the
69917** schema on any databases.  This can be used to position the OP_Goto
69918** early in the code, before we know if any database tables will be used.
69919*/
69920SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
69921  Parse *pToplevel = sqlite3ParseToplevel(pParse);
69922
69923  if( pToplevel->cookieGoto==0 ){
69924    Vdbe *v = sqlite3GetVdbe(pToplevel);
69925    if( v==0 ) return;  /* This only happens if there was a prior error */
69926    pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
69927  }
69928  if( iDb>=0 ){
69929    sqlite3 *db = pToplevel->db;
69930    int mask;
69931
69932    assert( iDb<db->nDb );
69933    assert( db->aDb[iDb].pBt!=0 || iDb==1 );
69934    assert( iDb<SQLITE_MAX_ATTACHED+2 );
69935    mask = 1<<iDb;
69936    if( (pToplevel->cookieMask & mask)==0 ){
69937      pToplevel->cookieMask |= mask;
69938      pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
69939      if( !OMIT_TEMPDB && iDb==1 ){
69940        sqlite3OpenTempDatabase(pToplevel);
69941      }
69942    }
69943  }
69944}
69945
69946/*
69947** Generate VDBE code that prepares for doing an operation that
69948** might change the database.
69949**
69950** This routine starts a new transaction if we are not already within
69951** a transaction.  If we are already within a transaction, then a checkpoint
69952** is set if the setStatement parameter is true.  A checkpoint should
69953** be set for operations that might fail (due to a constraint) part of
69954** the way through and which will need to undo some writes without having to
69955** rollback the whole transaction.  For operations where all constraints
69956** can be checked before any changes are made to the database, it is never
69957** necessary to undo a write and the checkpoint should not be set.
69958*/
69959SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
69960  Parse *pToplevel = sqlite3ParseToplevel(pParse);
69961  sqlite3CodeVerifySchema(pParse, iDb);
69962  pToplevel->writeMask |= 1<<iDb;
69963  pToplevel->isMultiWrite |= setStatement;
69964}
69965
69966/*
69967** Indicate that the statement currently under construction might write
69968** more than one entry (example: deleting one row then inserting another,
69969** inserting multiple rows in a table, or inserting a row and index entries.)
69970** If an abort occurs after some of these writes have completed, then it will
69971** be necessary to undo the completed writes.
69972*/
69973SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
69974  Parse *pToplevel = sqlite3ParseToplevel(pParse);
69975  pToplevel->isMultiWrite = 1;
69976}
69977
69978/*
69979** The code generator calls this routine if is discovers that it is
69980** possible to abort a statement prior to completion.  In order to
69981** perform this abort without corrupting the database, we need to make
69982** sure that the statement is protected by a statement transaction.
69983**
69984** Technically, we only need to set the mayAbort flag if the
69985** isMultiWrite flag was previously set.  There is a time dependency
69986** such that the abort must occur after the multiwrite.  This makes
69987** some statements involving the REPLACE conflict resolution algorithm
69988** go a little faster.  But taking advantage of this time dependency
69989** makes it more difficult to prove that the code is correct (in
69990** particular, it prevents us from writing an effective
69991** implementation of sqlite3AssertMayAbort()) and so we have chosen
69992** to take the safe route and skip the optimization.
69993*/
69994SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
69995  Parse *pToplevel = sqlite3ParseToplevel(pParse);
69996  pToplevel->mayAbort = 1;
69997}
69998
69999/*
70000** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
70001** error. The onError parameter determines which (if any) of the statement
70002** and/or current transaction is rolled back.
70003*/
70004SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
70005  Vdbe *v = sqlite3GetVdbe(pParse);
70006  if( onError==OE_Abort ){
70007    sqlite3MayAbort(pParse);
70008  }
70009  sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
70010}
70011
70012/*
70013** Check to see if pIndex uses the collating sequence pColl.  Return
70014** true if it does and false if it does not.
70015*/
70016#ifndef SQLITE_OMIT_REINDEX
70017static int collationMatch(const char *zColl, Index *pIndex){
70018  int i;
70019  assert( zColl!=0 );
70020  for(i=0; i<pIndex->nColumn; i++){
70021    const char *z = pIndex->azColl[i];
70022    assert( z!=0 );
70023    if( 0==sqlite3StrICmp(z, zColl) ){
70024      return 1;
70025    }
70026  }
70027  return 0;
70028}
70029#endif
70030
70031/*
70032** Recompute all indices of pTab that use the collating sequence pColl.
70033** If pColl==0 then recompute all indices of pTab.
70034*/
70035#ifndef SQLITE_OMIT_REINDEX
70036static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
70037  Index *pIndex;              /* An index associated with pTab */
70038
70039  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
70040    if( zColl==0 || collationMatch(zColl, pIndex) ){
70041      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
70042      sqlite3BeginWriteOperation(pParse, 0, iDb);
70043      sqlite3RefillIndex(pParse, pIndex, -1);
70044    }
70045  }
70046}
70047#endif
70048
70049/*
70050** Recompute all indices of all tables in all databases where the
70051** indices use the collating sequence pColl.  If pColl==0 then recompute
70052** all indices everywhere.
70053*/
70054#ifndef SQLITE_OMIT_REINDEX
70055static void reindexDatabases(Parse *pParse, char const *zColl){
70056  Db *pDb;                    /* A single database */
70057  int iDb;                    /* The database index number */
70058  sqlite3 *db = pParse->db;   /* The database connection */
70059  HashElem *k;                /* For looping over tables in pDb */
70060  Table *pTab;                /* A table in the database */
70061
70062  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
70063    assert( pDb!=0 );
70064    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
70065      pTab = (Table*)sqliteHashData(k);
70066      reindexTable(pParse, pTab, zColl);
70067    }
70068  }
70069}
70070#endif
70071
70072/*
70073** Generate code for the REINDEX command.
70074**
70075**        REINDEX                            -- 1
70076**        REINDEX  <collation>               -- 2
70077**        REINDEX  ?<database>.?<tablename>  -- 3
70078**        REINDEX  ?<database>.?<indexname>  -- 4
70079**
70080** Form 1 causes all indices in all attached databases to be rebuilt.
70081** Form 2 rebuilds all indices in all databases that use the named
70082** collating function.  Forms 3 and 4 rebuild the named index or all
70083** indices associated with the named table.
70084*/
70085#ifndef SQLITE_OMIT_REINDEX
70086SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
70087  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
70088  char *z;                    /* Name of a table or index */
70089  const char *zDb;            /* Name of the database */
70090  Table *pTab;                /* A table in the database */
70091  Index *pIndex;              /* An index associated with pTab */
70092  int iDb;                    /* The database index number */
70093  sqlite3 *db = pParse->db;   /* The database connection */
70094  Token *pObjName;            /* Name of the table or index to be reindexed */
70095
70096  /* Read the database schema. If an error occurs, leave an error message
70097  ** and code in pParse and return NULL. */
70098  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
70099    return;
70100  }
70101
70102  if( pName1==0 ){
70103    reindexDatabases(pParse, 0);
70104    return;
70105  }else if( NEVER(pName2==0) || pName2->z==0 ){
70106    char *zColl;
70107    assert( pName1->z );
70108    zColl = sqlite3NameFromToken(pParse->db, pName1);
70109    if( !zColl ) return;
70110    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
70111    if( pColl ){
70112      reindexDatabases(pParse, zColl);
70113      sqlite3DbFree(db, zColl);
70114      return;
70115    }
70116    sqlite3DbFree(db, zColl);
70117  }
70118  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
70119  if( iDb<0 ) return;
70120  z = sqlite3NameFromToken(db, pObjName);
70121  if( z==0 ) return;
70122  zDb = db->aDb[iDb].zName;
70123  pTab = sqlite3FindTable(db, z, zDb);
70124  if( pTab ){
70125    reindexTable(pParse, pTab, 0);
70126    sqlite3DbFree(db, z);
70127    return;
70128  }
70129  pIndex = sqlite3FindIndex(db, z, zDb);
70130  sqlite3DbFree(db, z);
70131  if( pIndex ){
70132    sqlite3BeginWriteOperation(pParse, 0, iDb);
70133    sqlite3RefillIndex(pParse, pIndex, -1);
70134    return;
70135  }
70136  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
70137}
70138#endif
70139
70140/*
70141** Return a dynamicly allocated KeyInfo structure that can be used
70142** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
70143**
70144** If successful, a pointer to the new structure is returned. In this case
70145** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
70146** pointer. If an error occurs (out of memory or missing collation
70147** sequence), NULL is returned and the state of pParse updated to reflect
70148** the error.
70149*/
70150SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
70151  int i;
70152  int nCol = pIdx->nColumn;
70153  int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
70154  sqlite3 *db = pParse->db;
70155  KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
70156
70157  if( pKey ){
70158    pKey->db = pParse->db;
70159    pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
70160    assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
70161    for(i=0; i<nCol; i++){
70162      char *zColl = pIdx->azColl[i];
70163      assert( zColl );
70164      pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
70165      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
70166    }
70167    pKey->nField = (u16)nCol;
70168  }
70169
70170  if( pParse->nErr ){
70171    sqlite3DbFree(db, pKey);
70172    pKey = 0;
70173  }
70174  return pKey;
70175}
70176
70177/************** End of build.c ***********************************************/
70178/************** Begin file callback.c ****************************************/
70179/*
70180** 2005 May 23
70181**
70182** The author disclaims copyright to this source code.  In place of
70183** a legal notice, here is a blessing:
70184**
70185**    May you do good and not evil.
70186**    May you find forgiveness for yourself and forgive others.
70187**    May you share freely, never taking more than you give.
70188**
70189*************************************************************************
70190**
70191** This file contains functions used to access the internal hash tables
70192** of user defined functions and collation sequences.
70193*/
70194
70195
70196/*
70197** Invoke the 'collation needed' callback to request a collation sequence
70198** in the encoding enc of name zName, length nName.
70199*/
70200static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
70201  assert( !db->xCollNeeded || !db->xCollNeeded16 );
70202  if( db->xCollNeeded ){
70203    char *zExternal = sqlite3DbStrDup(db, zName);
70204    if( !zExternal ) return;
70205    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
70206    sqlite3DbFree(db, zExternal);
70207  }
70208#ifndef SQLITE_OMIT_UTF16
70209  if( db->xCollNeeded16 ){
70210    char const *zExternal;
70211    sqlite3_value *pTmp = sqlite3ValueNew(db);
70212    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
70213    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
70214    if( zExternal ){
70215      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
70216    }
70217    sqlite3ValueFree(pTmp);
70218  }
70219#endif
70220}
70221
70222/*
70223** This routine is called if the collation factory fails to deliver a
70224** collation function in the best encoding but there may be other versions
70225** of this collation function (for other text encodings) available. Use one
70226** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
70227** possible.
70228*/
70229static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
70230  CollSeq *pColl2;
70231  char *z = pColl->zName;
70232  int i;
70233  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
70234  for(i=0; i<3; i++){
70235    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
70236    if( pColl2->xCmp!=0 ){
70237      memcpy(pColl, pColl2, sizeof(CollSeq));
70238      pColl->xDel = 0;         /* Do not copy the destructor */
70239      return SQLITE_OK;
70240    }
70241  }
70242  return SQLITE_ERROR;
70243}
70244
70245/*
70246** This function is responsible for invoking the collation factory callback
70247** or substituting a collation sequence of a different encoding when the
70248** requested collation sequence is not available in the desired encoding.
70249**
70250** If it is not NULL, then pColl must point to the database native encoding
70251** collation sequence with name zName, length nName.
70252**
70253** The return value is either the collation sequence to be used in database
70254** db for collation type name zName, length nName, or NULL, if no collation
70255** sequence can be found.
70256**
70257** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
70258*/
70259SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
70260  sqlite3* db,          /* The database connection */
70261  u8 enc,               /* The desired encoding for the collating sequence */
70262  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
70263  const char *zName     /* Collating sequence name */
70264){
70265  CollSeq *p;
70266
70267  p = pColl;
70268  if( !p ){
70269    p = sqlite3FindCollSeq(db, enc, zName, 0);
70270  }
70271  if( !p || !p->xCmp ){
70272    /* No collation sequence of this type for this encoding is registered.
70273    ** Call the collation factory to see if it can supply us with one.
70274    */
70275    callCollNeeded(db, enc, zName);
70276    p = sqlite3FindCollSeq(db, enc, zName, 0);
70277  }
70278  if( p && !p->xCmp && synthCollSeq(db, p) ){
70279    p = 0;
70280  }
70281  assert( !p || p->xCmp );
70282  return p;
70283}
70284
70285/*
70286** This routine is called on a collation sequence before it is used to
70287** check that it is defined. An undefined collation sequence exists when
70288** a database is loaded that contains references to collation sequences
70289** that have not been defined by sqlite3_create_collation() etc.
70290**
70291** If required, this routine calls the 'collation needed' callback to
70292** request a definition of the collating sequence. If this doesn't work,
70293** an equivalent collating sequence that uses a text encoding different
70294** from the main database is substituted, if one is available.
70295*/
70296SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
70297  if( pColl ){
70298    const char *zName = pColl->zName;
70299    sqlite3 *db = pParse->db;
70300    CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
70301    if( !p ){
70302      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
70303      pParse->nErr++;
70304      return SQLITE_ERROR;
70305    }
70306    assert( p==pColl );
70307  }
70308  return SQLITE_OK;
70309}
70310
70311
70312
70313/*
70314** Locate and return an entry from the db.aCollSeq hash table. If the entry
70315** specified by zName and nName is not found and parameter 'create' is
70316** true, then create a new entry. Otherwise return NULL.
70317**
70318** Each pointer stored in the sqlite3.aCollSeq hash table contains an
70319** array of three CollSeq structures. The first is the collation sequence
70320** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
70321**
70322** Stored immediately after the three collation sequences is a copy of
70323** the collation sequence name. A pointer to this string is stored in
70324** each collation sequence structure.
70325*/
70326static CollSeq *findCollSeqEntry(
70327  sqlite3 *db,          /* Database connection */
70328  const char *zName,    /* Name of the collating sequence */
70329  int create            /* Create a new entry if true */
70330){
70331  CollSeq *pColl;
70332  int nName = sqlite3Strlen30(zName);
70333  pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
70334
70335  if( 0==pColl && create ){
70336    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
70337    if( pColl ){
70338      CollSeq *pDel = 0;
70339      pColl[0].zName = (char*)&pColl[3];
70340      pColl[0].enc = SQLITE_UTF8;
70341      pColl[1].zName = (char*)&pColl[3];
70342      pColl[1].enc = SQLITE_UTF16LE;
70343      pColl[2].zName = (char*)&pColl[3];
70344      pColl[2].enc = SQLITE_UTF16BE;
70345      memcpy(pColl[0].zName, zName, nName);
70346      pColl[0].zName[nName] = 0;
70347      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
70348
70349      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
70350      ** return the pColl pointer to be deleted (because it wasn't added
70351      ** to the hash table).
70352      */
70353      assert( pDel==0 || pDel==pColl );
70354      if( pDel!=0 ){
70355        db->mallocFailed = 1;
70356        sqlite3DbFree(db, pDel);
70357        pColl = 0;
70358      }
70359    }
70360  }
70361  return pColl;
70362}
70363
70364/*
70365** Parameter zName points to a UTF-8 encoded string nName bytes long.
70366** Return the CollSeq* pointer for the collation sequence named zName
70367** for the encoding 'enc' from the database 'db'.
70368**
70369** If the entry specified is not found and 'create' is true, then create a
70370** new entry.  Otherwise return NULL.
70371**
70372** A separate function sqlite3LocateCollSeq() is a wrapper around
70373** this routine.  sqlite3LocateCollSeq() invokes the collation factory
70374** if necessary and generates an error message if the collating sequence
70375** cannot be found.
70376**
70377** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
70378*/
70379SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
70380  sqlite3 *db,
70381  u8 enc,
70382  const char *zName,
70383  int create
70384){
70385  CollSeq *pColl;
70386  if( zName ){
70387    pColl = findCollSeqEntry(db, zName, create);
70388  }else{
70389    pColl = db->pDfltColl;
70390  }
70391  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
70392  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
70393  if( pColl ) pColl += enc-1;
70394  return pColl;
70395}
70396
70397/* During the search for the best function definition, this procedure
70398** is called to test how well the function passed as the first argument
70399** matches the request for a function with nArg arguments in a system
70400** that uses encoding enc. The value returned indicates how well the
70401** request is matched. A higher value indicates a better match.
70402**
70403** The returned value is always between 0 and 6, as follows:
70404**
70405** 0: Not a match, or if nArg<0 and the function is has no implementation.
70406** 1: A variable arguments function that prefers UTF-8 when a UTF-16
70407**    encoding is requested, or vice versa.
70408** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
70409**    requested, or vice versa.
70410** 3: A variable arguments function using the same text encoding.
70411** 4: A function with the exact number of arguments requested that
70412**    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
70413** 5: A function with the exact number of arguments requested that
70414**    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
70415** 6: An exact match.
70416**
70417*/
70418static int matchQuality(FuncDef *p, int nArg, u8 enc){
70419  int match = 0;
70420  if( p->nArg==-1 || p->nArg==nArg
70421   || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
70422  ){
70423    match = 1;
70424    if( p->nArg==nArg || nArg==-1 ){
70425      match = 4;
70426    }
70427    if( enc==p->iPrefEnc ){
70428      match += 2;
70429    }
70430    else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
70431             (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
70432      match += 1;
70433    }
70434  }
70435  return match;
70436}
70437
70438/*
70439** Search a FuncDefHash for a function with the given name.  Return
70440** a pointer to the matching FuncDef if found, or 0 if there is no match.
70441*/
70442static FuncDef *functionSearch(
70443  FuncDefHash *pHash,  /* Hash table to search */
70444  int h,               /* Hash of the name */
70445  const char *zFunc,   /* Name of function */
70446  int nFunc            /* Number of bytes in zFunc */
70447){
70448  FuncDef *p;
70449  for(p=pHash->a[h]; p; p=p->pHash){
70450    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
70451      return p;
70452    }
70453  }
70454  return 0;
70455}
70456
70457/*
70458** Insert a new FuncDef into a FuncDefHash hash table.
70459*/
70460SQLITE_PRIVATE void sqlite3FuncDefInsert(
70461  FuncDefHash *pHash,  /* The hash table into which to insert */
70462  FuncDef *pDef        /* The function definition to insert */
70463){
70464  FuncDef *pOther;
70465  int nName = sqlite3Strlen30(pDef->zName);
70466  u8 c1 = (u8)pDef->zName[0];
70467  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
70468  pOther = functionSearch(pHash, h, pDef->zName, nName);
70469  if( pOther ){
70470    assert( pOther!=pDef && pOther->pNext!=pDef );
70471    pDef->pNext = pOther->pNext;
70472    pOther->pNext = pDef;
70473  }else{
70474    pDef->pNext = 0;
70475    pDef->pHash = pHash->a[h];
70476    pHash->a[h] = pDef;
70477  }
70478}
70479
70480
70481
70482/*
70483** Locate a user function given a name, a number of arguments and a flag
70484** indicating whether the function prefers UTF-16 over UTF-8.  Return a
70485** pointer to the FuncDef structure that defines that function, or return
70486** NULL if the function does not exist.
70487**
70488** If the createFlag argument is true, then a new (blank) FuncDef
70489** structure is created and liked into the "db" structure if a
70490** no matching function previously existed.  When createFlag is true
70491** and the nArg parameter is -1, then only a function that accepts
70492** any number of arguments will be returned.
70493**
70494** If createFlag is false and nArg is -1, then the first valid
70495** function found is returned.  A function is valid if either xFunc
70496** or xStep is non-zero.
70497**
70498** If createFlag is false, then a function with the required name and
70499** number of arguments may be returned even if the eTextRep flag does not
70500** match that requested.
70501*/
70502SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
70503  sqlite3 *db,       /* An open database */
70504  const char *zName, /* Name of the function.  Not null-terminated */
70505  int nName,         /* Number of characters in the name */
70506  int nArg,          /* Number of arguments.  -1 means any number */
70507  u8 enc,            /* Preferred text encoding */
70508  int createFlag     /* Create new entry if true and does not otherwise exist */
70509){
70510  FuncDef *p;         /* Iterator variable */
70511  FuncDef *pBest = 0; /* Best match found so far */
70512  int bestScore = 0;  /* Score of best match */
70513  int h;              /* Hash value */
70514
70515
70516  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
70517  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
70518
70519  /* First search for a match amongst the application-defined functions.
70520  */
70521  p = functionSearch(&db->aFunc, h, zName, nName);
70522  while( p ){
70523    int score = matchQuality(p, nArg, enc);
70524    if( score>bestScore ){
70525      pBest = p;
70526      bestScore = score;
70527    }
70528    p = p->pNext;
70529  }
70530
70531  /* If no match is found, search the built-in functions.
70532  **
70533  ** Except, if createFlag is true, that means that we are trying to
70534  ** install a new function.  Whatever FuncDef structure is returned will
70535  ** have fields overwritten with new information appropriate for the
70536  ** new function.  But the FuncDefs for built-in functions are read-only.
70537  ** So we must not search for built-ins when creating a new function.
70538  */
70539  if( !createFlag && !pBest ){
70540    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
70541    p = functionSearch(pHash, h, zName, nName);
70542    while( p ){
70543      int score = matchQuality(p, nArg, enc);
70544      if( score>bestScore ){
70545        pBest = p;
70546        bestScore = score;
70547      }
70548      p = p->pNext;
70549    }
70550  }
70551
70552  /* If the createFlag parameter is true and the search did not reveal an
70553  ** exact match for the name, number of arguments and encoding, then add a
70554  ** new entry to the hash table and return it.
70555  */
70556  if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
70557      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
70558    pBest->zName = (char *)&pBest[1];
70559    pBest->nArg = (u16)nArg;
70560    pBest->iPrefEnc = enc;
70561    memcpy(pBest->zName, zName, nName);
70562    pBest->zName[nName] = 0;
70563    sqlite3FuncDefInsert(&db->aFunc, pBest);
70564  }
70565
70566  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
70567    return pBest;
70568  }
70569  return 0;
70570}
70571
70572/*
70573** Free all resources held by the schema structure. The void* argument points
70574** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
70575** pointer itself, it just cleans up subsiduary resources (i.e. the contents
70576** of the schema hash tables).
70577**
70578** The Schema.cache_size variable is not cleared.
70579*/
70580SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
70581  Hash temp1;
70582  Hash temp2;
70583  HashElem *pElem;
70584  Schema *pSchema = (Schema *)p;
70585
70586  temp1 = pSchema->tblHash;
70587  temp2 = pSchema->trigHash;
70588  sqlite3HashInit(&pSchema->trigHash);
70589  sqlite3HashClear(&pSchema->idxHash);
70590  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
70591    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
70592  }
70593  sqlite3HashClear(&temp2);
70594  sqlite3HashInit(&pSchema->tblHash);
70595  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
70596    Table *pTab = sqliteHashData(pElem);
70597    assert( pTab->dbMem==0 );
70598    sqlite3DeleteTable(pTab);
70599  }
70600  sqlite3HashClear(&temp1);
70601  sqlite3HashClear(&pSchema->fkeyHash);
70602  pSchema->pSeqTab = 0;
70603  pSchema->flags &= ~DB_SchemaLoaded;
70604}
70605
70606/*
70607** Find and return the schema associated with a BTree.  Create
70608** a new one if necessary.
70609*/
70610SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
70611  Schema * p;
70612  if( pBt ){
70613    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
70614  }else{
70615    p = (Schema *)sqlite3MallocZero(sizeof(Schema));
70616  }
70617  if( !p ){
70618    db->mallocFailed = 1;
70619  }else if ( 0==p->file_format ){
70620    sqlite3HashInit(&p->tblHash);
70621    sqlite3HashInit(&p->idxHash);
70622    sqlite3HashInit(&p->trigHash);
70623    sqlite3HashInit(&p->fkeyHash);
70624    p->enc = SQLITE_UTF8;
70625  }
70626  return p;
70627}
70628
70629/************** End of callback.c ********************************************/
70630/************** Begin file delete.c ******************************************/
70631/*
70632** 2001 September 15
70633**
70634** The author disclaims copyright to this source code.  In place of
70635** a legal notice, here is a blessing:
70636**
70637**    May you do good and not evil.
70638**    May you find forgiveness for yourself and forgive others.
70639**    May you share freely, never taking more than you give.
70640**
70641*************************************************************************
70642** This file contains C code routines that are called by the parser
70643** in order to generate code for DELETE FROM statements.
70644*/
70645
70646/*
70647** Look up every table that is named in pSrc.  If any table is not found,
70648** add an error message to pParse->zErrMsg and return NULL.  If all tables
70649** are found, return a pointer to the last table.
70650*/
70651SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
70652  struct SrcList_item *pItem = pSrc->a;
70653  Table *pTab;
70654  assert( pItem && pSrc->nSrc==1 );
70655  pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
70656  sqlite3DeleteTable(pItem->pTab);
70657  pItem->pTab = pTab;
70658  if( pTab ){
70659    pTab->nRef++;
70660  }
70661  if( sqlite3IndexedByLookup(pParse, pItem) ){
70662    pTab = 0;
70663  }
70664  return pTab;
70665}
70666
70667/*
70668** Check to make sure the given table is writable.  If it is not
70669** writable, generate an error message and return 1.  If it is
70670** writable return 0;
70671*/
70672SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
70673  /* A table is not writable under the following circumstances:
70674  **
70675  **   1) It is a virtual table and no implementation of the xUpdate method
70676  **      has been provided, or
70677  **   2) It is a system table (i.e. sqlite_master), this call is not
70678  **      part of a nested parse and writable_schema pragma has not
70679  **      been specified.
70680  **
70681  ** In either case leave an error message in pParse and return non-zero.
70682  */
70683  if( ( IsVirtual(pTab)
70684     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
70685   || ( (pTab->tabFlags & TF_Readonly)!=0
70686     && (pParse->db->flags & SQLITE_WriteSchema)==0
70687     && pParse->nested==0 )
70688  ){
70689    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
70690    return 1;
70691  }
70692
70693#ifndef SQLITE_OMIT_VIEW
70694  if( !viewOk && pTab->pSelect ){
70695    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
70696    return 1;
70697  }
70698#endif
70699  return 0;
70700}
70701
70702
70703#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
70704/*
70705** Evaluate a view and store its result in an ephemeral table.  The
70706** pWhere argument is an optional WHERE clause that restricts the
70707** set of rows in the view that are to be added to the ephemeral table.
70708*/
70709SQLITE_PRIVATE void sqlite3MaterializeView(
70710  Parse *pParse,       /* Parsing context */
70711  Table *pView,        /* View definition */
70712  Expr *pWhere,        /* Optional WHERE clause to be added */
70713  int iCur             /* Cursor number for ephemerial table */
70714){
70715  SelectDest dest;
70716  Select *pDup;
70717  sqlite3 *db = pParse->db;
70718
70719  pDup = sqlite3SelectDup(db, pView->pSelect, 0);
70720  if( pWhere ){
70721    SrcList *pFrom;
70722
70723    pWhere = sqlite3ExprDup(db, pWhere, 0);
70724    pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
70725    if( pFrom ){
70726      assert( pFrom->nSrc==1 );
70727      pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
70728      pFrom->a[0].pSelect = pDup;
70729      assert( pFrom->a[0].pOn==0 );
70730      assert( pFrom->a[0].pUsing==0 );
70731    }else{
70732      sqlite3SelectDelete(db, pDup);
70733    }
70734    pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
70735  }
70736  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
70737  sqlite3Select(pParse, pDup, &dest);
70738  sqlite3SelectDelete(db, pDup);
70739}
70740#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
70741
70742#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
70743/*
70744** Generate an expression tree to implement the WHERE, ORDER BY,
70745** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
70746**
70747**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
70748**                            \__________________________/
70749**                               pLimitWhere (pInClause)
70750*/
70751SQLITE_PRIVATE Expr *sqlite3LimitWhere(
70752  Parse *pParse,               /* The parser context */
70753  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
70754  Expr *pWhere,                /* The WHERE clause.  May be null */
70755  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
70756  Expr *pLimit,                /* The LIMIT clause.  May be null */
70757  Expr *pOffset,               /* The OFFSET clause.  May be null */
70758  char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
70759){
70760  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
70761  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
70762  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
70763  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
70764  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
70765  Select *pSelect = NULL;      /* Complete SELECT tree */
70766
70767  /* Check that there isn't an ORDER BY without a LIMIT clause.
70768  */
70769  if( pOrderBy && (pLimit == 0) ) {
70770    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
70771    pParse->parseError = 1;
70772    goto limit_where_cleanup_2;
70773  }
70774
70775  /* We only need to generate a select expression if there
70776  ** is a limit/offset term to enforce.
70777  */
70778  if( pLimit == 0 ) {
70779    /* if pLimit is null, pOffset will always be null as well. */
70780    assert( pOffset == 0 );
70781    return pWhere;
70782  }
70783
70784  /* Generate a select expression tree to enforce the limit/offset
70785  ** term for the DELETE or UPDATE statement.  For example:
70786  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
70787  ** becomes:
70788  **   DELETE FROM table_a WHERE rowid IN (
70789  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
70790  **   );
70791  */
70792
70793  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
70794  if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
70795  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
70796  if( pEList == 0 ) goto limit_where_cleanup_2;
70797
70798  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
70799  ** and the SELECT subtree. */
70800  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
70801  if( pSelectSrc == 0 ) {
70802    sqlite3ExprListDelete(pParse->db, pEList);
70803    goto limit_where_cleanup_2;
70804  }
70805
70806  /* generate the SELECT expression tree. */
70807  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
70808                             pOrderBy,0,pLimit,pOffset);
70809  if( pSelect == 0 ) return 0;
70810
70811  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
70812  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
70813  if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
70814  pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
70815  if( pInClause == 0 ) goto limit_where_cleanup_1;
70816
70817  pInClause->x.pSelect = pSelect;
70818  pInClause->flags |= EP_xIsSelect;
70819  sqlite3ExprSetHeight(pParse, pInClause);
70820  return pInClause;
70821
70822  /* something went wrong. clean up anything allocated. */
70823limit_where_cleanup_1:
70824  sqlite3SelectDelete(pParse->db, pSelect);
70825  return 0;
70826
70827limit_where_cleanup_2:
70828  sqlite3ExprDelete(pParse->db, pWhere);
70829  sqlite3ExprListDelete(pParse->db, pOrderBy);
70830  sqlite3ExprDelete(pParse->db, pLimit);
70831  sqlite3ExprDelete(pParse->db, pOffset);
70832  return 0;
70833}
70834#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
70835
70836/*
70837** Generate code for a DELETE FROM statement.
70838**
70839**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
70840**                 \________/       \________________/
70841**                  pTabList              pWhere
70842*/
70843SQLITE_PRIVATE void sqlite3DeleteFrom(
70844  Parse *pParse,         /* The parser context */
70845  SrcList *pTabList,     /* The table from which we should delete things */
70846  Expr *pWhere           /* The WHERE clause.  May be null */
70847){
70848  Vdbe *v;               /* The virtual database engine */
70849  Table *pTab;           /* The table from which records will be deleted */
70850  const char *zDb;       /* Name of database holding pTab */
70851  int end, addr = 0;     /* A couple addresses of generated code */
70852  int i;                 /* Loop counter */
70853  WhereInfo *pWInfo;     /* Information about the WHERE clause */
70854  Index *pIdx;           /* For looping over indices of the table */
70855  int iCur;              /* VDBE Cursor number for pTab */
70856  sqlite3 *db;           /* Main database structure */
70857  AuthContext sContext;  /* Authorization context */
70858  NameContext sNC;       /* Name context to resolve expressions in */
70859  int iDb;               /* Database number */
70860  int memCnt = -1;       /* Memory cell used for change counting */
70861  int rcauth;            /* Value returned by authorization callback */
70862
70863#ifndef SQLITE_OMIT_TRIGGER
70864  int isView;                  /* True if attempting to delete from a view */
70865  Trigger *pTrigger;           /* List of table triggers, if required */
70866#endif
70867
70868  memset(&sContext, 0, sizeof(sContext));
70869  db = pParse->db;
70870  if( pParse->nErr || db->mallocFailed ){
70871    goto delete_from_cleanup;
70872  }
70873  assert( pTabList->nSrc==1 );
70874
70875  /* Locate the table which we want to delete.  This table has to be
70876  ** put in an SrcList structure because some of the subroutines we
70877  ** will be calling are designed to work with multiple tables and expect
70878  ** an SrcList* parameter instead of just a Table* parameter.
70879  */
70880  pTab = sqlite3SrcListLookup(pParse, pTabList);
70881  if( pTab==0 )  goto delete_from_cleanup;
70882
70883  /* Figure out if we have any triggers and if the table being
70884  ** deleted from is a view
70885  */
70886#ifndef SQLITE_OMIT_TRIGGER
70887  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
70888  isView = pTab->pSelect!=0;
70889#else
70890# define pTrigger 0
70891# define isView 0
70892#endif
70893#ifdef SQLITE_OMIT_VIEW
70894# undef isView
70895# define isView 0
70896#endif
70897
70898  /* If pTab is really a view, make sure it has been initialized.
70899  */
70900  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
70901    goto delete_from_cleanup;
70902  }
70903
70904  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
70905    goto delete_from_cleanup;
70906  }
70907  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
70908  assert( iDb<db->nDb );
70909  zDb = db->aDb[iDb].zName;
70910  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
70911  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
70912  if( rcauth==SQLITE_DENY ){
70913    goto delete_from_cleanup;
70914  }
70915  assert(!isView || pTrigger);
70916
70917  /* Assign  cursor number to the table and all its indices.
70918  */
70919  assert( pTabList->nSrc==1 );
70920  iCur = pTabList->a[0].iCursor = pParse->nTab++;
70921  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
70922    pParse->nTab++;
70923  }
70924
70925  /* Start the view context
70926  */
70927  if( isView ){
70928    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
70929  }
70930
70931  /* Begin generating code.
70932  */
70933  v = sqlite3GetVdbe(pParse);
70934  if( v==0 ){
70935    goto delete_from_cleanup;
70936  }
70937  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
70938  sqlite3BeginWriteOperation(pParse, 1, iDb);
70939
70940  /* If we are trying to delete from a view, realize that view into
70941  ** a ephemeral table.
70942  */
70943#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
70944  if( isView ){
70945    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
70946  }
70947#endif
70948
70949  /* Resolve the column names in the WHERE clause.
70950  */
70951  memset(&sNC, 0, sizeof(sNC));
70952  sNC.pParse = pParse;
70953  sNC.pSrcList = pTabList;
70954  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
70955    goto delete_from_cleanup;
70956  }
70957
70958  /* Initialize the counter of the number of rows deleted, if
70959  ** we are counting rows.
70960  */
70961  if( db->flags & SQLITE_CountRows ){
70962    memCnt = ++pParse->nMem;
70963    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
70964  }
70965
70966#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
70967  /* Special case: A DELETE without a WHERE clause deletes everything.
70968  ** It is easier just to erase the whole table. Prior to version 3.6.5,
70969  ** this optimization caused the row change count (the value returned by
70970  ** API function sqlite3_count_changes) to be set incorrectly.  */
70971  if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
70972   && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
70973  ){
70974    assert( !isView );
70975    sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
70976                      pTab->zName, P4_STATIC);
70977    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
70978      assert( pIdx->pSchema==pTab->pSchema );
70979      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
70980    }
70981  }else
70982#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
70983  /* The usual case: There is a WHERE clause so we have to scan through
70984  ** the table and pick which records to delete.
70985  */
70986  {
70987    int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
70988    int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
70989    int regRowid;                   /* Actual register containing rowids */
70990
70991    /* Collect rowids of every row to be deleted.
70992    */
70993    sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
70994    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
70995    if( pWInfo==0 ) goto delete_from_cleanup;
70996    regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
70997    sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
70998    if( db->flags & SQLITE_CountRows ){
70999      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
71000    }
71001    sqlite3WhereEnd(pWInfo);
71002
71003    /* Delete every item whose key was written to the list during the
71004    ** database scan.  We have to delete items after the scan is complete
71005    ** because deleting an item can change the scan order.  */
71006    end = sqlite3VdbeMakeLabel(v);
71007
71008    /* Unless this is a view, open cursors for the table we are
71009    ** deleting from and all its indices. If this is a view, then the
71010    ** only effect this statement has is to fire the INSTEAD OF
71011    ** triggers.  */
71012    if( !isView ){
71013      sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
71014    }
71015
71016    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
71017
71018    /* Delete the row */
71019#ifndef SQLITE_OMIT_VIRTUALTABLE
71020    if( IsVirtual(pTab) ){
71021      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
71022      sqlite3VtabMakeWritable(pParse, pTab);
71023      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
71024      sqlite3MayAbort(pParse);
71025    }else
71026#endif
71027    {
71028      int count = (pParse->nested==0);    /* True to count changes */
71029      sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
71030    }
71031
71032    /* End of the delete loop */
71033    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
71034    sqlite3VdbeResolveLabel(v, end);
71035
71036    /* Close the cursors open on the table and its indexes. */
71037    if( !isView && !IsVirtual(pTab) ){
71038      for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
71039        sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
71040      }
71041      sqlite3VdbeAddOp1(v, OP_Close, iCur);
71042    }
71043  }
71044
71045  /* Update the sqlite_sequence table by storing the content of the
71046  ** maximum rowid counter values recorded while inserting into
71047  ** autoincrement tables.
71048  */
71049  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
71050    sqlite3AutoincrementEnd(pParse);
71051  }
71052
71053  /* Return the number of rows that were deleted. If this routine is
71054  ** generating code because of a call to sqlite3NestedParse(), do not
71055  ** invoke the callback function.
71056  */
71057  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
71058    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
71059    sqlite3VdbeSetNumCols(v, 1);
71060    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
71061  }
71062
71063delete_from_cleanup:
71064  sqlite3AuthContextPop(&sContext);
71065  sqlite3SrcListDelete(db, pTabList);
71066  sqlite3ExprDelete(db, pWhere);
71067  return;
71068}
71069/* Make sure "isView" and other macros defined above are undefined. Otherwise
71070** thely may interfere with compilation of other functions in this file
71071** (or in another file, if this file becomes part of the amalgamation).  */
71072#ifdef isView
71073 #undef isView
71074#endif
71075#ifdef pTrigger
71076 #undef pTrigger
71077#endif
71078
71079/*
71080** This routine generates VDBE code that causes a single row of a
71081** single table to be deleted.
71082**
71083** The VDBE must be in a particular state when this routine is called.
71084** These are the requirements:
71085**
71086**   1.  A read/write cursor pointing to pTab, the table containing the row
71087**       to be deleted, must be opened as cursor number $iCur.
71088**
71089**   2.  Read/write cursors for all indices of pTab must be open as
71090**       cursor number base+i for the i-th index.
71091**
71092**   3.  The record number of the row to be deleted must be stored in
71093**       memory cell iRowid.
71094**
71095** This routine generates code to remove both the table record and all
71096** index entries that point to that record.
71097*/
71098SQLITE_PRIVATE void sqlite3GenerateRowDelete(
71099  Parse *pParse,     /* Parsing context */
71100  Table *pTab,       /* Table containing the row to be deleted */
71101  int iCur,          /* Cursor number for the table */
71102  int iRowid,        /* Memory cell that contains the rowid to delete */
71103  int count,         /* If non-zero, increment the row change counter */
71104  Trigger *pTrigger, /* List of triggers to (potentially) fire */
71105  int onconf         /* Default ON CONFLICT policy for triggers */
71106){
71107  Vdbe *v = pParse->pVdbe;        /* Vdbe */
71108  int iOld = 0;                   /* First register in OLD.* array */
71109  int iLabel;                     /* Label resolved to end of generated code */
71110
71111  /* Vdbe is guaranteed to have been allocated by this stage. */
71112  assert( v );
71113
71114  /* Seek cursor iCur to the row to delete. If this row no longer exists
71115  ** (this can happen if a trigger program has already deleted it), do
71116  ** not attempt to delete it or fire any DELETE triggers.  */
71117  iLabel = sqlite3VdbeMakeLabel(v);
71118  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
71119
71120  /* If there are any triggers to fire, allocate a range of registers to
71121  ** use for the old.* references in the triggers.  */
71122  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
71123    u32 mask;                     /* Mask of OLD.* columns in use */
71124    int iCol;                     /* Iterator used while populating OLD.* */
71125
71126    /* TODO: Could use temporary registers here. Also could attempt to
71127    ** avoid copying the contents of the rowid register.  */
71128    mask = sqlite3TriggerColmask(
71129        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
71130    );
71131    mask |= sqlite3FkOldmask(pParse, pTab);
71132    iOld = pParse->nMem+1;
71133    pParse->nMem += (1 + pTab->nCol);
71134
71135    /* Populate the OLD.* pseudo-table register array. These values will be
71136    ** used by any BEFORE and AFTER triggers that exist.  */
71137    sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
71138    for(iCol=0; iCol<pTab->nCol; iCol++){
71139      if( mask==0xffffffff || mask&(1<<iCol) ){
71140        int iTarget = iOld + iCol + 1;
71141        sqlite3VdbeAddOp3(v, OP_Column, iCur, iCol, iTarget);
71142        sqlite3ColumnDefault(v, pTab, iCol, iTarget);
71143      }
71144    }
71145
71146    /* Invoke BEFORE DELETE trigger programs. */
71147    sqlite3CodeRowTrigger(pParse, pTrigger,
71148        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
71149    );
71150
71151    /* Seek the cursor to the row to be deleted again. It may be that
71152    ** the BEFORE triggers coded above have already removed the row
71153    ** being deleted. Do not attempt to delete the row a second time, and
71154    ** do not fire AFTER triggers.  */
71155    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
71156
71157    /* Do FK processing. This call checks that any FK constraints that
71158    ** refer to this table (i.e. constraints attached to other tables)
71159    ** are not violated by deleting this row.  */
71160    sqlite3FkCheck(pParse, pTab, iOld, 0);
71161  }
71162
71163  /* Delete the index and table entries. Skip this step if pTab is really
71164  ** a view (in which case the only effect of the DELETE statement is to
71165  ** fire the INSTEAD OF triggers).  */
71166  if( pTab->pSelect==0 ){
71167    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
71168    sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
71169    if( count ){
71170      sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
71171    }
71172  }
71173
71174  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
71175  ** handle rows (possibly in other tables) that refer via a foreign key
71176  ** to the row just deleted. */
71177  sqlite3FkActions(pParse, pTab, 0, iOld);
71178
71179  /* Invoke AFTER DELETE trigger programs. */
71180  sqlite3CodeRowTrigger(pParse, pTrigger,
71181      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
71182  );
71183
71184  /* Jump here if the row had already been deleted before any BEFORE
71185  ** trigger programs were invoked. Or if a trigger program throws a
71186  ** RAISE(IGNORE) exception.  */
71187  sqlite3VdbeResolveLabel(v, iLabel);
71188}
71189
71190/*
71191** This routine generates VDBE code that causes the deletion of all
71192** index entries associated with a single row of a single table.
71193**
71194** The VDBE must be in a particular state when this routine is called.
71195** These are the requirements:
71196**
71197**   1.  A read/write cursor pointing to pTab, the table containing the row
71198**       to be deleted, must be opened as cursor number "iCur".
71199**
71200**   2.  Read/write cursors for all indices of pTab must be open as
71201**       cursor number iCur+i for the i-th index.
71202**
71203**   3.  The "iCur" cursor must be pointing to the row that is to be
71204**       deleted.
71205*/
71206SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
71207  Parse *pParse,     /* Parsing and code generating context */
71208  Table *pTab,       /* Table containing the row to be deleted */
71209  int iCur,          /* Cursor number for the table */
71210  int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
71211){
71212  int i;
71213  Index *pIdx;
71214  int r1;
71215
71216  for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
71217    if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
71218    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
71219    sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
71220  }
71221}
71222
71223/*
71224** Generate code that will assemble an index key and put it in register
71225** regOut.  The key with be for index pIdx which is an index on pTab.
71226** iCur is the index of a cursor open on the pTab table and pointing to
71227** the entry that needs indexing.
71228**
71229** Return a register number which is the first in a block of
71230** registers that holds the elements of the index key.  The
71231** block of registers has already been deallocated by the time
71232** this routine returns.
71233*/
71234SQLITE_PRIVATE int sqlite3GenerateIndexKey(
71235  Parse *pParse,     /* Parsing context */
71236  Index *pIdx,       /* The index for which to generate a key */
71237  int iCur,          /* Cursor number for the pIdx->pTable table */
71238  int regOut,        /* Write the new index key to this register */
71239  int doMakeRec      /* Run the OP_MakeRecord instruction if true */
71240){
71241  Vdbe *v = pParse->pVdbe;
71242  int j;
71243  Table *pTab = pIdx->pTable;
71244  int regBase;
71245  int nCol;
71246
71247  nCol = pIdx->nColumn;
71248  regBase = sqlite3GetTempRange(pParse, nCol+1);
71249  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
71250  for(j=0; j<nCol; j++){
71251    int idx = pIdx->aiColumn[j];
71252    if( idx==pTab->iPKey ){
71253      sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
71254    }else{
71255      sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
71256      sqlite3ColumnDefault(v, pTab, idx, -1);
71257    }
71258  }
71259  if( doMakeRec ){
71260    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
71261    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
71262  }
71263  sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
71264  return regBase;
71265}
71266
71267/************** End of delete.c **********************************************/
71268/************** Begin file func.c ********************************************/
71269/*
71270** 2002 February 23
71271**
71272** The author disclaims copyright to this source code.  In place of
71273** a legal notice, here is a blessing:
71274**
71275**    May you do good and not evil.
71276**    May you find forgiveness for yourself and forgive others.
71277**    May you share freely, never taking more than you give.
71278**
71279*************************************************************************
71280** This file contains the C functions that implement various SQL
71281** functions of SQLite.
71282**
71283** There is only one exported symbol in this file - the function
71284** sqliteRegisterBuildinFunctions() found at the bottom of the file.
71285** All other code has file scope.
71286*/
71287
71288/*
71289** Return the collating function associated with a function.
71290*/
71291static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
71292  return context->pColl;
71293}
71294
71295/*
71296** Implementation of the non-aggregate min() and max() functions
71297*/
71298static void minmaxFunc(
71299  sqlite3_context *context,
71300  int argc,
71301  sqlite3_value **argv
71302){
71303  int i;
71304  int mask;    /* 0 for min() or 0xffffffff for max() */
71305  int iBest;
71306  CollSeq *pColl;
71307
71308  assert( argc>1 );
71309  mask = sqlite3_user_data(context)==0 ? 0 : -1;
71310  pColl = sqlite3GetFuncCollSeq(context);
71311  assert( pColl );
71312  assert( mask==-1 || mask==0 );
71313  iBest = 0;
71314  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
71315  for(i=1; i<argc; i++){
71316    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
71317    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
71318      testcase( mask==0 );
71319      iBest = i;
71320    }
71321  }
71322  sqlite3_result_value(context, argv[iBest]);
71323}
71324
71325/*
71326** Return the type of the argument.
71327*/
71328static void typeofFunc(
71329  sqlite3_context *context,
71330  int NotUsed,
71331  sqlite3_value **argv
71332){
71333  const char *z = 0;
71334  UNUSED_PARAMETER(NotUsed);
71335  switch( sqlite3_value_type(argv[0]) ){
71336    case SQLITE_INTEGER: z = "integer"; break;
71337    case SQLITE_TEXT:    z = "text";    break;
71338    case SQLITE_FLOAT:   z = "real";    break;
71339    case SQLITE_BLOB:    z = "blob";    break;
71340    default:             z = "null";    break;
71341  }
71342  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
71343}
71344
71345
71346/*
71347** Implementation of the length() function
71348*/
71349static void lengthFunc(
71350  sqlite3_context *context,
71351  int argc,
71352  sqlite3_value **argv
71353){
71354  int len;
71355
71356  assert( argc==1 );
71357  UNUSED_PARAMETER(argc);
71358  switch( sqlite3_value_type(argv[0]) ){
71359    case SQLITE_BLOB:
71360    case SQLITE_INTEGER:
71361    case SQLITE_FLOAT: {
71362      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
71363      break;
71364    }
71365    case SQLITE_TEXT: {
71366      const unsigned char *z = sqlite3_value_text(argv[0]);
71367      if( z==0 ) return;
71368      len = 0;
71369      while( *z ){
71370        len++;
71371        SQLITE_SKIP_UTF8(z);
71372      }
71373      sqlite3_result_int(context, len);
71374      break;
71375    }
71376    default: {
71377      sqlite3_result_null(context);
71378      break;
71379    }
71380  }
71381}
71382
71383/*
71384** Implementation of the abs() function.
71385**
71386** IMP: R-23979-26855 The abs(X) function returns the absolute value of
71387** the numeric argument X.
71388*/
71389static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71390  assert( argc==1 );
71391  UNUSED_PARAMETER(argc);
71392  switch( sqlite3_value_type(argv[0]) ){
71393    case SQLITE_INTEGER: {
71394      i64 iVal = sqlite3_value_int64(argv[0]);
71395      if( iVal<0 ){
71396        if( (iVal<<1)==0 ){
71397          /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
71398          ** abs(X) throws an integer overflow error since there is no
71399          ** equivalent positive 64-bit two complement value. */
71400          sqlite3_result_error(context, "integer overflow", -1);
71401          return;
71402        }
71403        iVal = -iVal;
71404      }
71405      sqlite3_result_int64(context, iVal);
71406      break;
71407    }
71408    case SQLITE_NULL: {
71409      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
71410      sqlite3_result_null(context);
71411      break;
71412    }
71413    default: {
71414      /* Because sqlite3_value_double() returns 0.0 if the argument is not
71415      ** something that can be converted into a number, we have:
71416      ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
71417      ** cannot be converted to a numeric value.
71418      */
71419      double rVal = sqlite3_value_double(argv[0]);
71420      if( rVal<0 ) rVal = -rVal;
71421      sqlite3_result_double(context, rVal);
71422      break;
71423    }
71424  }
71425}
71426
71427/*
71428** Implementation of the substr() function.
71429**
71430** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
71431** p1 is 1-indexed.  So substr(x,1,1) returns the first character
71432** of x.  If x is text, then we actually count UTF-8 characters.
71433** If x is a blob, then we count bytes.
71434**
71435** If p1 is negative, then we begin abs(p1) from the end of x[].
71436**
71437** If p2 is negative, return the p2 characters preceeding p1.
71438*/
71439static void substrFunc(
71440  sqlite3_context *context,
71441  int argc,
71442  sqlite3_value **argv
71443){
71444  const unsigned char *z;
71445  const unsigned char *z2;
71446  int len;
71447  int p0type;
71448  i64 p1, p2;
71449  int negP2 = 0;
71450
71451  assert( argc==3 || argc==2 );
71452  if( sqlite3_value_type(argv[1])==SQLITE_NULL
71453   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
71454  ){
71455    return;
71456  }
71457  p0type = sqlite3_value_type(argv[0]);
71458  p1 = sqlite3_value_int(argv[1]);
71459  if( p0type==SQLITE_BLOB ){
71460    len = sqlite3_value_bytes(argv[0]);
71461    z = sqlite3_value_blob(argv[0]);
71462    if( z==0 ) return;
71463    assert( len==sqlite3_value_bytes(argv[0]) );
71464  }else{
71465    z = sqlite3_value_text(argv[0]);
71466    if( z==0 ) return;
71467    len = 0;
71468    if( p1<0 ){
71469      for(z2=z; *z2; len++){
71470        SQLITE_SKIP_UTF8(z2);
71471      }
71472    }
71473  }
71474  if( argc==3 ){
71475    p2 = sqlite3_value_int(argv[2]);
71476    if( p2<0 ){
71477      p2 = -p2;
71478      negP2 = 1;
71479    }
71480  }else{
71481    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
71482  }
71483  if( p1<0 ){
71484    p1 += len;
71485    if( p1<0 ){
71486      p2 += p1;
71487      if( p2<0 ) p2 = 0;
71488      p1 = 0;
71489    }
71490  }else if( p1>0 ){
71491    p1--;
71492  }else if( p2>0 ){
71493    p2--;
71494  }
71495  if( negP2 ){
71496    p1 -= p2;
71497    if( p1<0 ){
71498      p2 += p1;
71499      p1 = 0;
71500    }
71501  }
71502  assert( p1>=0 && p2>=0 );
71503  if( p0type!=SQLITE_BLOB ){
71504    while( *z && p1 ){
71505      SQLITE_SKIP_UTF8(z);
71506      p1--;
71507    }
71508    for(z2=z; *z2 && p2; p2--){
71509      SQLITE_SKIP_UTF8(z2);
71510    }
71511    sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
71512  }else{
71513    if( p1+p2>len ){
71514      p2 = len-p1;
71515      if( p2<0 ) p2 = 0;
71516    }
71517    sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
71518  }
71519}
71520
71521/*
71522** Implementation of the round() function
71523*/
71524#ifndef SQLITE_OMIT_FLOATING_POINT
71525static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71526  int n = 0;
71527  double r;
71528  char *zBuf;
71529  assert( argc==1 || argc==2 );
71530  if( argc==2 ){
71531    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
71532    n = sqlite3_value_int(argv[1]);
71533    if( n>30 ) n = 30;
71534    if( n<0 ) n = 0;
71535  }
71536  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
71537  r = sqlite3_value_double(argv[0]);
71538  zBuf = sqlite3_mprintf("%.*f",n,r);
71539  if( zBuf==0 ){
71540    sqlite3_result_error_nomem(context);
71541  }else{
71542    sqlite3AtoF(zBuf, &r);
71543    sqlite3_free(zBuf);
71544    sqlite3_result_double(context, r);
71545  }
71546}
71547#endif
71548
71549/*
71550** Allocate nByte bytes of space using sqlite3_malloc(). If the
71551** allocation fails, call sqlite3_result_error_nomem() to notify
71552** the database handle that malloc() has failed and return NULL.
71553** If nByte is larger than the maximum string or blob length, then
71554** raise an SQLITE_TOOBIG exception and return NULL.
71555*/
71556static void *contextMalloc(sqlite3_context *context, i64 nByte){
71557  char *z;
71558  sqlite3 *db = sqlite3_context_db_handle(context);
71559  assert( nByte>0 );
71560  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
71561  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
71562  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
71563    sqlite3_result_error_toobig(context);
71564    z = 0;
71565  }else{
71566    z = sqlite3Malloc((int)nByte);
71567    if( !z ){
71568      sqlite3_result_error_nomem(context);
71569    }
71570  }
71571  return z;
71572}
71573
71574/*
71575** Implementation of the upper() and lower() SQL functions.
71576*/
71577static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71578  char *z1;
71579  const char *z2;
71580  int i, n;
71581  UNUSED_PARAMETER(argc);
71582  z2 = (char*)sqlite3_value_text(argv[0]);
71583  n = sqlite3_value_bytes(argv[0]);
71584  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
71585  assert( z2==(char*)sqlite3_value_text(argv[0]) );
71586  if( z2 ){
71587    z1 = contextMalloc(context, ((i64)n)+1);
71588    if( z1 ){
71589      memcpy(z1, z2, n+1);
71590      for(i=0; z1[i]; i++){
71591        z1[i] = (char)sqlite3Toupper(z1[i]);
71592      }
71593      sqlite3_result_text(context, z1, -1, sqlite3_free);
71594    }
71595  }
71596}
71597static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71598  u8 *z1;
71599  const char *z2;
71600  int i, n;
71601  UNUSED_PARAMETER(argc);
71602  z2 = (char*)sqlite3_value_text(argv[0]);
71603  n = sqlite3_value_bytes(argv[0]);
71604  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
71605  assert( z2==(char*)sqlite3_value_text(argv[0]) );
71606  if( z2 ){
71607    z1 = contextMalloc(context, ((i64)n)+1);
71608    if( z1 ){
71609      memcpy(z1, z2, n+1);
71610      for(i=0; z1[i]; i++){
71611        z1[i] = sqlite3Tolower(z1[i]);
71612      }
71613      sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
71614    }
71615  }
71616}
71617
71618
71619#if 0  /* This function is never used. */
71620/*
71621** The COALESCE() and IFNULL() functions used to be implemented as shown
71622** here.  But now they are implemented as VDBE code so that unused arguments
71623** do not have to be computed.  This legacy implementation is retained as
71624** comment.
71625*/
71626/*
71627** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
71628** All three do the same thing.  They return the first non-NULL
71629** argument.
71630*/
71631static void ifnullFunc(
71632  sqlite3_context *context,
71633  int argc,
71634  sqlite3_value **argv
71635){
71636  int i;
71637  for(i=0; i<argc; i++){
71638    if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
71639      sqlite3_result_value(context, argv[i]);
71640      break;
71641    }
71642  }
71643}
71644#endif /* NOT USED */
71645#define ifnullFunc versionFunc   /* Substitute function - never called */
71646
71647/*
71648** Implementation of random().  Return a random integer.
71649*/
71650static void randomFunc(
71651  sqlite3_context *context,
71652  int NotUsed,
71653  sqlite3_value **NotUsed2
71654){
71655  sqlite_int64 r;
71656  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71657  sqlite3_randomness(sizeof(r), &r);
71658  if( r<0 ){
71659    /* We need to prevent a random number of 0x8000000000000000
71660    ** (or -9223372036854775808) since when you do abs() of that
71661    ** number of you get the same value back again.  To do this
71662    ** in a way that is testable, mask the sign bit off of negative
71663    ** values, resulting in a positive value.  Then take the
71664    ** 2s complement of that positive value.  The end result can
71665    ** therefore be no less than -9223372036854775807.
71666    */
71667    r = -(r ^ (((sqlite3_int64)1)<<63));
71668  }
71669  sqlite3_result_int64(context, r);
71670}
71671
71672/*
71673** Implementation of randomblob(N).  Return a random blob
71674** that is N bytes long.
71675*/
71676static void randomBlob(
71677  sqlite3_context *context,
71678  int argc,
71679  sqlite3_value **argv
71680){
71681  int n;
71682  unsigned char *p;
71683  assert( argc==1 );
71684  UNUSED_PARAMETER(argc);
71685  n = sqlite3_value_int(argv[0]);
71686  if( n<1 ){
71687    n = 1;
71688  }
71689  p = contextMalloc(context, n);
71690  if( p ){
71691    sqlite3_randomness(n, p);
71692    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
71693  }
71694}
71695
71696/*
71697** Implementation of the last_insert_rowid() SQL function.  The return
71698** value is the same as the sqlite3_last_insert_rowid() API function.
71699*/
71700static void last_insert_rowid(
71701  sqlite3_context *context,
71702  int NotUsed,
71703  sqlite3_value **NotUsed2
71704){
71705  sqlite3 *db = sqlite3_context_db_handle(context);
71706  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71707  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
71708}
71709
71710/*
71711** Implementation of the changes() SQL function.  The return value is the
71712** same as the sqlite3_changes() API function.
71713*/
71714static void changes(
71715  sqlite3_context *context,
71716  int NotUsed,
71717  sqlite3_value **NotUsed2
71718){
71719  sqlite3 *db = sqlite3_context_db_handle(context);
71720  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71721  sqlite3_result_int(context, sqlite3_changes(db));
71722}
71723
71724/*
71725** Implementation of the total_changes() SQL function.  The return value is
71726** the same as the sqlite3_total_changes() API function.
71727*/
71728static void total_changes(
71729  sqlite3_context *context,
71730  int NotUsed,
71731  sqlite3_value **NotUsed2
71732){
71733  sqlite3 *db = sqlite3_context_db_handle(context);
71734  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71735  sqlite3_result_int(context, sqlite3_total_changes(db));
71736}
71737
71738/*
71739** A structure defining how to do GLOB-style comparisons.
71740*/
71741struct compareInfo {
71742  u8 matchAll;
71743  u8 matchOne;
71744  u8 matchSet;
71745  u8 noCase;
71746};
71747
71748/*
71749** For LIKE and GLOB matching on EBCDIC machines, assume that every
71750** character is exactly one byte in size.  Also, all characters are
71751** able to participate in upper-case-to-lower-case mappings in EBCDIC
71752** whereas only characters less than 0x80 do in ASCII.
71753*/
71754#if defined(SQLITE_EBCDIC)
71755# define sqlite3Utf8Read(A,C)    (*(A++))
71756# define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
71757#else
71758# define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
71759#endif
71760
71761static const struct compareInfo globInfo = { '*', '?', '[', 0 };
71762/* The correct SQL-92 behavior is for the LIKE operator to ignore
71763** case.  Thus  'a' LIKE 'A' would be true. */
71764static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
71765/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
71766** is case sensitive causing 'a' LIKE 'A' to be false */
71767static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
71768
71769/*
71770** Compare two UTF-8 strings for equality where the first string can
71771** potentially be a "glob" expression.  Return true (1) if they
71772** are the same and false (0) if they are different.
71773**
71774** Globbing rules:
71775**
71776**      '*'       Matches any sequence of zero or more characters.
71777**
71778**      '?'       Matches exactly one character.
71779**
71780**     [...]      Matches one character from the enclosed list of
71781**                characters.
71782**
71783**     [^...]     Matches one character not in the enclosed list.
71784**
71785** With the [...] and [^...] matching, a ']' character can be included
71786** in the list by making it the first character after '[' or '^'.  A
71787** range of characters can be specified using '-'.  Example:
71788** "[a-z]" matches any single lower-case letter.  To match a '-', make
71789** it the last character in the list.
71790**
71791** This routine is usually quick, but can be N**2 in the worst case.
71792**
71793** Hints: to match '*' or '?', put them in "[]".  Like this:
71794**
71795**         abc[*]xyz        Matches "abc*xyz" only
71796*/
71797static int patternCompare(
71798  const u8 *zPattern,              /* The glob pattern */
71799  const u8 *zString,               /* The string to compare against the glob */
71800  const struct compareInfo *pInfo, /* Information about how to do the compare */
71801  const int esc                    /* The escape character */
71802){
71803  int c, c2;
71804  int invert;
71805  int seen;
71806  u8 matchOne = pInfo->matchOne;
71807  u8 matchAll = pInfo->matchAll;
71808  u8 matchSet = pInfo->matchSet;
71809  u8 noCase = pInfo->noCase;
71810  int prevEscape = 0;     /* True if the previous character was 'escape' */
71811
71812  while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
71813    if( !prevEscape && c==matchAll ){
71814      while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
71815               || c == matchOne ){
71816        if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
71817          return 0;
71818        }
71819      }
71820      if( c==0 ){
71821        return 1;
71822      }else if( c==esc ){
71823        c = sqlite3Utf8Read(zPattern, &zPattern);
71824        if( c==0 ){
71825          return 0;
71826        }
71827      }else if( c==matchSet ){
71828        assert( esc==0 );         /* This is GLOB, not LIKE */
71829        assert( matchSet<0x80 );  /* '[' is a single-byte character */
71830        while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
71831          SQLITE_SKIP_UTF8(zString);
71832        }
71833        return *zString!=0;
71834      }
71835      while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
71836        if( noCase ){
71837          GlogUpperToLower(c2);
71838          GlogUpperToLower(c);
71839          while( c2 != 0 && c2 != c ){
71840            c2 = sqlite3Utf8Read(zString, &zString);
71841            GlogUpperToLower(c2);
71842          }
71843        }else{
71844          while( c2 != 0 && c2 != c ){
71845            c2 = sqlite3Utf8Read(zString, &zString);
71846          }
71847        }
71848        if( c2==0 ) return 0;
71849        if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
71850      }
71851      return 0;
71852    }else if( !prevEscape && c==matchOne ){
71853      if( sqlite3Utf8Read(zString, &zString)==0 ){
71854        return 0;
71855      }
71856    }else if( c==matchSet ){
71857      int prior_c = 0;
71858      assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
71859      seen = 0;
71860      invert = 0;
71861      c = sqlite3Utf8Read(zString, &zString);
71862      if( c==0 ) return 0;
71863      c2 = sqlite3Utf8Read(zPattern, &zPattern);
71864      if( c2=='^' ){
71865        invert = 1;
71866        c2 = sqlite3Utf8Read(zPattern, &zPattern);
71867      }
71868      if( c2==']' ){
71869        if( c==']' ) seen = 1;
71870        c2 = sqlite3Utf8Read(zPattern, &zPattern);
71871      }
71872      while( c2 && c2!=']' ){
71873        if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
71874          c2 = sqlite3Utf8Read(zPattern, &zPattern);
71875          if( c>=prior_c && c<=c2 ) seen = 1;
71876          prior_c = 0;
71877        }else{
71878          if( c==c2 ){
71879            seen = 1;
71880          }
71881          prior_c = c2;
71882        }
71883        c2 = sqlite3Utf8Read(zPattern, &zPattern);
71884      }
71885      if( c2==0 || (seen ^ invert)==0 ){
71886        return 0;
71887      }
71888    }else if( esc==c && !prevEscape ){
71889      prevEscape = 1;
71890    }else{
71891      c2 = sqlite3Utf8Read(zString, &zString);
71892      if( noCase ){
71893        GlogUpperToLower(c);
71894        GlogUpperToLower(c2);
71895      }
71896      if( c!=c2 ){
71897        return 0;
71898      }
71899      prevEscape = 0;
71900    }
71901  }
71902  return *zString==0;
71903}
71904
71905/*
71906** Count the number of times that the LIKE operator (or GLOB which is
71907** just a variation of LIKE) gets called.  This is used for testing
71908** only.
71909*/
71910#ifdef SQLITE_TEST
71911SQLITE_API int sqlite3_like_count = 0;
71912#endif
71913
71914
71915/*
71916** Implementation of the like() SQL function.  This function implements
71917** the build-in LIKE operator.  The first argument to the function is the
71918** pattern and the second argument is the string.  So, the SQL statements:
71919**
71920**       A LIKE B
71921**
71922** is implemented as like(B,A).
71923**
71924** This same function (with a different compareInfo structure) computes
71925** the GLOB operator.
71926*/
71927static void likeFunc(
71928  sqlite3_context *context,
71929  int argc,
71930  sqlite3_value **argv
71931){
71932  const unsigned char *zA, *zB;
71933  int escape = 0;
71934  int nPat;
71935  sqlite3 *db = sqlite3_context_db_handle(context);
71936
71937  zB = sqlite3_value_text(argv[0]);
71938  zA = sqlite3_value_text(argv[1]);
71939
71940  /* Limit the length of the LIKE or GLOB pattern to avoid problems
71941  ** of deep recursion and N*N behavior in patternCompare().
71942  */
71943  nPat = sqlite3_value_bytes(argv[0]);
71944  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
71945  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
71946  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
71947    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
71948    return;
71949  }
71950  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
71951
71952  if( argc==3 ){
71953    /* The escape character string must consist of a single UTF-8 character.
71954    ** Otherwise, return an error.
71955    */
71956    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
71957    if( zEsc==0 ) return;
71958    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
71959      sqlite3_result_error(context,
71960          "ESCAPE expression must be a single character", -1);
71961      return;
71962    }
71963    escape = sqlite3Utf8Read(zEsc, &zEsc);
71964  }
71965  if( zA && zB ){
71966    struct compareInfo *pInfo = sqlite3_user_data(context);
71967#ifdef SQLITE_TEST
71968    sqlite3_like_count++;
71969#endif
71970
71971    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
71972  }
71973}
71974
71975/*
71976** Implementation of the NULLIF(x,y) function.  The result is the first
71977** argument if the arguments are different.  The result is NULL if the
71978** arguments are equal to each other.
71979*/
71980static void nullifFunc(
71981  sqlite3_context *context,
71982  int NotUsed,
71983  sqlite3_value **argv
71984){
71985  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
71986  UNUSED_PARAMETER(NotUsed);
71987  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
71988    sqlite3_result_value(context, argv[0]);
71989  }
71990}
71991
71992/*
71993** Implementation of the sqlite_version() function.  The result is the version
71994** of the SQLite library that is running.
71995*/
71996static void versionFunc(
71997  sqlite3_context *context,
71998  int NotUsed,
71999  sqlite3_value **NotUsed2
72000){
72001  UNUSED_PARAMETER2(NotUsed, NotUsed2);
72002  sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
72003}
72004
72005/*
72006** Implementation of the sqlite_source_id() function. The result is a string
72007** that identifies the particular version of the source code used to build
72008** SQLite.
72009*/
72010static void sourceidFunc(
72011  sqlite3_context *context,
72012  int NotUsed,
72013  sqlite3_value **NotUsed2
72014){
72015  UNUSED_PARAMETER2(NotUsed, NotUsed2);
72016  sqlite3_result_text(context, SQLITE_SOURCE_ID, -1, SQLITE_STATIC);
72017}
72018
72019/* Array for converting from half-bytes (nybbles) into ASCII hex
72020** digits. */
72021static const char hexdigits[] = {
72022  '0', '1', '2', '3', '4', '5', '6', '7',
72023  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
72024};
72025
72026/*
72027** EXPERIMENTAL - This is not an official function.  The interface may
72028** change.  This function may disappear.  Do not write code that depends
72029** on this function.
72030**
72031** Implementation of the QUOTE() function.  This function takes a single
72032** argument.  If the argument is numeric, the return value is the same as
72033** the argument.  If the argument is NULL, the return value is the string
72034** "NULL".  Otherwise, the argument is enclosed in single quotes with
72035** single-quote escapes.
72036*/
72037static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
72038  assert( argc==1 );
72039  UNUSED_PARAMETER(argc);
72040  switch( sqlite3_value_type(argv[0]) ){
72041    case SQLITE_INTEGER:
72042    case SQLITE_FLOAT: {
72043      sqlite3_result_value(context, argv[0]);
72044      break;
72045    }
72046    case SQLITE_BLOB: {
72047      char *zText = 0;
72048      char const *zBlob = sqlite3_value_blob(argv[0]);
72049      int nBlob = sqlite3_value_bytes(argv[0]);
72050      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
72051      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
72052      if( zText ){
72053        int i;
72054        for(i=0; i<nBlob; i++){
72055          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
72056          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
72057        }
72058        zText[(nBlob*2)+2] = '\'';
72059        zText[(nBlob*2)+3] = '\0';
72060        zText[0] = 'X';
72061        zText[1] = '\'';
72062        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
72063        sqlite3_free(zText);
72064      }
72065      break;
72066    }
72067    case SQLITE_TEXT: {
72068      int i,j;
72069      u64 n;
72070      const unsigned char *zArg = sqlite3_value_text(argv[0]);
72071      char *z;
72072
72073      if( zArg==0 ) return;
72074      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
72075      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
72076      if( z ){
72077        z[0] = '\'';
72078        for(i=0, j=1; zArg[i]; i++){
72079          z[j++] = zArg[i];
72080          if( zArg[i]=='\'' ){
72081            z[j++] = '\'';
72082          }
72083        }
72084        z[j++] = '\'';
72085        z[j] = 0;
72086        sqlite3_result_text(context, z, j, sqlite3_free);
72087      }
72088      break;
72089    }
72090    default: {
72091      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
72092      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
72093      break;
72094    }
72095  }
72096}
72097
72098/*
72099** The hex() function.  Interpret the argument as a blob.  Return
72100** a hexadecimal rendering as text.
72101*/
72102static void hexFunc(
72103  sqlite3_context *context,
72104  int argc,
72105  sqlite3_value **argv
72106){
72107  int i, n;
72108  const unsigned char *pBlob;
72109  char *zHex, *z;
72110  assert( argc==1 );
72111  UNUSED_PARAMETER(argc);
72112  pBlob = sqlite3_value_blob(argv[0]);
72113  n = sqlite3_value_bytes(argv[0]);
72114  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
72115  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
72116  if( zHex ){
72117    for(i=0; i<n; i++, pBlob++){
72118      unsigned char c = *pBlob;
72119      *(z++) = hexdigits[(c>>4)&0xf];
72120      *(z++) = hexdigits[c&0xf];
72121    }
72122    *z = 0;
72123    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
72124  }
72125}
72126
72127/*
72128** The zeroblob(N) function returns a zero-filled blob of size N bytes.
72129*/
72130static void zeroblobFunc(
72131  sqlite3_context *context,
72132  int argc,
72133  sqlite3_value **argv
72134){
72135  i64 n;
72136  sqlite3 *db = sqlite3_context_db_handle(context);
72137  assert( argc==1 );
72138  UNUSED_PARAMETER(argc);
72139  n = sqlite3_value_int64(argv[0]);
72140  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
72141  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
72142  if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
72143    sqlite3_result_error_toobig(context);
72144  }else{
72145    sqlite3_result_zeroblob(context, (int)n);
72146  }
72147}
72148
72149/*
72150** The replace() function.  Three arguments are all strings: call
72151** them A, B, and C. The result is also a string which is derived
72152** from A by replacing every occurance of B with C.  The match
72153** must be exact.  Collating sequences are not used.
72154*/
72155static void replaceFunc(
72156  sqlite3_context *context,
72157  int argc,
72158  sqlite3_value **argv
72159){
72160  const unsigned char *zStr;        /* The input string A */
72161  const unsigned char *zPattern;    /* The pattern string B */
72162  const unsigned char *zRep;        /* The replacement string C */
72163  unsigned char *zOut;              /* The output */
72164  int nStr;                /* Size of zStr */
72165  int nPattern;            /* Size of zPattern */
72166  int nRep;                /* Size of zRep */
72167  i64 nOut;                /* Maximum size of zOut */
72168  int loopLimit;           /* Last zStr[] that might match zPattern[] */
72169  int i, j;                /* Loop counters */
72170
72171  assert( argc==3 );
72172  UNUSED_PARAMETER(argc);
72173  zStr = sqlite3_value_text(argv[0]);
72174  if( zStr==0 ) return;
72175  nStr = sqlite3_value_bytes(argv[0]);
72176  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
72177  zPattern = sqlite3_value_text(argv[1]);
72178  if( zPattern==0 ){
72179    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
72180            || sqlite3_context_db_handle(context)->mallocFailed );
72181    return;
72182  }
72183  if( zPattern[0]==0 ){
72184    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
72185    sqlite3_result_value(context, argv[0]);
72186    return;
72187  }
72188  nPattern = sqlite3_value_bytes(argv[1]);
72189  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
72190  zRep = sqlite3_value_text(argv[2]);
72191  if( zRep==0 ) return;
72192  nRep = sqlite3_value_bytes(argv[2]);
72193  assert( zRep==sqlite3_value_text(argv[2]) );
72194  nOut = nStr + 1;
72195  assert( nOut<SQLITE_MAX_LENGTH );
72196  zOut = contextMalloc(context, (i64)nOut);
72197  if( zOut==0 ){
72198    return;
72199  }
72200  loopLimit = nStr - nPattern;
72201  for(i=j=0; i<=loopLimit; i++){
72202    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
72203      zOut[j++] = zStr[i];
72204    }else{
72205      u8 *zOld;
72206      sqlite3 *db = sqlite3_context_db_handle(context);
72207      nOut += nRep - nPattern;
72208      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
72209      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
72210      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
72211        sqlite3_result_error_toobig(context);
72212        sqlite3DbFree(db, zOut);
72213        return;
72214      }
72215      zOld = zOut;
72216      zOut = sqlite3_realloc(zOut, (int)nOut);
72217      if( zOut==0 ){
72218        sqlite3_result_error_nomem(context);
72219        sqlite3DbFree(db, zOld);
72220        return;
72221      }
72222      memcpy(&zOut[j], zRep, nRep);
72223      j += nRep;
72224      i += nPattern-1;
72225    }
72226  }
72227  assert( j+nStr-i+1==nOut );
72228  memcpy(&zOut[j], &zStr[i], nStr-i);
72229  j += nStr - i;
72230  assert( j<=nOut );
72231  zOut[j] = 0;
72232  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
72233}
72234
72235/*
72236** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
72237** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
72238*/
72239static void trimFunc(
72240  sqlite3_context *context,
72241  int argc,
72242  sqlite3_value **argv
72243){
72244  const unsigned char *zIn;         /* Input string */
72245  const unsigned char *zCharSet;    /* Set of characters to trim */
72246  int nIn;                          /* Number of bytes in input */
72247  int flags;                        /* 1: trimleft  2: trimright  3: trim */
72248  int i;                            /* Loop counter */
72249  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
72250  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
72251  int nChar;                        /* Number of characters in zCharSet */
72252
72253  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
72254    return;
72255  }
72256  zIn = sqlite3_value_text(argv[0]);
72257  if( zIn==0 ) return;
72258  nIn = sqlite3_value_bytes(argv[0]);
72259  assert( zIn==sqlite3_value_text(argv[0]) );
72260  if( argc==1 ){
72261    static const unsigned char lenOne[] = { 1 };
72262    static unsigned char * const azOne[] = { (u8*)" " };
72263    nChar = 1;
72264    aLen = (u8*)lenOne;
72265    azChar = (unsigned char **)azOne;
72266    zCharSet = 0;
72267  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
72268    return;
72269  }else{
72270    const unsigned char *z;
72271    for(z=zCharSet, nChar=0; *z; nChar++){
72272      SQLITE_SKIP_UTF8(z);
72273    }
72274    if( nChar>0 ){
72275      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
72276      if( azChar==0 ){
72277        return;
72278      }
72279      aLen = (unsigned char*)&azChar[nChar];
72280      for(z=zCharSet, nChar=0; *z; nChar++){
72281        azChar[nChar] = (unsigned char *)z;
72282        SQLITE_SKIP_UTF8(z);
72283        aLen[nChar] = (u8)(z - azChar[nChar]);
72284      }
72285    }
72286  }
72287  if( nChar>0 ){
72288    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
72289    if( flags & 1 ){
72290      while( nIn>0 ){
72291        int len = 0;
72292        for(i=0; i<nChar; i++){
72293          len = aLen[i];
72294          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
72295        }
72296        if( i>=nChar ) break;
72297        zIn += len;
72298        nIn -= len;
72299      }
72300    }
72301    if( flags & 2 ){
72302      while( nIn>0 ){
72303        int len = 0;
72304        for(i=0; i<nChar; i++){
72305          len = aLen[i];
72306          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
72307        }
72308        if( i>=nChar ) break;
72309        nIn -= len;
72310      }
72311    }
72312    if( zCharSet ){
72313      sqlite3_free(azChar);
72314    }
72315  }
72316  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
72317}
72318
72319
72320/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
72321** is only available if the SQLITE_SOUNDEX compile-time option is used
72322** when SQLite is built.
72323*/
72324#ifdef SQLITE_SOUNDEX
72325/*
72326** Compute the soundex encoding of a word.
72327**
72328** IMP: R-59782-00072 The soundex(X) function returns a string that is the
72329** soundex encoding of the string X.
72330*/
72331static void soundexFunc(
72332  sqlite3_context *context,
72333  int argc,
72334  sqlite3_value **argv
72335){
72336  char zResult[8];
72337  const u8 *zIn;
72338  int i, j;
72339  static const unsigned char iCode[] = {
72340    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72341    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72342    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72343    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72344    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
72345    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
72346    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
72347    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
72348  };
72349  assert( argc==1 );
72350  zIn = (u8*)sqlite3_value_text(argv[0]);
72351  if( zIn==0 ) zIn = (u8*)"";
72352  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
72353  if( zIn[i] ){
72354    u8 prevcode = iCode[zIn[i]&0x7f];
72355    zResult[0] = sqlite3Toupper(zIn[i]);
72356    for(j=1; j<4 && zIn[i]; i++){
72357      int code = iCode[zIn[i]&0x7f];
72358      if( code>0 ){
72359        if( code!=prevcode ){
72360          prevcode = code;
72361          zResult[j++] = code + '0';
72362        }
72363      }else{
72364        prevcode = 0;
72365      }
72366    }
72367    while( j<4 ){
72368      zResult[j++] = '0';
72369    }
72370    zResult[j] = 0;
72371    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
72372  }else{
72373    /* IMP: R-64894-50321 The string "?000" is returned if the argument
72374    ** is NULL or contains no ASCII alphabetic characters. */
72375    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
72376  }
72377}
72378#endif /* SQLITE_SOUNDEX */
72379
72380#ifndef SQLITE_OMIT_LOAD_EXTENSION
72381/*
72382** A function that loads a shared-library extension then returns NULL.
72383*/
72384static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
72385  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
72386  const char *zProc;
72387  sqlite3 *db = sqlite3_context_db_handle(context);
72388  char *zErrMsg = 0;
72389
72390  if( argc==2 ){
72391    zProc = (const char *)sqlite3_value_text(argv[1]);
72392  }else{
72393    zProc = 0;
72394  }
72395  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
72396    sqlite3_result_error(context, zErrMsg, -1);
72397    sqlite3_free(zErrMsg);
72398  }
72399}
72400#endif
72401
72402
72403/*
72404** An instance of the following structure holds the context of a
72405** sum() or avg() aggregate computation.
72406*/
72407typedef struct SumCtx SumCtx;
72408struct SumCtx {
72409  double rSum;      /* Floating point sum */
72410  i64 iSum;         /* Integer sum */
72411  i64 cnt;          /* Number of elements summed */
72412  u8 overflow;      /* True if integer overflow seen */
72413  u8 approx;        /* True if non-integer value was input to the sum */
72414};
72415
72416/*
72417** Routines used to compute the sum, average, and total.
72418**
72419** The SUM() function follows the (broken) SQL standard which means
72420** that it returns NULL if it sums over no inputs.  TOTAL returns
72421** 0.0 in that case.  In addition, TOTAL always returns a float where
72422** SUM might return an integer if it never encounters a floating point
72423** value.  TOTAL never fails, but SUM might through an exception if
72424** it overflows an integer.
72425*/
72426static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
72427  SumCtx *p;
72428  int type;
72429  assert( argc==1 );
72430  UNUSED_PARAMETER(argc);
72431  p = sqlite3_aggregate_context(context, sizeof(*p));
72432  type = sqlite3_value_numeric_type(argv[0]);
72433  if( p && type!=SQLITE_NULL ){
72434    p->cnt++;
72435    if( type==SQLITE_INTEGER ){
72436      i64 v = sqlite3_value_int64(argv[0]);
72437      p->rSum += v;
72438      if( (p->approx|p->overflow)==0 ){
72439        i64 iNewSum = p->iSum + v;
72440        int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
72441        int s2 = (int)(v       >> (sizeof(i64)*8-1));
72442        int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
72443        p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
72444        p->iSum = iNewSum;
72445      }
72446    }else{
72447      p->rSum += sqlite3_value_double(argv[0]);
72448      p->approx = 1;
72449    }
72450  }
72451}
72452static void sumFinalize(sqlite3_context *context){
72453  SumCtx *p;
72454  p = sqlite3_aggregate_context(context, 0);
72455  if( p && p->cnt>0 ){
72456    if( p->overflow ){
72457      sqlite3_result_error(context,"integer overflow",-1);
72458    }else if( p->approx ){
72459      sqlite3_result_double(context, p->rSum);
72460    }else{
72461      sqlite3_result_int64(context, p->iSum);
72462    }
72463  }
72464}
72465static void avgFinalize(sqlite3_context *context){
72466  SumCtx *p;
72467  p = sqlite3_aggregate_context(context, 0);
72468  if( p && p->cnt>0 ){
72469    sqlite3_result_double(context, p->rSum/(double)p->cnt);
72470  }
72471}
72472static void totalFinalize(sqlite3_context *context){
72473  SumCtx *p;
72474  p = sqlite3_aggregate_context(context, 0);
72475  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
72476  sqlite3_result_double(context, p ? p->rSum : (double)0);
72477}
72478
72479/*
72480** The following structure keeps track of state information for the
72481** count() aggregate function.
72482*/
72483typedef struct CountCtx CountCtx;
72484struct CountCtx {
72485  i64 n;
72486};
72487
72488/*
72489** Routines to implement the count() aggregate function.
72490*/
72491static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
72492  CountCtx *p;
72493  p = sqlite3_aggregate_context(context, sizeof(*p));
72494  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
72495    p->n++;
72496  }
72497
72498#ifndef SQLITE_OMIT_DEPRECATED
72499  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
72500  ** sure it still operates correctly, verify that its count agrees with our
72501  ** internal count when using count(*) and when the total count can be
72502  ** expressed as a 32-bit integer. */
72503  assert( argc==1 || p==0 || p->n>0x7fffffff
72504          || p->n==sqlite3_aggregate_count(context) );
72505#endif
72506}
72507static void countFinalize(sqlite3_context *context){
72508  CountCtx *p;
72509  p = sqlite3_aggregate_context(context, 0);
72510  sqlite3_result_int64(context, p ? p->n : 0);
72511}
72512
72513/*
72514** Routines to implement min() and max() aggregate functions.
72515*/
72516static void minmaxStep(
72517  sqlite3_context *context,
72518  int NotUsed,
72519  sqlite3_value **argv
72520){
72521  Mem *pArg  = (Mem *)argv[0];
72522  Mem *pBest;
72523  UNUSED_PARAMETER(NotUsed);
72524
72525  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
72526  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
72527  if( !pBest ) return;
72528
72529  if( pBest->flags ){
72530    int max;
72531    int cmp;
72532    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
72533    /* This step function is used for both the min() and max() aggregates,
72534    ** the only difference between the two being that the sense of the
72535    ** comparison is inverted. For the max() aggregate, the
72536    ** sqlite3_user_data() function returns (void *)-1. For min() it
72537    ** returns (void *)db, where db is the sqlite3* database pointer.
72538    ** Therefore the next statement sets variable 'max' to 1 for the max()
72539    ** aggregate, or 0 for min().
72540    */
72541    max = sqlite3_user_data(context)!=0;
72542    cmp = sqlite3MemCompare(pBest, pArg, pColl);
72543    if( (max && cmp<0) || (!max && cmp>0) ){
72544      sqlite3VdbeMemCopy(pBest, pArg);
72545    }
72546  }else{
72547    sqlite3VdbeMemCopy(pBest, pArg);
72548  }
72549}
72550static void minMaxFinalize(sqlite3_context *context){
72551  sqlite3_value *pRes;
72552  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
72553  if( pRes ){
72554    if( ALWAYS(pRes->flags) ){
72555      sqlite3_result_value(context, pRes);
72556    }
72557    sqlite3VdbeMemRelease(pRes);
72558  }
72559}
72560
72561/*
72562** group_concat(EXPR, ?SEPARATOR?)
72563*/
72564static void groupConcatStep(
72565  sqlite3_context *context,
72566  int argc,
72567  sqlite3_value **argv
72568){
72569  const char *zVal;
72570  StrAccum *pAccum;
72571  const char *zSep;
72572  int nVal, nSep;
72573  assert( argc==1 || argc==2 );
72574  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
72575  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
72576
72577  if( pAccum ){
72578    sqlite3 *db = sqlite3_context_db_handle(context);
72579    int firstTerm = pAccum->useMalloc==0;
72580    pAccum->useMalloc = 1;
72581    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
72582    if( !firstTerm ){
72583      if( argc==2 ){
72584        zSep = (char*)sqlite3_value_text(argv[1]);
72585        nSep = sqlite3_value_bytes(argv[1]);
72586      }else{
72587        zSep = ",";
72588        nSep = 1;
72589      }
72590      sqlite3StrAccumAppend(pAccum, zSep, nSep);
72591    }
72592    zVal = (char*)sqlite3_value_text(argv[0]);
72593    nVal = sqlite3_value_bytes(argv[0]);
72594    sqlite3StrAccumAppend(pAccum, zVal, nVal);
72595  }
72596}
72597static void groupConcatFinalize(sqlite3_context *context){
72598  StrAccum *pAccum;
72599  pAccum = sqlite3_aggregate_context(context, 0);
72600  if( pAccum ){
72601    if( pAccum->tooBig ){
72602      sqlite3_result_error_toobig(context);
72603    }else if( pAccum->mallocFailed ){
72604      sqlite3_result_error_nomem(context);
72605    }else{
72606      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
72607                          sqlite3_free);
72608    }
72609  }
72610}
72611
72612/*
72613** This function registered all of the above C functions as SQL
72614** functions.  This should be the only routine in this file with
72615** external linkage.
72616*/
72617SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
72618#ifndef SQLITE_OMIT_ALTERTABLE
72619  sqlite3AlterFunctions(db);
72620#endif
72621  if( !db->mallocFailed ){
72622    int rc = sqlite3_overload_function(db, "MATCH", 2);
72623    assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
72624    if( rc==SQLITE_NOMEM ){
72625      db->mallocFailed = 1;
72626    }
72627  }
72628}
72629
72630/*
72631** Set the LIKEOPT flag on the 2-argument function with the given name.
72632*/
72633static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
72634  FuncDef *pDef;
72635  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
72636                             2, SQLITE_UTF8, 0);
72637  if( ALWAYS(pDef) ){
72638    pDef->flags = flagVal;
72639  }
72640}
72641
72642/*
72643** Register the built-in LIKE and GLOB functions.  The caseSensitive
72644** parameter determines whether or not the LIKE operator is case
72645** sensitive.  GLOB is always case sensitive.
72646*/
72647SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
72648  struct compareInfo *pInfo;
72649  if( caseSensitive ){
72650    pInfo = (struct compareInfo*)&likeInfoAlt;
72651  }else{
72652    pInfo = (struct compareInfo*)&likeInfoNorm;
72653  }
72654  sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0);
72655  sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0);
72656  sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY,
72657      (struct compareInfo*)&globInfo, likeFunc, 0,0);
72658  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
72659  setLikeOptFlag(db, "like",
72660      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
72661}
72662
72663/*
72664** pExpr points to an expression which implements a function.  If
72665** it is appropriate to apply the LIKE optimization to that function
72666** then set aWc[0] through aWc[2] to the wildcard characters and
72667** return TRUE.  If the function is not a LIKE-style function then
72668** return FALSE.
72669*/
72670SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
72671  FuncDef *pDef;
72672  if( pExpr->op!=TK_FUNCTION
72673   || !pExpr->x.pList
72674   || pExpr->x.pList->nExpr!=2
72675  ){
72676    return 0;
72677  }
72678  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
72679  pDef = sqlite3FindFunction(db, pExpr->u.zToken,
72680                             sqlite3Strlen30(pExpr->u.zToken),
72681                             2, SQLITE_UTF8, 0);
72682  if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
72683    return 0;
72684  }
72685
72686  /* The memcpy() statement assumes that the wildcard characters are
72687  ** the first three statements in the compareInfo structure.  The
72688  ** asserts() that follow verify that assumption
72689  */
72690  memcpy(aWc, pDef->pUserData, 3);
72691  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
72692  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
72693  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
72694  *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
72695  return 1;
72696}
72697
72698/*
72699** All all of the FuncDef structures in the aBuiltinFunc[] array above
72700** to the global function hash table.  This occurs at start-time (as
72701** a consequence of calling sqlite3_initialize()).
72702**
72703** After this routine runs
72704*/
72705SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
72706  /*
72707  ** The following array holds FuncDef structures for all of the functions
72708  ** defined in this file.
72709  **
72710  ** The array cannot be constant since changes are made to the
72711  ** FuncDef.pHash elements at start-time.  The elements of this array
72712  ** are read-only after initialization is complete.
72713  */
72714  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
72715    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
72716    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
72717    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
72718    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
72719    FUNCTION(trim,               1, 3, 0, trimFunc         ),
72720    FUNCTION(trim,               2, 3, 0, trimFunc         ),
72721    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
72722    FUNCTION(min,                0, 0, 1, 0                ),
72723    AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
72724    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
72725    FUNCTION(max,                0, 1, 1, 0                ),
72726    AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
72727    FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
72728    FUNCTION(length,             1, 0, 0, lengthFunc       ),
72729    FUNCTION(substr,             2, 0, 0, substrFunc       ),
72730    FUNCTION(substr,             3, 0, 0, substrFunc       ),
72731    FUNCTION(abs,                1, 0, 0, absFunc          ),
72732#ifndef SQLITE_OMIT_FLOATING_POINT
72733    FUNCTION(round,              1, 0, 0, roundFunc        ),
72734    FUNCTION(round,              2, 0, 0, roundFunc        ),
72735#endif
72736    FUNCTION(upper,              1, 0, 0, upperFunc        ),
72737    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
72738    FUNCTION(coalesce,           1, 0, 0, 0                ),
72739    FUNCTION(coalesce,           0, 0, 0, 0                ),
72740/*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
72741    {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0},
72742    FUNCTION(hex,                1, 0, 0, hexFunc          ),
72743/*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
72744    {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0},
72745    FUNCTION(random,             0, 0, 0, randomFunc       ),
72746    FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
72747    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
72748    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
72749    FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
72750    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
72751    FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
72752    FUNCTION(changes,            0, 0, 0, changes          ),
72753    FUNCTION(total_changes,      0, 0, 0, total_changes    ),
72754    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
72755    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
72756  #ifdef SQLITE_SOUNDEX
72757    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
72758  #endif
72759  #ifndef SQLITE_OMIT_LOAD_EXTENSION
72760    FUNCTION(load_extension,     1, 0, 0, loadExt          ),
72761    FUNCTION(load_extension,     2, 0, 0, loadExt          ),
72762  #endif
72763    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
72764    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
72765    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
72766 /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
72767    {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0},
72768    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
72769    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
72770    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
72771
72772    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
72773  #ifdef SQLITE_CASE_SENSITIVE_LIKE
72774    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
72775    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
72776  #else
72777    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
72778    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
72779  #endif
72780  };
72781
72782  int i;
72783  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
72784  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
72785
72786  for(i=0; i<ArraySize(aBuiltinFunc); i++){
72787    sqlite3FuncDefInsert(pHash, &aFunc[i]);
72788  }
72789  sqlite3RegisterDateTimeFunctions();
72790}
72791
72792/************** End of func.c ************************************************/
72793/************** Begin file fkey.c ********************************************/
72794/*
72795**
72796** The author disclaims copyright to this source code.  In place of
72797** a legal notice, here is a blessing:
72798**
72799**    May you do good and not evil.
72800**    May you find forgiveness for yourself and forgive others.
72801**    May you share freely, never taking more than you give.
72802**
72803*************************************************************************
72804** This file contains code used by the compiler to add foreign key
72805** support to compiled SQL statements.
72806*/
72807
72808#ifndef SQLITE_OMIT_FOREIGN_KEY
72809#ifndef SQLITE_OMIT_TRIGGER
72810
72811/*
72812** Deferred and Immediate FKs
72813** --------------------------
72814**
72815** Foreign keys in SQLite come in two flavours: deferred and immediate.
72816** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
72817** is returned and the current statement transaction rolled back. If a
72818** deferred foreign key constraint is violated, no action is taken
72819** immediately. However if the application attempts to commit the
72820** transaction before fixing the constraint violation, the attempt fails.
72821**
72822** Deferred constraints are implemented using a simple counter associated
72823** with the database handle. The counter is set to zero each time a
72824** database transaction is opened. Each time a statement is executed
72825** that causes a foreign key violation, the counter is incremented. Each
72826** time a statement is executed that removes an existing violation from
72827** the database, the counter is decremented. When the transaction is
72828** committed, the commit fails if the current value of the counter is
72829** greater than zero. This scheme has two big drawbacks:
72830**
72831**   * When a commit fails due to a deferred foreign key constraint,
72832**     there is no way to tell which foreign constraint is not satisfied,
72833**     or which row it is not satisfied for.
72834**
72835**   * If the database contains foreign key violations when the
72836**     transaction is opened, this may cause the mechanism to malfunction.
72837**
72838** Despite these problems, this approach is adopted as it seems simpler
72839** than the alternatives.
72840**
72841** INSERT operations:
72842**
72843**   I.1) For each FK for which the table is the child table, search
72844**        the parent table for a match. If none is found increment the
72845**        constraint counter.
72846**
72847**   I.2) For each FK for which the table is the parent table,
72848**        search the child table for rows that correspond to the new
72849**        row in the parent table. Decrement the counter for each row
72850**        found (as the constraint is now satisfied).
72851**
72852** DELETE operations:
72853**
72854**   D.1) For each FK for which the table is the child table,
72855**        search the parent table for a row that corresponds to the
72856**        deleted row in the child table. If such a row is not found,
72857**        decrement the counter.
72858**
72859**   D.2) For each FK for which the table is the parent table, search
72860**        the child table for rows that correspond to the deleted row
72861**        in the parent table. For each found increment the counter.
72862**
72863** UPDATE operations:
72864**
72865**   An UPDATE command requires that all 4 steps above are taken, but only
72866**   for FK constraints for which the affected columns are actually
72867**   modified (values must be compared at runtime).
72868**
72869** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
72870** This simplifies the implementation a bit.
72871**
72872** For the purposes of immediate FK constraints, the OR REPLACE conflict
72873** resolution is considered to delete rows before the new row is inserted.
72874** If a delete caused by OR REPLACE violates an FK constraint, an exception
72875** is thrown, even if the FK constraint would be satisfied after the new
72876** row is inserted.
72877**
72878** Immediate constraints are usually handled similarly. The only difference
72879** is that the counter used is stored as part of each individual statement
72880** object (struct Vdbe). If, after the statement has run, its immediate
72881** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
72882** and the statement transaction is rolled back. An exception is an INSERT
72883** statement that inserts a single row only (no triggers). In this case,
72884** instead of using a counter, an exception is thrown immediately if the
72885** INSERT violates a foreign key constraint. This is necessary as such
72886** an INSERT does not open a statement transaction.
72887**
72888** TODO: How should dropping a table be handled? How should renaming a
72889** table be handled?
72890**
72891**
72892** Query API Notes
72893** ---------------
72894**
72895** Before coding an UPDATE or DELETE row operation, the code-generator
72896** for those two operations needs to know whether or not the operation
72897** requires any FK processing and, if so, which columns of the original
72898** row are required by the FK processing VDBE code (i.e. if FKs were
72899** implemented using triggers, which of the old.* columns would be
72900** accessed). No information is required by the code-generator before
72901** coding an INSERT operation. The functions used by the UPDATE/DELETE
72902** generation code to query for this information are:
72903**
72904**   sqlite3FkRequired() - Test to see if FK processing is required.
72905**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
72906**
72907**
72908** Externally accessible module functions
72909** --------------------------------------
72910**
72911**   sqlite3FkCheck()    - Check for foreign key violations.
72912**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
72913**   sqlite3FkDelete()   - Delete an FKey structure.
72914*/
72915
72916/*
72917** VDBE Calling Convention
72918** -----------------------
72919**
72920** Example:
72921**
72922**   For the following INSERT statement:
72923**
72924**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
72925**     INSERT INTO t1 VALUES(1, 2, 3.1);
72926**
72927**   Register (x):        2    (type integer)
72928**   Register (x+1):      1    (type integer)
72929**   Register (x+2):      NULL (type NULL)
72930**   Register (x+3):      3.1  (type real)
72931*/
72932
72933/*
72934** A foreign key constraint requires that the key columns in the parent
72935** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
72936** Given that pParent is the parent table for foreign key constraint pFKey,
72937** search the schema a unique index on the parent key columns.
72938**
72939** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
72940** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
72941** is set to point to the unique index.
72942**
72943** If the parent key consists of a single column (the foreign key constraint
72944** is not a composite foreign key), output variable *paiCol is set to NULL.
72945** Otherwise, it is set to point to an allocated array of size N, where
72946** N is the number of columns in the parent key. The first element of the
72947** array is the index of the child table column that is mapped by the FK
72948** constraint to the parent table column stored in the left-most column
72949** of index *ppIdx. The second element of the array is the index of the
72950** child table column that corresponds to the second left-most column of
72951** *ppIdx, and so on.
72952**
72953** If the required index cannot be found, either because:
72954**
72955**   1) The named parent key columns do not exist, or
72956**
72957**   2) The named parent key columns do exist, but are not subject to a
72958**      UNIQUE or PRIMARY KEY constraint, or
72959**
72960**   3) No parent key columns were provided explicitly as part of the
72961**      foreign key definition, and the parent table does not have a
72962**      PRIMARY KEY, or
72963**
72964**   4) No parent key columns were provided explicitly as part of the
72965**      foreign key definition, and the PRIMARY KEY of the parent table
72966**      consists of a a different number of columns to the child key in
72967**      the child table.
72968**
72969** then non-zero is returned, and a "foreign key mismatch" error loaded
72970** into pParse. If an OOM error occurs, non-zero is returned and the
72971** pParse->db->mallocFailed flag is set.
72972*/
72973static int locateFkeyIndex(
72974  Parse *pParse,                  /* Parse context to store any error in */
72975  Table *pParent,                 /* Parent table of FK constraint pFKey */
72976  FKey *pFKey,                    /* Foreign key to find index for */
72977  Index **ppIdx,                  /* OUT: Unique index on parent table */
72978  int **paiCol                    /* OUT: Map of index columns in pFKey */
72979){
72980  Index *pIdx = 0;                    /* Value to return via *ppIdx */
72981  int *aiCol = 0;                     /* Value to return via *paiCol */
72982  int nCol = pFKey->nCol;             /* Number of columns in parent key */
72983  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
72984
72985  /* The caller is responsible for zeroing output parameters. */
72986  assert( ppIdx && *ppIdx==0 );
72987  assert( !paiCol || *paiCol==0 );
72988  assert( pParse );
72989
72990  /* If this is a non-composite (single column) foreign key, check if it
72991  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
72992  ** and *paiCol set to zero and return early.
72993  **
72994  ** Otherwise, for a composite foreign key (more than one column), allocate
72995  ** space for the aiCol array (returned via output parameter *paiCol).
72996  ** Non-composite foreign keys do not require the aiCol array.
72997  */
72998  if( nCol==1 ){
72999    /* The FK maps to the IPK if any of the following are true:
73000    **
73001    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
73002    **      mapped to the primary key of table pParent, or
73003    **   2) The FK is explicitly mapped to a column declared as INTEGER
73004    **      PRIMARY KEY.
73005    */
73006    if( pParent->iPKey>=0 ){
73007      if( !zKey ) return 0;
73008      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
73009    }
73010  }else if( paiCol ){
73011    assert( nCol>1 );
73012    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
73013    if( !aiCol ) return 1;
73014    *paiCol = aiCol;
73015  }
73016
73017  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
73018    if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
73019      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
73020      ** of columns. If each indexed column corresponds to a foreign key
73021      ** column of pFKey, then this index is a winner.  */
73022
73023      if( zKey==0 ){
73024        /* If zKey is NULL, then this foreign key is implicitly mapped to
73025        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
73026        ** identified by the test (Index.autoIndex==2).  */
73027        if( pIdx->autoIndex==2 ){
73028          if( aiCol ){
73029            int i;
73030            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
73031          }
73032          break;
73033        }
73034      }else{
73035        /* If zKey is non-NULL, then this foreign key was declared to
73036        ** map to an explicit list of columns in table pParent. Check if this
73037        ** index matches those columns. Also, check that the index uses
73038        ** the default collation sequences for each column. */
73039        int i, j;
73040        for(i=0; i<nCol; i++){
73041          int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
73042          char *zDfltColl;                  /* Def. collation for column */
73043          char *zIdxCol;                    /* Name of indexed column */
73044
73045          /* If the index uses a collation sequence that is different from
73046          ** the default collation sequence for the column, this index is
73047          ** unusable. Bail out early in this case.  */
73048          zDfltColl = pParent->aCol[iCol].zColl;
73049          if( !zDfltColl ){
73050            zDfltColl = "BINARY";
73051          }
73052          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
73053
73054          zIdxCol = pParent->aCol[iCol].zName;
73055          for(j=0; j<nCol; j++){
73056            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
73057              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
73058              break;
73059            }
73060          }
73061          if( j==nCol ) break;
73062        }
73063        if( i==nCol ) break;      /* pIdx is usable */
73064      }
73065    }
73066  }
73067
73068  if( !pIdx ){
73069    if( !pParse->disableTriggers ){
73070      sqlite3ErrorMsg(pParse, "foreign key mismatch");
73071    }
73072    sqlite3DbFree(pParse->db, aiCol);
73073    return 1;
73074  }
73075
73076  *ppIdx = pIdx;
73077  return 0;
73078}
73079
73080/*
73081** This function is called when a row is inserted into or deleted from the
73082** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
73083** on the child table of pFKey, this function is invoked twice for each row
73084** affected - once to "delete" the old row, and then again to "insert" the
73085** new row.
73086**
73087** Each time it is called, this function generates VDBE code to locate the
73088** row in the parent table that corresponds to the row being inserted into
73089** or deleted from the child table. If the parent row can be found, no
73090** special action is taken. Otherwise, if the parent row can *not* be
73091** found in the parent table:
73092**
73093**   Operation | FK type   | Action taken
73094**   --------------------------------------------------------------------------
73095**   INSERT      immediate   Increment the "immediate constraint counter".
73096**
73097**   DELETE      immediate   Decrement the "immediate constraint counter".
73098**
73099**   INSERT      deferred    Increment the "deferred constraint counter".
73100**
73101**   DELETE      deferred    Decrement the "deferred constraint counter".
73102**
73103** These operations are identified in the comment at the top of this file
73104** (fkey.c) as "I.1" and "D.1".
73105*/
73106static void fkLookupParent(
73107  Parse *pParse,        /* Parse context */
73108  int iDb,              /* Index of database housing pTab */
73109  Table *pTab,          /* Parent table of FK pFKey */
73110  Index *pIdx,          /* Unique index on parent key columns in pTab */
73111  FKey *pFKey,          /* Foreign key constraint */
73112  int *aiCol,           /* Map from parent key columns to child table columns */
73113  int regData,          /* Address of array containing child table row */
73114  int nIncr,            /* Increment constraint counter by this */
73115  int isIgnore          /* If true, pretend pTab contains all NULL values */
73116){
73117  int i;                                    /* Iterator variable */
73118  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
73119  int iCur = pParse->nTab - 1;              /* Cursor number to use */
73120  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
73121
73122  /* If nIncr is less than zero, then check at runtime if there are any
73123  ** outstanding constraints to resolve. If there are not, there is no need
73124  ** to check if deleting this row resolves any outstanding violations.
73125  **
73126  ** Check if any of the key columns in the child table row are NULL. If
73127  ** any are, then the constraint is considered satisfied. No need to
73128  ** search for a matching row in the parent table.  */
73129  if( nIncr<0 ){
73130    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
73131  }
73132  for(i=0; i<pFKey->nCol; i++){
73133    int iReg = aiCol[i] + regData + 1;
73134    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
73135  }
73136
73137  if( isIgnore==0 ){
73138    if( pIdx==0 ){
73139      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
73140      ** column of the parent table (table pTab).  */
73141      int iMustBeInt;               /* Address of MustBeInt instruction */
73142      int regTemp = sqlite3GetTempReg(pParse);
73143
73144      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
73145      ** apply the affinity of the parent key). If this fails, then there
73146      ** is no matching parent key. Before using MustBeInt, make a copy of
73147      ** the value. Otherwise, the value inserted into the child key column
73148      ** will have INTEGER affinity applied to it, which may not be correct.  */
73149      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
73150      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
73151
73152      /* If the parent table is the same as the child table, and we are about
73153      ** to increment the constraint-counter (i.e. this is an INSERT operation),
73154      ** then check if the row being inserted matches itself. If so, do not
73155      ** increment the constraint-counter.  */
73156      if( pTab==pFKey->pFrom && nIncr==1 ){
73157        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
73158      }
73159
73160      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
73161      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
73162      sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
73163      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
73164      sqlite3VdbeJumpHere(v, iMustBeInt);
73165      sqlite3ReleaseTempReg(pParse, regTemp);
73166    }else{
73167      int nCol = pFKey->nCol;
73168      int regTemp = sqlite3GetTempRange(pParse, nCol);
73169      int regRec = sqlite3GetTempReg(pParse);
73170      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
73171
73172      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
73173      sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
73174      for(i=0; i<nCol; i++){
73175        sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
73176      }
73177
73178      /* If the parent table is the same as the child table, and we are about
73179      ** to increment the constraint-counter (i.e. this is an INSERT operation),
73180      ** then check if the row being inserted matches itself. If so, do not
73181      ** increment the constraint-counter.  */
73182      if( pTab==pFKey->pFrom && nIncr==1 ){
73183        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
73184        for(i=0; i<nCol; i++){
73185          int iChild = aiCol[i]+1+regData;
73186          int iParent = pIdx->aiColumn[i]+1+regData;
73187          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
73188        }
73189        sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
73190      }
73191
73192      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
73193      sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
73194      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
73195
73196      sqlite3ReleaseTempReg(pParse, regRec);
73197      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
73198    }
73199  }
73200
73201  if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
73202    /* Special case: If this is an INSERT statement that will insert exactly
73203    ** one row into the table, raise a constraint immediately instead of
73204    ** incrementing a counter. This is necessary as the VM code is being
73205    ** generated for will not open a statement transaction.  */
73206    assert( nIncr==1 );
73207    sqlite3HaltConstraint(
73208        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
73209    );
73210  }else{
73211    if( nIncr>0 && pFKey->isDeferred==0 ){
73212      sqlite3ParseToplevel(pParse)->mayAbort = 1;
73213    }
73214    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
73215  }
73216
73217  sqlite3VdbeResolveLabel(v, iOk);
73218  sqlite3VdbeAddOp1(v, OP_Close, iCur);
73219}
73220
73221/*
73222** This function is called to generate code executed when a row is deleted
73223** from the parent table of foreign key constraint pFKey and, if pFKey is
73224** deferred, when a row is inserted into the same table. When generating
73225** code for an SQL UPDATE operation, this function may be called twice -
73226** once to "delete" the old row and once to "insert" the new row.
73227**
73228** The code generated by this function scans through the rows in the child
73229** table that correspond to the parent table row being deleted or inserted.
73230** For each child row found, one of the following actions is taken:
73231**
73232**   Operation | FK type   | Action taken
73233**   --------------------------------------------------------------------------
73234**   DELETE      immediate   Increment the "immediate constraint counter".
73235**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
73236**                           throw a "foreign key constraint failed" exception.
73237**
73238**   INSERT      immediate   Decrement the "immediate constraint counter".
73239**
73240**   DELETE      deferred    Increment the "deferred constraint counter".
73241**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
73242**                           throw a "foreign key constraint failed" exception.
73243**
73244**   INSERT      deferred    Decrement the "deferred constraint counter".
73245**
73246** These operations are identified in the comment at the top of this file
73247** (fkey.c) as "I.2" and "D.2".
73248*/
73249static void fkScanChildren(
73250  Parse *pParse,                  /* Parse context */
73251  SrcList *pSrc,                  /* SrcList containing the table to scan */
73252  Table *pTab,
73253  Index *pIdx,                    /* Foreign key index */
73254  FKey *pFKey,                    /* Foreign key relationship */
73255  int *aiCol,                     /* Map from pIdx cols to child table cols */
73256  int regData,                    /* Referenced table data starts here */
73257  int nIncr                       /* Amount to increment deferred counter by */
73258){
73259  sqlite3 *db = pParse->db;       /* Database handle */
73260  int i;                          /* Iterator variable */
73261  Expr *pWhere = 0;               /* WHERE clause to scan with */
73262  NameContext sNameContext;       /* Context used to resolve WHERE clause */
73263  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
73264  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
73265  Vdbe *v = sqlite3GetVdbe(pParse);
73266
73267  assert( !pIdx || pIdx->pTable==pTab );
73268
73269  if( nIncr<0 ){
73270    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
73271  }
73272
73273  /* Create an Expr object representing an SQL expression like:
73274  **
73275  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
73276  **
73277  ** The collation sequence used for the comparison should be that of
73278  ** the parent key columns. The affinity of the parent key column should
73279  ** be applied to each child key value before the comparison takes place.
73280  */
73281  for(i=0; i<pFKey->nCol; i++){
73282    Expr *pLeft;                  /* Value from parent table row */
73283    Expr *pRight;                 /* Column ref to child table */
73284    Expr *pEq;                    /* Expression (pLeft = pRight) */
73285    int iCol;                     /* Index of column in child table */
73286    const char *zCol;             /* Name of column in child table */
73287
73288    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
73289    if( pLeft ){
73290      /* Set the collation sequence and affinity of the LHS of each TK_EQ
73291      ** expression to the parent key column defaults.  */
73292      if( pIdx ){
73293        Column *pCol;
73294        iCol = pIdx->aiColumn[i];
73295        pCol = &pIdx->pTable->aCol[iCol];
73296        pLeft->iTable = regData+iCol+1;
73297        pLeft->affinity = pCol->affinity;
73298        pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
73299      }else{
73300        pLeft->iTable = regData;
73301        pLeft->affinity = SQLITE_AFF_INTEGER;
73302      }
73303    }
73304    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
73305    assert( iCol>=0 );
73306    zCol = pFKey->pFrom->aCol[iCol].zName;
73307    pRight = sqlite3Expr(db, TK_ID, zCol);
73308    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
73309    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
73310  }
73311
73312  /* If the child table is the same as the parent table, and this scan
73313  ** is taking place as part of a DELETE operation (operation D.2), omit the
73314  ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
73315  ** clause, where $rowid is the rowid of the row being deleted.  */
73316  if( pTab==pFKey->pFrom && nIncr>0 ){
73317    Expr *pEq;                    /* Expression (pLeft = pRight) */
73318    Expr *pLeft;                  /* Value from parent table row */
73319    Expr *pRight;                 /* Column ref to child table */
73320    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
73321    pRight = sqlite3Expr(db, TK_COLUMN, 0);
73322    if( pLeft && pRight ){
73323      pLeft->iTable = regData;
73324      pLeft->affinity = SQLITE_AFF_INTEGER;
73325      pRight->iTable = pSrc->a[0].iCursor;
73326      pRight->iColumn = -1;
73327    }
73328    pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
73329    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
73330  }
73331
73332  /* Resolve the references in the WHERE clause. */
73333  memset(&sNameContext, 0, sizeof(NameContext));
73334  sNameContext.pSrcList = pSrc;
73335  sNameContext.pParse = pParse;
73336  sqlite3ResolveExprNames(&sNameContext, pWhere);
73337
73338  /* Create VDBE to loop through the entries in pSrc that match the WHERE
73339  ** clause. If the constraint is not deferred, throw an exception for
73340  ** each row found. Otherwise, for deferred constraints, increment the
73341  ** deferred constraint counter by nIncr for each row selected.  */
73342  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
73343  if( nIncr>0 && pFKey->isDeferred==0 ){
73344    sqlite3ParseToplevel(pParse)->mayAbort = 1;
73345  }
73346  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
73347  if( pWInfo ){
73348    sqlite3WhereEnd(pWInfo);
73349  }
73350
73351  /* Clean up the WHERE clause constructed above. */
73352  sqlite3ExprDelete(db, pWhere);
73353  if( iFkIfZero ){
73354    sqlite3VdbeJumpHere(v, iFkIfZero);
73355  }
73356}
73357
73358/*
73359** This function returns a pointer to the head of a linked list of FK
73360** constraints for which table pTab is the parent table. For example,
73361** given the following schema:
73362**
73363**   CREATE TABLE t1(a PRIMARY KEY);
73364**   CREATE TABLE t2(b REFERENCES t1(a);
73365**
73366** Calling this function with table "t1" as an argument returns a pointer
73367** to the FKey structure representing the foreign key constraint on table
73368** "t2". Calling this function with "t2" as the argument would return a
73369** NULL pointer (as there are no FK constraints for which t2 is the parent
73370** table).
73371*/
73372SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
73373  int nName = sqlite3Strlen30(pTab->zName);
73374  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
73375}
73376
73377/*
73378** The second argument is a Trigger structure allocated by the
73379** fkActionTrigger() routine. This function deletes the Trigger structure
73380** and all of its sub-components.
73381**
73382** The Trigger structure or any of its sub-components may be allocated from
73383** the lookaside buffer belonging to database handle dbMem.
73384*/
73385static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
73386  if( p ){
73387    TriggerStep *pStep = p->step_list;
73388    sqlite3ExprDelete(dbMem, pStep->pWhere);
73389    sqlite3ExprListDelete(dbMem, pStep->pExprList);
73390    sqlite3SelectDelete(dbMem, pStep->pSelect);
73391    sqlite3ExprDelete(dbMem, p->pWhen);
73392    sqlite3DbFree(dbMem, p);
73393  }
73394}
73395
73396/*
73397** This function is called to generate code that runs when table pTab is
73398** being dropped from the database. The SrcList passed as the second argument
73399** to this function contains a single entry guaranteed to resolve to
73400** table pTab.
73401**
73402** Normally, no code is required. However, if either
73403**
73404**   (a) The table is the parent table of a FK constraint, or
73405**   (b) The table is the child table of a deferred FK constraint and it is
73406**       determined at runtime that there are outstanding deferred FK
73407**       constraint violations in the database,
73408**
73409** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
73410** the table from the database. Triggers are disabled while running this
73411** DELETE, but foreign key actions are not.
73412*/
73413SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
73414  sqlite3 *db = pParse->db;
73415  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
73416    int iSkip = 0;
73417    Vdbe *v = sqlite3GetVdbe(pParse);
73418
73419    assert( v );                  /* VDBE has already been allocated */
73420    if( sqlite3FkReferences(pTab)==0 ){
73421      /* Search for a deferred foreign key constraint for which this table
73422      ** is the child table. If one cannot be found, return without
73423      ** generating any VDBE code. If one can be found, then jump over
73424      ** the entire DELETE if there are no outstanding deferred constraints
73425      ** when this statement is run.  */
73426      FKey *p;
73427      for(p=pTab->pFKey; p; p=p->pNextFrom){
73428        if( p->isDeferred ) break;
73429      }
73430      if( !p ) return;
73431      iSkip = sqlite3VdbeMakeLabel(v);
73432      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
73433    }
73434
73435    pParse->disableTriggers = 1;
73436    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
73437    pParse->disableTriggers = 0;
73438
73439    /* If the DELETE has generated immediate foreign key constraint
73440    ** violations, halt the VDBE and return an error at this point, before
73441    ** any modifications to the schema are made. This is because statement
73442    ** transactions are not able to rollback schema changes.  */
73443    sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
73444    sqlite3HaltConstraint(
73445        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
73446    );
73447
73448    if( iSkip ){
73449      sqlite3VdbeResolveLabel(v, iSkip);
73450    }
73451  }
73452}
73453
73454/*
73455** This function is called when inserting, deleting or updating a row of
73456** table pTab to generate VDBE code to perform foreign key constraint
73457** processing for the operation.
73458**
73459** For a DELETE operation, parameter regOld is passed the index of the
73460** first register in an array of (pTab->nCol+1) registers containing the
73461** rowid of the row being deleted, followed by each of the column values
73462** of the row being deleted, from left to right. Parameter regNew is passed
73463** zero in this case.
73464**
73465** For an INSERT operation, regOld is passed zero and regNew is passed the
73466** first register of an array of (pTab->nCol+1) registers containing the new
73467** row data.
73468**
73469** For an UPDATE operation, this function is called twice. Once before
73470** the original record is deleted from the table using the calling convention
73471** described for DELETE. Then again after the original record is deleted
73472** but before the new record is inserted using the INSERT convention.
73473*/
73474SQLITE_PRIVATE void sqlite3FkCheck(
73475  Parse *pParse,                  /* Parse context */
73476  Table *pTab,                    /* Row is being deleted from this table */
73477  int regOld,                     /* Previous row data is stored here */
73478  int regNew                      /* New row data is stored here */
73479){
73480  sqlite3 *db = pParse->db;       /* Database handle */
73481  Vdbe *v;                        /* VM to write code to */
73482  FKey *pFKey;                    /* Used to iterate through FKs */
73483  int iDb;                        /* Index of database containing pTab */
73484  const char *zDb;                /* Name of database containing pTab */
73485  int isIgnoreErrors = pParse->disableTriggers;
73486
73487  /* Exactly one of regOld and regNew should be non-zero. */
73488  assert( (regOld==0)!=(regNew==0) );
73489
73490  /* If foreign-keys are disabled, this function is a no-op. */
73491  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
73492
73493  v = sqlite3GetVdbe(pParse);
73494  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
73495  zDb = db->aDb[iDb].zName;
73496
73497  /* Loop through all the foreign key constraints for which pTab is the
73498  ** child table (the table that the foreign key definition is part of).  */
73499  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
73500    Table *pTo;                   /* Parent table of foreign key pFKey */
73501    Index *pIdx = 0;              /* Index on key columns in pTo */
73502    int *aiFree = 0;
73503    int *aiCol;
73504    int iCol;
73505    int i;
73506    int isIgnore = 0;
73507
73508    /* Find the parent table of this foreign key. Also find a unique index
73509    ** on the parent key columns in the parent table. If either of these
73510    ** schema items cannot be located, set an error in pParse and return
73511    ** early.  */
73512    if( pParse->disableTriggers ){
73513      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
73514    }else{
73515      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
73516    }
73517    if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
73518      if( !isIgnoreErrors || db->mallocFailed ) return;
73519      continue;
73520    }
73521    assert( pFKey->nCol==1 || (aiFree && pIdx) );
73522
73523    if( aiFree ){
73524      aiCol = aiFree;
73525    }else{
73526      iCol = pFKey->aCol[0].iFrom;
73527      aiCol = &iCol;
73528    }
73529    for(i=0; i<pFKey->nCol; i++){
73530      if( aiCol[i]==pTab->iPKey ){
73531        aiCol[i] = -1;
73532      }
73533#ifndef SQLITE_OMIT_AUTHORIZATION
73534      /* Request permission to read the parent key columns. If the
73535      ** authorization callback returns SQLITE_IGNORE, behave as if any
73536      ** values read from the parent table are NULL. */
73537      if( db->xAuth ){
73538        int rcauth;
73539        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
73540        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
73541        isIgnore = (rcauth==SQLITE_IGNORE);
73542      }
73543#endif
73544    }
73545
73546    /* Take a shared-cache advisory read-lock on the parent table. Allocate
73547    ** a cursor to use to search the unique index on the parent key columns
73548    ** in the parent table.  */
73549    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
73550    pParse->nTab++;
73551
73552    if( regOld!=0 ){
73553      /* A row is being removed from the child table. Search for the parent.
73554      ** If the parent does not exist, removing the child row resolves an
73555      ** outstanding foreign key constraint violation. */
73556      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
73557    }
73558    if( regNew!=0 ){
73559      /* A row is being added to the child table. If a parent row cannot
73560      ** be found, adding the child row has violated the FK constraint. */
73561      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
73562    }
73563
73564    sqlite3DbFree(db, aiFree);
73565  }
73566
73567  /* Loop through all the foreign key constraints that refer to this table */
73568  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
73569    Index *pIdx = 0;              /* Foreign key index for pFKey */
73570    SrcList *pSrc;
73571    int *aiCol = 0;
73572
73573    if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
73574      assert( regOld==0 && regNew!=0 );
73575      /* Inserting a single row into a parent table cannot cause an immediate
73576      ** foreign key violation. So do nothing in this case.  */
73577      continue;
73578    }
73579
73580    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
73581      if( !isIgnoreErrors || db->mallocFailed ) return;
73582      continue;
73583    }
73584    assert( aiCol || pFKey->nCol==1 );
73585
73586    /* Create a SrcList structure containing a single table (the table
73587    ** the foreign key that refers to this table is attached to). This
73588    ** is required for the sqlite3WhereXXX() interface.  */
73589    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
73590    if( pSrc ){
73591      struct SrcList_item *pItem = pSrc->a;
73592      pItem->pTab = pFKey->pFrom;
73593      pItem->zName = pFKey->pFrom->zName;
73594      pItem->pTab->nRef++;
73595      pItem->iCursor = pParse->nTab++;
73596
73597      if( regNew!=0 ){
73598        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
73599      }
73600      if( regOld!=0 ){
73601        /* If there is a RESTRICT action configured for the current operation
73602        ** on the parent table of this FK, then throw an exception
73603        ** immediately if the FK constraint is violated, even if this is a
73604        ** deferred trigger. That's what RESTRICT means. To defer checking
73605        ** the constraint, the FK should specify NO ACTION (represented
73606        ** using OE_None). NO ACTION is the default.  */
73607        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
73608      }
73609      pItem->zName = 0;
73610      sqlite3SrcListDelete(db, pSrc);
73611    }
73612    sqlite3DbFree(db, aiCol);
73613  }
73614}
73615
73616#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
73617
73618/*
73619** This function is called before generating code to update or delete a
73620** row contained in table pTab.
73621*/
73622SQLITE_PRIVATE u32 sqlite3FkOldmask(
73623  Parse *pParse,                  /* Parse context */
73624  Table *pTab                     /* Table being modified */
73625){
73626  u32 mask = 0;
73627  if( pParse->db->flags&SQLITE_ForeignKeys ){
73628    FKey *p;
73629    int i;
73630    for(p=pTab->pFKey; p; p=p->pNextFrom){
73631      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
73632    }
73633    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
73634      Index *pIdx = 0;
73635      locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
73636      if( pIdx ){
73637        for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
73638      }
73639    }
73640  }
73641  return mask;
73642}
73643
73644/*
73645** This function is called before generating code to update or delete a
73646** row contained in table pTab. If the operation is a DELETE, then
73647** parameter aChange is passed a NULL value. For an UPDATE, aChange points
73648** to an array of size N, where N is the number of columns in table pTab.
73649** If the i'th column is not modified by the UPDATE, then the corresponding
73650** entry in the aChange[] array is set to -1. If the column is modified,
73651** the value is 0 or greater. Parameter chngRowid is set to true if the
73652** UPDATE statement modifies the rowid fields of the table.
73653**
73654** If any foreign key processing will be required, this function returns
73655** true. If there is no foreign key related processing, this function
73656** returns false.
73657*/
73658SQLITE_PRIVATE int sqlite3FkRequired(
73659  Parse *pParse,                  /* Parse context */
73660  Table *pTab,                    /* Table being modified */
73661  int *aChange,                   /* Non-NULL for UPDATE operations */
73662  int chngRowid                   /* True for UPDATE that affects rowid */
73663){
73664  if( pParse->db->flags&SQLITE_ForeignKeys ){
73665    if( !aChange ){
73666      /* A DELETE operation. Foreign key processing is required if the
73667      ** table in question is either the child or parent table for any
73668      ** foreign key constraint.  */
73669      return (sqlite3FkReferences(pTab) || pTab->pFKey);
73670    }else{
73671      /* This is an UPDATE. Foreign key processing is only required if the
73672      ** operation modifies one or more child or parent key columns. */
73673      int i;
73674      FKey *p;
73675
73676      /* Check if any child key columns are being modified. */
73677      for(p=pTab->pFKey; p; p=p->pNextFrom){
73678        for(i=0; i<p->nCol; i++){
73679          int iChildKey = p->aCol[i].iFrom;
73680          if( aChange[iChildKey]>=0 ) return 1;
73681          if( iChildKey==pTab->iPKey && chngRowid ) return 1;
73682        }
73683      }
73684
73685      /* Check if any parent key columns are being modified. */
73686      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
73687        for(i=0; i<p->nCol; i++){
73688          char *zKey = p->aCol[i].zCol;
73689          int iKey;
73690          for(iKey=0; iKey<pTab->nCol; iKey++){
73691            Column *pCol = &pTab->aCol[iKey];
73692            if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
73693              if( aChange[iKey]>=0 ) return 1;
73694              if( iKey==pTab->iPKey && chngRowid ) return 1;
73695            }
73696          }
73697        }
73698      }
73699    }
73700  }
73701  return 0;
73702}
73703
73704/*
73705** This function is called when an UPDATE or DELETE operation is being
73706** compiled on table pTab, which is the parent table of foreign-key pFKey.
73707** If the current operation is an UPDATE, then the pChanges parameter is
73708** passed a pointer to the list of columns being modified. If it is a
73709** DELETE, pChanges is passed a NULL pointer.
73710**
73711** It returns a pointer to a Trigger structure containing a trigger
73712** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
73713** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
73714** returned (these actions require no special handling by the triggers
73715** sub-system, code for them is created by fkScanChildren()).
73716**
73717** For example, if pFKey is the foreign key and pTab is table "p" in
73718** the following schema:
73719**
73720**   CREATE TABLE p(pk PRIMARY KEY);
73721**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
73722**
73723** then the returned trigger structure is equivalent to:
73724**
73725**   CREATE TRIGGER ... DELETE ON p BEGIN
73726**     DELETE FROM c WHERE ck = old.pk;
73727**   END;
73728**
73729** The returned pointer is cached as part of the foreign key object. It
73730** is eventually freed along with the rest of the foreign key object by
73731** sqlite3FkDelete().
73732*/
73733static Trigger *fkActionTrigger(
73734  Parse *pParse,                  /* Parse context */
73735  Table *pTab,                    /* Table being updated or deleted from */
73736  FKey *pFKey,                    /* Foreign key to get action for */
73737  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
73738){
73739  sqlite3 *db = pParse->db;       /* Database handle */
73740  int action;                     /* One of OE_None, OE_Cascade etc. */
73741  Trigger *pTrigger;              /* Trigger definition to return */
73742  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
73743
73744  action = pFKey->aAction[iAction];
73745  pTrigger = pFKey->apTrigger[iAction];
73746
73747  if( action!=OE_None && !pTrigger ){
73748    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
73749    char const *zFrom;            /* Name of child table */
73750    int nFrom;                    /* Length in bytes of zFrom */
73751    Index *pIdx = 0;              /* Parent key index for this FK */
73752    int *aiCol = 0;               /* child table cols -> parent key cols */
73753    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
73754    Expr *pWhere = 0;             /* WHERE clause of trigger step */
73755    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
73756    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
73757    int i;                        /* Iterator variable */
73758    Expr *pWhen = 0;              /* WHEN clause for the trigger */
73759
73760    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
73761    assert( aiCol || pFKey->nCol==1 );
73762
73763    for(i=0; i<pFKey->nCol; i++){
73764      Token tOld = { "old", 3 };  /* Literal "old" token */
73765      Token tNew = { "new", 3 };  /* Literal "new" token */
73766      Token tFromCol;             /* Name of column in child table */
73767      Token tToCol;               /* Name of column in parent table */
73768      int iFromCol;               /* Idx of column in child table */
73769      Expr *pEq;                  /* tFromCol = OLD.tToCol */
73770
73771      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
73772      assert( iFromCol>=0 );
73773      tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
73774      tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
73775
73776      tToCol.n = sqlite3Strlen30(tToCol.z);
73777      tFromCol.n = sqlite3Strlen30(tFromCol.z);
73778
73779      /* Create the expression "OLD.zToCol = zFromCol". It is important
73780      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
73781      ** that the affinity and collation sequence associated with the
73782      ** parent table are used for the comparison. */
73783      pEq = sqlite3PExpr(pParse, TK_EQ,
73784          sqlite3PExpr(pParse, TK_DOT,
73785            sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
73786            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
73787          , 0),
73788          sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
73789      , 0);
73790      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
73791
73792      /* For ON UPDATE, construct the next term of the WHEN clause.
73793      ** The final WHEN clause will be like this:
73794      **
73795      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
73796      */
73797      if( pChanges ){
73798        pEq = sqlite3PExpr(pParse, TK_IS,
73799            sqlite3PExpr(pParse, TK_DOT,
73800              sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
73801              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
73802              0),
73803            sqlite3PExpr(pParse, TK_DOT,
73804              sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
73805              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
73806              0),
73807            0);
73808        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
73809      }
73810
73811      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
73812        Expr *pNew;
73813        if( action==OE_Cascade ){
73814          pNew = sqlite3PExpr(pParse, TK_DOT,
73815            sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
73816            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
73817          , 0);
73818        }else if( action==OE_SetDflt ){
73819          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
73820          if( pDflt ){
73821            pNew = sqlite3ExprDup(db, pDflt, 0);
73822          }else{
73823            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
73824          }
73825        }else{
73826          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
73827        }
73828        pList = sqlite3ExprListAppend(pParse, pList, pNew);
73829        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
73830      }
73831    }
73832    sqlite3DbFree(db, aiCol);
73833
73834    zFrom = pFKey->pFrom->zName;
73835    nFrom = sqlite3Strlen30(zFrom);
73836
73837    if( action==OE_Restrict ){
73838      Token tFrom;
73839      Expr *pRaise;
73840
73841      tFrom.z = zFrom;
73842      tFrom.n = nFrom;
73843      pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
73844      if( pRaise ){
73845        pRaise->affinity = OE_Abort;
73846      }
73847      pSelect = sqlite3SelectNew(pParse,
73848          sqlite3ExprListAppend(pParse, 0, pRaise),
73849          sqlite3SrcListAppend(db, 0, &tFrom, 0),
73850          pWhere,
73851          0, 0, 0, 0, 0, 0
73852      );
73853      pWhere = 0;
73854    }
73855
73856    /* In the current implementation, pTab->dbMem==0 for all tables except
73857    ** for temporary tables used to describe subqueries.  And temporary
73858    ** tables do not have foreign key constraints.  Hence, pTab->dbMem
73859    ** should always be 0 there.
73860    */
73861    enableLookaside = db->lookaside.bEnabled;
73862    db->lookaside.bEnabled = 0;
73863
73864    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
73865        sizeof(Trigger) +         /* struct Trigger */
73866        sizeof(TriggerStep) +     /* Single step in trigger program */
73867        nFrom + 1                 /* Space for pStep->target.z */
73868    );
73869    if( pTrigger ){
73870      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
73871      pStep->target.z = (char *)&pStep[1];
73872      pStep->target.n = nFrom;
73873      memcpy((char *)pStep->target.z, zFrom, nFrom);
73874
73875      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
73876      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
73877      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
73878      if( pWhen ){
73879        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
73880        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
73881      }
73882    }
73883
73884    /* Re-enable the lookaside buffer, if it was disabled earlier. */
73885    db->lookaside.bEnabled = enableLookaside;
73886
73887    sqlite3ExprDelete(db, pWhere);
73888    sqlite3ExprDelete(db, pWhen);
73889    sqlite3ExprListDelete(db, pList);
73890    sqlite3SelectDelete(db, pSelect);
73891    if( db->mallocFailed==1 ){
73892      fkTriggerDelete(db, pTrigger);
73893      return 0;
73894    }
73895
73896    switch( action ){
73897      case OE_Restrict:
73898        pStep->op = TK_SELECT;
73899        break;
73900      case OE_Cascade:
73901        if( !pChanges ){
73902          pStep->op = TK_DELETE;
73903          break;
73904        }
73905      default:
73906        pStep->op = TK_UPDATE;
73907    }
73908    pStep->pTrig = pTrigger;
73909    pTrigger->pSchema = pTab->pSchema;
73910    pTrigger->pTabSchema = pTab->pSchema;
73911    pFKey->apTrigger[iAction] = pTrigger;
73912    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
73913  }
73914
73915  return pTrigger;
73916}
73917
73918/*
73919** This function is called when deleting or updating a row to implement
73920** any required CASCADE, SET NULL or SET DEFAULT actions.
73921*/
73922SQLITE_PRIVATE void sqlite3FkActions(
73923  Parse *pParse,                  /* Parse context */
73924  Table *pTab,                    /* Table being updated or deleted from */
73925  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
73926  int regOld                      /* Address of array containing old row */
73927){
73928  /* If foreign-key support is enabled, iterate through all FKs that
73929  ** refer to table pTab. If there is an action associated with the FK
73930  ** for this operation (either update or delete), invoke the associated
73931  ** trigger sub-program.  */
73932  if( pParse->db->flags&SQLITE_ForeignKeys ){
73933    FKey *pFKey;                  /* Iterator variable */
73934    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
73935      Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
73936      if( pAction ){
73937        sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
73938      }
73939    }
73940  }
73941}
73942
73943#endif /* ifndef SQLITE_OMIT_TRIGGER */
73944
73945/*
73946** Free all memory associated with foreign key definitions attached to
73947** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
73948** hash table.
73949*/
73950SQLITE_PRIVATE void sqlite3FkDelete(Table *pTab){
73951  FKey *pFKey;                    /* Iterator variable */
73952  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
73953
73954  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
73955
73956    /* Remove the FK from the fkeyHash hash table. */
73957    if( pFKey->pPrevTo ){
73958      pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
73959    }else{
73960      void *data = (void *)pFKey->pNextTo;
73961      const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
73962      sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
73963    }
73964    if( pFKey->pNextTo ){
73965      pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
73966    }
73967
73968    /* Delete any triggers created to implement actions for this FK. */
73969#ifndef SQLITE_OMIT_TRIGGER
73970    fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
73971    fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
73972#endif
73973
73974    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
73975    ** classified as either immediate or deferred.
73976    */
73977    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
73978
73979    pNext = pFKey->pNextFrom;
73980    sqlite3DbFree(pTab->dbMem, pFKey);
73981  }
73982}
73983#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
73984
73985/************** End of fkey.c ************************************************/
73986/************** Begin file insert.c ******************************************/
73987/*
73988** 2001 September 15
73989**
73990** The author disclaims copyright to this source code.  In place of
73991** a legal notice, here is a blessing:
73992**
73993**    May you do good and not evil.
73994**    May you find forgiveness for yourself and forgive others.
73995**    May you share freely, never taking more than you give.
73996**
73997*************************************************************************
73998** This file contains C code routines that are called by the parser
73999** to handle INSERT statements in SQLite.
74000*/
74001
74002/*
74003** Generate code that will open a table for reading.
74004*/
74005SQLITE_PRIVATE void sqlite3OpenTable(
74006  Parse *p,       /* Generate code into this VDBE */
74007  int iCur,       /* The cursor number of the table */
74008  int iDb,        /* The database index in sqlite3.aDb[] */
74009  Table *pTab,    /* The table to be opened */
74010  int opcode      /* OP_OpenRead or OP_OpenWrite */
74011){
74012  Vdbe *v;
74013  if( IsVirtual(pTab) ) return;
74014  v = sqlite3GetVdbe(p);
74015  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
74016  sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
74017  sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
74018  sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
74019  VdbeComment((v, "%s", pTab->zName));
74020}
74021
74022/*
74023** Return a pointer to the column affinity string associated with index
74024** pIdx. A column affinity string has one character for each column in
74025** the table, according to the affinity of the column:
74026**
74027**  Character      Column affinity
74028**  ------------------------------
74029**  'a'            TEXT
74030**  'b'            NONE
74031**  'c'            NUMERIC
74032**  'd'            INTEGER
74033**  'e'            REAL
74034**
74035** An extra 'b' is appended to the end of the string to cover the
74036** rowid that appears as the last column in every index.
74037**
74038** Memory for the buffer containing the column index affinity string
74039** is managed along with the rest of the Index structure. It will be
74040** released when sqlite3DeleteIndex() is called.
74041*/
74042SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
74043  if( !pIdx->zColAff ){
74044    /* The first time a column affinity string for a particular index is
74045    ** required, it is allocated and populated here. It is then stored as
74046    ** a member of the Index structure for subsequent use.
74047    **
74048    ** The column affinity string will eventually be deleted by
74049    ** sqliteDeleteIndex() when the Index structure itself is cleaned
74050    ** up.
74051    */
74052    int n;
74053    Table *pTab = pIdx->pTable;
74054    sqlite3 *db = sqlite3VdbeDb(v);
74055    pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
74056    if( !pIdx->zColAff ){
74057      db->mallocFailed = 1;
74058      return 0;
74059    }
74060    for(n=0; n<pIdx->nColumn; n++){
74061      pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
74062    }
74063    pIdx->zColAff[n++] = SQLITE_AFF_NONE;
74064    pIdx->zColAff[n] = 0;
74065  }
74066
74067  return pIdx->zColAff;
74068}
74069
74070/*
74071** Set P4 of the most recently inserted opcode to a column affinity
74072** string for table pTab. A column affinity string has one character
74073** for each column indexed by the index, according to the affinity of the
74074** column:
74075**
74076**  Character      Column affinity
74077**  ------------------------------
74078**  'a'            TEXT
74079**  'b'            NONE
74080**  'c'            NUMERIC
74081**  'd'            INTEGER
74082**  'e'            REAL
74083*/
74084SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
74085  /* The first time a column affinity string for a particular table
74086  ** is required, it is allocated and populated here. It is then
74087  ** stored as a member of the Table structure for subsequent use.
74088  **
74089  ** The column affinity string will eventually be deleted by
74090  ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
74091  */
74092  if( !pTab->zColAff ){
74093    char *zColAff;
74094    int i;
74095    sqlite3 *db = sqlite3VdbeDb(v);
74096
74097    zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
74098    if( !zColAff ){
74099      db->mallocFailed = 1;
74100      return;
74101    }
74102
74103    for(i=0; i<pTab->nCol; i++){
74104      zColAff[i] = pTab->aCol[i].affinity;
74105    }
74106    zColAff[pTab->nCol] = '\0';
74107
74108    pTab->zColAff = zColAff;
74109  }
74110
74111  sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
74112}
74113
74114/*
74115** Return non-zero if the table pTab in database iDb or any of its indices
74116** have been opened at any point in the VDBE program beginning at location
74117** iStartAddr throught the end of the program.  This is used to see if
74118** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
74119** run without using temporary table for the results of the SELECT.
74120*/
74121static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
74122  Vdbe *v = sqlite3GetVdbe(p);
74123  int i;
74124  int iEnd = sqlite3VdbeCurrentAddr(v);
74125#ifndef SQLITE_OMIT_VIRTUALTABLE
74126  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
74127#endif
74128
74129  for(i=iStartAddr; i<iEnd; i++){
74130    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
74131    assert( pOp!=0 );
74132    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
74133      Index *pIndex;
74134      int tnum = pOp->p2;
74135      if( tnum==pTab->tnum ){
74136        return 1;
74137      }
74138      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
74139        if( tnum==pIndex->tnum ){
74140          return 1;
74141        }
74142      }
74143    }
74144#ifndef SQLITE_OMIT_VIRTUALTABLE
74145    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
74146      assert( pOp->p4.pVtab!=0 );
74147      assert( pOp->p4type==P4_VTAB );
74148      return 1;
74149    }
74150#endif
74151  }
74152  return 0;
74153}
74154
74155#ifndef SQLITE_OMIT_AUTOINCREMENT
74156/*
74157** Locate or create an AutoincInfo structure associated with table pTab
74158** which is in database iDb.  Return the register number for the register
74159** that holds the maximum rowid.
74160**
74161** There is at most one AutoincInfo structure per table even if the
74162** same table is autoincremented multiple times due to inserts within
74163** triggers.  A new AutoincInfo structure is created if this is the
74164** first use of table pTab.  On 2nd and subsequent uses, the original
74165** AutoincInfo structure is used.
74166**
74167** Three memory locations are allocated:
74168**
74169**   (1)  Register to hold the name of the pTab table.
74170**   (2)  Register to hold the maximum ROWID of pTab.
74171**   (3)  Register to hold the rowid in sqlite_sequence of pTab
74172**
74173** The 2nd register is the one that is returned.  That is all the
74174** insert routine needs to know about.
74175*/
74176static int autoIncBegin(
74177  Parse *pParse,      /* Parsing context */
74178  int iDb,            /* Index of the database holding pTab */
74179  Table *pTab         /* The table we are writing to */
74180){
74181  int memId = 0;      /* Register holding maximum rowid */
74182  if( pTab->tabFlags & TF_Autoincrement ){
74183    Parse *pToplevel = sqlite3ParseToplevel(pParse);
74184    AutoincInfo *pInfo;
74185
74186    pInfo = pToplevel->pAinc;
74187    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
74188    if( pInfo==0 ){
74189      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
74190      if( pInfo==0 ) return 0;
74191      pInfo->pNext = pToplevel->pAinc;
74192      pToplevel->pAinc = pInfo;
74193      pInfo->pTab = pTab;
74194      pInfo->iDb = iDb;
74195      pToplevel->nMem++;                  /* Register to hold name of table */
74196      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
74197      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
74198    }
74199    memId = pInfo->regCtr;
74200  }
74201  return memId;
74202}
74203
74204/*
74205** This routine generates code that will initialize all of the
74206** register used by the autoincrement tracker.
74207*/
74208SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
74209  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
74210  sqlite3 *db = pParse->db;  /* The database connection */
74211  Db *pDb;                   /* Database only autoinc table */
74212  int memId;                 /* Register holding max rowid */
74213  int addr;                  /* A VDBE address */
74214  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
74215
74216  /* This routine is never called during trigger-generation.  It is
74217  ** only called from the top-level */
74218  assert( pParse->pTriggerTab==0 );
74219  assert( pParse==sqlite3ParseToplevel(pParse) );
74220
74221  assert( v );   /* We failed long ago if this is not so */
74222  for(p = pParse->pAinc; p; p = p->pNext){
74223    pDb = &db->aDb[p->iDb];
74224    memId = p->regCtr;
74225    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
74226    addr = sqlite3VdbeCurrentAddr(v);
74227    sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
74228    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
74229    sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
74230    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
74231    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
74232    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
74233    sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
74234    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
74235    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
74236    sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
74237    sqlite3VdbeAddOp0(v, OP_Close);
74238  }
74239}
74240
74241/*
74242** Update the maximum rowid for an autoincrement calculation.
74243**
74244** This routine should be called when the top of the stack holds a
74245** new rowid that is about to be inserted.  If that new rowid is
74246** larger than the maximum rowid in the memId memory cell, then the
74247** memory cell is updated.  The stack is unchanged.
74248*/
74249static void autoIncStep(Parse *pParse, int memId, int regRowid){
74250  if( memId>0 ){
74251    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
74252  }
74253}
74254
74255/*
74256** This routine generates the code needed to write autoincrement
74257** maximum rowid values back into the sqlite_sequence register.
74258** Every statement that might do an INSERT into an autoincrement
74259** table (either directly or through triggers) needs to call this
74260** routine just before the "exit" code.
74261*/
74262SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
74263  AutoincInfo *p;
74264  Vdbe *v = pParse->pVdbe;
74265  sqlite3 *db = pParse->db;
74266
74267  assert( v );
74268  for(p = pParse->pAinc; p; p = p->pNext){
74269    Db *pDb = &db->aDb[p->iDb];
74270    int j1, j2, j3, j4, j5;
74271    int iRec;
74272    int memId = p->regCtr;
74273
74274    iRec = sqlite3GetTempReg(pParse);
74275    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
74276    j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
74277    j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
74278    j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
74279    j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
74280    sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
74281    sqlite3VdbeJumpHere(v, j2);
74282    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
74283    j5 = sqlite3VdbeAddOp0(v, OP_Goto);
74284    sqlite3VdbeJumpHere(v, j4);
74285    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
74286    sqlite3VdbeJumpHere(v, j1);
74287    sqlite3VdbeJumpHere(v, j5);
74288    sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
74289    sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
74290    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
74291    sqlite3VdbeAddOp0(v, OP_Close);
74292    sqlite3ReleaseTempReg(pParse, iRec);
74293  }
74294}
74295#else
74296/*
74297** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
74298** above are all no-ops
74299*/
74300# define autoIncBegin(A,B,C) (0)
74301# define autoIncStep(A,B,C)
74302#endif /* SQLITE_OMIT_AUTOINCREMENT */
74303
74304
74305/* Forward declaration */
74306static int xferOptimization(
74307  Parse *pParse,        /* Parser context */
74308  Table *pDest,         /* The table we are inserting into */
74309  Select *pSelect,      /* A SELECT statement to use as the data source */
74310  int onError,          /* How to handle constraint errors */
74311  int iDbDest           /* The database of pDest */
74312);
74313
74314/*
74315** This routine is call to handle SQL of the following forms:
74316**
74317**    insert into TABLE (IDLIST) values(EXPRLIST)
74318**    insert into TABLE (IDLIST) select
74319**
74320** The IDLIST following the table name is always optional.  If omitted,
74321** then a list of all columns for the table is substituted.  The IDLIST
74322** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
74323**
74324** The pList parameter holds EXPRLIST in the first form of the INSERT
74325** statement above, and pSelect is NULL.  For the second form, pList is
74326** NULL and pSelect is a pointer to the select statement used to generate
74327** data for the insert.
74328**
74329** The code generated follows one of four templates.  For a simple
74330** select with data coming from a VALUES clause, the code executes
74331** once straight down through.  Pseudo-code follows (we call this
74332** the "1st template"):
74333**
74334**         open write cursor to <table> and its indices
74335**         puts VALUES clause expressions onto the stack
74336**         write the resulting record into <table>
74337**         cleanup
74338**
74339** The three remaining templates assume the statement is of the form
74340**
74341**   INSERT INTO <table> SELECT ...
74342**
74343** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
74344** in other words if the SELECT pulls all columns from a single table
74345** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
74346** if <table2> and <table1> are distinct tables but have identical
74347** schemas, including all the same indices, then a special optimization
74348** is invoked that copies raw records from <table2> over to <table1>.
74349** See the xferOptimization() function for the implementation of this
74350** template.  This is the 2nd template.
74351**
74352**         open a write cursor to <table>
74353**         open read cursor on <table2>
74354**         transfer all records in <table2> over to <table>
74355**         close cursors
74356**         foreach index on <table>
74357**           open a write cursor on the <table> index
74358**           open a read cursor on the corresponding <table2> index
74359**           transfer all records from the read to the write cursors
74360**           close cursors
74361**         end foreach
74362**
74363** The 3rd template is for when the second template does not apply
74364** and the SELECT clause does not read from <table> at any time.
74365** The generated code follows this template:
74366**
74367**         EOF <- 0
74368**         X <- A
74369**         goto B
74370**      A: setup for the SELECT
74371**         loop over the rows in the SELECT
74372**           load values into registers R..R+n
74373**           yield X
74374**         end loop
74375**         cleanup after the SELECT
74376**         EOF <- 1
74377**         yield X
74378**         goto A
74379**      B: open write cursor to <table> and its indices
74380**      C: yield X
74381**         if EOF goto D
74382**         insert the select result into <table> from R..R+n
74383**         goto C
74384**      D: cleanup
74385**
74386** The 4th template is used if the insert statement takes its
74387** values from a SELECT but the data is being inserted into a table
74388** that is also read as part of the SELECT.  In the third form,
74389** we have to use a intermediate table to store the results of
74390** the select.  The template is like this:
74391**
74392**         EOF <- 0
74393**         X <- A
74394**         goto B
74395**      A: setup for the SELECT
74396**         loop over the tables in the SELECT
74397**           load value into register R..R+n
74398**           yield X
74399**         end loop
74400**         cleanup after the SELECT
74401**         EOF <- 1
74402**         yield X
74403**         halt-error
74404**      B: open temp table
74405**      L: yield X
74406**         if EOF goto M
74407**         insert row from R..R+n into temp table
74408**         goto L
74409**      M: open write cursor to <table> and its indices
74410**         rewind temp table
74411**      C: loop over rows of intermediate table
74412**           transfer values form intermediate table into <table>
74413**         end loop
74414**      D: cleanup
74415*/
74416SQLITE_PRIVATE void sqlite3Insert(
74417  Parse *pParse,        /* Parser context */
74418  SrcList *pTabList,    /* Name of table into which we are inserting */
74419  ExprList *pList,      /* List of values to be inserted */
74420  Select *pSelect,      /* A SELECT statement to use as the data source */
74421  IdList *pColumn,      /* Column names corresponding to IDLIST. */
74422  int onError           /* How to handle constraint errors */
74423){
74424  sqlite3 *db;          /* The main database structure */
74425  Table *pTab;          /* The table to insert into.  aka TABLE */
74426  char *zTab;           /* Name of the table into which we are inserting */
74427  const char *zDb;      /* Name of the database holding this table */
74428  int i, j, idx;        /* Loop counters */
74429  Vdbe *v;              /* Generate code into this virtual machine */
74430  Index *pIdx;          /* For looping over indices of the table */
74431  int nColumn;          /* Number of columns in the data */
74432  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
74433  int baseCur = 0;      /* VDBE Cursor number for pTab */
74434  int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
74435  int endOfLoop;        /* Label for the end of the insertion loop */
74436  int useTempTable = 0; /* Store SELECT results in intermediate table */
74437  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
74438  int addrInsTop = 0;   /* Jump to label "D" */
74439  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
74440  int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
74441  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
74442  int iDb;              /* Index of database holding TABLE */
74443  Db *pDb;              /* The database containing table being inserted into */
74444  int appendFlag = 0;   /* True if the insert is likely to be an append */
74445
74446  /* Register allocations */
74447  int regFromSelect = 0;/* Base register for data coming from SELECT */
74448  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
74449  int regRowCount = 0;  /* Memory cell used for the row counter */
74450  int regIns;           /* Block of regs holding rowid+data being inserted */
74451  int regRowid;         /* registers holding insert rowid */
74452  int regData;          /* register holding first column to insert */
74453  int regRecord;        /* Holds the assemblied row record */
74454  int regEof = 0;       /* Register recording end of SELECT data */
74455  int *aRegIdx = 0;     /* One register allocated to each index */
74456
74457#ifndef SQLITE_OMIT_TRIGGER
74458  int isView;                 /* True if attempting to insert into a view */
74459  Trigger *pTrigger;          /* List of triggers on pTab, if required */
74460  int tmask;                  /* Mask of trigger times */
74461#endif
74462
74463  db = pParse->db;
74464  memset(&dest, 0, sizeof(dest));
74465  if( pParse->nErr || db->mallocFailed ){
74466    goto insert_cleanup;
74467  }
74468
74469  /* Locate the table into which we will be inserting new information.
74470  */
74471  assert( pTabList->nSrc==1 );
74472  zTab = pTabList->a[0].zName;
74473  if( NEVER(zTab==0) ) goto insert_cleanup;
74474  pTab = sqlite3SrcListLookup(pParse, pTabList);
74475  if( pTab==0 ){
74476    goto insert_cleanup;
74477  }
74478  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74479  assert( iDb<db->nDb );
74480  pDb = &db->aDb[iDb];
74481  zDb = pDb->zName;
74482  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
74483    goto insert_cleanup;
74484  }
74485
74486  /* Figure out if we have any triggers and if the table being
74487  ** inserted into is a view
74488  */
74489#ifndef SQLITE_OMIT_TRIGGER
74490  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
74491  isView = pTab->pSelect!=0;
74492#else
74493# define pTrigger 0
74494# define tmask 0
74495# define isView 0
74496#endif
74497#ifdef SQLITE_OMIT_VIEW
74498# undef isView
74499# define isView 0
74500#endif
74501  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
74502
74503  /* If pTab is really a view, make sure it has been initialized.
74504  ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
74505  ** module table).
74506  */
74507  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
74508    goto insert_cleanup;
74509  }
74510
74511  /* Ensure that:
74512  *  (a) the table is not read-only,
74513  *  (b) that if it is a view then ON INSERT triggers exist
74514  */
74515  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
74516    goto insert_cleanup;
74517  }
74518
74519  /* Allocate a VDBE
74520  */
74521  v = sqlite3GetVdbe(pParse);
74522  if( v==0 ) goto insert_cleanup;
74523  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
74524  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
74525
74526#ifndef SQLITE_OMIT_XFER_OPT
74527  /* If the statement is of the form
74528  **
74529  **       INSERT INTO <table1> SELECT * FROM <table2>;
74530  **
74531  ** Then special optimizations can be applied that make the transfer
74532  ** very fast and which reduce fragmentation of indices.
74533  **
74534  ** This is the 2nd template.
74535  */
74536  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
74537    assert( !pTrigger );
74538    assert( pList==0 );
74539    goto insert_end;
74540  }
74541#endif /* SQLITE_OMIT_XFER_OPT */
74542
74543  /* If this is an AUTOINCREMENT table, look up the sequence number in the
74544  ** sqlite_sequence table and store it in memory cell regAutoinc.
74545  */
74546  regAutoinc = autoIncBegin(pParse, iDb, pTab);
74547
74548  /* Figure out how many columns of data are supplied.  If the data
74549  ** is coming from a SELECT statement, then generate a co-routine that
74550  ** produces a single row of the SELECT on each invocation.  The
74551  ** co-routine is the common header to the 3rd and 4th templates.
74552  */
74553  if( pSelect ){
74554    /* Data is coming from a SELECT.  Generate code to implement that SELECT
74555    ** as a co-routine.  The code is common to both the 3rd and 4th
74556    ** templates:
74557    **
74558    **         EOF <- 0
74559    **         X <- A
74560    **         goto B
74561    **      A: setup for the SELECT
74562    **         loop over the tables in the SELECT
74563    **           load value into register R..R+n
74564    **           yield X
74565    **         end loop
74566    **         cleanup after the SELECT
74567    **         EOF <- 1
74568    **         yield X
74569    **         halt-error
74570    **
74571    ** On each invocation of the co-routine, it puts a single row of the
74572    ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
74573    ** (These output registers are allocated by sqlite3Select().)  When
74574    ** the SELECT completes, it sets the EOF flag stored in regEof.
74575    */
74576    int rc, j1;
74577
74578    regEof = ++pParse->nMem;
74579    sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
74580    VdbeComment((v, "SELECT eof flag"));
74581    sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
74582    addrSelect = sqlite3VdbeCurrentAddr(v)+2;
74583    sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
74584    j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
74585    VdbeComment((v, "Jump over SELECT coroutine"));
74586
74587    /* Resolve the expressions in the SELECT statement and execute it. */
74588    rc = sqlite3Select(pParse, pSelect, &dest);
74589    assert( pParse->nErr==0 || rc );
74590    if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
74591      goto insert_cleanup;
74592    }
74593    sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
74594    sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
74595    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
74596    VdbeComment((v, "End of SELECT coroutine"));
74597    sqlite3VdbeJumpHere(v, j1);                          /* label B: */
74598
74599    regFromSelect = dest.iMem;
74600    assert( pSelect->pEList );
74601    nColumn = pSelect->pEList->nExpr;
74602    assert( dest.nMem==nColumn );
74603
74604    /* Set useTempTable to TRUE if the result of the SELECT statement
74605    ** should be written into a temporary table (template 4).  Set to
74606    ** FALSE if each* row of the SELECT can be written directly into
74607    ** the destination table (template 3).
74608    **
74609    ** A temp table must be used if the table being updated is also one
74610    ** of the tables being read by the SELECT statement.  Also use a
74611    ** temp table in the case of row triggers.
74612    */
74613    if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
74614      useTempTable = 1;
74615    }
74616
74617    if( useTempTable ){
74618      /* Invoke the coroutine to extract information from the SELECT
74619      ** and add it to a transient table srcTab.  The code generated
74620      ** here is from the 4th template:
74621      **
74622      **      B: open temp table
74623      **      L: yield X
74624      **         if EOF goto M
74625      **         insert row from R..R+n into temp table
74626      **         goto L
74627      **      M: ...
74628      */
74629      int regRec;          /* Register to hold packed record */
74630      int regTempRowid;    /* Register to hold temp table ROWID */
74631      int addrTop;         /* Label "L" */
74632      int addrIf;          /* Address of jump to M */
74633
74634      srcTab = pParse->nTab++;
74635      regRec = sqlite3GetTempReg(pParse);
74636      regTempRowid = sqlite3GetTempReg(pParse);
74637      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
74638      addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
74639      addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
74640      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
74641      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
74642      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
74643      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
74644      sqlite3VdbeJumpHere(v, addrIf);
74645      sqlite3ReleaseTempReg(pParse, regRec);
74646      sqlite3ReleaseTempReg(pParse, regTempRowid);
74647    }
74648  }else{
74649    /* This is the case if the data for the INSERT is coming from a VALUES
74650    ** clause
74651    */
74652    NameContext sNC;
74653    memset(&sNC, 0, sizeof(sNC));
74654    sNC.pParse = pParse;
74655    srcTab = -1;
74656    assert( useTempTable==0 );
74657    nColumn = pList ? pList->nExpr : 0;
74658    for(i=0; i<nColumn; i++){
74659      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
74660        goto insert_cleanup;
74661      }
74662    }
74663  }
74664
74665  /* Make sure the number of columns in the source data matches the number
74666  ** of columns to be inserted into the table.
74667  */
74668  if( IsVirtual(pTab) ){
74669    for(i=0; i<pTab->nCol; i++){
74670      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
74671    }
74672  }
74673  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
74674    sqlite3ErrorMsg(pParse,
74675       "table %S has %d columns but %d values were supplied",
74676       pTabList, 0, pTab->nCol-nHidden, nColumn);
74677    goto insert_cleanup;
74678  }
74679  if( pColumn!=0 && nColumn!=pColumn->nId ){
74680    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
74681    goto insert_cleanup;
74682  }
74683
74684  /* If the INSERT statement included an IDLIST term, then make sure
74685  ** all elements of the IDLIST really are columns of the table and
74686  ** remember the column indices.
74687  **
74688  ** If the table has an INTEGER PRIMARY KEY column and that column
74689  ** is named in the IDLIST, then record in the keyColumn variable
74690  ** the index into IDLIST of the primary key column.  keyColumn is
74691  ** the index of the primary key as it appears in IDLIST, not as
74692  ** is appears in the original table.  (The index of the primary
74693  ** key in the original table is pTab->iPKey.)
74694  */
74695  if( pColumn ){
74696    for(i=0; i<pColumn->nId; i++){
74697      pColumn->a[i].idx = -1;
74698    }
74699    for(i=0; i<pColumn->nId; i++){
74700      for(j=0; j<pTab->nCol; j++){
74701        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
74702          pColumn->a[i].idx = j;
74703          if( j==pTab->iPKey ){
74704            keyColumn = i;
74705          }
74706          break;
74707        }
74708      }
74709      if( j>=pTab->nCol ){
74710        if( sqlite3IsRowid(pColumn->a[i].zName) ){
74711          keyColumn = i;
74712        }else{
74713          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
74714              pTabList, 0, pColumn->a[i].zName);
74715          pParse->nErr++;
74716          goto insert_cleanup;
74717        }
74718      }
74719    }
74720  }
74721
74722  /* If there is no IDLIST term but the table has an integer primary
74723  ** key, the set the keyColumn variable to the primary key column index
74724  ** in the original table definition.
74725  */
74726  if( pColumn==0 && nColumn>0 ){
74727    keyColumn = pTab->iPKey;
74728  }
74729
74730  /* Initialize the count of rows to be inserted
74731  */
74732  if( db->flags & SQLITE_CountRows ){
74733    regRowCount = ++pParse->nMem;
74734    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
74735  }
74736
74737  /* If this is not a view, open the table and and all indices */
74738  if( !isView ){
74739    int nIdx;
74740
74741    baseCur = pParse->nTab;
74742    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
74743    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
74744    if( aRegIdx==0 ){
74745      goto insert_cleanup;
74746    }
74747    for(i=0; i<nIdx; i++){
74748      aRegIdx[i] = ++pParse->nMem;
74749    }
74750  }
74751
74752  /* This is the top of the main insertion loop */
74753  if( useTempTable ){
74754    /* This block codes the top of loop only.  The complete loop is the
74755    ** following pseudocode (template 4):
74756    **
74757    **         rewind temp table
74758    **      C: loop over rows of intermediate table
74759    **           transfer values form intermediate table into <table>
74760    **         end loop
74761    **      D: ...
74762    */
74763    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
74764    addrCont = sqlite3VdbeCurrentAddr(v);
74765  }else if( pSelect ){
74766    /* This block codes the top of loop only.  The complete loop is the
74767    ** following pseudocode (template 3):
74768    **
74769    **      C: yield X
74770    **         if EOF goto D
74771    **         insert the select result into <table> from R..R+n
74772    **         goto C
74773    **      D: ...
74774    */
74775    addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
74776    addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
74777  }
74778
74779  /* Allocate registers for holding the rowid of the new row,
74780  ** the content of the new row, and the assemblied row record.
74781  */
74782  regRecord = ++pParse->nMem;
74783  regRowid = regIns = pParse->nMem+1;
74784  pParse->nMem += pTab->nCol + 1;
74785  if( IsVirtual(pTab) ){
74786    regRowid++;
74787    pParse->nMem++;
74788  }
74789  regData = regRowid+1;
74790
74791  /* Run the BEFORE and INSTEAD OF triggers, if there are any
74792  */
74793  endOfLoop = sqlite3VdbeMakeLabel(v);
74794  if( tmask & TRIGGER_BEFORE ){
74795    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
74796
74797    /* build the NEW.* reference row.  Note that if there is an INTEGER
74798    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
74799    ** translated into a unique ID for the row.  But on a BEFORE trigger,
74800    ** we do not know what the unique ID will be (because the insert has
74801    ** not happened yet) so we substitute a rowid of -1
74802    */
74803    if( keyColumn<0 ){
74804      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
74805    }else{
74806      int j1;
74807      if( useTempTable ){
74808        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
74809      }else{
74810        assert( pSelect==0 );  /* Otherwise useTempTable is true */
74811        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
74812      }
74813      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
74814      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
74815      sqlite3VdbeJumpHere(v, j1);
74816      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
74817    }
74818
74819    /* Cannot have triggers on a virtual table. If it were possible,
74820    ** this block would have to account for hidden column.
74821    */
74822    assert( !IsVirtual(pTab) );
74823
74824    /* Create the new column data
74825    */
74826    for(i=0; i<pTab->nCol; i++){
74827      if( pColumn==0 ){
74828        j = i;
74829      }else{
74830        for(j=0; j<pColumn->nId; j++){
74831          if( pColumn->a[j].idx==i ) break;
74832        }
74833      }
74834      if( pColumn && j>=pColumn->nId ){
74835        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
74836      }else if( useTempTable ){
74837        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
74838      }else{
74839        assert( pSelect==0 ); /* Otherwise useTempTable is true */
74840        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
74841      }
74842    }
74843
74844    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
74845    ** do not attempt any conversions before assembling the record.
74846    ** If this is a real table, attempt conversions as required by the
74847    ** table column affinities.
74848    */
74849    if( !isView ){
74850      sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
74851      sqlite3TableAffinityStr(v, pTab);
74852    }
74853
74854    /* Fire BEFORE or INSTEAD OF triggers */
74855    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
74856        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
74857
74858    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
74859  }
74860
74861  /* Push the record number for the new entry onto the stack.  The
74862  ** record number is a randomly generate integer created by NewRowid
74863  ** except when the table has an INTEGER PRIMARY KEY column, in which
74864  ** case the record number is the same as that column.
74865  */
74866  if( !isView ){
74867    if( IsVirtual(pTab) ){
74868      /* The row that the VUpdate opcode will delete: none */
74869      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
74870    }
74871    if( keyColumn>=0 ){
74872      if( useTempTable ){
74873        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
74874      }else if( pSelect ){
74875        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
74876      }else{
74877        VdbeOp *pOp;
74878        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
74879        pOp = sqlite3VdbeGetOp(v, -1);
74880        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
74881          appendFlag = 1;
74882          pOp->opcode = OP_NewRowid;
74883          pOp->p1 = baseCur;
74884          pOp->p2 = regRowid;
74885          pOp->p3 = regAutoinc;
74886        }
74887      }
74888      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
74889      ** to generate a unique primary key value.
74890      */
74891      if( !appendFlag ){
74892        int j1;
74893        if( !IsVirtual(pTab) ){
74894          j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
74895          sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
74896          sqlite3VdbeJumpHere(v, j1);
74897        }else{
74898          j1 = sqlite3VdbeCurrentAddr(v);
74899          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
74900        }
74901        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
74902      }
74903    }else if( IsVirtual(pTab) ){
74904      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
74905    }else{
74906      sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
74907      appendFlag = 1;
74908    }
74909    autoIncStep(pParse, regAutoinc, regRowid);
74910
74911    /* Push onto the stack, data for all columns of the new entry, beginning
74912    ** with the first column.
74913    */
74914    nHidden = 0;
74915    for(i=0; i<pTab->nCol; i++){
74916      int iRegStore = regRowid+1+i;
74917      if( i==pTab->iPKey ){
74918        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
74919        ** Whenever this column is read, the record number will be substituted
74920        ** in its place.  So will fill this column with a NULL to avoid
74921        ** taking up data space with information that will never be used. */
74922        sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
74923        continue;
74924      }
74925      if( pColumn==0 ){
74926        if( IsHiddenColumn(&pTab->aCol[i]) ){
74927          assert( IsVirtual(pTab) );
74928          j = -1;
74929          nHidden++;
74930        }else{
74931          j = i - nHidden;
74932        }
74933      }else{
74934        for(j=0; j<pColumn->nId; j++){
74935          if( pColumn->a[j].idx==i ) break;
74936        }
74937      }
74938      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
74939        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
74940      }else if( useTempTable ){
74941        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
74942      }else if( pSelect ){
74943        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
74944      }else{
74945        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
74946      }
74947    }
74948
74949    /* Generate code to check constraints and generate index keys and
74950    ** do the insertion.
74951    */
74952#ifndef SQLITE_OMIT_VIRTUALTABLE
74953    if( IsVirtual(pTab) ){
74954      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
74955      sqlite3VtabMakeWritable(pParse, pTab);
74956      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
74957      sqlite3MayAbort(pParse);
74958    }else
74959#endif
74960    {
74961      int isReplace;    /* Set to true if constraints may cause a replace */
74962      sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
74963          keyColumn>=0, 0, onError, endOfLoop, &isReplace
74964      );
74965      sqlite3FkCheck(pParse, pTab, 0, regIns);
74966      sqlite3CompleteInsertion(
74967          pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
74968      );
74969    }
74970  }
74971
74972  /* Update the count of rows that are inserted
74973  */
74974  if( (db->flags & SQLITE_CountRows)!=0 ){
74975    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
74976  }
74977
74978  if( pTrigger ){
74979    /* Code AFTER triggers */
74980    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
74981        pTab, regData-2-pTab->nCol, onError, endOfLoop);
74982  }
74983
74984  /* The bottom of the main insertion loop, if the data source
74985  ** is a SELECT statement.
74986  */
74987  sqlite3VdbeResolveLabel(v, endOfLoop);
74988  if( useTempTable ){
74989    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
74990    sqlite3VdbeJumpHere(v, addrInsTop);
74991    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
74992  }else if( pSelect ){
74993    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
74994    sqlite3VdbeJumpHere(v, addrInsTop);
74995  }
74996
74997  if( !IsVirtual(pTab) && !isView ){
74998    /* Close all tables opened */
74999    sqlite3VdbeAddOp1(v, OP_Close, baseCur);
75000    for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
75001      sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
75002    }
75003  }
75004
75005insert_end:
75006  /* Update the sqlite_sequence table by storing the content of the
75007  ** maximum rowid counter values recorded while inserting into
75008  ** autoincrement tables.
75009  */
75010  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
75011    sqlite3AutoincrementEnd(pParse);
75012  }
75013
75014  /*
75015  ** Return the number of rows inserted. If this routine is
75016  ** generating code because of a call to sqlite3NestedParse(), do not
75017  ** invoke the callback function.
75018  */
75019  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
75020    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
75021    sqlite3VdbeSetNumCols(v, 1);
75022    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
75023  }
75024
75025insert_cleanup:
75026  sqlite3SrcListDelete(db, pTabList);
75027  sqlite3ExprListDelete(db, pList);
75028  sqlite3SelectDelete(db, pSelect);
75029  sqlite3IdListDelete(db, pColumn);
75030  sqlite3DbFree(db, aRegIdx);
75031}
75032
75033/* Make sure "isView" and other macros defined above are undefined. Otherwise
75034** thely may interfere with compilation of other functions in this file
75035** (or in another file, if this file becomes part of the amalgamation).  */
75036#ifdef isView
75037 #undef isView
75038#endif
75039#ifdef pTrigger
75040 #undef pTrigger
75041#endif
75042#ifdef tmask
75043 #undef tmask
75044#endif
75045
75046
75047/*
75048** Generate code to do constraint checks prior to an INSERT or an UPDATE.
75049**
75050** The input is a range of consecutive registers as follows:
75051**
75052**    1.  The rowid of the row after the update.
75053**
75054**    2.  The data in the first column of the entry after the update.
75055**
75056**    i.  Data from middle columns...
75057**
75058**    N.  The data in the last column of the entry after the update.
75059**
75060** The regRowid parameter is the index of the register containing (1).
75061**
75062** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
75063** the address of a register containing the rowid before the update takes
75064** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
75065** is false, indicating an INSERT statement, then a non-zero rowidChng
75066** indicates that the rowid was explicitly specified as part of the
75067** INSERT statement. If rowidChng is false, it means that  the rowid is
75068** computed automatically in an insert or that the rowid value is not
75069** modified by an update.
75070**
75071** The code generated by this routine store new index entries into
75072** registers identified by aRegIdx[].  No index entry is created for
75073** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
75074** the same as the order of indices on the linked list of indices
75075** attached to the table.
75076**
75077** This routine also generates code to check constraints.  NOT NULL,
75078** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
75079** then the appropriate action is performed.  There are five possible
75080** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
75081**
75082**  Constraint type  Action       What Happens
75083**  ---------------  ----------   ----------------------------------------
75084**  any              ROLLBACK     The current transaction is rolled back and
75085**                                sqlite3_exec() returns immediately with a
75086**                                return code of SQLITE_CONSTRAINT.
75087**
75088**  any              ABORT        Back out changes from the current command
75089**                                only (do not do a complete rollback) then
75090**                                cause sqlite3_exec() to return immediately
75091**                                with SQLITE_CONSTRAINT.
75092**
75093**  any              FAIL         Sqlite_exec() returns immediately with a
75094**                                return code of SQLITE_CONSTRAINT.  The
75095**                                transaction is not rolled back and any
75096**                                prior changes are retained.
75097**
75098**  any              IGNORE       The record number and data is popped from
75099**                                the stack and there is an immediate jump
75100**                                to label ignoreDest.
75101**
75102**  NOT NULL         REPLACE      The NULL value is replace by the default
75103**                                value for that column.  If the default value
75104**                                is NULL, the action is the same as ABORT.
75105**
75106**  UNIQUE           REPLACE      The other row that conflicts with the row
75107**                                being inserted is removed.
75108**
75109**  CHECK            REPLACE      Illegal.  The results in an exception.
75110**
75111** Which action to take is determined by the overrideError parameter.
75112** Or if overrideError==OE_Default, then the pParse->onError parameter
75113** is used.  Or if pParse->onError==OE_Default then the onError value
75114** for the constraint is used.
75115**
75116** The calling routine must open a read/write cursor for pTab with
75117** cursor number "baseCur".  All indices of pTab must also have open
75118** read/write cursors with cursor number baseCur+i for the i-th cursor.
75119** Except, if there is no possibility of a REPLACE action then
75120** cursors do not need to be open for indices where aRegIdx[i]==0.
75121*/
75122SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
75123  Parse *pParse,      /* The parser context */
75124  Table *pTab,        /* the table into which we are inserting */
75125  int baseCur,        /* Index of a read/write cursor pointing at pTab */
75126  int regRowid,       /* Index of the range of input registers */
75127  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
75128  int rowidChng,      /* True if the rowid might collide with existing entry */
75129  int isUpdate,       /* True for UPDATE, False for INSERT */
75130  int overrideError,  /* Override onError to this if not OE_Default */
75131  int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
75132  int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
75133){
75134  int i;              /* loop counter */
75135  Vdbe *v;            /* VDBE under constrution */
75136  int nCol;           /* Number of columns */
75137  int onError;        /* Conflict resolution strategy */
75138  int j1;             /* Addresss of jump instruction */
75139  int j2 = 0, j3;     /* Addresses of jump instructions */
75140  int regData;        /* Register containing first data column */
75141  int iCur;           /* Table cursor number */
75142  Index *pIdx;         /* Pointer to one of the indices */
75143  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
75144  int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
75145
75146  v = sqlite3GetVdbe(pParse);
75147  assert( v!=0 );
75148  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
75149  nCol = pTab->nCol;
75150  regData = regRowid + 1;
75151
75152  /* Test all NOT NULL constraints.
75153  */
75154  for(i=0; i<nCol; i++){
75155    if( i==pTab->iPKey ){
75156      continue;
75157    }
75158    onError = pTab->aCol[i].notNull;
75159    if( onError==OE_None ) continue;
75160    if( overrideError!=OE_Default ){
75161      onError = overrideError;
75162    }else if( onError==OE_Default ){
75163      onError = OE_Abort;
75164    }
75165    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
75166      onError = OE_Abort;
75167    }
75168    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
75169        || onError==OE_Ignore || onError==OE_Replace );
75170    switch( onError ){
75171      case OE_Abort:
75172        sqlite3MayAbort(pParse);
75173      case OE_Rollback:
75174      case OE_Fail: {
75175        char *zMsg;
75176        j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
75177                                  SQLITE_CONSTRAINT, onError, regData+i);
75178        zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
75179                              pTab->zName, pTab->aCol[i].zName);
75180        sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
75181        break;
75182      }
75183      case OE_Ignore: {
75184        sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
75185        break;
75186      }
75187      default: {
75188        assert( onError==OE_Replace );
75189        j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
75190        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
75191        sqlite3VdbeJumpHere(v, j1);
75192        break;
75193      }
75194    }
75195  }
75196
75197  /* Test all CHECK constraints
75198  */
75199#ifndef SQLITE_OMIT_CHECK
75200  if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
75201    int allOk = sqlite3VdbeMakeLabel(v);
75202    pParse->ckBase = regData;
75203    sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
75204    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
75205    if( onError==OE_Ignore ){
75206      sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
75207    }else{
75208      sqlite3HaltConstraint(pParse, onError, 0, 0);
75209    }
75210    sqlite3VdbeResolveLabel(v, allOk);
75211  }
75212#endif /* !defined(SQLITE_OMIT_CHECK) */
75213
75214  /* If we have an INTEGER PRIMARY KEY, make sure the primary key
75215  ** of the new record does not previously exist.  Except, if this
75216  ** is an UPDATE and the primary key is not changing, that is OK.
75217  */
75218  if( rowidChng ){
75219    onError = pTab->keyConf;
75220    if( overrideError!=OE_Default ){
75221      onError = overrideError;
75222    }else if( onError==OE_Default ){
75223      onError = OE_Abort;
75224    }
75225
75226    if( isUpdate ){
75227      j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
75228    }
75229    j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
75230    switch( onError ){
75231      default: {
75232        onError = OE_Abort;
75233        /* Fall thru into the next case */
75234      }
75235      case OE_Rollback:
75236      case OE_Abort:
75237      case OE_Fail: {
75238        sqlite3HaltConstraint(
75239          pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
75240        break;
75241      }
75242      case OE_Replace: {
75243        /* If there are DELETE triggers on this table and the
75244        ** recursive-triggers flag is set, call GenerateRowDelete() to
75245        ** remove the conflicting row from the the table. This will fire
75246        ** the triggers and remove both the table and index b-tree entries.
75247        **
75248        ** Otherwise, if there are no triggers or the recursive-triggers
75249        ** flag is not set, call GenerateRowIndexDelete(). This removes
75250        ** the index b-tree entries only. The table b-tree entry will be
75251        ** replaced by the new entry when it is inserted.  */
75252        Trigger *pTrigger = 0;
75253        if( pParse->db->flags&SQLITE_RecTriggers ){
75254          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
75255        }
75256        sqlite3MultiWrite(pParse);
75257        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
75258          sqlite3GenerateRowDelete(
75259              pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
75260          );
75261        }else{
75262          sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
75263        }
75264        seenReplace = 1;
75265        break;
75266      }
75267      case OE_Ignore: {
75268        assert( seenReplace==0 );
75269        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
75270        break;
75271      }
75272    }
75273    sqlite3VdbeJumpHere(v, j3);
75274    if( isUpdate ){
75275      sqlite3VdbeJumpHere(v, j2);
75276    }
75277  }
75278
75279  /* Test all UNIQUE constraints by creating entries for each UNIQUE
75280  ** index and making sure that duplicate entries do not already exist.
75281  ** Add the new records to the indices as we go.
75282  */
75283  for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
75284    int regIdx;
75285    int regR;
75286
75287    if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
75288
75289    /* Create a key for accessing the index entry */
75290    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
75291    for(i=0; i<pIdx->nColumn; i++){
75292      int idx = pIdx->aiColumn[i];
75293      if( idx==pTab->iPKey ){
75294        sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
75295      }else{
75296        sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
75297      }
75298    }
75299    sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
75300    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
75301    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
75302    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
75303
75304    /* Find out what action to take in case there is an indexing conflict */
75305    onError = pIdx->onError;
75306    if( onError==OE_None ){
75307      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
75308      continue;  /* pIdx is not a UNIQUE index */
75309    }
75310    if( overrideError!=OE_Default ){
75311      onError = overrideError;
75312    }else if( onError==OE_Default ){
75313      onError = OE_Abort;
75314    }
75315    if( seenReplace ){
75316      if( onError==OE_Ignore ) onError = OE_Replace;
75317      else if( onError==OE_Fail ) onError = OE_Abort;
75318    }
75319
75320    /* Check to see if the new index entry will be unique */
75321    regR = sqlite3GetTempReg(pParse);
75322    sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
75323    j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
75324                           regR, SQLITE_INT_TO_PTR(regIdx),
75325                           P4_INT32);
75326    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
75327
75328    /* Generate code that executes if the new index entry is not unique */
75329    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
75330        || onError==OE_Ignore || onError==OE_Replace );
75331    switch( onError ){
75332      case OE_Rollback:
75333      case OE_Abort:
75334      case OE_Fail: {
75335        int j;
75336        StrAccum errMsg;
75337        const char *zSep;
75338        char *zErr;
75339
75340        sqlite3StrAccumInit(&errMsg, 0, 0, 200);
75341        errMsg.db = pParse->db;
75342        zSep = pIdx->nColumn>1 ? "columns " : "column ";
75343        for(j=0; j<pIdx->nColumn; j++){
75344          char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
75345          sqlite3StrAccumAppend(&errMsg, zSep, -1);
75346          zSep = ", ";
75347          sqlite3StrAccumAppend(&errMsg, zCol, -1);
75348        }
75349        sqlite3StrAccumAppend(&errMsg,
75350            pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
75351        zErr = sqlite3StrAccumFinish(&errMsg);
75352        sqlite3HaltConstraint(pParse, onError, zErr, 0);
75353        sqlite3DbFree(errMsg.db, zErr);
75354        break;
75355      }
75356      case OE_Ignore: {
75357        assert( seenReplace==0 );
75358        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
75359        break;
75360      }
75361      default: {
75362        Trigger *pTrigger = 0;
75363        assert( onError==OE_Replace );
75364        sqlite3MultiWrite(pParse);
75365        if( pParse->db->flags&SQLITE_RecTriggers ){
75366          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
75367        }
75368        sqlite3GenerateRowDelete(
75369            pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
75370        );
75371        seenReplace = 1;
75372        break;
75373      }
75374    }
75375    sqlite3VdbeJumpHere(v, j3);
75376    sqlite3ReleaseTempReg(pParse, regR);
75377  }
75378
75379  if( pbMayReplace ){
75380    *pbMayReplace = seenReplace;
75381  }
75382}
75383
75384/*
75385** This routine generates code to finish the INSERT or UPDATE operation
75386** that was started by a prior call to sqlite3GenerateConstraintChecks.
75387** A consecutive range of registers starting at regRowid contains the
75388** rowid and the content to be inserted.
75389**
75390** The arguments to this routine should be the same as the first six
75391** arguments to sqlite3GenerateConstraintChecks.
75392*/
75393SQLITE_PRIVATE void sqlite3CompleteInsertion(
75394  Parse *pParse,      /* The parser context */
75395  Table *pTab,        /* the table into which we are inserting */
75396  int baseCur,        /* Index of a read/write cursor pointing at pTab */
75397  int regRowid,       /* Range of content */
75398  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
75399  int isUpdate,       /* True for UPDATE, False for INSERT */
75400  int appendBias,     /* True if this is likely to be an append */
75401  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
75402){
75403  int i;
75404  Vdbe *v;
75405  int nIdx;
75406  Index *pIdx;
75407  u8 pik_flags;
75408  int regData;
75409  int regRec;
75410
75411  v = sqlite3GetVdbe(pParse);
75412  assert( v!=0 );
75413  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
75414  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
75415  for(i=nIdx-1; i>=0; i--){
75416    if( aRegIdx[i]==0 ) continue;
75417    sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
75418    if( useSeekResult ){
75419      sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
75420    }
75421  }
75422  regData = regRowid + 1;
75423  regRec = sqlite3GetTempReg(pParse);
75424  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
75425  sqlite3TableAffinityStr(v, pTab);
75426  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
75427  if( pParse->nested ){
75428    pik_flags = 0;
75429  }else{
75430    pik_flags = OPFLAG_NCHANGE;
75431    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
75432  }
75433  if( appendBias ){
75434    pik_flags |= OPFLAG_APPEND;
75435  }
75436  if( useSeekResult ){
75437    pik_flags |= OPFLAG_USESEEKRESULT;
75438  }
75439  sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
75440  if( !pParse->nested ){
75441    sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
75442  }
75443  sqlite3VdbeChangeP5(v, pik_flags);
75444}
75445
75446/*
75447** Generate code that will open cursors for a table and for all
75448** indices of that table.  The "baseCur" parameter is the cursor number used
75449** for the table.  Indices are opened on subsequent cursors.
75450**
75451** Return the number of indices on the table.
75452*/
75453SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
75454  Parse *pParse,   /* Parsing context */
75455  Table *pTab,     /* Table to be opened */
75456  int baseCur,     /* Cursor number assigned to the table */
75457  int op           /* OP_OpenRead or OP_OpenWrite */
75458){
75459  int i;
75460  int iDb;
75461  Index *pIdx;
75462  Vdbe *v;
75463
75464  if( IsVirtual(pTab) ) return 0;
75465  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75466  v = sqlite3GetVdbe(pParse);
75467  assert( v!=0 );
75468  sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
75469  for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
75470    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
75471    assert( pIdx->pSchema==pTab->pSchema );
75472    sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
75473                      (char*)pKey, P4_KEYINFO_HANDOFF);
75474    VdbeComment((v, "%s", pIdx->zName));
75475  }
75476  if( pParse->nTab<baseCur+i ){
75477    pParse->nTab = baseCur+i;
75478  }
75479  return i-1;
75480}
75481
75482
75483#ifdef SQLITE_TEST
75484/*
75485** The following global variable is incremented whenever the
75486** transfer optimization is used.  This is used for testing
75487** purposes only - to make sure the transfer optimization really
75488** is happening when it is suppose to.
75489*/
75490SQLITE_API int sqlite3_xferopt_count;
75491#endif /* SQLITE_TEST */
75492
75493
75494#ifndef SQLITE_OMIT_XFER_OPT
75495/*
75496** Check to collation names to see if they are compatible.
75497*/
75498static int xferCompatibleCollation(const char *z1, const char *z2){
75499  if( z1==0 ){
75500    return z2==0;
75501  }
75502  if( z2==0 ){
75503    return 0;
75504  }
75505  return sqlite3StrICmp(z1, z2)==0;
75506}
75507
75508
75509/*
75510** Check to see if index pSrc is compatible as a source of data
75511** for index pDest in an insert transfer optimization.  The rules
75512** for a compatible index:
75513**
75514**    *   The index is over the same set of columns
75515**    *   The same DESC and ASC markings occurs on all columns
75516**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
75517**    *   The same collating sequence on each column
75518*/
75519static int xferCompatibleIndex(Index *pDest, Index *pSrc){
75520  int i;
75521  assert( pDest && pSrc );
75522  assert( pDest->pTable!=pSrc->pTable );
75523  if( pDest->nColumn!=pSrc->nColumn ){
75524    return 0;   /* Different number of columns */
75525  }
75526  if( pDest->onError!=pSrc->onError ){
75527    return 0;   /* Different conflict resolution strategies */
75528  }
75529  for(i=0; i<pSrc->nColumn; i++){
75530    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
75531      return 0;   /* Different columns indexed */
75532    }
75533    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
75534      return 0;   /* Different sort orders */
75535    }
75536    if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
75537      return 0;   /* Different collating sequences */
75538    }
75539  }
75540
75541  /* If no test above fails then the indices must be compatible */
75542  return 1;
75543}
75544
75545/*
75546** Attempt the transfer optimization on INSERTs of the form
75547**
75548**     INSERT INTO tab1 SELECT * FROM tab2;
75549**
75550** This optimization is only attempted if
75551**
75552**    (1)  tab1 and tab2 have identical schemas including all the
75553**         same indices and constraints
75554**
75555**    (2)  tab1 and tab2 are different tables
75556**
75557**    (3)  There must be no triggers on tab1
75558**
75559**    (4)  The result set of the SELECT statement is "*"
75560**
75561**    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
75562**         or LIMIT clause.
75563**
75564**    (6)  The SELECT statement is a simple (not a compound) select that
75565**         contains only tab2 in its FROM clause
75566**
75567** This method for implementing the INSERT transfers raw records from
75568** tab2 over to tab1.  The columns are not decoded.  Raw records from
75569** the indices of tab2 are transfered to tab1 as well.  In so doing,
75570** the resulting tab1 has much less fragmentation.
75571**
75572** This routine returns TRUE if the optimization is attempted.  If any
75573** of the conditions above fail so that the optimization should not
75574** be attempted, then this routine returns FALSE.
75575*/
75576static int xferOptimization(
75577  Parse *pParse,        /* Parser context */
75578  Table *pDest,         /* The table we are inserting into */
75579  Select *pSelect,      /* A SELECT statement to use as the data source */
75580  int onError,          /* How to handle constraint errors */
75581  int iDbDest           /* The database of pDest */
75582){
75583  ExprList *pEList;                /* The result set of the SELECT */
75584  Table *pSrc;                     /* The table in the FROM clause of SELECT */
75585  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
75586  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
75587  int i;                           /* Loop counter */
75588  int iDbSrc;                      /* The database of pSrc */
75589  int iSrc, iDest;                 /* Cursors from source and destination */
75590  int addr1, addr2;                /* Loop addresses */
75591  int emptyDestTest;               /* Address of test for empty pDest */
75592  int emptySrcTest;                /* Address of test for empty pSrc */
75593  Vdbe *v;                         /* The VDBE we are building */
75594  KeyInfo *pKey;                   /* Key information for an index */
75595  int regAutoinc;                  /* Memory register used by AUTOINC */
75596  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
75597  int regData, regRowid;           /* Registers holding data and rowid */
75598
75599  if( pSelect==0 ){
75600    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
75601  }
75602  if( sqlite3TriggerList(pParse, pDest) ){
75603    return 0;   /* tab1 must not have triggers */
75604  }
75605#ifndef SQLITE_OMIT_VIRTUALTABLE
75606  if( pDest->tabFlags & TF_Virtual ){
75607    return 0;   /* tab1 must not be a virtual table */
75608  }
75609#endif
75610  if( onError==OE_Default ){
75611    onError = OE_Abort;
75612  }
75613  if( onError!=OE_Abort && onError!=OE_Rollback ){
75614    return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
75615  }
75616  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
75617  if( pSelect->pSrc->nSrc!=1 ){
75618    return 0;   /* FROM clause must have exactly one term */
75619  }
75620  if( pSelect->pSrc->a[0].pSelect ){
75621    return 0;   /* FROM clause cannot contain a subquery */
75622  }
75623  if( pSelect->pWhere ){
75624    return 0;   /* SELECT may not have a WHERE clause */
75625  }
75626  if( pSelect->pOrderBy ){
75627    return 0;   /* SELECT may not have an ORDER BY clause */
75628  }
75629  /* Do not need to test for a HAVING clause.  If HAVING is present but
75630  ** there is no ORDER BY, we will get an error. */
75631  if( pSelect->pGroupBy ){
75632    return 0;   /* SELECT may not have a GROUP BY clause */
75633  }
75634  if( pSelect->pLimit ){
75635    return 0;   /* SELECT may not have a LIMIT clause */
75636  }
75637  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
75638  if( pSelect->pPrior ){
75639    return 0;   /* SELECT may not be a compound query */
75640  }
75641  if( pSelect->selFlags & SF_Distinct ){
75642    return 0;   /* SELECT may not be DISTINCT */
75643  }
75644  pEList = pSelect->pEList;
75645  assert( pEList!=0 );
75646  if( pEList->nExpr!=1 ){
75647    return 0;   /* The result set must have exactly one column */
75648  }
75649  assert( pEList->a[0].pExpr );
75650  if( pEList->a[0].pExpr->op!=TK_ALL ){
75651    return 0;   /* The result set must be the special operator "*" */
75652  }
75653
75654  /* At this point we have established that the statement is of the
75655  ** correct syntactic form to participate in this optimization.  Now
75656  ** we have to check the semantics.
75657  */
75658  pItem = pSelect->pSrc->a;
75659  pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
75660  if( pSrc==0 ){
75661    return 0;   /* FROM clause does not contain a real table */
75662  }
75663  if( pSrc==pDest ){
75664    return 0;   /* tab1 and tab2 may not be the same table */
75665  }
75666#ifndef SQLITE_OMIT_VIRTUALTABLE
75667  if( pSrc->tabFlags & TF_Virtual ){
75668    return 0;   /* tab2 must not be a virtual table */
75669  }
75670#endif
75671  if( pSrc->pSelect ){
75672    return 0;   /* tab2 may not be a view */
75673  }
75674  if( pDest->nCol!=pSrc->nCol ){
75675    return 0;   /* Number of columns must be the same in tab1 and tab2 */
75676  }
75677  if( pDest->iPKey!=pSrc->iPKey ){
75678    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
75679  }
75680  for(i=0; i<pDest->nCol; i++){
75681    if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
75682      return 0;    /* Affinity must be the same on all columns */
75683    }
75684    if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
75685      return 0;    /* Collating sequence must be the same on all columns */
75686    }
75687    if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
75688      return 0;    /* tab2 must be NOT NULL if tab1 is */
75689    }
75690  }
75691  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
75692    if( pDestIdx->onError!=OE_None ){
75693      destHasUniqueIdx = 1;
75694    }
75695    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
75696      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
75697    }
75698    if( pSrcIdx==0 ){
75699      return 0;    /* pDestIdx has no corresponding index in pSrc */
75700    }
75701  }
75702#ifndef SQLITE_OMIT_CHECK
75703  if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
75704    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
75705  }
75706#endif
75707
75708  /* If we get this far, it means either:
75709  **
75710  **    *   We can always do the transfer if the table contains an
75711  **        an integer primary key
75712  **
75713  **    *   We can conditionally do the transfer if the destination
75714  **        table is empty.
75715  */
75716#ifdef SQLITE_TEST
75717  sqlite3_xferopt_count++;
75718#endif
75719  iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
75720  v = sqlite3GetVdbe(pParse);
75721  sqlite3CodeVerifySchema(pParse, iDbSrc);
75722  iSrc = pParse->nTab++;
75723  iDest = pParse->nTab++;
75724  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
75725  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
75726  if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
75727    /* If tables do not have an INTEGER PRIMARY KEY and there
75728    ** are indices to be copied and the destination is not empty,
75729    ** we have to disallow the transfer optimization because the
75730    ** the rowids might change which will mess up indexing.
75731    **
75732    ** Or if the destination has a UNIQUE index and is not empty,
75733    ** we also disallow the transfer optimization because we cannot
75734    ** insure that all entries in the union of DEST and SRC will be
75735    ** unique.
75736    */
75737    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
75738    emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
75739    sqlite3VdbeJumpHere(v, addr1);
75740  }else{
75741    emptyDestTest = 0;
75742  }
75743  sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
75744  emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
75745  regData = sqlite3GetTempReg(pParse);
75746  regRowid = sqlite3GetTempReg(pParse);
75747  if( pDest->iPKey>=0 ){
75748    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
75749    addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
75750    sqlite3HaltConstraint(
75751        pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
75752    sqlite3VdbeJumpHere(v, addr2);
75753    autoIncStep(pParse, regAutoinc, regRowid);
75754  }else if( pDest->pIndex==0 ){
75755    addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
75756  }else{
75757    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
75758    assert( (pDest->tabFlags & TF_Autoincrement)==0 );
75759  }
75760  sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
75761  sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
75762  sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
75763  sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
75764  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
75765  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
75766    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
75767      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
75768    }
75769    assert( pSrcIdx );
75770    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
75771    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
75772    pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
75773    sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
75774                      (char*)pKey, P4_KEYINFO_HANDOFF);
75775    VdbeComment((v, "%s", pSrcIdx->zName));
75776    pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
75777    sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
75778                      (char*)pKey, P4_KEYINFO_HANDOFF);
75779    VdbeComment((v, "%s", pDestIdx->zName));
75780    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
75781    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
75782    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
75783    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
75784    sqlite3VdbeJumpHere(v, addr1);
75785  }
75786  sqlite3VdbeJumpHere(v, emptySrcTest);
75787  sqlite3ReleaseTempReg(pParse, regRowid);
75788  sqlite3ReleaseTempReg(pParse, regData);
75789  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
75790  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
75791  if( emptyDestTest ){
75792    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
75793    sqlite3VdbeJumpHere(v, emptyDestTest);
75794    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
75795    return 0;
75796  }else{
75797    return 1;
75798  }
75799}
75800#endif /* SQLITE_OMIT_XFER_OPT */
75801
75802/************** End of insert.c **********************************************/
75803/************** Begin file legacy.c ******************************************/
75804/*
75805** 2001 September 15
75806**
75807** The author disclaims copyright to this source code.  In place of
75808** a legal notice, here is a blessing:
75809**
75810**    May you do good and not evil.
75811**    May you find forgiveness for yourself and forgive others.
75812**    May you share freely, never taking more than you give.
75813**
75814*************************************************************************
75815** Main file for the SQLite library.  The routines in this file
75816** implement the programmer interface to the library.  Routines in
75817** other files are for internal use by SQLite and should not be
75818** accessed by users of the library.
75819*/
75820
75821
75822/*
75823** Execute SQL code.  Return one of the SQLITE_ success/failure
75824** codes.  Also write an error message into memory obtained from
75825** malloc() and make *pzErrMsg point to that message.
75826**
75827** If the SQL is a query, then for each row in the query result
75828** the xCallback() function is called.  pArg becomes the first
75829** argument to xCallback().  If xCallback=NULL then no callback
75830** is invoked, even for queries.
75831*/
75832SQLITE_API int sqlite3_exec(
75833  sqlite3 *db,                /* The database on which the SQL executes */
75834  const char *zSql,           /* The SQL to be executed */
75835  sqlite3_callback xCallback, /* Invoke this callback routine */
75836  void *pArg,                 /* First argument to xCallback() */
75837  char **pzErrMsg             /* Write error messages here */
75838){
75839  int rc = SQLITE_OK;         /* Return code */
75840  const char *zLeftover;      /* Tail of unprocessed SQL */
75841  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
75842  char **azCols = 0;          /* Names of result columns */
75843  int nRetry = 0;             /* Number of retry attempts */
75844  int callbackIsInit;         /* True if callback data is initialized */
75845
75846  if( zSql==0 ) zSql = "";
75847
75848  sqlite3_mutex_enter(db->mutex);
75849  sqlite3Error(db, SQLITE_OK, 0);
75850  while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
75851    int nCol;
75852    char **azVals = 0;
75853
75854    pStmt = 0;
75855    rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
75856    assert( rc==SQLITE_OK || pStmt==0 );
75857    if( rc!=SQLITE_OK ){
75858      continue;
75859    }
75860    if( !pStmt ){
75861      /* this happens for a comment or white-space */
75862      zSql = zLeftover;
75863      continue;
75864    }
75865
75866    callbackIsInit = 0;
75867    nCol = sqlite3_column_count(pStmt);
75868
75869    while( 1 ){
75870      int i;
75871      rc = sqlite3_step(pStmt);
75872
75873      /* Invoke the callback function if required */
75874      if( xCallback && (SQLITE_ROW==rc ||
75875          (SQLITE_DONE==rc && !callbackIsInit
75876                           && db->flags&SQLITE_NullCallback)) ){
75877        if( !callbackIsInit ){
75878          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
75879          if( azCols==0 ){
75880            goto exec_out;
75881          }
75882          for(i=0; i<nCol; i++){
75883            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
75884            /* sqlite3VdbeSetColName() installs column names as UTF8
75885            ** strings so there is no way for sqlite3_column_name() to fail. */
75886            assert( azCols[i]!=0 );
75887          }
75888          callbackIsInit = 1;
75889        }
75890        if( rc==SQLITE_ROW ){
75891          azVals = &azCols[nCol];
75892          for(i=0; i<nCol; i++){
75893            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
75894            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
75895              db->mallocFailed = 1;
75896              goto exec_out;
75897            }
75898          }
75899        }
75900        if( xCallback(pArg, nCol, azVals, azCols) ){
75901          rc = SQLITE_ABORT;
75902          sqlite3VdbeFinalize((Vdbe *)pStmt);
75903          pStmt = 0;
75904          sqlite3Error(db, SQLITE_ABORT, 0);
75905          goto exec_out;
75906        }
75907      }
75908
75909      if( rc!=SQLITE_ROW ){
75910        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
75911        pStmt = 0;
75912        if( rc!=SQLITE_SCHEMA ){
75913          nRetry = 0;
75914          zSql = zLeftover;
75915          while( sqlite3Isspace(zSql[0]) ) zSql++;
75916        }
75917        break;
75918      }
75919    }
75920
75921    sqlite3DbFree(db, azCols);
75922    azCols = 0;
75923  }
75924
75925exec_out:
75926  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
75927  sqlite3DbFree(db, azCols);
75928
75929  rc = sqlite3ApiExit(db, rc);
75930  if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
75931    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
75932    *pzErrMsg = sqlite3Malloc(nErrMsg);
75933    if( *pzErrMsg ){
75934      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
75935    }else{
75936      rc = SQLITE_NOMEM;
75937      sqlite3Error(db, SQLITE_NOMEM, 0);
75938    }
75939  }else if( pzErrMsg ){
75940    *pzErrMsg = 0;
75941  }
75942
75943  assert( (rc&db->errMask)==rc );
75944  sqlite3_mutex_leave(db->mutex);
75945  return rc;
75946}
75947
75948/************** End of legacy.c **********************************************/
75949/************** Begin file loadext.c *****************************************/
75950/*
75951** 2006 June 7
75952**
75953** The author disclaims copyright to this source code.  In place of
75954** a legal notice, here is a blessing:
75955**
75956**    May you do good and not evil.
75957**    May you find forgiveness for yourself and forgive others.
75958**    May you share freely, never taking more than you give.
75959**
75960*************************************************************************
75961** This file contains code used to dynamically load extensions into
75962** the SQLite library.
75963*/
75964
75965#ifndef SQLITE_CORE
75966  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
75967#endif
75968/************** Include sqlite3ext.h in the middle of loadext.c **************/
75969/************** Begin file sqlite3ext.h **************************************/
75970/*
75971** 2006 June 7
75972**
75973** The author disclaims copyright to this source code.  In place of
75974** a legal notice, here is a blessing:
75975**
75976**    May you do good and not evil.
75977**    May you find forgiveness for yourself and forgive others.
75978**    May you share freely, never taking more than you give.
75979**
75980*************************************************************************
75981** This header file defines the SQLite interface for use by
75982** shared libraries that want to be imported as extensions into
75983** an SQLite instance.  Shared libraries that intend to be loaded
75984** as extensions by SQLite should #include this file instead of
75985** sqlite3.h.
75986*/
75987#ifndef _SQLITE3EXT_H_
75988#define _SQLITE3EXT_H_
75989
75990typedef struct sqlite3_api_routines sqlite3_api_routines;
75991
75992/*
75993** The following structure holds pointers to all of the SQLite API
75994** routines.
75995**
75996** WARNING:  In order to maintain backwards compatibility, add new
75997** interfaces to the end of this structure only.  If you insert new
75998** interfaces in the middle of this structure, then older different
75999** versions of SQLite will not be able to load each others' shared
76000** libraries!
76001*/
76002struct sqlite3_api_routines {
76003  void * (*aggregate_context)(sqlite3_context*,int nBytes);
76004  int  (*aggregate_count)(sqlite3_context*);
76005  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
76006  int  (*bind_double)(sqlite3_stmt*,int,double);
76007  int  (*bind_int)(sqlite3_stmt*,int,int);
76008  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
76009  int  (*bind_null)(sqlite3_stmt*,int);
76010  int  (*bind_parameter_count)(sqlite3_stmt*);
76011  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
76012  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
76013  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
76014  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
76015  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
76016  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
76017  int  (*busy_timeout)(sqlite3*,int ms);
76018  int  (*changes)(sqlite3*);
76019  int  (*close)(sqlite3*);
76020  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
76021  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
76022  const void * (*column_blob)(sqlite3_stmt*,int iCol);
76023  int  (*column_bytes)(sqlite3_stmt*,int iCol);
76024  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
76025  int  (*column_count)(sqlite3_stmt*pStmt);
76026  const char * (*column_database_name)(sqlite3_stmt*,int);
76027  const void * (*column_database_name16)(sqlite3_stmt*,int);
76028  const char * (*column_decltype)(sqlite3_stmt*,int i);
76029  const void * (*column_decltype16)(sqlite3_stmt*,int);
76030  double  (*column_double)(sqlite3_stmt*,int iCol);
76031  int  (*column_int)(sqlite3_stmt*,int iCol);
76032  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
76033  const char * (*column_name)(sqlite3_stmt*,int);
76034  const void * (*column_name16)(sqlite3_stmt*,int);
76035  const char * (*column_origin_name)(sqlite3_stmt*,int);
76036  const void * (*column_origin_name16)(sqlite3_stmt*,int);
76037  const char * (*column_table_name)(sqlite3_stmt*,int);
76038  const void * (*column_table_name16)(sqlite3_stmt*,int);
76039  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
76040  const void * (*column_text16)(sqlite3_stmt*,int iCol);
76041  int  (*column_type)(sqlite3_stmt*,int iCol);
76042  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
76043  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
76044  int  (*complete)(const char*sql);
76045  int  (*complete16)(const void*sql);
76046  int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
76047  int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
76048  int  (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
76049  int  (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
76050  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
76051  int  (*data_count)(sqlite3_stmt*pStmt);
76052  sqlite3 * (*db_handle)(sqlite3_stmt*);
76053  int (*declare_vtab)(sqlite3*,const char*);
76054  int  (*enable_shared_cache)(int);
76055  int  (*errcode)(sqlite3*db);
76056  const char * (*errmsg)(sqlite3*);
76057  const void * (*errmsg16)(sqlite3*);
76058  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
76059  int  (*expired)(sqlite3_stmt*);
76060  int  (*finalize)(sqlite3_stmt*pStmt);
76061  void  (*free)(void*);
76062  void  (*free_table)(char**result);
76063  int  (*get_autocommit)(sqlite3*);
76064  void * (*get_auxdata)(sqlite3_context*,int);
76065  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
76066  int  (*global_recover)(void);
76067  void  (*interruptx)(sqlite3*);
76068  sqlite_int64  (*last_insert_rowid)(sqlite3*);
76069  const char * (*libversion)(void);
76070  int  (*libversion_number)(void);
76071  void *(*malloc)(int);
76072  char * (*mprintf)(const char*,...);
76073  int  (*open)(const char*,sqlite3**);
76074  int  (*open16)(const void*,sqlite3**);
76075  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
76076  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
76077  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
76078  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
76079  void *(*realloc)(void*,int);
76080  int  (*reset)(sqlite3_stmt*pStmt);
76081  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
76082  void  (*result_double)(sqlite3_context*,double);
76083  void  (*result_error)(sqlite3_context*,const char*,int);
76084  void  (*result_error16)(sqlite3_context*,const void*,int);
76085  void  (*result_int)(sqlite3_context*,int);
76086  void  (*result_int64)(sqlite3_context*,sqlite_int64);
76087  void  (*result_null)(sqlite3_context*);
76088  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
76089  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
76090  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
76091  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
76092  void  (*result_value)(sqlite3_context*,sqlite3_value*);
76093  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
76094  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
76095  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
76096  char * (*snprintf)(int,char*,const char*,...);
76097  int  (*step)(sqlite3_stmt*);
76098  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
76099  void  (*thread_cleanup)(void);
76100  int  (*total_changes)(sqlite3*);
76101  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
76102  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
76103  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
76104  void * (*user_data)(sqlite3_context*);
76105  const void * (*value_blob)(sqlite3_value*);
76106  int  (*value_bytes)(sqlite3_value*);
76107  int  (*value_bytes16)(sqlite3_value*);
76108  double  (*value_double)(sqlite3_value*);
76109  int  (*value_int)(sqlite3_value*);
76110  sqlite_int64  (*value_int64)(sqlite3_value*);
76111  int  (*value_numeric_type)(sqlite3_value*);
76112  const unsigned char * (*value_text)(sqlite3_value*);
76113  const void * (*value_text16)(sqlite3_value*);
76114  const void * (*value_text16be)(sqlite3_value*);
76115  const void * (*value_text16le)(sqlite3_value*);
76116  int  (*value_type)(sqlite3_value*);
76117  char *(*vmprintf)(const char*,va_list);
76118  /* Added ??? */
76119  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
76120  /* Added by 3.3.13 */
76121  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
76122  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
76123  int (*clear_bindings)(sqlite3_stmt*);
76124  /* Added by 3.4.1 */
76125  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
76126  /* Added by 3.5.0 */
76127  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
76128  int (*blob_bytes)(sqlite3_blob*);
76129  int (*blob_close)(sqlite3_blob*);
76130  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
76131  int (*blob_read)(sqlite3_blob*,void*,int,int);
76132  int (*blob_write)(sqlite3_blob*,const void*,int,int);
76133  int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
76134  int (*file_control)(sqlite3*,const char*,int,void*);
76135  sqlite3_int64 (*memory_highwater)(int);
76136  sqlite3_int64 (*memory_used)(void);
76137  sqlite3_mutex *(*mutex_alloc)(int);
76138  void (*mutex_enter)(sqlite3_mutex*);
76139  void (*mutex_free)(sqlite3_mutex*);
76140  void (*mutex_leave)(sqlite3_mutex*);
76141  int (*mutex_try)(sqlite3_mutex*);
76142  int (*open_v2)(const char*,sqlite3**,int,const char*);
76143  int (*release_memory)(int);
76144  void (*result_error_nomem)(sqlite3_context*);
76145  void (*result_error_toobig)(sqlite3_context*);
76146  int (*sleep)(int);
76147  void (*soft_heap_limit)(int);
76148  sqlite3_vfs *(*vfs_find)(const char*);
76149  int (*vfs_register)(sqlite3_vfs*,int);
76150  int (*vfs_unregister)(sqlite3_vfs*);
76151  int (*xthreadsafe)(void);
76152  void (*result_zeroblob)(sqlite3_context*,int);
76153  void (*result_error_code)(sqlite3_context*,int);
76154  int (*test_control)(int, ...);
76155  void (*randomness)(int,void*);
76156  sqlite3 *(*context_db_handle)(sqlite3_context*);
76157  int (*extended_result_codes)(sqlite3*,int);
76158  int (*limit)(sqlite3*,int,int);
76159  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
76160  const char *(*sql)(sqlite3_stmt*);
76161  int (*status)(int,int*,int*,int);
76162};
76163
76164/*
76165** The following macros redefine the API routines so that they are
76166** redirected throught the global sqlite3_api structure.
76167**
76168** This header file is also used by the loadext.c source file
76169** (part of the main SQLite library - not an extension) so that
76170** it can get access to the sqlite3_api_routines structure
76171** definition.  But the main library does not want to redefine
76172** the API.  So the redefinition macros are only valid if the
76173** SQLITE_CORE macros is undefined.
76174*/
76175#ifndef SQLITE_CORE
76176#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
76177#ifndef SQLITE_OMIT_DEPRECATED
76178#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
76179#endif
76180#define sqlite3_bind_blob              sqlite3_api->bind_blob
76181#define sqlite3_bind_double            sqlite3_api->bind_double
76182#define sqlite3_bind_int               sqlite3_api->bind_int
76183#define sqlite3_bind_int64             sqlite3_api->bind_int64
76184#define sqlite3_bind_null              sqlite3_api->bind_null
76185#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
76186#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
76187#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
76188#define sqlite3_bind_text              sqlite3_api->bind_text
76189#define sqlite3_bind_text16            sqlite3_api->bind_text16
76190#define sqlite3_bind_value             sqlite3_api->bind_value
76191#define sqlite3_busy_handler           sqlite3_api->busy_handler
76192#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
76193#define sqlite3_changes                sqlite3_api->changes
76194#define sqlite3_close                  sqlite3_api->close
76195#define sqlite3_collation_needed       sqlite3_api->collation_needed
76196#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
76197#define sqlite3_column_blob            sqlite3_api->column_blob
76198#define sqlite3_column_bytes           sqlite3_api->column_bytes
76199#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
76200#define sqlite3_column_count           sqlite3_api->column_count
76201#define sqlite3_column_database_name   sqlite3_api->column_database_name
76202#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
76203#define sqlite3_column_decltype        sqlite3_api->column_decltype
76204#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
76205#define sqlite3_column_double          sqlite3_api->column_double
76206#define sqlite3_column_int             sqlite3_api->column_int
76207#define sqlite3_column_int64           sqlite3_api->column_int64
76208#define sqlite3_column_name            sqlite3_api->column_name
76209#define sqlite3_column_name16          sqlite3_api->column_name16
76210#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
76211#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
76212#define sqlite3_column_table_name      sqlite3_api->column_table_name
76213#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
76214#define sqlite3_column_text            sqlite3_api->column_text
76215#define sqlite3_column_text16          sqlite3_api->column_text16
76216#define sqlite3_column_type            sqlite3_api->column_type
76217#define sqlite3_column_value           sqlite3_api->column_value
76218#define sqlite3_commit_hook            sqlite3_api->commit_hook
76219#define sqlite3_complete               sqlite3_api->complete
76220#define sqlite3_complete16             sqlite3_api->complete16
76221#define sqlite3_create_collation       sqlite3_api->create_collation
76222#define sqlite3_create_collation16     sqlite3_api->create_collation16
76223#define sqlite3_create_function        sqlite3_api->create_function
76224#define sqlite3_create_function16      sqlite3_api->create_function16
76225#define sqlite3_create_module          sqlite3_api->create_module
76226#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
76227#define sqlite3_data_count             sqlite3_api->data_count
76228#define sqlite3_db_handle              sqlite3_api->db_handle
76229#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
76230#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
76231#define sqlite3_errcode                sqlite3_api->errcode
76232#define sqlite3_errmsg                 sqlite3_api->errmsg
76233#define sqlite3_errmsg16               sqlite3_api->errmsg16
76234#define sqlite3_exec                   sqlite3_api->exec
76235#ifndef SQLITE_OMIT_DEPRECATED
76236#define sqlite3_expired                sqlite3_api->expired
76237#endif
76238#define sqlite3_finalize               sqlite3_api->finalize
76239#define sqlite3_free                   sqlite3_api->free
76240#define sqlite3_free_table             sqlite3_api->free_table
76241#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
76242#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
76243#define sqlite3_get_table              sqlite3_api->get_table
76244#ifndef SQLITE_OMIT_DEPRECATED
76245#define sqlite3_global_recover         sqlite3_api->global_recover
76246#endif
76247#define sqlite3_interrupt              sqlite3_api->interruptx
76248#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
76249#define sqlite3_libversion             sqlite3_api->libversion
76250#define sqlite3_libversion_number      sqlite3_api->libversion_number
76251#define sqlite3_malloc                 sqlite3_api->malloc
76252#define sqlite3_mprintf                sqlite3_api->mprintf
76253#define sqlite3_open                   sqlite3_api->open
76254#define sqlite3_open16                 sqlite3_api->open16
76255#define sqlite3_prepare                sqlite3_api->prepare
76256#define sqlite3_prepare16              sqlite3_api->prepare16
76257#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
76258#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
76259#define sqlite3_profile                sqlite3_api->profile
76260#define sqlite3_progress_handler       sqlite3_api->progress_handler
76261#define sqlite3_realloc                sqlite3_api->realloc
76262#define sqlite3_reset                  sqlite3_api->reset
76263#define sqlite3_result_blob            sqlite3_api->result_blob
76264#define sqlite3_result_double          sqlite3_api->result_double
76265#define sqlite3_result_error           sqlite3_api->result_error
76266#define sqlite3_result_error16         sqlite3_api->result_error16
76267#define sqlite3_result_int             sqlite3_api->result_int
76268#define sqlite3_result_int64           sqlite3_api->result_int64
76269#define sqlite3_result_null            sqlite3_api->result_null
76270#define sqlite3_result_text            sqlite3_api->result_text
76271#define sqlite3_result_text16          sqlite3_api->result_text16
76272#define sqlite3_result_text16be        sqlite3_api->result_text16be
76273#define sqlite3_result_text16le        sqlite3_api->result_text16le
76274#define sqlite3_result_value           sqlite3_api->result_value
76275#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
76276#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
76277#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
76278#define sqlite3_snprintf               sqlite3_api->snprintf
76279#define sqlite3_step                   sqlite3_api->step
76280#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
76281#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
76282#define sqlite3_total_changes          sqlite3_api->total_changes
76283#define sqlite3_trace                  sqlite3_api->trace
76284#ifndef SQLITE_OMIT_DEPRECATED
76285#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
76286#endif
76287#define sqlite3_update_hook            sqlite3_api->update_hook
76288#define sqlite3_user_data              sqlite3_api->user_data
76289#define sqlite3_value_blob             sqlite3_api->value_blob
76290#define sqlite3_value_bytes            sqlite3_api->value_bytes
76291#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
76292#define sqlite3_value_double           sqlite3_api->value_double
76293#define sqlite3_value_int              sqlite3_api->value_int
76294#define sqlite3_value_int64            sqlite3_api->value_int64
76295#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
76296#define sqlite3_value_text             sqlite3_api->value_text
76297#define sqlite3_value_text16           sqlite3_api->value_text16
76298#define sqlite3_value_text16be         sqlite3_api->value_text16be
76299#define sqlite3_value_text16le         sqlite3_api->value_text16le
76300#define sqlite3_value_type             sqlite3_api->value_type
76301#define sqlite3_vmprintf               sqlite3_api->vmprintf
76302#define sqlite3_overload_function      sqlite3_api->overload_function
76303#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
76304#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
76305#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
76306#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
76307#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
76308#define sqlite3_blob_close             sqlite3_api->blob_close
76309#define sqlite3_blob_open              sqlite3_api->blob_open
76310#define sqlite3_blob_read              sqlite3_api->blob_read
76311#define sqlite3_blob_write             sqlite3_api->blob_write
76312#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
76313#define sqlite3_file_control           sqlite3_api->file_control
76314#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
76315#define sqlite3_memory_used            sqlite3_api->memory_used
76316#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
76317#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
76318#define sqlite3_mutex_free             sqlite3_api->mutex_free
76319#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
76320#define sqlite3_mutex_try              sqlite3_api->mutex_try
76321#define sqlite3_open_v2                sqlite3_api->open_v2
76322#define sqlite3_release_memory         sqlite3_api->release_memory
76323#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
76324#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
76325#define sqlite3_sleep                  sqlite3_api->sleep
76326#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
76327#define sqlite3_vfs_find               sqlite3_api->vfs_find
76328#define sqlite3_vfs_register           sqlite3_api->vfs_register
76329#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
76330#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
76331#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
76332#define sqlite3_result_error_code      sqlite3_api->result_error_code
76333#define sqlite3_test_control           sqlite3_api->test_control
76334#define sqlite3_randomness             sqlite3_api->randomness
76335#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
76336#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
76337#define sqlite3_limit                  sqlite3_api->limit
76338#define sqlite3_next_stmt              sqlite3_api->next_stmt
76339#define sqlite3_sql                    sqlite3_api->sql
76340#define sqlite3_status                 sqlite3_api->status
76341#endif /* SQLITE_CORE */
76342
76343#define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
76344#define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
76345
76346#endif /* _SQLITE3EXT_H_ */
76347
76348/************** End of sqlite3ext.h ******************************************/
76349/************** Continuing where we left off in loadext.c ********************/
76350
76351#ifndef SQLITE_OMIT_LOAD_EXTENSION
76352
76353/*
76354** Some API routines are omitted when various features are
76355** excluded from a build of SQLite.  Substitute a NULL pointer
76356** for any missing APIs.
76357*/
76358#ifndef SQLITE_ENABLE_COLUMN_METADATA
76359# define sqlite3_column_database_name   0
76360# define sqlite3_column_database_name16 0
76361# define sqlite3_column_table_name      0
76362# define sqlite3_column_table_name16    0
76363# define sqlite3_column_origin_name     0
76364# define sqlite3_column_origin_name16   0
76365# define sqlite3_table_column_metadata  0
76366#endif
76367
76368#ifdef SQLITE_OMIT_AUTHORIZATION
76369# define sqlite3_set_authorizer         0
76370#endif
76371
76372#ifdef SQLITE_OMIT_UTF16
76373# define sqlite3_bind_text16            0
76374# define sqlite3_collation_needed16     0
76375# define sqlite3_column_decltype16      0
76376# define sqlite3_column_name16          0
76377# define sqlite3_column_text16          0
76378# define sqlite3_complete16             0
76379# define sqlite3_create_collation16     0
76380# define sqlite3_create_function16      0
76381# define sqlite3_errmsg16               0
76382# define sqlite3_open16                 0
76383# define sqlite3_prepare16              0
76384# define sqlite3_prepare16_v2           0
76385# define sqlite3_result_error16         0
76386# define sqlite3_result_text16          0
76387# define sqlite3_result_text16be        0
76388# define sqlite3_result_text16le        0
76389# define sqlite3_value_text16           0
76390# define sqlite3_value_text16be         0
76391# define sqlite3_value_text16le         0
76392# define sqlite3_column_database_name16 0
76393# define sqlite3_column_table_name16    0
76394# define sqlite3_column_origin_name16   0
76395#endif
76396
76397#ifdef SQLITE_OMIT_COMPLETE
76398# define sqlite3_complete 0
76399# define sqlite3_complete16 0
76400#endif
76401
76402#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
76403# define sqlite3_progress_handler 0
76404#endif
76405
76406#ifdef SQLITE_OMIT_VIRTUALTABLE
76407# define sqlite3_create_module 0
76408# define sqlite3_create_module_v2 0
76409# define sqlite3_declare_vtab 0
76410#endif
76411
76412#ifdef SQLITE_OMIT_SHARED_CACHE
76413# define sqlite3_enable_shared_cache 0
76414#endif
76415
76416#ifdef SQLITE_OMIT_TRACE
76417# define sqlite3_profile       0
76418# define sqlite3_trace         0
76419#endif
76420
76421#ifdef SQLITE_OMIT_GET_TABLE
76422# define sqlite3_free_table    0
76423# define sqlite3_get_table     0
76424#endif
76425
76426#ifdef SQLITE_OMIT_INCRBLOB
76427#define sqlite3_bind_zeroblob  0
76428#define sqlite3_blob_bytes     0
76429#define sqlite3_blob_close     0
76430#define sqlite3_blob_open      0
76431#define sqlite3_blob_read      0
76432#define sqlite3_blob_write     0
76433#endif
76434
76435/*
76436** The following structure contains pointers to all SQLite API routines.
76437** A pointer to this structure is passed into extensions when they are
76438** loaded so that the extension can make calls back into the SQLite
76439** library.
76440**
76441** When adding new APIs, add them to the bottom of this structure
76442** in order to preserve backwards compatibility.
76443**
76444** Extensions that use newer APIs should first call the
76445** sqlite3_libversion_number() to make sure that the API they
76446** intend to use is supported by the library.  Extensions should
76447** also check to make sure that the pointer to the function is
76448** not NULL before calling it.
76449*/
76450static const sqlite3_api_routines sqlite3Apis = {
76451  sqlite3_aggregate_context,
76452#ifndef SQLITE_OMIT_DEPRECATED
76453  sqlite3_aggregate_count,
76454#else
76455  0,
76456#endif
76457  sqlite3_bind_blob,
76458  sqlite3_bind_double,
76459  sqlite3_bind_int,
76460  sqlite3_bind_int64,
76461  sqlite3_bind_null,
76462  sqlite3_bind_parameter_count,
76463  sqlite3_bind_parameter_index,
76464  sqlite3_bind_parameter_name,
76465  sqlite3_bind_text,
76466  sqlite3_bind_text16,
76467  sqlite3_bind_value,
76468  sqlite3_busy_handler,
76469  sqlite3_busy_timeout,
76470  sqlite3_changes,
76471  sqlite3_close,
76472  sqlite3_collation_needed,
76473  sqlite3_collation_needed16,
76474  sqlite3_column_blob,
76475  sqlite3_column_bytes,
76476  sqlite3_column_bytes16,
76477  sqlite3_column_count,
76478  sqlite3_column_database_name,
76479  sqlite3_column_database_name16,
76480  sqlite3_column_decltype,
76481  sqlite3_column_decltype16,
76482  sqlite3_column_double,
76483  sqlite3_column_int,
76484  sqlite3_column_int64,
76485  sqlite3_column_name,
76486  sqlite3_column_name16,
76487  sqlite3_column_origin_name,
76488  sqlite3_column_origin_name16,
76489  sqlite3_column_table_name,
76490  sqlite3_column_table_name16,
76491  sqlite3_column_text,
76492  sqlite3_column_text16,
76493  sqlite3_column_type,
76494  sqlite3_column_value,
76495  sqlite3_commit_hook,
76496  sqlite3_complete,
76497  sqlite3_complete16,
76498  sqlite3_create_collation,
76499  sqlite3_create_collation16,
76500  sqlite3_create_function,
76501  sqlite3_create_function16,
76502  sqlite3_create_module,
76503  sqlite3_data_count,
76504  sqlite3_db_handle,
76505  sqlite3_declare_vtab,
76506  sqlite3_enable_shared_cache,
76507  sqlite3_errcode,
76508  sqlite3_errmsg,
76509  sqlite3_errmsg16,
76510  sqlite3_exec,
76511#ifndef SQLITE_OMIT_DEPRECATED
76512  sqlite3_expired,
76513#else
76514  0,
76515#endif
76516  sqlite3_finalize,
76517  sqlite3_free,
76518  sqlite3_free_table,
76519  sqlite3_get_autocommit,
76520  sqlite3_get_auxdata,
76521  sqlite3_get_table,
76522  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
76523  sqlite3_interrupt,
76524  sqlite3_last_insert_rowid,
76525  sqlite3_libversion,
76526  sqlite3_libversion_number,
76527  sqlite3_malloc,
76528  sqlite3_mprintf,
76529  sqlite3_open,
76530  sqlite3_open16,
76531  sqlite3_prepare,
76532  sqlite3_prepare16,
76533  sqlite3_profile,
76534  sqlite3_progress_handler,
76535  sqlite3_realloc,
76536  sqlite3_reset,
76537  sqlite3_result_blob,
76538  sqlite3_result_double,
76539  sqlite3_result_error,
76540  sqlite3_result_error16,
76541  sqlite3_result_int,
76542  sqlite3_result_int64,
76543  sqlite3_result_null,
76544  sqlite3_result_text,
76545  sqlite3_result_text16,
76546  sqlite3_result_text16be,
76547  sqlite3_result_text16le,
76548  sqlite3_result_value,
76549  sqlite3_rollback_hook,
76550  sqlite3_set_authorizer,
76551  sqlite3_set_auxdata,
76552  sqlite3_snprintf,
76553  sqlite3_step,
76554  sqlite3_table_column_metadata,
76555#ifndef SQLITE_OMIT_DEPRECATED
76556  sqlite3_thread_cleanup,
76557#else
76558  0,
76559#endif
76560  sqlite3_total_changes,
76561  sqlite3_trace,
76562#ifndef SQLITE_OMIT_DEPRECATED
76563  sqlite3_transfer_bindings,
76564#else
76565  0,
76566#endif
76567  sqlite3_update_hook,
76568  sqlite3_user_data,
76569  sqlite3_value_blob,
76570  sqlite3_value_bytes,
76571  sqlite3_value_bytes16,
76572  sqlite3_value_double,
76573  sqlite3_value_int,
76574  sqlite3_value_int64,
76575  sqlite3_value_numeric_type,
76576  sqlite3_value_text,
76577  sqlite3_value_text16,
76578  sqlite3_value_text16be,
76579  sqlite3_value_text16le,
76580  sqlite3_value_type,
76581  sqlite3_vmprintf,
76582  /*
76583  ** The original API set ends here.  All extensions can call any
76584  ** of the APIs above provided that the pointer is not NULL.  But
76585  ** before calling APIs that follow, extension should check the
76586  ** sqlite3_libversion_number() to make sure they are dealing with
76587  ** a library that is new enough to support that API.
76588  *************************************************************************
76589  */
76590  sqlite3_overload_function,
76591
76592  /*
76593  ** Added after 3.3.13
76594  */
76595  sqlite3_prepare_v2,
76596  sqlite3_prepare16_v2,
76597  sqlite3_clear_bindings,
76598
76599  /*
76600  ** Added for 3.4.1
76601  */
76602  sqlite3_create_module_v2,
76603
76604  /*
76605  ** Added for 3.5.0
76606  */
76607  sqlite3_bind_zeroblob,
76608  sqlite3_blob_bytes,
76609  sqlite3_blob_close,
76610  sqlite3_blob_open,
76611  sqlite3_blob_read,
76612  sqlite3_blob_write,
76613  sqlite3_create_collation_v2,
76614  sqlite3_file_control,
76615  sqlite3_memory_highwater,
76616  sqlite3_memory_used,
76617#ifdef SQLITE_MUTEX_OMIT
76618  0,
76619  0,
76620  0,
76621  0,
76622  0,
76623#else
76624  sqlite3_mutex_alloc,
76625  sqlite3_mutex_enter,
76626  sqlite3_mutex_free,
76627  sqlite3_mutex_leave,
76628  sqlite3_mutex_try,
76629#endif
76630  sqlite3_open_v2,
76631  sqlite3_release_memory,
76632  sqlite3_result_error_nomem,
76633  sqlite3_result_error_toobig,
76634  sqlite3_sleep,
76635  sqlite3_soft_heap_limit,
76636  sqlite3_vfs_find,
76637  sqlite3_vfs_register,
76638  sqlite3_vfs_unregister,
76639
76640  /*
76641  ** Added for 3.5.8
76642  */
76643  sqlite3_threadsafe,
76644  sqlite3_result_zeroblob,
76645  sqlite3_result_error_code,
76646  sqlite3_test_control,
76647  sqlite3_randomness,
76648  sqlite3_context_db_handle,
76649
76650  /*
76651  ** Added for 3.6.0
76652  */
76653  sqlite3_extended_result_codes,
76654  sqlite3_limit,
76655  sqlite3_next_stmt,
76656  sqlite3_sql,
76657  sqlite3_status,
76658};
76659
76660/*
76661** Attempt to load an SQLite extension library contained in the file
76662** zFile.  The entry point is zProc.  zProc may be 0 in which case a
76663** default entry point name (sqlite3_extension_init) is used.  Use
76664** of the default name is recommended.
76665**
76666** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
76667**
76668** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
76669** error message text.  The calling function should free this memory
76670** by calling sqlite3DbFree(db, ).
76671*/
76672static int sqlite3LoadExtension(
76673  sqlite3 *db,          /* Load the extension into this database connection */
76674  const char *zFile,    /* Name of the shared library containing extension */
76675  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
76676  char **pzErrMsg       /* Put error message here if not 0 */
76677){
76678  sqlite3_vfs *pVfs = db->pVfs;
76679  void *handle;
76680  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
76681  char *zErrmsg = 0;
76682  void **aHandle;
76683  const int nMsg = 300;
76684
76685  if( pzErrMsg ) *pzErrMsg = 0;
76686
76687  /* Ticket #1863.  To avoid a creating security problems for older
76688  ** applications that relink against newer versions of SQLite, the
76689  ** ability to run load_extension is turned off by default.  One
76690  ** must call sqlite3_enable_load_extension() to turn on extension
76691  ** loading.  Otherwise you get the following error.
76692  */
76693  if( (db->flags & SQLITE_LoadExtension)==0 ){
76694    if( pzErrMsg ){
76695      *pzErrMsg = sqlite3_mprintf("not authorized");
76696    }
76697    return SQLITE_ERROR;
76698  }
76699
76700  if( zProc==0 ){
76701    zProc = "sqlite3_extension_init";
76702  }
76703
76704  handle = sqlite3OsDlOpen(pVfs, zFile);
76705  if( handle==0 ){
76706    if( pzErrMsg ){
76707      zErrmsg = sqlite3StackAllocZero(db, nMsg);
76708      if( zErrmsg ){
76709        sqlite3_snprintf(nMsg, zErrmsg,
76710            "unable to open shared library [%s]", zFile);
76711        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
76712        *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
76713        sqlite3StackFree(db, zErrmsg);
76714      }
76715    }
76716    return SQLITE_ERROR;
76717  }
76718  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
76719                   sqlite3OsDlSym(pVfs, handle, zProc);
76720  if( xInit==0 ){
76721    if( pzErrMsg ){
76722      zErrmsg = sqlite3StackAllocZero(db, nMsg);
76723      if( zErrmsg ){
76724        sqlite3_snprintf(nMsg, zErrmsg,
76725            "no entry point [%s] in shared library [%s]", zProc,zFile);
76726        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
76727        *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
76728        sqlite3StackFree(db, zErrmsg);
76729      }
76730      sqlite3OsDlClose(pVfs, handle);
76731    }
76732    return SQLITE_ERROR;
76733  }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
76734    if( pzErrMsg ){
76735      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
76736    }
76737    sqlite3_free(zErrmsg);
76738    sqlite3OsDlClose(pVfs, handle);
76739    return SQLITE_ERROR;
76740  }
76741
76742  /* Append the new shared library handle to the db->aExtension array. */
76743  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
76744  if( aHandle==0 ){
76745    return SQLITE_NOMEM;
76746  }
76747  if( db->nExtension>0 ){
76748    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
76749  }
76750  sqlite3DbFree(db, db->aExtension);
76751  db->aExtension = aHandle;
76752
76753  db->aExtension[db->nExtension++] = handle;
76754  return SQLITE_OK;
76755}
76756SQLITE_API int sqlite3_load_extension(
76757  sqlite3 *db,          /* Load the extension into this database connection */
76758  const char *zFile,    /* Name of the shared library containing extension */
76759  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
76760  char **pzErrMsg       /* Put error message here if not 0 */
76761){
76762  int rc;
76763  sqlite3_mutex_enter(db->mutex);
76764  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
76765  rc = sqlite3ApiExit(db, rc);
76766  sqlite3_mutex_leave(db->mutex);
76767  return rc;
76768}
76769
76770/*
76771** Call this routine when the database connection is closing in order
76772** to clean up loaded extensions
76773*/
76774SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
76775  int i;
76776  assert( sqlite3_mutex_held(db->mutex) );
76777  for(i=0; i<db->nExtension; i++){
76778    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
76779  }
76780  sqlite3DbFree(db, db->aExtension);
76781}
76782
76783/*
76784** Enable or disable extension loading.  Extension loading is disabled by
76785** default so as not to open security holes in older applications.
76786*/
76787SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
76788  sqlite3_mutex_enter(db->mutex);
76789  if( onoff ){
76790    db->flags |= SQLITE_LoadExtension;
76791  }else{
76792    db->flags &= ~SQLITE_LoadExtension;
76793  }
76794  sqlite3_mutex_leave(db->mutex);
76795  return SQLITE_OK;
76796}
76797
76798#endif /* SQLITE_OMIT_LOAD_EXTENSION */
76799
76800/*
76801** The auto-extension code added regardless of whether or not extension
76802** loading is supported.  We need a dummy sqlite3Apis pointer for that
76803** code if regular extension loading is not available.  This is that
76804** dummy pointer.
76805*/
76806#ifdef SQLITE_OMIT_LOAD_EXTENSION
76807static const sqlite3_api_routines sqlite3Apis = { 0 };
76808#endif
76809
76810
76811/*
76812** The following object holds the list of automatically loaded
76813** extensions.
76814**
76815** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
76816** mutex must be held while accessing this list.
76817*/
76818typedef struct sqlite3AutoExtList sqlite3AutoExtList;
76819static SQLITE_WSD struct sqlite3AutoExtList {
76820  int nExt;              /* Number of entries in aExt[] */
76821  void (**aExt)(void);   /* Pointers to the extension init functions */
76822} sqlite3Autoext = { 0, 0 };
76823
76824/* The "wsdAutoext" macro will resolve to the autoextension
76825** state vector.  If writable static data is unsupported on the target,
76826** we have to locate the state vector at run-time.  In the more common
76827** case where writable static data is supported, wsdStat can refer directly
76828** to the "sqlite3Autoext" state vector declared above.
76829*/
76830#ifdef SQLITE_OMIT_WSD
76831# define wsdAutoextInit \
76832  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
76833# define wsdAutoext x[0]
76834#else
76835# define wsdAutoextInit
76836# define wsdAutoext sqlite3Autoext
76837#endif
76838
76839
76840/*
76841** Register a statically linked extension that is automatically
76842** loaded by every new database connection.
76843*/
76844SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
76845  int rc = SQLITE_OK;
76846#ifndef SQLITE_OMIT_AUTOINIT
76847  rc = sqlite3_initialize();
76848  if( rc ){
76849    return rc;
76850  }else
76851#endif
76852  {
76853    int i;
76854#if SQLITE_THREADSAFE
76855    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
76856#endif
76857    wsdAutoextInit;
76858    sqlite3_mutex_enter(mutex);
76859    for(i=0; i<wsdAutoext.nExt; i++){
76860      if( wsdAutoext.aExt[i]==xInit ) break;
76861    }
76862    if( i==wsdAutoext.nExt ){
76863      int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
76864      void (**aNew)(void);
76865      aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
76866      if( aNew==0 ){
76867        rc = SQLITE_NOMEM;
76868      }else{
76869        wsdAutoext.aExt = aNew;
76870        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
76871        wsdAutoext.nExt++;
76872      }
76873    }
76874    sqlite3_mutex_leave(mutex);
76875    assert( (rc&0xff)==rc );
76876    return rc;
76877  }
76878}
76879
76880/*
76881** Reset the automatic extension loading mechanism.
76882*/
76883SQLITE_API void sqlite3_reset_auto_extension(void){
76884#ifndef SQLITE_OMIT_AUTOINIT
76885  if( sqlite3_initialize()==SQLITE_OK )
76886#endif
76887  {
76888#if SQLITE_THREADSAFE
76889    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
76890#endif
76891    wsdAutoextInit;
76892    sqlite3_mutex_enter(mutex);
76893    sqlite3_free(wsdAutoext.aExt);
76894    wsdAutoext.aExt = 0;
76895    wsdAutoext.nExt = 0;
76896    sqlite3_mutex_leave(mutex);
76897  }
76898}
76899
76900/*
76901** Load all automatic extensions.
76902**
76903** If anything goes wrong, set an error in the database connection.
76904*/
76905SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
76906  int i;
76907  int go = 1;
76908  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
76909
76910  wsdAutoextInit;
76911  if( wsdAutoext.nExt==0 ){
76912    /* Common case: early out without every having to acquire a mutex */
76913    return;
76914  }
76915  for(i=0; go; i++){
76916    char *zErrmsg;
76917#if SQLITE_THREADSAFE
76918    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
76919#endif
76920    sqlite3_mutex_enter(mutex);
76921    if( i>=wsdAutoext.nExt ){
76922      xInit = 0;
76923      go = 0;
76924    }else{
76925      xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
76926              wsdAutoext.aExt[i];
76927    }
76928    sqlite3_mutex_leave(mutex);
76929    zErrmsg = 0;
76930    if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
76931      sqlite3Error(db, SQLITE_ERROR,
76932            "automatic extension loading failed: %s", zErrmsg);
76933      go = 0;
76934    }
76935    sqlite3_free(zErrmsg);
76936  }
76937}
76938
76939/************** End of loadext.c *********************************************/
76940/************** Begin file pragma.c ******************************************/
76941/*
76942** 2003 April 6
76943**
76944** The author disclaims copyright to this source code.  In place of
76945** a legal notice, here is a blessing:
76946**
76947**    May you do good and not evil.
76948**    May you find forgiveness for yourself and forgive others.
76949**    May you share freely, never taking more than you give.
76950**
76951*************************************************************************
76952** This file contains code used to implement the PRAGMA command.
76953*/
76954
76955/* Ignore this whole file if pragmas are disabled
76956*/
76957#if !defined(SQLITE_OMIT_PRAGMA)
76958
76959/*
76960** Interpret the given string as a safety level.  Return 0 for OFF,
76961** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
76962** unrecognized string argument.
76963**
76964** Note that the values returned are one less that the values that
76965** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
76966** to support legacy SQL code.  The safety level used to be boolean
76967** and older scripts may have used numbers 0 for OFF and 1 for ON.
76968*/
76969static u8 getSafetyLevel(const char *z){
76970                             /* 123456789 123456789 */
76971  static const char zText[] = "onoffalseyestruefull";
76972  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
76973  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
76974  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
76975  int i, n;
76976  if( sqlite3Isdigit(*z) ){
76977    return (u8)atoi(z);
76978  }
76979  n = sqlite3Strlen30(z);
76980  for(i=0; i<ArraySize(iLength); i++){
76981    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
76982      return iValue[i];
76983    }
76984  }
76985  return 1;
76986}
76987
76988/*
76989** Interpret the given string as a boolean value.
76990*/
76991static u8 getBoolean(const char *z){
76992  return getSafetyLevel(z)&1;
76993}
76994
76995/*
76996** Interpret the given string as a locking mode value.
76997*/
76998static int getLockingMode(const char *z){
76999  if( z ){
77000    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
77001    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
77002  }
77003  return PAGER_LOCKINGMODE_QUERY;
77004}
77005
77006#ifndef SQLITE_OMIT_AUTOVACUUM
77007/*
77008** Interpret the given string as an auto-vacuum mode value.
77009**
77010** The following strings, "none", "full" and "incremental" are
77011** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
77012*/
77013static int getAutoVacuum(const char *z){
77014  int i;
77015  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
77016  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
77017  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
77018  i = atoi(z);
77019  return (u8)((i>=0&&i<=2)?i:0);
77020}
77021#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
77022
77023#ifndef SQLITE_OMIT_PAGER_PRAGMAS
77024/*
77025** Interpret the given string as a temp db location. Return 1 for file
77026** backed temporary databases, 2 for the Red-Black tree in memory database
77027** and 0 to use the compile-time default.
77028*/
77029static int getTempStore(const char *z){
77030  if( z[0]>='0' && z[0]<='2' ){
77031    return z[0] - '0';
77032  }else if( sqlite3StrICmp(z, "file")==0 ){
77033    return 1;
77034  }else if( sqlite3StrICmp(z, "memory")==0 ){
77035    return 2;
77036  }else{
77037    return 0;
77038  }
77039}
77040#endif /* SQLITE_PAGER_PRAGMAS */
77041
77042#ifndef SQLITE_OMIT_PAGER_PRAGMAS
77043/*
77044** Invalidate temp storage, either when the temp storage is changed
77045** from default, or when 'file' and the temp_store_directory has changed
77046*/
77047static int invalidateTempStorage(Parse *pParse){
77048  sqlite3 *db = pParse->db;
77049  if( db->aDb[1].pBt!=0 ){
77050    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
77051      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
77052        "from within a transaction");
77053      return SQLITE_ERROR;
77054    }
77055    sqlite3BtreeClose(db->aDb[1].pBt);
77056    db->aDb[1].pBt = 0;
77057    sqlite3ResetInternalSchema(db, 0);
77058  }
77059  return SQLITE_OK;
77060}
77061#endif /* SQLITE_PAGER_PRAGMAS */
77062
77063#ifndef SQLITE_OMIT_PAGER_PRAGMAS
77064/*
77065** If the TEMP database is open, close it and mark the database schema
77066** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
77067** or DEFAULT_TEMP_STORE pragmas.
77068*/
77069static int changeTempStorage(Parse *pParse, const char *zStorageType){
77070  int ts = getTempStore(zStorageType);
77071  sqlite3 *db = pParse->db;
77072  if( db->temp_store==ts ) return SQLITE_OK;
77073  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
77074    return SQLITE_ERROR;
77075  }
77076  db->temp_store = (u8)ts;
77077  return SQLITE_OK;
77078}
77079#endif /* SQLITE_PAGER_PRAGMAS */
77080
77081/*
77082** Generate code to return a single integer value.
77083*/
77084static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
77085  Vdbe *v = sqlite3GetVdbe(pParse);
77086  int mem = ++pParse->nMem;
77087  i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
77088  if( pI64 ){
77089    memcpy(pI64, &value, sizeof(value));
77090  }
77091  sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
77092  sqlite3VdbeSetNumCols(v, 1);
77093  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
77094  sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
77095}
77096
77097#ifndef SQLITE_OMIT_FLAG_PRAGMAS
77098/*
77099** Check to see if zRight and zLeft refer to a pragma that queries
77100** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
77101** Also, implement the pragma.
77102*/
77103static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
77104  static const struct sPragmaType {
77105    const char *zName;  /* Name of the pragma */
77106    int mask;           /* Mask for the db->flags value */
77107  } aPragma[] = {
77108    { "full_column_names",        SQLITE_FullColNames  },
77109    { "short_column_names",       SQLITE_ShortColNames },
77110    { "count_changes",            SQLITE_CountRows     },
77111    { "empty_result_callbacks",   SQLITE_NullCallback  },
77112    { "legacy_file_format",       SQLITE_LegacyFileFmt },
77113    { "fullfsync",                SQLITE_FullFSync     },
77114    { "reverse_unordered_selects", SQLITE_ReverseOrder  },
77115#ifdef SQLITE_DEBUG
77116    { "sql_trace",                SQLITE_SqlTrace      },
77117    { "vdbe_listing",             SQLITE_VdbeListing   },
77118    { "vdbe_trace",               SQLITE_VdbeTrace     },
77119#endif
77120#ifndef SQLITE_OMIT_CHECK
77121    { "ignore_check_constraints", SQLITE_IgnoreChecks  },
77122#endif
77123    /* The following is VERY experimental */
77124    { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
77125    { "omit_readlock",            SQLITE_NoReadlock    },
77126
77127    /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
77128    ** flag if there are any active statements. */
77129    { "read_uncommitted",         SQLITE_ReadUncommitted },
77130    { "recursive_triggers",       SQLITE_RecTriggers },
77131
77132    /* This flag may only be set if both foreign-key and trigger support
77133    ** are present in the build.  */
77134#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
77135    { "foreign_keys",             SQLITE_ForeignKeys },
77136#endif
77137  };
77138  int i;
77139  const struct sPragmaType *p;
77140  for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
77141    if( sqlite3StrICmp(zLeft, p->zName)==0 ){
77142      sqlite3 *db = pParse->db;
77143      Vdbe *v;
77144      v = sqlite3GetVdbe(pParse);
77145      assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
77146      if( ALWAYS(v) ){
77147        if( zRight==0 ){
77148          returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
77149        }else{
77150          int mask = p->mask;          /* Mask of bits to set or clear. */
77151          if( db->autoCommit==0 ){
77152            /* Foreign key support may not be enabled or disabled while not
77153            ** in auto-commit mode.  */
77154            mask &= ~(SQLITE_ForeignKeys);
77155          }
77156
77157          if( getBoolean(zRight) ){
77158            db->flags |= mask;
77159          }else{
77160            db->flags &= ~mask;
77161          }
77162
77163          /* Many of the flag-pragmas modify the code generated by the SQL
77164          ** compiler (eg. count_changes). So add an opcode to expire all
77165          ** compiled SQL statements after modifying a pragma value.
77166          */
77167          sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
77168        }
77169      }
77170
77171      return 1;
77172    }
77173  }
77174  return 0;
77175}
77176#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
77177
77178/*
77179** Return a human-readable name for a constraint resolution action.
77180*/
77181#ifndef SQLITE_OMIT_FOREIGN_KEY
77182static const char *actionName(u8 action){
77183  const char *zName;
77184  switch( action ){
77185    case OE_SetNull:  zName = "SET NULL";        break;
77186    case OE_SetDflt:  zName = "SET DEFAULT";     break;
77187    case OE_Cascade:  zName = "CASCADE";         break;
77188    case OE_Restrict: zName = "RESTRICT";        break;
77189    default:          zName = "NO ACTION";
77190                      assert( action==OE_None ); break;
77191  }
77192  return zName;
77193}
77194#endif
77195
77196/*
77197** Process a pragma statement.
77198**
77199** Pragmas are of this form:
77200**
77201**      PRAGMA [database.]id [= value]
77202**
77203** The identifier might also be a string.  The value is a string, and
77204** identifier, or a number.  If minusFlag is true, then the value is
77205** a number that was preceded by a minus sign.
77206**
77207** If the left side is "database.id" then pId1 is the database name
77208** and pId2 is the id.  If the left side is just "id" then pId1 is the
77209** id and pId2 is any empty string.
77210*/
77211SQLITE_PRIVATE void sqlite3Pragma(
77212  Parse *pParse,
77213  Token *pId1,        /* First part of [database.]id field */
77214  Token *pId2,        /* Second part of [database.]id field, or NULL */
77215  Token *pValue,      /* Token for <value>, or NULL */
77216  int minusFlag       /* True if a '-' sign preceded <value> */
77217){
77218  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
77219  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
77220  const char *zDb = 0;   /* The database name */
77221  Token *pId;            /* Pointer to <id> token */
77222  int iDb;               /* Database index for <database> */
77223  sqlite3 *db = pParse->db;
77224  Db *pDb;
77225  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
77226  if( v==0 ) return;
77227  sqlite3VdbeRunOnlyOnce(v);
77228  pParse->nMem = 2;
77229
77230  /* Interpret the [database.] part of the pragma statement. iDb is the
77231  ** index of the database this pragma is being applied to in db.aDb[]. */
77232  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
77233  if( iDb<0 ) return;
77234  pDb = &db->aDb[iDb];
77235
77236  /* If the temp database has been explicitly named as part of the
77237  ** pragma, make sure it is open.
77238  */
77239  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
77240    return;
77241  }
77242
77243  zLeft = sqlite3NameFromToken(db, pId);
77244  if( !zLeft ) return;
77245  if( minusFlag ){
77246    zRight = sqlite3MPrintf(db, "-%T", pValue);
77247  }else{
77248    zRight = sqlite3NameFromToken(db, pValue);
77249  }
77250
77251  assert( pId2 );
77252  zDb = pId2->n>0 ? pDb->zName : 0;
77253  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
77254    goto pragma_out;
77255  }
77256
77257#ifndef SQLITE_OMIT_PAGER_PRAGMAS
77258  /*
77259  **  PRAGMA [database.]default_cache_size
77260  **  PRAGMA [database.]default_cache_size=N
77261  **
77262  ** The first form reports the current persistent setting for the
77263  ** page cache size.  The value returned is the maximum number of
77264  ** pages in the page cache.  The second form sets both the current
77265  ** page cache size value and the persistent page cache size value
77266  ** stored in the database file.
77267  **
77268  ** The default cache size is stored in meta-value 2 of page 1 of the
77269  ** database file.  The cache size is actually the absolute value of
77270  ** this memory location.  The sign of meta-value 2 determines the
77271  ** synchronous setting.  A negative value means synchronous is off
77272  ** and a positive value means synchronous is on.
77273  */
77274  if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
77275    static const VdbeOpList getCacheSize[] = {
77276      { OP_Transaction, 0, 0,        0},                         /* 0 */
77277      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
77278      { OP_IfPos,       1, 7,        0},
77279      { OP_Integer,     0, 2,        0},
77280      { OP_Subtract,    1, 2,        1},
77281      { OP_IfPos,       1, 7,        0},
77282      { OP_Integer,     0, 1,        0},                         /* 6 */
77283      { OP_ResultRow,   1, 1,        0},
77284    };
77285    int addr;
77286    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77287    sqlite3VdbeUsesBtree(v, iDb);
77288    if( !zRight ){
77289      sqlite3VdbeSetNumCols(v, 1);
77290      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
77291      pParse->nMem += 2;
77292      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
77293      sqlite3VdbeChangeP1(v, addr, iDb);
77294      sqlite3VdbeChangeP1(v, addr+1, iDb);
77295      sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
77296    }else{
77297      int size = atoi(zRight);
77298      if( size<0 ) size = -size;
77299      sqlite3BeginWriteOperation(pParse, 0, iDb);
77300      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
77301      sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, BTREE_DEFAULT_CACHE_SIZE);
77302      addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
77303      sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
77304      sqlite3VdbeJumpHere(v, addr);
77305      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
77306      pDb->pSchema->cache_size = size;
77307      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
77308    }
77309  }else
77310
77311  /*
77312  **  PRAGMA [database.]page_size
77313  **  PRAGMA [database.]page_size=N
77314  **
77315  ** The first form reports the current setting for the
77316  ** database page size in bytes.  The second form sets the
77317  ** database page size value.  The value can only be set if
77318  ** the database has not yet been created.
77319  */
77320  if( sqlite3StrICmp(zLeft,"page_size")==0 ){
77321    Btree *pBt = pDb->pBt;
77322    assert( pBt!=0 );
77323    if( !zRight ){
77324      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
77325      returnSingleInt(pParse, "page_size", size);
77326    }else{
77327      /* Malloc may fail when setting the page-size, as there is an internal
77328      ** buffer that the pager module resizes using sqlite3_realloc().
77329      */
77330      db->nextPagesize = atoi(zRight);
77331      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
77332        db->mallocFailed = 1;
77333      }
77334    }
77335  }else
77336
77337  /*
77338  **  PRAGMA [database.]max_page_count
77339  **  PRAGMA [database.]max_page_count=N
77340  **
77341  ** The first form reports the current setting for the
77342  ** maximum number of pages in the database file.  The
77343  ** second form attempts to change this setting.  Both
77344  ** forms return the current setting.
77345  */
77346  if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
77347    Btree *pBt = pDb->pBt;
77348    int newMax = 0;
77349    assert( pBt!=0 );
77350    if( zRight ){
77351      newMax = atoi(zRight);
77352    }
77353    if( ALWAYS(pBt) ){
77354      newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
77355    }
77356    returnSingleInt(pParse, "max_page_count", newMax);
77357  }else
77358
77359  /*
77360  **  PRAGMA [database.]page_count
77361  **
77362  ** Return the number of pages in the specified database.
77363  */
77364  if( sqlite3StrICmp(zLeft,"page_count")==0 ){
77365    int iReg;
77366    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77367    sqlite3CodeVerifySchema(pParse, iDb);
77368    iReg = ++pParse->nMem;
77369    sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
77370    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
77371    sqlite3VdbeSetNumCols(v, 1);
77372    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
77373  }else
77374
77375  /*
77376  **  PRAGMA [database.]locking_mode
77377  **  PRAGMA [database.]locking_mode = (normal|exclusive)
77378  */
77379  if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
77380    const char *zRet = "normal";
77381    int eMode = getLockingMode(zRight);
77382
77383    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
77384      /* Simple "PRAGMA locking_mode;" statement. This is a query for
77385      ** the current default locking mode (which may be different to
77386      ** the locking-mode of the main database).
77387      */
77388      eMode = db->dfltLockMode;
77389    }else{
77390      Pager *pPager;
77391      if( pId2->n==0 ){
77392        /* This indicates that no database name was specified as part
77393        ** of the PRAGMA command. In this case the locking-mode must be
77394        ** set on all attached databases, as well as the main db file.
77395        **
77396        ** Also, the sqlite3.dfltLockMode variable is set so that
77397        ** any subsequently attached databases also use the specified
77398        ** locking mode.
77399        */
77400        int ii;
77401        assert(pDb==&db->aDb[0]);
77402        for(ii=2; ii<db->nDb; ii++){
77403          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
77404          sqlite3PagerLockingMode(pPager, eMode);
77405        }
77406        db->dfltLockMode = (u8)eMode;
77407      }
77408      pPager = sqlite3BtreePager(pDb->pBt);
77409      eMode = sqlite3PagerLockingMode(pPager, eMode);
77410    }
77411
77412    assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
77413    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
77414      zRet = "exclusive";
77415    }
77416    sqlite3VdbeSetNumCols(v, 1);
77417    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
77418    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
77419    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77420  }else
77421
77422  /*
77423  **  PRAGMA [database.]journal_mode
77424  **  PRAGMA [database.]journal_mode = (delete|persist|off|truncate|memory)
77425  */
77426  if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
77427    int eMode;
77428    static char * const azModeName[] = {
77429      "delete", "persist", "off", "truncate", "memory"
77430    };
77431
77432    if( zRight==0 ){
77433      eMode = PAGER_JOURNALMODE_QUERY;
77434    }else{
77435      int n = sqlite3Strlen30(zRight);
77436      eMode = sizeof(azModeName)/sizeof(azModeName[0]) - 1;
77437      while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
77438        eMode--;
77439      }
77440    }
77441    if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
77442      /* Simple "PRAGMA journal_mode;" statement. This is a query for
77443      ** the current default journal mode (which may be different to
77444      ** the journal-mode of the main database).
77445      */
77446      eMode = db->dfltJournalMode;
77447    }else{
77448      Pager *pPager;
77449      if( pId2->n==0 ){
77450        /* This indicates that no database name was specified as part
77451        ** of the PRAGMA command. In this case the journal-mode must be
77452        ** set on all attached databases, as well as the main db file.
77453        **
77454        ** Also, the sqlite3.dfltJournalMode variable is set so that
77455        ** any subsequently attached databases also use the specified
77456        ** journal mode.
77457        */
77458        int ii;
77459        assert(pDb==&db->aDb[0]);
77460        for(ii=1; ii<db->nDb; ii++){
77461          if( db->aDb[ii].pBt ){
77462            pPager = sqlite3BtreePager(db->aDb[ii].pBt);
77463            sqlite3PagerJournalMode(pPager, eMode);
77464          }
77465        }
77466        db->dfltJournalMode = (u8)eMode;
77467      }
77468      pPager = sqlite3BtreePager(pDb->pBt);
77469      eMode = sqlite3PagerJournalMode(pPager, eMode);
77470    }
77471    assert( eMode==PAGER_JOURNALMODE_DELETE
77472              || eMode==PAGER_JOURNALMODE_TRUNCATE
77473              || eMode==PAGER_JOURNALMODE_PERSIST
77474              || eMode==PAGER_JOURNALMODE_OFF
77475              || eMode==PAGER_JOURNALMODE_MEMORY );
77476    sqlite3VdbeSetNumCols(v, 1);
77477    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
77478    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0,
77479           azModeName[eMode], P4_STATIC);
77480    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77481  }else
77482
77483  /*
77484  **  PRAGMA [database.]journal_size_limit
77485  **  PRAGMA [database.]journal_size_limit=N
77486  **
77487  ** Get or set the size limit on rollback journal files.
77488  */
77489  if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
77490    Pager *pPager = sqlite3BtreePager(pDb->pBt);
77491    i64 iLimit = -2;
77492    if( zRight ){
77493      sqlite3Atoi64(zRight, &iLimit);
77494      if( iLimit<-1 ) iLimit = -1;
77495    }
77496    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
77497    returnSingleInt(pParse, "journal_size_limit", iLimit);
77498  }else
77499
77500#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
77501
77502  /*
77503  **  PRAGMA [database.]auto_vacuum
77504  **  PRAGMA [database.]auto_vacuum=N
77505  **
77506  ** Get or set the value of the database 'auto-vacuum' parameter.
77507  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
77508  */
77509#ifndef SQLITE_OMIT_AUTOVACUUM
77510  if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
77511    Btree *pBt = pDb->pBt;
77512    assert( pBt!=0 );
77513    if( sqlite3ReadSchema(pParse) ){
77514      goto pragma_out;
77515    }
77516    if( !zRight ){
77517      int auto_vacuum;
77518      if( ALWAYS(pBt) ){
77519         auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
77520      }else{
77521         auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
77522      }
77523      returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
77524    }else{
77525      int eAuto = getAutoVacuum(zRight);
77526      assert( eAuto>=0 && eAuto<=2 );
77527      db->nextAutovac = (u8)eAuto;
77528      if( ALWAYS(eAuto>=0) ){
77529        /* Call SetAutoVacuum() to set initialize the internal auto and
77530        ** incr-vacuum flags. This is required in case this connection
77531        ** creates the database file. It is important that it is created
77532        ** as an auto-vacuum capable db.
77533        */
77534        int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
77535        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
77536          /* When setting the auto_vacuum mode to either "full" or
77537          ** "incremental", write the value of meta[6] in the database
77538          ** file. Before writing to meta[6], check that meta[3] indicates
77539          ** that this really is an auto-vacuum capable database.
77540          */
77541          static const VdbeOpList setMeta6[] = {
77542            { OP_Transaction,    0,         1,                 0},    /* 0 */
77543            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
77544            { OP_If,             1,         0,                 0},    /* 2 */
77545            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
77546            { OP_Integer,        0,         1,                 0},    /* 4 */
77547            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
77548          };
77549          int iAddr;
77550          iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
77551          sqlite3VdbeChangeP1(v, iAddr, iDb);
77552          sqlite3VdbeChangeP1(v, iAddr+1, iDb);
77553          sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
77554          sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
77555          sqlite3VdbeChangeP1(v, iAddr+5, iDb);
77556          sqlite3VdbeUsesBtree(v, iDb);
77557        }
77558      }
77559    }
77560  }else
77561#endif
77562
77563  /*
77564  **  PRAGMA [database.]incremental_vacuum(N)
77565  **
77566  ** Do N steps of incremental vacuuming on a database.
77567  */
77568#ifndef SQLITE_OMIT_AUTOVACUUM
77569  if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
77570    int iLimit, addr;
77571    if( sqlite3ReadSchema(pParse) ){
77572      goto pragma_out;
77573    }
77574    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
77575      iLimit = 0x7fffffff;
77576    }
77577    sqlite3BeginWriteOperation(pParse, 0, iDb);
77578    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
77579    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
77580    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
77581    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
77582    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
77583    sqlite3VdbeJumpHere(v, addr);
77584  }else
77585#endif
77586
77587#ifndef SQLITE_OMIT_PAGER_PRAGMAS
77588  /*
77589  **  PRAGMA [database.]cache_size
77590  **  PRAGMA [database.]cache_size=N
77591  **
77592  ** The first form reports the current local setting for the
77593  ** page cache size.  The local setting can be different from
77594  ** the persistent cache size value that is stored in the database
77595  ** file itself.  The value returned is the maximum number of
77596  ** pages in the page cache.  The second form sets the local
77597  ** page cache size value.  It does not change the persistent
77598  ** cache size stored on the disk so the cache size will revert
77599  ** to its default value when the database is closed and reopened.
77600  ** N should be a positive integer.
77601  */
77602  if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
77603    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77604    if( !zRight ){
77605      returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
77606    }else{
77607      int size = atoi(zRight);
77608      if( size<0 ) size = -size;
77609      pDb->pSchema->cache_size = size;
77610      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
77611    }
77612  }else
77613
77614  /*
77615  **   PRAGMA temp_store
77616  **   PRAGMA temp_store = "default"|"memory"|"file"
77617  **
77618  ** Return or set the local value of the temp_store flag.  Changing
77619  ** the local value does not make changes to the disk file and the default
77620  ** value will be restored the next time the database is opened.
77621  **
77622  ** Note that it is possible for the library compile-time options to
77623  ** override this setting
77624  */
77625  if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
77626    if( !zRight ){
77627      returnSingleInt(pParse, "temp_store", db->temp_store);
77628    }else{
77629      changeTempStorage(pParse, zRight);
77630    }
77631  }else
77632
77633  /*
77634  **   PRAGMA temp_store_directory
77635  **   PRAGMA temp_store_directory = ""|"directory_name"
77636  **
77637  ** Return or set the local value of the temp_store_directory flag.  Changing
77638  ** the value sets a specific directory to be used for temporary files.
77639  ** Setting to a null string reverts to the default temporary directory search.
77640  ** If temporary directory is changed, then invalidateTempStorage.
77641  **
77642  */
77643  if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
77644    if( !zRight ){
77645      if( sqlite3_temp_directory ){
77646        sqlite3VdbeSetNumCols(v, 1);
77647        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
77648            "temp_store_directory", SQLITE_STATIC);
77649        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
77650        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77651      }
77652    }else{
77653#ifndef SQLITE_OMIT_WSD
77654      if( zRight[0] ){
77655        int rc;
77656        int res;
77657        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
77658        if( rc!=SQLITE_OK || res==0 ){
77659          sqlite3ErrorMsg(pParse, "not a writable directory");
77660          goto pragma_out;
77661        }
77662      }
77663      if( SQLITE_TEMP_STORE==0
77664       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
77665       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
77666      ){
77667        invalidateTempStorage(pParse);
77668      }
77669      sqlite3_free(sqlite3_temp_directory);
77670      if( zRight[0] ){
77671        sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
77672      }else{
77673        sqlite3_temp_directory = 0;
77674      }
77675#endif /* SQLITE_OMIT_WSD */
77676    }
77677  }else
77678
77679#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
77680#  if defined(__APPLE__)
77681#    define SQLITE_ENABLE_LOCKING_STYLE 1
77682#  else
77683#    define SQLITE_ENABLE_LOCKING_STYLE 0
77684#  endif
77685#endif
77686#if SQLITE_ENABLE_LOCKING_STYLE
77687  /*
77688   **   PRAGMA [database.]lock_proxy_file
77689   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
77690   **
77691   ** Return or set the value of the lock_proxy_file flag.  Changing
77692   ** the value sets a specific file to be used for database access locks.
77693   **
77694   */
77695  if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
77696    if( !zRight ){
77697      Pager *pPager = sqlite3BtreePager(pDb->pBt);
77698      char *proxy_file_path = NULL;
77699      sqlite3_file *pFile = sqlite3PagerFile(pPager);
77700      sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE,
77701                           &proxy_file_path);
77702
77703      if( proxy_file_path ){
77704        sqlite3VdbeSetNumCols(v, 1);
77705        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
77706                              "lock_proxy_file", SQLITE_STATIC);
77707        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
77708        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77709      }
77710    }else{
77711      Pager *pPager = sqlite3BtreePager(pDb->pBt);
77712      sqlite3_file *pFile = sqlite3PagerFile(pPager);
77713      int res;
77714      if( zRight[0] ){
77715        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
77716                                     zRight);
77717      } else {
77718        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
77719                                     NULL);
77720      }
77721      if( res!=SQLITE_OK ){
77722        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
77723        goto pragma_out;
77724      }
77725    }
77726  }else
77727#endif /* SQLITE_ENABLE_LOCKING_STYLE */
77728
77729  /*
77730  **   PRAGMA [database.]synchronous
77731  **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
77732  **
77733  ** Return or set the local value of the synchronous flag.  Changing
77734  ** the local value does not make changes to the disk file and the
77735  ** default value will be restored the next time the database is
77736  ** opened.
77737  */
77738  if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
77739    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77740    if( !zRight ){
77741      returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
77742    }else{
77743      if( !db->autoCommit ){
77744        sqlite3ErrorMsg(pParse,
77745            "Safety level may not be changed inside a transaction");
77746      }else{
77747        pDb->safety_level = getSafetyLevel(zRight)+1;
77748      }
77749    }
77750  }else
77751#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
77752
77753#ifndef SQLITE_OMIT_FLAG_PRAGMAS
77754  if( flagPragma(pParse, zLeft, zRight) ){
77755    /* The flagPragma() subroutine also generates any necessary code
77756    ** there is nothing more to do here */
77757  }else
77758#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
77759
77760#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
77761  /*
77762  **   PRAGMA table_info(<table>)
77763  **
77764  ** Return a single row for each column of the named table. The columns of
77765  ** the returned data set are:
77766  **
77767  ** cid:        Column id (numbered from left to right, starting at 0)
77768  ** name:       Column name
77769  ** type:       Column declaration type.
77770  ** notnull:    True if 'NOT NULL' is part of column declaration
77771  ** dflt_value: The default value for the column, if any.
77772  */
77773  if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
77774    Table *pTab;
77775    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77776    pTab = sqlite3FindTable(db, zRight, zDb);
77777    if( pTab ){
77778      int i;
77779      int nHidden = 0;
77780      Column *pCol;
77781      sqlite3VdbeSetNumCols(v, 6);
77782      pParse->nMem = 6;
77783      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
77784      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77785      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
77786      sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
77787      sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
77788      sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
77789      sqlite3ViewGetColumnNames(pParse, pTab);
77790      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
77791        if( IsHiddenColumn(pCol) ){
77792          nHidden++;
77793          continue;
77794        }
77795        sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
77796        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
77797        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
77798           pCol->zType ? pCol->zType : "", 0);
77799        sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
77800        if( pCol->zDflt ){
77801          sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
77802        }else{
77803          sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
77804        }
77805        sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
77806        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
77807      }
77808    }
77809  }else
77810
77811  if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
77812    Index *pIdx;
77813    Table *pTab;
77814    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77815    pIdx = sqlite3FindIndex(db, zRight, zDb);
77816    if( pIdx ){
77817      int i;
77818      pTab = pIdx->pTable;
77819      sqlite3VdbeSetNumCols(v, 3);
77820      pParse->nMem = 3;
77821      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
77822      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
77823      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
77824      for(i=0; i<pIdx->nColumn; i++){
77825        int cnum = pIdx->aiColumn[i];
77826        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77827        sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
77828        assert( pTab->nCol>cnum );
77829        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
77830        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
77831      }
77832    }
77833  }else
77834
77835  if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
77836    Index *pIdx;
77837    Table *pTab;
77838    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77839    pTab = sqlite3FindTable(db, zRight, zDb);
77840    if( pTab ){
77841      v = sqlite3GetVdbe(pParse);
77842      pIdx = pTab->pIndex;
77843      if( pIdx ){
77844        int i = 0;
77845        sqlite3VdbeSetNumCols(v, 3);
77846        pParse->nMem = 3;
77847        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
77848        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77849        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
77850        while(pIdx){
77851          sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77852          sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
77853          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
77854          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
77855          ++i;
77856          pIdx = pIdx->pNext;
77857        }
77858      }
77859    }
77860  }else
77861
77862  if( sqlite3StrICmp(zLeft, "database_list")==0 ){
77863    int i;
77864    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77865    sqlite3VdbeSetNumCols(v, 3);
77866    pParse->nMem = 3;
77867    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
77868    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77869    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
77870    for(i=0; i<db->nDb; i++){
77871      if( db->aDb[i].pBt==0 ) continue;
77872      assert( db->aDb[i].zName!=0 );
77873      sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77874      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
77875      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
77876           sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
77877      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
77878    }
77879  }else
77880
77881  if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
77882    int i = 0;
77883    HashElem *p;
77884    sqlite3VdbeSetNumCols(v, 2);
77885    pParse->nMem = 2;
77886    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
77887    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77888    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
77889      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
77890      sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
77891      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
77892      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
77893    }
77894  }else
77895#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
77896
77897#ifndef SQLITE_OMIT_FOREIGN_KEY
77898  if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
77899    FKey *pFK;
77900    Table *pTab;
77901    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77902    pTab = sqlite3FindTable(db, zRight, zDb);
77903    if( pTab ){
77904      v = sqlite3GetVdbe(pParse);
77905      pFK = pTab->pFKey;
77906      if( pFK ){
77907        int i = 0;
77908        sqlite3VdbeSetNumCols(v, 8);
77909        pParse->nMem = 8;
77910        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
77911        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
77912        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
77913        sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
77914        sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
77915        sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
77916        sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
77917        sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
77918        while(pFK){
77919          int j;
77920          for(j=0; j<pFK->nCol; j++){
77921            char *zCol = pFK->aCol[j].zCol;
77922            char *zOnDelete = (char *)actionName(pFK->aAction[0]);
77923            char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
77924            sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77925            sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
77926            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
77927            sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
77928                              pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
77929            sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
77930            sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
77931            sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
77932            sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
77933            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
77934          }
77935          ++i;
77936          pFK = pFK->pNextFrom;
77937        }
77938      }
77939    }
77940  }else
77941#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
77942
77943#ifndef NDEBUG
77944  if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
77945    if( zRight ){
77946      if( getBoolean(zRight) ){
77947        sqlite3ParserTrace(stderr, "parser: ");
77948      }else{
77949        sqlite3ParserTrace(0, 0);
77950      }
77951    }
77952  }else
77953#endif
77954
77955  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
77956  ** used will be case sensitive or not depending on the RHS.
77957  */
77958  if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
77959    if( zRight ){
77960      sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
77961    }
77962  }else
77963
77964#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
77965# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
77966#endif
77967
77968#ifndef SQLITE_OMIT_INTEGRITY_CHECK
77969  /* Pragma "quick_check" is an experimental reduced version of
77970  ** integrity_check designed to detect most database corruption
77971  ** without most of the overhead of a full integrity-check.
77972  */
77973  if( sqlite3StrICmp(zLeft, "integrity_check")==0
77974   || sqlite3StrICmp(zLeft, "quick_check")==0
77975  ){
77976    int i, j, addr, mxErr;
77977
77978    /* Code that appears at the end of the integrity check.  If no error
77979    ** messages have been generated, output OK.  Otherwise output the
77980    ** error message
77981    */
77982    static const VdbeOpList endCode[] = {
77983      { OP_AddImm,      1, 0,        0},    /* 0 */
77984      { OP_IfNeg,       1, 0,        0},    /* 1 */
77985      { OP_String8,     0, 3,        0},    /* 2 */
77986      { OP_ResultRow,   3, 1,        0},
77987    };
77988
77989    int isQuick = (zLeft[0]=='q');
77990
77991    /* Initialize the VDBE program */
77992    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77993    pParse->nMem = 6;
77994    sqlite3VdbeSetNumCols(v, 1);
77995    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
77996
77997    /* Set the maximum error count */
77998    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
77999    if( zRight ){
78000      mxErr = atoi(zRight);
78001      if( mxErr<=0 ){
78002        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
78003      }
78004    }
78005    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
78006
78007    /* Do an integrity check on each database file */
78008    for(i=0; i<db->nDb; i++){
78009      HashElem *x;
78010      Hash *pTbls;
78011      int cnt = 0;
78012
78013      if( OMIT_TEMPDB && i==1 ) continue;
78014
78015      sqlite3CodeVerifySchema(pParse, i);
78016      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
78017      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
78018      sqlite3VdbeJumpHere(v, addr);
78019
78020      /* Do an integrity check of the B-Tree
78021      **
78022      ** Begin by filling registers 2, 3, ... with the root pages numbers
78023      ** for all tables and indices in the database.
78024      */
78025      pTbls = &db->aDb[i].pSchema->tblHash;
78026      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
78027        Table *pTab = sqliteHashData(x);
78028        Index *pIdx;
78029        sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
78030        cnt++;
78031        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
78032          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
78033          cnt++;
78034        }
78035      }
78036
78037      /* Make sure sufficient number of registers have been allocated */
78038      if( pParse->nMem < cnt+4 ){
78039        pParse->nMem = cnt+4;
78040      }
78041
78042      /* Do the b-tree integrity checks */
78043      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
78044      sqlite3VdbeChangeP5(v, (u8)i);
78045      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
78046      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
78047         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
78048         P4_DYNAMIC);
78049      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
78050      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
78051      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
78052      sqlite3VdbeJumpHere(v, addr);
78053
78054      /* Make sure all the indices are constructed correctly.
78055      */
78056      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
78057        Table *pTab = sqliteHashData(x);
78058        Index *pIdx;
78059        int loopTop;
78060
78061        if( pTab->pIndex==0 ) continue;
78062        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
78063        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
78064        sqlite3VdbeJumpHere(v, addr);
78065        sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
78066        sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
78067        loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
78068        sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
78069        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
78070          int jmp2;
78071          int r1;
78072          static const VdbeOpList idxErr[] = {
78073            { OP_AddImm,      1, -1,  0},
78074            { OP_String8,     0,  3,  0},    /* 1 */
78075            { OP_Rowid,       1,  4,  0},
78076            { OP_String8,     0,  5,  0},    /* 3 */
78077            { OP_String8,     0,  6,  0},    /* 4 */
78078            { OP_Concat,      4,  3,  3},
78079            { OP_Concat,      5,  3,  3},
78080            { OP_Concat,      6,  3,  3},
78081            { OP_ResultRow,   3,  1,  0},
78082            { OP_IfPos,       1,  0,  0},    /* 9 */
78083            { OP_Halt,        0,  0,  0},
78084          };
78085          r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
78086          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
78087          addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
78088          sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
78089          sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
78090          sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
78091          sqlite3VdbeJumpHere(v, addr+9);
78092          sqlite3VdbeJumpHere(v, jmp2);
78093        }
78094        sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
78095        sqlite3VdbeJumpHere(v, loopTop);
78096        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
78097          static const VdbeOpList cntIdx[] = {
78098             { OP_Integer,      0,  3,  0},
78099             { OP_Rewind,       0,  0,  0},  /* 1 */
78100             { OP_AddImm,       3,  1,  0},
78101             { OP_Next,         0,  0,  0},  /* 3 */
78102             { OP_Eq,           2,  0,  3},  /* 4 */
78103             { OP_AddImm,       1, -1,  0},
78104             { OP_String8,      0,  2,  0},  /* 6 */
78105             { OP_String8,      0,  3,  0},  /* 7 */
78106             { OP_Concat,       3,  2,  2},
78107             { OP_ResultRow,    2,  1,  0},
78108          };
78109          addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
78110          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
78111          sqlite3VdbeJumpHere(v, addr);
78112          addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
78113          sqlite3VdbeChangeP1(v, addr+1, j+2);
78114          sqlite3VdbeChangeP2(v, addr+1, addr+4);
78115          sqlite3VdbeChangeP1(v, addr+3, j+2);
78116          sqlite3VdbeChangeP2(v, addr+3, addr+2);
78117          sqlite3VdbeJumpHere(v, addr+4);
78118          sqlite3VdbeChangeP4(v, addr+6,
78119                     "wrong # of entries in index ", P4_STATIC);
78120          sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
78121        }
78122      }
78123    }
78124    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
78125    sqlite3VdbeChangeP2(v, addr, -mxErr);
78126    sqlite3VdbeJumpHere(v, addr+1);
78127    sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
78128  }else
78129#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
78130
78131#ifndef SQLITE_OMIT_UTF16
78132  /*
78133  **   PRAGMA encoding
78134  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
78135  **
78136  ** In its first form, this pragma returns the encoding of the main
78137  ** database. If the database is not initialized, it is initialized now.
78138  **
78139  ** The second form of this pragma is a no-op if the main database file
78140  ** has not already been initialized. In this case it sets the default
78141  ** encoding that will be used for the main database file if a new file
78142  ** is created. If an existing main database file is opened, then the
78143  ** default text encoding for the existing database is used.
78144  **
78145  ** In all cases new databases created using the ATTACH command are
78146  ** created to use the same default text encoding as the main database. If
78147  ** the main database has not been initialized and/or created when ATTACH
78148  ** is executed, this is done before the ATTACH operation.
78149  **
78150  ** In the second form this pragma sets the text encoding to be used in
78151  ** new database files created using this database handle. It is only
78152  ** useful if invoked immediately after the main database i
78153  */
78154  if( sqlite3StrICmp(zLeft, "encoding")==0 ){
78155    static const struct EncName {
78156      char *zName;
78157      u8 enc;
78158    } encnames[] = {
78159      { "UTF8",     SQLITE_UTF8        },
78160      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
78161      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
78162      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
78163      { "UTF16le",  SQLITE_UTF16LE     },
78164      { "UTF16be",  SQLITE_UTF16BE     },
78165      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
78166      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
78167      { 0, 0 }
78168    };
78169    const struct EncName *pEnc;
78170    if( !zRight ){    /* "PRAGMA encoding" */
78171      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
78172      sqlite3VdbeSetNumCols(v, 1);
78173      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
78174      sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
78175      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
78176      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
78177      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
78178      sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
78179      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
78180    }else{                        /* "PRAGMA encoding = XXX" */
78181      /* Only change the value of sqlite.enc if the database handle is not
78182      ** initialized. If the main database exists, the new sqlite.enc value
78183      ** will be overwritten when the schema is next loaded. If it does not
78184      ** already exists, it will be created to use the new encoding value.
78185      */
78186      if(
78187        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
78188        DbHasProperty(db, 0, DB_Empty)
78189      ){
78190        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
78191          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
78192            ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
78193            break;
78194          }
78195        }
78196        if( !pEnc->zName ){
78197          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
78198        }
78199      }
78200    }
78201  }else
78202#endif /* SQLITE_OMIT_UTF16 */
78203
78204#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
78205  /*
78206  **   PRAGMA [database.]schema_version
78207  **   PRAGMA [database.]schema_version = <integer>
78208  **
78209  **   PRAGMA [database.]user_version
78210  **   PRAGMA [database.]user_version = <integer>
78211  **
78212  ** The pragma's schema_version and user_version are used to set or get
78213  ** the value of the schema-version and user-version, respectively. Both
78214  ** the schema-version and the user-version are 32-bit signed integers
78215  ** stored in the database header.
78216  **
78217  ** The schema-cookie is usually only manipulated internally by SQLite. It
78218  ** is incremented by SQLite whenever the database schema is modified (by
78219  ** creating or dropping a table or index). The schema version is used by
78220  ** SQLite each time a query is executed to ensure that the internal cache
78221  ** of the schema used when compiling the SQL query matches the schema of
78222  ** the database against which the compiled query is actually executed.
78223  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
78224  ** the schema-version is potentially dangerous and may lead to program
78225  ** crashes or database corruption. Use with caution!
78226  **
78227  ** The user-version is not used internally by SQLite. It may be used by
78228  ** applications for any purpose.
78229  */
78230  if( sqlite3StrICmp(zLeft, "schema_version")==0
78231   || sqlite3StrICmp(zLeft, "user_version")==0
78232   || sqlite3StrICmp(zLeft, "freelist_count")==0
78233  ){
78234    int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
78235    sqlite3VdbeUsesBtree(v, iDb);
78236    switch( zLeft[0] ){
78237      case 'f': case 'F':
78238        iCookie = BTREE_FREE_PAGE_COUNT;
78239        break;
78240      case 's': case 'S':
78241        iCookie = BTREE_SCHEMA_VERSION;
78242        break;
78243      default:
78244        iCookie = BTREE_USER_VERSION;
78245        break;
78246    }
78247
78248    if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
78249      /* Write the specified cookie value */
78250      static const VdbeOpList setCookie[] = {
78251        { OP_Transaction,    0,  1,  0},    /* 0 */
78252        { OP_Integer,        0,  1,  0},    /* 1 */
78253        { OP_SetCookie,      0,  0,  1},    /* 2 */
78254      };
78255      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
78256      sqlite3VdbeChangeP1(v, addr, iDb);
78257      sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
78258      sqlite3VdbeChangeP1(v, addr+2, iDb);
78259      sqlite3VdbeChangeP2(v, addr+2, iCookie);
78260    }else{
78261      /* Read the specified cookie value */
78262      static const VdbeOpList readCookie[] = {
78263        { OP_Transaction,     0,  0,  0},    /* 0 */
78264        { OP_ReadCookie,      0,  1,  0},    /* 1 */
78265        { OP_ResultRow,       1,  1,  0}
78266      };
78267      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
78268      sqlite3VdbeChangeP1(v, addr, iDb);
78269      sqlite3VdbeChangeP1(v, addr+1, iDb);
78270      sqlite3VdbeChangeP3(v, addr+1, iCookie);
78271      sqlite3VdbeSetNumCols(v, 1);
78272      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
78273    }
78274  }else
78275#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
78276
78277#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
78278  /*
78279  ** Report the current state of file logs for all databases
78280  */
78281  if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
78282    static const char *const azLockName[] = {
78283      "unlocked", "shared", "reserved", "pending", "exclusive"
78284    };
78285    int i;
78286    sqlite3VdbeSetNumCols(v, 2);
78287    pParse->nMem = 2;
78288    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
78289    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
78290    for(i=0; i<db->nDb; i++){
78291      Btree *pBt;
78292      Pager *pPager;
78293      const char *zState = "unknown";
78294      int j;
78295      if( db->aDb[i].zName==0 ) continue;
78296      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
78297      pBt = db->aDb[i].pBt;
78298      if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
78299        zState = "closed";
78300      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
78301                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
78302         zState = azLockName[j];
78303      }
78304      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
78305      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
78306    }
78307
78308  }else
78309#endif
78310
78311#if SQLITE_HAS_CODEC
78312  if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
78313    sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
78314  }else
78315  if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
78316    sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
78317  }else
78318  if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
78319                 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
78320    int i, h1, h2;
78321    char zKey[40];
78322    for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
78323      h1 += 9*(1&(h1>>6));
78324      h2 += 9*(1&(h2>>6));
78325      zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
78326    }
78327    if( (zLeft[3] & 0xf)==0xb ){
78328      sqlite3_key(db, zKey, i/2);
78329    }else{
78330      sqlite3_rekey(db, zKey, i/2);
78331    }
78332  }else
78333#endif
78334#if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
78335  if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
78336#if SQLITE_HAS_CODEC
78337    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
78338      extern void sqlite3_activate_see(const char*);
78339      sqlite3_activate_see(&zRight[4]);
78340    }
78341#endif
78342#ifdef SQLITE_ENABLE_CEROD
78343    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
78344      extern void sqlite3_activate_cerod(const char*);
78345      sqlite3_activate_cerod(&zRight[6]);
78346    }
78347#endif
78348  }else
78349#endif
78350
78351
78352  {/* Empty ELSE clause */}
78353
78354  /*
78355  ** Reset the safety level, in case the fullfsync flag or synchronous
78356  ** setting changed.
78357  */
78358#ifndef SQLITE_OMIT_PAGER_PRAGMAS
78359  if( db->autoCommit ){
78360    sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
78361               (db->flags&SQLITE_FullFSync)!=0);
78362  }
78363#endif
78364pragma_out:
78365  sqlite3DbFree(db, zLeft);
78366  sqlite3DbFree(db, zRight);
78367}
78368
78369#endif /* SQLITE_OMIT_PRAGMA */
78370
78371/************** End of pragma.c **********************************************/
78372/************** Begin file prepare.c *****************************************/
78373/*
78374** 2005 May 25
78375**
78376** The author disclaims copyright to this source code.  In place of
78377** a legal notice, here is a blessing:
78378**
78379**    May you do good and not evil.
78380**    May you find forgiveness for yourself and forgive others.
78381**    May you share freely, never taking more than you give.
78382**
78383*************************************************************************
78384** This file contains the implementation of the sqlite3_prepare()
78385** interface, and routines that contribute to loading the database schema
78386** from disk.
78387*/
78388
78389/*
78390** Fill the InitData structure with an error message that indicates
78391** that the database is corrupt.
78392*/
78393static void corruptSchema(
78394  InitData *pData,     /* Initialization context */
78395  const char *zObj,    /* Object being parsed at the point of error */
78396  const char *zExtra   /* Error information */
78397){
78398  sqlite3 *db = pData->db;
78399  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
78400    if( zObj==0 ) zObj = "?";
78401    sqlite3SetString(pData->pzErrMsg, db,
78402      "malformed database schema (%s)", zObj);
78403    if( zExtra ){
78404      *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
78405                                 "%s - %s", *pData->pzErrMsg, zExtra);
78406    }
78407  }
78408  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT;
78409}
78410
78411/*
78412** This is the callback routine for the code that initializes the
78413** database.  See sqlite3Init() below for additional information.
78414** This routine is also called from the OP_ParseSchema opcode of the VDBE.
78415**
78416** Each callback contains the following information:
78417**
78418**     argv[0] = name of thing being created
78419**     argv[1] = root page number for table or index. 0 for trigger or view.
78420**     argv[2] = SQL text for the CREATE statement.
78421**
78422*/
78423SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
78424  InitData *pData = (InitData*)pInit;
78425  sqlite3 *db = pData->db;
78426  int iDb = pData->iDb;
78427
78428  assert( argc==3 );
78429  UNUSED_PARAMETER2(NotUsed, argc);
78430  assert( sqlite3_mutex_held(db->mutex) );
78431  DbClearProperty(db, iDb, DB_Empty);
78432  if( db->mallocFailed ){
78433    corruptSchema(pData, argv[0], 0);
78434    return 1;
78435  }
78436
78437  assert( iDb>=0 && iDb<db->nDb );
78438  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
78439  if( argv[1]==0 ){
78440    corruptSchema(pData, argv[0], 0);
78441  }else if( argv[2] && argv[2][0] ){
78442    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
78443    ** But because db->init.busy is set to 1, no VDBE code is generated
78444    ** or executed.  All the parser does is build the internal data
78445    ** structures that describe the table, index, or view.
78446    */
78447    char *zErr;
78448    int rc;
78449    assert( db->init.busy );
78450    db->init.iDb = iDb;
78451    db->init.newTnum = atoi(argv[1]);
78452    db->init.orphanTrigger = 0;
78453    rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
78454    db->init.iDb = 0;
78455    assert( rc!=SQLITE_OK || zErr==0 );
78456    if( SQLITE_OK!=rc ){
78457      if( db->init.orphanTrigger ){
78458        assert( iDb==1 );
78459      }else{
78460        pData->rc = rc;
78461        if( rc==SQLITE_NOMEM ){
78462          db->mallocFailed = 1;
78463        }else if( rc!=SQLITE_INTERRUPT && rc!=SQLITE_LOCKED ){
78464          corruptSchema(pData, argv[0], zErr);
78465        }
78466      }
78467      sqlite3DbFree(db, zErr);
78468    }
78469  }else if( argv[0]==0 ){
78470    corruptSchema(pData, 0, 0);
78471  }else{
78472    /* If the SQL column is blank it means this is an index that
78473    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
78474    ** constraint for a CREATE TABLE.  The index should have already
78475    ** been created when we processed the CREATE TABLE.  All we have
78476    ** to do here is record the root page number for that index.
78477    */
78478    Index *pIndex;
78479    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
78480    if( pIndex==0 ){
78481      /* This can occur if there exists an index on a TEMP table which
78482      ** has the same name as another index on a permanent index.  Since
78483      ** the permanent table is hidden by the TEMP table, we can also
78484      ** safely ignore the index on the permanent table.
78485      */
78486      /* Do Nothing */;
78487    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
78488      corruptSchema(pData, argv[0], "invalid rootpage");
78489    }
78490  }
78491  return 0;
78492}
78493
78494/*
78495** Attempt to read the database schema and initialize internal
78496** data structures for a single database file.  The index of the
78497** database file is given by iDb.  iDb==0 is used for the main
78498** database.  iDb==1 should never be used.  iDb>=2 is used for
78499** auxiliary databases.  Return one of the SQLITE_ error codes to
78500** indicate success or failure.
78501*/
78502static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
78503  int rc;
78504  int i;
78505  int size;
78506  Table *pTab;
78507  Db *pDb;
78508  char const *azArg[4];
78509  int meta[5];
78510  InitData initData;
78511  char const *zMasterSchema;
78512  char const *zMasterName = SCHEMA_TABLE(iDb);
78513  int openedTransaction = 0;
78514
78515  /*
78516  ** The master database table has a structure like this
78517  */
78518  static const char master_schema[] =
78519     "CREATE TABLE sqlite_master(\n"
78520     "  type text,\n"
78521     "  name text,\n"
78522     "  tbl_name text,\n"
78523     "  rootpage integer,\n"
78524     "  sql text\n"
78525     ")"
78526  ;
78527#ifndef SQLITE_OMIT_TEMPDB
78528  static const char temp_master_schema[] =
78529     "CREATE TEMP TABLE sqlite_temp_master(\n"
78530     "  type text,\n"
78531     "  name text,\n"
78532     "  tbl_name text,\n"
78533     "  rootpage integer,\n"
78534     "  sql text\n"
78535     ")"
78536  ;
78537#else
78538  #define temp_master_schema 0
78539#endif
78540
78541  assert( iDb>=0 && iDb<db->nDb );
78542  assert( db->aDb[iDb].pSchema );
78543  assert( sqlite3_mutex_held(db->mutex) );
78544  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
78545
78546  /* zMasterSchema and zInitScript are set to point at the master schema
78547  ** and initialisation script appropriate for the database being
78548  ** initialised. zMasterName is the name of the master table.
78549  */
78550  if( !OMIT_TEMPDB && iDb==1 ){
78551    zMasterSchema = temp_master_schema;
78552  }else{
78553    zMasterSchema = master_schema;
78554  }
78555  zMasterName = SCHEMA_TABLE(iDb);
78556
78557  /* Construct the schema tables.  */
78558  azArg[0] = zMasterName;
78559  azArg[1] = "1";
78560  azArg[2] = zMasterSchema;
78561  azArg[3] = 0;
78562  initData.db = db;
78563  initData.iDb = iDb;
78564  initData.rc = SQLITE_OK;
78565  initData.pzErrMsg = pzErrMsg;
78566  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
78567  if( initData.rc ){
78568    rc = initData.rc;
78569    goto error_out;
78570  }
78571  pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
78572  if( ALWAYS(pTab) ){
78573    pTab->tabFlags |= TF_Readonly;
78574  }
78575
78576  /* Create a cursor to hold the database open
78577  */
78578  pDb = &db->aDb[iDb];
78579  if( pDb->pBt==0 ){
78580    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
78581      DbSetProperty(db, 1, DB_SchemaLoaded);
78582    }
78583    return SQLITE_OK;
78584  }
78585
78586  /* If there is not already a read-only (or read-write) transaction opened
78587  ** on the b-tree database, open one now. If a transaction is opened, it
78588  ** will be closed before this function returns.  */
78589  sqlite3BtreeEnter(pDb->pBt);
78590  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
78591    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
78592    if( rc!=SQLITE_OK ){
78593      sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
78594      goto initone_error_out;
78595    }
78596    openedTransaction = 1;
78597  }
78598
78599  /* Get the database meta information.
78600  **
78601  ** Meta values are as follows:
78602  **    meta[0]   Schema cookie.  Changes with each schema change.
78603  **    meta[1]   File format of schema layer.
78604  **    meta[2]   Size of the page cache.
78605  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
78606  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
78607  **    meta[5]   User version
78608  **    meta[6]   Incremental vacuum mode
78609  **    meta[7]   unused
78610  **    meta[8]   unused
78611  **    meta[9]   unused
78612  **
78613  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
78614  ** the possible values of meta[4].
78615  */
78616  for(i=0; i<ArraySize(meta); i++){
78617    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
78618  }
78619  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
78620
78621  /* If opening a non-empty database, check the text encoding. For the
78622  ** main database, set sqlite3.enc to the encoding of the main database.
78623  ** For an attached db, it is an error if the encoding is not the same
78624  ** as sqlite3.enc.
78625  */
78626  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
78627    if( iDb==0 ){
78628      u8 encoding;
78629      /* If opening the main database, set ENC(db). */
78630      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
78631      if( encoding==0 ) encoding = SQLITE_UTF8;
78632      ENC(db) = encoding;
78633      db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
78634    }else{
78635      /* If opening an attached database, the encoding much match ENC(db) */
78636      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
78637        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
78638            " text encoding as main database");
78639        rc = SQLITE_ERROR;
78640        goto initone_error_out;
78641      }
78642    }
78643  }else{
78644    DbSetProperty(db, iDb, DB_Empty);
78645  }
78646  pDb->pSchema->enc = ENC(db);
78647
78648  if( pDb->pSchema->cache_size==0 ){
78649    size = meta[BTREE_DEFAULT_CACHE_SIZE-1];
78650    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
78651    if( size<0 ) size = -size;
78652    pDb->pSchema->cache_size = size;
78653    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
78654  }
78655
78656  /*
78657  ** file_format==1    Version 3.0.0.
78658  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
78659  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
78660  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
78661  */
78662  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
78663  if( pDb->pSchema->file_format==0 ){
78664    pDb->pSchema->file_format = 1;
78665  }
78666  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
78667    sqlite3SetString(pzErrMsg, db, "unsupported file format");
78668    rc = SQLITE_ERROR;
78669    goto initone_error_out;
78670  }
78671
78672  /* Ticket #2804:  When we open a database in the newer file format,
78673  ** clear the legacy_file_format pragma flag so that a VACUUM will
78674  ** not downgrade the database and thus invalidate any descending
78675  ** indices that the user might have created.
78676  */
78677  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
78678    db->flags &= ~SQLITE_LegacyFileFmt;
78679  }
78680
78681  /* Read the schema information out of the schema tables
78682  */
78683  assert( db->init.busy );
78684  {
78685    char *zSql;
78686    zSql = sqlite3MPrintf(db,
78687        "SELECT name, rootpage, sql FROM '%q'.%s",
78688        db->aDb[iDb].zName, zMasterName);
78689#ifndef SQLITE_OMIT_AUTHORIZATION
78690    {
78691      int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
78692      xAuth = db->xAuth;
78693      db->xAuth = 0;
78694#endif
78695      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
78696#ifndef SQLITE_OMIT_AUTHORIZATION
78697      db->xAuth = xAuth;
78698    }
78699#endif
78700    if( rc==SQLITE_OK ) rc = initData.rc;
78701    sqlite3DbFree(db, zSql);
78702#ifndef SQLITE_OMIT_ANALYZE
78703    if( rc==SQLITE_OK ){
78704      sqlite3AnalysisLoad(db, iDb);
78705    }
78706#endif
78707  }
78708  if( db->mallocFailed ){
78709    rc = SQLITE_NOMEM;
78710    sqlite3ResetInternalSchema(db, 0);
78711  }
78712  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
78713    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
78714    ** the schema loaded, even if errors occurred. In this situation the
78715    ** current sqlite3_prepare() operation will fail, but the following one
78716    ** will attempt to compile the supplied statement against whatever subset
78717    ** of the schema was loaded before the error occurred. The primary
78718    ** purpose of this is to allow access to the sqlite_master table
78719    ** even when its contents have been corrupted.
78720    */
78721    DbSetProperty(db, iDb, DB_SchemaLoaded);
78722    rc = SQLITE_OK;
78723  }
78724
78725  /* Jump here for an error that occurs after successfully allocating
78726  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
78727  ** before that point, jump to error_out.
78728  */
78729initone_error_out:
78730  if( openedTransaction ){
78731    sqlite3BtreeCommit(pDb->pBt);
78732  }
78733  sqlite3BtreeLeave(pDb->pBt);
78734
78735error_out:
78736  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
78737    db->mallocFailed = 1;
78738  }
78739  return rc;
78740}
78741
78742/*
78743** Initialize all database files - the main database file, the file
78744** used to store temporary tables, and any additional database files
78745** created using ATTACH statements.  Return a success code.  If an
78746** error occurs, write an error message into *pzErrMsg.
78747**
78748** After a database is initialized, the DB_SchemaLoaded bit is set
78749** bit is set in the flags field of the Db structure. If the database
78750** file was of zero-length, then the DB_Empty flag is also set.
78751*/
78752SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
78753  int i, rc;
78754  int commit_internal = !(db->flags&SQLITE_InternChanges);
78755
78756  assert( sqlite3_mutex_held(db->mutex) );
78757  rc = SQLITE_OK;
78758  db->init.busy = 1;
78759  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
78760    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
78761    rc = sqlite3InitOne(db, i, pzErrMsg);
78762    if( rc ){
78763      sqlite3ResetInternalSchema(db, i);
78764    }
78765  }
78766
78767  /* Once all the other databases have been initialised, load the schema
78768  ** for the TEMP database. This is loaded last, as the TEMP database
78769  ** schema may contain references to objects in other databases.
78770  */
78771#ifndef SQLITE_OMIT_TEMPDB
78772  if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
78773                    && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
78774    rc = sqlite3InitOne(db, 1, pzErrMsg);
78775    if( rc ){
78776      sqlite3ResetInternalSchema(db, 1);
78777    }
78778  }
78779#endif
78780
78781  db->init.busy = 0;
78782  if( rc==SQLITE_OK && commit_internal ){
78783    sqlite3CommitInternalChanges(db);
78784  }
78785
78786  return rc;
78787}
78788
78789/*
78790** This routine is a no-op if the database schema is already initialised.
78791** Otherwise, the schema is loaded. An error code is returned.
78792*/
78793SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
78794  int rc = SQLITE_OK;
78795  sqlite3 *db = pParse->db;
78796  assert( sqlite3_mutex_held(db->mutex) );
78797  if( !db->init.busy ){
78798    rc = sqlite3Init(db, &pParse->zErrMsg);
78799  }
78800  if( rc!=SQLITE_OK ){
78801    pParse->rc = rc;
78802    pParse->nErr++;
78803  }
78804  return rc;
78805}
78806
78807
78808/*
78809** Check schema cookies in all databases.  If any cookie is out
78810** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
78811** make no changes to pParse->rc.
78812*/
78813static void schemaIsValid(Parse *pParse){
78814  sqlite3 *db = pParse->db;
78815  int iDb;
78816  int rc;
78817  int cookie;
78818
78819  assert( pParse->checkSchema );
78820  assert( sqlite3_mutex_held(db->mutex) );
78821  for(iDb=0; iDb<db->nDb; iDb++){
78822    int openedTransaction = 0;         /* True if a transaction is opened */
78823    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
78824    if( pBt==0 ) continue;
78825
78826    /* If there is not already a read-only (or read-write) transaction opened
78827    ** on the b-tree database, open one now. If a transaction is opened, it
78828    ** will be closed immediately after reading the meta-value. */
78829    if( !sqlite3BtreeIsInReadTrans(pBt) ){
78830      rc = sqlite3BtreeBeginTrans(pBt, 0);
78831      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
78832        db->mallocFailed = 1;
78833      }
78834      if( rc!=SQLITE_OK ) return;
78835      openedTransaction = 1;
78836    }
78837
78838    /* Read the schema cookie from the database. If it does not match the
78839    ** value stored as part of the in-memory schema representation,
78840    ** set Parse.rc to SQLITE_SCHEMA. */
78841    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
78842    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
78843      pParse->rc = SQLITE_SCHEMA;
78844    }
78845
78846    /* Close the transaction, if one was opened. */
78847    if( openedTransaction ){
78848      sqlite3BtreeCommit(pBt);
78849    }
78850  }
78851}
78852
78853/*
78854** Convert a schema pointer into the iDb index that indicates
78855** which database file in db->aDb[] the schema refers to.
78856**
78857** If the same database is attached more than once, the first
78858** attached database is returned.
78859*/
78860SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
78861  int i = -1000000;
78862
78863  /* If pSchema is NULL, then return -1000000. This happens when code in
78864  ** expr.c is trying to resolve a reference to a transient table (i.e. one
78865  ** created by a sub-select). In this case the return value of this
78866  ** function should never be used.
78867  **
78868  ** We return -1000000 instead of the more usual -1 simply because using
78869  ** -1000000 as the incorrect index into db->aDb[] is much
78870  ** more likely to cause a segfault than -1 (of course there are assert()
78871  ** statements too, but it never hurts to play the odds).
78872  */
78873  assert( sqlite3_mutex_held(db->mutex) );
78874  if( pSchema ){
78875    for(i=0; ALWAYS(i<db->nDb); i++){
78876      if( db->aDb[i].pSchema==pSchema ){
78877        break;
78878      }
78879    }
78880    assert( i>=0 && i<db->nDb );
78881  }
78882  return i;
78883}
78884
78885/*
78886** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
78887*/
78888static int sqlite3Prepare(
78889  sqlite3 *db,              /* Database handle. */
78890  const char *zSql,         /* UTF-8 encoded SQL statement. */
78891  int nBytes,               /* Length of zSql in bytes. */
78892  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
78893  Vdbe *pReprepare,         /* VM being reprepared */
78894  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78895  const char **pzTail       /* OUT: End of parsed string */
78896){
78897  Parse *pParse;            /* Parsing context */
78898  char *zErrMsg = 0;        /* Error message */
78899  int rc = SQLITE_OK;       /* Result code */
78900  int i;                    /* Loop counter */
78901
78902  /* Allocate the parsing context */
78903  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
78904  if( pParse==0 ){
78905    rc = SQLITE_NOMEM;
78906    goto end_prepare;
78907  }
78908  pParse->pReprepare = pReprepare;
78909  assert( ppStmt && *ppStmt==0 );
78910  assert( !db->mallocFailed );
78911  assert( sqlite3_mutex_held(db->mutex) );
78912
78913  /* Check to verify that it is possible to get a read lock on all
78914  ** database schemas.  The inability to get a read lock indicates that
78915  ** some other database connection is holding a write-lock, which in
78916  ** turn means that the other connection has made uncommitted changes
78917  ** to the schema.
78918  **
78919  ** Were we to proceed and prepare the statement against the uncommitted
78920  ** schema changes and if those schema changes are subsequently rolled
78921  ** back and different changes are made in their place, then when this
78922  ** prepared statement goes to run the schema cookie would fail to detect
78923  ** the schema change.  Disaster would follow.
78924  **
78925  ** This thread is currently holding mutexes on all Btrees (because
78926  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
78927  ** is not possible for another thread to start a new schema change
78928  ** while this routine is running.  Hence, we do not need to hold
78929  ** locks on the schema, we just need to make sure nobody else is
78930  ** holding them.
78931  **
78932  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
78933  ** but it does *not* override schema lock detection, so this all still
78934  ** works even if READ_UNCOMMITTED is set.
78935  */
78936  for(i=0; i<db->nDb; i++) {
78937    Btree *pBt = db->aDb[i].pBt;
78938    if( pBt ){
78939      assert( sqlite3BtreeHoldsMutex(pBt) );
78940      rc = sqlite3BtreeSchemaLocked(pBt);
78941      if( rc ){
78942        const char *zDb = db->aDb[i].zName;
78943        sqlite3Error(db, rc, "database schema is locked: %s", zDb);
78944        testcase( db->flags & SQLITE_ReadUncommitted );
78945        goto end_prepare;
78946      }
78947    }
78948  }
78949
78950  sqlite3VtabUnlockList(db);
78951
78952  pParse->db = db;
78953  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
78954    char *zSqlCopy;
78955    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
78956    testcase( nBytes==mxLen );
78957    testcase( nBytes==mxLen+1 );
78958    if( nBytes>mxLen ){
78959      sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
78960      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
78961      goto end_prepare;
78962    }
78963    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
78964    if( zSqlCopy ){
78965      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
78966      sqlite3DbFree(db, zSqlCopy);
78967      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
78968    }else{
78969      pParse->zTail = &zSql[nBytes];
78970    }
78971  }else{
78972    sqlite3RunParser(pParse, zSql, &zErrMsg);
78973  }
78974
78975  if( db->mallocFailed ){
78976    pParse->rc = SQLITE_NOMEM;
78977  }
78978  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
78979  if( pParse->checkSchema ){
78980    schemaIsValid(pParse);
78981  }
78982  if( pParse->rc==SQLITE_SCHEMA ){
78983    sqlite3ResetInternalSchema(db, 0);
78984  }
78985  if( db->mallocFailed ){
78986    pParse->rc = SQLITE_NOMEM;
78987  }
78988  if( pzTail ){
78989    *pzTail = pParse->zTail;
78990  }
78991  rc = pParse->rc;
78992
78993#ifndef SQLITE_OMIT_EXPLAIN
78994  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
78995    static const char * const azColName[] = {
78996       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
78997       "order", "from", "detail"
78998    };
78999    int iFirst, mx;
79000    if( pParse->explain==2 ){
79001      sqlite3VdbeSetNumCols(pParse->pVdbe, 3);
79002      iFirst = 8;
79003      mx = 11;
79004    }else{
79005      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
79006      iFirst = 0;
79007      mx = 8;
79008    }
79009    for(i=iFirst; i<mx; i++){
79010      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
79011                            azColName[i], SQLITE_STATIC);
79012    }
79013  }
79014#endif
79015
79016  assert( db->init.busy==0 || saveSqlFlag==0 );
79017  if( db->init.busy==0 ){
79018    Vdbe *pVdbe = pParse->pVdbe;
79019    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
79020  }
79021  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
79022    sqlite3VdbeFinalize(pParse->pVdbe);
79023    assert(!(*ppStmt));
79024  }else{
79025    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
79026  }
79027
79028  if( zErrMsg ){
79029    sqlite3Error(db, rc, "%s", zErrMsg);
79030    sqlite3DbFree(db, zErrMsg);
79031  }else{
79032    sqlite3Error(db, rc, 0);
79033  }
79034
79035  /* Delete any TriggerPrg structures allocated while parsing this statement. */
79036  while( pParse->pTriggerPrg ){
79037    TriggerPrg *pT = pParse->pTriggerPrg;
79038    pParse->pTriggerPrg = pT->pNext;
79039    sqlite3VdbeProgramDelete(db, pT->pProgram, 0);
79040    sqlite3DbFree(db, pT);
79041  }
79042
79043end_prepare:
79044
79045  sqlite3StackFree(db, pParse);
79046  rc = sqlite3ApiExit(db, rc);
79047  assert( (rc&db->errMask)==rc );
79048  return rc;
79049}
79050static int sqlite3LockAndPrepare(
79051  sqlite3 *db,              /* Database handle. */
79052  const char *zSql,         /* UTF-8 encoded SQL statement. */
79053  int nBytes,               /* Length of zSql in bytes. */
79054  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
79055  Vdbe *pOld,               /* VM being reprepared */
79056  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
79057  const char **pzTail       /* OUT: End of parsed string */
79058){
79059  int rc;
79060  assert( ppStmt!=0 );
79061  *ppStmt = 0;
79062  if( !sqlite3SafetyCheckOk(db) ){
79063    return SQLITE_MISUSE_BKPT;
79064  }
79065  sqlite3_mutex_enter(db->mutex);
79066  sqlite3BtreeEnterAll(db);
79067  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
79068  if( rc==SQLITE_SCHEMA ){
79069    sqlite3_finalize(*ppStmt);
79070    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
79071  }
79072  sqlite3BtreeLeaveAll(db);
79073  sqlite3_mutex_leave(db->mutex);
79074  return rc;
79075}
79076
79077/*
79078** Rerun the compilation of a statement after a schema change.
79079**
79080** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
79081** if the statement cannot be recompiled because another connection has
79082** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
79083** occurs, return SQLITE_SCHEMA.
79084*/
79085SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
79086  int rc;
79087  sqlite3_stmt *pNew;
79088  const char *zSql;
79089  sqlite3 *db;
79090
79091  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
79092  zSql = sqlite3_sql((sqlite3_stmt *)p);
79093  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
79094  db = sqlite3VdbeDb(p);
79095  assert( sqlite3_mutex_held(db->mutex) );
79096  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
79097  if( rc ){
79098    if( rc==SQLITE_NOMEM ){
79099      db->mallocFailed = 1;
79100    }
79101    assert( pNew==0 );
79102    return rc;
79103  }else{
79104    assert( pNew!=0 );
79105  }
79106  sqlite3VdbeSwap((Vdbe*)pNew, p);
79107  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
79108  sqlite3VdbeResetStepResult((Vdbe*)pNew);
79109  sqlite3VdbeFinalize((Vdbe*)pNew);
79110  return SQLITE_OK;
79111}
79112
79113
79114/*
79115** Two versions of the official API.  Legacy and new use.  In the legacy
79116** version, the original SQL text is not saved in the prepared statement
79117** and so if a schema change occurs, SQLITE_SCHEMA is returned by
79118** sqlite3_step().  In the new version, the original SQL text is retained
79119** and the statement is automatically recompiled if an schema change
79120** occurs.
79121*/
79122SQLITE_API int sqlite3_prepare(
79123  sqlite3 *db,              /* Database handle. */
79124  const char *zSql,         /* UTF-8 encoded SQL statement. */
79125  int nBytes,               /* Length of zSql in bytes. */
79126  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
79127  const char **pzTail       /* OUT: End of parsed string */
79128){
79129  int rc;
79130  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
79131  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
79132  return rc;
79133}
79134SQLITE_API int sqlite3_prepare_v2(
79135  sqlite3 *db,              /* Database handle. */
79136  const char *zSql,         /* UTF-8 encoded SQL statement. */
79137  int nBytes,               /* Length of zSql in bytes. */
79138  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
79139  const char **pzTail       /* OUT: End of parsed string */
79140){
79141  int rc;
79142  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
79143  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
79144  return rc;
79145}
79146
79147
79148#ifndef SQLITE_OMIT_UTF16
79149/*
79150** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
79151*/
79152static int sqlite3Prepare16(
79153  sqlite3 *db,              /* Database handle. */
79154  const void *zSql,         /* UTF-8 encoded SQL statement. */
79155  int nBytes,               /* Length of zSql in bytes. */
79156  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
79157  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
79158  const void **pzTail       /* OUT: End of parsed string */
79159){
79160  /* This function currently works by first transforming the UTF-16
79161  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
79162  ** tricky bit is figuring out the pointer to return in *pzTail.
79163  */
79164  char *zSql8;
79165  const char *zTail8 = 0;
79166  int rc = SQLITE_OK;
79167
79168  assert( ppStmt );
79169  *ppStmt = 0;
79170  if( !sqlite3SafetyCheckOk(db) ){
79171    return SQLITE_MISUSE_BKPT;
79172  }
79173  sqlite3_mutex_enter(db->mutex);
79174  zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
79175  if( zSql8 ){
79176    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
79177  }
79178
79179  if( zTail8 && pzTail ){
79180    /* If sqlite3_prepare returns a tail pointer, we calculate the
79181    ** equivalent pointer into the UTF-16 string by counting the unicode
79182    ** characters between zSql8 and zTail8, and then returning a pointer
79183    ** the same number of characters into the UTF-16 string.
79184    */
79185    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
79186    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
79187  }
79188  sqlite3DbFree(db, zSql8);
79189  rc = sqlite3ApiExit(db, rc);
79190  sqlite3_mutex_leave(db->mutex);
79191  return rc;
79192}
79193
79194/*
79195** Two versions of the official API.  Legacy and new use.  In the legacy
79196** version, the original SQL text is not saved in the prepared statement
79197** and so if a schema change occurs, SQLITE_SCHEMA is returned by
79198** sqlite3_step().  In the new version, the original SQL text is retained
79199** and the statement is automatically recompiled if an schema change
79200** occurs.
79201*/
79202SQLITE_API int sqlite3_prepare16(
79203  sqlite3 *db,              /* Database handle. */
79204  const void *zSql,         /* UTF-8 encoded SQL statement. */
79205  int nBytes,               /* Length of zSql in bytes. */
79206  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
79207  const void **pzTail       /* OUT: End of parsed string */
79208){
79209  int rc;
79210  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
79211  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
79212  return rc;
79213}
79214SQLITE_API int sqlite3_prepare16_v2(
79215  sqlite3 *db,              /* Database handle. */
79216  const void *zSql,         /* UTF-8 encoded SQL statement. */
79217  int nBytes,               /* Length of zSql in bytes. */
79218  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
79219  const void **pzTail       /* OUT: End of parsed string */
79220){
79221  int rc;
79222  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
79223  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
79224  return rc;
79225}
79226
79227#endif /* SQLITE_OMIT_UTF16 */
79228
79229/************** End of prepare.c *********************************************/
79230/************** Begin file select.c ******************************************/
79231/*
79232** 2001 September 15
79233**
79234** The author disclaims copyright to this source code.  In place of
79235** a legal notice, here is a blessing:
79236**
79237**    May you do good and not evil.
79238**    May you find forgiveness for yourself and forgive others.
79239**    May you share freely, never taking more than you give.
79240**
79241*************************************************************************
79242** This file contains C code routines that are called by the parser
79243** to handle SELECT statements in SQLite.
79244*/
79245
79246
79247/*
79248** Delete all the content of a Select structure but do not deallocate
79249** the select structure itself.
79250*/
79251static void clearSelect(sqlite3 *db, Select *p){
79252  sqlite3ExprListDelete(db, p->pEList);
79253  sqlite3SrcListDelete(db, p->pSrc);
79254  sqlite3ExprDelete(db, p->pWhere);
79255  sqlite3ExprListDelete(db, p->pGroupBy);
79256  sqlite3ExprDelete(db, p->pHaving);
79257  sqlite3ExprListDelete(db, p->pOrderBy);
79258  sqlite3SelectDelete(db, p->pPrior);
79259  sqlite3ExprDelete(db, p->pLimit);
79260  sqlite3ExprDelete(db, p->pOffset);
79261}
79262
79263/*
79264** Initialize a SelectDest structure.
79265*/
79266SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
79267  pDest->eDest = (u8)eDest;
79268  pDest->iParm = iParm;
79269  pDest->affinity = 0;
79270  pDest->iMem = 0;
79271  pDest->nMem = 0;
79272}
79273
79274
79275/*
79276** Allocate a new Select structure and return a pointer to that
79277** structure.
79278*/
79279SQLITE_PRIVATE Select *sqlite3SelectNew(
79280  Parse *pParse,        /* Parsing context */
79281  ExprList *pEList,     /* which columns to include in the result */
79282  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
79283  Expr *pWhere,         /* the WHERE clause */
79284  ExprList *pGroupBy,   /* the GROUP BY clause */
79285  Expr *pHaving,        /* the HAVING clause */
79286  ExprList *pOrderBy,   /* the ORDER BY clause */
79287  int isDistinct,       /* true if the DISTINCT keyword is present */
79288  Expr *pLimit,         /* LIMIT value.  NULL means not used */
79289  Expr *pOffset         /* OFFSET value.  NULL means no offset */
79290){
79291  Select *pNew;
79292  Select standin;
79293  sqlite3 *db = pParse->db;
79294  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
79295  assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
79296  if( pNew==0 ){
79297    pNew = &standin;
79298    memset(pNew, 0, sizeof(*pNew));
79299  }
79300  if( pEList==0 ){
79301    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
79302  }
79303  pNew->pEList = pEList;
79304  pNew->pSrc = pSrc;
79305  pNew->pWhere = pWhere;
79306  pNew->pGroupBy = pGroupBy;
79307  pNew->pHaving = pHaving;
79308  pNew->pOrderBy = pOrderBy;
79309  pNew->selFlags = isDistinct ? SF_Distinct : 0;
79310  pNew->op = TK_SELECT;
79311  pNew->pLimit = pLimit;
79312  pNew->pOffset = pOffset;
79313  assert( pOffset==0 || pLimit!=0 );
79314  pNew->addrOpenEphm[0] = -1;
79315  pNew->addrOpenEphm[1] = -1;
79316  pNew->addrOpenEphm[2] = -1;
79317  if( db->mallocFailed ) {
79318    clearSelect(db, pNew);
79319    if( pNew!=&standin ) sqlite3DbFree(db, pNew);
79320    pNew = 0;
79321  }
79322  return pNew;
79323}
79324
79325/*
79326** Delete the given Select structure and all of its substructures.
79327*/
79328SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
79329  if( p ){
79330    clearSelect(db, p);
79331    sqlite3DbFree(db, p);
79332  }
79333}
79334
79335/*
79336** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
79337** type of join.  Return an integer constant that expresses that type
79338** in terms of the following bit values:
79339**
79340**     JT_INNER
79341**     JT_CROSS
79342**     JT_OUTER
79343**     JT_NATURAL
79344**     JT_LEFT
79345**     JT_RIGHT
79346**
79347** A full outer join is the combination of JT_LEFT and JT_RIGHT.
79348**
79349** If an illegal or unsupported join type is seen, then still return
79350** a join type, but put an error in the pParse structure.
79351*/
79352SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
79353  int jointype = 0;
79354  Token *apAll[3];
79355  Token *p;
79356                             /*   0123456789 123456789 123456789 123 */
79357  static const char zKeyText[] = "naturaleftouterightfullinnercross";
79358  static const struct {
79359    u8 i;        /* Beginning of keyword text in zKeyText[] */
79360    u8 nChar;    /* Length of the keyword in characters */
79361    u8 code;     /* Join type mask */
79362  } aKeyword[] = {
79363    /* natural */ { 0,  7, JT_NATURAL                },
79364    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
79365    /* outer   */ { 10, 5, JT_OUTER                  },
79366    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
79367    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
79368    /* inner   */ { 23, 5, JT_INNER                  },
79369    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
79370  };
79371  int i, j;
79372  apAll[0] = pA;
79373  apAll[1] = pB;
79374  apAll[2] = pC;
79375  for(i=0; i<3 && apAll[i]; i++){
79376    p = apAll[i];
79377    for(j=0; j<ArraySize(aKeyword); j++){
79378      if( p->n==aKeyword[j].nChar
79379          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
79380        jointype |= aKeyword[j].code;
79381        break;
79382      }
79383    }
79384    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
79385    if( j>=ArraySize(aKeyword) ){
79386      jointype |= JT_ERROR;
79387      break;
79388    }
79389  }
79390  if(
79391     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
79392     (jointype & JT_ERROR)!=0
79393  ){
79394    const char *zSp = " ";
79395    assert( pB!=0 );
79396    if( pC==0 ){ zSp++; }
79397    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
79398       "%T %T%s%T", pA, pB, zSp, pC);
79399    jointype = JT_INNER;
79400  }else if( (jointype & JT_OUTER)!=0
79401         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
79402    sqlite3ErrorMsg(pParse,
79403      "RIGHT and FULL OUTER JOINs are not currently supported");
79404    jointype = JT_INNER;
79405  }
79406  return jointype;
79407}
79408
79409/*
79410** Return the index of a column in a table.  Return -1 if the column
79411** is not contained in the table.
79412*/
79413static int columnIndex(Table *pTab, const char *zCol){
79414  int i;
79415  for(i=0; i<pTab->nCol; i++){
79416    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
79417  }
79418  return -1;
79419}
79420
79421/*
79422** Search the first N tables in pSrc, from left to right, looking for a
79423** table that has a column named zCol.
79424**
79425** When found, set *piTab and *piCol to the table index and column index
79426** of the matching column and return TRUE.
79427**
79428** If not found, return FALSE.
79429*/
79430static int tableAndColumnIndex(
79431  SrcList *pSrc,       /* Array of tables to search */
79432  int N,               /* Number of tables in pSrc->a[] to search */
79433  const char *zCol,    /* Name of the column we are looking for */
79434  int *piTab,          /* Write index of pSrc->a[] here */
79435  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
79436){
79437  int i;               /* For looping over tables in pSrc */
79438  int iCol;            /* Index of column matching zCol */
79439
79440  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
79441  for(i=0; i<N; i++){
79442    iCol = columnIndex(pSrc->a[i].pTab, zCol);
79443    if( iCol>=0 ){
79444      if( piTab ){
79445        *piTab = i;
79446        *piCol = iCol;
79447      }
79448      return 1;
79449    }
79450  }
79451  return 0;
79452}
79453
79454/*
79455** This function is used to add terms implied by JOIN syntax to the
79456** WHERE clause expression of a SELECT statement. The new term, which
79457** is ANDed with the existing WHERE clause, is of the form:
79458**
79459**    (tab1.col1 = tab2.col2)
79460**
79461** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
79462** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
79463** column iColRight of tab2.
79464*/
79465static void addWhereTerm(
79466  Parse *pParse,                  /* Parsing context */
79467  SrcList *pSrc,                  /* List of tables in FROM clause */
79468  int iLeft,                      /* Index of first table to join in pSrc */
79469  int iColLeft,                   /* Index of column in first table */
79470  int iRight,                     /* Index of second table in pSrc */
79471  int iColRight,                  /* Index of column in second table */
79472  int isOuterJoin,                /* True if this is an OUTER join */
79473  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
79474){
79475  sqlite3 *db = pParse->db;
79476  Expr *pE1;
79477  Expr *pE2;
79478  Expr *pEq;
79479
79480  assert( iLeft<iRight );
79481  assert( pSrc->nSrc>iRight );
79482  assert( pSrc->a[iLeft].pTab );
79483  assert( pSrc->a[iRight].pTab );
79484
79485  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
79486  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
79487
79488  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
79489  if( pEq && isOuterJoin ){
79490    ExprSetProperty(pEq, EP_FromJoin);
79491    assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
79492    ExprSetIrreducible(pEq);
79493    pEq->iRightJoinTable = (i16)pE2->iTable;
79494  }
79495  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
79496}
79497
79498/*
79499** Set the EP_FromJoin property on all terms of the given expression.
79500** And set the Expr.iRightJoinTable to iTable for every term in the
79501** expression.
79502**
79503** The EP_FromJoin property is used on terms of an expression to tell
79504** the LEFT OUTER JOIN processing logic that this term is part of the
79505** join restriction specified in the ON or USING clause and not a part
79506** of the more general WHERE clause.  These terms are moved over to the
79507** WHERE clause during join processing but we need to remember that they
79508** originated in the ON or USING clause.
79509**
79510** The Expr.iRightJoinTable tells the WHERE clause processing that the
79511** expression depends on table iRightJoinTable even if that table is not
79512** explicitly mentioned in the expression.  That information is needed
79513** for cases like this:
79514**
79515**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
79516**
79517** The where clause needs to defer the handling of the t1.x=5
79518** term until after the t2 loop of the join.  In that way, a
79519** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
79520** defer the handling of t1.x=5, it will be processed immediately
79521** after the t1 loop and rows with t1.x!=5 will never appear in
79522** the output, which is incorrect.
79523*/
79524static void setJoinExpr(Expr *p, int iTable){
79525  while( p ){
79526    ExprSetProperty(p, EP_FromJoin);
79527    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
79528    ExprSetIrreducible(p);
79529    p->iRightJoinTable = (i16)iTable;
79530    setJoinExpr(p->pLeft, iTable);
79531    p = p->pRight;
79532  }
79533}
79534
79535/*
79536** This routine processes the join information for a SELECT statement.
79537** ON and USING clauses are converted into extra terms of the WHERE clause.
79538** NATURAL joins also create extra WHERE clause terms.
79539**
79540** The terms of a FROM clause are contained in the Select.pSrc structure.
79541** The left most table is the first entry in Select.pSrc.  The right-most
79542** table is the last entry.  The join operator is held in the entry to
79543** the left.  Thus entry 0 contains the join operator for the join between
79544** entries 0 and 1.  Any ON or USING clauses associated with the join are
79545** also attached to the left entry.
79546**
79547** This routine returns the number of errors encountered.
79548*/
79549static int sqliteProcessJoin(Parse *pParse, Select *p){
79550  SrcList *pSrc;                  /* All tables in the FROM clause */
79551  int i, j;                       /* Loop counters */
79552  struct SrcList_item *pLeft;     /* Left table being joined */
79553  struct SrcList_item *pRight;    /* Right table being joined */
79554
79555  pSrc = p->pSrc;
79556  pLeft = &pSrc->a[0];
79557  pRight = &pLeft[1];
79558  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
79559    Table *pLeftTab = pLeft->pTab;
79560    Table *pRightTab = pRight->pTab;
79561    int isOuter;
79562
79563    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
79564    isOuter = (pRight->jointype & JT_OUTER)!=0;
79565
79566    /* When the NATURAL keyword is present, add WHERE clause terms for
79567    ** every column that the two tables have in common.
79568    */
79569    if( pRight->jointype & JT_NATURAL ){
79570      if( pRight->pOn || pRight->pUsing ){
79571        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
79572           "an ON or USING clause", 0);
79573        return 1;
79574      }
79575      for(j=0; j<pRightTab->nCol; j++){
79576        char *zName;   /* Name of column in the right table */
79577        int iLeft;     /* Matching left table */
79578        int iLeftCol;  /* Matching column in the left table */
79579
79580        zName = pRightTab->aCol[j].zName;
79581        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
79582          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
79583                       isOuter, &p->pWhere);
79584        }
79585      }
79586    }
79587
79588    /* Disallow both ON and USING clauses in the same join
79589    */
79590    if( pRight->pOn && pRight->pUsing ){
79591      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
79592        "clauses in the same join");
79593      return 1;
79594    }
79595
79596    /* Add the ON clause to the end of the WHERE clause, connected by
79597    ** an AND operator.
79598    */
79599    if( pRight->pOn ){
79600      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
79601      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
79602      pRight->pOn = 0;
79603    }
79604
79605    /* Create extra terms on the WHERE clause for each column named
79606    ** in the USING clause.  Example: If the two tables to be joined are
79607    ** A and B and the USING clause names X, Y, and Z, then add this
79608    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
79609    ** Report an error if any column mentioned in the USING clause is
79610    ** not contained in both tables to be joined.
79611    */
79612    if( pRight->pUsing ){
79613      IdList *pList = pRight->pUsing;
79614      for(j=0; j<pList->nId; j++){
79615        char *zName;     /* Name of the term in the USING clause */
79616        int iLeft;       /* Table on the left with matching column name */
79617        int iLeftCol;    /* Column number of matching column on the left */
79618        int iRightCol;   /* Column number of matching column on the right */
79619
79620        zName = pList->a[j].zName;
79621        iRightCol = columnIndex(pRightTab, zName);
79622        if( iRightCol<0
79623         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
79624        ){
79625          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
79626            "not present in both tables", zName);
79627          return 1;
79628        }
79629        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
79630                     isOuter, &p->pWhere);
79631      }
79632    }
79633  }
79634  return 0;
79635}
79636
79637/*
79638** Insert code into "v" that will push the record on the top of the
79639** stack into the sorter.
79640*/
79641static void pushOntoSorter(
79642  Parse *pParse,         /* Parser context */
79643  ExprList *pOrderBy,    /* The ORDER BY clause */
79644  Select *pSelect,       /* The whole SELECT statement */
79645  int regData            /* Register holding data to be sorted */
79646){
79647  Vdbe *v = pParse->pVdbe;
79648  int nExpr = pOrderBy->nExpr;
79649  int regBase = sqlite3GetTempRange(pParse, nExpr+2);
79650  int regRecord = sqlite3GetTempReg(pParse);
79651  sqlite3ExprCacheClear(pParse);
79652  sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
79653  sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
79654  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
79655  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
79656  sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
79657  sqlite3ReleaseTempReg(pParse, regRecord);
79658  sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
79659  if( pSelect->iLimit ){
79660    int addr1, addr2;
79661    int iLimit;
79662    if( pSelect->iOffset ){
79663      iLimit = pSelect->iOffset+1;
79664    }else{
79665      iLimit = pSelect->iLimit;
79666    }
79667    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
79668    sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
79669    addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
79670    sqlite3VdbeJumpHere(v, addr1);
79671    sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
79672    sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
79673    sqlite3VdbeJumpHere(v, addr2);
79674    pSelect->iLimit = 0;
79675  }
79676}
79677
79678/*
79679** Add code to implement the OFFSET
79680*/
79681static void codeOffset(
79682  Vdbe *v,          /* Generate code into this VM */
79683  Select *p,        /* The SELECT statement being coded */
79684  int iContinue     /* Jump here to skip the current record */
79685){
79686  if( p->iOffset && iContinue!=0 ){
79687    int addr;
79688    sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
79689    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
79690    sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
79691    VdbeComment((v, "skip OFFSET records"));
79692    sqlite3VdbeJumpHere(v, addr);
79693  }
79694}
79695
79696/*
79697** Add code that will check to make sure the N registers starting at iMem
79698** form a distinct entry.  iTab is a sorting index that holds previously
79699** seen combinations of the N values.  A new entry is made in iTab
79700** if the current N values are new.
79701**
79702** A jump to addrRepeat is made and the N+1 values are popped from the
79703** stack if the top N elements are not distinct.
79704*/
79705static void codeDistinct(
79706  Parse *pParse,     /* Parsing and code generating context */
79707  int iTab,          /* A sorting index used to test for distinctness */
79708  int addrRepeat,    /* Jump to here if not distinct */
79709  int N,             /* Number of elements */
79710  int iMem           /* First element */
79711){
79712  Vdbe *v;
79713  int r1;
79714
79715  v = pParse->pVdbe;
79716  r1 = sqlite3GetTempReg(pParse);
79717  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
79718  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
79719  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
79720  sqlite3ReleaseTempReg(pParse, r1);
79721}
79722
79723/*
79724** Generate an error message when a SELECT is used within a subexpression
79725** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
79726** column.  We do this in a subroutine because the error occurs in multiple
79727** places.
79728*/
79729static int checkForMultiColumnSelectError(
79730  Parse *pParse,       /* Parse context. */
79731  SelectDest *pDest,   /* Destination of SELECT results */
79732  int nExpr            /* Number of result columns returned by SELECT */
79733){
79734  int eDest = pDest->eDest;
79735  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
79736    sqlite3ErrorMsg(pParse, "only a single result allowed for "
79737       "a SELECT that is part of an expression");
79738    return 1;
79739  }else{
79740    return 0;
79741  }
79742}
79743
79744/*
79745** This routine generates the code for the inside of the inner loop
79746** of a SELECT.
79747**
79748** If srcTab and nColumn are both zero, then the pEList expressions
79749** are evaluated in order to get the data for this row.  If nColumn>0
79750** then data is pulled from srcTab and pEList is used only to get the
79751** datatypes for each column.
79752*/
79753static void selectInnerLoop(
79754  Parse *pParse,          /* The parser context */
79755  Select *p,              /* The complete select statement being coded */
79756  ExprList *pEList,       /* List of values being extracted */
79757  int srcTab,             /* Pull data from this table */
79758  int nColumn,            /* Number of columns in the source table */
79759  ExprList *pOrderBy,     /* If not NULL, sort results using this key */
79760  int distinct,           /* If >=0, make sure results are distinct */
79761  SelectDest *pDest,      /* How to dispose of the results */
79762  int iContinue,          /* Jump here to continue with next row */
79763  int iBreak              /* Jump here to break out of the inner loop */
79764){
79765  Vdbe *v = pParse->pVdbe;
79766  int i;
79767  int hasDistinct;        /* True if the DISTINCT keyword is present */
79768  int regResult;              /* Start of memory holding result set */
79769  int eDest = pDest->eDest;   /* How to dispose of results */
79770  int iParm = pDest->iParm;   /* First argument to disposal method */
79771  int nResultCol;             /* Number of result columns */
79772
79773  assert( v );
79774  if( NEVER(v==0) ) return;
79775  assert( pEList!=0 );
79776  hasDistinct = distinct>=0;
79777  if( pOrderBy==0 && !hasDistinct ){
79778    codeOffset(v, p, iContinue);
79779  }
79780
79781  /* Pull the requested columns.
79782  */
79783  if( nColumn>0 ){
79784    nResultCol = nColumn;
79785  }else{
79786    nResultCol = pEList->nExpr;
79787  }
79788  if( pDest->iMem==0 ){
79789    pDest->iMem = pParse->nMem+1;
79790    pDest->nMem = nResultCol;
79791    pParse->nMem += nResultCol;
79792  }else{
79793    assert( pDest->nMem==nResultCol );
79794  }
79795  regResult = pDest->iMem;
79796  if( nColumn>0 ){
79797    for(i=0; i<nColumn; i++){
79798      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
79799    }
79800  }else if( eDest!=SRT_Exists ){
79801    /* If the destination is an EXISTS(...) expression, the actual
79802    ** values returned by the SELECT are not required.
79803    */
79804    sqlite3ExprCacheClear(pParse);
79805    sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
79806  }
79807  nColumn = nResultCol;
79808
79809  /* If the DISTINCT keyword was present on the SELECT statement
79810  ** and this row has been seen before, then do not make this row
79811  ** part of the result.
79812  */
79813  if( hasDistinct ){
79814    assert( pEList!=0 );
79815    assert( pEList->nExpr==nColumn );
79816    codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
79817    if( pOrderBy==0 ){
79818      codeOffset(v, p, iContinue);
79819    }
79820  }
79821
79822  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
79823    return;
79824  }
79825
79826  switch( eDest ){
79827    /* In this mode, write each query result to the key of the temporary
79828    ** table iParm.
79829    */
79830#ifndef SQLITE_OMIT_COMPOUND_SELECT
79831    case SRT_Union: {
79832      int r1;
79833      r1 = sqlite3GetTempReg(pParse);
79834      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
79835      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
79836      sqlite3ReleaseTempReg(pParse, r1);
79837      break;
79838    }
79839
79840    /* Construct a record from the query result, but instead of
79841    ** saving that record, use it as a key to delete elements from
79842    ** the temporary table iParm.
79843    */
79844    case SRT_Except: {
79845      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
79846      break;
79847    }
79848#endif
79849
79850    /* Store the result as data using a unique key.
79851    */
79852    case SRT_Table:
79853    case SRT_EphemTab: {
79854      int r1 = sqlite3GetTempReg(pParse);
79855      testcase( eDest==SRT_Table );
79856      testcase( eDest==SRT_EphemTab );
79857      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
79858      if( pOrderBy ){
79859        pushOntoSorter(pParse, pOrderBy, p, r1);
79860      }else{
79861        int r2 = sqlite3GetTempReg(pParse);
79862        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
79863        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
79864        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79865        sqlite3ReleaseTempReg(pParse, r2);
79866      }
79867      sqlite3ReleaseTempReg(pParse, r1);
79868      break;
79869    }
79870
79871#ifndef SQLITE_OMIT_SUBQUERY
79872    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
79873    ** then there should be a single item on the stack.  Write this
79874    ** item into the set table with bogus data.
79875    */
79876    case SRT_Set: {
79877      assert( nColumn==1 );
79878      p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
79879      if( pOrderBy ){
79880        /* At first glance you would think we could optimize out the
79881        ** ORDER BY in this case since the order of entries in the set
79882        ** does not matter.  But there might be a LIMIT clause, in which
79883        ** case the order does matter */
79884        pushOntoSorter(pParse, pOrderBy, p, regResult);
79885      }else{
79886        int r1 = sqlite3GetTempReg(pParse);
79887        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
79888        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
79889        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
79890        sqlite3ReleaseTempReg(pParse, r1);
79891      }
79892      break;
79893    }
79894
79895    /* If any row exist in the result set, record that fact and abort.
79896    */
79897    case SRT_Exists: {
79898      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
79899      /* The LIMIT clause will terminate the loop for us */
79900      break;
79901    }
79902
79903    /* If this is a scalar select that is part of an expression, then
79904    ** store the results in the appropriate memory cell and break out
79905    ** of the scan loop.
79906    */
79907    case SRT_Mem: {
79908      assert( nColumn==1 );
79909      if( pOrderBy ){
79910        pushOntoSorter(pParse, pOrderBy, p, regResult);
79911      }else{
79912        sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
79913        /* The LIMIT clause will jump out of the loop for us */
79914      }
79915      break;
79916    }
79917#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
79918
79919    /* Send the data to the callback function or to a subroutine.  In the
79920    ** case of a subroutine, the subroutine itself is responsible for
79921    ** popping the data from the stack.
79922    */
79923    case SRT_Coroutine:
79924    case SRT_Output: {
79925      testcase( eDest==SRT_Coroutine );
79926      testcase( eDest==SRT_Output );
79927      if( pOrderBy ){
79928        int r1 = sqlite3GetTempReg(pParse);
79929        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
79930        pushOntoSorter(pParse, pOrderBy, p, r1);
79931        sqlite3ReleaseTempReg(pParse, r1);
79932      }else if( eDest==SRT_Coroutine ){
79933        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
79934      }else{
79935        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
79936        sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
79937      }
79938      break;
79939    }
79940
79941#if !defined(SQLITE_OMIT_TRIGGER)
79942    /* Discard the results.  This is used for SELECT statements inside
79943    ** the body of a TRIGGER.  The purpose of such selects is to call
79944    ** user-defined functions that have side effects.  We do not care
79945    ** about the actual results of the select.
79946    */
79947    default: {
79948      assert( eDest==SRT_Discard );
79949      break;
79950    }
79951#endif
79952  }
79953
79954  /* Jump to the end of the loop if the LIMIT is reached.
79955  */
79956  if( p->iLimit ){
79957    assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
79958                            ** pushOntoSorter() would have cleared p->iLimit */
79959    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
79960  }
79961}
79962
79963/*
79964** Given an expression list, generate a KeyInfo structure that records
79965** the collating sequence for each expression in that expression list.
79966**
79967** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
79968** KeyInfo structure is appropriate for initializing a virtual index to
79969** implement that clause.  If the ExprList is the result set of a SELECT
79970** then the KeyInfo structure is appropriate for initializing a virtual
79971** index to implement a DISTINCT test.
79972**
79973** Space to hold the KeyInfo structure is obtain from malloc.  The calling
79974** function is responsible for seeing that this structure is eventually
79975** freed.  Add the KeyInfo structure to the P4 field of an opcode using
79976** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
79977*/
79978static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
79979  sqlite3 *db = pParse->db;
79980  int nExpr;
79981  KeyInfo *pInfo;
79982  struct ExprList_item *pItem;
79983  int i;
79984
79985  nExpr = pList->nExpr;
79986  pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
79987  if( pInfo ){
79988    pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
79989    pInfo->nField = (u16)nExpr;
79990    pInfo->enc = ENC(db);
79991    pInfo->db = db;
79992    for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
79993      CollSeq *pColl;
79994      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
79995      if( !pColl ){
79996        pColl = db->pDfltColl;
79997      }
79998      pInfo->aColl[i] = pColl;
79999      pInfo->aSortOrder[i] = pItem->sortOrder;
80000    }
80001  }
80002  return pInfo;
80003}
80004
80005
80006/*
80007** If the inner loop was generated using a non-null pOrderBy argument,
80008** then the results were placed in a sorter.  After the loop is terminated
80009** we need to run the sorter and output the results.  The following
80010** routine generates the code needed to do that.
80011*/
80012static void generateSortTail(
80013  Parse *pParse,    /* Parsing context */
80014  Select *p,        /* The SELECT statement */
80015  Vdbe *v,          /* Generate code into this VDBE */
80016  int nColumn,      /* Number of columns of data */
80017  SelectDest *pDest /* Write the sorted results here */
80018){
80019  int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
80020  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
80021  int addr;
80022  int iTab;
80023  int pseudoTab = 0;
80024  ExprList *pOrderBy = p->pOrderBy;
80025
80026  int eDest = pDest->eDest;
80027  int iParm = pDest->iParm;
80028
80029  int regRow;
80030  int regRowid;
80031
80032  iTab = pOrderBy->iECursor;
80033  regRow = sqlite3GetTempReg(pParse);
80034  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
80035    pseudoTab = pParse->nTab++;
80036    sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
80037    regRowid = 0;
80038  }else{
80039    regRowid = sqlite3GetTempReg(pParse);
80040  }
80041  addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
80042  codeOffset(v, p, addrContinue);
80043  sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
80044  switch( eDest ){
80045    case SRT_Table:
80046    case SRT_EphemTab: {
80047      testcase( eDest==SRT_Table );
80048      testcase( eDest==SRT_EphemTab );
80049      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
80050      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
80051      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80052      break;
80053    }
80054#ifndef SQLITE_OMIT_SUBQUERY
80055    case SRT_Set: {
80056      assert( nColumn==1 );
80057      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
80058      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
80059      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
80060      break;
80061    }
80062    case SRT_Mem: {
80063      assert( nColumn==1 );
80064      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
80065      /* The LIMIT clause will terminate the loop for us */
80066      break;
80067    }
80068#endif
80069    default: {
80070      int i;
80071      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
80072      testcase( eDest==SRT_Output );
80073      testcase( eDest==SRT_Coroutine );
80074      for(i=0; i<nColumn; i++){
80075        assert( regRow!=pDest->iMem+i );
80076        sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
80077        if( i==0 ){
80078          sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
80079        }
80080      }
80081      if( eDest==SRT_Output ){
80082        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
80083        sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
80084      }else{
80085        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
80086      }
80087      break;
80088    }
80089  }
80090  sqlite3ReleaseTempReg(pParse, regRow);
80091  sqlite3ReleaseTempReg(pParse, regRowid);
80092
80093  /* LIMIT has been implemented by the pushOntoSorter() routine.
80094  */
80095  assert( p->iLimit==0 );
80096
80097  /* The bottom of the loop
80098  */
80099  sqlite3VdbeResolveLabel(v, addrContinue);
80100  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
80101  sqlite3VdbeResolveLabel(v, addrBreak);
80102  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
80103    sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
80104  }
80105}
80106
80107/*
80108** Return a pointer to a string containing the 'declaration type' of the
80109** expression pExpr. The string may be treated as static by the caller.
80110**
80111** The declaration type is the exact datatype definition extracted from the
80112** original CREATE TABLE statement if the expression is a column. The
80113** declaration type for a ROWID field is INTEGER. Exactly when an expression
80114** is considered a column can be complex in the presence of subqueries. The
80115** result-set expression in all of the following SELECT statements is
80116** considered a column by this function.
80117**
80118**   SELECT col FROM tbl;
80119**   SELECT (SELECT col FROM tbl;
80120**   SELECT (SELECT col FROM tbl);
80121**   SELECT abc FROM (SELECT col AS abc FROM tbl);
80122**
80123** The declaration type for any expression other than a column is NULL.
80124*/
80125static const char *columnType(
80126  NameContext *pNC,
80127  Expr *pExpr,
80128  const char **pzOriginDb,
80129  const char **pzOriginTab,
80130  const char **pzOriginCol
80131){
80132  char const *zType = 0;
80133  char const *zOriginDb = 0;
80134  char const *zOriginTab = 0;
80135  char const *zOriginCol = 0;
80136  int j;
80137  if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
80138
80139  switch( pExpr->op ){
80140    case TK_AGG_COLUMN:
80141    case TK_COLUMN: {
80142      /* The expression is a column. Locate the table the column is being
80143      ** extracted from in NameContext.pSrcList. This table may be real
80144      ** database table or a subquery.
80145      */
80146      Table *pTab = 0;            /* Table structure column is extracted from */
80147      Select *pS = 0;             /* Select the column is extracted from */
80148      int iCol = pExpr->iColumn;  /* Index of column in pTab */
80149      testcase( pExpr->op==TK_AGG_COLUMN );
80150      testcase( pExpr->op==TK_COLUMN );
80151      while( pNC && !pTab ){
80152        SrcList *pTabList = pNC->pSrcList;
80153        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
80154        if( j<pTabList->nSrc ){
80155          pTab = pTabList->a[j].pTab;
80156          pS = pTabList->a[j].pSelect;
80157        }else{
80158          pNC = pNC->pNext;
80159        }
80160      }
80161
80162      if( pTab==0 ){
80163        /* At one time, code such as "SELECT new.x" within a trigger would
80164        ** cause this condition to run.  Since then, we have restructured how
80165        ** trigger code is generated and so this condition is no longer
80166        ** possible. However, it can still be true for statements like
80167        ** the following:
80168        **
80169        **   CREATE TABLE t1(col INTEGER);
80170        **   SELECT (SELECT t1.col) FROM FROM t1;
80171        **
80172        ** when columnType() is called on the expression "t1.col" in the
80173        ** sub-select. In this case, set the column type to NULL, even
80174        ** though it should really be "INTEGER".
80175        **
80176        ** This is not a problem, as the column type of "t1.col" is never
80177        ** used. When columnType() is called on the expression
80178        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
80179        ** branch below.  */
80180        break;
80181      }
80182
80183      assert( pTab && pExpr->pTab==pTab );
80184      if( pS ){
80185        /* The "table" is actually a sub-select or a view in the FROM clause
80186        ** of the SELECT statement. Return the declaration type and origin
80187        ** data for the result-set column of the sub-select.
80188        */
80189        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
80190          /* If iCol is less than zero, then the expression requests the
80191          ** rowid of the sub-select or view. This expression is legal (see
80192          ** test case misc2.2.2) - it always evaluates to NULL.
80193          */
80194          NameContext sNC;
80195          Expr *p = pS->pEList->a[iCol].pExpr;
80196          sNC.pSrcList = pS->pSrc;
80197          sNC.pNext = pNC;
80198          sNC.pParse = pNC->pParse;
80199          zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
80200        }
80201      }else if( ALWAYS(pTab->pSchema) ){
80202        /* A real table */
80203        assert( !pS );
80204        if( iCol<0 ) iCol = pTab->iPKey;
80205        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
80206        if( iCol<0 ){
80207          zType = "INTEGER";
80208          zOriginCol = "rowid";
80209        }else{
80210          zType = pTab->aCol[iCol].zType;
80211          zOriginCol = pTab->aCol[iCol].zName;
80212        }
80213        zOriginTab = pTab->zName;
80214        if( pNC->pParse ){
80215          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
80216          zOriginDb = pNC->pParse->db->aDb[iDb].zName;
80217        }
80218      }
80219      break;
80220    }
80221#ifndef SQLITE_OMIT_SUBQUERY
80222    case TK_SELECT: {
80223      /* The expression is a sub-select. Return the declaration type and
80224      ** origin info for the single column in the result set of the SELECT
80225      ** statement.
80226      */
80227      NameContext sNC;
80228      Select *pS = pExpr->x.pSelect;
80229      Expr *p = pS->pEList->a[0].pExpr;
80230      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
80231      sNC.pSrcList = pS->pSrc;
80232      sNC.pNext = pNC;
80233      sNC.pParse = pNC->pParse;
80234      zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
80235      break;
80236    }
80237#endif
80238  }
80239
80240  if( pzOriginDb ){
80241    assert( pzOriginTab && pzOriginCol );
80242    *pzOriginDb = zOriginDb;
80243    *pzOriginTab = zOriginTab;
80244    *pzOriginCol = zOriginCol;
80245  }
80246  return zType;
80247}
80248
80249/*
80250** Generate code that will tell the VDBE the declaration types of columns
80251** in the result set.
80252*/
80253static void generateColumnTypes(
80254  Parse *pParse,      /* Parser context */
80255  SrcList *pTabList,  /* List of tables */
80256  ExprList *pEList    /* Expressions defining the result set */
80257){
80258#ifndef SQLITE_OMIT_DECLTYPE
80259  Vdbe *v = pParse->pVdbe;
80260  int i;
80261  NameContext sNC;
80262  sNC.pSrcList = pTabList;
80263  sNC.pParse = pParse;
80264  for(i=0; i<pEList->nExpr; i++){
80265    Expr *p = pEList->a[i].pExpr;
80266    const char *zType;
80267#ifdef SQLITE_ENABLE_COLUMN_METADATA
80268    const char *zOrigDb = 0;
80269    const char *zOrigTab = 0;
80270    const char *zOrigCol = 0;
80271    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
80272
80273    /* The vdbe must make its own copy of the column-type and other
80274    ** column specific strings, in case the schema is reset before this
80275    ** virtual machine is deleted.
80276    */
80277    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
80278    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
80279    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
80280#else
80281    zType = columnType(&sNC, p, 0, 0, 0);
80282#endif
80283    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
80284  }
80285#endif /* SQLITE_OMIT_DECLTYPE */
80286}
80287
80288/*
80289** Generate code that will tell the VDBE the names of columns
80290** in the result set.  This information is used to provide the
80291** azCol[] values in the callback.
80292*/
80293static void generateColumnNames(
80294  Parse *pParse,      /* Parser context */
80295  SrcList *pTabList,  /* List of tables */
80296  ExprList *pEList    /* Expressions defining the result set */
80297){
80298  Vdbe *v = pParse->pVdbe;
80299  int i, j;
80300  sqlite3 *db = pParse->db;
80301  int fullNames, shortNames;
80302
80303#ifndef SQLITE_OMIT_EXPLAIN
80304  /* If this is an EXPLAIN, skip this step */
80305  if( pParse->explain ){
80306    return;
80307  }
80308#endif
80309
80310  if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
80311  pParse->colNamesSet = 1;
80312  fullNames = (db->flags & SQLITE_FullColNames)!=0;
80313  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
80314  sqlite3VdbeSetNumCols(v, pEList->nExpr);
80315  for(i=0; i<pEList->nExpr; i++){
80316    Expr *p;
80317    p = pEList->a[i].pExpr;
80318    if( NEVER(p==0) ) continue;
80319    if( pEList->a[i].zName ){
80320      char *zName = pEList->a[i].zName;
80321      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
80322    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
80323      Table *pTab;
80324      char *zCol;
80325      int iCol = p->iColumn;
80326      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
80327        if( pTabList->a[j].iCursor==p->iTable ) break;
80328      }
80329      assert( j<pTabList->nSrc );
80330      pTab = pTabList->a[j].pTab;
80331      if( iCol<0 ) iCol = pTab->iPKey;
80332      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
80333      if( iCol<0 ){
80334        zCol = "rowid";
80335      }else{
80336        zCol = pTab->aCol[iCol].zName;
80337      }
80338      if( !shortNames && !fullNames ){
80339        sqlite3VdbeSetColName(v, i, COLNAME_NAME,
80340            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
80341      }else if( fullNames ){
80342        char *zName = 0;
80343        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
80344        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
80345      }else{
80346        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
80347      }
80348    }else{
80349      sqlite3VdbeSetColName(v, i, COLNAME_NAME,
80350          sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
80351    }
80352  }
80353  generateColumnTypes(pParse, pTabList, pEList);
80354}
80355
80356#ifndef SQLITE_OMIT_COMPOUND_SELECT
80357/*
80358** Name of the connection operator, used for error messages.
80359*/
80360static const char *selectOpName(int id){
80361  char *z;
80362  switch( id ){
80363    case TK_ALL:       z = "UNION ALL";   break;
80364    case TK_INTERSECT: z = "INTERSECT";   break;
80365    case TK_EXCEPT:    z = "EXCEPT";      break;
80366    default:           z = "UNION";       break;
80367  }
80368  return z;
80369}
80370#endif /* SQLITE_OMIT_COMPOUND_SELECT */
80371
80372/*
80373** Given a an expression list (which is really the list of expressions
80374** that form the result set of a SELECT statement) compute appropriate
80375** column names for a table that would hold the expression list.
80376**
80377** All column names will be unique.
80378**
80379** Only the column names are computed.  Column.zType, Column.zColl,
80380** and other fields of Column are zeroed.
80381**
80382** Return SQLITE_OK on success.  If a memory allocation error occurs,
80383** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
80384*/
80385static int selectColumnsFromExprList(
80386  Parse *pParse,          /* Parsing context */
80387  ExprList *pEList,       /* Expr list from which to derive column names */
80388  int *pnCol,             /* Write the number of columns here */
80389  Column **paCol          /* Write the new column list here */
80390){
80391  sqlite3 *db = pParse->db;   /* Database connection */
80392  int i, j;                   /* Loop counters */
80393  int cnt;                    /* Index added to make the name unique */
80394  Column *aCol, *pCol;        /* For looping over result columns */
80395  int nCol;                   /* Number of columns in the result set */
80396  Expr *p;                    /* Expression for a single result column */
80397  char *zName;                /* Column name */
80398  int nName;                  /* Size of name in zName[] */
80399
80400  *pnCol = nCol = pEList->nExpr;
80401  aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
80402  if( aCol==0 ) return SQLITE_NOMEM;
80403  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
80404    /* Get an appropriate name for the column
80405    */
80406    p = pEList->a[i].pExpr;
80407    assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
80408               || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
80409    if( (zName = pEList->a[i].zName)!=0 ){
80410      /* If the column contains an "AS <name>" phrase, use <name> as the name */
80411      zName = sqlite3DbStrDup(db, zName);
80412    }else{
80413      Expr *pColExpr = p;  /* The expression that is the result column name */
80414      Table *pTab;         /* Table associated with this expression */
80415      while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
80416      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
80417        /* For columns use the column name name */
80418        int iCol = pColExpr->iColumn;
80419        pTab = pColExpr->pTab;
80420        if( iCol<0 ) iCol = pTab->iPKey;
80421        zName = sqlite3MPrintf(db, "%s",
80422                 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
80423      }else if( pColExpr->op==TK_ID ){
80424        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
80425        zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
80426      }else{
80427        /* Use the original text of the column expression as its name */
80428        zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
80429      }
80430    }
80431    if( db->mallocFailed ){
80432      sqlite3DbFree(db, zName);
80433      break;
80434    }
80435
80436    /* Make sure the column name is unique.  If the name is not unique,
80437    ** append a integer to the name so that it becomes unique.
80438    */
80439    nName = sqlite3Strlen30(zName);
80440    for(j=cnt=0; j<i; j++){
80441      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
80442        char *zNewName;
80443        zName[nName] = 0;
80444        zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
80445        sqlite3DbFree(db, zName);
80446        zName = zNewName;
80447        j = -1;
80448        if( zName==0 ) break;
80449      }
80450    }
80451    pCol->zName = zName;
80452  }
80453  if( db->mallocFailed ){
80454    for(j=0; j<i; j++){
80455      sqlite3DbFree(db, aCol[j].zName);
80456    }
80457    sqlite3DbFree(db, aCol);
80458    *paCol = 0;
80459    *pnCol = 0;
80460    return SQLITE_NOMEM;
80461  }
80462  return SQLITE_OK;
80463}
80464
80465/*
80466** Add type and collation information to a column list based on
80467** a SELECT statement.
80468**
80469** The column list presumably came from selectColumnNamesFromExprList().
80470** The column list has only names, not types or collations.  This
80471** routine goes through and adds the types and collations.
80472**
80473** This routine requires that all identifiers in the SELECT
80474** statement be resolved.
80475*/
80476static void selectAddColumnTypeAndCollation(
80477  Parse *pParse,        /* Parsing contexts */
80478  int nCol,             /* Number of columns */
80479  Column *aCol,         /* List of columns */
80480  Select *pSelect       /* SELECT used to determine types and collations */
80481){
80482  sqlite3 *db = pParse->db;
80483  NameContext sNC;
80484  Column *pCol;
80485  CollSeq *pColl;
80486  int i;
80487  Expr *p;
80488  struct ExprList_item *a;
80489
80490  assert( pSelect!=0 );
80491  assert( (pSelect->selFlags & SF_Resolved)!=0 );
80492  assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
80493  if( db->mallocFailed ) return;
80494  memset(&sNC, 0, sizeof(sNC));
80495  sNC.pSrcList = pSelect->pSrc;
80496  a = pSelect->pEList->a;
80497  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
80498    p = a[i].pExpr;
80499    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
80500    pCol->affinity = sqlite3ExprAffinity(p);
80501    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
80502    pColl = sqlite3ExprCollSeq(pParse, p);
80503    if( pColl ){
80504      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
80505    }
80506  }
80507}
80508
80509/*
80510** Given a SELECT statement, generate a Table structure that describes
80511** the result set of that SELECT.
80512*/
80513SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
80514  Table *pTab;
80515  sqlite3 *db = pParse->db;
80516  int savedFlags;
80517
80518  savedFlags = db->flags;
80519  db->flags &= ~SQLITE_FullColNames;
80520  db->flags |= SQLITE_ShortColNames;
80521  sqlite3SelectPrep(pParse, pSelect, 0);
80522  if( pParse->nErr ) return 0;
80523  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
80524  db->flags = savedFlags;
80525  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
80526  if( pTab==0 ){
80527    return 0;
80528  }
80529  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
80530  ** is disabled, so we might as well hard-code pTab->dbMem to NULL. */
80531  assert( db->lookaside.bEnabled==0 );
80532  pTab->dbMem = 0;
80533  pTab->nRef = 1;
80534  pTab->zName = 0;
80535  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
80536  selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
80537  pTab->iPKey = -1;
80538  if( db->mallocFailed ){
80539    sqlite3DeleteTable(pTab);
80540    return 0;
80541  }
80542  return pTab;
80543}
80544
80545/*
80546** Get a VDBE for the given parser context.  Create a new one if necessary.
80547** If an error occurs, return NULL and leave a message in pParse.
80548*/
80549SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
80550  Vdbe *v = pParse->pVdbe;
80551  if( v==0 ){
80552    v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
80553#ifndef SQLITE_OMIT_TRACE
80554    if( v ){
80555      sqlite3VdbeAddOp0(v, OP_Trace);
80556    }
80557#endif
80558  }
80559  return v;
80560}
80561
80562
80563/*
80564** Compute the iLimit and iOffset fields of the SELECT based on the
80565** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
80566** that appear in the original SQL statement after the LIMIT and OFFSET
80567** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
80568** are the integer memory register numbers for counters used to compute
80569** the limit and offset.  If there is no limit and/or offset, then
80570** iLimit and iOffset are negative.
80571**
80572** This routine changes the values of iLimit and iOffset only if
80573** a limit or offset is defined by pLimit and pOffset.  iLimit and
80574** iOffset should have been preset to appropriate default values
80575** (usually but not always -1) prior to calling this routine.
80576** Only if pLimit!=0 or pOffset!=0 do the limit registers get
80577** redefined.  The UNION ALL operator uses this property to force
80578** the reuse of the same limit and offset registers across multiple
80579** SELECT statements.
80580*/
80581static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
80582  Vdbe *v = 0;
80583  int iLimit = 0;
80584  int iOffset;
80585  int addr1, n;
80586  if( p->iLimit ) return;
80587
80588  /*
80589  ** "LIMIT -1" always shows all rows.  There is some
80590  ** contraversy about what the correct behavior should be.
80591  ** The current implementation interprets "LIMIT 0" to mean
80592  ** no rows.
80593  */
80594  sqlite3ExprCacheClear(pParse);
80595  assert( p->pOffset==0 || p->pLimit!=0 );
80596  if( p->pLimit ){
80597    p->iLimit = iLimit = ++pParse->nMem;
80598    v = sqlite3GetVdbe(pParse);
80599    if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
80600    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
80601      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
80602      VdbeComment((v, "LIMIT counter"));
80603      if( n==0 ){
80604        sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
80605      }
80606    }else{
80607      sqlite3ExprCode(pParse, p->pLimit, iLimit);
80608      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
80609      VdbeComment((v, "LIMIT counter"));
80610      sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
80611    }
80612    if( p->pOffset ){
80613      p->iOffset = iOffset = ++pParse->nMem;
80614      pParse->nMem++;   /* Allocate an extra register for limit+offset */
80615      sqlite3ExprCode(pParse, p->pOffset, iOffset);
80616      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
80617      VdbeComment((v, "OFFSET counter"));
80618      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
80619      sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
80620      sqlite3VdbeJumpHere(v, addr1);
80621      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
80622      VdbeComment((v, "LIMIT+OFFSET"));
80623      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
80624      sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
80625      sqlite3VdbeJumpHere(v, addr1);
80626    }
80627  }
80628}
80629
80630#ifndef SQLITE_OMIT_COMPOUND_SELECT
80631/*
80632** Return the appropriate collating sequence for the iCol-th column of
80633** the result set for the compound-select statement "p".  Return NULL if
80634** the column has no default collating sequence.
80635**
80636** The collating sequence for the compound select is taken from the
80637** left-most term of the select that has a collating sequence.
80638*/
80639static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
80640  CollSeq *pRet;
80641  if( p->pPrior ){
80642    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
80643  }else{
80644    pRet = 0;
80645  }
80646  assert( iCol>=0 );
80647  if( pRet==0 && iCol<p->pEList->nExpr ){
80648    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
80649  }
80650  return pRet;
80651}
80652#endif /* SQLITE_OMIT_COMPOUND_SELECT */
80653
80654/* Forward reference */
80655static int multiSelectOrderBy(
80656  Parse *pParse,        /* Parsing context */
80657  Select *p,            /* The right-most of SELECTs to be coded */
80658  SelectDest *pDest     /* What to do with query results */
80659);
80660
80661
80662#ifndef SQLITE_OMIT_COMPOUND_SELECT
80663/*
80664** This routine is called to process a compound query form from
80665** two or more separate queries using UNION, UNION ALL, EXCEPT, or
80666** INTERSECT
80667**
80668** "p" points to the right-most of the two queries.  the query on the
80669** left is p->pPrior.  The left query could also be a compound query
80670** in which case this routine will be called recursively.
80671**
80672** The results of the total query are to be written into a destination
80673** of type eDest with parameter iParm.
80674**
80675** Example 1:  Consider a three-way compound SQL statement.
80676**
80677**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
80678**
80679** This statement is parsed up as follows:
80680**
80681**     SELECT c FROM t3
80682**      |
80683**      `----->  SELECT b FROM t2
80684**                |
80685**                `------>  SELECT a FROM t1
80686**
80687** The arrows in the diagram above represent the Select.pPrior pointer.
80688** So if this routine is called with p equal to the t3 query, then
80689** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
80690**
80691** Notice that because of the way SQLite parses compound SELECTs, the
80692** individual selects always group from left to right.
80693*/
80694static int multiSelect(
80695  Parse *pParse,        /* Parsing context */
80696  Select *p,            /* The right-most of SELECTs to be coded */
80697  SelectDest *pDest     /* What to do with query results */
80698){
80699  int rc = SQLITE_OK;   /* Success code from a subroutine */
80700  Select *pPrior;       /* Another SELECT immediately to our left */
80701  Vdbe *v;              /* Generate code to this VDBE */
80702  SelectDest dest;      /* Alternative data destination */
80703  Select *pDelete = 0;  /* Chain of simple selects to delete */
80704  sqlite3 *db;          /* Database connection */
80705
80706  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
80707  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
80708  */
80709  assert( p && p->pPrior );  /* Calling function guarantees this much */
80710  db = pParse->db;
80711  pPrior = p->pPrior;
80712  assert( pPrior->pRightmost!=pPrior );
80713  assert( pPrior->pRightmost==p->pRightmost );
80714  dest = *pDest;
80715  if( pPrior->pOrderBy ){
80716    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
80717      selectOpName(p->op));
80718    rc = 1;
80719    goto multi_select_end;
80720  }
80721  if( pPrior->pLimit ){
80722    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
80723      selectOpName(p->op));
80724    rc = 1;
80725    goto multi_select_end;
80726  }
80727
80728  v = sqlite3GetVdbe(pParse);
80729  assert( v!=0 );  /* The VDBE already created by calling function */
80730
80731  /* Create the destination temporary table if necessary
80732  */
80733  if( dest.eDest==SRT_EphemTab ){
80734    assert( p->pEList );
80735    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
80736    dest.eDest = SRT_Table;
80737  }
80738
80739  /* Make sure all SELECTs in the statement have the same number of elements
80740  ** in their result sets.
80741  */
80742  assert( p->pEList && pPrior->pEList );
80743  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
80744    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
80745      " do not have the same number of result columns", selectOpName(p->op));
80746    rc = 1;
80747    goto multi_select_end;
80748  }
80749
80750  /* Compound SELECTs that have an ORDER BY clause are handled separately.
80751  */
80752  if( p->pOrderBy ){
80753    return multiSelectOrderBy(pParse, p, pDest);
80754  }
80755
80756  /* Generate code for the left and right SELECT statements.
80757  */
80758  switch( p->op ){
80759    case TK_ALL: {
80760      int addr = 0;
80761      assert( !pPrior->pLimit );
80762      pPrior->pLimit = p->pLimit;
80763      pPrior->pOffset = p->pOffset;
80764      rc = sqlite3Select(pParse, pPrior, &dest);
80765      p->pLimit = 0;
80766      p->pOffset = 0;
80767      if( rc ){
80768        goto multi_select_end;
80769      }
80770      p->pPrior = 0;
80771      p->iLimit = pPrior->iLimit;
80772      p->iOffset = pPrior->iOffset;
80773      if( p->iLimit ){
80774        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
80775        VdbeComment((v, "Jump ahead if LIMIT reached"));
80776      }
80777      rc = sqlite3Select(pParse, p, &dest);
80778      testcase( rc!=SQLITE_OK );
80779      pDelete = p->pPrior;
80780      p->pPrior = pPrior;
80781      if( addr ){
80782        sqlite3VdbeJumpHere(v, addr);
80783      }
80784      break;
80785    }
80786    case TK_EXCEPT:
80787    case TK_UNION: {
80788      int unionTab;    /* Cursor number of the temporary table holding result */
80789      u8 op = 0;       /* One of the SRT_ operations to apply to self */
80790      int priorOp;     /* The SRT_ operation to apply to prior selects */
80791      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
80792      int addr;
80793      SelectDest uniondest;
80794
80795      testcase( p->op==TK_EXCEPT );
80796      testcase( p->op==TK_UNION );
80797      priorOp = SRT_Union;
80798      if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
80799        /* We can reuse a temporary table generated by a SELECT to our
80800        ** right.
80801        */
80802        assert( p->pRightmost!=p );  /* Can only happen for leftward elements
80803                                     ** of a 3-way or more compound */
80804        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
80805        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
80806        unionTab = dest.iParm;
80807      }else{
80808        /* We will need to create our own temporary table to hold the
80809        ** intermediate results.
80810        */
80811        unionTab = pParse->nTab++;
80812        assert( p->pOrderBy==0 );
80813        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
80814        assert( p->addrOpenEphm[0] == -1 );
80815        p->addrOpenEphm[0] = addr;
80816        p->pRightmost->selFlags |= SF_UsesEphemeral;
80817        assert( p->pEList );
80818      }
80819
80820      /* Code the SELECT statements to our left
80821      */
80822      assert( !pPrior->pOrderBy );
80823      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
80824      rc = sqlite3Select(pParse, pPrior, &uniondest);
80825      if( rc ){
80826        goto multi_select_end;
80827      }
80828
80829      /* Code the current SELECT statement
80830      */
80831      if( p->op==TK_EXCEPT ){
80832        op = SRT_Except;
80833      }else{
80834        assert( p->op==TK_UNION );
80835        op = SRT_Union;
80836      }
80837      p->pPrior = 0;
80838      pLimit = p->pLimit;
80839      p->pLimit = 0;
80840      pOffset = p->pOffset;
80841      p->pOffset = 0;
80842      uniondest.eDest = op;
80843      rc = sqlite3Select(pParse, p, &uniondest);
80844      testcase( rc!=SQLITE_OK );
80845      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
80846      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
80847      sqlite3ExprListDelete(db, p->pOrderBy);
80848      pDelete = p->pPrior;
80849      p->pPrior = pPrior;
80850      p->pOrderBy = 0;
80851      sqlite3ExprDelete(db, p->pLimit);
80852      p->pLimit = pLimit;
80853      p->pOffset = pOffset;
80854      p->iLimit = 0;
80855      p->iOffset = 0;
80856
80857      /* Convert the data in the temporary table into whatever form
80858      ** it is that we currently need.
80859      */
80860      assert( unionTab==dest.iParm || dest.eDest!=priorOp );
80861      if( dest.eDest!=priorOp ){
80862        int iCont, iBreak, iStart;
80863        assert( p->pEList );
80864        if( dest.eDest==SRT_Output ){
80865          Select *pFirst = p;
80866          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
80867          generateColumnNames(pParse, 0, pFirst->pEList);
80868        }
80869        iBreak = sqlite3VdbeMakeLabel(v);
80870        iCont = sqlite3VdbeMakeLabel(v);
80871        computeLimitRegisters(pParse, p, iBreak);
80872        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
80873        iStart = sqlite3VdbeCurrentAddr(v);
80874        selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
80875                        0, -1, &dest, iCont, iBreak);
80876        sqlite3VdbeResolveLabel(v, iCont);
80877        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
80878        sqlite3VdbeResolveLabel(v, iBreak);
80879        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
80880      }
80881      break;
80882    }
80883    default: assert( p->op==TK_INTERSECT ); {
80884      int tab1, tab2;
80885      int iCont, iBreak, iStart;
80886      Expr *pLimit, *pOffset;
80887      int addr;
80888      SelectDest intersectdest;
80889      int r1;
80890
80891      /* INTERSECT is different from the others since it requires
80892      ** two temporary tables.  Hence it has its own case.  Begin
80893      ** by allocating the tables we will need.
80894      */
80895      tab1 = pParse->nTab++;
80896      tab2 = pParse->nTab++;
80897      assert( p->pOrderBy==0 );
80898
80899      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
80900      assert( p->addrOpenEphm[0] == -1 );
80901      p->addrOpenEphm[0] = addr;
80902      p->pRightmost->selFlags |= SF_UsesEphemeral;
80903      assert( p->pEList );
80904
80905      /* Code the SELECTs to our left into temporary table "tab1".
80906      */
80907      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
80908      rc = sqlite3Select(pParse, pPrior, &intersectdest);
80909      if( rc ){
80910        goto multi_select_end;
80911      }
80912
80913      /* Code the current SELECT into temporary table "tab2"
80914      */
80915      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
80916      assert( p->addrOpenEphm[1] == -1 );
80917      p->addrOpenEphm[1] = addr;
80918      p->pPrior = 0;
80919      pLimit = p->pLimit;
80920      p->pLimit = 0;
80921      pOffset = p->pOffset;
80922      p->pOffset = 0;
80923      intersectdest.iParm = tab2;
80924      rc = sqlite3Select(pParse, p, &intersectdest);
80925      testcase( rc!=SQLITE_OK );
80926      pDelete = p->pPrior;
80927      p->pPrior = pPrior;
80928      sqlite3ExprDelete(db, p->pLimit);
80929      p->pLimit = pLimit;
80930      p->pOffset = pOffset;
80931
80932      /* Generate code to take the intersection of the two temporary
80933      ** tables.
80934      */
80935      assert( p->pEList );
80936      if( dest.eDest==SRT_Output ){
80937        Select *pFirst = p;
80938        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
80939        generateColumnNames(pParse, 0, pFirst->pEList);
80940      }
80941      iBreak = sqlite3VdbeMakeLabel(v);
80942      iCont = sqlite3VdbeMakeLabel(v);
80943      computeLimitRegisters(pParse, p, iBreak);
80944      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
80945      r1 = sqlite3GetTempReg(pParse);
80946      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
80947      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
80948      sqlite3ReleaseTempReg(pParse, r1);
80949      selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
80950                      0, -1, &dest, iCont, iBreak);
80951      sqlite3VdbeResolveLabel(v, iCont);
80952      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
80953      sqlite3VdbeResolveLabel(v, iBreak);
80954      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
80955      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
80956      break;
80957    }
80958  }
80959
80960  /* Compute collating sequences used by
80961  ** temporary tables needed to implement the compound select.
80962  ** Attach the KeyInfo structure to all temporary tables.
80963  **
80964  ** This section is run by the right-most SELECT statement only.
80965  ** SELECT statements to the left always skip this part.  The right-most
80966  ** SELECT might also skip this part if it has no ORDER BY clause and
80967  ** no temp tables are required.
80968  */
80969  if( p->selFlags & SF_UsesEphemeral ){
80970    int i;                        /* Loop counter */
80971    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
80972    Select *pLoop;                /* For looping through SELECT statements */
80973    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
80974    int nCol;                     /* Number of columns in result set */
80975
80976    assert( p->pRightmost==p );
80977    nCol = p->pEList->nExpr;
80978    pKeyInfo = sqlite3DbMallocZero(db,
80979                       sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
80980    if( !pKeyInfo ){
80981      rc = SQLITE_NOMEM;
80982      goto multi_select_end;
80983    }
80984
80985    pKeyInfo->enc = ENC(db);
80986    pKeyInfo->nField = (u16)nCol;
80987
80988    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
80989      *apColl = multiSelectCollSeq(pParse, p, i);
80990      if( 0==*apColl ){
80991        *apColl = db->pDfltColl;
80992      }
80993    }
80994
80995    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
80996      for(i=0; i<2; i++){
80997        int addr = pLoop->addrOpenEphm[i];
80998        if( addr<0 ){
80999          /* If [0] is unused then [1] is also unused.  So we can
81000          ** always safely abort as soon as the first unused slot is found */
81001          assert( pLoop->addrOpenEphm[1]<0 );
81002          break;
81003        }
81004        sqlite3VdbeChangeP2(v, addr, nCol);
81005        sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
81006        pLoop->addrOpenEphm[i] = -1;
81007      }
81008    }
81009    sqlite3DbFree(db, pKeyInfo);
81010  }
81011
81012multi_select_end:
81013  pDest->iMem = dest.iMem;
81014  pDest->nMem = dest.nMem;
81015  sqlite3SelectDelete(db, pDelete);
81016  return rc;
81017}
81018#endif /* SQLITE_OMIT_COMPOUND_SELECT */
81019
81020/*
81021** Code an output subroutine for a coroutine implementation of a
81022** SELECT statment.
81023**
81024** The data to be output is contained in pIn->iMem.  There are
81025** pIn->nMem columns to be output.  pDest is where the output should
81026** be sent.
81027**
81028** regReturn is the number of the register holding the subroutine
81029** return address.
81030**
81031** If regPrev>0 then it is a the first register in a vector that
81032** records the previous output.  mem[regPrev] is a flag that is false
81033** if there has been no previous output.  If regPrev>0 then code is
81034** generated to suppress duplicates.  pKeyInfo is used for comparing
81035** keys.
81036**
81037** If the LIMIT found in p->iLimit is reached, jump immediately to
81038** iBreak.
81039*/
81040static int generateOutputSubroutine(
81041  Parse *pParse,          /* Parsing context */
81042  Select *p,              /* The SELECT statement */
81043  SelectDest *pIn,        /* Coroutine supplying data */
81044  SelectDest *pDest,      /* Where to send the data */
81045  int regReturn,          /* The return address register */
81046  int regPrev,            /* Previous result register.  No uniqueness if 0 */
81047  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
81048  int p4type,             /* The p4 type for pKeyInfo */
81049  int iBreak              /* Jump here if we hit the LIMIT */
81050){
81051  Vdbe *v = pParse->pVdbe;
81052  int iContinue;
81053  int addr;
81054
81055  addr = sqlite3VdbeCurrentAddr(v);
81056  iContinue = sqlite3VdbeMakeLabel(v);
81057
81058  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
81059  */
81060  if( regPrev ){
81061    int j1, j2;
81062    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
81063    j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
81064                              (char*)pKeyInfo, p4type);
81065    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
81066    sqlite3VdbeJumpHere(v, j1);
81067    sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
81068    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
81069  }
81070  if( pParse->db->mallocFailed ) return 0;
81071
81072  /* Suppress the the first OFFSET entries if there is an OFFSET clause
81073  */
81074  codeOffset(v, p, iContinue);
81075
81076  switch( pDest->eDest ){
81077    /* Store the result as data using a unique key.
81078    */
81079    case SRT_Table:
81080    case SRT_EphemTab: {
81081      int r1 = sqlite3GetTempReg(pParse);
81082      int r2 = sqlite3GetTempReg(pParse);
81083      testcase( pDest->eDest==SRT_Table );
81084      testcase( pDest->eDest==SRT_EphemTab );
81085      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
81086      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
81087      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
81088      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
81089      sqlite3ReleaseTempReg(pParse, r2);
81090      sqlite3ReleaseTempReg(pParse, r1);
81091      break;
81092    }
81093
81094#ifndef SQLITE_OMIT_SUBQUERY
81095    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
81096    ** then there should be a single item on the stack.  Write this
81097    ** item into the set table with bogus data.
81098    */
81099    case SRT_Set: {
81100      int r1;
81101      assert( pIn->nMem==1 );
81102      p->affinity =
81103         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
81104      r1 = sqlite3GetTempReg(pParse);
81105      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
81106      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
81107      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
81108      sqlite3ReleaseTempReg(pParse, r1);
81109      break;
81110    }
81111
81112#if 0  /* Never occurs on an ORDER BY query */
81113    /* If any row exist in the result set, record that fact and abort.
81114    */
81115    case SRT_Exists: {
81116      sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
81117      /* The LIMIT clause will terminate the loop for us */
81118      break;
81119    }
81120#endif
81121
81122    /* If this is a scalar select that is part of an expression, then
81123    ** store the results in the appropriate memory cell and break out
81124    ** of the scan loop.
81125    */
81126    case SRT_Mem: {
81127      assert( pIn->nMem==1 );
81128      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
81129      /* The LIMIT clause will jump out of the loop for us */
81130      break;
81131    }
81132#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
81133
81134    /* The results are stored in a sequence of registers
81135    ** starting at pDest->iMem.  Then the co-routine yields.
81136    */
81137    case SRT_Coroutine: {
81138      if( pDest->iMem==0 ){
81139        pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
81140        pDest->nMem = pIn->nMem;
81141      }
81142      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
81143      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
81144      break;
81145    }
81146
81147    /* If none of the above, then the result destination must be
81148    ** SRT_Output.  This routine is never called with any other
81149    ** destination other than the ones handled above or SRT_Output.
81150    **
81151    ** For SRT_Output, results are stored in a sequence of registers.
81152    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
81153    ** return the next row of result.
81154    */
81155    default: {
81156      assert( pDest->eDest==SRT_Output );
81157      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
81158      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
81159      break;
81160    }
81161  }
81162
81163  /* Jump to the end of the loop if the LIMIT is reached.
81164  */
81165  if( p->iLimit ){
81166    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
81167  }
81168
81169  /* Generate the subroutine return
81170  */
81171  sqlite3VdbeResolveLabel(v, iContinue);
81172  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
81173
81174  return addr;
81175}
81176
81177/*
81178** Alternative compound select code generator for cases when there
81179** is an ORDER BY clause.
81180**
81181** We assume a query of the following form:
81182**
81183**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
81184**
81185** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
81186** is to code both <selectA> and <selectB> with the ORDER BY clause as
81187** co-routines.  Then run the co-routines in parallel and merge the results
81188** into the output.  In addition to the two coroutines (called selectA and
81189** selectB) there are 7 subroutines:
81190**
81191**    outA:    Move the output of the selectA coroutine into the output
81192**             of the compound query.
81193**
81194**    outB:    Move the output of the selectB coroutine into the output
81195**             of the compound query.  (Only generated for UNION and
81196**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
81197**             appears only in B.)
81198**
81199**    AltB:    Called when there is data from both coroutines and A<B.
81200**
81201**    AeqB:    Called when there is data from both coroutines and A==B.
81202**
81203**    AgtB:    Called when there is data from both coroutines and A>B.
81204**
81205**    EofA:    Called when data is exhausted from selectA.
81206**
81207**    EofB:    Called when data is exhausted from selectB.
81208**
81209** The implementation of the latter five subroutines depend on which
81210** <operator> is used:
81211**
81212**
81213**             UNION ALL         UNION            EXCEPT          INTERSECT
81214**          -------------  -----------------  --------------  -----------------
81215**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
81216**
81217**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
81218**
81219**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
81220**
81221**   EofA:   outB, nextB      outB, nextB          halt             halt
81222**
81223**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
81224**
81225** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
81226** causes an immediate jump to EofA and an EOF on B following nextB causes
81227** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
81228** following nextX causes a jump to the end of the select processing.
81229**
81230** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
81231** within the output subroutine.  The regPrev register set holds the previously
81232** output value.  A comparison is made against this value and the output
81233** is skipped if the next results would be the same as the previous.
81234**
81235** The implementation plan is to implement the two coroutines and seven
81236** subroutines first, then put the control logic at the bottom.  Like this:
81237**
81238**          goto Init
81239**     coA: coroutine for left query (A)
81240**     coB: coroutine for right query (B)
81241**    outA: output one row of A
81242**    outB: output one row of B (UNION and UNION ALL only)
81243**    EofA: ...
81244**    EofB: ...
81245**    AltB: ...
81246**    AeqB: ...
81247**    AgtB: ...
81248**    Init: initialize coroutine registers
81249**          yield coA
81250**          if eof(A) goto EofA
81251**          yield coB
81252**          if eof(B) goto EofB
81253**    Cmpr: Compare A, B
81254**          Jump AltB, AeqB, AgtB
81255**     End: ...
81256**
81257** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
81258** actually called using Gosub and they do not Return.  EofA and EofB loop
81259** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
81260** and AgtB jump to either L2 or to one of EofA or EofB.
81261*/
81262#ifndef SQLITE_OMIT_COMPOUND_SELECT
81263static int multiSelectOrderBy(
81264  Parse *pParse,        /* Parsing context */
81265  Select *p,            /* The right-most of SELECTs to be coded */
81266  SelectDest *pDest     /* What to do with query results */
81267){
81268  int i, j;             /* Loop counters */
81269  Select *pPrior;       /* Another SELECT immediately to our left */
81270  Vdbe *v;              /* Generate code to this VDBE */
81271  SelectDest destA;     /* Destination for coroutine A */
81272  SelectDest destB;     /* Destination for coroutine B */
81273  int regAddrA;         /* Address register for select-A coroutine */
81274  int regEofA;          /* Flag to indicate when select-A is complete */
81275  int regAddrB;         /* Address register for select-B coroutine */
81276  int regEofB;          /* Flag to indicate when select-B is complete */
81277  int addrSelectA;      /* Address of the select-A coroutine */
81278  int addrSelectB;      /* Address of the select-B coroutine */
81279  int regOutA;          /* Address register for the output-A subroutine */
81280  int regOutB;          /* Address register for the output-B subroutine */
81281  int addrOutA;         /* Address of the output-A subroutine */
81282  int addrOutB = 0;     /* Address of the output-B subroutine */
81283  int addrEofA;         /* Address of the select-A-exhausted subroutine */
81284  int addrEofB;         /* Address of the select-B-exhausted subroutine */
81285  int addrAltB;         /* Address of the A<B subroutine */
81286  int addrAeqB;         /* Address of the A==B subroutine */
81287  int addrAgtB;         /* Address of the A>B subroutine */
81288  int regLimitA;        /* Limit register for select-A */
81289  int regLimitB;        /* Limit register for select-A */
81290  int regPrev;          /* A range of registers to hold previous output */
81291  int savedLimit;       /* Saved value of p->iLimit */
81292  int savedOffset;      /* Saved value of p->iOffset */
81293  int labelCmpr;        /* Label for the start of the merge algorithm */
81294  int labelEnd;         /* Label for the end of the overall SELECT stmt */
81295  int j1;               /* Jump instructions that get retargetted */
81296  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
81297  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
81298  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
81299  sqlite3 *db;          /* Database connection */
81300  ExprList *pOrderBy;   /* The ORDER BY clause */
81301  int nOrderBy;         /* Number of terms in the ORDER BY clause */
81302  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
81303
81304  assert( p->pOrderBy!=0 );
81305  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
81306  db = pParse->db;
81307  v = pParse->pVdbe;
81308  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
81309  labelEnd = sqlite3VdbeMakeLabel(v);
81310  labelCmpr = sqlite3VdbeMakeLabel(v);
81311
81312
81313  /* Patch up the ORDER BY clause
81314  */
81315  op = p->op;
81316  pPrior = p->pPrior;
81317  assert( pPrior->pOrderBy==0 );
81318  pOrderBy = p->pOrderBy;
81319  assert( pOrderBy );
81320  nOrderBy = pOrderBy->nExpr;
81321
81322  /* For operators other than UNION ALL we have to make sure that
81323  ** the ORDER BY clause covers every term of the result set.  Add
81324  ** terms to the ORDER BY clause as necessary.
81325  */
81326  if( op!=TK_ALL ){
81327    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
81328      struct ExprList_item *pItem;
81329      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
81330        assert( pItem->iCol>0 );
81331        if( pItem->iCol==i ) break;
81332      }
81333      if( j==nOrderBy ){
81334        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
81335        if( pNew==0 ) return SQLITE_NOMEM;
81336        pNew->flags |= EP_IntValue;
81337        pNew->u.iValue = i;
81338        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
81339        pOrderBy->a[nOrderBy++].iCol = (u16)i;
81340      }
81341    }
81342  }
81343
81344  /* Compute the comparison permutation and keyinfo that is used with
81345  ** the permutation used to determine if the next
81346  ** row of results comes from selectA or selectB.  Also add explicit
81347  ** collations to the ORDER BY clause terms so that when the subqueries
81348  ** to the right and the left are evaluated, they use the correct
81349  ** collation.
81350  */
81351  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
81352  if( aPermute ){
81353    struct ExprList_item *pItem;
81354    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
81355      assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
81356      aPermute[i] = pItem->iCol - 1;
81357    }
81358    pKeyMerge =
81359      sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
81360    if( pKeyMerge ){
81361      pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
81362      pKeyMerge->nField = (u16)nOrderBy;
81363      pKeyMerge->enc = ENC(db);
81364      for(i=0; i<nOrderBy; i++){
81365        CollSeq *pColl;
81366        Expr *pTerm = pOrderBy->a[i].pExpr;
81367        if( pTerm->flags & EP_ExpCollate ){
81368          pColl = pTerm->pColl;
81369        }else{
81370          pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
81371          pTerm->flags |= EP_ExpCollate;
81372          pTerm->pColl = pColl;
81373        }
81374        pKeyMerge->aColl[i] = pColl;
81375        pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
81376      }
81377    }
81378  }else{
81379    pKeyMerge = 0;
81380  }
81381
81382  /* Reattach the ORDER BY clause to the query.
81383  */
81384  p->pOrderBy = pOrderBy;
81385  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
81386
81387  /* Allocate a range of temporary registers and the KeyInfo needed
81388  ** for the logic that removes duplicate result rows when the
81389  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
81390  */
81391  if( op==TK_ALL ){
81392    regPrev = 0;
81393  }else{
81394    int nExpr = p->pEList->nExpr;
81395    assert( nOrderBy>=nExpr || db->mallocFailed );
81396    regPrev = sqlite3GetTempRange(pParse, nExpr+1);
81397    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
81398    pKeyDup = sqlite3DbMallocZero(db,
81399                  sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
81400    if( pKeyDup ){
81401      pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
81402      pKeyDup->nField = (u16)nExpr;
81403      pKeyDup->enc = ENC(db);
81404      for(i=0; i<nExpr; i++){
81405        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
81406        pKeyDup->aSortOrder[i] = 0;
81407      }
81408    }
81409  }
81410
81411  /* Separate the left and the right query from one another
81412  */
81413  p->pPrior = 0;
81414  pPrior->pRightmost = 0;
81415  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
81416  if( pPrior->pPrior==0 ){
81417    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
81418  }
81419
81420  /* Compute the limit registers */
81421  computeLimitRegisters(pParse, p, labelEnd);
81422  if( p->iLimit && op==TK_ALL ){
81423    regLimitA = ++pParse->nMem;
81424    regLimitB = ++pParse->nMem;
81425    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
81426                                  regLimitA);
81427    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
81428  }else{
81429    regLimitA = regLimitB = 0;
81430  }
81431  sqlite3ExprDelete(db, p->pLimit);
81432  p->pLimit = 0;
81433  sqlite3ExprDelete(db, p->pOffset);
81434  p->pOffset = 0;
81435
81436  regAddrA = ++pParse->nMem;
81437  regEofA = ++pParse->nMem;
81438  regAddrB = ++pParse->nMem;
81439  regEofB = ++pParse->nMem;
81440  regOutA = ++pParse->nMem;
81441  regOutB = ++pParse->nMem;
81442  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
81443  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
81444
81445  /* Jump past the various subroutines and coroutines to the main
81446  ** merge loop
81447  */
81448  j1 = sqlite3VdbeAddOp0(v, OP_Goto);
81449  addrSelectA = sqlite3VdbeCurrentAddr(v);
81450
81451
81452  /* Generate a coroutine to evaluate the SELECT statement to the
81453  ** left of the compound operator - the "A" select.
81454  */
81455  VdbeNoopComment((v, "Begin coroutine for left SELECT"));
81456  pPrior->iLimit = regLimitA;
81457  sqlite3Select(pParse, pPrior, &destA);
81458  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
81459  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81460  VdbeNoopComment((v, "End coroutine for left SELECT"));
81461
81462  /* Generate a coroutine to evaluate the SELECT statement on
81463  ** the right - the "B" select
81464  */
81465  addrSelectB = sqlite3VdbeCurrentAddr(v);
81466  VdbeNoopComment((v, "Begin coroutine for right SELECT"));
81467  savedLimit = p->iLimit;
81468  savedOffset = p->iOffset;
81469  p->iLimit = regLimitB;
81470  p->iOffset = 0;
81471  sqlite3Select(pParse, p, &destB);
81472  p->iLimit = savedLimit;
81473  p->iOffset = savedOffset;
81474  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
81475  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
81476  VdbeNoopComment((v, "End coroutine for right SELECT"));
81477
81478  /* Generate a subroutine that outputs the current row of the A
81479  ** select as the next output row of the compound select.
81480  */
81481  VdbeNoopComment((v, "Output routine for A"));
81482  addrOutA = generateOutputSubroutine(pParse,
81483                 p, &destA, pDest, regOutA,
81484                 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
81485
81486  /* Generate a subroutine that outputs the current row of the B
81487  ** select as the next output row of the compound select.
81488  */
81489  if( op==TK_ALL || op==TK_UNION ){
81490    VdbeNoopComment((v, "Output routine for B"));
81491    addrOutB = generateOutputSubroutine(pParse,
81492                 p, &destB, pDest, regOutB,
81493                 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
81494  }
81495
81496  /* Generate a subroutine to run when the results from select A
81497  ** are exhausted and only data in select B remains.
81498  */
81499  VdbeNoopComment((v, "eof-A subroutine"));
81500  if( op==TK_EXCEPT || op==TK_INTERSECT ){
81501    addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
81502  }else{
81503    addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
81504    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
81505    sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
81506    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
81507  }
81508
81509  /* Generate a subroutine to run when the results from select B
81510  ** are exhausted and only data in select A remains.
81511  */
81512  if( op==TK_INTERSECT ){
81513    addrEofB = addrEofA;
81514  }else{
81515    VdbeNoopComment((v, "eof-B subroutine"));
81516    addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
81517    sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
81518    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81519    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
81520  }
81521
81522  /* Generate code to handle the case of A<B
81523  */
81524  VdbeNoopComment((v, "A-lt-B subroutine"));
81525  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
81526  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81527  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
81528  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
81529
81530  /* Generate code to handle the case of A==B
81531  */
81532  if( op==TK_ALL ){
81533    addrAeqB = addrAltB;
81534  }else if( op==TK_INTERSECT ){
81535    addrAeqB = addrAltB;
81536    addrAltB++;
81537  }else{
81538    VdbeNoopComment((v, "A-eq-B subroutine"));
81539    addrAeqB =
81540    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81541    sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
81542    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
81543  }
81544
81545  /* Generate code to handle the case of A>B
81546  */
81547  VdbeNoopComment((v, "A-gt-B subroutine"));
81548  addrAgtB = sqlite3VdbeCurrentAddr(v);
81549  if( op==TK_ALL || op==TK_UNION ){
81550    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
81551  }
81552  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
81553  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
81554  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
81555
81556  /* This code runs once to initialize everything.
81557  */
81558  sqlite3VdbeJumpHere(v, j1);
81559  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
81560  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
81561  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
81562  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
81563  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
81564  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
81565
81566  /* Implement the main merge loop
81567  */
81568  sqlite3VdbeResolveLabel(v, labelCmpr);
81569  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
81570  sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
81571                         (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
81572  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
81573
81574  /* Release temporary registers
81575  */
81576  if( regPrev ){
81577    sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
81578  }
81579
81580  /* Jump to the this point in order to terminate the query.
81581  */
81582  sqlite3VdbeResolveLabel(v, labelEnd);
81583
81584  /* Set the number of output columns
81585  */
81586  if( pDest->eDest==SRT_Output ){
81587    Select *pFirst = pPrior;
81588    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
81589    generateColumnNames(pParse, 0, pFirst->pEList);
81590  }
81591
81592  /* Reassembly the compound query so that it will be freed correctly
81593  ** by the calling function */
81594  if( p->pPrior ){
81595    sqlite3SelectDelete(db, p->pPrior);
81596  }
81597  p->pPrior = pPrior;
81598
81599  /*** TBD:  Insert subroutine calls to close cursors on incomplete
81600  **** subqueries ****/
81601  return SQLITE_OK;
81602}
81603#endif
81604
81605#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
81606/* Forward Declarations */
81607static void substExprList(sqlite3*, ExprList*, int, ExprList*);
81608static void substSelect(sqlite3*, Select *, int, ExprList *);
81609
81610/*
81611** Scan through the expression pExpr.  Replace every reference to
81612** a column in table number iTable with a copy of the iColumn-th
81613** entry in pEList.  (But leave references to the ROWID column
81614** unchanged.)
81615**
81616** This routine is part of the flattening procedure.  A subquery
81617** whose result set is defined by pEList appears as entry in the
81618** FROM clause of a SELECT such that the VDBE cursor assigned to that
81619** FORM clause entry is iTable.  This routine make the necessary
81620** changes to pExpr so that it refers directly to the source table
81621** of the subquery rather the result set of the subquery.
81622*/
81623static Expr *substExpr(
81624  sqlite3 *db,        /* Report malloc errors to this connection */
81625  Expr *pExpr,        /* Expr in which substitution occurs */
81626  int iTable,         /* Table to be substituted */
81627  ExprList *pEList    /* Substitute expressions */
81628){
81629  if( pExpr==0 ) return 0;
81630  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
81631    if( pExpr->iColumn<0 ){
81632      pExpr->op = TK_NULL;
81633    }else{
81634      Expr *pNew;
81635      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
81636      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
81637      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
81638      if( pNew && pExpr->pColl ){
81639        pNew->pColl = pExpr->pColl;
81640      }
81641      sqlite3ExprDelete(db, pExpr);
81642      pExpr = pNew;
81643    }
81644  }else{
81645    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
81646    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
81647    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
81648      substSelect(db, pExpr->x.pSelect, iTable, pEList);
81649    }else{
81650      substExprList(db, pExpr->x.pList, iTable, pEList);
81651    }
81652  }
81653  return pExpr;
81654}
81655static void substExprList(
81656  sqlite3 *db,         /* Report malloc errors here */
81657  ExprList *pList,     /* List to scan and in which to make substitutes */
81658  int iTable,          /* Table to be substituted */
81659  ExprList *pEList     /* Substitute values */
81660){
81661  int i;
81662  if( pList==0 ) return;
81663  for(i=0; i<pList->nExpr; i++){
81664    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
81665  }
81666}
81667static void substSelect(
81668  sqlite3 *db,         /* Report malloc errors here */
81669  Select *p,           /* SELECT statement in which to make substitutions */
81670  int iTable,          /* Table to be replaced */
81671  ExprList *pEList     /* Substitute values */
81672){
81673  SrcList *pSrc;
81674  struct SrcList_item *pItem;
81675  int i;
81676  if( !p ) return;
81677  substExprList(db, p->pEList, iTable, pEList);
81678  substExprList(db, p->pGroupBy, iTable, pEList);
81679  substExprList(db, p->pOrderBy, iTable, pEList);
81680  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
81681  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
81682  substSelect(db, p->pPrior, iTable, pEList);
81683  pSrc = p->pSrc;
81684  assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
81685  if( ALWAYS(pSrc) ){
81686    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
81687      substSelect(db, pItem->pSelect, iTable, pEList);
81688    }
81689  }
81690}
81691#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
81692
81693#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
81694/*
81695** This routine attempts to flatten subqueries in order to speed
81696** execution.  It returns 1 if it makes changes and 0 if no flattening
81697** occurs.
81698**
81699** To understand the concept of flattening, consider the following
81700** query:
81701**
81702**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
81703**
81704** The default way of implementing this query is to execute the
81705** subquery first and store the results in a temporary table, then
81706** run the outer query on that temporary table.  This requires two
81707** passes over the data.  Furthermore, because the temporary table
81708** has no indices, the WHERE clause on the outer query cannot be
81709** optimized.
81710**
81711** This routine attempts to rewrite queries such as the above into
81712** a single flat select, like this:
81713**
81714**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
81715**
81716** The code generated for this simpification gives the same result
81717** but only has to scan the data once.  And because indices might
81718** exist on the table t1, a complete scan of the data might be
81719** avoided.
81720**
81721** Flattening is only attempted if all of the following are true:
81722**
81723**   (1)  The subquery and the outer query do not both use aggregates.
81724**
81725**   (2)  The subquery is not an aggregate or the outer query is not a join.
81726**
81727**   (3)  The subquery is not the right operand of a left outer join
81728**        (Originally ticket #306.  Strenghtened by ticket #3300)
81729**
81730**   (4)  The subquery is not DISTINCT or the outer query is not a join.
81731**
81732**   (5)  The subquery is not DISTINCT or the outer query does not use
81733**        aggregates.
81734**
81735**   (6)  The subquery does not use aggregates or the outer query is not
81736**        DISTINCT.
81737**
81738**   (7)  The subquery has a FROM clause.
81739**
81740**   (8)  The subquery does not use LIMIT or the outer query is not a join.
81741**
81742**   (9)  The subquery does not use LIMIT or the outer query does not use
81743**        aggregates.
81744**
81745**  (10)  The subquery does not use aggregates or the outer query does not
81746**        use LIMIT.
81747**
81748**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
81749**
81750**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
81751**        a separate restriction deriving from ticket #350.
81752**
81753**  (13)  The subquery and outer query do not both use LIMIT
81754**
81755**  (14)  The subquery does not use OFFSET
81756**
81757**  (15)  The outer query is not part of a compound select or the
81758**        subquery does not have both an ORDER BY and a LIMIT clause.
81759**        (See ticket #2339)
81760**
81761**  (16)  The outer query is not an aggregate or the subquery does
81762**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
81763**        until we introduced the group_concat() function.
81764**
81765**  (17)  The sub-query is not a compound select, or it is a UNION ALL
81766**        compound clause made up entirely of non-aggregate queries, and
81767**        the parent query:
81768**
81769**          * is not itself part of a compound select,
81770**          * is not an aggregate or DISTINCT query, and
81771**          * has no other tables or sub-selects in the FROM clause.
81772**
81773**        The parent and sub-query may contain WHERE clauses. Subject to
81774**        rules (11), (13) and (14), they may also contain ORDER BY,
81775**        LIMIT and OFFSET clauses.
81776**
81777**  (18)  If the sub-query is a compound select, then all terms of the
81778**        ORDER by clause of the parent must be simple references to
81779**        columns of the sub-query.
81780**
81781**  (19)  The subquery does not use LIMIT or the outer query does not
81782**        have a WHERE clause.
81783**
81784**  (20)  If the sub-query is a compound select, then it must not use
81785**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
81786**        somewhat by saying that the terms of the ORDER BY clause must
81787**        appear as unmodified result columns in the outer query.  But
81788**        have other optimizations in mind to deal with that case.
81789**
81790** In this routine, the "p" parameter is a pointer to the outer query.
81791** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
81792** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
81793**
81794** If flattening is not attempted, this routine is a no-op and returns 0.
81795** If flattening is attempted this routine returns 1.
81796**
81797** All of the expression analysis must occur on both the outer query and
81798** the subquery before this routine runs.
81799*/
81800static int flattenSubquery(
81801  Parse *pParse,       /* Parsing context */
81802  Select *p,           /* The parent or outer SELECT statement */
81803  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
81804  int isAgg,           /* True if outer SELECT uses aggregate functions */
81805  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
81806){
81807  const char *zSavedAuthContext = pParse->zAuthContext;
81808  Select *pParent;
81809  Select *pSub;       /* The inner query or "subquery" */
81810  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
81811  SrcList *pSrc;      /* The FROM clause of the outer query */
81812  SrcList *pSubSrc;   /* The FROM clause of the subquery */
81813  ExprList *pList;    /* The result set of the outer query */
81814  int iParent;        /* VDBE cursor number of the pSub result set temp table */
81815  int i;              /* Loop counter */
81816  Expr *pWhere;                    /* The WHERE clause */
81817  struct SrcList_item *pSubitem;   /* The subquery */
81818  sqlite3 *db = pParse->db;
81819
81820  /* Check to see if flattening is permitted.  Return 0 if not.
81821  */
81822  assert( p!=0 );
81823  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
81824  if( db->flags & SQLITE_QueryFlattener ) return 0;
81825  pSrc = p->pSrc;
81826  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
81827  pSubitem = &pSrc->a[iFrom];
81828  iParent = pSubitem->iCursor;
81829  pSub = pSubitem->pSelect;
81830  assert( pSub!=0 );
81831  if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
81832  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
81833  pSubSrc = pSub->pSrc;
81834  assert( pSubSrc );
81835  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
81836  ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
81837  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
81838  ** became arbitrary expressions, we were forced to add restrictions (13)
81839  ** and (14). */
81840  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
81841  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
81842  if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
81843    return 0;                                            /* Restriction (15) */
81844  }
81845  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
81846  if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit)
81847         && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
81848     return 0;
81849  }
81850  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
81851     return 0;         /* Restriction (6)  */
81852  }
81853  if( p->pOrderBy && pSub->pOrderBy ){
81854     return 0;                                           /* Restriction (11) */
81855  }
81856  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
81857  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
81858
81859  /* OBSOLETE COMMENT 1:
81860  ** Restriction 3:  If the subquery is a join, make sure the subquery is
81861  ** not used as the right operand of an outer join.  Examples of why this
81862  ** is not allowed:
81863  **
81864  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
81865  **
81866  ** If we flatten the above, we would get
81867  **
81868  **         (t1 LEFT OUTER JOIN t2) JOIN t3
81869  **
81870  ** which is not at all the same thing.
81871  **
81872  ** OBSOLETE COMMENT 2:
81873  ** Restriction 12:  If the subquery is the right operand of a left outer
81874  ** join, make sure the subquery has no WHERE clause.
81875  ** An examples of why this is not allowed:
81876  **
81877  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
81878  **
81879  ** If we flatten the above, we would get
81880  **
81881  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
81882  **
81883  ** But the t2.x>0 test will always fail on a NULL row of t2, which
81884  ** effectively converts the OUTER JOIN into an INNER JOIN.
81885  **
81886  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
81887  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
81888  ** is fraught with danger.  Best to avoid the whole thing.  If the
81889  ** subquery is the right term of a LEFT JOIN, then do not flatten.
81890  */
81891  if( (pSubitem->jointype & JT_OUTER)!=0 ){
81892    return 0;
81893  }
81894
81895  /* Restriction 17: If the sub-query is a compound SELECT, then it must
81896  ** use only the UNION ALL operator. And none of the simple select queries
81897  ** that make up the compound SELECT are allowed to be aggregate or distinct
81898  ** queries.
81899  */
81900  if( pSub->pPrior ){
81901    if( pSub->pOrderBy ){
81902      return 0;  /* Restriction 20 */
81903    }
81904    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
81905      return 0;
81906    }
81907    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
81908      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
81909      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
81910      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
81911       || (pSub1->pPrior && pSub1->op!=TK_ALL)
81912       || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
81913      ){
81914        return 0;
81915      }
81916    }
81917
81918    /* Restriction 18. */
81919    if( p->pOrderBy ){
81920      int ii;
81921      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
81922        if( p->pOrderBy->a[ii].iCol==0 ) return 0;
81923      }
81924    }
81925  }
81926
81927  /***** If we reach this point, flattening is permitted. *****/
81928
81929  /* Authorize the subquery */
81930  pParse->zAuthContext = pSubitem->zName;
81931  sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
81932  pParse->zAuthContext = zSavedAuthContext;
81933
81934  /* If the sub-query is a compound SELECT statement, then (by restrictions
81935  ** 17 and 18 above) it must be a UNION ALL and the parent query must
81936  ** be of the form:
81937  **
81938  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
81939  **
81940  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
81941  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
81942  ** OFFSET clauses and joins them to the left-hand-side of the original
81943  ** using UNION ALL operators. In this case N is the number of simple
81944  ** select statements in the compound sub-query.
81945  **
81946  ** Example:
81947  **
81948  **     SELECT a+1 FROM (
81949  **        SELECT x FROM tab
81950  **        UNION ALL
81951  **        SELECT y FROM tab
81952  **        UNION ALL
81953  **        SELECT abs(z*2) FROM tab2
81954  **     ) WHERE a!=5 ORDER BY 1
81955  **
81956  ** Transformed into:
81957  **
81958  **     SELECT x+1 FROM tab WHERE x+1!=5
81959  **     UNION ALL
81960  **     SELECT y+1 FROM tab WHERE y+1!=5
81961  **     UNION ALL
81962  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
81963  **     ORDER BY 1
81964  **
81965  ** We call this the "compound-subquery flattening".
81966  */
81967  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
81968    Select *pNew;
81969    ExprList *pOrderBy = p->pOrderBy;
81970    Expr *pLimit = p->pLimit;
81971    Select *pPrior = p->pPrior;
81972    p->pOrderBy = 0;
81973    p->pSrc = 0;
81974    p->pPrior = 0;
81975    p->pLimit = 0;
81976    pNew = sqlite3SelectDup(db, p, 0);
81977    p->pLimit = pLimit;
81978    p->pOrderBy = pOrderBy;
81979    p->pSrc = pSrc;
81980    p->op = TK_ALL;
81981    p->pRightmost = 0;
81982    if( pNew==0 ){
81983      pNew = pPrior;
81984    }else{
81985      pNew->pPrior = pPrior;
81986      pNew->pRightmost = 0;
81987    }
81988    p->pPrior = pNew;
81989    if( db->mallocFailed ) return 1;
81990  }
81991
81992  /* Begin flattening the iFrom-th entry of the FROM clause
81993  ** in the outer query.
81994  */
81995  pSub = pSub1 = pSubitem->pSelect;
81996
81997  /* Delete the transient table structure associated with the
81998  ** subquery
81999  */
82000  sqlite3DbFree(db, pSubitem->zDatabase);
82001  sqlite3DbFree(db, pSubitem->zName);
82002  sqlite3DbFree(db, pSubitem->zAlias);
82003  pSubitem->zDatabase = 0;
82004  pSubitem->zName = 0;
82005  pSubitem->zAlias = 0;
82006  pSubitem->pSelect = 0;
82007
82008  /* Defer deleting the Table object associated with the
82009  ** subquery until code generation is
82010  ** complete, since there may still exist Expr.pTab entries that
82011  ** refer to the subquery even after flattening.  Ticket #3346.
82012  **
82013  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
82014  */
82015  if( ALWAYS(pSubitem->pTab!=0) ){
82016    Table *pTabToDel = pSubitem->pTab;
82017    if( pTabToDel->nRef==1 ){
82018      Parse *pToplevel = sqlite3ParseToplevel(pParse);
82019      pTabToDel->pNextZombie = pToplevel->pZombieTab;
82020      pToplevel->pZombieTab = pTabToDel;
82021    }else{
82022      pTabToDel->nRef--;
82023    }
82024    pSubitem->pTab = 0;
82025  }
82026
82027  /* The following loop runs once for each term in a compound-subquery
82028  ** flattening (as described above).  If we are doing a different kind
82029  ** of flattening - a flattening other than a compound-subquery flattening -
82030  ** then this loop only runs once.
82031  **
82032  ** This loop moves all of the FROM elements of the subquery into the
82033  ** the FROM clause of the outer query.  Before doing this, remember
82034  ** the cursor number for the original outer query FROM element in
82035  ** iParent.  The iParent cursor will never be used.  Subsequent code
82036  ** will scan expressions looking for iParent references and replace
82037  ** those references with expressions that resolve to the subquery FROM
82038  ** elements we are now copying in.
82039  */
82040  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
82041    int nSubSrc;
82042    u8 jointype = 0;
82043    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
82044    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
82045    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
82046
82047    if( pSrc ){
82048      assert( pParent==p );  /* First time through the loop */
82049      jointype = pSubitem->jointype;
82050    }else{
82051      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
82052      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
82053      if( pSrc==0 ){
82054        assert( db->mallocFailed );
82055        break;
82056      }
82057    }
82058
82059    /* The subquery uses a single slot of the FROM clause of the outer
82060    ** query.  If the subquery has more than one element in its FROM clause,
82061    ** then expand the outer query to make space for it to hold all elements
82062    ** of the subquery.
82063    **
82064    ** Example:
82065    **
82066    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
82067    **
82068    ** The outer query has 3 slots in its FROM clause.  One slot of the
82069    ** outer query (the middle slot) is used by the subquery.  The next
82070    ** block of code will expand the out query to 4 slots.  The middle
82071    ** slot is expanded to two slots in order to make space for the
82072    ** two elements in the FROM clause of the subquery.
82073    */
82074    if( nSubSrc>1 ){
82075      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
82076      if( db->mallocFailed ){
82077        break;
82078      }
82079    }
82080
82081    /* Transfer the FROM clause terms from the subquery into the
82082    ** outer query.
82083    */
82084    for(i=0; i<nSubSrc; i++){
82085      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
82086      pSrc->a[i+iFrom] = pSubSrc->a[i];
82087      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
82088    }
82089    pSrc->a[iFrom].jointype = jointype;
82090
82091    /* Now begin substituting subquery result set expressions for
82092    ** references to the iParent in the outer query.
82093    **
82094    ** Example:
82095    **
82096    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
82097    **   \                     \_____________ subquery __________/          /
82098    **    \_____________________ outer query ______________________________/
82099    **
82100    ** We look at every expression in the outer query and every place we see
82101    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
82102    */
82103    pList = pParent->pEList;
82104    for(i=0; i<pList->nExpr; i++){
82105      if( pList->a[i].zName==0 ){
82106        const char *zSpan = pList->a[i].zSpan;
82107        if( ALWAYS(zSpan) ){
82108          pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
82109        }
82110      }
82111    }
82112    substExprList(db, pParent->pEList, iParent, pSub->pEList);
82113    if( isAgg ){
82114      substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
82115      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
82116    }
82117    if( pSub->pOrderBy ){
82118      assert( pParent->pOrderBy==0 );
82119      pParent->pOrderBy = pSub->pOrderBy;
82120      pSub->pOrderBy = 0;
82121    }else if( pParent->pOrderBy ){
82122      substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
82123    }
82124    if( pSub->pWhere ){
82125      pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
82126    }else{
82127      pWhere = 0;
82128    }
82129    if( subqueryIsAgg ){
82130      assert( pParent->pHaving==0 );
82131      pParent->pHaving = pParent->pWhere;
82132      pParent->pWhere = pWhere;
82133      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
82134      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
82135                                  sqlite3ExprDup(db, pSub->pHaving, 0));
82136      assert( pParent->pGroupBy==0 );
82137      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
82138    }else{
82139      pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
82140      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
82141    }
82142
82143    /* The flattened query is distinct if either the inner or the
82144    ** outer query is distinct.
82145    */
82146    pParent->selFlags |= pSub->selFlags & SF_Distinct;
82147
82148    /*
82149    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
82150    **
82151    ** One is tempted to try to add a and b to combine the limits.  But this
82152    ** does not work if either limit is negative.
82153    */
82154    if( pSub->pLimit ){
82155      pParent->pLimit = pSub->pLimit;
82156      pSub->pLimit = 0;
82157    }
82158  }
82159
82160  /* Finially, delete what is left of the subquery and return
82161  ** success.
82162  */
82163  sqlite3SelectDelete(db, pSub1);
82164
82165  return 1;
82166}
82167#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
82168
82169/*
82170** Analyze the SELECT statement passed as an argument to see if it
82171** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
82172** it is, or 0 otherwise. At present, a query is considered to be
82173** a min()/max() query if:
82174**
82175**   1. There is a single object in the FROM clause.
82176**
82177**   2. There is a single expression in the result set, and it is
82178**      either min(x) or max(x), where x is a column reference.
82179*/
82180static u8 minMaxQuery(Select *p){
82181  Expr *pExpr;
82182  ExprList *pEList = p->pEList;
82183
82184  if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
82185  pExpr = pEList->a[0].pExpr;
82186  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
82187  if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
82188  pEList = pExpr->x.pList;
82189  if( pEList==0 || pEList->nExpr!=1 ) return 0;
82190  if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
82191  assert( !ExprHasProperty(pExpr, EP_IntValue) );
82192  if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
82193    return WHERE_ORDERBY_MIN;
82194  }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
82195    return WHERE_ORDERBY_MAX;
82196  }
82197  return WHERE_ORDERBY_NORMAL;
82198}
82199
82200/*
82201** The select statement passed as the first argument is an aggregate query.
82202** The second argment is the associated aggregate-info object. This
82203** function tests if the SELECT is of the form:
82204**
82205**   SELECT count(*) FROM <tbl>
82206**
82207** where table is a database table, not a sub-select or view. If the query
82208** does match this pattern, then a pointer to the Table object representing
82209** <tbl> is returned. Otherwise, 0 is returned.
82210*/
82211static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
82212  Table *pTab;
82213  Expr *pExpr;
82214
82215  assert( !p->pGroupBy );
82216
82217  if( p->pWhere || p->pEList->nExpr!=1
82218   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
82219  ){
82220    return 0;
82221  }
82222  pTab = p->pSrc->a[0].pTab;
82223  pExpr = p->pEList->a[0].pExpr;
82224  assert( pTab && !pTab->pSelect && pExpr );
82225
82226  if( IsVirtual(pTab) ) return 0;
82227  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
82228  if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
82229  if( pExpr->flags&EP_Distinct ) return 0;
82230
82231  return pTab;
82232}
82233
82234/*
82235** If the source-list item passed as an argument was augmented with an
82236** INDEXED BY clause, then try to locate the specified index. If there
82237** was such a clause and the named index cannot be found, return
82238** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
82239** pFrom->pIndex and return SQLITE_OK.
82240*/
82241SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
82242  if( pFrom->pTab && pFrom->zIndex ){
82243    Table *pTab = pFrom->pTab;
82244    char *zIndex = pFrom->zIndex;
82245    Index *pIdx;
82246    for(pIdx=pTab->pIndex;
82247        pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
82248        pIdx=pIdx->pNext
82249    );
82250    if( !pIdx ){
82251      sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
82252      return SQLITE_ERROR;
82253    }
82254    pFrom->pIndex = pIdx;
82255  }
82256  return SQLITE_OK;
82257}
82258
82259/*
82260** This routine is a Walker callback for "expanding" a SELECT statement.
82261** "Expanding" means to do the following:
82262**
82263**    (1)  Make sure VDBE cursor numbers have been assigned to every
82264**         element of the FROM clause.
82265**
82266**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
82267**         defines FROM clause.  When views appear in the FROM clause,
82268**         fill pTabList->a[].pSelect with a copy of the SELECT statement
82269**         that implements the view.  A copy is made of the view's SELECT
82270**         statement so that we can freely modify or delete that statement
82271**         without worrying about messing up the presistent representation
82272**         of the view.
82273**
82274**    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
82275**         on joins and the ON and USING clause of joins.
82276**
82277**    (4)  Scan the list of columns in the result set (pEList) looking
82278**         for instances of the "*" operator or the TABLE.* operator.
82279**         If found, expand each "*" to be every column in every table
82280**         and TABLE.* to be every column in TABLE.
82281**
82282*/
82283static int selectExpander(Walker *pWalker, Select *p){
82284  Parse *pParse = pWalker->pParse;
82285  int i, j, k;
82286  SrcList *pTabList;
82287  ExprList *pEList;
82288  struct SrcList_item *pFrom;
82289  sqlite3 *db = pParse->db;
82290
82291  if( db->mallocFailed  ){
82292    return WRC_Abort;
82293  }
82294  if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
82295    return WRC_Prune;
82296  }
82297  p->selFlags |= SF_Expanded;
82298  pTabList = p->pSrc;
82299  pEList = p->pEList;
82300
82301  /* Make sure cursor numbers have been assigned to all entries in
82302  ** the FROM clause of the SELECT statement.
82303  */
82304  sqlite3SrcListAssignCursors(pParse, pTabList);
82305
82306  /* Look up every table named in the FROM clause of the select.  If
82307  ** an entry of the FROM clause is a subquery instead of a table or view,
82308  ** then create a transient table structure to describe the subquery.
82309  */
82310  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
82311    Table *pTab;
82312    if( pFrom->pTab!=0 ){
82313      /* This statement has already been prepared.  There is no need
82314      ** to go further. */
82315      assert( i==0 );
82316      return WRC_Prune;
82317    }
82318    if( pFrom->zName==0 ){
82319#ifndef SQLITE_OMIT_SUBQUERY
82320      Select *pSel = pFrom->pSelect;
82321      /* A sub-query in the FROM clause of a SELECT */
82322      assert( pSel!=0 );
82323      assert( pFrom->pTab==0 );
82324      sqlite3WalkSelect(pWalker, pSel);
82325      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
82326      if( pTab==0 ) return WRC_Abort;
82327      pTab->dbMem = db->lookaside.bEnabled ? db : 0;
82328      pTab->nRef = 1;
82329      pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
82330      while( pSel->pPrior ){ pSel = pSel->pPrior; }
82331      selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
82332      pTab->iPKey = -1;
82333      pTab->tabFlags |= TF_Ephemeral;
82334#endif
82335    }else{
82336      /* An ordinary table or view name in the FROM clause */
82337      assert( pFrom->pTab==0 );
82338      pFrom->pTab = pTab =
82339        sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
82340      if( pTab==0 ) return WRC_Abort;
82341      pTab->nRef++;
82342#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
82343      if( pTab->pSelect || IsVirtual(pTab) ){
82344        /* We reach here if the named table is a really a view */
82345        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
82346        assert( pFrom->pSelect==0 );
82347        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
82348        sqlite3WalkSelect(pWalker, pFrom->pSelect);
82349      }
82350#endif
82351    }
82352
82353    /* Locate the index named by the INDEXED BY clause, if any. */
82354    if( sqlite3IndexedByLookup(pParse, pFrom) ){
82355      return WRC_Abort;
82356    }
82357  }
82358
82359  /* Process NATURAL keywords, and ON and USING clauses of joins.
82360  */
82361  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
82362    return WRC_Abort;
82363  }
82364
82365  /* For every "*" that occurs in the column list, insert the names of
82366  ** all columns in all tables.  And for every TABLE.* insert the names
82367  ** of all columns in TABLE.  The parser inserted a special expression
82368  ** with the TK_ALL operator for each "*" that it found in the column list.
82369  ** The following code just has to locate the TK_ALL expressions and expand
82370  ** each one to the list of all columns in all tables.
82371  **
82372  ** The first loop just checks to see if there are any "*" operators
82373  ** that need expanding.
82374  */
82375  for(k=0; k<pEList->nExpr; k++){
82376    Expr *pE = pEList->a[k].pExpr;
82377    if( pE->op==TK_ALL ) break;
82378    assert( pE->op!=TK_DOT || pE->pRight!=0 );
82379    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
82380    if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
82381  }
82382  if( k<pEList->nExpr ){
82383    /*
82384    ** If we get here it means the result set contains one or more "*"
82385    ** operators that need to be expanded.  Loop through each expression
82386    ** in the result set and expand them one by one.
82387    */
82388    struct ExprList_item *a = pEList->a;
82389    ExprList *pNew = 0;
82390    int flags = pParse->db->flags;
82391    int longNames = (flags & SQLITE_FullColNames)!=0
82392                      && (flags & SQLITE_ShortColNames)==0;
82393
82394    for(k=0; k<pEList->nExpr; k++){
82395      Expr *pE = a[k].pExpr;
82396      assert( pE->op!=TK_DOT || pE->pRight!=0 );
82397      if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
82398        /* This particular expression does not need to be expanded.
82399        */
82400        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
82401        if( pNew ){
82402          pNew->a[pNew->nExpr-1].zName = a[k].zName;
82403          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
82404          a[k].zName = 0;
82405          a[k].zSpan = 0;
82406        }
82407        a[k].pExpr = 0;
82408      }else{
82409        /* This expression is a "*" or a "TABLE.*" and needs to be
82410        ** expanded. */
82411        int tableSeen = 0;      /* Set to 1 when TABLE matches */
82412        char *zTName;            /* text of name of TABLE */
82413        if( pE->op==TK_DOT ){
82414          assert( pE->pLeft!=0 );
82415          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
82416          zTName = pE->pLeft->u.zToken;
82417        }else{
82418          zTName = 0;
82419        }
82420        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
82421          Table *pTab = pFrom->pTab;
82422          char *zTabName = pFrom->zAlias;
82423          if( zTabName==0 ){
82424            zTabName = pTab->zName;
82425          }
82426          if( db->mallocFailed ) break;
82427          if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
82428            continue;
82429          }
82430          tableSeen = 1;
82431          for(j=0; j<pTab->nCol; j++){
82432            Expr *pExpr, *pRight;
82433            char *zName = pTab->aCol[j].zName;
82434            char *zColname;  /* The computed column name */
82435            char *zToFree;   /* Malloced string that needs to be freed */
82436            Token sColname;  /* Computed column name as a token */
82437
82438            /* If a column is marked as 'hidden' (currently only possible
82439            ** for virtual tables), do not include it in the expanded
82440            ** result-set list.
82441            */
82442            if( IsHiddenColumn(&pTab->aCol[j]) ){
82443              assert(IsVirtual(pTab));
82444              continue;
82445            }
82446
82447            if( i>0 && zTName==0 ){
82448              if( (pFrom->jointype & JT_NATURAL)!=0
82449                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
82450              ){
82451                /* In a NATURAL join, omit the join columns from the
82452                ** table to the right of the join */
82453                continue;
82454              }
82455              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
82456                /* In a join with a USING clause, omit columns in the
82457                ** using clause from the table on the right. */
82458                continue;
82459              }
82460            }
82461            pRight = sqlite3Expr(db, TK_ID, zName);
82462            zColname = zName;
82463            zToFree = 0;
82464            if( longNames || pTabList->nSrc>1 ){
82465              Expr *pLeft;
82466              pLeft = sqlite3Expr(db, TK_ID, zTabName);
82467              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
82468              if( longNames ){
82469                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
82470                zToFree = zColname;
82471              }
82472            }else{
82473              pExpr = pRight;
82474            }
82475            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
82476            sColname.z = zColname;
82477            sColname.n = sqlite3Strlen30(zColname);
82478            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
82479            sqlite3DbFree(db, zToFree);
82480          }
82481        }
82482        if( !tableSeen ){
82483          if( zTName ){
82484            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
82485          }else{
82486            sqlite3ErrorMsg(pParse, "no tables specified");
82487          }
82488        }
82489      }
82490    }
82491    sqlite3ExprListDelete(db, pEList);
82492    p->pEList = pNew;
82493  }
82494#if SQLITE_MAX_COLUMN
82495  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
82496    sqlite3ErrorMsg(pParse, "too many columns in result set");
82497  }
82498#endif
82499  return WRC_Continue;
82500}
82501
82502/*
82503** No-op routine for the parse-tree walker.
82504**
82505** When this routine is the Walker.xExprCallback then expression trees
82506** are walked without any actions being taken at each node.  Presumably,
82507** when this routine is used for Walker.xExprCallback then
82508** Walker.xSelectCallback is set to do something useful for every
82509** subquery in the parser tree.
82510*/
82511static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
82512  UNUSED_PARAMETER2(NotUsed, NotUsed2);
82513  return WRC_Continue;
82514}
82515
82516/*
82517** This routine "expands" a SELECT statement and all of its subqueries.
82518** For additional information on what it means to "expand" a SELECT
82519** statement, see the comment on the selectExpand worker callback above.
82520**
82521** Expanding a SELECT statement is the first step in processing a
82522** SELECT statement.  The SELECT statement must be expanded before
82523** name resolution is performed.
82524**
82525** If anything goes wrong, an error message is written into pParse.
82526** The calling function can detect the problem by looking at pParse->nErr
82527** and/or pParse->db->mallocFailed.
82528*/
82529static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
82530  Walker w;
82531  w.xSelectCallback = selectExpander;
82532  w.xExprCallback = exprWalkNoop;
82533  w.pParse = pParse;
82534  sqlite3WalkSelect(&w, pSelect);
82535}
82536
82537
82538#ifndef SQLITE_OMIT_SUBQUERY
82539/*
82540** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
82541** interface.
82542**
82543** For each FROM-clause subquery, add Column.zType and Column.zColl
82544** information to the Table structure that represents the result set
82545** of that subquery.
82546**
82547** The Table structure that represents the result set was constructed
82548** by selectExpander() but the type and collation information was omitted
82549** at that point because identifiers had not yet been resolved.  This
82550** routine is called after identifier resolution.
82551*/
82552static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
82553  Parse *pParse;
82554  int i;
82555  SrcList *pTabList;
82556  struct SrcList_item *pFrom;
82557
82558  assert( p->selFlags & SF_Resolved );
82559  assert( (p->selFlags & SF_HasTypeInfo)==0 );
82560  p->selFlags |= SF_HasTypeInfo;
82561  pParse = pWalker->pParse;
82562  pTabList = p->pSrc;
82563  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
82564    Table *pTab = pFrom->pTab;
82565    if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
82566      /* A sub-query in the FROM clause of a SELECT */
82567      Select *pSel = pFrom->pSelect;
82568      assert( pSel );
82569      while( pSel->pPrior ) pSel = pSel->pPrior;
82570      selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
82571    }
82572  }
82573  return WRC_Continue;
82574}
82575#endif
82576
82577
82578/*
82579** This routine adds datatype and collating sequence information to
82580** the Table structures of all FROM-clause subqueries in a
82581** SELECT statement.
82582**
82583** Use this routine after name resolution.
82584*/
82585static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
82586#ifndef SQLITE_OMIT_SUBQUERY
82587  Walker w;
82588  w.xSelectCallback = selectAddSubqueryTypeInfo;
82589  w.xExprCallback = exprWalkNoop;
82590  w.pParse = pParse;
82591  sqlite3WalkSelect(&w, pSelect);
82592#endif
82593}
82594
82595
82596/*
82597** This routine sets of a SELECT statement for processing.  The
82598** following is accomplished:
82599**
82600**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
82601**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
82602**     *  ON and USING clauses are shifted into WHERE statements
82603**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
82604**     *  Identifiers in expression are matched to tables.
82605**
82606** This routine acts recursively on all subqueries within the SELECT.
82607*/
82608SQLITE_PRIVATE void sqlite3SelectPrep(
82609  Parse *pParse,         /* The parser context */
82610  Select *p,             /* The SELECT statement being coded. */
82611  NameContext *pOuterNC  /* Name context for container */
82612){
82613  sqlite3 *db;
82614  if( NEVER(p==0) ) return;
82615  db = pParse->db;
82616  if( p->selFlags & SF_HasTypeInfo ) return;
82617  sqlite3SelectExpand(pParse, p);
82618  if( pParse->nErr || db->mallocFailed ) return;
82619  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
82620  if( pParse->nErr || db->mallocFailed ) return;
82621  sqlite3SelectAddTypeInfo(pParse, p);
82622}
82623
82624/*
82625** Reset the aggregate accumulator.
82626**
82627** The aggregate accumulator is a set of memory cells that hold
82628** intermediate results while calculating an aggregate.  This
82629** routine simply stores NULLs in all of those memory cells.
82630*/
82631static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
82632  Vdbe *v = pParse->pVdbe;
82633  int i;
82634  struct AggInfo_func *pFunc;
82635  if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
82636    return;
82637  }
82638  for(i=0; i<pAggInfo->nColumn; i++){
82639    sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
82640  }
82641  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
82642    sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
82643    if( pFunc->iDistinct>=0 ){
82644      Expr *pE = pFunc->pExpr;
82645      assert( !ExprHasProperty(pE, EP_xIsSelect) );
82646      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
82647        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
82648           "argument");
82649        pFunc->iDistinct = -1;
82650      }else{
82651        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
82652        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
82653                          (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82654      }
82655    }
82656  }
82657}
82658
82659/*
82660** Invoke the OP_AggFinalize opcode for every aggregate function
82661** in the AggInfo structure.
82662*/
82663static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
82664  Vdbe *v = pParse->pVdbe;
82665  int i;
82666  struct AggInfo_func *pF;
82667  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
82668    ExprList *pList = pF->pExpr->x.pList;
82669    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
82670    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
82671                      (void*)pF->pFunc, P4_FUNCDEF);
82672  }
82673}
82674
82675/*
82676** Update the accumulator memory cells for an aggregate based on
82677** the current cursor position.
82678*/
82679static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
82680  Vdbe *v = pParse->pVdbe;
82681  int i;
82682  struct AggInfo_func *pF;
82683  struct AggInfo_col *pC;
82684
82685  pAggInfo->directMode = 1;
82686  sqlite3ExprCacheClear(pParse);
82687  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
82688    int nArg;
82689    int addrNext = 0;
82690    int regAgg;
82691    ExprList *pList = pF->pExpr->x.pList;
82692    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
82693    if( pList ){
82694      nArg = pList->nExpr;
82695      regAgg = sqlite3GetTempRange(pParse, nArg);
82696      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
82697    }else{
82698      nArg = 0;
82699      regAgg = 0;
82700    }
82701    if( pF->iDistinct>=0 ){
82702      addrNext = sqlite3VdbeMakeLabel(v);
82703      assert( nArg==1 );
82704      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
82705    }
82706    if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
82707      CollSeq *pColl = 0;
82708      struct ExprList_item *pItem;
82709      int j;
82710      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
82711      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
82712        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
82713      }
82714      if( !pColl ){
82715        pColl = pParse->db->pDfltColl;
82716      }
82717      sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
82718    }
82719    sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
82720                      (void*)pF->pFunc, P4_FUNCDEF);
82721    sqlite3VdbeChangeP5(v, (u8)nArg);
82722    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
82723    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
82724    if( addrNext ){
82725      sqlite3VdbeResolveLabel(v, addrNext);
82726      sqlite3ExprCacheClear(pParse);
82727    }
82728  }
82729  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
82730    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
82731  }
82732  pAggInfo->directMode = 0;
82733  sqlite3ExprCacheClear(pParse);
82734}
82735
82736/*
82737** Generate code for the SELECT statement given in the p argument.
82738**
82739** The results are distributed in various ways depending on the
82740** contents of the SelectDest structure pointed to by argument pDest
82741** as follows:
82742**
82743**     pDest->eDest    Result
82744**     ------------    -------------------------------------------
82745**     SRT_Output      Generate a row of output (using the OP_ResultRow
82746**                     opcode) for each row in the result set.
82747**
82748**     SRT_Mem         Only valid if the result is a single column.
82749**                     Store the first column of the first result row
82750**                     in register pDest->iParm then abandon the rest
82751**                     of the query.  This destination implies "LIMIT 1".
82752**
82753**     SRT_Set         The result must be a single column.  Store each
82754**                     row of result as the key in table pDest->iParm.
82755**                     Apply the affinity pDest->affinity before storing
82756**                     results.  Used to implement "IN (SELECT ...)".
82757**
82758**     SRT_Union       Store results as a key in a temporary table pDest->iParm.
82759**
82760**     SRT_Except      Remove results from the temporary table pDest->iParm.
82761**
82762**     SRT_Table       Store results in temporary table pDest->iParm.
82763**                     This is like SRT_EphemTab except that the table
82764**                     is assumed to already be open.
82765**
82766**     SRT_EphemTab    Create an temporary table pDest->iParm and store
82767**                     the result there. The cursor is left open after
82768**                     returning.  This is like SRT_Table except that
82769**                     this destination uses OP_OpenEphemeral to create
82770**                     the table first.
82771**
82772**     SRT_Coroutine   Generate a co-routine that returns a new row of
82773**                     results each time it is invoked.  The entry point
82774**                     of the co-routine is stored in register pDest->iParm.
82775**
82776**     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
82777**                     set is not empty.
82778**
82779**     SRT_Discard     Throw the results away.  This is used by SELECT
82780**                     statements within triggers whose only purpose is
82781**                     the side-effects of functions.
82782**
82783** This routine returns the number of errors.  If any errors are
82784** encountered, then an appropriate error message is left in
82785** pParse->zErrMsg.
82786**
82787** This routine does NOT free the Select structure passed in.  The
82788** calling function needs to do that.
82789*/
82790SQLITE_PRIVATE int sqlite3Select(
82791  Parse *pParse,         /* The parser context */
82792  Select *p,             /* The SELECT statement being coded. */
82793  SelectDest *pDest      /* What to do with the query results */
82794){
82795  int i, j;              /* Loop counters */
82796  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
82797  Vdbe *v;               /* The virtual machine under construction */
82798  int isAgg;             /* True for select lists like "count(*)" */
82799  ExprList *pEList;      /* List of columns to extract. */
82800  SrcList *pTabList;     /* List of tables to select from */
82801  Expr *pWhere;          /* The WHERE clause.  May be NULL */
82802  ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
82803  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
82804  Expr *pHaving;         /* The HAVING clause.  May be NULL */
82805  int isDistinct;        /* True if the DISTINCT keyword is present */
82806  int distinct;          /* Table to use for the distinct set */
82807  int rc = 1;            /* Value to return from this function */
82808  int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
82809  AggInfo sAggInfo;      /* Information used by aggregate queries */
82810  int iEnd;              /* Address of the end of the query */
82811  sqlite3 *db;           /* The database connection */
82812
82813  db = pParse->db;
82814  if( p==0 || db->mallocFailed || pParse->nErr ){
82815    return 1;
82816  }
82817  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
82818  memset(&sAggInfo, 0, sizeof(sAggInfo));
82819
82820  if( IgnorableOrderby(pDest) ){
82821    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
82822           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
82823    /* If ORDER BY makes no difference in the output then neither does
82824    ** DISTINCT so it can be removed too. */
82825    sqlite3ExprListDelete(db, p->pOrderBy);
82826    p->pOrderBy = 0;
82827    p->selFlags &= ~SF_Distinct;
82828  }
82829  sqlite3SelectPrep(pParse, p, 0);
82830  pOrderBy = p->pOrderBy;
82831  pTabList = p->pSrc;
82832  pEList = p->pEList;
82833  if( pParse->nErr || db->mallocFailed ){
82834    goto select_end;
82835  }
82836  isAgg = (p->selFlags & SF_Aggregate)!=0;
82837  assert( pEList!=0 );
82838
82839  /* Begin generating code.
82840  */
82841  v = sqlite3GetVdbe(pParse);
82842  if( v==0 ) goto select_end;
82843
82844  /* Generate code for all sub-queries in the FROM clause
82845  */
82846#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
82847  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
82848    struct SrcList_item *pItem = &pTabList->a[i];
82849    SelectDest dest;
82850    Select *pSub = pItem->pSelect;
82851    int isAggSub;
82852
82853    if( pSub==0 || pItem->isPopulated ) continue;
82854
82855    /* Increment Parse.nHeight by the height of the largest expression
82856    ** tree refered to by this, the parent select. The child select
82857    ** may contain expression trees of at most
82858    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
82859    ** more conservative than necessary, but much easier than enforcing
82860    ** an exact limit.
82861    */
82862    pParse->nHeight += sqlite3SelectExprHeight(p);
82863
82864    /* Check to see if the subquery can be absorbed into the parent. */
82865    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
82866    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
82867      if( isAggSub ){
82868        isAgg = 1;
82869        p->selFlags |= SF_Aggregate;
82870      }
82871      i = -1;
82872    }else{
82873      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
82874      assert( pItem->isPopulated==0 );
82875      sqlite3Select(pParse, pSub, &dest);
82876      pItem->isPopulated = 1;
82877    }
82878    if( /*pParse->nErr ||*/ db->mallocFailed ){
82879      goto select_end;
82880    }
82881    pParse->nHeight -= sqlite3SelectExprHeight(p);
82882    pTabList = p->pSrc;
82883    if( !IgnorableOrderby(pDest) ){
82884      pOrderBy = p->pOrderBy;
82885    }
82886  }
82887  pEList = p->pEList;
82888#endif
82889  pWhere = p->pWhere;
82890  pGroupBy = p->pGroupBy;
82891  pHaving = p->pHaving;
82892  isDistinct = (p->selFlags & SF_Distinct)!=0;
82893
82894#ifndef SQLITE_OMIT_COMPOUND_SELECT
82895  /* If there is are a sequence of queries, do the earlier ones first.
82896  */
82897  if( p->pPrior ){
82898    if( p->pRightmost==0 ){
82899      Select *pLoop, *pRight = 0;
82900      int cnt = 0;
82901      int mxSelect;
82902      for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
82903        pLoop->pRightmost = p;
82904        pLoop->pNext = pRight;
82905        pRight = pLoop;
82906      }
82907      mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
82908      if( mxSelect && cnt>mxSelect ){
82909        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
82910        return 1;
82911      }
82912    }
82913    return multiSelect(pParse, p, pDest);
82914  }
82915#endif
82916
82917  /* If writing to memory or generating a set
82918  ** only a single column may be output.
82919  */
82920#ifndef SQLITE_OMIT_SUBQUERY
82921  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
82922    goto select_end;
82923  }
82924#endif
82925
82926  /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
82927  ** GROUP BY might use an index, DISTINCT never does.
82928  */
82929  assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
82930  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
82931    p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
82932    pGroupBy = p->pGroupBy;
82933    p->selFlags &= ~SF_Distinct;
82934    isDistinct = 0;
82935  }
82936
82937  /* If there is an ORDER BY clause, then this sorting
82938  ** index might end up being unused if the data can be
82939  ** extracted in pre-sorted order.  If that is the case, then the
82940  ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
82941  ** we figure out that the sorting index is not needed.  The addrSortIndex
82942  ** variable is used to facilitate that change.
82943  */
82944  if( pOrderBy ){
82945    KeyInfo *pKeyInfo;
82946    pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
82947    pOrderBy->iECursor = pParse->nTab++;
82948    p->addrOpenEphm[2] = addrSortIndex =
82949      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
82950                           pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
82951                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82952  }else{
82953    addrSortIndex = -1;
82954  }
82955
82956  /* If the output is destined for a temporary table, open that table.
82957  */
82958  if( pDest->eDest==SRT_EphemTab ){
82959    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
82960  }
82961
82962  /* Set the limiter.
82963  */
82964  iEnd = sqlite3VdbeMakeLabel(v);
82965  computeLimitRegisters(pParse, p, iEnd);
82966
82967  /* Open a virtual index to use for the distinct set.
82968  */
82969  if( isDistinct ){
82970    KeyInfo *pKeyInfo;
82971    assert( isAgg || pGroupBy );
82972    distinct = pParse->nTab++;
82973    pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
82974    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
82975                        (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82976  }else{
82977    distinct = -1;
82978  }
82979
82980  /* Aggregate and non-aggregate queries are handled differently */
82981  if( !isAgg && pGroupBy==0 ){
82982    /* This case is for non-aggregate queries
82983    ** Begin the database scan
82984    */
82985    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
82986    if( pWInfo==0 ) goto select_end;
82987
82988    /* If sorting index that was created by a prior OP_OpenEphemeral
82989    ** instruction ended up not being needed, then change the OP_OpenEphemeral
82990    ** into an OP_Noop.
82991    */
82992    if( addrSortIndex>=0 && pOrderBy==0 ){
82993      sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
82994      p->addrOpenEphm[2] = -1;
82995    }
82996
82997    /* Use the standard inner loop
82998    */
82999    assert(!isDistinct);
83000    selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
83001                    pWInfo->iContinue, pWInfo->iBreak);
83002
83003    /* End the database scan loop.
83004    */
83005    sqlite3WhereEnd(pWInfo);
83006  }else{
83007    /* This is the processing for aggregate queries */
83008    NameContext sNC;    /* Name context for processing aggregate information */
83009    int iAMem;          /* First Mem address for storing current GROUP BY */
83010    int iBMem;          /* First Mem address for previous GROUP BY */
83011    int iUseFlag;       /* Mem address holding flag indicating that at least
83012                        ** one row of the input to the aggregator has been
83013                        ** processed */
83014    int iAbortFlag;     /* Mem address which causes query abort if positive */
83015    int groupBySort;    /* Rows come from source in GROUP BY order */
83016    int addrEnd;        /* End of processing for this SELECT */
83017
83018    /* Remove any and all aliases between the result set and the
83019    ** GROUP BY clause.
83020    */
83021    if( pGroupBy ){
83022      int k;                        /* Loop counter */
83023      struct ExprList_item *pItem;  /* For looping over expression in a list */
83024
83025      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
83026        pItem->iAlias = 0;
83027      }
83028      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
83029        pItem->iAlias = 0;
83030      }
83031    }
83032
83033
83034    /* Create a label to jump to when we want to abort the query */
83035    addrEnd = sqlite3VdbeMakeLabel(v);
83036
83037    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
83038    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
83039    ** SELECT statement.
83040    */
83041    memset(&sNC, 0, sizeof(sNC));
83042    sNC.pParse = pParse;
83043    sNC.pSrcList = pTabList;
83044    sNC.pAggInfo = &sAggInfo;
83045    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
83046    sAggInfo.pGroupBy = pGroupBy;
83047    sqlite3ExprAnalyzeAggList(&sNC, pEList);
83048    sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
83049    if( pHaving ){
83050      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
83051    }
83052    sAggInfo.nAccumulator = sAggInfo.nColumn;
83053    for(i=0; i<sAggInfo.nFunc; i++){
83054      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
83055      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
83056    }
83057    if( db->mallocFailed ) goto select_end;
83058
83059    /* Processing for aggregates with GROUP BY is very different and
83060    ** much more complex than aggregates without a GROUP BY.
83061    */
83062    if( pGroupBy ){
83063      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
83064      int j1;             /* A-vs-B comparision jump */
83065      int addrOutputRow;  /* Start of subroutine that outputs a result row */
83066      int regOutputRow;   /* Return address register for output subroutine */
83067      int addrSetAbort;   /* Set the abort flag and return */
83068      int addrTopOfLoop;  /* Top of the input loop */
83069      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
83070      int addrReset;      /* Subroutine for resetting the accumulator */
83071      int regReset;       /* Return address register for reset subroutine */
83072
83073      /* If there is a GROUP BY clause we might need a sorting index to
83074      ** implement it.  Allocate that sorting index now.  If it turns out
83075      ** that we do not need it after all, the OpenEphemeral instruction
83076      ** will be converted into a Noop.
83077      */
83078      sAggInfo.sortingIdx = pParse->nTab++;
83079      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
83080      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
83081          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
83082          0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
83083
83084      /* Initialize memory locations used by GROUP BY aggregate processing
83085      */
83086      iUseFlag = ++pParse->nMem;
83087      iAbortFlag = ++pParse->nMem;
83088      regOutputRow = ++pParse->nMem;
83089      addrOutputRow = sqlite3VdbeMakeLabel(v);
83090      regReset = ++pParse->nMem;
83091      addrReset = sqlite3VdbeMakeLabel(v);
83092      iAMem = pParse->nMem + 1;
83093      pParse->nMem += pGroupBy->nExpr;
83094      iBMem = pParse->nMem + 1;
83095      pParse->nMem += pGroupBy->nExpr;
83096      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
83097      VdbeComment((v, "clear abort flag"));
83098      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
83099      VdbeComment((v, "indicate accumulator empty"));
83100
83101      /* Begin a loop that will extract all source rows in GROUP BY order.
83102      ** This might involve two separate loops with an OP_Sort in between, or
83103      ** it might be a single loop that uses an index to extract information
83104      ** in the right order to begin with.
83105      */
83106      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
83107      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
83108      if( pWInfo==0 ) goto select_end;
83109      if( pGroupBy==0 ){
83110        /* The optimizer is able to deliver rows in group by order so
83111        ** we do not have to sort.  The OP_OpenEphemeral table will be
83112        ** cancelled later because we still need to use the pKeyInfo
83113        */
83114        pGroupBy = p->pGroupBy;
83115        groupBySort = 0;
83116      }else{
83117        /* Rows are coming out in undetermined order.  We have to push
83118        ** each row into a sorting index, terminate the first loop,
83119        ** then loop over the sorting index in order to get the output
83120        ** in sorted order
83121        */
83122        int regBase;
83123        int regRecord;
83124        int nCol;
83125        int nGroupBy;
83126
83127        groupBySort = 1;
83128        nGroupBy = pGroupBy->nExpr;
83129        nCol = nGroupBy + 1;
83130        j = nGroupBy+1;
83131        for(i=0; i<sAggInfo.nColumn; i++){
83132          if( sAggInfo.aCol[i].iSorterColumn>=j ){
83133            nCol++;
83134            j++;
83135          }
83136        }
83137        regBase = sqlite3GetTempRange(pParse, nCol);
83138        sqlite3ExprCacheClear(pParse);
83139        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
83140        sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
83141        j = nGroupBy+1;
83142        for(i=0; i<sAggInfo.nColumn; i++){
83143          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
83144          if( pCol->iSorterColumn>=j ){
83145            int r1 = j + regBase;
83146            int r2;
83147
83148            r2 = sqlite3ExprCodeGetColumn(pParse,
83149                               pCol->pTab, pCol->iColumn, pCol->iTable, r1);
83150            if( r1!=r2 ){
83151              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
83152            }
83153            j++;
83154          }
83155        }
83156        regRecord = sqlite3GetTempReg(pParse);
83157        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
83158        sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
83159        sqlite3ReleaseTempReg(pParse, regRecord);
83160        sqlite3ReleaseTempRange(pParse, regBase, nCol);
83161        sqlite3WhereEnd(pWInfo);
83162        sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
83163        VdbeComment((v, "GROUP BY sort"));
83164        sAggInfo.useSortingIdx = 1;
83165        sqlite3ExprCacheClear(pParse);
83166      }
83167
83168      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
83169      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
83170      ** Then compare the current GROUP BY terms against the GROUP BY terms
83171      ** from the previous row currently stored in a0, a1, a2...
83172      */
83173      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
83174      sqlite3ExprCacheClear(pParse);
83175      for(j=0; j<pGroupBy->nExpr; j++){
83176        if( groupBySort ){
83177          sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
83178        }else{
83179          sAggInfo.directMode = 1;
83180          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
83181        }
83182      }
83183      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
83184                          (char*)pKeyInfo, P4_KEYINFO);
83185      j1 = sqlite3VdbeCurrentAddr(v);
83186      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
83187
83188      /* Generate code that runs whenever the GROUP BY changes.
83189      ** Changes in the GROUP BY are detected by the previous code
83190      ** block.  If there were no changes, this block is skipped.
83191      **
83192      ** This code copies current group by terms in b0,b1,b2,...
83193      ** over to a0,a1,a2.  It then calls the output subroutine
83194      ** and resets the aggregate accumulator registers in preparation
83195      ** for the next GROUP BY batch.
83196      */
83197      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
83198      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
83199      VdbeComment((v, "output one row"));
83200      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
83201      VdbeComment((v, "check abort flag"));
83202      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
83203      VdbeComment((v, "reset accumulator"));
83204
83205      /* Update the aggregate accumulators based on the content of
83206      ** the current row
83207      */
83208      sqlite3VdbeJumpHere(v, j1);
83209      updateAccumulator(pParse, &sAggInfo);
83210      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
83211      VdbeComment((v, "indicate data in accumulator"));
83212
83213      /* End of the loop
83214      */
83215      if( groupBySort ){
83216        sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
83217      }else{
83218        sqlite3WhereEnd(pWInfo);
83219        sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
83220      }
83221
83222      /* Output the final row of result
83223      */
83224      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
83225      VdbeComment((v, "output final row"));
83226
83227      /* Jump over the subroutines
83228      */
83229      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
83230
83231      /* Generate a subroutine that outputs a single row of the result
83232      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
83233      ** is less than or equal to zero, the subroutine is a no-op.  If
83234      ** the processing calls for the query to abort, this subroutine
83235      ** increments the iAbortFlag memory location before returning in
83236      ** order to signal the caller to abort.
83237      */
83238      addrSetAbort = sqlite3VdbeCurrentAddr(v);
83239      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
83240      VdbeComment((v, "set abort flag"));
83241      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
83242      sqlite3VdbeResolveLabel(v, addrOutputRow);
83243      addrOutputRow = sqlite3VdbeCurrentAddr(v);
83244      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
83245      VdbeComment((v, "Groupby result generator entry point"));
83246      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
83247      finalizeAggFunctions(pParse, &sAggInfo);
83248      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
83249      selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
83250                      distinct, pDest,
83251                      addrOutputRow+1, addrSetAbort);
83252      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
83253      VdbeComment((v, "end groupby result generator"));
83254
83255      /* Generate a subroutine that will reset the group-by accumulator
83256      */
83257      sqlite3VdbeResolveLabel(v, addrReset);
83258      resetAccumulator(pParse, &sAggInfo);
83259      sqlite3VdbeAddOp1(v, OP_Return, regReset);
83260
83261    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
83262    else {
83263      ExprList *pDel = 0;
83264#ifndef SQLITE_OMIT_BTREECOUNT
83265      Table *pTab;
83266      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
83267        /* If isSimpleCount() returns a pointer to a Table structure, then
83268        ** the SQL statement is of the form:
83269        **
83270        **   SELECT count(*) FROM <tbl>
83271        **
83272        ** where the Table structure returned represents table <tbl>.
83273        **
83274        ** This statement is so common that it is optimized specially. The
83275        ** OP_Count instruction is executed either on the intkey table that
83276        ** contains the data for table <tbl> or on one of its indexes. It
83277        ** is better to execute the op on an index, as indexes are almost
83278        ** always spread across less pages than their corresponding tables.
83279        */
83280        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
83281        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
83282        Index *pIdx;                         /* Iterator variable */
83283        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
83284        Index *pBest = 0;                    /* Best index found so far */
83285        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
83286
83287        sqlite3CodeVerifySchema(pParse, iDb);
83288        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
83289
83290        /* Search for the index that has the least amount of columns. If
83291        ** there is such an index, and it has less columns than the table
83292        ** does, then we can assume that it consumes less space on disk and
83293        ** will therefore be cheaper to scan to determine the query result.
83294        ** In this case set iRoot to the root page number of the index b-tree
83295        ** and pKeyInfo to the KeyInfo structure required to navigate the
83296        ** index.
83297        **
83298        ** In practice the KeyInfo structure will not be used. It is only
83299        ** passed to keep OP_OpenRead happy.
83300        */
83301        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83302          if( !pBest || pIdx->nColumn<pBest->nColumn ){
83303            pBest = pIdx;
83304          }
83305        }
83306        if( pBest && pBest->nColumn<pTab->nCol ){
83307          iRoot = pBest->tnum;
83308          pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
83309        }
83310
83311        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
83312        sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
83313        if( pKeyInfo ){
83314          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
83315        }
83316        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
83317        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
83318      }else
83319#endif /* SQLITE_OMIT_BTREECOUNT */
83320      {
83321        /* Check if the query is of one of the following forms:
83322        **
83323        **   SELECT min(x) FROM ...
83324        **   SELECT max(x) FROM ...
83325        **
83326        ** If it is, then ask the code in where.c to attempt to sort results
83327        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
83328        ** If where.c is able to produce results sorted in this order, then
83329        ** add vdbe code to break out of the processing loop after the
83330        ** first iteration (since the first iteration of the loop is
83331        ** guaranteed to operate on the row with the minimum or maximum
83332        ** value of x, the only row required).
83333        **
83334        ** A special flag must be passed to sqlite3WhereBegin() to slightly
83335        ** modify behaviour as follows:
83336        **
83337        **   + If the query is a "SELECT min(x)", then the loop coded by
83338        **     where.c should not iterate over any values with a NULL value
83339        **     for x.
83340        **
83341        **   + The optimizer code in where.c (the thing that decides which
83342        **     index or indices to use) should place a different priority on
83343        **     satisfying the 'ORDER BY' clause than it does in other cases.
83344        **     Refer to code and comments in where.c for details.
83345        */
83346        ExprList *pMinMax = 0;
83347        u8 flag = minMaxQuery(p);
83348        if( flag ){
83349          assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
83350          pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
83351          pDel = pMinMax;
83352          if( pMinMax && !db->mallocFailed ){
83353            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
83354            pMinMax->a[0].pExpr->op = TK_COLUMN;
83355          }
83356        }
83357
83358        /* This case runs if the aggregate has no GROUP BY clause.  The
83359        ** processing is much simpler since there is only a single row
83360        ** of output.
83361        */
83362        resetAccumulator(pParse, &sAggInfo);
83363        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
83364        if( pWInfo==0 ){
83365          sqlite3ExprListDelete(db, pDel);
83366          goto select_end;
83367        }
83368        updateAccumulator(pParse, &sAggInfo);
83369        if( !pMinMax && flag ){
83370          sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
83371          VdbeComment((v, "%s() by index",
83372                (flag==WHERE_ORDERBY_MIN?"min":"max")));
83373        }
83374        sqlite3WhereEnd(pWInfo);
83375        finalizeAggFunctions(pParse, &sAggInfo);
83376      }
83377
83378      pOrderBy = 0;
83379      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
83380      selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
83381                      pDest, addrEnd, addrEnd);
83382      sqlite3ExprListDelete(db, pDel);
83383    }
83384    sqlite3VdbeResolveLabel(v, addrEnd);
83385
83386  } /* endif aggregate query */
83387
83388  /* If there is an ORDER BY clause, then we need to sort the results
83389  ** and send them to the callback one by one.
83390  */
83391  if( pOrderBy ){
83392    generateSortTail(pParse, p, v, pEList->nExpr, pDest);
83393  }
83394
83395  /* Jump here to skip this query
83396  */
83397  sqlite3VdbeResolveLabel(v, iEnd);
83398
83399  /* The SELECT was successfully coded.   Set the return code to 0
83400  ** to indicate no errors.
83401  */
83402  rc = 0;
83403
83404  /* Control jumps to here if an error is encountered above, or upon
83405  ** successful coding of the SELECT.
83406  */
83407select_end:
83408
83409  /* Identify column names if results of the SELECT are to be output.
83410  */
83411  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
83412    generateColumnNames(pParse, pTabList, pEList);
83413  }
83414
83415  sqlite3DbFree(db, sAggInfo.aCol);
83416  sqlite3DbFree(db, sAggInfo.aFunc);
83417  return rc;
83418}
83419
83420#if defined(SQLITE_DEBUG)
83421/*
83422*******************************************************************************
83423** The following code is used for testing and debugging only.  The code
83424** that follows does not appear in normal builds.
83425**
83426** These routines are used to print out the content of all or part of a
83427** parse structures such as Select or Expr.  Such printouts are useful
83428** for helping to understand what is happening inside the code generator
83429** during the execution of complex SELECT statements.
83430**
83431** These routine are not called anywhere from within the normal
83432** code base.  Then are intended to be called from within the debugger
83433** or from temporary "printf" statements inserted for debugging.
83434*/
83435SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
83436  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
83437    sqlite3DebugPrintf("(%s", p->u.zToken);
83438  }else{
83439    sqlite3DebugPrintf("(%d", p->op);
83440  }
83441  if( p->pLeft ){
83442    sqlite3DebugPrintf(" ");
83443    sqlite3PrintExpr(p->pLeft);
83444  }
83445  if( p->pRight ){
83446    sqlite3DebugPrintf(" ");
83447    sqlite3PrintExpr(p->pRight);
83448  }
83449  sqlite3DebugPrintf(")");
83450}
83451SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
83452  int i;
83453  for(i=0; i<pList->nExpr; i++){
83454    sqlite3PrintExpr(pList->a[i].pExpr);
83455    if( i<pList->nExpr-1 ){
83456      sqlite3DebugPrintf(", ");
83457    }
83458  }
83459}
83460SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
83461  sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
83462  sqlite3PrintExprList(p->pEList);
83463  sqlite3DebugPrintf("\n");
83464  if( p->pSrc ){
83465    char *zPrefix;
83466    int i;
83467    zPrefix = "FROM";
83468    for(i=0; i<p->pSrc->nSrc; i++){
83469      struct SrcList_item *pItem = &p->pSrc->a[i];
83470      sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
83471      zPrefix = "";
83472      if( pItem->pSelect ){
83473        sqlite3DebugPrintf("(\n");
83474        sqlite3PrintSelect(pItem->pSelect, indent+10);
83475        sqlite3DebugPrintf("%*s)", indent+8, "");
83476      }else if( pItem->zName ){
83477        sqlite3DebugPrintf("%s", pItem->zName);
83478      }
83479      if( pItem->pTab ){
83480        sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
83481      }
83482      if( pItem->zAlias ){
83483        sqlite3DebugPrintf(" AS %s", pItem->zAlias);
83484      }
83485      if( i<p->pSrc->nSrc-1 ){
83486        sqlite3DebugPrintf(",");
83487      }
83488      sqlite3DebugPrintf("\n");
83489    }
83490  }
83491  if( p->pWhere ){
83492    sqlite3DebugPrintf("%*s WHERE ", indent, "");
83493    sqlite3PrintExpr(p->pWhere);
83494    sqlite3DebugPrintf("\n");
83495  }
83496  if( p->pGroupBy ){
83497    sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
83498    sqlite3PrintExprList(p->pGroupBy);
83499    sqlite3DebugPrintf("\n");
83500  }
83501  if( p->pHaving ){
83502    sqlite3DebugPrintf("%*s HAVING ", indent, "");
83503    sqlite3PrintExpr(p->pHaving);
83504    sqlite3DebugPrintf("\n");
83505  }
83506  if( p->pOrderBy ){
83507    sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
83508    sqlite3PrintExprList(p->pOrderBy);
83509    sqlite3DebugPrintf("\n");
83510  }
83511}
83512/* End of the structure debug printing code
83513*****************************************************************************/
83514#endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
83515
83516/************** End of select.c **********************************************/
83517/************** Begin file table.c *******************************************/
83518/*
83519** 2001 September 15
83520**
83521** The author disclaims copyright to this source code.  In place of
83522** a legal notice, here is a blessing:
83523**
83524**    May you do good and not evil.
83525**    May you find forgiveness for yourself and forgive others.
83526**    May you share freely, never taking more than you give.
83527**
83528*************************************************************************
83529** This file contains the sqlite3_get_table() and sqlite3_free_table()
83530** interface routines.  These are just wrappers around the main
83531** interface routine of sqlite3_exec().
83532**
83533** These routines are in a separate files so that they will not be linked
83534** if they are not used.
83535*/
83536
83537#ifndef SQLITE_OMIT_GET_TABLE
83538
83539/*
83540** This structure is used to pass data from sqlite3_get_table() through
83541** to the callback function is uses to build the result.
83542*/
83543typedef struct TabResult {
83544  char **azResult;   /* Accumulated output */
83545  char *zErrMsg;     /* Error message text, if an error occurs */
83546  int nAlloc;        /* Slots allocated for azResult[] */
83547  int nRow;          /* Number of rows in the result */
83548  int nColumn;       /* Number of columns in the result */
83549  int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
83550  int rc;            /* Return code from sqlite3_exec() */
83551} TabResult;
83552
83553/*
83554** This routine is called once for each row in the result table.  Its job
83555** is to fill in the TabResult structure appropriately, allocating new
83556** memory as necessary.
83557*/
83558static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
83559  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
83560  int need;                         /* Slots needed in p->azResult[] */
83561  int i;                            /* Loop counter */
83562  char *z;                          /* A single column of result */
83563
83564  /* Make sure there is enough space in p->azResult to hold everything
83565  ** we need to remember from this invocation of the callback.
83566  */
83567  if( p->nRow==0 && argv!=0 ){
83568    need = nCol*2;
83569  }else{
83570    need = nCol;
83571  }
83572  if( p->nData + need > p->nAlloc ){
83573    char **azNew;
83574    p->nAlloc = p->nAlloc*2 + need;
83575    azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
83576    if( azNew==0 ) goto malloc_failed;
83577    p->azResult = azNew;
83578  }
83579
83580  /* If this is the first row, then generate an extra row containing
83581  ** the names of all columns.
83582  */
83583  if( p->nRow==0 ){
83584    p->nColumn = nCol;
83585    for(i=0; i<nCol; i++){
83586      z = sqlite3_mprintf("%s", colv[i]);
83587      if( z==0 ) goto malloc_failed;
83588      p->azResult[p->nData++] = z;
83589    }
83590  }else if( p->nColumn!=nCol ){
83591    sqlite3_free(p->zErrMsg);
83592    p->zErrMsg = sqlite3_mprintf(
83593       "sqlite3_get_table() called with two or more incompatible queries"
83594    );
83595    p->rc = SQLITE_ERROR;
83596    return 1;
83597  }
83598
83599  /* Copy over the row data
83600  */
83601  if( argv!=0 ){
83602    for(i=0; i<nCol; i++){
83603      if( argv[i]==0 ){
83604        z = 0;
83605      }else{
83606        int n = sqlite3Strlen30(argv[i])+1;
83607        z = sqlite3_malloc( n );
83608        if( z==0 ) goto malloc_failed;
83609        memcpy(z, argv[i], n);
83610      }
83611      p->azResult[p->nData++] = z;
83612    }
83613    p->nRow++;
83614  }
83615  return 0;
83616
83617malloc_failed:
83618  p->rc = SQLITE_NOMEM;
83619  return 1;
83620}
83621
83622/*
83623** Query the database.  But instead of invoking a callback for each row,
83624** malloc() for space to hold the result and return the entire results
83625** at the conclusion of the call.
83626**
83627** The result that is written to ***pazResult is held in memory obtained
83628** from malloc().  But the caller cannot free this memory directly.
83629** Instead, the entire table should be passed to sqlite3_free_table() when
83630** the calling procedure is finished using it.
83631*/
83632SQLITE_API int sqlite3_get_table(
83633  sqlite3 *db,                /* The database on which the SQL executes */
83634  const char *zSql,           /* The SQL to be executed */
83635  char ***pazResult,          /* Write the result table here */
83636  int *pnRow,                 /* Write the number of rows in the result here */
83637  int *pnColumn,              /* Write the number of columns of result here */
83638  char **pzErrMsg             /* Write error messages here */
83639){
83640  int rc;
83641  TabResult res;
83642
83643  *pazResult = 0;
83644  if( pnColumn ) *pnColumn = 0;
83645  if( pnRow ) *pnRow = 0;
83646  if( pzErrMsg ) *pzErrMsg = 0;
83647  res.zErrMsg = 0;
83648  res.nRow = 0;
83649  res.nColumn = 0;
83650  res.nData = 1;
83651  res.nAlloc = 20;
83652  res.rc = SQLITE_OK;
83653  res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
83654  if( res.azResult==0 ){
83655     db->errCode = SQLITE_NOMEM;
83656     return SQLITE_NOMEM;
83657  }
83658  res.azResult[0] = 0;
83659  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
83660  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
83661  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
83662  if( (rc&0xff)==SQLITE_ABORT ){
83663    sqlite3_free_table(&res.azResult[1]);
83664    if( res.zErrMsg ){
83665      if( pzErrMsg ){
83666        sqlite3_free(*pzErrMsg);
83667        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
83668      }
83669      sqlite3_free(res.zErrMsg);
83670    }
83671    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
83672    return res.rc;
83673  }
83674  sqlite3_free(res.zErrMsg);
83675  if( rc!=SQLITE_OK ){
83676    sqlite3_free_table(&res.azResult[1]);
83677    return rc;
83678  }
83679  if( res.nAlloc>res.nData ){
83680    char **azNew;
83681    azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
83682    if( azNew==0 ){
83683      sqlite3_free_table(&res.azResult[1]);
83684      db->errCode = SQLITE_NOMEM;
83685      return SQLITE_NOMEM;
83686    }
83687    res.azResult = azNew;
83688  }
83689  *pazResult = &res.azResult[1];
83690  if( pnColumn ) *pnColumn = res.nColumn;
83691  if( pnRow ) *pnRow = res.nRow;
83692  return rc;
83693}
83694
83695/*
83696** This routine frees the space the sqlite3_get_table() malloced.
83697*/
83698SQLITE_API void sqlite3_free_table(
83699  char **azResult            /* Result returned from from sqlite3_get_table() */
83700){
83701  if( azResult ){
83702    int i, n;
83703    azResult--;
83704    assert( azResult!=0 );
83705    n = SQLITE_PTR_TO_INT(azResult[0]);
83706    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
83707    sqlite3_free(azResult);
83708  }
83709}
83710
83711#endif /* SQLITE_OMIT_GET_TABLE */
83712
83713/************** End of table.c ***********************************************/
83714/************** Begin file trigger.c *****************************************/
83715/*
83716**
83717** The author disclaims copyright to this source code.  In place of
83718** a legal notice, here is a blessing:
83719**
83720**    May you do good and not evil.
83721**    May you find forgiveness for yourself and forgive others.
83722**    May you share freely, never taking more than you give.
83723**
83724*************************************************************************
83725** This file contains the implementation for TRIGGERs
83726*/
83727
83728#ifndef SQLITE_OMIT_TRIGGER
83729/*
83730** Delete a linked list of TriggerStep structures.
83731*/
83732SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
83733  while( pTriggerStep ){
83734    TriggerStep * pTmp = pTriggerStep;
83735    pTriggerStep = pTriggerStep->pNext;
83736
83737    sqlite3ExprDelete(db, pTmp->pWhere);
83738    sqlite3ExprListDelete(db, pTmp->pExprList);
83739    sqlite3SelectDelete(db, pTmp->pSelect);
83740    sqlite3IdListDelete(db, pTmp->pIdList);
83741
83742    sqlite3DbFree(db, pTmp);
83743  }
83744}
83745
83746/*
83747** Given table pTab, return a list of all the triggers attached to
83748** the table. The list is connected by Trigger.pNext pointers.
83749**
83750** All of the triggers on pTab that are in the same database as pTab
83751** are already attached to pTab->pTrigger.  But there might be additional
83752** triggers on pTab in the TEMP schema.  This routine prepends all
83753** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
83754** and returns the combined list.
83755**
83756** To state it another way:  This routine returns a list of all triggers
83757** that fire off of pTab.  The list will include any TEMP triggers on
83758** pTab as well as the triggers lised in pTab->pTrigger.
83759*/
83760SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
83761  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
83762  Trigger *pList = 0;                  /* List of triggers to return */
83763
83764  if( pParse->disableTriggers ){
83765    return 0;
83766  }
83767
83768  if( pTmpSchema!=pTab->pSchema ){
83769    HashElem *p;
83770    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
83771      Trigger *pTrig = (Trigger *)sqliteHashData(p);
83772      if( pTrig->pTabSchema==pTab->pSchema
83773       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
83774      ){
83775        pTrig->pNext = (pList ? pList : pTab->pTrigger);
83776        pList = pTrig;
83777      }
83778    }
83779  }
83780
83781  return (pList ? pList : pTab->pTrigger);
83782}
83783
83784/*
83785** This is called by the parser when it sees a CREATE TRIGGER statement
83786** up to the point of the BEGIN before the trigger actions.  A Trigger
83787** structure is generated based on the information available and stored
83788** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
83789** sqlite3FinishTrigger() function is called to complete the trigger
83790** construction process.
83791*/
83792SQLITE_PRIVATE void sqlite3BeginTrigger(
83793  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
83794  Token *pName1,      /* The name of the trigger */
83795  Token *pName2,      /* The name of the trigger */
83796  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
83797  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
83798  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
83799  SrcList *pTableName,/* The name of the table/view the trigger applies to */
83800  Expr *pWhen,        /* WHEN clause */
83801  int isTemp,         /* True if the TEMPORARY keyword is present */
83802  int noErr           /* Suppress errors if the trigger already exists */
83803){
83804  Trigger *pTrigger = 0;  /* The new trigger */
83805  Table *pTab;            /* Table that the trigger fires off of */
83806  char *zName = 0;        /* Name of the trigger */
83807  sqlite3 *db = pParse->db;  /* The database connection */
83808  int iDb;                /* The database to store the trigger in */
83809  Token *pName;           /* The unqualified db name */
83810  DbFixer sFix;           /* State vector for the DB fixer */
83811  int iTabDb;             /* Index of the database holding pTab */
83812
83813  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
83814  assert( pName2!=0 );
83815  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
83816  assert( op>0 && op<0xff );
83817  if( isTemp ){
83818    /* If TEMP was specified, then the trigger name may not be qualified. */
83819    if( pName2->n>0 ){
83820      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
83821      goto trigger_cleanup;
83822    }
83823    iDb = 1;
83824    pName = pName1;
83825  }else{
83826    /* Figure out the db that the the trigger will be created in */
83827    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
83828    if( iDb<0 ){
83829      goto trigger_cleanup;
83830    }
83831  }
83832
83833  /* If the trigger name was unqualified, and the table is a temp table,
83834  ** then set iDb to 1 to create the trigger in the temporary database.
83835  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
83836  ** exist, the error is caught by the block below.
83837  */
83838  if( !pTableName || db->mallocFailed ){
83839    goto trigger_cleanup;
83840  }
83841  pTab = sqlite3SrcListLookup(pParse, pTableName);
83842  if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
83843    iDb = 1;
83844  }
83845
83846  /* Ensure the table name matches database name and that the table exists */
83847  if( db->mallocFailed ) goto trigger_cleanup;
83848  assert( pTableName->nSrc==1 );
83849  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
83850      sqlite3FixSrcList(&sFix, pTableName) ){
83851    goto trigger_cleanup;
83852  }
83853  pTab = sqlite3SrcListLookup(pParse, pTableName);
83854  if( !pTab ){
83855    /* The table does not exist. */
83856    if( db->init.iDb==1 ){
83857      /* Ticket #3810.
83858      ** Normally, whenever a table is dropped, all associated triggers are
83859      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
83860      ** and the table is dropped by a different database connection, the
83861      ** trigger is not visible to the database connection that does the
83862      ** drop so the trigger cannot be dropped.  This results in an
83863      ** "orphaned trigger" - a trigger whose associated table is missing.
83864      */
83865      db->init.orphanTrigger = 1;
83866    }
83867    goto trigger_cleanup;
83868  }
83869  if( IsVirtual(pTab) ){
83870    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
83871    goto trigger_cleanup;
83872  }
83873
83874  /* Check that the trigger name is not reserved and that no trigger of the
83875  ** specified name exists */
83876  zName = sqlite3NameFromToken(db, pName);
83877  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
83878    goto trigger_cleanup;
83879  }
83880  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
83881                      zName, sqlite3Strlen30(zName)) ){
83882    if( !noErr ){
83883      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
83884    }
83885    goto trigger_cleanup;
83886  }
83887
83888  /* Do not create a trigger on a system table */
83889  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
83890    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
83891    pParse->nErr++;
83892    goto trigger_cleanup;
83893  }
83894
83895  /* INSTEAD of triggers are only for views and views only support INSTEAD
83896  ** of triggers.
83897  */
83898  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
83899    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
83900        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
83901    goto trigger_cleanup;
83902  }
83903  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
83904    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
83905        " trigger on table: %S", pTableName, 0);
83906    goto trigger_cleanup;
83907  }
83908  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83909
83910#ifndef SQLITE_OMIT_AUTHORIZATION
83911  {
83912    int code = SQLITE_CREATE_TRIGGER;
83913    const char *zDb = db->aDb[iTabDb].zName;
83914    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
83915    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
83916    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
83917      goto trigger_cleanup;
83918    }
83919    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
83920      goto trigger_cleanup;
83921    }
83922  }
83923#endif
83924
83925  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
83926  ** cannot appear on views.  So we might as well translate every
83927  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
83928  ** elsewhere.
83929  */
83930  if (tr_tm == TK_INSTEAD){
83931    tr_tm = TK_BEFORE;
83932  }
83933
83934  /* Build the Trigger object */
83935  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
83936  if( pTrigger==0 ) goto trigger_cleanup;
83937  pTrigger->zName = zName;
83938  zName = 0;
83939  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
83940  pTrigger->pSchema = db->aDb[iDb].pSchema;
83941  pTrigger->pTabSchema = pTab->pSchema;
83942  pTrigger->op = (u8)op;
83943  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
83944  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
83945  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
83946  assert( pParse->pNewTrigger==0 );
83947  pParse->pNewTrigger = pTrigger;
83948
83949trigger_cleanup:
83950  sqlite3DbFree(db, zName);
83951  sqlite3SrcListDelete(db, pTableName);
83952  sqlite3IdListDelete(db, pColumns);
83953  sqlite3ExprDelete(db, pWhen);
83954  if( !pParse->pNewTrigger ){
83955    sqlite3DeleteTrigger(db, pTrigger);
83956  }else{
83957    assert( pParse->pNewTrigger==pTrigger );
83958  }
83959}
83960
83961/*
83962** This routine is called after all of the trigger actions have been parsed
83963** in order to complete the process of building the trigger.
83964*/
83965SQLITE_PRIVATE void sqlite3FinishTrigger(
83966  Parse *pParse,          /* Parser context */
83967  TriggerStep *pStepList, /* The triggered program */
83968  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
83969){
83970  Trigger *pTrig = pParse->pNewTrigger;    /* Trigger being finished */
83971  char *zName;                             /* Name of trigger */
83972  sqlite3 *db = pParse->db;                /* The database */
83973  DbFixer sFix;
83974  int iDb;                                 /* Database containing the trigger */
83975  Token nameToken;           /* Trigger name for error reporting */
83976
83977  pTrig = pParse->pNewTrigger;
83978  pParse->pNewTrigger = 0;
83979  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
83980  zName = pTrig->zName;
83981  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
83982  pTrig->step_list = pStepList;
83983  while( pStepList ){
83984    pStepList->pTrig = pTrig;
83985    pStepList = pStepList->pNext;
83986  }
83987  nameToken.z = pTrig->zName;
83988  nameToken.n = sqlite3Strlen30(nameToken.z);
83989  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
83990          && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
83991    goto triggerfinish_cleanup;
83992  }
83993
83994  /* if we are not initializing, and this trigger is not on a TEMP table,
83995  ** build the sqlite_master entry
83996  */
83997  if( !db->init.busy ){
83998    Vdbe *v;
83999    char *z;
84000
84001    /* Make an entry in the sqlite_master table */
84002    v = sqlite3GetVdbe(pParse);
84003    if( v==0 ) goto triggerfinish_cleanup;
84004    sqlite3BeginWriteOperation(pParse, 0, iDb);
84005    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
84006    sqlite3NestedParse(pParse,
84007       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
84008       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
84009       pTrig->table, z);
84010    sqlite3DbFree(db, z);
84011    sqlite3ChangeCookie(pParse, iDb);
84012    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
84013        db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
84014    );
84015  }
84016
84017  if( db->init.busy ){
84018    Trigger *pLink = pTrig;
84019    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
84020    pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
84021    if( pTrig ){
84022      db->mallocFailed = 1;
84023    }else if( pLink->pSchema==pLink->pTabSchema ){
84024      Table *pTab;
84025      int n = sqlite3Strlen30(pLink->table);
84026      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
84027      assert( pTab!=0 );
84028      pLink->pNext = pTab->pTrigger;
84029      pTab->pTrigger = pLink;
84030    }
84031  }
84032
84033triggerfinish_cleanup:
84034  sqlite3DeleteTrigger(db, pTrig);
84035  assert( !pParse->pNewTrigger );
84036  sqlite3DeleteTriggerStep(db, pStepList);
84037}
84038
84039/*
84040** Turn a SELECT statement (that the pSelect parameter points to) into
84041** a trigger step.  Return a pointer to a TriggerStep structure.
84042**
84043** The parser calls this routine when it finds a SELECT statement in
84044** body of a TRIGGER.
84045*/
84046SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
84047  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
84048  if( pTriggerStep==0 ) {
84049    sqlite3SelectDelete(db, pSelect);
84050    return 0;
84051  }
84052  pTriggerStep->op = TK_SELECT;
84053  pTriggerStep->pSelect = pSelect;
84054  pTriggerStep->orconf = OE_Default;
84055  return pTriggerStep;
84056}
84057
84058/*
84059** Allocate space to hold a new trigger step.  The allocated space
84060** holds both the TriggerStep object and the TriggerStep.target.z string.
84061**
84062** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
84063*/
84064static TriggerStep *triggerStepAllocate(
84065  sqlite3 *db,                /* Database connection */
84066  u8 op,                      /* Trigger opcode */
84067  Token *pName                /* The target name */
84068){
84069  TriggerStep *pTriggerStep;
84070
84071  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
84072  if( pTriggerStep ){
84073    char *z = (char*)&pTriggerStep[1];
84074    memcpy(z, pName->z, pName->n);
84075    pTriggerStep->target.z = z;
84076    pTriggerStep->target.n = pName->n;
84077    pTriggerStep->op = op;
84078  }
84079  return pTriggerStep;
84080}
84081
84082/*
84083** Build a trigger step out of an INSERT statement.  Return a pointer
84084** to the new trigger step.
84085**
84086** The parser calls this routine when it sees an INSERT inside the
84087** body of a trigger.
84088*/
84089SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
84090  sqlite3 *db,        /* The database connection */
84091  Token *pTableName,  /* Name of the table into which we insert */
84092  IdList *pColumn,    /* List of columns in pTableName to insert into */
84093  ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
84094  Select *pSelect,    /* A SELECT statement that supplies values */
84095  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
84096){
84097  TriggerStep *pTriggerStep;
84098
84099  assert(pEList == 0 || pSelect == 0);
84100  assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
84101
84102  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
84103  if( pTriggerStep ){
84104    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
84105    pTriggerStep->pIdList = pColumn;
84106    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
84107    pTriggerStep->orconf = orconf;
84108  }else{
84109    sqlite3IdListDelete(db, pColumn);
84110  }
84111  sqlite3ExprListDelete(db, pEList);
84112  sqlite3SelectDelete(db, pSelect);
84113
84114  return pTriggerStep;
84115}
84116
84117/*
84118** Construct a trigger step that implements an UPDATE statement and return
84119** a pointer to that trigger step.  The parser calls this routine when it
84120** sees an UPDATE statement inside the body of a CREATE TRIGGER.
84121*/
84122SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
84123  sqlite3 *db,         /* The database connection */
84124  Token *pTableName,   /* Name of the table to be updated */
84125  ExprList *pEList,    /* The SET clause: list of column and new values */
84126  Expr *pWhere,        /* The WHERE clause */
84127  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
84128){
84129  TriggerStep *pTriggerStep;
84130
84131  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
84132  if( pTriggerStep ){
84133    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
84134    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
84135    pTriggerStep->orconf = orconf;
84136  }
84137  sqlite3ExprListDelete(db, pEList);
84138  sqlite3ExprDelete(db, pWhere);
84139  return pTriggerStep;
84140}
84141
84142/*
84143** Construct a trigger step that implements a DELETE statement and return
84144** a pointer to that trigger step.  The parser calls this routine when it
84145** sees a DELETE statement inside the body of a CREATE TRIGGER.
84146*/
84147SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
84148  sqlite3 *db,            /* Database connection */
84149  Token *pTableName,      /* The table from which rows are deleted */
84150  Expr *pWhere            /* The WHERE clause */
84151){
84152  TriggerStep *pTriggerStep;
84153
84154  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
84155  if( pTriggerStep ){
84156    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
84157    pTriggerStep->orconf = OE_Default;
84158  }
84159  sqlite3ExprDelete(db, pWhere);
84160  return pTriggerStep;
84161}
84162
84163/*
84164** Recursively delete a Trigger structure
84165*/
84166SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
84167  if( pTrigger==0 ) return;
84168  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
84169  sqlite3DbFree(db, pTrigger->zName);
84170  sqlite3DbFree(db, pTrigger->table);
84171  sqlite3ExprDelete(db, pTrigger->pWhen);
84172  sqlite3IdListDelete(db, pTrigger->pColumns);
84173  sqlite3DbFree(db, pTrigger);
84174}
84175
84176/*
84177** This function is called to drop a trigger from the database schema.
84178**
84179** This may be called directly from the parser and therefore identifies
84180** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
84181** same job as this routine except it takes a pointer to the trigger
84182** instead of the trigger name.
84183**/
84184SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
84185  Trigger *pTrigger = 0;
84186  int i;
84187  const char *zDb;
84188  const char *zName;
84189  int nName;
84190  sqlite3 *db = pParse->db;
84191
84192  if( db->mallocFailed ) goto drop_trigger_cleanup;
84193  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
84194    goto drop_trigger_cleanup;
84195  }
84196
84197  assert( pName->nSrc==1 );
84198  zDb = pName->a[0].zDatabase;
84199  zName = pName->a[0].zName;
84200  nName = sqlite3Strlen30(zName);
84201  for(i=OMIT_TEMPDB; i<db->nDb; i++){
84202    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
84203    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
84204    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
84205    if( pTrigger ) break;
84206  }
84207  if( !pTrigger ){
84208    if( !noErr ){
84209      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
84210    }
84211    goto drop_trigger_cleanup;
84212  }
84213  sqlite3DropTriggerPtr(pParse, pTrigger);
84214
84215drop_trigger_cleanup:
84216  sqlite3SrcListDelete(db, pName);
84217}
84218
84219/*
84220** Return a pointer to the Table structure for the table that a trigger
84221** is set on.
84222*/
84223static Table *tableOfTrigger(Trigger *pTrigger){
84224  int n = sqlite3Strlen30(pTrigger->table);
84225  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
84226}
84227
84228
84229/*
84230** Drop a trigger given a pointer to that trigger.
84231*/
84232SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
84233  Table   *pTable;
84234  Vdbe *v;
84235  sqlite3 *db = pParse->db;
84236  int iDb;
84237
84238  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
84239  assert( iDb>=0 && iDb<db->nDb );
84240  pTable = tableOfTrigger(pTrigger);
84241  assert( pTable );
84242  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
84243#ifndef SQLITE_OMIT_AUTHORIZATION
84244  {
84245    int code = SQLITE_DROP_TRIGGER;
84246    const char *zDb = db->aDb[iDb].zName;
84247    const char *zTab = SCHEMA_TABLE(iDb);
84248    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
84249    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
84250      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
84251      return;
84252    }
84253  }
84254#endif
84255
84256  /* Generate code to destroy the database record of the trigger.
84257  */
84258  assert( pTable!=0 );
84259  if( (v = sqlite3GetVdbe(pParse))!=0 ){
84260    int base;
84261    static const VdbeOpList dropTrigger[] = {
84262      { OP_Rewind,     0, ADDR(9),  0},
84263      { OP_String8,    0, 1,        0}, /* 1 */
84264      { OP_Column,     0, 1,        2},
84265      { OP_Ne,         2, ADDR(8),  1},
84266      { OP_String8,    0, 1,        0}, /* 4: "trigger" */
84267      { OP_Column,     0, 0,        2},
84268      { OP_Ne,         2, ADDR(8),  1},
84269      { OP_Delete,     0, 0,        0},
84270      { OP_Next,       0, ADDR(1),  0}, /* 8 */
84271    };
84272
84273    sqlite3BeginWriteOperation(pParse, 0, iDb);
84274    sqlite3OpenMasterTable(pParse, iDb);
84275    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
84276    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
84277    sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
84278    sqlite3ChangeCookie(pParse, iDb);
84279    sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
84280    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
84281    if( pParse->nMem<3 ){
84282      pParse->nMem = 3;
84283    }
84284  }
84285}
84286
84287/*
84288** Remove a trigger from the hash tables of the sqlite* pointer.
84289*/
84290SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
84291  Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
84292  Trigger *pTrigger;
84293  pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
84294  if( ALWAYS(pTrigger) ){
84295    if( pTrigger->pSchema==pTrigger->pTabSchema ){
84296      Table *pTab = tableOfTrigger(pTrigger);
84297      Trigger **pp;
84298      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
84299      *pp = (*pp)->pNext;
84300    }
84301    sqlite3DeleteTrigger(db, pTrigger);
84302    db->flags |= SQLITE_InternChanges;
84303  }
84304}
84305
84306/*
84307** pEList is the SET clause of an UPDATE statement.  Each entry
84308** in pEList is of the format <id>=<expr>.  If any of the entries
84309** in pEList have an <id> which matches an identifier in pIdList,
84310** then return TRUE.  If pIdList==NULL, then it is considered a
84311** wildcard that matches anything.  Likewise if pEList==NULL then
84312** it matches anything so always return true.  Return false only
84313** if there is no match.
84314*/
84315static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
84316  int e;
84317  if( pIdList==0 || NEVER(pEList==0) ) return 1;
84318  for(e=0; e<pEList->nExpr; e++){
84319    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
84320  }
84321  return 0;
84322}
84323
84324/*
84325** Return a list of all triggers on table pTab if there exists at least
84326** one trigger that must be fired when an operation of type 'op' is
84327** performed on the table, and, if that operation is an UPDATE, if at
84328** least one of the columns in pChanges is being modified.
84329*/
84330SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
84331  Parse *pParse,          /* Parse context */
84332  Table *pTab,            /* The table the contains the triggers */
84333  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
84334  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
84335  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
84336){
84337  int mask = 0;
84338  Trigger *pList = sqlite3TriggerList(pParse, pTab);
84339  Trigger *p;
84340  assert( pList==0 || IsVirtual(pTab)==0 );
84341  for(p=pList; p; p=p->pNext){
84342    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
84343      mask |= p->tr_tm;
84344    }
84345  }
84346  if( pMask ){
84347    *pMask = mask;
84348  }
84349  return (mask ? pList : 0);
84350}
84351
84352/*
84353** Convert the pStep->target token into a SrcList and return a pointer
84354** to that SrcList.
84355**
84356** This routine adds a specific database name, if needed, to the target when
84357** forming the SrcList.  This prevents a trigger in one database from
84358** referring to a target in another database.  An exception is when the
84359** trigger is in TEMP in which case it can refer to any other database it
84360** wants.
84361*/
84362static SrcList *targetSrcList(
84363  Parse *pParse,       /* The parsing context */
84364  TriggerStep *pStep   /* The trigger containing the target token */
84365){
84366  int iDb;             /* Index of the database to use */
84367  SrcList *pSrc;       /* SrcList to be returned */
84368
84369  pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
84370  if( pSrc ){
84371    assert( pSrc->nSrc>0 );
84372    assert( pSrc->a!=0 );
84373    iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
84374    if( iDb==0 || iDb>=2 ){
84375      sqlite3 *db = pParse->db;
84376      assert( iDb<pParse->db->nDb );
84377      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
84378    }
84379  }
84380  return pSrc;
84381}
84382
84383/*
84384** Generate VDBE code for the statements inside the body of a single
84385** trigger.
84386*/
84387static int codeTriggerProgram(
84388  Parse *pParse,            /* The parser context */
84389  TriggerStep *pStepList,   /* List of statements inside the trigger body */
84390  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
84391){
84392  TriggerStep *pStep;
84393  Vdbe *v = pParse->pVdbe;
84394  sqlite3 *db = pParse->db;
84395
84396  assert( pParse->pTriggerTab && pParse->pToplevel );
84397  assert( pStepList );
84398  assert( v!=0 );
84399  for(pStep=pStepList; pStep; pStep=pStep->pNext){
84400    /* Figure out the ON CONFLICT policy that will be used for this step
84401    ** of the trigger program. If the statement that caused this trigger
84402    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
84403    ** the ON CONFLICT policy that was specified as part of the trigger
84404    ** step statement. Example:
84405    **
84406    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
84407    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
84408    **   END;
84409    **
84410    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
84411    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
84412    */
84413    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
84414
84415    switch( pStep->op ){
84416      case TK_UPDATE: {
84417        sqlite3Update(pParse,
84418          targetSrcList(pParse, pStep),
84419          sqlite3ExprListDup(db, pStep->pExprList, 0),
84420          sqlite3ExprDup(db, pStep->pWhere, 0),
84421          pParse->eOrconf
84422        );
84423        break;
84424      }
84425      case TK_INSERT: {
84426        sqlite3Insert(pParse,
84427          targetSrcList(pParse, pStep),
84428          sqlite3ExprListDup(db, pStep->pExprList, 0),
84429          sqlite3SelectDup(db, pStep->pSelect, 0),
84430          sqlite3IdListDup(db, pStep->pIdList),
84431          pParse->eOrconf
84432        );
84433        break;
84434      }
84435      case TK_DELETE: {
84436        sqlite3DeleteFrom(pParse,
84437          targetSrcList(pParse, pStep),
84438          sqlite3ExprDup(db, pStep->pWhere, 0)
84439        );
84440        break;
84441      }
84442      default: assert( pStep->op==TK_SELECT ); {
84443        SelectDest sDest;
84444        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
84445        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
84446        sqlite3Select(pParse, pSelect, &sDest);
84447        sqlite3SelectDelete(db, pSelect);
84448        break;
84449      }
84450    }
84451    if( pStep->op!=TK_SELECT ){
84452      sqlite3VdbeAddOp0(v, OP_ResetCount);
84453    }
84454  }
84455
84456  return 0;
84457}
84458
84459#ifdef SQLITE_DEBUG
84460/*
84461** This function is used to add VdbeComment() annotations to a VDBE
84462** program. It is not used in production code, only for debugging.
84463*/
84464static const char *onErrorText(int onError){
84465  switch( onError ){
84466    case OE_Abort:    return "abort";
84467    case OE_Rollback: return "rollback";
84468    case OE_Fail:     return "fail";
84469    case OE_Replace:  return "replace";
84470    case OE_Ignore:   return "ignore";
84471    case OE_Default:  return "default";
84472  }
84473  return "n/a";
84474}
84475#endif
84476
84477/*
84478** Parse context structure pFrom has just been used to create a sub-vdbe
84479** (trigger program). If an error has occurred, transfer error information
84480** from pFrom to pTo.
84481*/
84482static void transferParseError(Parse *pTo, Parse *pFrom){
84483  assert( pFrom->zErrMsg==0 || pFrom->nErr );
84484  assert( pTo->zErrMsg==0 || pTo->nErr );
84485  if( pTo->nErr==0 ){
84486    pTo->zErrMsg = pFrom->zErrMsg;
84487    pTo->nErr = pFrom->nErr;
84488  }else{
84489    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
84490  }
84491}
84492
84493/*
84494** Create and populate a new TriggerPrg object with a sub-program
84495** implementing trigger pTrigger with ON CONFLICT policy orconf.
84496*/
84497static TriggerPrg *codeRowTrigger(
84498  Parse *pParse,       /* Current parse context */
84499  Trigger *pTrigger,   /* Trigger to code */
84500  Table *pTab,         /* The table pTrigger is attached to */
84501  int orconf           /* ON CONFLICT policy to code trigger program with */
84502){
84503  Parse *pTop = sqlite3ParseToplevel(pParse);
84504  sqlite3 *db = pParse->db;   /* Database handle */
84505  TriggerPrg *pPrg;           /* Value to return */
84506  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
84507  Vdbe *v;                    /* Temporary VM */
84508  NameContext sNC;            /* Name context for sub-vdbe */
84509  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
84510  Parse *pSubParse;           /* Parse context for sub-vdbe */
84511  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
84512
84513  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
84514
84515  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
84516  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
84517  ** list of the top-level Parse object sooner rather than later.  */
84518  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
84519  if( !pPrg ) return 0;
84520  pPrg->pNext = pTop->pTriggerPrg;
84521  pTop->pTriggerPrg = pPrg;
84522  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
84523  if( !pProgram ) return 0;
84524  pProgram->nRef = 1;
84525  pPrg->pTrigger = pTrigger;
84526  pPrg->orconf = orconf;
84527  pPrg->aColmask[0] = 0xffffffff;
84528  pPrg->aColmask[1] = 0xffffffff;
84529
84530  /* Allocate and populate a new Parse context to use for coding the
84531  ** trigger sub-program.  */
84532  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
84533  if( !pSubParse ) return 0;
84534  memset(&sNC, 0, sizeof(sNC));
84535  sNC.pParse = pSubParse;
84536  pSubParse->db = db;
84537  pSubParse->pTriggerTab = pTab;
84538  pSubParse->pToplevel = pTop;
84539  pSubParse->zAuthContext = pTrigger->zName;
84540  pSubParse->eTriggerOp = pTrigger->op;
84541
84542  v = sqlite3GetVdbe(pSubParse);
84543  if( v ){
84544    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
84545      pTrigger->zName, onErrorText(orconf),
84546      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
84547        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
84548        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
84549        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
84550      pTab->zName
84551    ));
84552#ifndef SQLITE_OMIT_TRACE
84553    sqlite3VdbeChangeP4(v, -1,
84554      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
84555    );
84556#endif
84557
84558    /* If one was specified, code the WHEN clause. If it evaluates to false
84559    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
84560    ** OP_Halt inserted at the end of the program.  */
84561    if( pTrigger->pWhen ){
84562      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
84563      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
84564       && db->mallocFailed==0
84565      ){
84566        iEndTrigger = sqlite3VdbeMakeLabel(v);
84567        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
84568      }
84569      sqlite3ExprDelete(db, pWhen);
84570    }
84571
84572    /* Code the trigger program into the sub-vdbe. */
84573    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
84574
84575    /* Insert an OP_Halt at the end of the sub-program. */
84576    if( iEndTrigger ){
84577      sqlite3VdbeResolveLabel(v, iEndTrigger);
84578    }
84579    sqlite3VdbeAddOp0(v, OP_Halt);
84580    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
84581
84582    transferParseError(pParse, pSubParse);
84583    if( db->mallocFailed==0 ){
84584      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
84585    }
84586    pProgram->nMem = pSubParse->nMem;
84587    pProgram->nCsr = pSubParse->nTab;
84588    pProgram->token = (void *)pTrigger;
84589    pPrg->aColmask[0] = pSubParse->oldmask;
84590    pPrg->aColmask[1] = pSubParse->newmask;
84591    sqlite3VdbeDelete(v);
84592  }
84593
84594  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
84595  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
84596  sqlite3StackFree(db, pSubParse);
84597
84598  return pPrg;
84599}
84600
84601/*
84602** Return a pointer to a TriggerPrg object containing the sub-program for
84603** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
84604** TriggerPrg object exists, a new object is allocated and populated before
84605** being returned.
84606*/
84607static TriggerPrg *getRowTrigger(
84608  Parse *pParse,       /* Current parse context */
84609  Trigger *pTrigger,   /* Trigger to code */
84610  Table *pTab,         /* The table trigger pTrigger is attached to */
84611  int orconf           /* ON CONFLICT algorithm. */
84612){
84613  Parse *pRoot = sqlite3ParseToplevel(pParse);
84614  TriggerPrg *pPrg;
84615
84616  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
84617
84618  /* It may be that this trigger has already been coded (or is in the
84619  ** process of being coded). If this is the case, then an entry with
84620  ** a matching TriggerPrg.pTrigger field will be present somewhere
84621  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
84622  for(pPrg=pRoot->pTriggerPrg;
84623      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
84624      pPrg=pPrg->pNext
84625  );
84626
84627  /* If an existing TriggerPrg could not be located, create a new one. */
84628  if( !pPrg ){
84629    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
84630  }
84631
84632  return pPrg;
84633}
84634
84635/*
84636** Generate code for the trigger program associated with trigger p on
84637** table pTab. The reg, orconf and ignoreJump parameters passed to this
84638** function are the same as those described in the header function for
84639** sqlite3CodeRowTrigger()
84640*/
84641SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
84642  Parse *pParse,       /* Parse context */
84643  Trigger *p,          /* Trigger to code */
84644  Table *pTab,         /* The table to code triggers from */
84645  int reg,             /* Reg array containing OLD.* and NEW.* values */
84646  int orconf,          /* ON CONFLICT policy */
84647  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
84648){
84649  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
84650  TriggerPrg *pPrg;
84651  pPrg = getRowTrigger(pParse, p, pTab, orconf);
84652  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
84653
84654  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
84655  ** is a pointer to the sub-vdbe containing the trigger program.  */
84656  if( pPrg ){
84657    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
84658    pPrg->pProgram->nRef++;
84659    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
84660    VdbeComment(
84661        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
84662
84663    /* Set the P5 operand of the OP_Program instruction to non-zero if
84664    ** recursive invocation of this trigger program is disallowed. Recursive
84665    ** invocation is disallowed if (a) the sub-program is really a trigger,
84666    ** not a foreign key action, and (b) the flag to enable recursive triggers
84667    ** is clear.  */
84668    sqlite3VdbeChangeP5(v, (u8)(p->zName && !(pParse->db->flags&SQLITE_RecTriggers)));
84669  }
84670}
84671
84672/*
84673** This is called to code the required FOR EACH ROW triggers for an operation
84674** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
84675** is given by the op paramater. The tr_tm parameter determines whether the
84676** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
84677** parameter pChanges is passed the list of columns being modified.
84678**
84679** If there are no triggers that fire at the specified time for the specified
84680** operation on pTab, this function is a no-op.
84681**
84682** The reg argument is the address of the first in an array of registers
84683** that contain the values substituted for the new.* and old.* references
84684** in the trigger program. If N is the number of columns in table pTab
84685** (a copy of pTab->nCol), then registers are populated as follows:
84686**
84687**   Register       Contains
84688**   ------------------------------------------------------
84689**   reg+0          OLD.rowid
84690**   reg+1          OLD.* value of left-most column of pTab
84691**   ...            ...
84692**   reg+N          OLD.* value of right-most column of pTab
84693**   reg+N+1        NEW.rowid
84694**   reg+N+2        OLD.* value of left-most column of pTab
84695**   ...            ...
84696**   reg+N+N+1      NEW.* value of right-most column of pTab
84697**
84698** For ON DELETE triggers, the registers containing the NEW.* values will
84699** never be accessed by the trigger program, so they are not allocated or
84700** populated by the caller (there is no data to populate them with anyway).
84701** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
84702** are never accessed, and so are not allocated by the caller. So, for an
84703** ON INSERT trigger, the value passed to this function as parameter reg
84704** is not a readable register, although registers (reg+N) through
84705** (reg+N+N+1) are.
84706**
84707** Parameter orconf is the default conflict resolution algorithm for the
84708** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
84709** is the instruction that control should jump to if a trigger program
84710** raises an IGNORE exception.
84711*/
84712SQLITE_PRIVATE void sqlite3CodeRowTrigger(
84713  Parse *pParse,       /* Parse context */
84714  Trigger *pTrigger,   /* List of triggers on table pTab */
84715  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
84716  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
84717  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
84718  Table *pTab,         /* The table to code triggers from */
84719  int reg,             /* The first in an array of registers (see above) */
84720  int orconf,          /* ON CONFLICT policy */
84721  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
84722){
84723  Trigger *p;          /* Used to iterate through pTrigger list */
84724
84725  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
84726  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
84727  assert( (op==TK_UPDATE)==(pChanges!=0) );
84728
84729  for(p=pTrigger; p; p=p->pNext){
84730
84731    /* Sanity checking:  The schema for the trigger and for the table are
84732    ** always defined.  The trigger must be in the same schema as the table
84733    ** or else it must be a TEMP trigger. */
84734    assert( p->pSchema!=0 );
84735    assert( p->pTabSchema!=0 );
84736    assert( p->pSchema==p->pTabSchema
84737         || p->pSchema==pParse->db->aDb[1].pSchema );
84738
84739    /* Determine whether we should code this trigger */
84740    if( p->op==op
84741     && p->tr_tm==tr_tm
84742     && checkColumnOverlap(p->pColumns, pChanges)
84743    ){
84744      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
84745    }
84746  }
84747}
84748
84749/*
84750** Triggers may access values stored in the old.* or new.* pseudo-table.
84751** This function returns a 32-bit bitmask indicating which columns of the
84752** old.* or new.* tables actually are used by triggers. This information
84753** may be used by the caller, for example, to avoid having to load the entire
84754** old.* record into memory when executing an UPDATE or DELETE command.
84755**
84756** Bit 0 of the returned mask is set if the left-most column of the
84757** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
84758** the second leftmost column value is required, and so on. If there
84759** are more than 32 columns in the table, and at least one of the columns
84760** with an index greater than 32 may be accessed, 0xffffffff is returned.
84761**
84762** It is not possible to determine if the old.rowid or new.rowid column is
84763** accessed by triggers. The caller must always assume that it is.
84764**
84765** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
84766** applies to the old.* table. If 1, the new.* table.
84767**
84768** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
84769** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
84770** included in the returned mask if the TRIGGER_BEFORE bit is set in the
84771** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
84772** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
84773*/
84774SQLITE_PRIVATE u32 sqlite3TriggerColmask(
84775  Parse *pParse,       /* Parse context */
84776  Trigger *pTrigger,   /* List of triggers on table pTab */
84777  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
84778  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
84779  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
84780  Table *pTab,         /* The table to code triggers from */
84781  int orconf           /* Default ON CONFLICT policy for trigger steps */
84782){
84783  const int op = pChanges ? TK_UPDATE : TK_DELETE;
84784  u32 mask = 0;
84785  Trigger *p;
84786
84787  assert( isNew==1 || isNew==0 );
84788  for(p=pTrigger; p; p=p->pNext){
84789    if( p->op==op && (tr_tm&p->tr_tm)
84790     && checkColumnOverlap(p->pColumns,pChanges)
84791    ){
84792      TriggerPrg *pPrg;
84793      pPrg = getRowTrigger(pParse, p, pTab, orconf);
84794      if( pPrg ){
84795        mask |= pPrg->aColmask[isNew];
84796      }
84797    }
84798  }
84799
84800  return mask;
84801}
84802
84803#endif /* !defined(SQLITE_OMIT_TRIGGER) */
84804
84805/************** End of trigger.c *********************************************/
84806/************** Begin file update.c ******************************************/
84807/*
84808** 2001 September 15
84809**
84810** The author disclaims copyright to this source code.  In place of
84811** a legal notice, here is a blessing:
84812**
84813**    May you do good and not evil.
84814**    May you find forgiveness for yourself and forgive others.
84815**    May you share freely, never taking more than you give.
84816**
84817*************************************************************************
84818** This file contains C code routines that are called by the parser
84819** to handle UPDATE statements.
84820*/
84821
84822#ifndef SQLITE_OMIT_VIRTUALTABLE
84823/* Forward declaration */
84824static void updateVirtualTable(
84825  Parse *pParse,       /* The parsing context */
84826  SrcList *pSrc,       /* The virtual table to be modified */
84827  Table *pTab,         /* The virtual table */
84828  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
84829  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
84830  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
84831  Expr *pWhere         /* WHERE clause of the UPDATE statement */
84832);
84833#endif /* SQLITE_OMIT_VIRTUALTABLE */
84834
84835/*
84836** The most recently coded instruction was an OP_Column to retrieve the
84837** i-th column of table pTab. This routine sets the P4 parameter of the
84838** OP_Column to the default value, if any.
84839**
84840** The default value of a column is specified by a DEFAULT clause in the
84841** column definition. This was either supplied by the user when the table
84842** was created, or added later to the table definition by an ALTER TABLE
84843** command. If the latter, then the row-records in the table btree on disk
84844** may not contain a value for the column and the default value, taken
84845** from the P4 parameter of the OP_Column instruction, is returned instead.
84846** If the former, then all row-records are guaranteed to include a value
84847** for the column and the P4 value is not required.
84848**
84849** Column definitions created by an ALTER TABLE command may only have
84850** literal default values specified: a number, null or a string. (If a more
84851** complicated default expression value was provided, it is evaluated
84852** when the ALTER TABLE is executed and one of the literal values written
84853** into the sqlite_master table.)
84854**
84855** Therefore, the P4 parameter is only required if the default value for
84856** the column is a literal number, string or null. The sqlite3ValueFromExpr()
84857** function is capable of transforming these types of expressions into
84858** sqlite3_value objects.
84859**
84860** If parameter iReg is not negative, code an OP_RealAffinity instruction
84861** on register iReg. This is used when an equivalent integer value is
84862** stored in place of an 8-byte floating point value in order to save
84863** space.
84864*/
84865SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
84866  assert( pTab!=0 );
84867  if( !pTab->pSelect ){
84868    sqlite3_value *pValue;
84869    u8 enc = ENC(sqlite3VdbeDb(v));
84870    Column *pCol = &pTab->aCol[i];
84871    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
84872    assert( i<pTab->nCol );
84873    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
84874                         pCol->affinity, &pValue);
84875    if( pValue ){
84876      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
84877    }
84878#ifndef SQLITE_OMIT_FLOATING_POINT
84879    if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
84880      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
84881    }
84882#endif
84883  }
84884}
84885
84886/*
84887** Process an UPDATE statement.
84888**
84889**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
84890**          \_______/ \________/     \______/       \________________/
84891*            onError   pTabList      pChanges             pWhere
84892*/
84893SQLITE_PRIVATE void sqlite3Update(
84894  Parse *pParse,         /* The parser context */
84895  SrcList *pTabList,     /* The table in which we should change things */
84896  ExprList *pChanges,    /* Things to be changed */
84897  Expr *pWhere,          /* The WHERE clause.  May be null */
84898  int onError            /* How to handle constraint errors */
84899){
84900  int i, j;              /* Loop counters */
84901  Table *pTab;           /* The table to be updated */
84902  int addr = 0;          /* VDBE instruction address of the start of the loop */
84903  WhereInfo *pWInfo;     /* Information about the WHERE clause */
84904  Vdbe *v;               /* The virtual database engine */
84905  Index *pIdx;           /* For looping over indices */
84906  int nIdx;              /* Number of indices that need updating */
84907  int iCur;              /* VDBE Cursor number of pTab */
84908  sqlite3 *db;           /* The database structure */
84909  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
84910  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
84911                         ** an expression for the i-th column of the table.
84912                         ** aXRef[i]==-1 if the i-th column is not changed. */
84913  int chngRowid;         /* True if the record number is being changed */
84914  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
84915  int openAll = 0;       /* True if all indices need to be opened */
84916  AuthContext sContext;  /* The authorization context */
84917  NameContext sNC;       /* The name-context to resolve expressions in */
84918  int iDb;               /* Database containing the table being updated */
84919  int okOnePass;         /* True for one-pass algorithm without the FIFO */
84920  int hasFK;             /* True if foreign key processing is required */
84921
84922#ifndef SQLITE_OMIT_TRIGGER
84923  int isView;            /* True when updating a view (INSTEAD OF trigger) */
84924  Trigger *pTrigger;     /* List of triggers on pTab, if required */
84925  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
84926#endif
84927  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
84928
84929  /* Register Allocations */
84930  int regRowCount = 0;   /* A count of rows changed */
84931  int regOldRowid;       /* The old rowid */
84932  int regNewRowid;       /* The new rowid */
84933  int regNew;
84934  int regOld = 0;
84935  int regRowSet = 0;     /* Rowset of rows to be updated */
84936  int regRec;            /* Register used for new table record to insert */
84937
84938  memset(&sContext, 0, sizeof(sContext));
84939  db = pParse->db;
84940  if( pParse->nErr || db->mallocFailed ){
84941    goto update_cleanup;
84942  }
84943  assert( pTabList->nSrc==1 );
84944
84945  /* Locate the table which we want to update.
84946  */
84947  pTab = sqlite3SrcListLookup(pParse, pTabList);
84948  if( pTab==0 ) goto update_cleanup;
84949  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84950
84951  /* Figure out if we have any triggers and if the table being
84952  ** updated is a view.
84953  */
84954#ifndef SQLITE_OMIT_TRIGGER
84955  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
84956  isView = pTab->pSelect!=0;
84957  assert( pTrigger || tmask==0 );
84958#else
84959# define pTrigger 0
84960# define isView 0
84961# define tmask 0
84962#endif
84963#ifdef SQLITE_OMIT_VIEW
84964# undef isView
84965# define isView 0
84966#endif
84967
84968  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
84969    goto update_cleanup;
84970  }
84971  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
84972    goto update_cleanup;
84973  }
84974  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
84975  if( aXRef==0 ) goto update_cleanup;
84976  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
84977
84978  /* Allocate a cursors for the main database table and for all indices.
84979  ** The index cursors might not be used, but if they are used they
84980  ** need to occur right after the database cursor.  So go ahead and
84981  ** allocate enough space, just in case.
84982  */
84983  pTabList->a[0].iCursor = iCur = pParse->nTab++;
84984  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84985    pParse->nTab++;
84986  }
84987
84988  /* Initialize the name-context */
84989  memset(&sNC, 0, sizeof(sNC));
84990  sNC.pParse = pParse;
84991  sNC.pSrcList = pTabList;
84992
84993  /* Resolve the column names in all the expressions of the
84994  ** of the UPDATE statement.  Also find the column index
84995  ** for each column to be updated in the pChanges array.  For each
84996  ** column to be updated, make sure we have authorization to change
84997  ** that column.
84998  */
84999  chngRowid = 0;
85000  for(i=0; i<pChanges->nExpr; i++){
85001    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
85002      goto update_cleanup;
85003    }
85004    for(j=0; j<pTab->nCol; j++){
85005      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
85006        if( j==pTab->iPKey ){
85007          chngRowid = 1;
85008          pRowidExpr = pChanges->a[i].pExpr;
85009        }
85010        aXRef[j] = i;
85011        break;
85012      }
85013    }
85014    if( j>=pTab->nCol ){
85015      if( sqlite3IsRowid(pChanges->a[i].zName) ){
85016        chngRowid = 1;
85017        pRowidExpr = pChanges->a[i].pExpr;
85018      }else{
85019        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
85020        goto update_cleanup;
85021      }
85022    }
85023#ifndef SQLITE_OMIT_AUTHORIZATION
85024    {
85025      int rc;
85026      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
85027                           pTab->aCol[j].zName, db->aDb[iDb].zName);
85028      if( rc==SQLITE_DENY ){
85029        goto update_cleanup;
85030      }else if( rc==SQLITE_IGNORE ){
85031        aXRef[j] = -1;
85032      }
85033    }
85034#endif
85035  }
85036
85037  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
85038
85039  /* Allocate memory for the array aRegIdx[].  There is one entry in the
85040  ** array for each index associated with table being updated.  Fill in
85041  ** the value with a register number for indices that are to be used
85042  ** and with zero for unused indices.
85043  */
85044  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
85045  if( nIdx>0 ){
85046    aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
85047    if( aRegIdx==0 ) goto update_cleanup;
85048  }
85049  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
85050    int reg;
85051    if( chngRowid ){
85052      reg = ++pParse->nMem;
85053    }else{
85054      reg = 0;
85055      for(i=0; i<pIdx->nColumn; i++){
85056        if( aXRef[pIdx->aiColumn[i]]>=0 ){
85057          reg = ++pParse->nMem;
85058          break;
85059        }
85060      }
85061    }
85062    aRegIdx[j] = reg;
85063  }
85064
85065  /* Begin generating code. */
85066  v = sqlite3GetVdbe(pParse);
85067  if( v==0 ) goto update_cleanup;
85068  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
85069  sqlite3BeginWriteOperation(pParse, 1, iDb);
85070
85071#ifndef SQLITE_OMIT_VIRTUALTABLE
85072  /* Virtual tables must be handled separately */
85073  if( IsVirtual(pTab) ){
85074    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
85075                       pWhere);
85076    pWhere = 0;
85077    pTabList = 0;
85078    goto update_cleanup;
85079  }
85080#endif
85081
85082  /* Allocate required registers. */
85083  regOldRowid = regNewRowid = ++pParse->nMem;
85084  if( pTrigger || hasFK ){
85085    regOld = pParse->nMem + 1;
85086    pParse->nMem += pTab->nCol;
85087  }
85088  if( chngRowid || pTrigger || hasFK ){
85089    regNewRowid = ++pParse->nMem;
85090  }
85091  regNew = pParse->nMem + 1;
85092  pParse->nMem += pTab->nCol;
85093  regRec = ++pParse->nMem;
85094
85095  /* Start the view context. */
85096  if( isView ){
85097    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
85098  }
85099
85100  /* If we are trying to update a view, realize that view into
85101  ** a ephemeral table.
85102  */
85103#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
85104  if( isView ){
85105    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
85106  }
85107#endif
85108
85109  /* Resolve the column names in all the expressions in the
85110  ** WHERE clause.
85111  */
85112  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
85113    goto update_cleanup;
85114  }
85115
85116  /* Begin the database scan
85117  */
85118  sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
85119  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
85120  if( pWInfo==0 ) goto update_cleanup;
85121  okOnePass = pWInfo->okOnePass;
85122
85123  /* Remember the rowid of every item to be updated.
85124  */
85125  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
85126  if( !okOnePass ){
85127    regRowSet = ++pParse->nMem;
85128    sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
85129  }
85130
85131  /* End the database scan loop.
85132  */
85133  sqlite3WhereEnd(pWInfo);
85134
85135  /* Initialize the count of updated rows
85136  */
85137  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
85138    regRowCount = ++pParse->nMem;
85139    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
85140  }
85141
85142  if( !isView ){
85143    /*
85144    ** Open every index that needs updating.  Note that if any
85145    ** index could potentially invoke a REPLACE conflict resolution
85146    ** action, then we need to open all indices because we might need
85147    ** to be deleting some records.
85148    */
85149    if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
85150    if( onError==OE_Replace ){
85151      openAll = 1;
85152    }else{
85153      openAll = 0;
85154      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85155        if( pIdx->onError==OE_Replace ){
85156          openAll = 1;
85157          break;
85158        }
85159      }
85160    }
85161    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
85162      if( openAll || aRegIdx[i]>0 ){
85163        KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
85164        sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
85165                       (char*)pKey, P4_KEYINFO_HANDOFF);
85166        assert( pParse->nTab>iCur+i+1 );
85167      }
85168    }
85169  }
85170
85171  /* Top of the update loop */
85172  if( okOnePass ){
85173    int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
85174    addr = sqlite3VdbeAddOp0(v, OP_Goto);
85175    sqlite3VdbeJumpHere(v, a1);
85176  }else{
85177    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
85178  }
85179
85180  /* Make cursor iCur point to the record that is being updated. If
85181  ** this record does not exist for some reason (deleted by a trigger,
85182  ** for example, then jump to the next iteration of the RowSet loop.  */
85183  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
85184
85185  /* If the record number will change, set register regNewRowid to
85186  ** contain the new value. If the record number is not being modified,
85187  ** then regNewRowid is the same register as regOldRowid, which is
85188  ** already populated.  */
85189  assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
85190  if( chngRowid ){
85191    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
85192    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
85193  }
85194
85195  /* If there are triggers on this table, populate an array of registers
85196  ** with the required old.* column data.  */
85197  if( hasFK || pTrigger ){
85198    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
85199    oldmask |= sqlite3TriggerColmask(pParse,
85200        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
85201    );
85202    for(i=0; i<pTab->nCol; i++){
85203      if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
85204        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regOld+i);
85205        sqlite3ColumnDefault(v, pTab, i, regOld+i);
85206      }else{
85207        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
85208      }
85209    }
85210    if( chngRowid==0 ){
85211      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
85212    }
85213  }
85214
85215  /* Populate the array of registers beginning at regNew with the new
85216  ** row data. This array is used to check constaints, create the new
85217  ** table and index records, and as the values for any new.* references
85218  ** made by triggers.
85219  **
85220  ** If there are one or more BEFORE triggers, then do not populate the
85221  ** registers associated with columns that are (a) not modified by
85222  ** this UPDATE statement and (b) not accessed by new.* references. The
85223  ** values for registers not modified by the UPDATE must be reloaded from
85224  ** the database after the BEFORE triggers are fired anyway (as the trigger
85225  ** may have modified them). So not loading those that are not going to
85226  ** be used eliminates some redundant opcodes.
85227  */
85228  newmask = sqlite3TriggerColmask(
85229      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
85230  );
85231  for(i=0; i<pTab->nCol; i++){
85232    if( i==pTab->iPKey ){
85233      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
85234    }else{
85235      j = aXRef[i];
85236      if( j>=0 ){
85237        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
85238      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
85239        /* This branch loads the value of a column that will not be changed
85240        ** into a register. This is done if there are no BEFORE triggers, or
85241        ** if there are one or more BEFORE triggers that use this value via
85242        ** a new.* reference in a trigger program.
85243        */
85244        testcase( i==31 );
85245        testcase( i==32 );
85246        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
85247        sqlite3ColumnDefault(v, pTab, i, regNew+i);
85248      }
85249    }
85250  }
85251
85252  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
85253  ** verified. One could argue that this is wrong.
85254  */
85255  if( tmask&TRIGGER_BEFORE ){
85256    sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
85257    sqlite3TableAffinityStr(v, pTab);
85258    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
85259        TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
85260
85261    /* The row-trigger may have deleted the row being updated. In this
85262    ** case, jump to the next row. No updates or AFTER triggers are
85263    ** required. This behaviour - what happens when the row being updated
85264    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
85265    ** documentation.
85266    */
85267    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
85268
85269    /* If it did not delete it, the row-trigger may still have modified
85270    ** some of the columns of the row being updated. Load the values for
85271    ** all columns not modified by the update statement into their
85272    ** registers in case this has happened.
85273    */
85274    for(i=0; i<pTab->nCol; i++){
85275      if( aXRef[i]<0 && i!=pTab->iPKey ){
85276        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
85277        sqlite3ColumnDefault(v, pTab, i, regNew+i);
85278      }
85279    }
85280  }
85281
85282  if( !isView ){
85283    int j1;                       /* Address of jump instruction */
85284
85285    /* Do constraint checks. */
85286    sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
85287        aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
85288
85289    /* Do FK constraint checks. */
85290    if( hasFK ){
85291      sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
85292    }
85293
85294    /* Delete the index entries associated with the current record.  */
85295    j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
85296    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
85297
85298    /* If changing the record number, delete the old record.  */
85299    if( hasFK || chngRowid ){
85300      sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
85301    }
85302    sqlite3VdbeJumpHere(v, j1);
85303
85304    if( hasFK ){
85305      sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
85306    }
85307
85308    /* Insert the new index entries and the new record. */
85309    sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
85310
85311    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
85312    ** handle rows (possibly in other tables) that refer via a foreign key
85313    ** to the row just updated. */
85314    if( hasFK ){
85315      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
85316    }
85317  }
85318
85319  /* Increment the row counter
85320  */
85321  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
85322    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
85323  }
85324
85325  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
85326      TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
85327
85328  /* Repeat the above with the next record to be updated, until
85329  ** all record selected by the WHERE clause have been updated.
85330  */
85331  sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
85332  sqlite3VdbeJumpHere(v, addr);
85333
85334  /* Close all tables */
85335  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
85336    if( openAll || aRegIdx[i]>0 ){
85337      sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
85338    }
85339  }
85340  sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
85341
85342  /* Update the sqlite_sequence table by storing the content of the
85343  ** maximum rowid counter values recorded while inserting into
85344  ** autoincrement tables.
85345  */
85346  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85347    sqlite3AutoincrementEnd(pParse);
85348  }
85349
85350  /*
85351  ** Return the number of rows that were changed. If this routine is
85352  ** generating code because of a call to sqlite3NestedParse(), do not
85353  ** invoke the callback function.
85354  */
85355  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
85356    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
85357    sqlite3VdbeSetNumCols(v, 1);
85358    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
85359  }
85360
85361update_cleanup:
85362  sqlite3AuthContextPop(&sContext);
85363  sqlite3DbFree(db, aRegIdx);
85364  sqlite3DbFree(db, aXRef);
85365  sqlite3SrcListDelete(db, pTabList);
85366  sqlite3ExprListDelete(db, pChanges);
85367  sqlite3ExprDelete(db, pWhere);
85368  return;
85369}
85370/* Make sure "isView" and other macros defined above are undefined. Otherwise
85371** thely may interfere with compilation of other functions in this file
85372** (or in another file, if this file becomes part of the amalgamation).  */
85373#ifdef isView
85374 #undef isView
85375#endif
85376#ifdef pTrigger
85377 #undef pTrigger
85378#endif
85379
85380#ifndef SQLITE_OMIT_VIRTUALTABLE
85381/*
85382** Generate code for an UPDATE of a virtual table.
85383**
85384** The strategy is that we create an ephemerial table that contains
85385** for each row to be changed:
85386**
85387**   (A)  The original rowid of that row.
85388**   (B)  The revised rowid for the row. (note1)
85389**   (C)  The content of every column in the row.
85390**
85391** Then we loop over this ephemeral table and for each row in
85392** the ephermeral table call VUpdate.
85393**
85394** When finished, drop the ephemeral table.
85395**
85396** (note1) Actually, if we know in advance that (A) is always the same
85397** as (B) we only store (A), then duplicate (A) when pulling
85398** it out of the ephemeral table before calling VUpdate.
85399*/
85400static void updateVirtualTable(
85401  Parse *pParse,       /* The parsing context */
85402  SrcList *pSrc,       /* The virtual table to be modified */
85403  Table *pTab,         /* The virtual table */
85404  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
85405  Expr *pRowid,        /* Expression used to recompute the rowid */
85406  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
85407  Expr *pWhere         /* WHERE clause of the UPDATE statement */
85408){
85409  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
85410  ExprList *pEList = 0;     /* The result set of the SELECT statement */
85411  Select *pSelect = 0;      /* The SELECT statement */
85412  Expr *pExpr;              /* Temporary expression */
85413  int ephemTab;             /* Table holding the result of the SELECT */
85414  int i;                    /* Loop counter */
85415  int addr;                 /* Address of top of loop */
85416  int iReg;                 /* First register in set passed to OP_VUpdate */
85417  sqlite3 *db = pParse->db; /* Database connection */
85418  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
85419  SelectDest dest;
85420
85421  /* Construct the SELECT statement that will find the new values for
85422  ** all updated rows.
85423  */
85424  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
85425  if( pRowid ){
85426    pEList = sqlite3ExprListAppend(pParse, pEList,
85427                                   sqlite3ExprDup(db, pRowid, 0));
85428  }
85429  assert( pTab->iPKey<0 );
85430  for(i=0; i<pTab->nCol; i++){
85431    if( aXRef[i]>=0 ){
85432      pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
85433    }else{
85434      pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
85435    }
85436    pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
85437  }
85438  pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
85439
85440  /* Create the ephemeral table into which the update results will
85441  ** be stored.
85442  */
85443  assert( v );
85444  ephemTab = pParse->nTab++;
85445  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
85446
85447  /* fill the ephemeral table
85448  */
85449  sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
85450  sqlite3Select(pParse, pSelect, &dest);
85451
85452  /* Generate code to scan the ephemeral table and call VUpdate. */
85453  iReg = ++pParse->nMem;
85454  pParse->nMem += pTab->nCol+1;
85455  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
85456  sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
85457  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
85458  for(i=0; i<pTab->nCol; i++){
85459    sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
85460  }
85461  sqlite3VtabMakeWritable(pParse, pTab);
85462  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
85463  sqlite3MayAbort(pParse);
85464  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
85465  sqlite3VdbeJumpHere(v, addr);
85466  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
85467
85468  /* Cleanup */
85469  sqlite3SelectDelete(db, pSelect);
85470}
85471#endif /* SQLITE_OMIT_VIRTUALTABLE */
85472
85473/************** End of update.c **********************************************/
85474/************** Begin file vacuum.c ******************************************/
85475/*
85476** 2003 April 6
85477**
85478** The author disclaims copyright to this source code.  In place of
85479** a legal notice, here is a blessing:
85480**
85481**    May you do good and not evil.
85482**    May you find forgiveness for yourself and forgive others.
85483**    May you share freely, never taking more than you give.
85484**
85485*************************************************************************
85486** This file contains code used to implement the VACUUM command.
85487**
85488** Most of the code in this file may be omitted by defining the
85489** SQLITE_OMIT_VACUUM macro.
85490*/
85491
85492#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
85493/*
85494** Finalize a prepared statement.  If there was an error, store the
85495** text of the error message in *pzErrMsg.  Return the result code.
85496*/
85497static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
85498  int rc;
85499  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
85500  if( rc ){
85501    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
85502  }
85503  return rc;
85504}
85505
85506/*
85507** Execute zSql on database db. Return an error code.
85508*/
85509static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
85510  sqlite3_stmt *pStmt;
85511  VVA_ONLY( int rc; )
85512  if( !zSql ){
85513    return SQLITE_NOMEM;
85514  }
85515  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
85516    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
85517    return sqlite3_errcode(db);
85518  }
85519  VVA_ONLY( rc = ) sqlite3_step(pStmt);
85520  assert( rc!=SQLITE_ROW );
85521  return vacuumFinalize(db, pStmt, pzErrMsg);
85522}
85523
85524/*
85525** Execute zSql on database db. The statement returns exactly
85526** one column. Execute this as SQL on the same database.
85527*/
85528static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
85529  sqlite3_stmt *pStmt;
85530  int rc;
85531
85532  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
85533  if( rc!=SQLITE_OK ) return rc;
85534
85535  while( SQLITE_ROW==sqlite3_step(pStmt) ){
85536    rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
85537    if( rc!=SQLITE_OK ){
85538      vacuumFinalize(db, pStmt, pzErrMsg);
85539      return rc;
85540    }
85541  }
85542
85543  return vacuumFinalize(db, pStmt, pzErrMsg);
85544}
85545
85546/*
85547** The non-standard VACUUM command is used to clean up the database,
85548** collapse free space, etc.  It is modelled after the VACUUM command
85549** in PostgreSQL.
85550**
85551** In version 1.0.x of SQLite, the VACUUM command would call
85552** gdbm_reorganize() on all the database tables.  But beginning
85553** with 2.0.0, SQLite no longer uses GDBM so this command has
85554** become a no-op.
85555*/
85556SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
85557  Vdbe *v = sqlite3GetVdbe(pParse);
85558  if( v ){
85559    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
85560  }
85561  return;
85562}
85563
85564/*
85565** This routine implements the OP_Vacuum opcode of the VDBE.
85566*/
85567SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
85568  int rc = SQLITE_OK;     /* Return code from service routines */
85569  Btree *pMain;           /* The database being vacuumed */
85570  Btree *pTemp;           /* The temporary database we vacuum into */
85571  char *zSql = 0;         /* SQL statements */
85572  int saved_flags;        /* Saved value of the db->flags */
85573  int saved_nChange;      /* Saved value of db->nChange */
85574  int saved_nTotalChange; /* Saved value of db->nTotalChange */
85575  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
85576  Db *pDb = 0;            /* Database to detach at end of vacuum */
85577  int isMemDb;            /* True if vacuuming a :memory: database */
85578  int nRes;
85579
85580  if( !db->autoCommit ){
85581    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
85582    return SQLITE_ERROR;
85583  }
85584
85585  /* Save the current value of the database flags so that it can be
85586  ** restored before returning. Then set the writable-schema flag, and
85587  ** disable CHECK and foreign key constraints.  */
85588  saved_flags = db->flags;
85589  saved_nChange = db->nChange;
85590  saved_nTotalChange = db->nTotalChange;
85591  saved_xTrace = db->xTrace;
85592  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
85593  db->flags &= ~SQLITE_ForeignKeys;
85594  db->xTrace = 0;
85595
85596  pMain = db->aDb[0].pBt;
85597  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
85598
85599  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
85600  ** can be set to 'off' for this file, as it is not recovered if a crash
85601  ** occurs anyway. The integrity of the database is maintained by a
85602  ** (possibly synchronous) transaction opened on the main database before
85603  ** sqlite3BtreeCopyFile() is called.
85604  **
85605  ** An optimisation would be to use a non-journaled pager.
85606  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
85607  ** that actually made the VACUUM run slower.  Very little journalling
85608  ** actually occurs when doing a vacuum since the vacuum_db is initially
85609  ** empty.  Only the journal header is written.  Apparently it takes more
85610  ** time to parse and run the PRAGMA to turn journalling off than it does
85611  ** to write the journal header file.
85612  */
85613  if( sqlite3TempInMemory(db) ){
85614    zSql = "ATTACH ':memory:' AS vacuum_db;";
85615  }else{
85616    zSql = "ATTACH '' AS vacuum_db;";
85617  }
85618  rc = execSql(db, pzErrMsg, zSql);
85619  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85620  pDb = &db->aDb[db->nDb-1];
85621  assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
85622  pTemp = db->aDb[db->nDb-1].pBt;
85623
85624  /* The call to execSql() to attach the temp database has left the file
85625  ** locked (as there was more than one active statement when the transaction
85626  ** to read the schema was concluded. Unlock it here so that this doesn't
85627  ** cause problems for the call to BtreeSetPageSize() below.  */
85628  sqlite3BtreeCommit(pTemp);
85629
85630  nRes = sqlite3BtreeGetReserve(pMain);
85631
85632  /* A VACUUM cannot change the pagesize of an encrypted database. */
85633#ifdef SQLITE_HAS_CODEC
85634  if( db->nextPagesize ){
85635    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
85636    int nKey;
85637    char *zKey;
85638    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
85639    if( nKey ) db->nextPagesize = 0;
85640  }
85641#endif
85642
85643  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
85644   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
85645   || NEVER(db->mallocFailed)
85646  ){
85647    rc = SQLITE_NOMEM;
85648    goto end_of_vacuum;
85649  }
85650  rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
85651  if( rc!=SQLITE_OK ){
85652    goto end_of_vacuum;
85653  }
85654
85655#ifndef SQLITE_OMIT_AUTOVACUUM
85656  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
85657                                           sqlite3BtreeGetAutoVacuum(pMain));
85658#endif
85659
85660  /* Begin a transaction */
85661  rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
85662  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85663
85664  /* Query the schema of the main database. Create a mirror schema
85665  ** in the temporary database.
85666  */
85667  rc = execExecSql(db, pzErrMsg,
85668      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
85669      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
85670      "   AND rootpage>0"
85671  );
85672  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85673  rc = execExecSql(db, pzErrMsg,
85674      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
85675      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
85676  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85677  rc = execExecSql(db, pzErrMsg,
85678      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
85679      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
85680  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85681
85682  /* Loop through the tables in the main database. For each, do
85683  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
85684  ** the contents to the temporary database.
85685  */
85686  rc = execExecSql(db, pzErrMsg,
85687      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
85688      "|| ' SELECT * FROM main.' || quote(name) || ';'"
85689      "FROM main.sqlite_master "
85690      "WHERE type = 'table' AND name!='sqlite_sequence' "
85691      "  AND rootpage>0"
85692  );
85693  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85694
85695  /* Copy over the sequence table
85696  */
85697  rc = execExecSql(db, pzErrMsg,
85698      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
85699      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
85700  );
85701  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85702  rc = execExecSql(db, pzErrMsg,
85703      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
85704      "|| ' SELECT * FROM main.' || quote(name) || ';' "
85705      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
85706  );
85707  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85708
85709
85710  /* Copy the triggers, views, and virtual tables from the main database
85711  ** over to the temporary database.  None of these objects has any
85712  ** associated storage, so all we have to do is copy their entries
85713  ** from the SQLITE_MASTER table.
85714  */
85715  rc = execSql(db, pzErrMsg,
85716      "INSERT INTO vacuum_db.sqlite_master "
85717      "  SELECT type, name, tbl_name, rootpage, sql"
85718      "    FROM main.sqlite_master"
85719      "   WHERE type='view' OR type='trigger'"
85720      "      OR (type='table' AND rootpage=0)"
85721  );
85722  if( rc ) goto end_of_vacuum;
85723
85724  /* At this point, unless the main db was completely empty, there is now a
85725  ** transaction open on the vacuum database, but not on the main database.
85726  ** Open a btree level transaction on the main database. This allows a
85727  ** call to sqlite3BtreeCopyFile(). The main database btree level
85728  ** transaction is then committed, so the SQL level never knows it was
85729  ** opened for writing. This way, the SQL transaction used to create the
85730  ** temporary database never needs to be committed.
85731  */
85732  {
85733    u32 meta;
85734    int i;
85735
85736    /* This array determines which meta meta values are preserved in the
85737    ** vacuum.  Even entries are the meta value number and odd entries
85738    ** are an increment to apply to the meta value after the vacuum.
85739    ** The increment is used to increase the schema cookie so that other
85740    ** connections to the same database will know to reread the schema.
85741    */
85742    static const unsigned char aCopy[] = {
85743       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
85744       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
85745       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
85746       BTREE_USER_VERSION,       0,  /* Preserve the user version */
85747    };
85748
85749    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
85750    assert( 1==sqlite3BtreeIsInTrans(pMain) );
85751
85752    /* Copy Btree meta values */
85753    for(i=0; i<ArraySize(aCopy); i+=2){
85754      /* GetMeta() and UpdateMeta() cannot fail in this context because
85755      ** we already have page 1 loaded into cache and marked dirty. */
85756      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
85757      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
85758      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
85759    }
85760
85761    rc = sqlite3BtreeCopyFile(pMain, pTemp);
85762    if( rc!=SQLITE_OK ) goto end_of_vacuum;
85763    rc = sqlite3BtreeCommit(pTemp);
85764    if( rc!=SQLITE_OK ) goto end_of_vacuum;
85765#ifndef SQLITE_OMIT_AUTOVACUUM
85766    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
85767#endif
85768  }
85769
85770  assert( rc==SQLITE_OK );
85771  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
85772
85773end_of_vacuum:
85774  /* Restore the original value of db->flags */
85775  db->flags = saved_flags;
85776  db->nChange = saved_nChange;
85777  db->nTotalChange = saved_nTotalChange;
85778  db->xTrace = saved_xTrace;
85779
85780  /* Currently there is an SQL level transaction open on the vacuum
85781  ** database. No locks are held on any other files (since the main file
85782  ** was committed at the btree level). So it safe to end the transaction
85783  ** by manually setting the autoCommit flag to true and detaching the
85784  ** vacuum database. The vacuum_db journal file is deleted when the pager
85785  ** is closed by the DETACH.
85786  */
85787  db->autoCommit = 1;
85788
85789  if( pDb ){
85790    sqlite3BtreeClose(pDb->pBt);
85791    pDb->pBt = 0;
85792    pDb->pSchema = 0;
85793  }
85794
85795  sqlite3ResetInternalSchema(db, 0);
85796
85797  return rc;
85798}
85799#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
85800
85801/************** End of vacuum.c **********************************************/
85802/************** Begin file vtab.c ********************************************/
85803/*
85804** 2006 June 10
85805**
85806** The author disclaims copyright to this source code.  In place of
85807** a legal notice, here is a blessing:
85808**
85809**    May you do good and not evil.
85810**    May you find forgiveness for yourself and forgive others.
85811**    May you share freely, never taking more than you give.
85812**
85813*************************************************************************
85814** This file contains code used to help implement virtual tables.
85815*/
85816#ifndef SQLITE_OMIT_VIRTUALTABLE
85817
85818/*
85819** The actual function that does the work of creating a new module.
85820** This function implements the sqlite3_create_module() and
85821** sqlite3_create_module_v2() interfaces.
85822*/
85823static int createModule(
85824  sqlite3 *db,                    /* Database in which module is registered */
85825  const char *zName,              /* Name assigned to this module */
85826  const sqlite3_module *pModule,  /* The definition of the module */
85827  void *pAux,                     /* Context pointer for xCreate/xConnect */
85828  void (*xDestroy)(void *)        /* Module destructor function */
85829){
85830  int rc, nName;
85831  Module *pMod;
85832
85833  sqlite3_mutex_enter(db->mutex);
85834  nName = sqlite3Strlen30(zName);
85835  pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
85836  if( pMod ){
85837    Module *pDel;
85838    char *zCopy = (char *)(&pMod[1]);
85839    memcpy(zCopy, zName, nName+1);
85840    pMod->zName = zCopy;
85841    pMod->pModule = pModule;
85842    pMod->pAux = pAux;
85843    pMod->xDestroy = xDestroy;
85844    pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
85845    if( pDel && pDel->xDestroy ){
85846      pDel->xDestroy(pDel->pAux);
85847    }
85848    sqlite3DbFree(db, pDel);
85849    if( pDel==pMod ){
85850      db->mallocFailed = 1;
85851    }
85852    sqlite3ResetInternalSchema(db, 0);
85853  }else if( xDestroy ){
85854    xDestroy(pAux);
85855  }
85856  rc = sqlite3ApiExit(db, SQLITE_OK);
85857  sqlite3_mutex_leave(db->mutex);
85858  return rc;
85859}
85860
85861
85862/*
85863** External API function used to create a new virtual-table module.
85864*/
85865SQLITE_API int sqlite3_create_module(
85866  sqlite3 *db,                    /* Database in which module is registered */
85867  const char *zName,              /* Name assigned to this module */
85868  const sqlite3_module *pModule,  /* The definition of the module */
85869  void *pAux                      /* Context pointer for xCreate/xConnect */
85870){
85871  return createModule(db, zName, pModule, pAux, 0);
85872}
85873
85874/*
85875** External API function used to create a new virtual-table module.
85876*/
85877SQLITE_API int sqlite3_create_module_v2(
85878  sqlite3 *db,                    /* Database in which module is registered */
85879  const char *zName,              /* Name assigned to this module */
85880  const sqlite3_module *pModule,  /* The definition of the module */
85881  void *pAux,                     /* Context pointer for xCreate/xConnect */
85882  void (*xDestroy)(void *)        /* Module destructor function */
85883){
85884  return createModule(db, zName, pModule, pAux, xDestroy);
85885}
85886
85887/*
85888** Lock the virtual table so that it cannot be disconnected.
85889** Locks nest.  Every lock should have a corresponding unlock.
85890** If an unlock is omitted, resources leaks will occur.
85891**
85892** If a disconnect is attempted while a virtual table is locked,
85893** the disconnect is deferred until all locks have been removed.
85894*/
85895SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
85896  pVTab->nRef++;
85897}
85898
85899
85900/*
85901** pTab is a pointer to a Table structure representing a virtual-table.
85902** Return a pointer to the VTable object used by connection db to access
85903** this virtual-table, if one has been created, or NULL otherwise.
85904*/
85905SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
85906  VTable *pVtab;
85907  assert( IsVirtual(pTab) );
85908  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
85909  return pVtab;
85910}
85911
85912/*
85913** Decrement the ref-count on a virtual table object. When the ref-count
85914** reaches zero, call the xDisconnect() method to delete the object.
85915*/
85916SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
85917  sqlite3 *db = pVTab->db;
85918
85919  assert( db );
85920  assert( pVTab->nRef>0 );
85921  assert( sqlite3SafetyCheckOk(db) );
85922
85923  pVTab->nRef--;
85924  if( pVTab->nRef==0 ){
85925    sqlite3_vtab *p = pVTab->pVtab;
85926    if( p ){
85927      p->pModule->xDisconnect(p);
85928    }
85929    sqlite3DbFree(db, pVTab);
85930  }
85931}
85932
85933/*
85934** Table p is a virtual table. This function moves all elements in the
85935** p->pVTable list to the sqlite3.pDisconnect lists of their associated
85936** database connections to be disconnected at the next opportunity.
85937** Except, if argument db is not NULL, then the entry associated with
85938** connection db is left in the p->pVTable list.
85939*/
85940static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
85941  VTable *pRet = 0;
85942  VTable *pVTable = p->pVTable;
85943  p->pVTable = 0;
85944
85945  /* Assert that the mutex (if any) associated with the BtShared database
85946  ** that contains table p is held by the caller. See header comments
85947  ** above function sqlite3VtabUnlockList() for an explanation of why
85948  ** this makes it safe to access the sqlite3.pDisconnect list of any
85949  ** database connection that may have an entry in the p->pVTable list.  */
85950  assert( db==0 ||
85951    sqlite3BtreeHoldsMutex(db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].pBt)
85952  );
85953
85954  while( pVTable ){
85955    sqlite3 *db2 = pVTable->db;
85956    VTable *pNext = pVTable->pNext;
85957    assert( db2 );
85958    if( db2==db ){
85959      pRet = pVTable;
85960      p->pVTable = pRet;
85961      pRet->pNext = 0;
85962    }else{
85963      pVTable->pNext = db2->pDisconnect;
85964      db2->pDisconnect = pVTable;
85965    }
85966    pVTable = pNext;
85967  }
85968
85969  assert( !db || pRet );
85970  return pRet;
85971}
85972
85973
85974/*
85975** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
85976**
85977** This function may only be called when the mutexes associated with all
85978** shared b-tree databases opened using connection db are held by the
85979** caller. This is done to protect the sqlite3.pDisconnect list. The
85980** sqlite3.pDisconnect list is accessed only as follows:
85981**
85982**   1) By this function. In this case, all BtShared mutexes and the mutex
85983**      associated with the database handle itself must be held.
85984**
85985**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
85986**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
85987**      associated with the database the virtual table is stored in is held
85988**      or, if the virtual table is stored in a non-sharable database, then
85989**      the database handle mutex is held.
85990**
85991** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
85992** by multiple threads. It is thread-safe.
85993*/
85994SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
85995  VTable *p = db->pDisconnect;
85996  db->pDisconnect = 0;
85997
85998  assert( sqlite3BtreeHoldsAllMutexes(db) );
85999  assert( sqlite3_mutex_held(db->mutex) );
86000
86001  if( p ){
86002    sqlite3ExpirePreparedStatements(db);
86003    do {
86004      VTable *pNext = p->pNext;
86005      sqlite3VtabUnlock(p);
86006      p = pNext;
86007    }while( p );
86008  }
86009}
86010
86011/*
86012** Clear any and all virtual-table information from the Table record.
86013** This routine is called, for example, just before deleting the Table
86014** record.
86015**
86016** Since it is a virtual-table, the Table structure contains a pointer
86017** to the head of a linked list of VTable structures. Each VTable
86018** structure is associated with a single sqlite3* user of the schema.
86019** The reference count of the VTable structure associated with database
86020** connection db is decremented immediately (which may lead to the
86021** structure being xDisconnected and free). Any other VTable structures
86022** in the list are moved to the sqlite3.pDisconnect list of the associated
86023** database connection.
86024*/
86025SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
86026  vtabDisconnectAll(0, p);
86027  if( p->azModuleArg ){
86028    int i;
86029    for(i=0; i<p->nModuleArg; i++){
86030      sqlite3DbFree(p->dbMem, p->azModuleArg[i]);
86031    }
86032    sqlite3DbFree(p->dbMem, p->azModuleArg);
86033  }
86034}
86035
86036/*
86037** Add a new module argument to pTable->azModuleArg[].
86038** The string is not copied - the pointer is stored.  The
86039** string will be freed automatically when the table is
86040** deleted.
86041*/
86042static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
86043  int i = pTable->nModuleArg++;
86044  int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
86045  char **azModuleArg;
86046  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
86047  if( azModuleArg==0 ){
86048    int j;
86049    for(j=0; j<i; j++){
86050      sqlite3DbFree(db, pTable->azModuleArg[j]);
86051    }
86052    sqlite3DbFree(db, zArg);
86053    sqlite3DbFree(db, pTable->azModuleArg);
86054    pTable->nModuleArg = 0;
86055  }else{
86056    azModuleArg[i] = zArg;
86057    azModuleArg[i+1] = 0;
86058  }
86059  pTable->azModuleArg = azModuleArg;
86060}
86061
86062/*
86063** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
86064** statement.  The module name has been parsed, but the optional list
86065** of parameters that follow the module name are still pending.
86066*/
86067SQLITE_PRIVATE void sqlite3VtabBeginParse(
86068  Parse *pParse,        /* Parsing context */
86069  Token *pName1,        /* Name of new table, or database name */
86070  Token *pName2,        /* Name of new table or NULL */
86071  Token *pModuleName    /* Name of the module for the virtual table */
86072){
86073  int iDb;              /* The database the table is being created in */
86074  Table *pTable;        /* The new virtual table */
86075  sqlite3 *db;          /* Database connection */
86076
86077  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
86078  pTable = pParse->pNewTable;
86079  if( pTable==0 ) return;
86080  assert( 0==pTable->pIndex );
86081
86082  db = pParse->db;
86083  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
86084  assert( iDb>=0 );
86085
86086  pTable->tabFlags |= TF_Virtual;
86087  pTable->nModuleArg = 0;
86088  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
86089  addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
86090  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
86091  pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
86092
86093#ifndef SQLITE_OMIT_AUTHORIZATION
86094  /* Creating a virtual table invokes the authorization callback twice.
86095  ** The first invocation, to obtain permission to INSERT a row into the
86096  ** sqlite_master table, has already been made by sqlite3StartTable().
86097  ** The second call, to obtain permission to create the table, is made now.
86098  */
86099  if( pTable->azModuleArg ){
86100    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
86101            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
86102  }
86103#endif
86104}
86105
86106/*
86107** This routine takes the module argument that has been accumulating
86108** in pParse->zArg[] and appends it to the list of arguments on the
86109** virtual table currently under construction in pParse->pTable.
86110*/
86111static void addArgumentToVtab(Parse *pParse){
86112  if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
86113    const char *z = (const char*)pParse->sArg.z;
86114    int n = pParse->sArg.n;
86115    sqlite3 *db = pParse->db;
86116    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
86117  }
86118}
86119
86120/*
86121** The parser calls this routine after the CREATE VIRTUAL TABLE statement
86122** has been completely parsed.
86123*/
86124SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
86125  Table *pTab = pParse->pNewTable;  /* The table being constructed */
86126  sqlite3 *db = pParse->db;         /* The database connection */
86127
86128  if( pTab==0 ) return;
86129  addArgumentToVtab(pParse);
86130  pParse->sArg.z = 0;
86131  if( pTab->nModuleArg<1 ) return;
86132
86133  /* If the CREATE VIRTUAL TABLE statement is being entered for the
86134  ** first time (in other words if the virtual table is actually being
86135  ** created now instead of just being read out of sqlite_master) then
86136  ** do additional initialization work and store the statement text
86137  ** in the sqlite_master table.
86138  */
86139  if( !db->init.busy ){
86140    char *zStmt;
86141    char *zWhere;
86142    int iDb;
86143    Vdbe *v;
86144
86145    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
86146    if( pEnd ){
86147      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
86148    }
86149    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
86150
86151    /* A slot for the record has already been allocated in the
86152    ** SQLITE_MASTER table.  We just need to update that slot with all
86153    ** the information we've collected.
86154    **
86155    ** The VM register number pParse->regRowid holds the rowid of an
86156    ** entry in the sqlite_master table tht was created for this vtab
86157    ** by sqlite3StartTable().
86158    */
86159    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
86160    sqlite3NestedParse(pParse,
86161      "UPDATE %Q.%s "
86162         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
86163       "WHERE rowid=#%d",
86164      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
86165      pTab->zName,
86166      pTab->zName,
86167      zStmt,
86168      pParse->regRowid
86169    );
86170    sqlite3DbFree(db, zStmt);
86171    v = sqlite3GetVdbe(pParse);
86172    sqlite3ChangeCookie(pParse, iDb);
86173
86174    sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
86175    zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
86176    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
86177    sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
86178                         pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
86179  }
86180
86181  /* If we are rereading the sqlite_master table create the in-memory
86182  ** record of the table. The xConnect() method is not called until
86183  ** the first time the virtual table is used in an SQL statement. This
86184  ** allows a schema that contains virtual tables to be loaded before
86185  ** the required virtual table implementations are registered.  */
86186  else {
86187    Table *pOld;
86188    Schema *pSchema = pTab->pSchema;
86189    const char *zName = pTab->zName;
86190    int nName = sqlite3Strlen30(zName);
86191    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
86192    if( pOld ){
86193      db->mallocFailed = 1;
86194      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
86195      return;
86196    }
86197    pSchema->db = pParse->db;
86198    pParse->pNewTable = 0;
86199  }
86200}
86201
86202/*
86203** The parser calls this routine when it sees the first token
86204** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
86205*/
86206SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
86207  addArgumentToVtab(pParse);
86208  pParse->sArg.z = 0;
86209  pParse->sArg.n = 0;
86210}
86211
86212/*
86213** The parser calls this routine for each token after the first token
86214** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
86215*/
86216SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
86217  Token *pArg = &pParse->sArg;
86218  if( pArg->z==0 ){
86219    pArg->z = p->z;
86220    pArg->n = p->n;
86221  }else{
86222    assert(pArg->z < p->z);
86223    pArg->n = (int)(&p->z[p->n] - pArg->z);
86224  }
86225}
86226
86227/*
86228** Invoke a virtual table constructor (either xCreate or xConnect). The
86229** pointer to the function to invoke is passed as the fourth parameter
86230** to this procedure.
86231*/
86232static int vtabCallConstructor(
86233  sqlite3 *db,
86234  Table *pTab,
86235  Module *pMod,
86236  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
86237  char **pzErr
86238){
86239  VTable *pVTable;
86240  int rc;
86241  const char *const*azArg = (const char *const*)pTab->azModuleArg;
86242  int nArg = pTab->nModuleArg;
86243  char *zErr = 0;
86244  char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
86245
86246  if( !zModuleName ){
86247    return SQLITE_NOMEM;
86248  }
86249
86250  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
86251  if( !pVTable ){
86252    sqlite3DbFree(db, zModuleName);
86253    return SQLITE_NOMEM;
86254  }
86255  pVTable->db = db;
86256  pVTable->pMod = pMod;
86257
86258  assert( !db->pVTab );
86259  assert( xConstruct );
86260  db->pVTab = pTab;
86261
86262  /* Invoke the virtual table constructor */
86263  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
86264  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
86265
86266  if( SQLITE_OK!=rc ){
86267    if( zErr==0 ){
86268      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
86269    }else {
86270      *pzErr = sqlite3MPrintf(db, "%s", zErr);
86271      sqlite3DbFree(db, zErr);
86272    }
86273    sqlite3DbFree(db, pVTable);
86274  }else if( ALWAYS(pVTable->pVtab) ){
86275    /* Justification of ALWAYS():  A correct vtab constructor must allocate
86276    ** the sqlite3_vtab object if successful.  */
86277    pVTable->pVtab->pModule = pMod->pModule;
86278    pVTable->nRef = 1;
86279    if( db->pVTab ){
86280      const char *zFormat = "vtable constructor did not declare schema: %s";
86281      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
86282      sqlite3VtabUnlock(pVTable);
86283      rc = SQLITE_ERROR;
86284    }else{
86285      int iCol;
86286      /* If everything went according to plan, link the new VTable structure
86287      ** into the linked list headed by pTab->pVTable. Then loop through the
86288      ** columns of the table to see if any of them contain the token "hidden".
86289      ** If so, set the Column.isHidden flag and remove the token from
86290      ** the type string.  */
86291      pVTable->pNext = pTab->pVTable;
86292      pTab->pVTable = pVTable;
86293
86294      for(iCol=0; iCol<pTab->nCol; iCol++){
86295        char *zType = pTab->aCol[iCol].zType;
86296        int nType;
86297        int i = 0;
86298        if( !zType ) continue;
86299        nType = sqlite3Strlen30(zType);
86300        if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
86301          for(i=0; i<nType; i++){
86302            if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
86303             && (zType[i+7]=='\0' || zType[i+7]==' ')
86304            ){
86305              i++;
86306              break;
86307            }
86308          }
86309        }
86310        if( i<nType ){
86311          int j;
86312          int nDel = 6 + (zType[i+6] ? 1 : 0);
86313          for(j=i; (j+nDel)<=nType; j++){
86314            zType[j] = zType[j+nDel];
86315          }
86316          if( zType[i]=='\0' && i>0 ){
86317            assert(zType[i-1]==' ');
86318            zType[i-1] = '\0';
86319          }
86320          pTab->aCol[iCol].isHidden = 1;
86321        }
86322      }
86323    }
86324  }
86325
86326  sqlite3DbFree(db, zModuleName);
86327  db->pVTab = 0;
86328  return rc;
86329}
86330
86331/*
86332** This function is invoked by the parser to call the xConnect() method
86333** of the virtual table pTab. If an error occurs, an error code is returned
86334** and an error left in pParse.
86335**
86336** This call is a no-op if table pTab is not a virtual table.
86337*/
86338SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
86339  sqlite3 *db = pParse->db;
86340  const char *zMod;
86341  Module *pMod;
86342  int rc;
86343
86344  assert( pTab );
86345  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
86346    return SQLITE_OK;
86347  }
86348
86349  /* Locate the required virtual table module */
86350  zMod = pTab->azModuleArg[0];
86351  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
86352
86353  if( !pMod ){
86354    const char *zModule = pTab->azModuleArg[0];
86355    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
86356    rc = SQLITE_ERROR;
86357  }else{
86358    char *zErr = 0;
86359    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
86360    if( rc!=SQLITE_OK ){
86361      sqlite3ErrorMsg(pParse, "%s", zErr);
86362    }
86363    sqlite3DbFree(db, zErr);
86364  }
86365
86366  return rc;
86367}
86368
86369/*
86370** Add the virtual table pVTab to the array sqlite3.aVTrans[].
86371*/
86372static int addToVTrans(sqlite3 *db, VTable *pVTab){
86373  const int ARRAY_INCR = 5;
86374
86375  /* Grow the sqlite3.aVTrans array if required */
86376  if( (db->nVTrans%ARRAY_INCR)==0 ){
86377    VTable **aVTrans;
86378    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
86379    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
86380    if( !aVTrans ){
86381      return SQLITE_NOMEM;
86382    }
86383    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
86384    db->aVTrans = aVTrans;
86385  }
86386
86387  /* Add pVtab to the end of sqlite3.aVTrans */
86388  db->aVTrans[db->nVTrans++] = pVTab;
86389  sqlite3VtabLock(pVTab);
86390  return SQLITE_OK;
86391}
86392
86393/*
86394** This function is invoked by the vdbe to call the xCreate method
86395** of the virtual table named zTab in database iDb.
86396**
86397** If an error occurs, *pzErr is set to point an an English language
86398** description of the error and an SQLITE_XXX error code is returned.
86399** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
86400*/
86401SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
86402  int rc = SQLITE_OK;
86403  Table *pTab;
86404  Module *pMod;
86405  const char *zMod;
86406
86407  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
86408  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
86409
86410  /* Locate the required virtual table module */
86411  zMod = pTab->azModuleArg[0];
86412  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
86413
86414  /* If the module has been registered and includes a Create method,
86415  ** invoke it now. If the module has not been registered, return an
86416  ** error. Otherwise, do nothing.
86417  */
86418  if( !pMod ){
86419    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
86420    rc = SQLITE_ERROR;
86421  }else{
86422    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
86423  }
86424
86425  /* Justification of ALWAYS():  The xConstructor method is required to
86426  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
86427  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
86428      rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
86429  }
86430
86431  return rc;
86432}
86433
86434/*
86435** This function is used to set the schema of a virtual table.  It is only
86436** valid to call this function from within the xCreate() or xConnect() of a
86437** virtual table module.
86438*/
86439SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
86440  Parse *pParse;
86441
86442  int rc = SQLITE_OK;
86443  Table *pTab;
86444  char *zErr = 0;
86445
86446  sqlite3_mutex_enter(db->mutex);
86447  pTab = db->pVTab;
86448  if( !pTab ){
86449    sqlite3Error(db, SQLITE_MISUSE, 0);
86450    sqlite3_mutex_leave(db->mutex);
86451    return SQLITE_MISUSE_BKPT;
86452  }
86453  assert( (pTab->tabFlags & TF_Virtual)!=0 );
86454
86455  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
86456  if( pParse==0 ){
86457    rc = SQLITE_NOMEM;
86458  }else{
86459    pParse->declareVtab = 1;
86460    pParse->db = db;
86461
86462    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
86463     && pParse->pNewTable
86464     && !db->mallocFailed
86465     && !pParse->pNewTable->pSelect
86466     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
86467    ){
86468      if( !pTab->aCol ){
86469        pTab->aCol = pParse->pNewTable->aCol;
86470        pTab->nCol = pParse->pNewTable->nCol;
86471        pParse->pNewTable->nCol = 0;
86472        pParse->pNewTable->aCol = 0;
86473      }
86474      db->pVTab = 0;
86475    }else{
86476      sqlite3Error(db, SQLITE_ERROR, zErr);
86477      sqlite3DbFree(db, zErr);
86478      rc = SQLITE_ERROR;
86479    }
86480    pParse->declareVtab = 0;
86481
86482    if( pParse->pVdbe ){
86483      sqlite3VdbeFinalize(pParse->pVdbe);
86484    }
86485    sqlite3DeleteTable(pParse->pNewTable);
86486    sqlite3StackFree(db, pParse);
86487  }
86488
86489  assert( (rc&0xff)==rc );
86490  rc = sqlite3ApiExit(db, rc);
86491  sqlite3_mutex_leave(db->mutex);
86492  return rc;
86493}
86494
86495/*
86496** This function is invoked by the vdbe to call the xDestroy method
86497** of the virtual table named zTab in database iDb. This occurs
86498** when a DROP TABLE is mentioned.
86499**
86500** This call is a no-op if zTab is not a virtual table.
86501*/
86502SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
86503  int rc = SQLITE_OK;
86504  Table *pTab;
86505
86506  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
86507  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
86508    VTable *p = vtabDisconnectAll(db, pTab);
86509
86510    assert( rc==SQLITE_OK );
86511    rc = p->pMod->pModule->xDestroy(p->pVtab);
86512
86513    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
86514    if( rc==SQLITE_OK ){
86515      assert( pTab->pVTable==p && p->pNext==0 );
86516      p->pVtab = 0;
86517      pTab->pVTable = 0;
86518      sqlite3VtabUnlock(p);
86519    }
86520  }
86521
86522  return rc;
86523}
86524
86525/*
86526** This function invokes either the xRollback or xCommit method
86527** of each of the virtual tables in the sqlite3.aVTrans array. The method
86528** called is identified by the second argument, "offset", which is
86529** the offset of the method to call in the sqlite3_module structure.
86530**
86531** The array is cleared after invoking the callbacks.
86532*/
86533static void callFinaliser(sqlite3 *db, int offset){
86534  int i;
86535  if( db->aVTrans ){
86536    for(i=0; i<db->nVTrans; i++){
86537      VTable *pVTab = db->aVTrans[i];
86538      sqlite3_vtab *p = pVTab->pVtab;
86539      if( p ){
86540        int (*x)(sqlite3_vtab *);
86541        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
86542        if( x ) x(p);
86543      }
86544      sqlite3VtabUnlock(pVTab);
86545    }
86546    sqlite3DbFree(db, db->aVTrans);
86547    db->nVTrans = 0;
86548    db->aVTrans = 0;
86549  }
86550}
86551
86552/*
86553** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
86554** array. Return the error code for the first error that occurs, or
86555** SQLITE_OK if all xSync operations are successful.
86556**
86557** Set *pzErrmsg to point to a buffer that should be released using
86558** sqlite3DbFree() containing an error message, if one is available.
86559*/
86560SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
86561  int i;
86562  int rc = SQLITE_OK;
86563  VTable **aVTrans = db->aVTrans;
86564
86565  db->aVTrans = 0;
86566  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
86567    int (*x)(sqlite3_vtab *);
86568    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
86569    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
86570      rc = x(pVtab);
86571      sqlite3DbFree(db, *pzErrmsg);
86572      *pzErrmsg = pVtab->zErrMsg;
86573      pVtab->zErrMsg = 0;
86574    }
86575  }
86576  db->aVTrans = aVTrans;
86577  return rc;
86578}
86579
86580/*
86581** Invoke the xRollback method of all virtual tables in the
86582** sqlite3.aVTrans array. Then clear the array itself.
86583*/
86584SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
86585  callFinaliser(db, offsetof(sqlite3_module,xRollback));
86586  return SQLITE_OK;
86587}
86588
86589/*
86590** Invoke the xCommit method of all virtual tables in the
86591** sqlite3.aVTrans array. Then clear the array itself.
86592*/
86593SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
86594  callFinaliser(db, offsetof(sqlite3_module,xCommit));
86595  return SQLITE_OK;
86596}
86597
86598/*
86599** If the virtual table pVtab supports the transaction interface
86600** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
86601** not currently open, invoke the xBegin method now.
86602**
86603** If the xBegin call is successful, place the sqlite3_vtab pointer
86604** in the sqlite3.aVTrans array.
86605*/
86606SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
86607  int rc = SQLITE_OK;
86608  const sqlite3_module *pModule;
86609
86610  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
86611  ** than zero, then this function is being called from within a
86612  ** virtual module xSync() callback. It is illegal to write to
86613  ** virtual module tables in this case, so return SQLITE_LOCKED.
86614  */
86615  if( sqlite3VtabInSync(db) ){
86616    return SQLITE_LOCKED;
86617  }
86618  if( !pVTab ){
86619    return SQLITE_OK;
86620  }
86621  pModule = pVTab->pVtab->pModule;
86622
86623  if( pModule->xBegin ){
86624    int i;
86625
86626
86627    /* If pVtab is already in the aVTrans array, return early */
86628    for(i=0; i<db->nVTrans; i++){
86629      if( db->aVTrans[i]==pVTab ){
86630        return SQLITE_OK;
86631      }
86632    }
86633
86634    /* Invoke the xBegin method */
86635    rc = pModule->xBegin(pVTab->pVtab);
86636    if( rc==SQLITE_OK ){
86637      rc = addToVTrans(db, pVTab);
86638    }
86639  }
86640  return rc;
86641}
86642
86643/*
86644** The first parameter (pDef) is a function implementation.  The
86645** second parameter (pExpr) is the first argument to this function.
86646** If pExpr is a column in a virtual table, then let the virtual
86647** table implementation have an opportunity to overload the function.
86648**
86649** This routine is used to allow virtual table implementations to
86650** overload MATCH, LIKE, GLOB, and REGEXP operators.
86651**
86652** Return either the pDef argument (indicating no change) or a
86653** new FuncDef structure that is marked as ephemeral using the
86654** SQLITE_FUNC_EPHEM flag.
86655*/
86656SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
86657  sqlite3 *db,    /* Database connection for reporting malloc problems */
86658  FuncDef *pDef,  /* Function to possibly overload */
86659  int nArg,       /* Number of arguments to the function */
86660  Expr *pExpr     /* First argument to the function */
86661){
86662  Table *pTab;
86663  sqlite3_vtab *pVtab;
86664  sqlite3_module *pMod;
86665  void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
86666  void *pArg = 0;
86667  FuncDef *pNew;
86668  int rc = 0;
86669  char *zLowerName;
86670  unsigned char *z;
86671
86672
86673  /* Check to see the left operand is a column in a virtual table */
86674  if( NEVER(pExpr==0) ) return pDef;
86675  if( pExpr->op!=TK_COLUMN ) return pDef;
86676  pTab = pExpr->pTab;
86677  if( NEVER(pTab==0) ) return pDef;
86678  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
86679  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
86680  assert( pVtab!=0 );
86681  assert( pVtab->pModule!=0 );
86682  pMod = (sqlite3_module *)pVtab->pModule;
86683  if( pMod->xFindFunction==0 ) return pDef;
86684
86685  /* Call the xFindFunction method on the virtual table implementation
86686  ** to see if the implementation wants to overload this function
86687  */
86688  zLowerName = sqlite3DbStrDup(db, pDef->zName);
86689  if( zLowerName ){
86690    for(z=(unsigned char*)zLowerName; *z; z++){
86691      *z = sqlite3UpperToLower[*z];
86692    }
86693    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
86694    sqlite3DbFree(db, zLowerName);
86695  }
86696  if( rc==0 ){
86697    return pDef;
86698  }
86699
86700  /* Create a new ephemeral function definition for the overloaded
86701  ** function */
86702  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
86703                             + sqlite3Strlen30(pDef->zName) + 1);
86704  if( pNew==0 ){
86705    return pDef;
86706  }
86707  *pNew = *pDef;
86708  pNew->zName = (char *)&pNew[1];
86709  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
86710  pNew->xFunc = xFunc;
86711  pNew->pUserData = pArg;
86712  pNew->flags |= SQLITE_FUNC_EPHEM;
86713  return pNew;
86714}
86715
86716/*
86717** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
86718** array so that an OP_VBegin will get generated for it.  Add pTab to the
86719** array if it is missing.  If pTab is already in the array, this routine
86720** is a no-op.
86721*/
86722SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
86723  Parse *pToplevel = sqlite3ParseToplevel(pParse);
86724  int i, n;
86725  Table **apVtabLock;
86726
86727  assert( IsVirtual(pTab) );
86728  for(i=0; i<pToplevel->nVtabLock; i++){
86729    if( pTab==pToplevel->apVtabLock[i] ) return;
86730  }
86731  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
86732  apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
86733  if( apVtabLock ){
86734    pToplevel->apVtabLock = apVtabLock;
86735    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
86736  }else{
86737    pToplevel->db->mallocFailed = 1;
86738  }
86739}
86740
86741#endif /* SQLITE_OMIT_VIRTUALTABLE */
86742
86743/************** End of vtab.c ************************************************/
86744/************** Begin file where.c *******************************************/
86745/*
86746** 2001 September 15
86747**
86748** The author disclaims copyright to this source code.  In place of
86749** a legal notice, here is a blessing:
86750**
86751**    May you do good and not evil.
86752**    May you find forgiveness for yourself and forgive others.
86753**    May you share freely, never taking more than you give.
86754**
86755*************************************************************************
86756** This module contains C code that generates VDBE code used to process
86757** the WHERE clause of SQL statements.  This module is responsible for
86758** generating the code that loops through a table looking for applicable
86759** rows.  Indices are selected and used to speed the search when doing
86760** so is applicable.  Because this module is responsible for selecting
86761** indices, you might also think of this module as the "query optimizer".
86762*/
86763
86764/*
86765** Trace output macros
86766*/
86767#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
86768SQLITE_PRIVATE int sqlite3WhereTrace = 0;
86769#endif
86770#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
86771# define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
86772#else
86773# define WHERETRACE(X)
86774#endif
86775
86776/* Forward reference
86777*/
86778typedef struct WhereClause WhereClause;
86779typedef struct WhereMaskSet WhereMaskSet;
86780typedef struct WhereOrInfo WhereOrInfo;
86781typedef struct WhereAndInfo WhereAndInfo;
86782typedef struct WhereCost WhereCost;
86783
86784/*
86785** The query generator uses an array of instances of this structure to
86786** help it analyze the subexpressions of the WHERE clause.  Each WHERE
86787** clause subexpression is separated from the others by AND operators,
86788** usually, or sometimes subexpressions separated by OR.
86789**
86790** All WhereTerms are collected into a single WhereClause structure.
86791** The following identity holds:
86792**
86793**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
86794**
86795** When a term is of the form:
86796**
86797**              X <op> <expr>
86798**
86799** where X is a column name and <op> is one of certain operators,
86800** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
86801** cursor number and column number for X.  WhereTerm.eOperator records
86802** the <op> using a bitmask encoding defined by WO_xxx below.  The
86803** use of a bitmask encoding for the operator allows us to search
86804** quickly for terms that match any of several different operators.
86805**
86806** A WhereTerm might also be two or more subterms connected by OR:
86807**
86808**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
86809**
86810** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
86811** and the WhereTerm.u.pOrInfo field points to auxiliary information that
86812** is collected about the
86813**
86814** If a term in the WHERE clause does not match either of the two previous
86815** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
86816** to the original subexpression content and wtFlags is set up appropriately
86817** but no other fields in the WhereTerm object are meaningful.
86818**
86819** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
86820** but they do so indirectly.  A single WhereMaskSet structure translates
86821** cursor number into bits and the translated bit is stored in the prereq
86822** fields.  The translation is used in order to maximize the number of
86823** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
86824** spread out over the non-negative integers.  For example, the cursor
86825** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
86826** translates these sparse cursor numbers into consecutive integers
86827** beginning with 0 in order to make the best possible use of the available
86828** bits in the Bitmask.  So, in the example above, the cursor numbers
86829** would be mapped into integers 0 through 7.
86830**
86831** The number of terms in a join is limited by the number of bits
86832** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
86833** is only able to process joins with 64 or fewer tables.
86834*/
86835typedef struct WhereTerm WhereTerm;
86836struct WhereTerm {
86837  Expr *pExpr;            /* Pointer to the subexpression that is this term */
86838  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
86839  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
86840  union {
86841    int leftColumn;         /* Column number of X in "X <op> <expr>" */
86842    WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
86843    WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
86844  } u;
86845  u16 eOperator;          /* A WO_xx value describing <op> */
86846  u8 wtFlags;             /* TERM_xxx bit flags.  See below */
86847  u8 nChild;              /* Number of children that must disable us */
86848  WhereClause *pWC;       /* The clause this term is part of */
86849  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
86850  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
86851};
86852
86853/*
86854** Allowed values of WhereTerm.wtFlags
86855*/
86856#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
86857#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
86858#define TERM_CODED      0x04   /* This term is already coded */
86859#define TERM_COPIED     0x08   /* Has a child */
86860#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
86861#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
86862#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
86863
86864/*
86865** An instance of the following structure holds all information about a
86866** WHERE clause.  Mostly this is a container for one or more WhereTerms.
86867*/
86868struct WhereClause {
86869  Parse *pParse;           /* The parser context */
86870  WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
86871  Bitmask vmask;           /* Bitmask identifying virtual table cursors */
86872  u8 op;                   /* Split operator.  TK_AND or TK_OR */
86873  int nTerm;               /* Number of terms */
86874  int nSlot;               /* Number of entries in a[] */
86875  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
86876#if defined(SQLITE_SMALL_STACK)
86877  WhereTerm aStatic[1];    /* Initial static space for a[] */
86878#else
86879  WhereTerm aStatic[8];    /* Initial static space for a[] */
86880#endif
86881};
86882
86883/*
86884** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
86885** a dynamically allocated instance of the following structure.
86886*/
86887struct WhereOrInfo {
86888  WhereClause wc;          /* Decomposition into subterms */
86889  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
86890};
86891
86892/*
86893** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
86894** a dynamically allocated instance of the following structure.
86895*/
86896struct WhereAndInfo {
86897  WhereClause wc;          /* The subexpression broken out */
86898};
86899
86900/*
86901** An instance of the following structure keeps track of a mapping
86902** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
86903**
86904** The VDBE cursor numbers are small integers contained in
86905** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
86906** clause, the cursor numbers might not begin with 0 and they might
86907** contain gaps in the numbering sequence.  But we want to make maximum
86908** use of the bits in our bitmasks.  This structure provides a mapping
86909** from the sparse cursor numbers into consecutive integers beginning
86910** with 0.
86911**
86912** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
86913** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
86914**
86915** For example, if the WHERE clause expression used these VDBE
86916** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
86917** would map those cursor numbers into bits 0 through 5.
86918**
86919** Note that the mapping is not necessarily ordered.  In the example
86920** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
86921** 57->5, 73->4.  Or one of 719 other combinations might be used. It
86922** does not really matter.  What is important is that sparse cursor
86923** numbers all get mapped into bit numbers that begin with 0 and contain
86924** no gaps.
86925*/
86926struct WhereMaskSet {
86927  int n;                        /* Number of assigned cursor values */
86928  int ix[BMS];                  /* Cursor assigned to each bit */
86929};
86930
86931/*
86932** A WhereCost object records a lookup strategy and the estimated
86933** cost of pursuing that strategy.
86934*/
86935struct WhereCost {
86936  WherePlan plan;    /* The lookup strategy */
86937  double rCost;      /* Overall cost of pursuing this search strategy */
86938  double nRow;       /* Estimated number of output rows */
86939  Bitmask used;      /* Bitmask of cursors used by this plan */
86940};
86941
86942/*
86943** Bitmasks for the operators that indices are able to exploit.  An
86944** OR-ed combination of these values can be used when searching for
86945** terms in the where clause.
86946*/
86947#define WO_IN     0x001
86948#define WO_EQ     0x002
86949#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
86950#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
86951#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
86952#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
86953#define WO_MATCH  0x040
86954#define WO_ISNULL 0x080
86955#define WO_OR     0x100       /* Two or more OR-connected terms */
86956#define WO_AND    0x200       /* Two or more AND-connected terms */
86957
86958#define WO_ALL    0xfff       /* Mask of all possible WO_* values */
86959#define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
86960
86961/*
86962** Value for wsFlags returned by bestIndex() and stored in
86963** WhereLevel.wsFlags.  These flags determine which search
86964** strategies are appropriate.
86965**
86966** The least significant 12 bits is reserved as a mask for WO_ values above.
86967** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
86968** But if the table is the right table of a left join, WhereLevel.wsFlags
86969** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
86970** the "op" parameter to findTerm when we are resolving equality constraints.
86971** ISNULL constraints will then not be used on the right table of a left
86972** join.  Tickets #2177 and #2189.
86973*/
86974#define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
86975#define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
86976#define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
86977#define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
86978#define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
86979#define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
86980#define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
86981#define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
86982#define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
86983#define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
86984#define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
86985#define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
86986#define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
86987#define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
86988#define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
86989#define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
86990
86991/*
86992** Initialize a preallocated WhereClause structure.
86993*/
86994static void whereClauseInit(
86995  WhereClause *pWC,        /* The WhereClause to be initialized */
86996  Parse *pParse,           /* The parsing context */
86997  WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
86998){
86999  pWC->pParse = pParse;
87000  pWC->pMaskSet = pMaskSet;
87001  pWC->nTerm = 0;
87002  pWC->nSlot = ArraySize(pWC->aStatic);
87003  pWC->a = pWC->aStatic;
87004  pWC->vmask = 0;
87005}
87006
87007/* Forward reference */
87008static void whereClauseClear(WhereClause*);
87009
87010/*
87011** Deallocate all memory associated with a WhereOrInfo object.
87012*/
87013static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
87014  whereClauseClear(&p->wc);
87015  sqlite3DbFree(db, p);
87016}
87017
87018/*
87019** Deallocate all memory associated with a WhereAndInfo object.
87020*/
87021static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
87022  whereClauseClear(&p->wc);
87023  sqlite3DbFree(db, p);
87024}
87025
87026/*
87027** Deallocate a WhereClause structure.  The WhereClause structure
87028** itself is not freed.  This routine is the inverse of whereClauseInit().
87029*/
87030static void whereClauseClear(WhereClause *pWC){
87031  int i;
87032  WhereTerm *a;
87033  sqlite3 *db = pWC->pParse->db;
87034  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
87035    if( a->wtFlags & TERM_DYNAMIC ){
87036      sqlite3ExprDelete(db, a->pExpr);
87037    }
87038    if( a->wtFlags & TERM_ORINFO ){
87039      whereOrInfoDelete(db, a->u.pOrInfo);
87040    }else if( a->wtFlags & TERM_ANDINFO ){
87041      whereAndInfoDelete(db, a->u.pAndInfo);
87042    }
87043  }
87044  if( pWC->a!=pWC->aStatic ){
87045    sqlite3DbFree(db, pWC->a);
87046  }
87047}
87048
87049/*
87050** Add a single new WhereTerm entry to the WhereClause object pWC.
87051** The new WhereTerm object is constructed from Expr p and with wtFlags.
87052** The index in pWC->a[] of the new WhereTerm is returned on success.
87053** 0 is returned if the new WhereTerm could not be added due to a memory
87054** allocation error.  The memory allocation failure will be recorded in
87055** the db->mallocFailed flag so that higher-level functions can detect it.
87056**
87057** This routine will increase the size of the pWC->a[] array as necessary.
87058**
87059** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
87060** for freeing the expression p is assumed by the WhereClause object pWC.
87061** This is true even if this routine fails to allocate a new WhereTerm.
87062**
87063** WARNING:  This routine might reallocate the space used to store
87064** WhereTerms.  All pointers to WhereTerms should be invalidated after
87065** calling this routine.  Such pointers may be reinitialized by referencing
87066** the pWC->a[] array.
87067*/
87068static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
87069  WhereTerm *pTerm;
87070  int idx;
87071  if( pWC->nTerm>=pWC->nSlot ){
87072    WhereTerm *pOld = pWC->a;
87073    sqlite3 *db = pWC->pParse->db;
87074    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
87075    if( pWC->a==0 ){
87076      if( wtFlags & TERM_DYNAMIC ){
87077        sqlite3ExprDelete(db, p);
87078      }
87079      pWC->a = pOld;
87080      return 0;
87081    }
87082    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
87083    if( pOld!=pWC->aStatic ){
87084      sqlite3DbFree(db, pOld);
87085    }
87086    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
87087  }
87088  pTerm = &pWC->a[idx = pWC->nTerm++];
87089  pTerm->pExpr = p;
87090  pTerm->wtFlags = wtFlags;
87091  pTerm->pWC = pWC;
87092  pTerm->iParent = -1;
87093  return idx;
87094}
87095
87096/*
87097** This routine identifies subexpressions in the WHERE clause where
87098** each subexpression is separated by the AND operator or some other
87099** operator specified in the op parameter.  The WhereClause structure
87100** is filled with pointers to subexpressions.  For example:
87101**
87102**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
87103**           \________/     \_______________/     \________________/
87104**            slot[0]            slot[1]               slot[2]
87105**
87106** The original WHERE clause in pExpr is unaltered.  All this routine
87107** does is make slot[] entries point to substructure within pExpr.
87108**
87109** In the previous sentence and in the diagram, "slot[]" refers to
87110** the WhereClause.a[] array.  The slot[] array grows as needed to contain
87111** all terms of the WHERE clause.
87112*/
87113static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
87114  pWC->op = (u8)op;
87115  if( pExpr==0 ) return;
87116  if( pExpr->op!=op ){
87117    whereClauseInsert(pWC, pExpr, 0);
87118  }else{
87119    whereSplit(pWC, pExpr->pLeft, op);
87120    whereSplit(pWC, pExpr->pRight, op);
87121  }
87122}
87123
87124/*
87125** Initialize an expression mask set (a WhereMaskSet object)
87126*/
87127#define initMaskSet(P)  memset(P, 0, sizeof(*P))
87128
87129/*
87130** Return the bitmask for the given cursor number.  Return 0 if
87131** iCursor is not in the set.
87132*/
87133static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
87134  int i;
87135  assert( pMaskSet->n<=sizeof(Bitmask)*8 );
87136  for(i=0; i<pMaskSet->n; i++){
87137    if( pMaskSet->ix[i]==iCursor ){
87138      return ((Bitmask)1)<<i;
87139    }
87140  }
87141  return 0;
87142}
87143
87144/*
87145** Create a new mask for cursor iCursor.
87146**
87147** There is one cursor per table in the FROM clause.  The number of
87148** tables in the FROM clause is limited by a test early in the
87149** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
87150** array will never overflow.
87151*/
87152static void createMask(WhereMaskSet *pMaskSet, int iCursor){
87153  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
87154  pMaskSet->ix[pMaskSet->n++] = iCursor;
87155}
87156
87157/*
87158** This routine walks (recursively) an expression tree and generates
87159** a bitmask indicating which tables are used in that expression
87160** tree.
87161**
87162** In order for this routine to work, the calling function must have
87163** previously invoked sqlite3ResolveExprNames() on the expression.  See
87164** the header comment on that routine for additional information.
87165** The sqlite3ResolveExprNames() routines looks for column names and
87166** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
87167** the VDBE cursor number of the table.  This routine just has to
87168** translate the cursor numbers into bitmask values and OR all
87169** the bitmasks together.
87170*/
87171static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
87172static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
87173static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
87174  Bitmask mask = 0;
87175  if( p==0 ) return 0;
87176  if( p->op==TK_COLUMN ){
87177    mask = getMask(pMaskSet, p->iTable);
87178    return mask;
87179  }
87180  mask = exprTableUsage(pMaskSet, p->pRight);
87181  mask |= exprTableUsage(pMaskSet, p->pLeft);
87182  if( ExprHasProperty(p, EP_xIsSelect) ){
87183    mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
87184  }else{
87185    mask |= exprListTableUsage(pMaskSet, p->x.pList);
87186  }
87187  return mask;
87188}
87189static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
87190  int i;
87191  Bitmask mask = 0;
87192  if( pList ){
87193    for(i=0; i<pList->nExpr; i++){
87194      mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
87195    }
87196  }
87197  return mask;
87198}
87199static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
87200  Bitmask mask = 0;
87201  while( pS ){
87202    mask |= exprListTableUsage(pMaskSet, pS->pEList);
87203    mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
87204    mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
87205    mask |= exprTableUsage(pMaskSet, pS->pWhere);
87206    mask |= exprTableUsage(pMaskSet, pS->pHaving);
87207    pS = pS->pPrior;
87208  }
87209  return mask;
87210}
87211
87212/*
87213** Return TRUE if the given operator is one of the operators that is
87214** allowed for an indexable WHERE clause term.  The allowed operators are
87215** "=", "<", ">", "<=", ">=", and "IN".
87216*/
87217static int allowedOp(int op){
87218  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
87219  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
87220  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
87221  assert( TK_GE==TK_EQ+4 );
87222  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
87223}
87224
87225/*
87226** Swap two objects of type TYPE.
87227*/
87228#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
87229
87230/*
87231** Commute a comparison operator.  Expressions of the form "X op Y"
87232** are converted into "Y op X".
87233**
87234** If a collation sequence is associated with either the left or right
87235** side of the comparison, it remains associated with the same side after
87236** the commutation. So "Y collate NOCASE op X" becomes
87237** "X collate NOCASE op Y". This is because any collation sequence on
87238** the left hand side of a comparison overrides any collation sequence
87239** attached to the right. For the same reason the EP_ExpCollate flag
87240** is not commuted.
87241*/
87242static void exprCommute(Parse *pParse, Expr *pExpr){
87243  u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
87244  u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
87245  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
87246  pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
87247  pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
87248  SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
87249  pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
87250  pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
87251  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
87252  if( pExpr->op>=TK_GT ){
87253    assert( TK_LT==TK_GT+2 );
87254    assert( TK_GE==TK_LE+2 );
87255    assert( TK_GT>TK_EQ );
87256    assert( TK_GT<TK_LE );
87257    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
87258    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
87259  }
87260}
87261
87262/*
87263** Translate from TK_xx operator to WO_xx bitmask.
87264*/
87265static u16 operatorMask(int op){
87266  u16 c;
87267  assert( allowedOp(op) );
87268  if( op==TK_IN ){
87269    c = WO_IN;
87270  }else if( op==TK_ISNULL ){
87271    c = WO_ISNULL;
87272  }else{
87273    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
87274    c = (u16)(WO_EQ<<(op-TK_EQ));
87275  }
87276  assert( op!=TK_ISNULL || c==WO_ISNULL );
87277  assert( op!=TK_IN || c==WO_IN );
87278  assert( op!=TK_EQ || c==WO_EQ );
87279  assert( op!=TK_LT || c==WO_LT );
87280  assert( op!=TK_LE || c==WO_LE );
87281  assert( op!=TK_GT || c==WO_GT );
87282  assert( op!=TK_GE || c==WO_GE );
87283  return c;
87284}
87285
87286/*
87287** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
87288** where X is a reference to the iColumn of table iCur and <op> is one of
87289** the WO_xx operator codes specified by the op parameter.
87290** Return a pointer to the term.  Return 0 if not found.
87291*/
87292static WhereTerm *findTerm(
87293  WhereClause *pWC,     /* The WHERE clause to be searched */
87294  int iCur,             /* Cursor number of LHS */
87295  int iColumn,          /* Column number of LHS */
87296  Bitmask notReady,     /* RHS must not overlap with this mask */
87297  u32 op,               /* Mask of WO_xx values describing operator */
87298  Index *pIdx           /* Must be compatible with this index, if not NULL */
87299){
87300  WhereTerm *pTerm;
87301  int k;
87302  assert( iCur>=0 );
87303  op &= WO_ALL;
87304  for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
87305    if( pTerm->leftCursor==iCur
87306       && (pTerm->prereqRight & notReady)==0
87307       && pTerm->u.leftColumn==iColumn
87308       && (pTerm->eOperator & op)!=0
87309    ){
87310      if( pIdx && pTerm->eOperator!=WO_ISNULL ){
87311        Expr *pX = pTerm->pExpr;
87312        CollSeq *pColl;
87313        char idxaff;
87314        int j;
87315        Parse *pParse = pWC->pParse;
87316
87317        idxaff = pIdx->pTable->aCol[iColumn].affinity;
87318        if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
87319
87320        /* Figure out the collation sequence required from an index for
87321        ** it to be useful for optimising expression pX. Store this
87322        ** value in variable pColl.
87323        */
87324        assert(pX->pLeft);
87325        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
87326        assert(pColl || pParse->nErr);
87327
87328        for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
87329          if( NEVER(j>=pIdx->nColumn) ) return 0;
87330        }
87331        if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
87332      }
87333      return pTerm;
87334    }
87335  }
87336  return 0;
87337}
87338
87339/* Forward reference */
87340static void exprAnalyze(SrcList*, WhereClause*, int);
87341
87342/*
87343** Call exprAnalyze on all terms in a WHERE clause.
87344**
87345**
87346*/
87347static void exprAnalyzeAll(
87348  SrcList *pTabList,       /* the FROM clause */
87349  WhereClause *pWC         /* the WHERE clause to be analyzed */
87350){
87351  int i;
87352  for(i=pWC->nTerm-1; i>=0; i--){
87353    exprAnalyze(pTabList, pWC, i);
87354  }
87355}
87356
87357#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
87358/*
87359** Check to see if the given expression is a LIKE or GLOB operator that
87360** can be optimized using inequality constraints.  Return TRUE if it is
87361** so and false if not.
87362**
87363** In order for the operator to be optimizible, the RHS must be a string
87364** literal that does not begin with a wildcard.
87365*/
87366static int isLikeOrGlob(
87367  Parse *pParse,    /* Parsing and code generating context */
87368  Expr *pExpr,      /* Test this expression */
87369  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
87370  int *pisComplete, /* True if the only wildcard is % in the last character */
87371  int *pnoCase      /* True if uppercase is equivalent to lowercase */
87372){
87373  const char *z = 0;         /* String on RHS of LIKE operator */
87374  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
87375  ExprList *pList;           /* List of operands to the LIKE operator */
87376  int c;                     /* One character in z[] */
87377  int cnt;                   /* Number of non-wildcard prefix characters */
87378  char wc[3];                /* Wildcard characters */
87379  CollSeq *pColl;            /* Collating sequence for LHS */
87380  sqlite3 *db = pParse->db;  /* Database connection */
87381  sqlite3_value *pVal = 0;
87382  int op;                    /* Opcode of pRight */
87383
87384  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
87385    return 0;
87386  }
87387#ifdef SQLITE_EBCDIC
87388  if( *pnoCase ) return 0;
87389#endif
87390  pList = pExpr->x.pList;
87391  pLeft = pList->a[1].pExpr;
87392  if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
87393    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
87394    ** be the name of an indexed column with TEXT affinity. */
87395    return 0;
87396  }
87397  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
87398  pColl = sqlite3ExprCollSeq(pParse, pLeft);
87399  assert( pColl!=0 );  /* Every non-IPK column has a collating sequence */
87400  if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
87401      (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
87402    /* IMP: R-09003-32046 For the GLOB operator, the column must use the
87403    ** default BINARY collating sequence.
87404    ** IMP: R-41408-28306 For the LIKE operator, if case_sensitive_like mode
87405    ** is enabled then the column must use the default BINARY collating
87406    ** sequence, or if case_sensitive_like mode is disabled then the column
87407    ** must use the built-in NOCASE collating sequence.
87408    */
87409    return 0;
87410  }
87411
87412  pRight = pList->a[0].pExpr;
87413  op = pRight->op;
87414  if( op==TK_REGISTER ){
87415    op = pRight->op2;
87416  }
87417  if( op==TK_VARIABLE ){
87418    Vdbe *pReprepare = pParse->pReprepare;
87419    pVal = sqlite3VdbeGetValue(pReprepare, pRight->iColumn, SQLITE_AFF_NONE);
87420    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
87421      z = (char *)sqlite3_value_text(pVal);
87422    }
87423    sqlite3VdbeSetVarmask(pParse->pVdbe, pRight->iColumn);
87424    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
87425  }else if( op==TK_STRING ){
87426    z = pRight->u.zToken;
87427  }
87428  if( z ){
87429    cnt = 0;
87430    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
87431      cnt++;
87432    }
87433    if( cnt!=0 && c!=0 && 255!=(u8)z[cnt-1] ){
87434      Expr *pPrefix;
87435      *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
87436      pPrefix = sqlite3Expr(db, TK_STRING, z);
87437      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
87438      *ppPrefix = pPrefix;
87439      if( op==TK_VARIABLE ){
87440        Vdbe *v = pParse->pVdbe;
87441        sqlite3VdbeSetVarmask(v, pRight->iColumn);
87442        if( *pisComplete && pRight->u.zToken[1] ){
87443          /* If the rhs of the LIKE expression is a variable, and the current
87444          ** value of the variable means there is no need to invoke the LIKE
87445          ** function, then no OP_Variable will be added to the program.
87446          ** This causes problems for the sqlite3_bind_parameter_name()
87447          ** API. To workaround them, add a dummy OP_Variable here.
87448          */
87449          int r1 = sqlite3GetTempReg(pParse);
87450          sqlite3ExprCodeTarget(pParse, pRight, r1);
87451          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
87452          sqlite3ReleaseTempReg(pParse, r1);
87453        }
87454      }
87455    }else{
87456      z = 0;
87457    }
87458  }
87459
87460  sqlite3ValueFree(pVal);
87461  return (z!=0);
87462}
87463#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
87464
87465
87466#ifndef SQLITE_OMIT_VIRTUALTABLE
87467/*
87468** Check to see if the given expression is of the form
87469**
87470**         column MATCH expr
87471**
87472** If it is then return TRUE.  If not, return FALSE.
87473*/
87474static int isMatchOfColumn(
87475  Expr *pExpr      /* Test this expression */
87476){
87477  ExprList *pList;
87478
87479  if( pExpr->op!=TK_FUNCTION ){
87480    return 0;
87481  }
87482  if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
87483    return 0;
87484  }
87485  pList = pExpr->x.pList;
87486  if( pList->nExpr!=2 ){
87487    return 0;
87488  }
87489  if( pList->a[1].pExpr->op != TK_COLUMN ){
87490    return 0;
87491  }
87492  return 1;
87493}
87494#endif /* SQLITE_OMIT_VIRTUALTABLE */
87495
87496/*
87497** If the pBase expression originated in the ON or USING clause of
87498** a join, then transfer the appropriate markings over to derived.
87499*/
87500static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
87501  pDerived->flags |= pBase->flags & EP_FromJoin;
87502  pDerived->iRightJoinTable = pBase->iRightJoinTable;
87503}
87504
87505#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
87506/*
87507** Analyze a term that consists of two or more OR-connected
87508** subterms.  So in:
87509**
87510**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
87511**                          ^^^^^^^^^^^^^^^^^^^^
87512**
87513** This routine analyzes terms such as the middle term in the above example.
87514** A WhereOrTerm object is computed and attached to the term under
87515** analysis, regardless of the outcome of the analysis.  Hence:
87516**
87517**     WhereTerm.wtFlags   |=  TERM_ORINFO
87518**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
87519**
87520** The term being analyzed must have two or more of OR-connected subterms.
87521** A single subterm might be a set of AND-connected sub-subterms.
87522** Examples of terms under analysis:
87523**
87524**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
87525**     (B)     x=expr1 OR expr2=x OR x=expr3
87526**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
87527**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
87528**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
87529**
87530** CASE 1:
87531**
87532** If all subterms are of the form T.C=expr for some single column of C
87533** a single table T (as shown in example B above) then create a new virtual
87534** term that is an equivalent IN expression.  In other words, if the term
87535** being analyzed is:
87536**
87537**      x = expr1  OR  expr2 = x  OR  x = expr3
87538**
87539** then create a new virtual term like this:
87540**
87541**      x IN (expr1,expr2,expr3)
87542**
87543** CASE 2:
87544**
87545** If all subterms are indexable by a single table T, then set
87546**
87547**     WhereTerm.eOperator              =  WO_OR
87548**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
87549**
87550** A subterm is "indexable" if it is of the form
87551** "T.C <op> <expr>" where C is any column of table T and
87552** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
87553** A subterm is also indexable if it is an AND of two or more
87554** subsubterms at least one of which is indexable.  Indexable AND
87555** subterms have their eOperator set to WO_AND and they have
87556** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
87557**
87558** From another point of view, "indexable" means that the subterm could
87559** potentially be used with an index if an appropriate index exists.
87560** This analysis does not consider whether or not the index exists; that
87561** is something the bestIndex() routine will determine.  This analysis
87562** only looks at whether subterms appropriate for indexing exist.
87563**
87564** All examples A through E above all satisfy case 2.  But if a term
87565** also statisfies case 1 (such as B) we know that the optimizer will
87566** always prefer case 1, so in that case we pretend that case 2 is not
87567** satisfied.
87568**
87569** It might be the case that multiple tables are indexable.  For example,
87570** (E) above is indexable on tables P, Q, and R.
87571**
87572** Terms that satisfy case 2 are candidates for lookup by using
87573** separate indices to find rowids for each subterm and composing
87574** the union of all rowids using a RowSet object.  This is similar
87575** to "bitmap indices" in other database engines.
87576**
87577** OTHERWISE:
87578**
87579** If neither case 1 nor case 2 apply, then leave the eOperator set to
87580** zero.  This term is not useful for search.
87581*/
87582static void exprAnalyzeOrTerm(
87583  SrcList *pSrc,            /* the FROM clause */
87584  WhereClause *pWC,         /* the complete WHERE clause */
87585  int idxTerm               /* Index of the OR-term to be analyzed */
87586){
87587  Parse *pParse = pWC->pParse;            /* Parser context */
87588  sqlite3 *db = pParse->db;               /* Database connection */
87589  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
87590  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
87591  WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
87592  int i;                                  /* Loop counters */
87593  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
87594  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
87595  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
87596  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
87597  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
87598
87599  /*
87600  ** Break the OR clause into its separate subterms.  The subterms are
87601  ** stored in a WhereClause structure containing within the WhereOrInfo
87602  ** object that is attached to the original OR clause term.
87603  */
87604  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
87605  assert( pExpr->op==TK_OR );
87606  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
87607  if( pOrInfo==0 ) return;
87608  pTerm->wtFlags |= TERM_ORINFO;
87609  pOrWc = &pOrInfo->wc;
87610  whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
87611  whereSplit(pOrWc, pExpr, TK_OR);
87612  exprAnalyzeAll(pSrc, pOrWc);
87613  if( db->mallocFailed ) return;
87614  assert( pOrWc->nTerm>=2 );
87615
87616  /*
87617  ** Compute the set of tables that might satisfy cases 1 or 2.
87618  */
87619  indexable = ~(Bitmask)0;
87620  chngToIN = ~(pWC->vmask);
87621  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
87622    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
87623      WhereAndInfo *pAndInfo;
87624      assert( pOrTerm->eOperator==0 );
87625      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
87626      chngToIN = 0;
87627      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
87628      if( pAndInfo ){
87629        WhereClause *pAndWC;
87630        WhereTerm *pAndTerm;
87631        int j;
87632        Bitmask b = 0;
87633        pOrTerm->u.pAndInfo = pAndInfo;
87634        pOrTerm->wtFlags |= TERM_ANDINFO;
87635        pOrTerm->eOperator = WO_AND;
87636        pAndWC = &pAndInfo->wc;
87637        whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
87638        whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
87639        exprAnalyzeAll(pSrc, pAndWC);
87640        testcase( db->mallocFailed );
87641        if( !db->mallocFailed ){
87642          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
87643            assert( pAndTerm->pExpr );
87644            if( allowedOp(pAndTerm->pExpr->op) ){
87645              b |= getMask(pMaskSet, pAndTerm->leftCursor);
87646            }
87647          }
87648        }
87649        indexable &= b;
87650      }
87651    }else if( pOrTerm->wtFlags & TERM_COPIED ){
87652      /* Skip this term for now.  We revisit it when we process the
87653      ** corresponding TERM_VIRTUAL term */
87654    }else{
87655      Bitmask b;
87656      b = getMask(pMaskSet, pOrTerm->leftCursor);
87657      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
87658        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
87659        b |= getMask(pMaskSet, pOther->leftCursor);
87660      }
87661      indexable &= b;
87662      if( pOrTerm->eOperator!=WO_EQ ){
87663        chngToIN = 0;
87664      }else{
87665        chngToIN &= b;
87666      }
87667    }
87668  }
87669
87670  /*
87671  ** Record the set of tables that satisfy case 2.  The set might be
87672  ** empty.
87673  */
87674  pOrInfo->indexable = indexable;
87675  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
87676
87677  /*
87678  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
87679  ** we have to do some additional checking to see if case 1 really
87680  ** is satisfied.
87681  **
87682  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
87683  ** that there is no possibility of transforming the OR clause into an
87684  ** IN operator because one or more terms in the OR clause contain
87685  ** something other than == on a column in the single table.  The 1-bit
87686  ** case means that every term of the OR clause is of the form
87687  ** "table.column=expr" for some single table.  The one bit that is set
87688  ** will correspond to the common table.  We still need to check to make
87689  ** sure the same column is used on all terms.  The 2-bit case is when
87690  ** the all terms are of the form "table1.column=table2.column".  It
87691  ** might be possible to form an IN operator with either table1.column
87692  ** or table2.column as the LHS if either is common to every term of
87693  ** the OR clause.
87694  **
87695  ** Note that terms of the form "table.column1=table.column2" (the
87696  ** same table on both sizes of the ==) cannot be optimized.
87697  */
87698  if( chngToIN ){
87699    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
87700    int iColumn = -1;         /* Column index on lhs of IN operator */
87701    int iCursor = -1;         /* Table cursor common to all terms */
87702    int j = 0;                /* Loop counter */
87703
87704    /* Search for a table and column that appears on one side or the
87705    ** other of the == operator in every subterm.  That table and column
87706    ** will be recorded in iCursor and iColumn.  There might not be any
87707    ** such table and column.  Set okToChngToIN if an appropriate table
87708    ** and column is found but leave okToChngToIN false if not found.
87709    */
87710    for(j=0; j<2 && !okToChngToIN; j++){
87711      pOrTerm = pOrWc->a;
87712      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
87713        assert( pOrTerm->eOperator==WO_EQ );
87714        pOrTerm->wtFlags &= ~TERM_OR_OK;
87715        if( pOrTerm->leftCursor==iCursor ){
87716          /* This is the 2-bit case and we are on the second iteration and
87717          ** current term is from the first iteration.  So skip this term. */
87718          assert( j==1 );
87719          continue;
87720        }
87721        if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
87722          /* This term must be of the form t1.a==t2.b where t2 is in the
87723          ** chngToIN set but t1 is not.  This term will be either preceeded
87724          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
87725          ** and use its inversion. */
87726          testcase( pOrTerm->wtFlags & TERM_COPIED );
87727          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
87728          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
87729          continue;
87730        }
87731        iColumn = pOrTerm->u.leftColumn;
87732        iCursor = pOrTerm->leftCursor;
87733        break;
87734      }
87735      if( i<0 ){
87736        /* No candidate table+column was found.  This can only occur
87737        ** on the second iteration */
87738        assert( j==1 );
87739        assert( (chngToIN&(chngToIN-1))==0 );
87740        assert( chngToIN==getMask(pMaskSet, iCursor) );
87741        break;
87742      }
87743      testcase( j==1 );
87744
87745      /* We have found a candidate table and column.  Check to see if that
87746      ** table and column is common to every term in the OR clause */
87747      okToChngToIN = 1;
87748      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
87749        assert( pOrTerm->eOperator==WO_EQ );
87750        if( pOrTerm->leftCursor!=iCursor ){
87751          pOrTerm->wtFlags &= ~TERM_OR_OK;
87752        }else if( pOrTerm->u.leftColumn!=iColumn ){
87753          okToChngToIN = 0;
87754        }else{
87755          int affLeft, affRight;
87756          /* If the right-hand side is also a column, then the affinities
87757          ** of both right and left sides must be such that no type
87758          ** conversions are required on the right.  (Ticket #2249)
87759          */
87760          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
87761          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
87762          if( affRight!=0 && affRight!=affLeft ){
87763            okToChngToIN = 0;
87764          }else{
87765            pOrTerm->wtFlags |= TERM_OR_OK;
87766          }
87767        }
87768      }
87769    }
87770
87771    /* At this point, okToChngToIN is true if original pTerm satisfies
87772    ** case 1.  In that case, construct a new virtual term that is
87773    ** pTerm converted into an IN operator.
87774    */
87775    if( okToChngToIN ){
87776      Expr *pDup;            /* A transient duplicate expression */
87777      ExprList *pList = 0;   /* The RHS of the IN operator */
87778      Expr *pLeft = 0;       /* The LHS of the IN operator */
87779      Expr *pNew;            /* The complete IN operator */
87780
87781      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
87782        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
87783        assert( pOrTerm->eOperator==WO_EQ );
87784        assert( pOrTerm->leftCursor==iCursor );
87785        assert( pOrTerm->u.leftColumn==iColumn );
87786        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
87787        pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
87788        pLeft = pOrTerm->pExpr->pLeft;
87789      }
87790      assert( pLeft!=0 );
87791      pDup = sqlite3ExprDup(db, pLeft, 0);
87792      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
87793      if( pNew ){
87794        int idxNew;
87795        transferJoinMarkings(pNew, pExpr);
87796        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
87797        pNew->x.pList = pList;
87798        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
87799        testcase( idxNew==0 );
87800        exprAnalyze(pSrc, pWC, idxNew);
87801        pTerm = &pWC->a[idxTerm];
87802        pWC->a[idxNew].iParent = idxTerm;
87803        pTerm->nChild = 1;
87804      }else{
87805        sqlite3ExprListDelete(db, pList);
87806      }
87807      pTerm->eOperator = 0;  /* case 1 trumps case 2 */
87808    }
87809  }
87810}
87811#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
87812
87813
87814/*
87815** The input to this routine is an WhereTerm structure with only the
87816** "pExpr" field filled in.  The job of this routine is to analyze the
87817** subexpression and populate all the other fields of the WhereTerm
87818** structure.
87819**
87820** If the expression is of the form "<expr> <op> X" it gets commuted
87821** to the standard form of "X <op> <expr>".
87822**
87823** If the expression is of the form "X <op> Y" where both X and Y are
87824** columns, then the original expression is unchanged and a new virtual
87825** term of the form "Y <op> X" is added to the WHERE clause and
87826** analyzed separately.  The original term is marked with TERM_COPIED
87827** and the new term is marked with TERM_DYNAMIC (because it's pExpr
87828** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
87829** is a commuted copy of a prior term.)  The original term has nChild=1
87830** and the copy has idxParent set to the index of the original term.
87831*/
87832static void exprAnalyze(
87833  SrcList *pSrc,            /* the FROM clause */
87834  WhereClause *pWC,         /* the WHERE clause */
87835  int idxTerm               /* Index of the term to be analyzed */
87836){
87837  WhereTerm *pTerm;                /* The term to be analyzed */
87838  WhereMaskSet *pMaskSet;          /* Set of table index masks */
87839  Expr *pExpr;                     /* The expression to be analyzed */
87840  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
87841  Bitmask prereqAll;               /* Prerequesites of pExpr */
87842  Bitmask extraRight = 0;          /* */
87843  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
87844  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
87845  int noCase = 0;                  /* LIKE/GLOB distinguishes case */
87846  int op;                          /* Top-level operator.  pExpr->op */
87847  Parse *pParse = pWC->pParse;     /* Parsing context */
87848  sqlite3 *db = pParse->db;        /* Database connection */
87849
87850  if( db->mallocFailed ){
87851    return;
87852  }
87853  pTerm = &pWC->a[idxTerm];
87854  pMaskSet = pWC->pMaskSet;
87855  pExpr = pTerm->pExpr;
87856  prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
87857  op = pExpr->op;
87858  if( op==TK_IN ){
87859    assert( pExpr->pRight==0 );
87860    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
87861      pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
87862    }else{
87863      pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
87864    }
87865  }else if( op==TK_ISNULL ){
87866    pTerm->prereqRight = 0;
87867  }else{
87868    pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
87869  }
87870  prereqAll = exprTableUsage(pMaskSet, pExpr);
87871  if( ExprHasProperty(pExpr, EP_FromJoin) ){
87872    Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
87873    prereqAll |= x;
87874    extraRight = x-1;  /* ON clause terms may not be used with an index
87875                       ** on left table of a LEFT JOIN.  Ticket #3015 */
87876  }
87877  pTerm->prereqAll = prereqAll;
87878  pTerm->leftCursor = -1;
87879  pTerm->iParent = -1;
87880  pTerm->eOperator = 0;
87881  if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
87882    Expr *pLeft = pExpr->pLeft;
87883    Expr *pRight = pExpr->pRight;
87884    if( pLeft->op==TK_COLUMN ){
87885      pTerm->leftCursor = pLeft->iTable;
87886      pTerm->u.leftColumn = pLeft->iColumn;
87887      pTerm->eOperator = operatorMask(op);
87888    }
87889    if( pRight && pRight->op==TK_COLUMN ){
87890      WhereTerm *pNew;
87891      Expr *pDup;
87892      if( pTerm->leftCursor>=0 ){
87893        int idxNew;
87894        pDup = sqlite3ExprDup(db, pExpr, 0);
87895        if( db->mallocFailed ){
87896          sqlite3ExprDelete(db, pDup);
87897          return;
87898        }
87899        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
87900        if( idxNew==0 ) return;
87901        pNew = &pWC->a[idxNew];
87902        pNew->iParent = idxTerm;
87903        pTerm = &pWC->a[idxTerm];
87904        pTerm->nChild = 1;
87905        pTerm->wtFlags |= TERM_COPIED;
87906      }else{
87907        pDup = pExpr;
87908        pNew = pTerm;
87909      }
87910      exprCommute(pParse, pDup);
87911      pLeft = pDup->pLeft;
87912      pNew->leftCursor = pLeft->iTable;
87913      pNew->u.leftColumn = pLeft->iColumn;
87914      pNew->prereqRight = prereqLeft;
87915      pNew->prereqAll = prereqAll;
87916      pNew->eOperator = operatorMask(pDup->op);
87917    }
87918  }
87919
87920#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
87921  /* If a term is the BETWEEN operator, create two new virtual terms
87922  ** that define the range that the BETWEEN implements.  For example:
87923  **
87924  **      a BETWEEN b AND c
87925  **
87926  ** is converted into:
87927  **
87928  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
87929  **
87930  ** The two new terms are added onto the end of the WhereClause object.
87931  ** The new terms are "dynamic" and are children of the original BETWEEN
87932  ** term.  That means that if the BETWEEN term is coded, the children are
87933  ** skipped.  Or, if the children are satisfied by an index, the original
87934  ** BETWEEN term is skipped.
87935  */
87936  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
87937    ExprList *pList = pExpr->x.pList;
87938    int i;
87939    static const u8 ops[] = {TK_GE, TK_LE};
87940    assert( pList!=0 );
87941    assert( pList->nExpr==2 );
87942    for(i=0; i<2; i++){
87943      Expr *pNewExpr;
87944      int idxNew;
87945      pNewExpr = sqlite3PExpr(pParse, ops[i],
87946                             sqlite3ExprDup(db, pExpr->pLeft, 0),
87947                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
87948      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
87949      testcase( idxNew==0 );
87950      exprAnalyze(pSrc, pWC, idxNew);
87951      pTerm = &pWC->a[idxTerm];
87952      pWC->a[idxNew].iParent = idxTerm;
87953    }
87954    pTerm->nChild = 2;
87955  }
87956#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
87957
87958#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
87959  /* Analyze a term that is composed of two or more subterms connected by
87960  ** an OR operator.
87961  */
87962  else if( pExpr->op==TK_OR ){
87963    assert( pWC->op==TK_AND );
87964    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
87965    pTerm = &pWC->a[idxTerm];
87966  }
87967#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
87968
87969#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
87970  /* Add constraints to reduce the search space on a LIKE or GLOB
87971  ** operator.
87972  **
87973  ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
87974  **
87975  **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
87976  **
87977  ** The last character of the prefix "abc" is incremented to form the
87978  ** termination condition "abd".
87979  */
87980  if( pWC->op==TK_AND
87981   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
87982  ){
87983    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
87984    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
87985    Expr *pNewExpr1;
87986    Expr *pNewExpr2;
87987    int idxNew1;
87988    int idxNew2;
87989
87990    pLeft = pExpr->x.pList->a[1].pExpr;
87991    pStr2 = sqlite3ExprDup(db, pStr1, 0);
87992    if( !db->mallocFailed ){
87993      u8 c, *pC;       /* Last character before the first wildcard */
87994      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
87995      c = *pC;
87996      if( noCase ){
87997        /* The point is to increment the last character before the first
87998        ** wildcard.  But if we increment '@', that will push it into the
87999        ** alphabetic range where case conversions will mess up the
88000        ** inequality.  To avoid this, make sure to also run the full
88001        ** LIKE on all candidate expressions by clearing the isComplete flag
88002        */
88003        if( c=='A'-1 ) isComplete = 0;
88004
88005        c = sqlite3UpperToLower[c];
88006      }
88007      *pC = c + 1;
88008    }
88009    pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft,0),pStr1,0);
88010    idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
88011    testcase( idxNew1==0 );
88012    exprAnalyze(pSrc, pWC, idxNew1);
88013    pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft,0),pStr2,0);
88014    idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
88015    testcase( idxNew2==0 );
88016    exprAnalyze(pSrc, pWC, idxNew2);
88017    pTerm = &pWC->a[idxTerm];
88018    if( isComplete ){
88019      pWC->a[idxNew1].iParent = idxTerm;
88020      pWC->a[idxNew2].iParent = idxTerm;
88021      pTerm->nChild = 2;
88022    }
88023  }
88024#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
88025
88026#ifndef SQLITE_OMIT_VIRTUALTABLE
88027  /* Add a WO_MATCH auxiliary term to the constraint set if the
88028  ** current expression is of the form:  column MATCH expr.
88029  ** This information is used by the xBestIndex methods of
88030  ** virtual tables.  The native query optimizer does not attempt
88031  ** to do anything with MATCH functions.
88032  */
88033  if( isMatchOfColumn(pExpr) ){
88034    int idxNew;
88035    Expr *pRight, *pLeft;
88036    WhereTerm *pNewTerm;
88037    Bitmask prereqColumn, prereqExpr;
88038
88039    pRight = pExpr->x.pList->a[0].pExpr;
88040    pLeft = pExpr->x.pList->a[1].pExpr;
88041    prereqExpr = exprTableUsage(pMaskSet, pRight);
88042    prereqColumn = exprTableUsage(pMaskSet, pLeft);
88043    if( (prereqExpr & prereqColumn)==0 ){
88044      Expr *pNewExpr;
88045      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
88046                              0, sqlite3ExprDup(db, pRight, 0), 0);
88047      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
88048      testcase( idxNew==0 );
88049      pNewTerm = &pWC->a[idxNew];
88050      pNewTerm->prereqRight = prereqExpr;
88051      pNewTerm->leftCursor = pLeft->iTable;
88052      pNewTerm->u.leftColumn = pLeft->iColumn;
88053      pNewTerm->eOperator = WO_MATCH;
88054      pNewTerm->iParent = idxTerm;
88055      pTerm = &pWC->a[idxTerm];
88056      pTerm->nChild = 1;
88057      pTerm->wtFlags |= TERM_COPIED;
88058      pNewTerm->prereqAll = pTerm->prereqAll;
88059    }
88060  }
88061#endif /* SQLITE_OMIT_VIRTUALTABLE */
88062
88063  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
88064  ** an index for tables to the left of the join.
88065  */
88066  pTerm->prereqRight |= extraRight;
88067}
88068
88069/*
88070** Return TRUE if any of the expressions in pList->a[iFirst...] contain
88071** a reference to any table other than the iBase table.
88072*/
88073static int referencesOtherTables(
88074  ExprList *pList,          /* Search expressions in ths list */
88075  WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
88076  int iFirst,               /* Be searching with the iFirst-th expression */
88077  int iBase                 /* Ignore references to this table */
88078){
88079  Bitmask allowed = ~getMask(pMaskSet, iBase);
88080  while( iFirst<pList->nExpr ){
88081    if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
88082      return 1;
88083    }
88084  }
88085  return 0;
88086}
88087
88088
88089/*
88090** This routine decides if pIdx can be used to satisfy the ORDER BY
88091** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
88092** ORDER BY clause, this routine returns 0.
88093**
88094** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
88095** left-most table in the FROM clause of that same SELECT statement and
88096** the table has a cursor number of "base".  pIdx is an index on pTab.
88097**
88098** nEqCol is the number of columns of pIdx that are used as equality
88099** constraints.  Any of these columns may be missing from the ORDER BY
88100** clause and the match can still be a success.
88101**
88102** All terms of the ORDER BY that match against the index must be either
88103** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
88104** index do not need to satisfy this constraint.)  The *pbRev value is
88105** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
88106** the ORDER BY clause is all ASC.
88107*/
88108static int isSortingIndex(
88109  Parse *pParse,          /* Parsing context */
88110  WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
88111  Index *pIdx,            /* The index we are testing */
88112  int base,               /* Cursor number for the table to be sorted */
88113  ExprList *pOrderBy,     /* The ORDER BY clause */
88114  int nEqCol,             /* Number of index columns with == constraints */
88115  int *pbRev              /* Set to 1 if ORDER BY is DESC */
88116){
88117  int i, j;                       /* Loop counters */
88118  int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
88119  int nTerm;                      /* Number of ORDER BY terms */
88120  struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
88121  sqlite3 *db = pParse->db;
88122
88123  assert( pOrderBy!=0 );
88124  nTerm = pOrderBy->nExpr;
88125  assert( nTerm>0 );
88126
88127  /* Argument pIdx must either point to a 'real' named index structure,
88128  ** or an index structure allocated on the stack by bestBtreeIndex() to
88129  ** represent the rowid index that is part of every table.  */
88130  assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
88131
88132  /* Match terms of the ORDER BY clause against columns of
88133  ** the index.
88134  **
88135  ** Note that indices have pIdx->nColumn regular columns plus
88136  ** one additional column containing the rowid.  The rowid column
88137  ** of the index is also allowed to match against the ORDER BY
88138  ** clause.
88139  */
88140  for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
88141    Expr *pExpr;       /* The expression of the ORDER BY pTerm */
88142    CollSeq *pColl;    /* The collating sequence of pExpr */
88143    int termSortOrder; /* Sort order for this term */
88144    int iColumn;       /* The i-th column of the index.  -1 for rowid */
88145    int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
88146    const char *zColl; /* Name of the collating sequence for i-th index term */
88147
88148    pExpr = pTerm->pExpr;
88149    if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
88150      /* Can not use an index sort on anything that is not a column in the
88151      ** left-most table of the FROM clause */
88152      break;
88153    }
88154    pColl = sqlite3ExprCollSeq(pParse, pExpr);
88155    if( !pColl ){
88156      pColl = db->pDfltColl;
88157    }
88158    if( pIdx->zName && i<pIdx->nColumn ){
88159      iColumn = pIdx->aiColumn[i];
88160      if( iColumn==pIdx->pTable->iPKey ){
88161        iColumn = -1;
88162      }
88163      iSortOrder = pIdx->aSortOrder[i];
88164      zColl = pIdx->azColl[i];
88165    }else{
88166      iColumn = -1;
88167      iSortOrder = 0;
88168      zColl = pColl->zName;
88169    }
88170    if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
88171      /* Term j of the ORDER BY clause does not match column i of the index */
88172      if( i<nEqCol ){
88173        /* If an index column that is constrained by == fails to match an
88174        ** ORDER BY term, that is OK.  Just ignore that column of the index
88175        */
88176        continue;
88177      }else if( i==pIdx->nColumn ){
88178        /* Index column i is the rowid.  All other terms match. */
88179        break;
88180      }else{
88181        /* If an index column fails to match and is not constrained by ==
88182        ** then the index cannot satisfy the ORDER BY constraint.
88183        */
88184        return 0;
88185      }
88186    }
88187    assert( pIdx->aSortOrder!=0 || iColumn==-1 );
88188    assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
88189    assert( iSortOrder==0 || iSortOrder==1 );
88190    termSortOrder = iSortOrder ^ pTerm->sortOrder;
88191    if( i>nEqCol ){
88192      if( termSortOrder!=sortOrder ){
88193        /* Indices can only be used if all ORDER BY terms past the
88194        ** equality constraints are all either DESC or ASC. */
88195        return 0;
88196      }
88197    }else{
88198      sortOrder = termSortOrder;
88199    }
88200    j++;
88201    pTerm++;
88202    if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
88203      /* If the indexed column is the primary key and everything matches
88204      ** so far and none of the ORDER BY terms to the right reference other
88205      ** tables in the join, then we are assured that the index can be used
88206      ** to sort because the primary key is unique and so none of the other
88207      ** columns will make any difference
88208      */
88209      j = nTerm;
88210    }
88211  }
88212
88213  *pbRev = sortOrder!=0;
88214  if( j>=nTerm ){
88215    /* All terms of the ORDER BY clause are covered by this index so
88216    ** this index can be used for sorting. */
88217    return 1;
88218  }
88219  if( pIdx->onError!=OE_None && i==pIdx->nColumn
88220      && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
88221    /* All terms of this index match some prefix of the ORDER BY clause
88222    ** and the index is UNIQUE and no terms on the tail of the ORDER BY
88223    ** clause reference other tables in a join.  If this is all true then
88224    ** the order by clause is superfluous. */
88225    return 1;
88226  }
88227  return 0;
88228}
88229
88230/*
88231** Prepare a crude estimate of the logarithm of the input value.
88232** The results need not be exact.  This is only used for estimating
88233** the total cost of performing operations with O(logN) or O(NlogN)
88234** complexity.  Because N is just a guess, it is no great tragedy if
88235** logN is a little off.
88236*/
88237static double estLog(double N){
88238  double logN = 1;
88239  double x = 10;
88240  while( N>x ){
88241    logN += 1;
88242    x *= 10;
88243  }
88244  return logN;
88245}
88246
88247/*
88248** Two routines for printing the content of an sqlite3_index_info
88249** structure.  Used for testing and debugging only.  If neither
88250** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
88251** are no-ops.
88252*/
88253#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
88254static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
88255  int i;
88256  if( !sqlite3WhereTrace ) return;
88257  for(i=0; i<p->nConstraint; i++){
88258    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
88259       i,
88260       p->aConstraint[i].iColumn,
88261       p->aConstraint[i].iTermOffset,
88262       p->aConstraint[i].op,
88263       p->aConstraint[i].usable);
88264  }
88265  for(i=0; i<p->nOrderBy; i++){
88266    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
88267       i,
88268       p->aOrderBy[i].iColumn,
88269       p->aOrderBy[i].desc);
88270  }
88271}
88272static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
88273  int i;
88274  if( !sqlite3WhereTrace ) return;
88275  for(i=0; i<p->nConstraint; i++){
88276    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
88277       i,
88278       p->aConstraintUsage[i].argvIndex,
88279       p->aConstraintUsage[i].omit);
88280  }
88281  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
88282  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
88283  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
88284  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
88285}
88286#else
88287#define TRACE_IDX_INPUTS(A)
88288#define TRACE_IDX_OUTPUTS(A)
88289#endif
88290
88291/*
88292** Required because bestIndex() is called by bestOrClauseIndex()
88293*/
88294static void bestIndex(
88295    Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*);
88296
88297/*
88298** This routine attempts to find an scanning strategy that can be used
88299** to optimize an 'OR' expression that is part of a WHERE clause.
88300**
88301** The table associated with FROM clause term pSrc may be either a
88302** regular B-Tree table or a virtual table.
88303*/
88304static void bestOrClauseIndex(
88305  Parse *pParse,              /* The parsing context */
88306  WhereClause *pWC,           /* The WHERE clause */
88307  struct SrcList_item *pSrc,  /* The FROM clause term to search */
88308  Bitmask notReady,           /* Mask of cursors that are not available */
88309  ExprList *pOrderBy,         /* The ORDER BY clause */
88310  WhereCost *pCost            /* Lowest cost query plan */
88311){
88312#ifndef SQLITE_OMIT_OR_OPTIMIZATION
88313  const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
88314  const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
88315  WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
88316  WhereTerm *pTerm;                 /* A single term of the WHERE clause */
88317
88318  /* Search the WHERE clause terms for a usable WO_OR term. */
88319  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
88320    if( pTerm->eOperator==WO_OR
88321     && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
88322     && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
88323    ){
88324      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
88325      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
88326      WhereTerm *pOrTerm;
88327      int flags = WHERE_MULTI_OR;
88328      double rTotal = 0;
88329      double nRow = 0;
88330      Bitmask used = 0;
88331
88332      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
88333        WhereCost sTermCost;
88334        WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
88335          (pOrTerm - pOrWC->a), (pTerm - pWC->a)
88336        ));
88337        if( pOrTerm->eOperator==WO_AND ){
88338          WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
88339          bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
88340        }else if( pOrTerm->leftCursor==iCur ){
88341          WhereClause tempWC;
88342          tempWC.pParse = pWC->pParse;
88343          tempWC.pMaskSet = pWC->pMaskSet;
88344          tempWC.op = TK_AND;
88345          tempWC.a = pOrTerm;
88346          tempWC.nTerm = 1;
88347          bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
88348        }else{
88349          continue;
88350        }
88351        rTotal += sTermCost.rCost;
88352        nRow += sTermCost.nRow;
88353        used |= sTermCost.used;
88354        if( rTotal>=pCost->rCost ) break;
88355      }
88356
88357      /* If there is an ORDER BY clause, increase the scan cost to account
88358      ** for the cost of the sort. */
88359      if( pOrderBy!=0 ){
88360        rTotal += nRow*estLog(nRow);
88361        WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
88362      }
88363
88364      /* If the cost of scanning using this OR term for optimization is
88365      ** less than the current cost stored in pCost, replace the contents
88366      ** of pCost. */
88367      WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
88368      if( rTotal<pCost->rCost ){
88369        pCost->rCost = rTotal;
88370        pCost->nRow = nRow;
88371        pCost->used = used;
88372        pCost->plan.wsFlags = flags;
88373        pCost->plan.u.pTerm = pTerm;
88374      }
88375    }
88376  }
88377#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
88378}
88379
88380#ifndef SQLITE_OMIT_VIRTUALTABLE
88381/*
88382** Allocate and populate an sqlite3_index_info structure. It is the
88383** responsibility of the caller to eventually release the structure
88384** by passing the pointer returned by this function to sqlite3_free().
88385*/
88386static sqlite3_index_info *allocateIndexInfo(
88387  Parse *pParse,
88388  WhereClause *pWC,
88389  struct SrcList_item *pSrc,
88390  ExprList *pOrderBy
88391){
88392  int i, j;
88393  int nTerm;
88394  struct sqlite3_index_constraint *pIdxCons;
88395  struct sqlite3_index_orderby *pIdxOrderBy;
88396  struct sqlite3_index_constraint_usage *pUsage;
88397  WhereTerm *pTerm;
88398  int nOrderBy;
88399  sqlite3_index_info *pIdxInfo;
88400
88401  WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
88402
88403  /* Count the number of possible WHERE clause constraints referring
88404  ** to this virtual table */
88405  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
88406    if( pTerm->leftCursor != pSrc->iCursor ) continue;
88407    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
88408    testcase( pTerm->eOperator==WO_IN );
88409    testcase( pTerm->eOperator==WO_ISNULL );
88410    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
88411    nTerm++;
88412  }
88413
88414  /* If the ORDER BY clause contains only columns in the current
88415  ** virtual table then allocate space for the aOrderBy part of
88416  ** the sqlite3_index_info structure.
88417  */
88418  nOrderBy = 0;
88419  if( pOrderBy ){
88420    for(i=0; i<pOrderBy->nExpr; i++){
88421      Expr *pExpr = pOrderBy->a[i].pExpr;
88422      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
88423    }
88424    if( i==pOrderBy->nExpr ){
88425      nOrderBy = pOrderBy->nExpr;
88426    }
88427  }
88428
88429  /* Allocate the sqlite3_index_info structure
88430  */
88431  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
88432                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
88433                           + sizeof(*pIdxOrderBy)*nOrderBy );
88434  if( pIdxInfo==0 ){
88435    sqlite3ErrorMsg(pParse, "out of memory");
88436    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
88437    return 0;
88438  }
88439
88440  /* Initialize the structure.  The sqlite3_index_info structure contains
88441  ** many fields that are declared "const" to prevent xBestIndex from
88442  ** changing them.  We have to do some funky casting in order to
88443  ** initialize those fields.
88444  */
88445  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
88446  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
88447  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
88448  *(int*)&pIdxInfo->nConstraint = nTerm;
88449  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
88450  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
88451  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
88452  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
88453                                                                   pUsage;
88454
88455  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
88456    if( pTerm->leftCursor != pSrc->iCursor ) continue;
88457    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
88458    testcase( pTerm->eOperator==WO_IN );
88459    testcase( pTerm->eOperator==WO_ISNULL );
88460    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
88461    pIdxCons[j].iColumn = pTerm->u.leftColumn;
88462    pIdxCons[j].iTermOffset = i;
88463    pIdxCons[j].op = (u8)pTerm->eOperator;
88464    /* The direct assignment in the previous line is possible only because
88465    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
88466    ** following asserts verify this fact. */
88467    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
88468    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
88469    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
88470    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
88471    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
88472    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
88473    assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
88474    j++;
88475  }
88476  for(i=0; i<nOrderBy; i++){
88477    Expr *pExpr = pOrderBy->a[i].pExpr;
88478    pIdxOrderBy[i].iColumn = pExpr->iColumn;
88479    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
88480  }
88481
88482  return pIdxInfo;
88483}
88484
88485/*
88486** The table object reference passed as the second argument to this function
88487** must represent a virtual table. This function invokes the xBestIndex()
88488** method of the virtual table with the sqlite3_index_info pointer passed
88489** as the argument.
88490**
88491** If an error occurs, pParse is populated with an error message and a
88492** non-zero value is returned. Otherwise, 0 is returned and the output
88493** part of the sqlite3_index_info structure is left populated.
88494**
88495** Whether or not an error is returned, it is the responsibility of the
88496** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
88497** that this is required.
88498*/
88499static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
88500  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
88501  int i;
88502  int rc;
88503
88504  WHERETRACE(("xBestIndex for %s\n", pTab->zName));
88505  TRACE_IDX_INPUTS(p);
88506  rc = pVtab->pModule->xBestIndex(pVtab, p);
88507  TRACE_IDX_OUTPUTS(p);
88508
88509  if( rc!=SQLITE_OK ){
88510    if( rc==SQLITE_NOMEM ){
88511      pParse->db->mallocFailed = 1;
88512    }else if( !pVtab->zErrMsg ){
88513      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
88514    }else{
88515      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
88516    }
88517  }
88518  sqlite3DbFree(pParse->db, pVtab->zErrMsg);
88519  pVtab->zErrMsg = 0;
88520
88521  for(i=0; i<p->nConstraint; i++){
88522    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
88523      sqlite3ErrorMsg(pParse,
88524          "table %s: xBestIndex returned an invalid plan", pTab->zName);
88525    }
88526  }
88527
88528  return pParse->nErr;
88529}
88530
88531
88532/*
88533** Compute the best index for a virtual table.
88534**
88535** The best index is computed by the xBestIndex method of the virtual
88536** table module.  This routine is really just a wrapper that sets up
88537** the sqlite3_index_info structure that is used to communicate with
88538** xBestIndex.
88539**
88540** In a join, this routine might be called multiple times for the
88541** same virtual table.  The sqlite3_index_info structure is created
88542** and initialized on the first invocation and reused on all subsequent
88543** invocations.  The sqlite3_index_info structure is also used when
88544** code is generated to access the virtual table.  The whereInfoDelete()
88545** routine takes care of freeing the sqlite3_index_info structure after
88546** everybody has finished with it.
88547*/
88548static void bestVirtualIndex(
88549  Parse *pParse,                  /* The parsing context */
88550  WhereClause *pWC,               /* The WHERE clause */
88551  struct SrcList_item *pSrc,      /* The FROM clause term to search */
88552  Bitmask notReady,               /* Mask of cursors that are not available */
88553  ExprList *pOrderBy,             /* The order by clause */
88554  WhereCost *pCost,               /* Lowest cost query plan */
88555  sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
88556){
88557  Table *pTab = pSrc->pTab;
88558  sqlite3_index_info *pIdxInfo;
88559  struct sqlite3_index_constraint *pIdxCons;
88560  struct sqlite3_index_constraint_usage *pUsage;
88561  WhereTerm *pTerm;
88562  int i, j;
88563  int nOrderBy;
88564
88565  /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
88566  ** malloc in allocateIndexInfo() fails and this function returns leaving
88567  ** wsFlags in an uninitialized state, the caller may behave unpredictably.
88568  */
88569  memset(pCost, 0, sizeof(*pCost));
88570  pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
88571
88572  /* If the sqlite3_index_info structure has not been previously
88573  ** allocated and initialized, then allocate and initialize it now.
88574  */
88575  pIdxInfo = *ppIdxInfo;
88576  if( pIdxInfo==0 ){
88577    *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
88578  }
88579  if( pIdxInfo==0 ){
88580    return;
88581  }
88582
88583  /* At this point, the sqlite3_index_info structure that pIdxInfo points
88584  ** to will have been initialized, either during the current invocation or
88585  ** during some prior invocation.  Now we just have to customize the
88586  ** details of pIdxInfo for the current invocation and pass it to
88587  ** xBestIndex.
88588  */
88589
88590  /* The module name must be defined. Also, by this point there must
88591  ** be a pointer to an sqlite3_vtab structure. Otherwise
88592  ** sqlite3ViewGetColumnNames() would have picked up the error.
88593  */
88594  assert( pTab->azModuleArg && pTab->azModuleArg[0] );
88595  assert( sqlite3GetVTable(pParse->db, pTab) );
88596
88597  /* Set the aConstraint[].usable fields and initialize all
88598  ** output variables to zero.
88599  **
88600  ** aConstraint[].usable is true for constraints where the right-hand
88601  ** side contains only references to tables to the left of the current
88602  ** table.  In other words, if the constraint is of the form:
88603  **
88604  **           column = expr
88605  **
88606  ** and we are evaluating a join, then the constraint on column is
88607  ** only valid if all tables referenced in expr occur to the left
88608  ** of the table containing column.
88609  **
88610  ** The aConstraints[] array contains entries for all constraints
88611  ** on the current table.  That way we only have to compute it once
88612  ** even though we might try to pick the best index multiple times.
88613  ** For each attempt at picking an index, the order of tables in the
88614  ** join might be different so we have to recompute the usable flag
88615  ** each time.
88616  */
88617  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
88618  pUsage = pIdxInfo->aConstraintUsage;
88619  for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
88620    j = pIdxCons->iTermOffset;
88621    pTerm = &pWC->a[j];
88622    pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
88623  }
88624  memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
88625  if( pIdxInfo->needToFreeIdxStr ){
88626    sqlite3_free(pIdxInfo->idxStr);
88627  }
88628  pIdxInfo->idxStr = 0;
88629  pIdxInfo->idxNum = 0;
88630  pIdxInfo->needToFreeIdxStr = 0;
88631  pIdxInfo->orderByConsumed = 0;
88632  /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
88633  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
88634  nOrderBy = pIdxInfo->nOrderBy;
88635  if( !pOrderBy ){
88636    pIdxInfo->nOrderBy = 0;
88637  }
88638
88639  if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
88640    return;
88641  }
88642
88643  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
88644  for(i=0; i<pIdxInfo->nConstraint; i++){
88645    if( pUsage[i].argvIndex>0 ){
88646      pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
88647    }
88648  }
88649
88650  /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
88651  ** inital value of lowestCost in this loop. If it is, then the
88652  ** (cost<lowestCost) test below will never be true.
88653  **
88654  ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
88655  ** is defined.
88656  */
88657  if( (SQLITE_BIG_DBL/((double)2))<pIdxInfo->estimatedCost ){
88658    pCost->rCost = (SQLITE_BIG_DBL/((double)2));
88659  }else{
88660    pCost->rCost = pIdxInfo->estimatedCost;
88661  }
88662  pCost->plan.u.pVtabIdx = pIdxInfo;
88663  if( pIdxInfo->orderByConsumed ){
88664    pCost->plan.wsFlags |= WHERE_ORDERBY;
88665  }
88666  pCost->plan.nEq = 0;
88667  pIdxInfo->nOrderBy = nOrderBy;
88668
88669  /* Try to find a more efficient access pattern by using multiple indexes
88670  ** to optimize an OR expression within the WHERE clause.
88671  */
88672  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
88673}
88674#endif /* SQLITE_OMIT_VIRTUALTABLE */
88675
88676/*
88677** Argument pIdx is a pointer to an index structure that has an array of
88678** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
88679** stored in Index.aSample. The domain of values stored in said column
88680** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
88681** Region 0 contains all values smaller than the first sample value. Region
88682** 1 contains values larger than or equal to the value of the first sample,
88683** but smaller than the value of the second. And so on.
88684**
88685** If successful, this function determines which of the regions value
88686** pVal lies in, sets *piRegion to the region index (a value between 0
88687** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
88688** Or, if an OOM occurs while converting text values between encodings,
88689** SQLITE_NOMEM is returned and *piRegion is undefined.
88690*/
88691#ifdef SQLITE_ENABLE_STAT2
88692static int whereRangeRegion(
88693  Parse *pParse,              /* Database connection */
88694  Index *pIdx,                /* Index to consider domain of */
88695  sqlite3_value *pVal,        /* Value to consider */
88696  int *piRegion               /* OUT: Region of domain in which value lies */
88697){
88698  if( ALWAYS(pVal) ){
88699    IndexSample *aSample = pIdx->aSample;
88700    int i = 0;
88701    int eType = sqlite3_value_type(pVal);
88702
88703    if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
88704      double r = sqlite3_value_double(pVal);
88705      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
88706        if( aSample[i].eType==SQLITE_NULL ) continue;
88707        if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
88708      }
88709    }else{
88710      sqlite3 *db = pParse->db;
88711      CollSeq *pColl;
88712      const u8 *z;
88713      int n;
88714
88715      /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
88716      assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
88717
88718      if( eType==SQLITE_BLOB ){
88719        z = (const u8 *)sqlite3_value_blob(pVal);
88720        pColl = db->pDfltColl;
88721        assert( pColl->enc==SQLITE_UTF8 );
88722      }else{
88723        pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
88724        if( pColl==0 ){
88725          sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
88726                          *pIdx->azColl);
88727          return SQLITE_ERROR;
88728        }
88729        z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
88730        if( !z ){
88731          return SQLITE_NOMEM;
88732        }
88733        assert( z && pColl && pColl->xCmp );
88734      }
88735      n = sqlite3ValueBytes(pVal, pColl->enc);
88736
88737      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
88738        int r;
88739        int eSampletype = aSample[i].eType;
88740        if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
88741        if( (eSampletype!=eType) ) break;
88742#ifndef SQLITE_OMIT_UTF16
88743        if( pColl->enc!=SQLITE_UTF8 ){
88744          int nSample;
88745          char *zSample = sqlite3Utf8to16(
88746              db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
88747          );
88748          if( !zSample ){
88749            assert( db->mallocFailed );
88750            return SQLITE_NOMEM;
88751          }
88752          r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
88753          sqlite3DbFree(db, zSample);
88754        }else
88755#endif
88756        {
88757          r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
88758        }
88759        if( r>0 ) break;
88760      }
88761    }
88762
88763    assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
88764    *piRegion = i;
88765  }
88766  return SQLITE_OK;
88767}
88768#endif   /* #ifdef SQLITE_ENABLE_STAT2 */
88769
88770/*
88771** If expression pExpr represents a literal value, set *pp to point to
88772** an sqlite3_value structure containing the same value, with affinity
88773** aff applied to it, before returning. It is the responsibility of the
88774** caller to eventually release this structure by passing it to
88775** sqlite3ValueFree().
88776**
88777** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
88778** is an SQL variable that currently has a non-NULL value bound to it,
88779** create an sqlite3_value structure containing this value, again with
88780** affinity aff applied to it, instead.
88781**
88782** If neither of the above apply, set *pp to NULL.
88783**
88784** If an error occurs, return an error code. Otherwise, SQLITE_OK.
88785*/
88786#ifdef SQLITE_ENABLE_STAT2
88787static int valueFromExpr(
88788  Parse *pParse,
88789  Expr *pExpr,
88790  u8 aff,
88791  sqlite3_value **pp
88792){
88793  /* The evalConstExpr() function will have already converted any TK_VARIABLE
88794  ** expression involved in an comparison into a TK_REGISTER. */
88795  assert( pExpr->op!=TK_VARIABLE );
88796  if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
88797    int iVar = pExpr->iColumn;
88798    sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
88799    *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
88800    return SQLITE_OK;
88801  }
88802  return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
88803}
88804#endif
88805
88806/*
88807** This function is used to estimate the number of rows that will be visited
88808** by scanning an index for a range of values. The range may have an upper
88809** bound, a lower bound, or both. The WHERE clause terms that set the upper
88810** and lower bounds are represented by pLower and pUpper respectively. For
88811** example, assuming that index p is on t1(a):
88812**
88813**   ... FROM t1 WHERE a > ? AND a < ? ...
88814**                    |_____|   |_____|
88815**                       |         |
88816**                     pLower    pUpper
88817**
88818** If either of the upper or lower bound is not present, then NULL is passed in
88819** place of the corresponding WhereTerm.
88820**
88821** The nEq parameter is passed the index of the index column subject to the
88822** range constraint. Or, equivalently, the number of equality constraints
88823** optimized by the proposed index scan. For example, assuming index p is
88824** on t1(a, b), and the SQL query is:
88825**
88826**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
88827**
88828** then nEq should be passed the value 1 (as the range restricted column,
88829** b, is the second left-most column of the index). Or, if the query is:
88830**
88831**   ... FROM t1 WHERE a > ? AND a < ? ...
88832**
88833** then nEq should be passed 0.
88834**
88835** The returned value is an integer between 1 and 100, inclusive. A return
88836** value of 1 indicates that the proposed range scan is expected to visit
88837** approximately 1/100th (1%) of the rows selected by the nEq equality
88838** constraints (if any). A return value of 100 indicates that it is expected
88839** that the range scan will visit every row (100%) selected by the equality
88840** constraints.
88841**
88842** In the absence of sqlite_stat2 ANALYZE data, each range inequality
88843** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
88844** results in a return of 33 and a range constraint (x>? AND x<?) results
88845** in a return of 11.
88846*/
88847static int whereRangeScanEst(
88848  Parse *pParse,       /* Parsing & code generating context */
88849  Index *p,            /* The index containing the range-compared column; "x" */
88850  int nEq,             /* index into p->aCol[] of the range-compared column */
88851  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
88852  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
88853  int *piEst           /* OUT: Return value */
88854){
88855  int rc = SQLITE_OK;
88856
88857#ifdef SQLITE_ENABLE_STAT2
88858
88859  if( nEq==0 && p->aSample ){
88860    sqlite3_value *pLowerVal = 0;
88861    sqlite3_value *pUpperVal = 0;
88862    int iEst;
88863    int iLower = 0;
88864    int iUpper = SQLITE_INDEX_SAMPLES;
88865    u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
88866
88867    if( pLower ){
88868      Expr *pExpr = pLower->pExpr->pRight;
88869      rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
88870    }
88871    if( rc==SQLITE_OK && pUpper ){
88872      Expr *pExpr = pUpper->pExpr->pRight;
88873      rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
88874    }
88875
88876    if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
88877      sqlite3ValueFree(pLowerVal);
88878      sqlite3ValueFree(pUpperVal);
88879      goto range_est_fallback;
88880    }else if( pLowerVal==0 ){
88881      rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
88882      if( pLower ) iLower = iUpper/2;
88883    }else if( pUpperVal==0 ){
88884      rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
88885      if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
88886    }else{
88887      rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
88888      if( rc==SQLITE_OK ){
88889        rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
88890      }
88891    }
88892
88893    iEst = iUpper - iLower;
88894    testcase( iEst==SQLITE_INDEX_SAMPLES );
88895    assert( iEst<=SQLITE_INDEX_SAMPLES );
88896    if( iEst<1 ){
88897      iEst = 1;
88898    }
88899
88900    sqlite3ValueFree(pLowerVal);
88901    sqlite3ValueFree(pUpperVal);
88902    *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
88903    return rc;
88904  }
88905range_est_fallback:
88906#else
88907  UNUSED_PARAMETER(pParse);
88908  UNUSED_PARAMETER(p);
88909  UNUSED_PARAMETER(nEq);
88910#endif
88911  assert( pLower || pUpper );
88912  if( pLower && pUpper ){
88913    *piEst = 11;
88914  }else{
88915    *piEst = 33;
88916  }
88917  return rc;
88918}
88919
88920
88921/*
88922** Find the query plan for accessing a particular table.  Write the
88923** best query plan and its cost into the WhereCost object supplied as the
88924** last parameter.
88925**
88926** The lowest cost plan wins.  The cost is an estimate of the amount of
88927** CPU and disk I/O need to process the request using the selected plan.
88928** Factors that influence cost include:
88929**
88930**    *  The estimated number of rows that will be retrieved.  (The
88931**       fewer the better.)
88932**
88933**    *  Whether or not sorting must occur.
88934**
88935**    *  Whether or not there must be separate lookups in the
88936**       index and in the main table.
88937**
88938** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
88939** the SQL statement, then this function only considers plans using the
88940** named index. If no such plan is found, then the returned cost is
88941** SQLITE_BIG_DBL. If a plan is found that uses the named index,
88942** then the cost is calculated in the usual way.
88943**
88944** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
88945** in the SELECT statement, then no indexes are considered. However, the
88946** selected plan may still take advantage of the tables built-in rowid
88947** index.
88948*/
88949static void bestBtreeIndex(
88950  Parse *pParse,              /* The parsing context */
88951  WhereClause *pWC,           /* The WHERE clause */
88952  struct SrcList_item *pSrc,  /* The FROM clause term to search */
88953  Bitmask notReady,           /* Mask of cursors that are not available */
88954  ExprList *pOrderBy,         /* The ORDER BY clause */
88955  WhereCost *pCost            /* Lowest cost query plan */
88956){
88957  int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
88958  Index *pProbe;              /* An index we are evaluating */
88959  Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
88960  int eqTermMask;             /* Current mask of valid equality operators */
88961  int idxEqTermMask;          /* Index mask of valid equality operators */
88962  Index sPk;                  /* A fake index object for the primary key */
88963  unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
88964  int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
88965  int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
88966
88967  /* Initialize the cost to a worst-case value */
88968  memset(pCost, 0, sizeof(*pCost));
88969  pCost->rCost = SQLITE_BIG_DBL;
88970
88971  /* If the pSrc table is the right table of a LEFT JOIN then we may not
88972  ** use an index to satisfy IS NULL constraints on that table.  This is
88973  ** because columns might end up being NULL if the table does not match -
88974  ** a circumstance which the index cannot help us discover.  Ticket #2177.
88975  */
88976  if( pSrc->jointype & JT_LEFT ){
88977    idxEqTermMask = WO_EQ|WO_IN;
88978  }else{
88979    idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
88980  }
88981
88982  if( pSrc->pIndex ){
88983    /* An INDEXED BY clause specifies a particular index to use */
88984    pIdx = pProbe = pSrc->pIndex;
88985    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
88986    eqTermMask = idxEqTermMask;
88987  }else{
88988    /* There is no INDEXED BY clause.  Create a fake Index object to
88989    ** represent the primary key */
88990    Index *pFirst;                /* Any other index on the table */
88991    memset(&sPk, 0, sizeof(Index));
88992    sPk.nColumn = 1;
88993    sPk.aiColumn = &aiColumnPk;
88994    sPk.aiRowEst = aiRowEstPk;
88995    aiRowEstPk[1] = 1;
88996    sPk.onError = OE_Replace;
88997    sPk.pTable = pSrc->pTab;
88998    pFirst = pSrc->pTab->pIndex;
88999    if( pSrc->notIndexed==0 ){
89000      sPk.pNext = pFirst;
89001    }
89002    /* The aiRowEstPk[0] is an estimate of the total number of rows in the
89003    ** table.  Get this information from the ANALYZE information if it is
89004    ** available.  If not available, assume the table 1 million rows in size.
89005    */
89006    if( pFirst ){
89007      assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */
89008      aiRowEstPk[0] = pFirst->aiRowEst[0];
89009    }else{
89010      aiRowEstPk[0] = 1000000;
89011    }
89012    pProbe = &sPk;
89013    wsFlagMask = ~(
89014        WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
89015    );
89016    eqTermMask = WO_EQ|WO_IN;
89017    pIdx = 0;
89018  }
89019
89020  /* Loop over all indices looking for the best one to use
89021  */
89022  for(; pProbe; pIdx=pProbe=pProbe->pNext){
89023    const unsigned int * const aiRowEst = pProbe->aiRowEst;
89024    double cost;                /* Cost of using pProbe */
89025    double nRow;                /* Estimated number of rows in result set */
89026    int rev;                    /* True to scan in reverse order */
89027    int wsFlags = 0;
89028    Bitmask used = 0;
89029
89030    /* The following variables are populated based on the properties of
89031    ** scan being evaluated. They are then used to determine the expected
89032    ** cost and number of rows returned.
89033    **
89034    **  nEq:
89035    **    Number of equality terms that can be implemented using the index.
89036    **
89037    **  nInMul:
89038    **    The "in-multiplier". This is an estimate of how many seek operations
89039    **    SQLite must perform on the index in question. For example, if the
89040    **    WHERE clause is:
89041    **
89042    **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
89043    **
89044    **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
89045    **    set to 9. Given the same schema and either of the following WHERE
89046    **    clauses:
89047    **
89048    **      WHERE a =  1
89049    **      WHERE a >= 2
89050    **
89051    **    nInMul is set to 1.
89052    **
89053    **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
89054    **    the sub-select is assumed to return 25 rows for the purposes of
89055    **    determining nInMul.
89056    **
89057    **  bInEst:
89058    **    Set to true if there was at least one "x IN (SELECT ...)" term used
89059    **    in determining the value of nInMul.
89060    **
89061    **  nBound:
89062    **    An estimate on the amount of the table that must be searched.  A
89063    **    value of 100 means the entire table is searched.  Range constraints
89064    **    might reduce this to a value less than 100 to indicate that only
89065    **    a fraction of the table needs searching.  In the absence of
89066    **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
89067    **    space to 1/3rd its original size.  So an x>? constraint reduces
89068    **    nBound to 33.  Two constraints (x>? AND x<?) reduce nBound to 11.
89069    **
89070    **  bSort:
89071    **    Boolean. True if there is an ORDER BY clause that will require an
89072    **    external sort (i.e. scanning the index being evaluated will not
89073    **    correctly order records).
89074    **
89075    **  bLookup:
89076    **    Boolean. True if for each index entry visited a lookup on the
89077    **    corresponding table b-tree is required. This is always false
89078    **    for the rowid index. For other indexes, it is true unless all the
89079    **    columns of the table used by the SELECT statement are present in
89080    **    the index (such an index is sometimes described as a covering index).
89081    **    For example, given the index on (a, b), the second of the following
89082    **    two queries requires table b-tree lookups, but the first does not.
89083    **
89084    **             SELECT a, b    FROM tbl WHERE a = 1;
89085    **             SELECT a, b, c FROM tbl WHERE a = 1;
89086    */
89087    int nEq;
89088    int bInEst = 0;
89089    int nInMul = 1;
89090    int nBound = 100;
89091    int bSort = 0;
89092    int bLookup = 0;
89093
89094    /* Determine the values of nEq and nInMul */
89095    for(nEq=0; nEq<pProbe->nColumn; nEq++){
89096      WhereTerm *pTerm;           /* A single term of the WHERE clause */
89097      int j = pProbe->aiColumn[nEq];
89098      pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
89099      if( pTerm==0 ) break;
89100      wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
89101      if( pTerm->eOperator & WO_IN ){
89102        Expr *pExpr = pTerm->pExpr;
89103        wsFlags |= WHERE_COLUMN_IN;
89104        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
89105          nInMul *= 25;
89106          bInEst = 1;
89107        }else if( pExpr->x.pList ){
89108          nInMul *= pExpr->x.pList->nExpr + 1;
89109        }
89110      }else if( pTerm->eOperator & WO_ISNULL ){
89111        wsFlags |= WHERE_COLUMN_NULL;
89112      }
89113      used |= pTerm->prereqRight;
89114    }
89115
89116    /* Determine the value of nBound. */
89117    if( nEq<pProbe->nColumn ){
89118      int j = pProbe->aiColumn[nEq];
89119      if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
89120        WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
89121        WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
89122        whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &nBound);
89123        if( pTop ){
89124          wsFlags |= WHERE_TOP_LIMIT;
89125          used |= pTop->prereqRight;
89126        }
89127        if( pBtm ){
89128          wsFlags |= WHERE_BTM_LIMIT;
89129          used |= pBtm->prereqRight;
89130        }
89131        wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
89132      }
89133    }else if( pProbe->onError!=OE_None ){
89134      testcase( wsFlags & WHERE_COLUMN_IN );
89135      testcase( wsFlags & WHERE_COLUMN_NULL );
89136      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
89137        wsFlags |= WHERE_UNIQUE;
89138      }
89139    }
89140
89141    /* If there is an ORDER BY clause and the index being considered will
89142    ** naturally scan rows in the required order, set the appropriate flags
89143    ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
89144    ** will scan rows in a different order, set the bSort variable.  */
89145    if( pOrderBy ){
89146      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
89147        && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
89148      ){
89149        wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
89150        wsFlags |= (rev ? WHERE_REVERSE : 0);
89151      }else{
89152        bSort = 1;
89153      }
89154    }
89155
89156    /* If currently calculating the cost of using an index (not the IPK
89157    ** index), determine if all required column data may be obtained without
89158    ** seeking to entries in the main table (i.e. if the index is a covering
89159    ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
89160    ** wsFlags. Otherwise, set the bLookup variable to true.  */
89161    if( pIdx && wsFlags ){
89162      Bitmask m = pSrc->colUsed;
89163      int j;
89164      for(j=0; j<pIdx->nColumn; j++){
89165        int x = pIdx->aiColumn[j];
89166        if( x<BMS-1 ){
89167          m &= ~(((Bitmask)1)<<x);
89168        }
89169      }
89170      if( m==0 ){
89171        wsFlags |= WHERE_IDX_ONLY;
89172      }else{
89173        bLookup = 1;
89174      }
89175    }
89176
89177    /**** Begin adding up the cost of using this index (Needs improvements)
89178    **
89179    ** Estimate the number of rows of output.  For an IN operator,
89180    ** do not let the estimate exceed half the rows in the table.
89181    */
89182    nRow = (double)(aiRowEst[nEq] * nInMul);
89183    if( bInEst && nRow*2>aiRowEst[0] ){
89184      nRow = aiRowEst[0]/2;
89185      nInMul = (int)(nRow / aiRowEst[nEq]);
89186    }
89187
89188    /* Assume constant cost to access a row and logarithmic cost to
89189    ** do a binary search.  Hence, the initial cost is the number of output
89190    ** rows plus log2(table-size) times the number of binary searches.
89191    */
89192    cost = nRow + nInMul*estLog(aiRowEst[0]);
89193
89194    /* Adjust the number of rows and the cost downward to reflect rows
89195    ** that are excluded by range constraints.
89196    */
89197    nRow = (nRow * (double)nBound) / (double)100;
89198    cost = (cost * (double)nBound) / (double)100;
89199
89200    /* Add in the estimated cost of sorting the result
89201    */
89202    if( bSort ){
89203      cost += cost*estLog(cost);
89204    }
89205
89206    /* If all information can be taken directly from the index, we avoid
89207    ** doing table lookups.  This reduces the cost by half.  (Not really -
89208    ** this needs to be fixed.)
89209    */
89210    if( pIdx && bLookup==0 ){
89211      cost /= (double)2;
89212    }
89213    /**** Cost of using this index has now been computed ****/
89214
89215    WHERETRACE((
89216      "tbl=%s idx=%s nEq=%d nInMul=%d nBound=%d bSort=%d bLookup=%d"
89217      " wsFlags=%d   (nRow=%.2f cost=%.2f)\n",
89218      pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
89219      nEq, nInMul, nBound, bSort, bLookup, wsFlags, nRow, cost
89220    ));
89221
89222    /* If this index is the best we have seen so far, then record this
89223    ** index and its cost in the pCost structure.
89224    */
89225    if( (!pIdx || wsFlags) && cost<pCost->rCost ){
89226      pCost->rCost = cost;
89227      pCost->nRow = nRow;
89228      pCost->used = used;
89229      pCost->plan.wsFlags = (wsFlags&wsFlagMask);
89230      pCost->plan.nEq = nEq;
89231      pCost->plan.u.pIdx = pIdx;
89232    }
89233
89234    /* If there was an INDEXED BY clause, then only that one index is
89235    ** considered. */
89236    if( pSrc->pIndex ) break;
89237
89238    /* Reset masks for the next index in the loop */
89239    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
89240    eqTermMask = idxEqTermMask;
89241  }
89242
89243  /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
89244  ** is set, then reverse the order that the index will be scanned
89245  ** in. This is used for application testing, to help find cases
89246  ** where application behaviour depends on the (undefined) order that
89247  ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
89248  if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
89249    pCost->plan.wsFlags |= WHERE_REVERSE;
89250  }
89251
89252  assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
89253  assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
89254  assert( pSrc->pIndex==0
89255       || pCost->plan.u.pIdx==0
89256       || pCost->plan.u.pIdx==pSrc->pIndex
89257  );
89258
89259  WHERETRACE(("best index is: %s\n",
89260    (pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
89261  ));
89262
89263  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
89264  pCost->plan.wsFlags |= eqTermMask;
89265}
89266
89267/*
89268** Find the query plan for accessing table pSrc->pTab. Write the
89269** best query plan and its cost into the WhereCost object supplied
89270** as the last parameter. This function may calculate the cost of
89271** both real and virtual table scans.
89272*/
89273static void bestIndex(
89274  Parse *pParse,              /* The parsing context */
89275  WhereClause *pWC,           /* The WHERE clause */
89276  struct SrcList_item *pSrc,  /* The FROM clause term to search */
89277  Bitmask notReady,           /* Mask of cursors that are not available */
89278  ExprList *pOrderBy,         /* The ORDER BY clause */
89279  WhereCost *pCost            /* Lowest cost query plan */
89280){
89281#ifndef SQLITE_OMIT_VIRTUALTABLE
89282  if( IsVirtual(pSrc->pTab) ){
89283    sqlite3_index_info *p = 0;
89284    bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p);
89285    if( p->needToFreeIdxStr ){
89286      sqlite3_free(p->idxStr);
89287    }
89288    sqlite3DbFree(pParse->db, p);
89289  }else
89290#endif
89291  {
89292    bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
89293  }
89294}
89295
89296/*
89297** Disable a term in the WHERE clause.  Except, do not disable the term
89298** if it controls a LEFT OUTER JOIN and it did not originate in the ON
89299** or USING clause of that join.
89300**
89301** Consider the term t2.z='ok' in the following queries:
89302**
89303**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
89304**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
89305**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
89306**
89307** The t2.z='ok' is disabled in the in (2) because it originates
89308** in the ON clause.  The term is disabled in (3) because it is not part
89309** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
89310**
89311** Disabling a term causes that term to not be tested in the inner loop
89312** of the join.  Disabling is an optimization.  When terms are satisfied
89313** by indices, we disable them to prevent redundant tests in the inner
89314** loop.  We would get the correct results if nothing were ever disabled,
89315** but joins might run a little slower.  The trick is to disable as much
89316** as we can without disabling too much.  If we disabled in (1), we'd get
89317** the wrong answer.  See ticket #813.
89318*/
89319static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
89320  if( pTerm
89321      && ALWAYS((pTerm->wtFlags & TERM_CODED)==0)
89322      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
89323  ){
89324    pTerm->wtFlags |= TERM_CODED;
89325    if( pTerm->iParent>=0 ){
89326      WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
89327      if( (--pOther->nChild)==0 ){
89328        disableTerm(pLevel, pOther);
89329      }
89330    }
89331  }
89332}
89333
89334/*
89335** Code an OP_Affinity opcode to apply the column affinity string zAff
89336** to the n registers starting at base.
89337**
89338** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
89339** beginning and end of zAff are ignored.  If all entries in zAff are
89340** SQLITE_AFF_NONE, then no code gets generated.
89341**
89342** This routine makes its own copy of zAff so that the caller is free
89343** to modify zAff after this routine returns.
89344*/
89345static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
89346  Vdbe *v = pParse->pVdbe;
89347  if( zAff==0 ){
89348    assert( pParse->db->mallocFailed );
89349    return;
89350  }
89351  assert( v!=0 );
89352
89353  /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
89354  ** and end of the affinity string.
89355  */
89356  while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
89357    n--;
89358    base++;
89359    zAff++;
89360  }
89361  while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
89362    n--;
89363  }
89364
89365  /* Code the OP_Affinity opcode if there is anything left to do. */
89366  if( n>0 ){
89367    sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
89368    sqlite3VdbeChangeP4(v, -1, zAff, n);
89369    sqlite3ExprCacheAffinityChange(pParse, base, n);
89370  }
89371}
89372
89373
89374/*
89375** Generate code for a single equality term of the WHERE clause.  An equality
89376** term can be either X=expr or X IN (...).   pTerm is the term to be
89377** coded.
89378**
89379** The current value for the constraint is left in register iReg.
89380**
89381** For a constraint of the form X=expr, the expression is evaluated and its
89382** result is left on the stack.  For constraints of the form X IN (...)
89383** this routine sets up a loop that will iterate over all values of X.
89384*/
89385static int codeEqualityTerm(
89386  Parse *pParse,      /* The parsing context */
89387  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
89388  WhereLevel *pLevel, /* When level of the FROM clause we are working on */
89389  int iTarget         /* Attempt to leave results in this register */
89390){
89391  Expr *pX = pTerm->pExpr;
89392  Vdbe *v = pParse->pVdbe;
89393  int iReg;                  /* Register holding results */
89394
89395  assert( iTarget>0 );
89396  if( pX->op==TK_EQ ){
89397    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
89398  }else if( pX->op==TK_ISNULL ){
89399    iReg = iTarget;
89400    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
89401#ifndef SQLITE_OMIT_SUBQUERY
89402  }else{
89403    int eType;
89404    int iTab;
89405    struct InLoop *pIn;
89406
89407    assert( pX->op==TK_IN );
89408    iReg = iTarget;
89409    eType = sqlite3FindInIndex(pParse, pX, 0);
89410    iTab = pX->iTable;
89411    sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
89412    assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
89413    if( pLevel->u.in.nIn==0 ){
89414      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
89415    }
89416    pLevel->u.in.nIn++;
89417    pLevel->u.in.aInLoop =
89418       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
89419                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
89420    pIn = pLevel->u.in.aInLoop;
89421    if( pIn ){
89422      pIn += pLevel->u.in.nIn - 1;
89423      pIn->iCur = iTab;
89424      if( eType==IN_INDEX_ROWID ){
89425        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
89426      }else{
89427        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
89428      }
89429      sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
89430    }else{
89431      pLevel->u.in.nIn = 0;
89432    }
89433#endif
89434  }
89435  disableTerm(pLevel, pTerm);
89436  return iReg;
89437}
89438
89439/*
89440** Generate code that will evaluate all == and IN constraints for an
89441** index.
89442**
89443** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
89444** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
89445** The index has as many as three equality constraints, but in this
89446** example, the third "c" value is an inequality.  So only two
89447** constraints are coded.  This routine will generate code to evaluate
89448** a==5 and b IN (1,2,3).  The current values for a and b will be stored
89449** in consecutive registers and the index of the first register is returned.
89450**
89451** In the example above nEq==2.  But this subroutine works for any value
89452** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
89453** The only thing it does is allocate the pLevel->iMem memory cell and
89454** compute the affinity string.
89455**
89456** This routine always allocates at least one memory cell and returns
89457** the index of that memory cell. The code that
89458** calls this routine will use that memory cell to store the termination
89459** key value of the loop.  If one or more IN operators appear, then
89460** this routine allocates an additional nEq memory cells for internal
89461** use.
89462**
89463** Before returning, *pzAff is set to point to a buffer containing a
89464** copy of the column affinity string of the index allocated using
89465** sqlite3DbMalloc(). Except, entries in the copy of the string associated
89466** with equality constraints that use NONE affinity are set to
89467** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
89468**
89469**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
89470**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
89471**
89472** In the example above, the index on t1(a) has TEXT affinity. But since
89473** the right hand side of the equality constraint (t2.b) has NONE affinity,
89474** no conversion should be attempted before using a t2.b value as part of
89475** a key to search the index. Hence the first byte in the returned affinity
89476** string in this example would be set to SQLITE_AFF_NONE.
89477*/
89478static int codeAllEqualityTerms(
89479  Parse *pParse,        /* Parsing context */
89480  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
89481  WhereClause *pWC,     /* The WHERE clause */
89482  Bitmask notReady,     /* Which parts of FROM have not yet been coded */
89483  int nExtraReg,        /* Number of extra registers to allocate */
89484  char **pzAff          /* OUT: Set to point to affinity string */
89485){
89486  int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
89487  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
89488  Index *pIdx;                  /* The index being used for this loop */
89489  int iCur = pLevel->iTabCur;   /* The cursor of the table */
89490  WhereTerm *pTerm;             /* A single constraint term */
89491  int j;                        /* Loop counter */
89492  int regBase;                  /* Base register */
89493  int nReg;                     /* Number of registers to allocate */
89494  char *zAff;                   /* Affinity string to return */
89495
89496  /* This module is only called on query plans that use an index. */
89497  assert( pLevel->plan.wsFlags & WHERE_INDEXED );
89498  pIdx = pLevel->plan.u.pIdx;
89499
89500  /* Figure out how many memory cells we will need then allocate them.
89501  */
89502  regBase = pParse->nMem + 1;
89503  nReg = pLevel->plan.nEq + nExtraReg;
89504  pParse->nMem += nReg;
89505
89506  zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
89507  if( !zAff ){
89508    pParse->db->mallocFailed = 1;
89509  }
89510
89511  /* Evaluate the equality constraints
89512  */
89513  assert( pIdx->nColumn>=nEq );
89514  for(j=0; j<nEq; j++){
89515    int r1;
89516    int k = pIdx->aiColumn[j];
89517    pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
89518    if( NEVER(pTerm==0) ) break;
89519    assert( (pTerm->wtFlags & TERM_CODED)==0 );
89520    r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
89521    if( r1!=regBase+j ){
89522      if( nReg==1 ){
89523        sqlite3ReleaseTempReg(pParse, regBase);
89524        regBase = r1;
89525      }else{
89526        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
89527      }
89528    }
89529    testcase( pTerm->eOperator & WO_ISNULL );
89530    testcase( pTerm->eOperator & WO_IN );
89531    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
89532      Expr *pRight = pTerm->pExpr->pRight;
89533      sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
89534      if( zAff ){
89535        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
89536          zAff[j] = SQLITE_AFF_NONE;
89537        }
89538        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
89539          zAff[j] = SQLITE_AFF_NONE;
89540        }
89541      }
89542    }
89543  }
89544  *pzAff = zAff;
89545  return regBase;
89546}
89547
89548/*
89549** Generate code for the start of the iLevel-th loop in the WHERE clause
89550** implementation described by pWInfo.
89551*/
89552static Bitmask codeOneLoopStart(
89553  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
89554  int iLevel,          /* Which level of pWInfo->a[] should be coded */
89555  u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
89556  Bitmask notReady     /* Which tables are currently available */
89557){
89558  int j, k;            /* Loop counters */
89559  int iCur;            /* The VDBE cursor for the table */
89560  int addrNxt;         /* Where to jump to continue with the next IN case */
89561  int omitTable;       /* True if we use the index only */
89562  int bRev;            /* True if we need to scan in reverse order */
89563  WhereLevel *pLevel;  /* The where level to be coded */
89564  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
89565  WhereTerm *pTerm;               /* A WHERE clause term */
89566  Parse *pParse;                  /* Parsing context */
89567  Vdbe *v;                        /* The prepared stmt under constructions */
89568  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
89569  int addrBrk;                    /* Jump here to break out of the loop */
89570  int addrCont;                   /* Jump here to continue with next cycle */
89571  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
89572  int iReleaseReg = 0;      /* Temp register to free before returning */
89573
89574  pParse = pWInfo->pParse;
89575  v = pParse->pVdbe;
89576  pWC = pWInfo->pWC;
89577  pLevel = &pWInfo->a[iLevel];
89578  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
89579  iCur = pTabItem->iCursor;
89580  bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
89581  omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
89582           && (wctrlFlags & WHERE_FORCE_TABLE)==0;
89583
89584  /* Create labels for the "break" and "continue" instructions
89585  ** for the current loop.  Jump to addrBrk to break out of a loop.
89586  ** Jump to cont to go immediately to the next iteration of the
89587  ** loop.
89588  **
89589  ** When there is an IN operator, we also have a "addrNxt" label that
89590  ** means to continue with the next IN value combination.  When
89591  ** there are no IN operators in the constraints, the "addrNxt" label
89592  ** is the same as "addrBrk".
89593  */
89594  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
89595  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
89596
89597  /* If this is the right table of a LEFT OUTER JOIN, allocate and
89598  ** initialize a memory cell that records if this table matches any
89599  ** row of the left table of the join.
89600  */
89601  if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
89602    pLevel->iLeftJoin = ++pParse->nMem;
89603    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
89604    VdbeComment((v, "init LEFT JOIN no-match flag"));
89605  }
89606
89607#ifndef SQLITE_OMIT_VIRTUALTABLE
89608  if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
89609    /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
89610    **          to access the data.
89611    */
89612    int iReg;   /* P3 Value for OP_VFilter */
89613    sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
89614    int nConstraint = pVtabIdx->nConstraint;
89615    struct sqlite3_index_constraint_usage *aUsage =
89616                                                pVtabIdx->aConstraintUsage;
89617    const struct sqlite3_index_constraint *aConstraint =
89618                                                pVtabIdx->aConstraint;
89619
89620    sqlite3ExprCachePush(pParse);
89621    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
89622    for(j=1; j<=nConstraint; j++){
89623      for(k=0; k<nConstraint; k++){
89624        if( aUsage[k].argvIndex==j ){
89625          int iTerm = aConstraint[k].iTermOffset;
89626          sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
89627          break;
89628        }
89629      }
89630      if( k==nConstraint ) break;
89631    }
89632    sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
89633    sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
89634    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
89635                      pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
89636    pVtabIdx->needToFreeIdxStr = 0;
89637    for(j=0; j<nConstraint; j++){
89638      if( aUsage[j].omit ){
89639        int iTerm = aConstraint[j].iTermOffset;
89640        disableTerm(pLevel, &pWC->a[iTerm]);
89641      }
89642    }
89643    pLevel->op = OP_VNext;
89644    pLevel->p1 = iCur;
89645    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
89646    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
89647    sqlite3ExprCachePop(pParse, 1);
89648  }else
89649#endif /* SQLITE_OMIT_VIRTUALTABLE */
89650
89651  if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
89652    /* Case 1:  We can directly reference a single row using an
89653    **          equality comparison against the ROWID field.  Or
89654    **          we reference multiple rows using a "rowid IN (...)"
89655    **          construct.
89656    */
89657    iReleaseReg = sqlite3GetTempReg(pParse);
89658    pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
89659    assert( pTerm!=0 );
89660    assert( pTerm->pExpr!=0 );
89661    assert( pTerm->leftCursor==iCur );
89662    assert( omitTable==0 );
89663    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
89664    addrNxt = pLevel->addrNxt;
89665    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
89666    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
89667    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
89668    VdbeComment((v, "pk"));
89669    pLevel->op = OP_Noop;
89670  }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
89671    /* Case 2:  We have an inequality comparison against the ROWID field.
89672    */
89673    int testOp = OP_Noop;
89674    int start;
89675    int memEndValue = 0;
89676    WhereTerm *pStart, *pEnd;
89677
89678    assert( omitTable==0 );
89679    pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
89680    pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
89681    if( bRev ){
89682      pTerm = pStart;
89683      pStart = pEnd;
89684      pEnd = pTerm;
89685    }
89686    if( pStart ){
89687      Expr *pX;             /* The expression that defines the start bound */
89688      int r1, rTemp;        /* Registers for holding the start boundary */
89689
89690      /* The following constant maps TK_xx codes into corresponding
89691      ** seek opcodes.  It depends on a particular ordering of TK_xx
89692      */
89693      const u8 aMoveOp[] = {
89694           /* TK_GT */  OP_SeekGt,
89695           /* TK_LE */  OP_SeekLe,
89696           /* TK_LT */  OP_SeekLt,
89697           /* TK_GE */  OP_SeekGe
89698      };
89699      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
89700      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
89701      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
89702
89703      pX = pStart->pExpr;
89704      assert( pX!=0 );
89705      assert( pStart->leftCursor==iCur );
89706      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
89707      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
89708      VdbeComment((v, "pk"));
89709      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
89710      sqlite3ReleaseTempReg(pParse, rTemp);
89711      disableTerm(pLevel, pStart);
89712    }else{
89713      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
89714    }
89715    if( pEnd ){
89716      Expr *pX;
89717      pX = pEnd->pExpr;
89718      assert( pX!=0 );
89719      assert( pEnd->leftCursor==iCur );
89720      memEndValue = ++pParse->nMem;
89721      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
89722      if( pX->op==TK_LT || pX->op==TK_GT ){
89723        testOp = bRev ? OP_Le : OP_Ge;
89724      }else{
89725        testOp = bRev ? OP_Lt : OP_Gt;
89726      }
89727      disableTerm(pLevel, pEnd);
89728    }
89729    start = sqlite3VdbeCurrentAddr(v);
89730    pLevel->op = bRev ? OP_Prev : OP_Next;
89731    pLevel->p1 = iCur;
89732    pLevel->p2 = start;
89733    pLevel->p5 = (pStart==0 && pEnd==0) ?1:0;
89734    if( testOp!=OP_Noop ){
89735      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
89736      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
89737      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
89738      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
89739      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
89740    }
89741  }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
89742    /* Case 3: A scan using an index.
89743    **
89744    **         The WHERE clause may contain zero or more equality
89745    **         terms ("==" or "IN" operators) that refer to the N
89746    **         left-most columns of the index. It may also contain
89747    **         inequality constraints (>, <, >= or <=) on the indexed
89748    **         column that immediately follows the N equalities. Only
89749    **         the right-most column can be an inequality - the rest must
89750    **         use the "==" and "IN" operators. For example, if the
89751    **         index is on (x,y,z), then the following clauses are all
89752    **         optimized:
89753    **
89754    **            x=5
89755    **            x=5 AND y=10
89756    **            x=5 AND y<10
89757    **            x=5 AND y>5 AND y<10
89758    **            x=5 AND y=5 AND z<=10
89759    **
89760    **         The z<10 term of the following cannot be used, only
89761    **         the x=5 term:
89762    **
89763    **            x=5 AND z<10
89764    **
89765    **         N may be zero if there are inequality constraints.
89766    **         If there are no inequality constraints, then N is at
89767    **         least one.
89768    **
89769    **         This case is also used when there are no WHERE clause
89770    **         constraints but an index is selected anyway, in order
89771    **         to force the output order to conform to an ORDER BY.
89772    */
89773    int aStartOp[] = {
89774      0,
89775      0,
89776      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
89777      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
89778      OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
89779      OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
89780      OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
89781      OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
89782    };
89783    int aEndOp[] = {
89784      OP_Noop,             /* 0: (!end_constraints) */
89785      OP_IdxGE,            /* 1: (end_constraints && !bRev) */
89786      OP_IdxLT             /* 2: (end_constraints && bRev) */
89787    };
89788    int nEq = pLevel->plan.nEq;
89789    int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
89790    int regBase;                 /* Base register holding constraint values */
89791    int r1;                      /* Temp register */
89792    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
89793    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
89794    int startEq;                 /* True if range start uses ==, >= or <= */
89795    int endEq;                   /* True if range end uses ==, >= or <= */
89796    int start_constraints;       /* Start of range is constrained */
89797    int nConstraint;             /* Number of constraint terms */
89798    Index *pIdx;         /* The index we will be using */
89799    int iIdxCur;         /* The VDBE cursor for the index */
89800    int nExtraReg = 0;   /* Number of extra registers needed */
89801    int op;              /* Instruction opcode */
89802    char *zAff;
89803
89804    pIdx = pLevel->plan.u.pIdx;
89805    iIdxCur = pLevel->iIdxCur;
89806    k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
89807
89808    /* If this loop satisfies a sort order (pOrderBy) request that
89809    ** was passed to this function to implement a "SELECT min(x) ..."
89810    ** query, then the caller will only allow the loop to run for
89811    ** a single iteration. This means that the first row returned
89812    ** should not have a NULL value stored in 'x'. If column 'x' is
89813    ** the first one after the nEq equality constraints in the index,
89814    ** this requires some special handling.
89815    */
89816    if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
89817     && (pLevel->plan.wsFlags&WHERE_ORDERBY)
89818     && (pIdx->nColumn>nEq)
89819    ){
89820      /* assert( pOrderBy->nExpr==1 ); */
89821      /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
89822      isMinQuery = 1;
89823      nExtraReg = 1;
89824    }
89825
89826    /* Find any inequality constraint terms for the start and end
89827    ** of the range.
89828    */
89829    if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
89830      pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
89831      nExtraReg = 1;
89832    }
89833    if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
89834      pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
89835      nExtraReg = 1;
89836    }
89837
89838    /* Generate code to evaluate all constraint terms using == or IN
89839    ** and store the values of those terms in an array of registers
89840    ** starting at regBase.
89841    */
89842    regBase = codeAllEqualityTerms(
89843        pParse, pLevel, pWC, notReady, nExtraReg, &zAff
89844    );
89845    addrNxt = pLevel->addrNxt;
89846
89847    /* If we are doing a reverse order scan on an ascending index, or
89848    ** a forward order scan on a descending index, interchange the
89849    ** start and end terms (pRangeStart and pRangeEnd).
89850    */
89851    if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
89852      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
89853    }
89854
89855    testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
89856    testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
89857    testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
89858    testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
89859    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
89860    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
89861    start_constraints = pRangeStart || nEq>0;
89862
89863    /* Seek the index cursor to the start of the range. */
89864    nConstraint = nEq;
89865    if( pRangeStart ){
89866      Expr *pRight = pRangeStart->pExpr->pRight;
89867      sqlite3ExprCode(pParse, pRight, regBase+nEq);
89868      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
89869      if( zAff ){
89870        if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
89871          /* Since the comparison is to be performed with no conversions
89872          ** applied to the operands, set the affinity to apply to pRight to
89873          ** SQLITE_AFF_NONE.  */
89874          zAff[nConstraint] = SQLITE_AFF_NONE;
89875        }
89876        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
89877          zAff[nConstraint] = SQLITE_AFF_NONE;
89878        }
89879      }
89880      nConstraint++;
89881    }else if( isMinQuery ){
89882      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
89883      nConstraint++;
89884      startEq = 0;
89885      start_constraints = 1;
89886    }
89887    codeApplyAffinity(pParse, regBase, nConstraint, zAff);
89888    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
89889    assert( op!=0 );
89890    testcase( op==OP_Rewind );
89891    testcase( op==OP_Last );
89892    testcase( op==OP_SeekGt );
89893    testcase( op==OP_SeekGe );
89894    testcase( op==OP_SeekLe );
89895    testcase( op==OP_SeekLt );
89896    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
89897
89898    /* Load the value for the inequality constraint at the end of the
89899    ** range (if any).
89900    */
89901    nConstraint = nEq;
89902    if( pRangeEnd ){
89903      Expr *pRight = pRangeEnd->pExpr->pRight;
89904      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
89905      sqlite3ExprCode(pParse, pRight, regBase+nEq);
89906      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
89907      if( zAff ){
89908        if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
89909          /* Since the comparison is to be performed with no conversions
89910          ** applied to the operands, set the affinity to apply to pRight to
89911          ** SQLITE_AFF_NONE.  */
89912          zAff[nConstraint] = SQLITE_AFF_NONE;
89913        }
89914        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
89915          zAff[nConstraint] = SQLITE_AFF_NONE;
89916        }
89917      }
89918      codeApplyAffinity(pParse, regBase, nEq+1, zAff);
89919      nConstraint++;
89920    }
89921    sqlite3DbFree(pParse->db, zAff);
89922
89923    /* Top of the loop body */
89924    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
89925
89926    /* Check if the index cursor is past the end of the range. */
89927    op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
89928    testcase( op==OP_Noop );
89929    testcase( op==OP_IdxGE );
89930    testcase( op==OP_IdxLT );
89931    if( op!=OP_Noop ){
89932      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
89933      sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
89934    }
89935
89936    /* If there are inequality constraints, check that the value
89937    ** of the table column that the inequality contrains is not NULL.
89938    ** If it is, jump to the next iteration of the loop.
89939    */
89940    r1 = sqlite3GetTempReg(pParse);
89941    testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
89942    testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
89943    if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
89944      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
89945      sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
89946    }
89947    sqlite3ReleaseTempReg(pParse, r1);
89948
89949    /* Seek the table cursor, if required */
89950    disableTerm(pLevel, pRangeStart);
89951    disableTerm(pLevel, pRangeEnd);
89952    if( !omitTable ){
89953      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
89954      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
89955      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
89956      sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
89957    }
89958
89959    /* Record the instruction used to terminate the loop. Disable
89960    ** WHERE clause terms made redundant by the index range scan.
89961    */
89962    pLevel->op = bRev ? OP_Prev : OP_Next;
89963    pLevel->p1 = iIdxCur;
89964  }else
89965
89966#ifndef SQLITE_OMIT_OR_OPTIMIZATION
89967  if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
89968    /* Case 4:  Two or more separately indexed terms connected by OR
89969    **
89970    ** Example:
89971    **
89972    **   CREATE TABLE t1(a,b,c,d);
89973    **   CREATE INDEX i1 ON t1(a);
89974    **   CREATE INDEX i2 ON t1(b);
89975    **   CREATE INDEX i3 ON t1(c);
89976    **
89977    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
89978    **
89979    ** In the example, there are three indexed terms connected by OR.
89980    ** The top of the loop looks like this:
89981    **
89982    **          Null       1                # Zero the rowset in reg 1
89983    **
89984    ** Then, for each indexed term, the following. The arguments to
89985    ** RowSetTest are such that the rowid of the current row is inserted
89986    ** into the RowSet. If it is already present, control skips the
89987    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
89988    **
89989    **        sqlite3WhereBegin(<term>)
89990    **          RowSetTest                  # Insert rowid into rowset
89991    **          Gosub      2 A
89992    **        sqlite3WhereEnd()
89993    **
89994    ** Following the above, code to terminate the loop. Label A, the target
89995    ** of the Gosub above, jumps to the instruction right after the Goto.
89996    **
89997    **          Null       1                # Zero the rowset in reg 1
89998    **          Goto       B                # The loop is finished.
89999    **
90000    **       A: <loop body>                 # Return data, whatever.
90001    **
90002    **          Return     2                # Jump back to the Gosub
90003    **
90004    **       B: <after the loop>
90005    **
90006    */
90007    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
90008    WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
90009    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
90010
90011    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
90012    int regRowset = 0;                        /* Register for RowSet object */
90013    int regRowid = 0;                         /* Register holding rowid */
90014    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
90015    int iRetInit;                             /* Address of regReturn init */
90016    int untestedTerms = 0;             /* Some terms not completely tested */
90017    int ii;
90018
90019    pTerm = pLevel->plan.u.pTerm;
90020    assert( pTerm!=0 );
90021    assert( pTerm->eOperator==WO_OR );
90022    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
90023    pOrWc = &pTerm->u.pOrInfo->wc;
90024    pFinal = &pOrWc->a[pOrWc->nTerm-1];
90025    pLevel->op = OP_Return;
90026    pLevel->p1 = regReturn;
90027
90028    /* Set up a new SrcList ni pOrTab containing the table being scanned
90029    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
90030    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
90031    */
90032    if( pWInfo->nLevel>1 ){
90033      int nNotReady;                 /* The number of notReady tables */
90034      struct SrcList_item *origSrc;     /* Original list of tables */
90035      nNotReady = pWInfo->nLevel - iLevel - 1;
90036      pOrTab = sqlite3StackAllocRaw(pParse->db,
90037                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
90038      if( pOrTab==0 ) return notReady;
90039      pOrTab->nAlloc = (i16)(nNotReady + 1);
90040      pOrTab->nSrc = pOrTab->nAlloc;
90041      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
90042      origSrc = pWInfo->pTabList->a;
90043      for(k=1; k<=nNotReady; k++){
90044        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
90045      }
90046    }else{
90047      pOrTab = pWInfo->pTabList;
90048    }
90049
90050    /* Initialize the rowset register to contain NULL. An SQL NULL is
90051    ** equivalent to an empty rowset.
90052    **
90053    ** Also initialize regReturn to contain the address of the instruction
90054    ** immediately following the OP_Return at the bottom of the loop. This
90055    ** is required in a few obscure LEFT JOIN cases where control jumps
90056    ** over the top of the loop into the body of it. In this case the
90057    ** correct response for the end-of-loop code (the OP_Return) is to
90058    ** fall through to the next instruction, just as an OP_Next does if
90059    ** called on an uninitialized cursor.
90060    */
90061    if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
90062      regRowset = ++pParse->nMem;
90063      regRowid = ++pParse->nMem;
90064      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
90065    }
90066    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
90067
90068    for(ii=0; ii<pOrWc->nTerm; ii++){
90069      WhereTerm *pOrTerm = &pOrWc->a[ii];
90070      if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
90071        WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
90072        /* Loop through table entries that match term pOrTerm. */
90073        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
90074                        WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
90075                        WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
90076        if( pSubWInfo ){
90077          if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
90078            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
90079            int r;
90080            r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
90081                                         regRowid);
90082            sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
90083                                 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
90084          }
90085          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
90086
90087          /* The pSubWInfo->untestedTerms flag means that this OR term
90088          ** contained one or more AND term from a notReady table.  The
90089          ** terms from the notReady table could not be tested and will
90090          ** need to be tested later.
90091          */
90092          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
90093
90094          /* Finish the loop through table entries that match term pOrTerm. */
90095          sqlite3WhereEnd(pSubWInfo);
90096        }
90097      }
90098    }
90099    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
90100    sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
90101    sqlite3VdbeResolveLabel(v, iLoopBody);
90102
90103    if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
90104    if( !untestedTerms ) disableTerm(pLevel, pTerm);
90105  }else
90106#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
90107
90108  {
90109    /* Case 5:  There is no usable index.  We must do a complete
90110    **          scan of the entire table.
90111    */
90112    static const u8 aStep[] = { OP_Next, OP_Prev };
90113    static const u8 aStart[] = { OP_Rewind, OP_Last };
90114    assert( bRev==0 || bRev==1 );
90115    assert( omitTable==0 );
90116    pLevel->op = aStep[bRev];
90117    pLevel->p1 = iCur;
90118    pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
90119    pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
90120  }
90121  notReady &= ~getMask(pWC->pMaskSet, iCur);
90122
90123  /* Insert code to test every subexpression that can be completely
90124  ** computed using the current set of tables.
90125  */
90126  k = 0;
90127  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
90128    Expr *pE;
90129    testcase( pTerm->wtFlags & TERM_VIRTUAL );
90130    testcase( pTerm->wtFlags & TERM_CODED );
90131    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
90132    if( (pTerm->prereqAll & notReady)!=0 ){
90133      testcase( pWInfo->untestedTerms==0
90134               && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
90135      pWInfo->untestedTerms = 1;
90136      continue;
90137    }
90138    pE = pTerm->pExpr;
90139    assert( pE!=0 );
90140    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
90141      continue;
90142    }
90143    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
90144    k = 1;
90145    pTerm->wtFlags |= TERM_CODED;
90146  }
90147
90148  /* For a LEFT OUTER JOIN, generate code that will record the fact that
90149  ** at least one row of the right table has matched the left table.
90150  */
90151  if( pLevel->iLeftJoin ){
90152    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
90153    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
90154    VdbeComment((v, "record LEFT JOIN hit"));
90155    sqlite3ExprCacheClear(pParse);
90156    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
90157      testcase( pTerm->wtFlags & TERM_VIRTUAL );
90158      testcase( pTerm->wtFlags & TERM_CODED );
90159      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
90160      if( (pTerm->prereqAll & notReady)!=0 ){
90161        assert( pWInfo->untestedTerms );
90162        continue;
90163      }
90164      assert( pTerm->pExpr );
90165      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
90166      pTerm->wtFlags |= TERM_CODED;
90167    }
90168  }
90169  sqlite3ReleaseTempReg(pParse, iReleaseReg);
90170
90171  return notReady;
90172}
90173
90174#if defined(SQLITE_TEST)
90175/*
90176** The following variable holds a text description of query plan generated
90177** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
90178** overwrites the previous.  This information is used for testing and
90179** analysis only.
90180*/
90181SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
90182static int nQPlan = 0;              /* Next free slow in _query_plan[] */
90183
90184#endif /* SQLITE_TEST */
90185
90186
90187/*
90188** Free a WhereInfo structure
90189*/
90190static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
90191  if( pWInfo ){
90192    int i;
90193    for(i=0; i<pWInfo->nLevel; i++){
90194      sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
90195      if( pInfo ){
90196        /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
90197        if( pInfo->needToFreeIdxStr ){
90198          sqlite3_free(pInfo->idxStr);
90199        }
90200        sqlite3DbFree(db, pInfo);
90201      }
90202    }
90203    whereClauseClear(pWInfo->pWC);
90204    sqlite3DbFree(db, pWInfo);
90205  }
90206}
90207
90208
90209/*
90210** Generate the beginning of the loop used for WHERE clause processing.
90211** The return value is a pointer to an opaque structure that contains
90212** information needed to terminate the loop.  Later, the calling routine
90213** should invoke sqlite3WhereEnd() with the return value of this function
90214** in order to complete the WHERE clause processing.
90215**
90216** If an error occurs, this routine returns NULL.
90217**
90218** The basic idea is to do a nested loop, one loop for each table in
90219** the FROM clause of a select.  (INSERT and UPDATE statements are the
90220** same as a SELECT with only a single table in the FROM clause.)  For
90221** example, if the SQL is this:
90222**
90223**       SELECT * FROM t1, t2, t3 WHERE ...;
90224**
90225** Then the code generated is conceptually like the following:
90226**
90227**      foreach row1 in t1 do       \    Code generated
90228**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
90229**          foreach row3 in t3 do   /
90230**            ...
90231**          end                     \    Code generated
90232**        end                        |-- by sqlite3WhereEnd()
90233**      end                         /
90234**
90235** Note that the loops might not be nested in the order in which they
90236** appear in the FROM clause if a different order is better able to make
90237** use of indices.  Note also that when the IN operator appears in
90238** the WHERE clause, it might result in additional nested loops for
90239** scanning through all values on the right-hand side of the IN.
90240**
90241** There are Btree cursors associated with each table.  t1 uses cursor
90242** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
90243** And so forth.  This routine generates code to open those VDBE cursors
90244** and sqlite3WhereEnd() generates the code to close them.
90245**
90246** The code that sqlite3WhereBegin() generates leaves the cursors named
90247** in pTabList pointing at their appropriate entries.  The [...] code
90248** can use OP_Column and OP_Rowid opcodes on these cursors to extract
90249** data from the various tables of the loop.
90250**
90251** If the WHERE clause is empty, the foreach loops must each scan their
90252** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
90253** the tables have indices and there are terms in the WHERE clause that
90254** refer to those indices, a complete table scan can be avoided and the
90255** code will run much faster.  Most of the work of this routine is checking
90256** to see if there are indices that can be used to speed up the loop.
90257**
90258** Terms of the WHERE clause are also used to limit which rows actually
90259** make it to the "..." in the middle of the loop.  After each "foreach",
90260** terms of the WHERE clause that use only terms in that loop and outer
90261** loops are evaluated and if false a jump is made around all subsequent
90262** inner loops (or around the "..." if the test occurs within the inner-
90263** most loop)
90264**
90265** OUTER JOINS
90266**
90267** An outer join of tables t1 and t2 is conceptally coded as follows:
90268**
90269**    foreach row1 in t1 do
90270**      flag = 0
90271**      foreach row2 in t2 do
90272**        start:
90273**          ...
90274**          flag = 1
90275**      end
90276**      if flag==0 then
90277**        move the row2 cursor to a null row
90278**        goto start
90279**      fi
90280**    end
90281**
90282** ORDER BY CLAUSE PROCESSING
90283**
90284** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
90285** if there is one.  If there is no ORDER BY clause or if this routine
90286** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
90287**
90288** If an index can be used so that the natural output order of the table
90289** scan is correct for the ORDER BY clause, then that index is used and
90290** *ppOrderBy is set to NULL.  This is an optimization that prevents an
90291** unnecessary sort of the result set if an index appropriate for the
90292** ORDER BY clause already exists.
90293**
90294** If the where clause loops cannot be arranged to provide the correct
90295** output order, then the *ppOrderBy is unchanged.
90296*/
90297SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
90298  Parse *pParse,        /* The parser context */
90299  SrcList *pTabList,    /* A list of all tables to be scanned */
90300  Expr *pWhere,         /* The WHERE clause */
90301  ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
90302  u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
90303){
90304  int i;                     /* Loop counter */
90305  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
90306  int nTabList;              /* Number of elements in pTabList */
90307  WhereInfo *pWInfo;         /* Will become the return value of this function */
90308  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
90309  Bitmask notReady;          /* Cursors that are not yet positioned */
90310  WhereMaskSet *pMaskSet;    /* The expression mask set */
90311  WhereClause *pWC;               /* Decomposition of the WHERE clause */
90312  struct SrcList_item *pTabItem;  /* A single entry from pTabList */
90313  WhereLevel *pLevel;             /* A single level in the pWInfo list */
90314  int iFrom;                      /* First unused FROM clause element */
90315  int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
90316  sqlite3 *db;               /* Database connection */
90317
90318  /* The number of tables in the FROM clause is limited by the number of
90319  ** bits in a Bitmask
90320  */
90321  if( pTabList->nSrc>BMS ){
90322    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
90323    return 0;
90324  }
90325
90326  /* This function normally generates a nested loop for all tables in
90327  ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
90328  ** only generate code for the first table in pTabList and assume that
90329  ** any cursors associated with subsequent tables are uninitialized.
90330  */
90331  nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
90332
90333  /* Allocate and initialize the WhereInfo structure that will become the
90334  ** return value. A single allocation is used to store the WhereInfo
90335  ** struct, the contents of WhereInfo.a[], the WhereClause structure
90336  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
90337  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
90338  ** some architectures. Hence the ROUND8() below.
90339  */
90340  db = pParse->db;
90341  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
90342  pWInfo = sqlite3DbMallocZero(db,
90343      nByteWInfo +
90344      sizeof(WhereClause) +
90345      sizeof(WhereMaskSet)
90346  );
90347  if( db->mallocFailed ){
90348    goto whereBeginError;
90349  }
90350  pWInfo->nLevel = nTabList;
90351  pWInfo->pParse = pParse;
90352  pWInfo->pTabList = pTabList;
90353  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
90354  pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
90355  pWInfo->wctrlFlags = wctrlFlags;
90356  pMaskSet = (WhereMaskSet*)&pWC[1];
90357
90358  /* Split the WHERE clause into separate subexpressions where each
90359  ** subexpression is separated by an AND operator.
90360  */
90361  initMaskSet(pMaskSet);
90362  whereClauseInit(pWC, pParse, pMaskSet);
90363  sqlite3ExprCodeConstants(pParse, pWhere);
90364  whereSplit(pWC, pWhere, TK_AND);
90365
90366  /* Special case: a WHERE clause that is constant.  Evaluate the
90367  ** expression and either jump over all of the code or fall thru.
90368  */
90369  if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
90370    sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
90371    pWhere = 0;
90372  }
90373
90374  /* Assign a bit from the bitmask to every term in the FROM clause.
90375  **
90376  ** When assigning bitmask values to FROM clause cursors, it must be
90377  ** the case that if X is the bitmask for the N-th FROM clause term then
90378  ** the bitmask for all FROM clause terms to the left of the N-th term
90379  ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
90380  ** its Expr.iRightJoinTable value to find the bitmask of the right table
90381  ** of the join.  Subtracting one from the right table bitmask gives a
90382  ** bitmask for all tables to the left of the join.  Knowing the bitmask
90383  ** for all tables to the left of a left join is important.  Ticket #3015.
90384  **
90385  ** Configure the WhereClause.vmask variable so that bits that correspond
90386  ** to virtual table cursors are set. This is used to selectively disable
90387  ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
90388  ** with virtual tables.
90389  **
90390  ** Note that bitmasks are created for all pTabList->nSrc tables in
90391  ** pTabList, not just the first nTabList tables.  nTabList is normally
90392  ** equal to pTabList->nSrc but might be shortened to 1 if the
90393  ** WHERE_ONETABLE_ONLY flag is set.
90394  */
90395  assert( pWC->vmask==0 && pMaskSet->n==0 );
90396  for(i=0; i<pTabList->nSrc; i++){
90397    createMask(pMaskSet, pTabList->a[i].iCursor);
90398#ifndef SQLITE_OMIT_VIRTUALTABLE
90399    if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
90400      pWC->vmask |= ((Bitmask)1 << i);
90401    }
90402#endif
90403  }
90404#ifndef NDEBUG
90405  {
90406    Bitmask toTheLeft = 0;
90407    for(i=0; i<pTabList->nSrc; i++){
90408      Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
90409      assert( (m-1)==toTheLeft );
90410      toTheLeft |= m;
90411    }
90412  }
90413#endif
90414
90415  /* Analyze all of the subexpressions.  Note that exprAnalyze() might
90416  ** add new virtual terms onto the end of the WHERE clause.  We do not
90417  ** want to analyze these virtual terms, so start analyzing at the end
90418  ** and work forward so that the added virtual terms are never processed.
90419  */
90420  exprAnalyzeAll(pTabList, pWC);
90421  if( db->mallocFailed ){
90422    goto whereBeginError;
90423  }
90424
90425  /* Chose the best index to use for each table in the FROM clause.
90426  **
90427  ** This loop fills in the following fields:
90428  **
90429  **   pWInfo->a[].pIdx      The index to use for this level of the loop.
90430  **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
90431  **   pWInfo->a[].nEq       The number of == and IN constraints
90432  **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
90433  **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
90434  **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
90435  **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
90436  **
90437  ** This loop also figures out the nesting order of tables in the FROM
90438  ** clause.
90439  */
90440  notReady = ~(Bitmask)0;
90441  pTabItem = pTabList->a;
90442  pLevel = pWInfo->a;
90443  andFlags = ~0;
90444  WHERETRACE(("*** Optimizer Start ***\n"));
90445  for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
90446    WhereCost bestPlan;         /* Most efficient plan seen so far */
90447    Index *pIdx;                /* Index for FROM table at pTabItem */
90448    int j;                      /* For looping over FROM tables */
90449    int bestJ = -1;             /* The value of j */
90450    Bitmask m;                  /* Bitmask value for j or bestJ */
90451    int isOptimal;              /* Iterator for optimal/non-optimal search */
90452
90453    memset(&bestPlan, 0, sizeof(bestPlan));
90454    bestPlan.rCost = SQLITE_BIG_DBL;
90455
90456    /* Loop through the remaining entries in the FROM clause to find the
90457    ** next nested loop. The FROM clause entries may be iterated through
90458    ** either once or twice.
90459    **
90460    ** The first iteration, which is always performed, searches for the
90461    ** FROM clause entry that permits the lowest-cost, "optimal" scan. In
90462    ** this context an optimal scan is one that uses the same strategy
90463    ** for the given FROM clause entry as would be selected if the entry
90464    ** were used as the innermost nested loop.  In other words, a table
90465    ** is chosen such that the cost of running that table cannot be reduced
90466    ** by waiting for other tables to run first.
90467    **
90468    ** The second iteration is only performed if no optimal scan strategies
90469    ** were found by the first. This iteration is used to search for the
90470    ** lowest cost scan overall.
90471    **
90472    ** Previous versions of SQLite performed only the second iteration -
90473    ** the next outermost loop was always that with the lowest overall
90474    ** cost. However, this meant that SQLite could select the wrong plan
90475    ** for scripts such as the following:
90476    **
90477    **   CREATE TABLE t1(a, b);
90478    **   CREATE TABLE t2(c, d);
90479    **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
90480    **
90481    ** The best strategy is to iterate through table t1 first. However it
90482    ** is not possible to determine this with a simple greedy algorithm.
90483    ** However, since the cost of a linear scan through table t2 is the same
90484    ** as the cost of a linear scan through table t1, a simple greedy
90485    ** algorithm may choose to use t2 for the outer loop, which is a much
90486    ** costlier approach.
90487    */
90488    for(isOptimal=1; isOptimal>=0 && bestJ<0; isOptimal--){
90489      Bitmask mask = (isOptimal ? 0 : notReady);
90490      assert( (nTabList-iFrom)>1 || isOptimal );
90491      for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
90492        int doNotReorder;    /* True if this table should not be reordered */
90493        WhereCost sCost;     /* Cost information from best[Virtual]Index() */
90494        ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
90495
90496        doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
90497        if( j!=iFrom && doNotReorder ) break;
90498        m = getMask(pMaskSet, pTabItem->iCursor);
90499        if( (m & notReady)==0 ){
90500          if( j==iFrom ) iFrom++;
90501          continue;
90502        }
90503        pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
90504
90505        assert( pTabItem->pTab );
90506#ifndef SQLITE_OMIT_VIRTUALTABLE
90507        if( IsVirtual(pTabItem->pTab) ){
90508          sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
90509          bestVirtualIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost, pp);
90510        }else
90511#endif
90512        {
90513          bestBtreeIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost);
90514        }
90515        assert( isOptimal || (sCost.used&notReady)==0 );
90516
90517        if( (sCost.used&notReady)==0
90518         && (j==iFrom || sCost.rCost<bestPlan.rCost)
90519        ){
90520          bestPlan = sCost;
90521          bestJ = j;
90522        }
90523        if( doNotReorder ) break;
90524      }
90525    }
90526    assert( bestJ>=0 );
90527    assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
90528    WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
90529           pLevel-pWInfo->a));
90530    if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
90531      *ppOrderBy = 0;
90532    }
90533    andFlags &= bestPlan.plan.wsFlags;
90534    pLevel->plan = bestPlan.plan;
90535    if( bestPlan.plan.wsFlags & WHERE_INDEXED ){
90536      pLevel->iIdxCur = pParse->nTab++;
90537    }else{
90538      pLevel->iIdxCur = -1;
90539    }
90540    notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
90541    pLevel->iFrom = (u8)bestJ;
90542
90543    /* Check that if the table scanned by this loop iteration had an
90544    ** INDEXED BY clause attached to it, that the named index is being
90545    ** used for the scan. If not, then query compilation has failed.
90546    ** Return an error.
90547    */
90548    pIdx = pTabList->a[bestJ].pIndex;
90549    if( pIdx ){
90550      if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
90551        sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
90552        goto whereBeginError;
90553      }else{
90554        /* If an INDEXED BY clause is used, the bestIndex() function is
90555        ** guaranteed to find the index specified in the INDEXED BY clause
90556        ** if it find an index at all. */
90557        assert( bestPlan.plan.u.pIdx==pIdx );
90558      }
90559    }
90560  }
90561  WHERETRACE(("*** Optimizer Finished ***\n"));
90562  if( pParse->nErr || db->mallocFailed ){
90563    goto whereBeginError;
90564  }
90565
90566  /* If the total query only selects a single row, then the ORDER BY
90567  ** clause is irrelevant.
90568  */
90569  if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
90570    *ppOrderBy = 0;
90571  }
90572
90573  /* If the caller is an UPDATE or DELETE statement that is requesting
90574  ** to use a one-pass algorithm, determine if this is appropriate.
90575  ** The one-pass algorithm only works if the WHERE clause constraints
90576  ** the statement to update a single row.
90577  */
90578  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
90579  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
90580    pWInfo->okOnePass = 1;
90581    pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
90582  }
90583
90584  /* Open all tables in the pTabList and any indices selected for
90585  ** searching those tables.
90586  */
90587  sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
90588  for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
90589    Table *pTab;     /* Table to open */
90590    int iDb;         /* Index of database containing table/index */
90591
90592#ifndef SQLITE_OMIT_EXPLAIN
90593    if( pParse->explain==2 ){
90594      char *zMsg;
90595      struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
90596      zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
90597      if( pItem->zAlias ){
90598        zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
90599      }
90600      if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90601        zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
90602           zMsg, pLevel->plan.u.pIdx->zName);
90603      }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
90604        zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
90605      }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
90606        zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
90607      }
90608#ifndef SQLITE_OMIT_VIRTUALTABLE
90609      else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
90610        sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
90611        zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
90612                    pVtabIdx->idxNum, pVtabIdx->idxStr);
90613      }
90614#endif
90615      if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
90616        zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
90617      }
90618      sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
90619    }
90620#endif /* SQLITE_OMIT_EXPLAIN */
90621    pTabItem = &pTabList->a[pLevel->iFrom];
90622    pTab = pTabItem->pTab;
90623    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
90624    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
90625#ifndef SQLITE_OMIT_VIRTUALTABLE
90626    if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
90627      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
90628      int iCur = pTabItem->iCursor;
90629      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
90630    }else
90631#endif
90632    if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
90633         && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
90634      int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
90635      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
90636      if( !pWInfo->okOnePass && pTab->nCol<BMS ){
90637        Bitmask b = pTabItem->colUsed;
90638        int n = 0;
90639        for(; b; b=b>>1, n++){}
90640        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
90641                            SQLITE_INT_TO_PTR(n), P4_INT32);
90642        assert( n<=pTab->nCol );
90643      }
90644    }else{
90645      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
90646    }
90647    pLevel->iTabCur = pTabItem->iCursor;
90648    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90649      Index *pIx = pLevel->plan.u.pIdx;
90650      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
90651      int iIdxCur = pLevel->iIdxCur;
90652      assert( pIx->pSchema==pTab->pSchema );
90653      assert( iIdxCur>=0 );
90654      sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
90655                        (char*)pKey, P4_KEYINFO_HANDOFF);
90656      VdbeComment((v, "%s", pIx->zName));
90657    }
90658    sqlite3CodeVerifySchema(pParse, iDb);
90659  }
90660  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
90661
90662  /* Generate the code to do the search.  Each iteration of the for
90663  ** loop below generates code for a single nested loop of the VM
90664  ** program.
90665  */
90666  notReady = ~(Bitmask)0;
90667  for(i=0; i<nTabList; i++){
90668    notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
90669    pWInfo->iContinue = pWInfo->a[i].addrCont;
90670  }
90671
90672#ifdef SQLITE_TEST  /* For testing and debugging use only */
90673  /* Record in the query plan information about the current table
90674  ** and the index used to access it (if any).  If the table itself
90675  ** is not used, its name is just '{}'.  If no index is used
90676  ** the index is listed as "{}".  If the primary key is used the
90677  ** index name is '*'.
90678  */
90679  for(i=0; i<nTabList; i++){
90680    char *z;
90681    int n;
90682    pLevel = &pWInfo->a[i];
90683    pTabItem = &pTabList->a[pLevel->iFrom];
90684    z = pTabItem->zAlias;
90685    if( z==0 ) z = pTabItem->pTab->zName;
90686    n = sqlite3Strlen30(z);
90687    if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
90688      if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
90689        memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
90690        nQPlan += 2;
90691      }else{
90692        memcpy(&sqlite3_query_plan[nQPlan], z, n);
90693        nQPlan += n;
90694      }
90695      sqlite3_query_plan[nQPlan++] = ' ';
90696    }
90697    testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
90698    testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
90699    if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
90700      memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
90701      nQPlan += 2;
90702    }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90703      n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
90704      if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
90705        memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
90706        nQPlan += n;
90707        sqlite3_query_plan[nQPlan++] = ' ';
90708      }
90709    }else{
90710      memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
90711      nQPlan += 3;
90712    }
90713  }
90714  while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
90715    sqlite3_query_plan[--nQPlan] = 0;
90716  }
90717  sqlite3_query_plan[nQPlan] = 0;
90718  nQPlan = 0;
90719#endif /* SQLITE_TEST // Testing and debugging use only */
90720
90721  /* Record the continuation address in the WhereInfo structure.  Then
90722  ** clean up and return.
90723  */
90724  return pWInfo;
90725
90726  /* Jump here if malloc fails */
90727whereBeginError:
90728  whereInfoFree(db, pWInfo);
90729  return 0;
90730}
90731
90732/*
90733** Generate the end of the WHERE loop.  See comments on
90734** sqlite3WhereBegin() for additional information.
90735*/
90736SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
90737  Parse *pParse = pWInfo->pParse;
90738  Vdbe *v = pParse->pVdbe;
90739  int i;
90740  WhereLevel *pLevel;
90741  SrcList *pTabList = pWInfo->pTabList;
90742  sqlite3 *db = pParse->db;
90743
90744  /* Generate loop termination code.
90745  */
90746  sqlite3ExprCacheClear(pParse);
90747  for(i=pWInfo->nLevel-1; i>=0; i--){
90748    pLevel = &pWInfo->a[i];
90749    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
90750    if( pLevel->op!=OP_Noop ){
90751      sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
90752      sqlite3VdbeChangeP5(v, pLevel->p5);
90753    }
90754    if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
90755      struct InLoop *pIn;
90756      int j;
90757      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
90758      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
90759        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
90760        sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
90761        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
90762      }
90763      sqlite3DbFree(db, pLevel->u.in.aInLoop);
90764    }
90765    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
90766    if( pLevel->iLeftJoin ){
90767      int addr;
90768      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
90769      assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
90770           || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
90771      if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
90772        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
90773      }
90774      if( pLevel->iIdxCur>=0 ){
90775        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
90776      }
90777      if( pLevel->op==OP_Return ){
90778        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
90779      }else{
90780        sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
90781      }
90782      sqlite3VdbeJumpHere(v, addr);
90783    }
90784  }
90785
90786  /* The "break" point is here, just past the end of the outer loop.
90787  ** Set it.
90788  */
90789  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
90790
90791  /* Close all of the cursors that were opened by sqlite3WhereBegin.
90792  */
90793  assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
90794  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
90795    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
90796    Table *pTab = pTabItem->pTab;
90797    assert( pTab!=0 );
90798    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
90799    if( (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0 ){
90800      if( !pWInfo->okOnePass && (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
90801        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
90802      }
90803      if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90804        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
90805      }
90806    }
90807
90808    /* If this scan uses an index, make code substitutions to read data
90809    ** from the index in preference to the table. Sometimes, this means
90810    ** the table need never be read from. This is a performance boost,
90811    ** as the vdbe level waits until the table is read before actually
90812    ** seeking the table cursor to the record corresponding to the current
90813    ** position in the index.
90814    **
90815    ** Calls to the code generator in between sqlite3WhereBegin and
90816    ** sqlite3WhereEnd will have created code that references the table
90817    ** directly.  This loop scans all that code looking for opcodes
90818    ** that reference the table and converts them into opcodes that
90819    ** reference the index.
90820    */
90821    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
90822      int k, j, last;
90823      VdbeOp *pOp;
90824      Index *pIdx = pLevel->plan.u.pIdx;
90825
90826      assert( pIdx!=0 );
90827      pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
90828      last = sqlite3VdbeCurrentAddr(v);
90829      for(k=pWInfo->iTop; k<last; k++, pOp++){
90830        if( pOp->p1!=pLevel->iTabCur ) continue;
90831        if( pOp->opcode==OP_Column ){
90832          for(j=0; j<pIdx->nColumn; j++){
90833            if( pOp->p2==pIdx->aiColumn[j] ){
90834              pOp->p2 = j;
90835              pOp->p1 = pLevel->iIdxCur;
90836              break;
90837            }
90838          }
90839          assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
90840               || j<pIdx->nColumn );
90841        }else if( pOp->opcode==OP_Rowid ){
90842          pOp->p1 = pLevel->iIdxCur;
90843          pOp->opcode = OP_IdxRowid;
90844        }
90845      }
90846    }
90847  }
90848
90849  /* Final cleanup
90850  */
90851  whereInfoFree(db, pWInfo);
90852  return;
90853}
90854
90855/************** End of where.c ***********************************************/
90856/************** Begin file parse.c *******************************************/
90857/* Driver template for the LEMON parser generator.
90858** The author disclaims copyright to this source code.
90859**
90860** This version of "lempar.c" is modified, slightly, for use by SQLite.
90861** The only modifications are the addition of a couple of NEVER()
90862** macros to disable tests that are needed in the case of a general
90863** LALR(1) grammar but which are always false in the
90864** specific grammar used by SQLite.
90865*/
90866/* First off, code is included that follows the "include" declaration
90867** in the input grammar file. */
90868
90869
90870/*
90871** Disable all error recovery processing in the parser push-down
90872** automaton.
90873*/
90874#define YYNOERRORRECOVERY 1
90875
90876/*
90877** Make yytestcase() the same as testcase()
90878*/
90879#define yytestcase(X) testcase(X)
90880
90881/*
90882** An instance of this structure holds information about the
90883** LIMIT clause of a SELECT statement.
90884*/
90885struct LimitVal {
90886  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
90887  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
90888};
90889
90890/*
90891** An instance of this structure is used to store the LIKE,
90892** GLOB, NOT LIKE, and NOT GLOB operators.
90893*/
90894struct LikeOp {
90895  Token eOperator;  /* "like" or "glob" or "regexp" */
90896  int not;         /* True if the NOT keyword is present */
90897};
90898
90899/*
90900** An instance of the following structure describes the event of a
90901** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
90902** TK_DELETE, or TK_INSTEAD.  If the event is of the form
90903**
90904**      UPDATE ON (a,b,c)
90905**
90906** Then the "b" IdList records the list "a,b,c".
90907*/
90908struct TrigEvent { int a; IdList * b; };
90909
90910/*
90911** An instance of this structure holds the ATTACH key and the key type.
90912*/
90913struct AttachKey { int type;  Token key; };
90914
90915
90916  /* This is a utility routine used to set the ExprSpan.zStart and
90917  ** ExprSpan.zEnd values of pOut so that the span covers the complete
90918  ** range of text beginning with pStart and going to the end of pEnd.
90919  */
90920  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
90921    pOut->zStart = pStart->z;
90922    pOut->zEnd = &pEnd->z[pEnd->n];
90923  }
90924
90925  /* Construct a new Expr object from a single identifier.  Use the
90926  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
90927  ** that created the expression.
90928  */
90929  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
90930    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
90931    pOut->zStart = pValue->z;
90932    pOut->zEnd = &pValue->z[pValue->n];
90933  }
90934
90935  /* This routine constructs a binary expression node out of two ExprSpan
90936  ** objects and uses the result to populate a new ExprSpan object.
90937  */
90938  static void spanBinaryExpr(
90939    ExprSpan *pOut,     /* Write the result here */
90940    Parse *pParse,      /* The parsing context.  Errors accumulate here */
90941    int op,             /* The binary operation */
90942    ExprSpan *pLeft,    /* The left operand */
90943    ExprSpan *pRight    /* The right operand */
90944  ){
90945    pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
90946    pOut->zStart = pLeft->zStart;
90947    pOut->zEnd = pRight->zEnd;
90948  }
90949
90950  /* Construct an expression node for a unary postfix operator
90951  */
90952  static void spanUnaryPostfix(
90953    ExprSpan *pOut,        /* Write the new expression node here */
90954    Parse *pParse,         /* Parsing context to record errors */
90955    int op,                /* The operator */
90956    ExprSpan *pOperand,    /* The operand */
90957    Token *pPostOp         /* The operand token for setting the span */
90958  ){
90959    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
90960    pOut->zStart = pOperand->zStart;
90961    pOut->zEnd = &pPostOp->z[pPostOp->n];
90962  }
90963
90964  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
90965  ** unary TK_ISNULL or TK_NOTNULL expression. */
90966  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
90967    sqlite3 *db = pParse->db;
90968    if( db->mallocFailed==0 && pY->op==TK_NULL ){
90969      pA->op = (u8)op;
90970      sqlite3ExprDelete(db, pA->pRight);
90971      pA->pRight = 0;
90972    }
90973  }
90974
90975  /* Construct an expression node for a unary prefix operator
90976  */
90977  static void spanUnaryPrefix(
90978    ExprSpan *pOut,        /* Write the new expression node here */
90979    Parse *pParse,         /* Parsing context to record errors */
90980    int op,                /* The operator */
90981    ExprSpan *pOperand,    /* The operand */
90982    Token *pPreOp         /* The operand token for setting the span */
90983  ){
90984    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
90985    pOut->zStart = pPreOp->z;
90986    pOut->zEnd = pOperand->zEnd;
90987  }
90988/* Next is all token values, in a form suitable for use by makeheaders.
90989** This section will be null unless lemon is run with the -m switch.
90990*/
90991/*
90992** These constants (all generated automatically by the parser generator)
90993** specify the various kinds of tokens (terminals) that the parser
90994** understands.
90995**
90996** Each symbol here is a terminal symbol in the grammar.
90997*/
90998/* Make sure the INTERFACE macro is defined.
90999*/
91000#ifndef INTERFACE
91001# define INTERFACE 1
91002#endif
91003/* The next thing included is series of defines which control
91004** various aspects of the generated parser.
91005**    YYCODETYPE         is the data type used for storing terminal
91006**                       and nonterminal numbers.  "unsigned char" is
91007**                       used if there are fewer than 250 terminals
91008**                       and nonterminals.  "int" is used otherwise.
91009**    YYNOCODE           is a number of type YYCODETYPE which corresponds
91010**                       to no legal terminal or nonterminal number.  This
91011**                       number is used to fill in empty slots of the hash
91012**                       table.
91013**    YYFALLBACK         If defined, this indicates that one or more tokens
91014**                       have fall-back values which should be used if the
91015**                       original value of the token will not parse.
91016**    YYACTIONTYPE       is the data type used for storing terminal
91017**                       and nonterminal numbers.  "unsigned char" is
91018**                       used if there are fewer than 250 rules and
91019**                       states combined.  "int" is used otherwise.
91020**    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
91021**                       directly to the parser from the tokenizer.
91022**    YYMINORTYPE        is the data type used for all minor tokens.
91023**                       This is typically a union of many types, one of
91024**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
91025**                       for base tokens is called "yy0".
91026**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
91027**                       zero the stack is dynamically sized using realloc()
91028**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
91029**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
91030**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
91031**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
91032**    YYNSTATE           the combined number of states.
91033**    YYNRULE            the number of rules in the grammar
91034**    YYERRORSYMBOL      is the code number of the error symbol.  If not
91035**                       defined, then do no error processing.
91036*/
91037#define YYCODETYPE unsigned char
91038#define YYNOCODE 254
91039#define YYACTIONTYPE unsigned short int
91040#define YYWILDCARD 67
91041#define sqlite3ParserTOKENTYPE Token
91042typedef union {
91043  int yyinit;
91044  sqlite3ParserTOKENTYPE yy0;
91045  Select* yy3;
91046  ExprList* yy14;
91047  SrcList* yy65;
91048  struct LikeOp yy96;
91049  Expr* yy132;
91050  u8 yy186;
91051  int yy328;
91052  ExprSpan yy346;
91053  struct TrigEvent yy378;
91054  IdList* yy408;
91055  struct {int value; int mask;} yy429;
91056  TriggerStep* yy473;
91057  struct LimitVal yy476;
91058} YYMINORTYPE;
91059#ifndef YYSTACKDEPTH
91060#define YYSTACKDEPTH 100
91061#endif
91062#define sqlite3ParserARG_SDECL Parse *pParse;
91063#define sqlite3ParserARG_PDECL ,Parse *pParse
91064#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
91065#define sqlite3ParserARG_STORE yypParser->pParse = pParse
91066#define YYNSTATE 631
91067#define YYNRULE 330
91068#define YYFALLBACK 1
91069#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
91070#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
91071#define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
91072
91073/* The yyzerominor constant is used to initialize instances of
91074** YYMINORTYPE objects to zero. */
91075static const YYMINORTYPE yyzerominor = { 0 };
91076
91077/* Define the yytestcase() macro to be a no-op if is not already defined
91078** otherwise.
91079**
91080** Applications can choose to define yytestcase() in the %include section
91081** to a macro that can assist in verifying code coverage.  For production
91082** code the yytestcase() macro should be turned off.  But it is useful
91083** for testing.
91084*/
91085#ifndef yytestcase
91086# define yytestcase(X)
91087#endif
91088
91089
91090/* Next are the tables used to determine what action to take based on the
91091** current state and lookahead token.  These tables are used to implement
91092** functions that take a state number and lookahead value and return an
91093** action integer.
91094**
91095** Suppose the action integer is N.  Then the action is determined as
91096** follows
91097**
91098**   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
91099**                                      token onto the stack and goto state N.
91100**
91101**   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
91102**
91103**   N == YYNSTATE+YYNRULE              A syntax error has occurred.
91104**
91105**   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
91106**
91107**   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
91108**                                      slots in the yy_action[] table.
91109**
91110** The action table is constructed as a single large table named yy_action[].
91111** Given state S and lookahead X, the action is computed as
91112**
91113**      yy_action[ yy_shift_ofst[S] + X ]
91114**
91115** If the index value yy_shift_ofst[S]+X is out of range or if the value
91116** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
91117** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
91118** and that yy_default[S] should be used instead.
91119**
91120** The formula above is for computing the action when the lookahead is
91121** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
91122** a reduce action) then the yy_reduce_ofst[] array is used in place of
91123** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
91124** YY_SHIFT_USE_DFLT.
91125**
91126** The following are the tables generated in this section:
91127**
91128**  yy_action[]        A single table containing all actions.
91129**  yy_lookahead[]     A table containing the lookahead for each entry in
91130**                     yy_action.  Used to detect hash collisions.
91131**  yy_shift_ofst[]    For each state, the offset into yy_action for
91132**                     shifting terminals.
91133**  yy_reduce_ofst[]   For each state, the offset into yy_action for
91134**                     shifting non-terminals after a reduce.
91135**  yy_default[]       Default action for each state.
91136*/
91137#define YY_ACTTAB_COUNT (1543)
91138static const YYACTIONTYPE yy_action[] = {
91139 /*     0 */   313,   49,  556,   46,  147,  172,  628,  598,   55,   55,
91140 /*    10 */    55,   55,  302,   53,   53,   53,   53,   52,   52,   51,
91141 /*    20 */    51,   51,   50,  238,  603,   66,  624,  623,  604,  598,
91142 /*    30 */   591,  585,   48,   53,   53,   53,   53,   52,   52,   51,
91143 /*    40 */    51,   51,   50,  238,   51,   51,   51,   50,  238,   56,
91144 /*    50 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
91145 /*    60 */    55,   55,  609,   53,   53,   53,   53,   52,   52,   51,
91146 /*    70 */    51,   51,   50,  238,  313,  598,  672,  330,  411,  217,
91147 /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
91148 /*    90 */    50,  238,  330,  414,  621,  620,  166,  598,  673,  382,
91149 /*   100 */   379,  378,  602,   73,  591,  585,  307,  424,  166,   58,
91150 /*   110 */   377,  382,  379,  378,  516,  515,  624,  623,  254,  200,
91151 /*   120 */   199,  198,  377,   56,   57,   47,  583,  582,  584,  584,
91152 /*   130 */    54,   54,   55,   55,   55,   55,  581,   53,   53,   53,
91153 /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  270,
91154 /*   150 */   226,  422,  283,  133,  177,  139,  284,  385,  279,  384,
91155 /*   160 */   169,  197,  251,  282,  253,  226,  411,  275,  440,  167,
91156 /*   170 */   139,  284,  385,  279,  384,  169,  571,  236,  591,  585,
91157 /*   180 */   240,  414,  275,  622,  621,  620,  674,  437,  441,  442,
91158 /*   190 */   602,   88,  352,  266,  439,  268,  438,   56,   57,   47,
91159 /*   200 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
91160 /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
91161 /*   220 */    50,  238,  313,  471,   52,   52,   51,   51,   51,   50,
91162 /*   230 */   238,  234,  166,  491,  567,  382,  379,  378,    1,  440,
91163 /*   240 */   252,  176,  624,  623,  608,   67,  377,  513,  622,  443,
91164 /*   250 */   237,  577,  591,  585,  622,  172,  466,  598,  554,  441,
91165 /*   260 */   340,  409,  526,  580,  580,  349,  596,  553,  194,  482,
91166 /*   270 */   175,   56,   57,   47,  583,  582,  584,  584,   54,   54,
91167 /*   280 */    55,   55,   55,   55,  562,   53,   53,   53,   53,   52,
91168 /*   290 */    52,   51,   51,   51,   50,  238,  313,  594,  594,  594,
91169 /*   300 */   561,  578,  469,   65,  259,  351,  258,  411,  624,  623,
91170 /*   310 */   621,  620,  332,  576,  575,  240,  560,  568,  520,  411,
91171 /*   320 */   341,  237,  414,  624,  623,  598,  591,  585,  542,  519,
91172 /*   330 */   171,  602,   95,   68,  414,  624,  623,  624,  623,   38,
91173 /*   340 */   877,  506,  507,  602,   88,   56,   57,   47,  583,  582,
91174 /*   350 */   584,  584,   54,   54,   55,   55,   55,   55,  532,   53,
91175 /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
91176 /*   370 */   313,  411,  579,  398,  531,  237,  621,  620,  388,  625,
91177 /*   380 */   500,  206,  167,  396,  233,  312,  414,  387,  569,  492,
91178 /*   390 */   216,  621,  620,  566,  622,  602,   74,  533,  210,  491,
91179 /*   400 */   591,  585,  548,  621,  620,  621,  620,  300,  598,  466,
91180 /*   410 */   481,   67,  603,   35,  622,  601,  604,  547,    6,   56,
91181 /*   420 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
91182 /*   430 */    55,   55,  601,   53,   53,   53,   53,   52,   52,   51,
91183 /*   440 */    51,   51,   50,  238,  313,  411,  184,  409,  528,  580,
91184 /*   450 */   580,  551,  962,  186,  419,    2,  353,  259,  351,  258,
91185 /*   460 */   414,  409,  411,  580,  580,   44,  411,  544,  240,  602,
91186 /*   470 */    94,  190,    7,   62,  591,  585,  598,  414,  350,  607,
91187 /*   480 */   493,  414,  409,  317,  580,  580,  602,   95,  496,  565,
91188 /*   490 */   602,   80,  203,   56,   57,   47,  583,  582,  584,  584,
91189 /*   500 */    54,   54,   55,   55,   55,   55,  535,   53,   53,   53,
91190 /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  202,
91191 /*   520 */   564,  293,  511,   49,  562,   46,  147,  411,  394,  183,
91192 /*   530 */   563,  549,  505,  549,  174,  409,  322,  580,  580,   39,
91193 /*   540 */   561,   37,  414,  624,  623,  192,  473,  383,  591,  585,
91194 /*   550 */   474,  602,   80,  601,  504,  544,  560,  364,  402,  210,
91195 /*   560 */   421,  952,  361,  952,  365,  201,  144,   56,   57,   47,
91196 /*   570 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
91197 /*   580 */   559,   53,   53,   53,   53,   52,   52,   51,   51,   51,
91198 /*   590 */    50,  238,  313,  601,  232,  264,  272,  321,  374,  484,
91199 /*   600 */   510,  146,  342,  146,  328,  425,  485,  407,  576,  575,
91200 /*   610 */   622,  621,  620,   49,  168,   46,  147,  353,  546,  491,
91201 /*   620 */   204,  240,  591,  585,  421,  951,  549,  951,  549,  168,
91202 /*   630 */   429,   67,  390,  343,  622,  434,  307,  423,  338,  360,
91203 /*   640 */   391,   56,   57,   47,  583,  582,  584,  584,   54,   54,
91204 /*   650 */    55,   55,   55,   55,  601,   53,   53,   53,   53,   52,
91205 /*   660 */    52,   51,   51,   51,   50,  238,  313,   34,  318,  425,
91206 /*   670 */   237,   21,  359,  273,  411,  167,  411,  276,  411,  540,
91207 /*   680 */   411,  422,   13,  318,  619,  618,  617,  622,  275,  414,
91208 /*   690 */   336,  414,  622,  414,  622,  414,  591,  585,  602,   69,
91209 /*   700 */   602,   97,  602,  100,  602,   98,  631,  629,  334,  475,
91210 /*   710 */   475,  367,  319,  148,  327,   56,   57,   47,  583,  582,
91211 /*   720 */   584,  584,   54,   54,   55,   55,   55,   55,  411,   53,
91212 /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
91213 /*   740 */   313,  411,  331,  414,  411,   49,  276,   46,  147,  569,
91214 /*   750 */   406,  216,  602,  106,  573,  573,  414,  354,  524,  414,
91215 /*   760 */   411,  622,  411,  224,    4,  602,  104,  605,  602,  108,
91216 /*   770 */   591,  585,  622,   20,  375,  414,  167,  414,  215,  144,
91217 /*   780 */   470,  239,  167,  225,  602,  109,  602,  134,   18,   56,
91218 /*   790 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
91219 /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
91220 /*   810 */    51,   51,   50,  238,  313,  411,  276,  414,   12,  459,
91221 /*   820 */   276,  171,  411,   16,  223,  189,  602,  135,  354,  170,
91222 /*   830 */   414,  622,  630,    2,  411,  622,  540,  414,  143,  602,
91223 /*   840 */    61,  359,  132,  622,  591,  585,  602,  105,  458,  414,
91224 /*   850 */    23,  622,  446,  326,   23,  538,  622,  325,  602,  103,
91225 /*   860 */   427,  530,  309,   56,   57,   47,  583,  582,  584,  584,
91226 /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
91227 /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
91228 /*   890 */   264,  414,  411,  276,  359,  219,  157,  214,  357,  366,
91229 /*   900 */   602,   96,  522,  521,  414,  622,  358,  414,  622,  622,
91230 /*   910 */   411,  613,  612,  602,  102,  142,  602,   77,  591,  585,
91231 /*   920 */   529,  540,  231,  426,  308,  414,  622,  622,  468,  521,
91232 /*   930 */   324,  601,  257,  263,  602,   99,  622,   56,   45,   47,
91233 /*   940 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
91234 /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
91235 /*   960 */    50,  238,  313,  264,  264,  414,  411,  213,  209,  544,
91236 /*   970 */   544,  207,  611,   28,  602,  138,   50,  238,  622,  622,
91237 /*   980 */   381,  414,  503,  140,  323,  222,  274,  622,  590,  589,
91238 /*   990 */   602,  137,  591,  585,  629,  334,  606,   30,  622,  571,
91239 /*  1000 */   236,  601,  601,  130,  496,  601,  453,  451,  288,  286,
91240 /*  1010 */   587,  586,   57,   47,  583,  582,  584,  584,   54,   54,
91241 /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
91242 /*  1030 */    52,   51,   51,   51,   50,  238,  313,  588,  411,  414,
91243 /*  1040 */   411,  264,  410,  129,  595,  400,   27,  376,  602,  136,
91244 /*  1050 */   128,  165,  479,  414,  282,  414,  622,  622,  411,  622,
91245 /*  1060 */   622,  411,  602,   76,  602,   93,  591,  585,  188,  372,
91246 /*  1070 */   368,  125,  476,  414,  261,  160,  414,  171,  124,  472,
91247 /*  1080 */   123,   15,  602,   92,  450,  602,   75,   47,  583,  582,
91248 /*  1090 */   584,  584,   54,   54,   55,   55,   55,   55,  464,   53,
91249 /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
91250 /*  1110 */    43,  405,  264,    3,  558,  264,  545,  415,  623,  159,
91251 /*  1120 */   541,  158,  539,  278,   25,  461,  121,  622,  408,  622,
91252 /*  1130 */   622,  622,   24,   43,  405,  622,    3,  622,  622,  120,
91253 /*  1140 */   415,  623,   11,  456,  411,  156,  452,  403,  509,  277,
91254 /*  1150 */   118,  408,  489,  113,  205,  449,  271,  567,  221,  414,
91255 /*  1160 */   269,  267,  155,  622,  622,  111,  411,  622,  602,   95,
91256 /*  1170 */   403,  622,  411,  110,   10,  622,  622,   40,   41,  534,
91257 /*  1180 */   567,  414,   64,  264,   42,  413,  412,  414,  601,  596,
91258 /*  1190 */   602,   91,  445,  436,  150,  435,  602,   90,  622,  265,
91259 /*  1200 */    40,   41,  337,  242,  411,  191,  333,   42,  413,  412,
91260 /*  1210 */   398,  420,  596,  316,  622,  399,  260,  107,  230,  414,
91261 /*  1220 */   594,  594,  594,  593,  592,   14,  220,  411,  602,  101,
91262 /*  1230 */   240,  622,   43,  405,  362,    3,  149,  315,  626,  415,
91263 /*  1240 */   623,  127,  414,  594,  594,  594,  593,  592,   14,  622,
91264 /*  1250 */   408,  602,   89,  411,  181,   33,  405,  463,    3,  411,
91265 /*  1260 */   264,  462,  415,  623,  616,  615,  614,  355,  414,  403,
91266 /*  1270 */   417,  416,  622,  408,  414,  622,  622,  602,   87,  567,
91267 /*  1280 */   418,  627,  622,  602,   86,    8,  241,  180,  126,  255,
91268 /*  1290 */   600,  178,  403,  240,  208,  455,  395,  294,  444,   40,
91269 /*  1300 */    41,  297,  567,  248,  622,  296,   42,  413,  412,  247,
91270 /*  1310 */   622,  596,  244,  622,   30,   60,   31,  243,  430,  624,
91271 /*  1320 */   623,  292,   40,   41,  622,  295,  145,  622,  601,   42,
91272 /*  1330 */   413,  412,  622,  622,  596,  393,  622,  397,  599,   59,
91273 /*  1340 */   235,  622,  594,  594,  594,  593,  592,   14,  218,  291,
91274 /*  1350 */   622,   36,  344,  305,  304,  303,  179,  301,  411,  567,
91275 /*  1360 */   454,  557,  173,  185,  622,  594,  594,  594,  593,  592,
91276 /*  1370 */    14,  411,   29,  414,  151,  289,  246,  523,  411,  196,
91277 /*  1380 */   195,  335,  602,   85,  411,  245,  414,  526,  392,  543,
91278 /*  1390 */   411,  596,  287,  414,  285,  602,   72,  537,  153,  414,
91279 /*  1400 */   466,  411,  602,   71,  154,  414,  411,  152,  602,   84,
91280 /*  1410 */   386,  536,  329,  411,  602,   83,  414,  518,  280,  411,
91281 /*  1420 */   513,  414,  594,  594,  594,  602,   82,  517,  414,  311,
91282 /*  1430 */   602,   81,  411,  514,  414,  512,  131,  602,   70,  229,
91283 /*  1440 */   228,  227,  494,  602,   17,  411,  488,  414,  259,  346,
91284 /*  1450 */   249,  389,  487,  486,  314,  164,  602,   79,  310,  240,
91285 /*  1460 */   414,  373,  480,  163,  262,  371,  414,  162,  369,  602,
91286 /*  1470 */    78,  212,  478,   26,  477,  602,    9,  161,  467,  363,
91287 /*  1480 */   141,  122,  339,  187,  119,  457,  348,  117,  347,  116,
91288 /*  1490 */   115,  114,  448,  112,  182,  320,   22,  433,   19,  432,
91289 /*  1500 */   431,   63,  428,  610,  193,  298,  597,  574,  572,  404,
91290 /*  1510 */   555,  552,  290,  281,  510,  499,  498,  497,  495,  380,
91291 /*  1520 */   356,  460,  256,  250,  345,  447,  306,    5,  570,  550,
91292 /*  1530 */   299,  211,  370,  401,  550,  508,  502,  501,  490,  527,
91293 /*  1540 */   525,  483,  238,
91294};
91295static const YYCODETYPE yy_lookahead[] = {
91296 /*     0 */    19,  222,  223,  224,  225,   24,    1,   26,   77,   78,
91297 /*    10 */    79,   80,   15,   82,   83,   84,   85,   86,   87,   88,
91298 /*    20 */    89,   90,   91,   92,  113,   22,   26,   27,  117,   26,
91299 /*    30 */    49,   50,   81,   82,   83,   84,   85,   86,   87,   88,
91300 /*    40 */    89,   90,   91,   92,   88,   89,   90,   91,   92,   68,
91301 /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
91302 /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
91303 /*    70 */    89,   90,   91,   92,   19,   94,  118,   19,  150,   22,
91304 /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91305 /*    90 */    91,   92,   19,  165,   94,   95,   96,   94,  118,   99,
91306 /*   100 */   100,  101,  174,  175,   49,   50,   22,   23,   96,   54,
91307 /*   110 */   110,   99,  100,  101,    7,    8,   26,   27,   16,  105,
91308 /*   120 */   106,  107,  110,   68,   69,   70,   71,   72,   73,   74,
91309 /*   130 */    75,   76,   77,   78,   79,   80,  113,   82,   83,   84,
91310 /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   16,
91311 /*   150 */    92,   67,   98,   24,   96,   97,   98,   99,  100,  101,
91312 /*   160 */   102,   25,   60,  109,   62,   92,  150,  109,  150,   25,
91313 /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
91314 /*   180 */   116,  165,  109,  165,   94,   95,  118,   97,  170,  171,
91315 /*   190 */   174,  175,  128,   60,  104,   62,  106,   68,   69,   70,
91316 /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
91317 /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91318 /*   220 */    91,   92,   19,   21,   86,   87,   88,   89,   90,   91,
91319 /*   230 */    92,  215,   96,  150,   66,   99,  100,  101,   22,  150,
91320 /*   240 */   138,  118,   26,   27,  161,  162,  110,  103,  165,  231,
91321 /*   250 */   232,   23,   49,   50,  165,   24,   57,   26,   32,  170,
91322 /*   260 */   171,  112,   94,  114,  115,   63,   98,   41,  185,  186,
91323 /*   270 */   118,   68,   69,   70,   71,   72,   73,   74,   75,   76,
91324 /*   280 */    77,   78,   79,   80,   12,   82,   83,   84,   85,   86,
91325 /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
91326 /*   300 */    28,   23,  100,   25,  105,  106,  107,  150,   26,   27,
91327 /*   310 */    94,   95,  169,  170,  171,  116,   44,   23,   46,  150,
91328 /*   320 */   231,  232,  165,   26,   27,   94,   49,   50,   23,   57,
91329 /*   330 */    25,  174,  175,   22,  165,   26,   27,   26,   27,  136,
91330 /*   340 */   138,   97,   98,  174,  175,   68,   69,   70,   71,   72,
91331 /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
91332 /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
91333 /*   370 */    19,  150,   23,  216,   23,  232,   94,   95,  221,  150,
91334 /*   380 */    23,  160,   25,  214,  215,  163,  165,   88,  166,  167,
91335 /*   390 */   168,   94,   95,   23,  165,  174,  175,   88,  160,  150,
91336 /*   400 */    49,   50,  120,   94,   95,   94,   95,  158,   26,   57,
91337 /*   410 */   161,  162,  113,  136,  165,  194,  117,  120,   22,   68,
91338 /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
91339 /*   430 */    79,   80,  194,   82,   83,   84,   85,   86,   87,   88,
91340 /*   440 */    89,   90,   91,   92,   19,  150,   23,  112,   23,  114,
91341 /*   450 */   115,   25,  142,  143,  144,  145,  218,  105,  106,  107,
91342 /*   460 */   165,  112,  150,  114,  115,   22,  150,  166,  116,  174,
91343 /*   470 */   175,   22,   76,  235,   49,   50,   94,  165,  240,  172,
91344 /*   480 */   173,  165,  112,  155,  114,  115,  174,  175,  181,   11,
91345 /*   490 */   174,  175,   22,   68,   69,   70,   71,   72,   73,   74,
91346 /*   500 */    75,   76,   77,   78,   79,   80,  205,   82,   83,   84,
91347 /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  160,
91348 /*   520 */    23,  226,   23,  222,   12,  224,  225,  150,  216,   23,
91349 /*   530 */    23,   25,   36,   25,   25,  112,  220,  114,  115,  135,
91350 /*   540 */    28,  137,  165,   26,   27,  119,   30,   51,   49,   50,
91351 /*   550 */    34,  174,  175,  194,   58,  166,   44,  229,   46,  160,
91352 /*   560 */    22,   23,  234,   25,   48,  206,  207,   68,   69,   70,
91353 /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
91354 /*   580 */    23,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91355 /*   590 */    91,   92,   19,  194,  205,  150,   23,  220,   19,  181,
91356 /*   600 */   182,   95,   97,   95,  108,   67,  188,  169,  170,  171,
91357 /*   610 */   165,   94,   95,  222,   50,  224,  225,  218,  120,  150,
91358 /*   620 */   160,  116,   49,   50,   22,   23,  120,   25,  120,   50,
91359 /*   630 */   161,  162,   19,  128,  165,  244,   22,   23,  193,  240,
91360 /*   640 */    27,   68,   69,   70,   71,   72,   73,   74,   75,   76,
91361 /*   650 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
91362 /*   660 */    87,   88,   89,   90,   91,   92,   19,   25,  104,   67,
91363 /*   670 */   232,   24,  150,   23,  150,   25,  150,  150,  150,  150,
91364 /*   680 */   150,   67,   25,  104,    7,    8,    9,  165,  109,  165,
91365 /*   690 */   245,  165,  165,  165,  165,  165,   49,   50,  174,  175,
91366 /*   700 */   174,  175,  174,  175,  174,  175,    0,    1,    2,  105,
91367 /*   710 */   106,  107,  248,  249,  187,   68,   69,   70,   71,   72,
91368 /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
91369 /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
91370 /*   740 */    19,  150,  213,  165,  150,  222,  150,  224,  225,  166,
91371 /*   750 */   167,  168,  174,  175,  129,  130,  165,  150,  165,  165,
91372 /*   760 */   150,  165,  150,  241,   35,  174,  175,  174,  174,  175,
91373 /*   770 */    49,   50,  165,   52,   23,  165,   25,  165,  206,  207,
91374 /*   780 */    23,  197,   25,  187,  174,  175,  174,  175,  204,   68,
91375 /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
91376 /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
91377 /*   810 */    89,   90,   91,   92,   19,  150,  150,  165,   35,   23,
91378 /*   820 */   150,   25,  150,   22,  217,   24,  174,  175,  150,   35,
91379 /*   830 */   165,  165,  144,  145,  150,  165,  150,  165,  118,  174,
91380 /*   840 */   175,  150,   22,  165,   49,   50,  174,  175,   23,  165,
91381 /*   850 */    25,  165,   23,  187,   25,   27,  165,  187,  174,  175,
91382 /*   860 */    23,   23,   25,   68,   69,   70,   71,   72,   73,   74,
91383 /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
91384 /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
91385 /*   890 */   150,  165,  150,  150,  150,  217,   25,  160,   19,  213,
91386 /*   900 */   174,  175,  190,  191,  165,  165,   27,  165,  165,  165,
91387 /*   910 */   150,  150,  150,  174,  175,   39,  174,  175,   49,   50,
91388 /*   920 */    23,  150,   52,  250,  251,  165,  165,  165,  190,  191,
91389 /*   930 */   187,  194,  241,  193,  174,  175,  165,   68,   69,   70,
91390 /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
91391 /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91392 /*   960 */    91,   92,   19,  150,  150,  165,  150,  160,  160,  166,
91393 /*   970 */   166,  160,  150,   22,  174,  175,   91,   92,  165,  165,
91394 /*   980 */    52,  165,   29,  150,  213,  241,   23,  165,   49,   50,
91395 /*   990 */   174,  175,   49,   50,    1,    2,  173,  126,  165,   86,
91396 /*  1000 */    87,  194,  194,   22,  181,  194,  193,  193,  205,  205,
91397 /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
91398 /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
91399 /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
91400 /*  1040 */   150,  150,  150,   22,  150,  150,   22,   52,  174,  175,
91401 /*  1050 */    22,  102,   20,  165,  109,  165,  165,  165,  150,  165,
91402 /*  1060 */   165,  150,  174,  175,  174,  175,   49,   50,   24,   19,
91403 /*  1070 */    43,  104,   59,  165,  138,  104,  165,   25,   53,   53,
91404 /*  1080 */    22,    5,  174,  175,  193,  174,  175,   70,   71,   72,
91405 /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,    1,   82,
91406 /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
91407 /*  1110 */    19,   20,  150,   22,  150,  150,  150,   26,   27,  118,
91408 /*  1120 */   150,   35,  150,  150,   76,   27,  108,  165,   37,  165,
91409 /*  1130 */   165,  165,   76,   19,   20,  165,   22,  165,  165,  127,
91410 /*  1140 */    26,   27,   22,    1,  150,   16,   20,   56,  150,  150,
91411 /*  1150 */   119,   37,  150,  119,  160,  193,  150,   66,  193,  165,
91412 /*  1160 */   150,  150,  121,  165,  165,  108,  150,  165,  174,  175,
91413 /*  1170 */    56,  165,  150,  127,   22,  165,  165,   86,   87,   88,
91414 /*  1180 */    66,  165,   16,  150,   93,   94,   95,  165,  194,   98,
91415 /*  1190 */   174,  175,  128,   23,   15,   23,  174,  175,  165,  150,
91416 /*  1200 */    86,   87,   65,  140,  150,   22,    3,   93,   94,   95,
91417 /*  1210 */   216,    4,   98,  252,  165,  221,  150,  164,  180,  165,
91418 /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
91419 /*  1230 */   116,  165,   19,   20,  150,   22,  249,  252,  149,   26,
91420 /*  1240 */    27,  180,  165,  129,  130,  131,  132,  133,  134,  165,
91421 /*  1250 */    37,  174,  175,  150,    6,   19,   20,  150,   22,  150,
91422 /*  1260 */   150,  150,   26,   27,  149,  149,   13,  150,  165,   56,
91423 /*  1270 */   149,  159,  165,   37,  165,  165,  165,  174,  175,   66,
91424 /*  1280 */   146,  147,  165,  174,  175,   25,  152,  151,  154,  150,
91425 /*  1290 */   194,  151,   56,  116,  160,  150,  123,  202,  150,   86,
91426 /*  1300 */    87,  199,   66,  193,  165,  200,   93,   94,   95,  150,
91427 /*  1310 */   165,   98,  150,  165,  126,   22,  124,  150,  150,   26,
91428 /*  1320 */    27,  150,   86,   87,  165,  201,  150,  165,  194,   93,
91429 /*  1330 */    94,   95,  165,  165,   98,  150,  165,  122,  203,  125,
91430 /*  1340 */   227,  165,  129,  130,  131,  132,  133,  134,    5,  150,
91431 /*  1350 */   165,  135,  218,   10,   11,   12,   13,   14,  150,   66,
91432 /*  1360 */    17,  157,  118,  157,  165,  129,  130,  131,  132,  133,
91433 /*  1370 */   134,  150,  104,  165,   31,  210,   33,  176,  150,   86,
91434 /*  1380 */    87,  247,  174,  175,  150,   42,  165,   94,  121,  211,
91435 /*  1390 */   150,   98,  210,  165,  210,  174,  175,  211,   55,  165,
91436 /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
91437 /*  1410 */   104,  211,   47,  150,  174,  175,  165,  176,  176,  150,
91438 /*  1420 */   103,  165,  129,  130,  131,  174,  175,  184,  165,  179,
91439 /*  1430 */   174,  175,  150,  178,  165,  176,   22,  174,  175,  230,
91440 /*  1440 */    92,  230,  184,  174,  175,  150,  176,  165,  105,  106,
91441 /*  1450 */   107,  150,  176,  176,  111,  156,  174,  175,  179,  116,
91442 /*  1460 */   165,   18,  157,  156,  238,  157,  165,  156,   45,  174,
91443 /*  1470 */   175,  157,  157,  135,  239,  174,  175,  156,  189,  157,
91444 /*  1480 */    68,  189,  139,  219,   22,  199,  157,  192,   18,  192,
91445 /*  1490 */   192,  192,  199,  189,  219,  157,  243,   40,  243,  157,
91446 /*  1500 */   157,  246,   38,  153,  196,  198,  166,  233,  233,  228,
91447 /*  1510 */   177,  177,  209,  177,  182,  177,  166,  177,  166,  178,
91448 /*  1520 */   242,  199,  242,  209,  209,  199,  148,  196,  166,  208,
91449 /*  1530 */   195,  236,  237,  191,  208,  183,  183,  183,  186,  174,
91450 /*  1540 */   174,  186,   92,
91451};
91452#define YY_SHIFT_USE_DFLT (-90)
91453#define YY_SHIFT_COUNT (418)
91454#define YY_SHIFT_MIN   (-89)
91455#define YY_SHIFT_MAX   (1470)
91456static const short yy_shift_ofst[] = {
91457 /*     0 */   993, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
91458 /*    10 */  1213, 1213, 1213, 1213, 1213,  352,  517,  721, 1091, 1213,
91459 /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
91460 /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
91461 /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
91462 /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
91463 /*    60 */  1213,  -49,  199,  517,  517,  913,  913,  382, 1177,   55,
91464 /*    70 */   647,  573,  499,  425,  351,  277,  203,  129,  795,  795,
91465 /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
91466 /*    90 */   795,  795,  795,  795,  795,  795,  869,  795,  943, 1017,
91467 /*   100 */  1017,  -69,  -69,  -69,  -69,   -1,   -1,   58,  138,  -44,
91468 /*   110 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91469 /*   120 */   517,  517,  517,  517,  517,  517,  202,  579,  517,  517,
91470 /*   130 */   517,  517,  517,  382,  885, 1450,  -90,  -90,  -90, 1293,
91471 /*   140 */    73,  272,  272,  309,  311,  297,  282,  216,  602,  538,
91472 /*   150 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91473 /*   160 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91474 /*   170 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91475 /*   180 */   517,  517,  505,  231,  231,  231,  706,   64, 1177, 1177,
91476 /*   190 */  1177,  -90,  -90,  -90,  136,  168,  168,   12,  496,  496,
91477 /*   200 */   496,  506,  423,  512,  370,  349,  335,  149,  149,  149,
91478 /*   210 */   149,  604,  516,  149,  149,  508,    3,  299,  677,  871,
91479 /*   220 */   613,  613,  879,  871,  879,  144,  382,  226,  382,  226,
91480 /*   230 */   564,  226,  613,  226,  226,  404,  625,  625,  382,  426,
91481 /*   240 */   -89,  801, 1464, 1244, 1244, 1457, 1457, 1244, 1462, 1412,
91482 /*   250 */  1188, 1470, 1470, 1470, 1470, 1244, 1188, 1462, 1412, 1412,
91483 /*   260 */  1244, 1443, 1338, 1423, 1244, 1244, 1443, 1244, 1443, 1244,
91484 /*   270 */  1443, 1414, 1306, 1306, 1306, 1365, 1348, 1348, 1414, 1306,
91485 /*   280 */  1317, 1306, 1365, 1306, 1306, 1267, 1268, 1267, 1268, 1267,
91486 /*   290 */  1268, 1244, 1244, 1216, 1214, 1215, 1192, 1173, 1188, 1177,
91487 /*   300 */  1260, 1253, 1253, 1248, 1248, 1248, 1248,  -90,  -90,  -90,
91488 /*   310 */   -90,  -90,  -90,  939,  102,  614,   84,  133,   14,  837,
91489 /*   320 */   396,  829,  825,  796,  757,  751,  650,  357,  244,  107,
91490 /*   330 */    54,  305,  278, 1207, 1203, 1183, 1063, 1179, 1137, 1166,
91491 /*   340 */  1172, 1170, 1064, 1152, 1046, 1057, 1034, 1126, 1041, 1129,
91492 /*   350 */  1142, 1031, 1120, 1012, 1056, 1048, 1018, 1098, 1086, 1001,
91493 /*   360 */  1097, 1076, 1058,  971,  936, 1026, 1052, 1025, 1013, 1027,
91494 /*   370 */   967, 1044, 1032, 1050,  945,  949, 1028,  995, 1024, 1021,
91495 /*   380 */   963,  981,  928,  953,  951,  870,  876,  897,  838,  720,
91496 /*   390 */   828,  794,  820,  498,  642,  783,  657,  729,  642,  557,
91497 /*   400 */   507,  509,  497,  470,  478,  449,  294,  228,  443,   23,
91498 /*   410 */   152,  123,   68,  -20,  -42,   57,   39,   -3,    5,
91499};
91500#define YY_REDUCE_USE_DFLT (-222)
91501#define YY_REDUCE_COUNT (312)
91502#define YY_REDUCE_MIN   (-221)
91503#define YY_REDUCE_MAX   (1378)
91504static const short yy_reduce_ofst[] = {
91505 /*     0 */   310,  994, 1134,  221,  169,  157,   89,   18,   83,  301,
91506 /*    10 */   377,  316,  312,   16,  295,  238,  249,  391, 1301, 1295,
91507 /*    20 */  1282, 1269, 1263, 1256, 1251, 1240, 1234, 1228, 1221, 1208,
91508 /*    30 */  1109, 1103, 1077, 1054, 1022, 1016,  911,  908,  890,  888,
91509 /*    40 */   874,  816,  800,  760,  742,  739,  726,  684,  672,  665,
91510 /*    50 */   652,  612,  610,  594,  591,  578,  530,  528,  526,  524,
91511 /*    60 */   -72, -221,  399,  469,  445,  438,  143,  222,  359,  523,
91512 /*    70 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
91513 /*    80 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
91514 /*    90 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
91515 /*   100 */   523,  523,  523,  523,  523,  523,  523,  307,  523,  523,
91516 /*   110 */  1110,  678, 1033,  965,  962,  891,  814,  813,  744,  771,
91517 /*   120 */   691,  607,  522,  743,  686,  740,  328,  418,  670,  666,
91518 /*   130 */   596,  527,  529,  583,  523,  523,  523,  523,  523,  593,
91519 /*   140 */   823,  738,  712,  892, 1199, 1185, 1176, 1171,  673,  673,
91520 /*   150 */  1168, 1167, 1162, 1159, 1148, 1145, 1139, 1117, 1111, 1107,
91521 /*   160 */  1084, 1066, 1049, 1011, 1010, 1006, 1002,  999,  998,  973,
91522 /*   170 */   972,  970,  966,  964,  895,  894,  892,  833,  822,  762,
91523 /*   180 */   761,  229,  811,  804,  803,  389,  688,  808,  807,  737,
91524 /*   190 */   460,  464,  572,  584, 1355, 1366, 1365, 1352, 1354, 1353,
91525 /*   200 */  1352, 1326, 1335, 1342, 1335, 1335, 1335, 1335, 1335, 1335,
91526 /*   210 */  1335, 1295, 1295, 1335, 1335, 1321, 1362, 1331, 1378, 1326,
91527 /*   220 */  1315, 1314, 1280, 1322, 1278, 1341, 1352, 1340, 1350, 1338,
91528 /*   230 */  1332, 1336, 1303, 1334, 1333, 1281, 1275, 1274, 1340, 1307,
91529 /*   240 */  1308, 1350, 1255, 1343, 1342, 1255, 1253, 1338, 1275, 1304,
91530 /*   250 */  1293, 1299, 1298, 1297, 1295, 1329, 1286, 1264, 1292, 1289,
91531 /*   260 */  1322, 1321, 1235, 1226, 1315, 1314, 1311, 1308, 1307, 1305,
91532 /*   270 */  1299, 1279, 1277, 1276, 1270, 1258, 1211, 1209, 1250, 1259,
91533 /*   280 */  1255, 1242, 1243, 1241, 1201, 1200, 1184, 1186, 1182, 1178,
91534 /*   290 */  1165, 1206, 1204, 1113, 1135, 1095, 1124, 1105, 1102, 1096,
91535 /*   300 */  1112, 1140, 1136, 1121, 1116, 1115, 1089,  985,  961,  987,
91536 /*   310 */  1061, 1038, 1053,
91537};
91538static const YYACTIONTYPE yy_default[] = {
91539 /*     0 */   636,  872,  961,  961,  961,  872,  901,  901,  961,  760,
91540 /*    10 */   961,  961,  961,  961,  870,  961,  961,  935,  961,  961,
91541 /*    20 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91542 /*    30 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91543 /*    40 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91544 /*    50 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91545 /*    60 */   961,  844,  961,  961,  961,  901,  901,  675,  764,  795,
91546 /*    70 */   961,  961,  961,  961,  961,  961,  961,  961,  934,  936,
91547 /*    80 */   810,  809,  803,  802,  914,  775,  800,  793,  786,  797,
91548 /*    90 */   873,  866,  867,  865,  869,  874,  961,  796,  832,  850,
91549 /*   100 */   831,  849,  856,  848,  834,  843,  833,  667,  835,  836,
91550 /*   110 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91551 /*   120 */   961,  961,  961,  961,  961,  961,  662,  729,  961,  961,
91552 /*   130 */   961,  961,  961,  961,  837,  838,  853,  852,  851,  961,
91553 /*   140 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91554 /*   150 */   961,  941,  939,  961,  885,  961,  961,  961,  961,  961,
91555 /*   160 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91556 /*   170 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91557 /*   180 */   961,  642,  961,  760,  760,  760,  636,  961,  961,  961,
91558 /*   190 */   961,  953,  764,  754,  720,  961,  961,  961,  961,  961,
91559 /*   200 */   961,  961,  961,  961,  961,  961,  961,  805,  743,  924,
91560 /*   210 */   926,  961,  907,  741,  664,  762,  677,  752,  644,  799,
91561 /*   220 */   777,  777,  919,  799,  919,  701,  961,  789,  961,  789,
91562 /*   230 */   698,  789,  777,  789,  789,  868,  961,  961,  961,  761,
91563 /*   240 */   752,  961,  946,  768,  768,  938,  938,  768,  811,  733,
91564 /*   250 */   799,  740,  740,  740,  740,  768,  799,  811,  733,  733,
91565 /*   260 */   768,  659,  913,  911,  768,  768,  659,  768,  659,  768,
91566 /*   270 */   659,  878,  731,  731,  731,  716,  882,  882,  878,  731,
91567 /*   280 */   701,  731,  716,  731,  731,  781,  776,  781,  776,  781,
91568 /*   290 */   776,  768,  768,  961,  794,  782,  792,  790,  799,  961,
91569 /*   300 */   719,  652,  652,  641,  641,  641,  641,  958,  958,  953,
91570 /*   310 */   703,  703,  685,  961,  961,  961,  961,  961,  961,  961,
91571 /*   320 */   887,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91572 /*   330 */   961,  961,  961,  961,  637,  948,  961,  961,  945,  961,
91573 /*   340 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91574 /*   350 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  917,
91575 /*   360 */   961,  961,  961,  961,  961,  961,  910,  909,  961,  961,
91576 /*   370 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91577 /*   380 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91578 /*   390 */   961,  961,  961,  961,  791,  961,  783,  961,  871,  961,
91579 /*   400 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  746,
91580 /*   410 */   820,  961,  819,  823,  818,  669,  961,  650,  961,  633,
91581 /*   420 */   638,  957,  960,  959,  956,  955,  954,  949,  947,  944,
91582 /*   430 */   943,  942,  940,  937,  933,  891,  889,  896,  895,  894,
91583 /*   440 */   893,  892,  890,  888,  886,  806,  804,  801,  798,  932,
91584 /*   450 */   884,  742,  739,  738,  658,  950,  916,  925,  923,  812,
91585 /*   460 */   922,  921,  920,  918,  915,  902,  808,  807,  734,  876,
91586 /*   470 */   875,  661,  906,  905,  904,  908,  912,  903,  770,  660,
91587 /*   480 */   657,  666,  723,  722,  730,  728,  727,  726,  725,  724,
91588 /*   490 */   721,  668,  676,  687,  715,  700,  699,  881,  883,  880,
91589 /*   500 */   879,  708,  707,  713,  712,  711,  710,  709,  706,  705,
91590 /*   510 */   704,  697,  696,  702,  695,  718,  717,  714,  694,  737,
91591 /*   520 */   736,  735,  732,  693,  692,  691,  823,  690,  689,  829,
91592 /*   530 */   828,  816,  860,  757,  756,  755,  767,  766,  779,  778,
91593 /*   540 */   814,  813,  780,  765,  759,  758,  774,  773,  772,  771,
91594 /*   550 */   763,  753,  785,  788,  787,  784,  845,  862,  769,  859,
91595 /*   560 */   931,  930,  929,  928,  927,  864,  863,  830,  827,  680,
91596 /*   570 */   681,  900,  898,  899,  897,  683,  682,  679,  678,  861,
91597 /*   580 */   748,  747,  857,  854,  846,  841,  858,  855,  847,  842,
91598 /*   590 */   840,  839,  825,  824,  822,  821,  817,  826,  671,  749,
91599 /*   600 */   745,  744,  815,  751,  750,  688,  686,  684,  665,  663,
91600 /*   610 */   656,  654,  653,  655,  651,  649,  648,  647,  646,  645,
91601 /*   620 */   674,  673,  672,  670,  669,  643,  640,  639,  635,  634,
91602 /*   630 */   632,
91603};
91604
91605/* The next table maps tokens into fallback tokens.  If a construct
91606** like the following:
91607**
91608**      %fallback ID X Y Z.
91609**
91610** appears in the grammar, then ID becomes a fallback token for X, Y,
91611** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
91612** but it does not parse, the type of the token is changed to ID and
91613** the parse is retried before an error is thrown.
91614*/
91615#ifdef YYFALLBACK
91616static const YYCODETYPE yyFallback[] = {
91617    0,  /*          $ => nothing */
91618    0,  /*       SEMI => nothing */
91619   26,  /*    EXPLAIN => ID */
91620   26,  /*      QUERY => ID */
91621   26,  /*       PLAN => ID */
91622   26,  /*      BEGIN => ID */
91623    0,  /* TRANSACTION => nothing */
91624   26,  /*   DEFERRED => ID */
91625   26,  /*  IMMEDIATE => ID */
91626   26,  /*  EXCLUSIVE => ID */
91627    0,  /*     COMMIT => nothing */
91628   26,  /*        END => ID */
91629   26,  /*   ROLLBACK => ID */
91630   26,  /*  SAVEPOINT => ID */
91631   26,  /*    RELEASE => ID */
91632    0,  /*         TO => nothing */
91633    0,  /*      TABLE => nothing */
91634    0,  /*     CREATE => nothing */
91635   26,  /*         IF => ID */
91636    0,  /*        NOT => nothing */
91637    0,  /*     EXISTS => nothing */
91638   26,  /*       TEMP => ID */
91639    0,  /*         LP => nothing */
91640    0,  /*         RP => nothing */
91641    0,  /*         AS => nothing */
91642    0,  /*      COMMA => nothing */
91643    0,  /*         ID => nothing */
91644    0,  /*    INDEXED => nothing */
91645   26,  /*      ABORT => ID */
91646   26,  /*     ACTION => ID */
91647   26,  /*      AFTER => ID */
91648   26,  /*    ANALYZE => ID */
91649   26,  /*        ASC => ID */
91650   26,  /*     ATTACH => ID */
91651   26,  /*     BEFORE => ID */
91652   26,  /*         BY => ID */
91653   26,  /*    CASCADE => ID */
91654   26,  /*       CAST => ID */
91655   26,  /*   COLUMNKW => ID */
91656   26,  /*   CONFLICT => ID */
91657   26,  /*   DATABASE => ID */
91658   26,  /*       DESC => ID */
91659   26,  /*     DETACH => ID */
91660   26,  /*       EACH => ID */
91661   26,  /*       FAIL => ID */
91662   26,  /*        FOR => ID */
91663   26,  /*     IGNORE => ID */
91664   26,  /*  INITIALLY => ID */
91665   26,  /*    INSTEAD => ID */
91666   26,  /*    LIKE_KW => ID */
91667   26,  /*      MATCH => ID */
91668   26,  /*         NO => ID */
91669   26,  /*        KEY => ID */
91670   26,  /*         OF => ID */
91671   26,  /*     OFFSET => ID */
91672   26,  /*     PRAGMA => ID */
91673   26,  /*      RAISE => ID */
91674   26,  /*    REPLACE => ID */
91675   26,  /*   RESTRICT => ID */
91676   26,  /*        ROW => ID */
91677   26,  /*    TRIGGER => ID */
91678   26,  /*     VACUUM => ID */
91679   26,  /*       VIEW => ID */
91680   26,  /*    VIRTUAL => ID */
91681   26,  /*    REINDEX => ID */
91682   26,  /*     RENAME => ID */
91683   26,  /*   CTIME_KW => ID */
91684};
91685#endif /* YYFALLBACK */
91686
91687/* The following structure represents a single element of the
91688** parser's stack.  Information stored includes:
91689**
91690**   +  The state number for the parser at this level of the stack.
91691**
91692**   +  The value of the token stored at this level of the stack.
91693**      (In other words, the "major" token.)
91694**
91695**   +  The semantic value stored at this level of the stack.  This is
91696**      the information used by the action routines in the grammar.
91697**      It is sometimes called the "minor" token.
91698*/
91699struct yyStackEntry {
91700  YYACTIONTYPE stateno;  /* The state-number */
91701  YYCODETYPE major;      /* The major token value.  This is the code
91702                         ** number for the token at this stack level */
91703  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
91704                         ** is the value of the token  */
91705};
91706typedef struct yyStackEntry yyStackEntry;
91707
91708/* The state of the parser is completely contained in an instance of
91709** the following structure */
91710struct yyParser {
91711  int yyidx;                    /* Index of top element in stack */
91712#ifdef YYTRACKMAXSTACKDEPTH
91713  int yyidxMax;                 /* Maximum value of yyidx */
91714#endif
91715  int yyerrcnt;                 /* Shifts left before out of the error */
91716  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
91717#if YYSTACKDEPTH<=0
91718  int yystksz;                  /* Current side of the stack */
91719  yyStackEntry *yystack;        /* The parser's stack */
91720#else
91721  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
91722#endif
91723};
91724typedef struct yyParser yyParser;
91725
91726#ifndef NDEBUG
91727static FILE *yyTraceFILE = 0;
91728static char *yyTracePrompt = 0;
91729#endif /* NDEBUG */
91730
91731#ifndef NDEBUG
91732/*
91733** Turn parser tracing on by giving a stream to which to write the trace
91734** and a prompt to preface each trace message.  Tracing is turned off
91735** by making either argument NULL
91736**
91737** Inputs:
91738** <ul>
91739** <li> A FILE* to which trace output should be written.
91740**      If NULL, then tracing is turned off.
91741** <li> A prefix string written at the beginning of every
91742**      line of trace output.  If NULL, then tracing is
91743**      turned off.
91744** </ul>
91745**
91746** Outputs:
91747** None.
91748*/
91749SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
91750  yyTraceFILE = TraceFILE;
91751  yyTracePrompt = zTracePrompt;
91752  if( yyTraceFILE==0 ) yyTracePrompt = 0;
91753  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
91754}
91755#endif /* NDEBUG */
91756
91757#ifndef NDEBUG
91758/* For tracing shifts, the names of all terminals and nonterminals
91759** are required.  The following table supplies these names */
91760static const char *const yyTokenName[] = {
91761  "$",             "SEMI",          "EXPLAIN",       "QUERY",
91762  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
91763  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
91764  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
91765  "TABLE",         "CREATE",        "IF",            "NOT",
91766  "EXISTS",        "TEMP",          "LP",            "RP",
91767  "AS",            "COMMA",         "ID",            "INDEXED",
91768  "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
91769  "ASC",           "ATTACH",        "BEFORE",        "BY",
91770  "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
91771  "DATABASE",      "DESC",          "DETACH",        "EACH",
91772  "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
91773  "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
91774  "KEY",           "OF",            "OFFSET",        "PRAGMA",
91775  "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
91776  "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
91777  "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
91778  "OR",            "AND",           "IS",            "BETWEEN",
91779  "IN",            "ISNULL",        "NOTNULL",       "NE",
91780  "EQ",            "GT",            "LE",            "LT",
91781  "GE",            "ESCAPE",        "BITAND",        "BITOR",
91782  "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
91783  "STAR",          "SLASH",         "REM",           "CONCAT",
91784  "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
91785  "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
91786  "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
91787  "ON",            "INSERT",        "DELETE",        "UPDATE",
91788  "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
91789  "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
91790  "SELECT",        "DISTINCT",      "DOT",           "FROM",
91791  "JOIN",          "USING",         "ORDER",         "GROUP",
91792  "HAVING",        "LIMIT",         "WHERE",         "INTO",
91793  "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
91794  "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
91795  "THEN",          "ELSE",          "INDEX",         "ALTER",
91796  "ADD",           "error",         "input",         "cmdlist",
91797  "ecmd",          "explain",       "cmdx",          "cmd",
91798  "transtype",     "trans_opt",     "nm",            "savepoint_opt",
91799  "create_table",  "create_table_args",  "createkw",      "temp",
91800  "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
91801  "select",        "column",        "columnid",      "type",
91802  "carglist",      "id",            "ids",           "typetoken",
91803  "typename",      "signed",        "plus_num",      "minus_num",
91804  "carg",          "ccons",         "term",          "expr",
91805  "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
91806  "refargs",       "defer_subclause",  "refarg",        "refact",
91807  "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",
91808  "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
91809  "ifexists",      "fullname",      "oneselect",     "multiselect_op",
91810  "distinct",      "selcollist",    "from",          "where_opt",
91811  "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
91812  "sclp",          "as",            "seltablist",    "stl_prefix",
91813  "joinop",        "indexed_opt",   "on_opt",        "using_opt",
91814  "joinop2",       "inscollist",    "sortlist",      "sortitem",
91815  "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
91816  "itemlist",      "exprlist",      "likeop",        "escape",
91817  "between_op",    "in_op",         "case_operand",  "case_exprlist",
91818  "case_else",     "uniqueflag",    "collate",       "nmnum",
91819  "plus_opt",      "number",        "trigger_decl",  "trigger_cmd_list",
91820  "trigger_time",  "trigger_event",  "foreach_clause",  "when_clause",
91821  "trigger_cmd",   "trnm",          "tridxby",       "database_kw_opt",
91822  "key_opt",       "add_column_fullname",  "kwcolumn_opt",  "create_vtab",
91823  "vtabarglist",   "vtabarg",       "vtabargtoken",  "lp",
91824  "anylist",
91825};
91826#endif /* NDEBUG */
91827
91828#ifndef NDEBUG
91829/* For tracing reduce actions, the names of all rules are required.
91830*/
91831static const char *const yyRuleName[] = {
91832 /*   0 */ "input ::= cmdlist",
91833 /*   1 */ "cmdlist ::= cmdlist ecmd",
91834 /*   2 */ "cmdlist ::= ecmd",
91835 /*   3 */ "ecmd ::= SEMI",
91836 /*   4 */ "ecmd ::= explain cmdx SEMI",
91837 /*   5 */ "explain ::=",
91838 /*   6 */ "explain ::= EXPLAIN",
91839 /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
91840 /*   8 */ "cmdx ::= cmd",
91841 /*   9 */ "cmd ::= BEGIN transtype trans_opt",
91842 /*  10 */ "trans_opt ::=",
91843 /*  11 */ "trans_opt ::= TRANSACTION",
91844 /*  12 */ "trans_opt ::= TRANSACTION nm",
91845 /*  13 */ "transtype ::=",
91846 /*  14 */ "transtype ::= DEFERRED",
91847 /*  15 */ "transtype ::= IMMEDIATE",
91848 /*  16 */ "transtype ::= EXCLUSIVE",
91849 /*  17 */ "cmd ::= COMMIT trans_opt",
91850 /*  18 */ "cmd ::= END trans_opt",
91851 /*  19 */ "cmd ::= ROLLBACK trans_opt",
91852 /*  20 */ "savepoint_opt ::= SAVEPOINT",
91853 /*  21 */ "savepoint_opt ::=",
91854 /*  22 */ "cmd ::= SAVEPOINT nm",
91855 /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
91856 /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
91857 /*  25 */ "cmd ::= create_table create_table_args",
91858 /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
91859 /*  27 */ "createkw ::= CREATE",
91860 /*  28 */ "ifnotexists ::=",
91861 /*  29 */ "ifnotexists ::= IF NOT EXISTS",
91862 /*  30 */ "temp ::= TEMP",
91863 /*  31 */ "temp ::=",
91864 /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
91865 /*  33 */ "create_table_args ::= AS select",
91866 /*  34 */ "columnlist ::= columnlist COMMA column",
91867 /*  35 */ "columnlist ::= column",
91868 /*  36 */ "column ::= columnid type carglist",
91869 /*  37 */ "columnid ::= nm",
91870 /*  38 */ "id ::= ID",
91871 /*  39 */ "id ::= INDEXED",
91872 /*  40 */ "ids ::= ID|STRING",
91873 /*  41 */ "nm ::= id",
91874 /*  42 */ "nm ::= STRING",
91875 /*  43 */ "nm ::= JOIN_KW",
91876 /*  44 */ "type ::=",
91877 /*  45 */ "type ::= typetoken",
91878 /*  46 */ "typetoken ::= typename",
91879 /*  47 */ "typetoken ::= typename LP signed RP",
91880 /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
91881 /*  49 */ "typename ::= ids",
91882 /*  50 */ "typename ::= typename ids",
91883 /*  51 */ "signed ::= plus_num",
91884 /*  52 */ "signed ::= minus_num",
91885 /*  53 */ "carglist ::= carglist carg",
91886 /*  54 */ "carglist ::=",
91887 /*  55 */ "carg ::= CONSTRAINT nm ccons",
91888 /*  56 */ "carg ::= ccons",
91889 /*  57 */ "ccons ::= DEFAULT term",
91890 /*  58 */ "ccons ::= DEFAULT LP expr RP",
91891 /*  59 */ "ccons ::= DEFAULT PLUS term",
91892 /*  60 */ "ccons ::= DEFAULT MINUS term",
91893 /*  61 */ "ccons ::= DEFAULT id",
91894 /*  62 */ "ccons ::= NULL onconf",
91895 /*  63 */ "ccons ::= NOT NULL onconf",
91896 /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
91897 /*  65 */ "ccons ::= UNIQUE onconf",
91898 /*  66 */ "ccons ::= CHECK LP expr RP",
91899 /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
91900 /*  68 */ "ccons ::= defer_subclause",
91901 /*  69 */ "ccons ::= COLLATE ids",
91902 /*  70 */ "autoinc ::=",
91903 /*  71 */ "autoinc ::= AUTOINCR",
91904 /*  72 */ "refargs ::=",
91905 /*  73 */ "refargs ::= refargs refarg",
91906 /*  74 */ "refarg ::= MATCH nm",
91907 /*  75 */ "refarg ::= ON INSERT refact",
91908 /*  76 */ "refarg ::= ON DELETE refact",
91909 /*  77 */ "refarg ::= ON UPDATE refact",
91910 /*  78 */ "refact ::= SET NULL",
91911 /*  79 */ "refact ::= SET DEFAULT",
91912 /*  80 */ "refact ::= CASCADE",
91913 /*  81 */ "refact ::= RESTRICT",
91914 /*  82 */ "refact ::= NO ACTION",
91915 /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
91916 /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
91917 /*  85 */ "init_deferred_pred_opt ::=",
91918 /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
91919 /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
91920 /*  88 */ "conslist_opt ::=",
91921 /*  89 */ "conslist_opt ::= COMMA conslist",
91922 /*  90 */ "conslist ::= conslist COMMA tcons",
91923 /*  91 */ "conslist ::= conslist tcons",
91924 /*  92 */ "conslist ::= tcons",
91925 /*  93 */ "tcons ::= CONSTRAINT nm",
91926 /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
91927 /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
91928 /*  96 */ "tcons ::= CHECK LP expr RP onconf",
91929 /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
91930 /*  98 */ "defer_subclause_opt ::=",
91931 /*  99 */ "defer_subclause_opt ::= defer_subclause",
91932 /* 100 */ "onconf ::=",
91933 /* 101 */ "onconf ::= ON CONFLICT resolvetype",
91934 /* 102 */ "orconf ::=",
91935 /* 103 */ "orconf ::= OR resolvetype",
91936 /* 104 */ "resolvetype ::= raisetype",
91937 /* 105 */ "resolvetype ::= IGNORE",
91938 /* 106 */ "resolvetype ::= REPLACE",
91939 /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
91940 /* 108 */ "ifexists ::= IF EXISTS",
91941 /* 109 */ "ifexists ::=",
91942 /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
91943 /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
91944 /* 112 */ "cmd ::= select",
91945 /* 113 */ "select ::= oneselect",
91946 /* 114 */ "select ::= select multiselect_op oneselect",
91947 /* 115 */ "multiselect_op ::= UNION",
91948 /* 116 */ "multiselect_op ::= UNION ALL",
91949 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
91950 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
91951 /* 119 */ "distinct ::= DISTINCT",
91952 /* 120 */ "distinct ::= ALL",
91953 /* 121 */ "distinct ::=",
91954 /* 122 */ "sclp ::= selcollist COMMA",
91955 /* 123 */ "sclp ::=",
91956 /* 124 */ "selcollist ::= sclp expr as",
91957 /* 125 */ "selcollist ::= sclp STAR",
91958 /* 126 */ "selcollist ::= sclp nm DOT STAR",
91959 /* 127 */ "as ::= AS nm",
91960 /* 128 */ "as ::= ids",
91961 /* 129 */ "as ::=",
91962 /* 130 */ "from ::=",
91963 /* 131 */ "from ::= FROM seltablist",
91964 /* 132 */ "stl_prefix ::= seltablist joinop",
91965 /* 133 */ "stl_prefix ::=",
91966 /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
91967 /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
91968 /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
91969 /* 137 */ "dbnm ::=",
91970 /* 138 */ "dbnm ::= DOT nm",
91971 /* 139 */ "fullname ::= nm dbnm",
91972 /* 140 */ "joinop ::= COMMA|JOIN",
91973 /* 141 */ "joinop ::= JOIN_KW JOIN",
91974 /* 142 */ "joinop ::= JOIN_KW nm JOIN",
91975 /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
91976 /* 144 */ "on_opt ::= ON expr",
91977 /* 145 */ "on_opt ::=",
91978 /* 146 */ "indexed_opt ::=",
91979 /* 147 */ "indexed_opt ::= INDEXED BY nm",
91980 /* 148 */ "indexed_opt ::= NOT INDEXED",
91981 /* 149 */ "using_opt ::= USING LP inscollist RP",
91982 /* 150 */ "using_opt ::=",
91983 /* 151 */ "orderby_opt ::=",
91984 /* 152 */ "orderby_opt ::= ORDER BY sortlist",
91985 /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
91986 /* 154 */ "sortlist ::= sortitem sortorder",
91987 /* 155 */ "sortitem ::= expr",
91988 /* 156 */ "sortorder ::= ASC",
91989 /* 157 */ "sortorder ::= DESC",
91990 /* 158 */ "sortorder ::=",
91991 /* 159 */ "groupby_opt ::=",
91992 /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
91993 /* 161 */ "having_opt ::=",
91994 /* 162 */ "having_opt ::= HAVING expr",
91995 /* 163 */ "limit_opt ::=",
91996 /* 164 */ "limit_opt ::= LIMIT expr",
91997 /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
91998 /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
91999 /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
92000 /* 168 */ "where_opt ::=",
92001 /* 169 */ "where_opt ::= WHERE expr",
92002 /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
92003 /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
92004 /* 172 */ "setlist ::= nm EQ expr",
92005 /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
92006 /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
92007 /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
92008 /* 176 */ "insert_cmd ::= INSERT orconf",
92009 /* 177 */ "insert_cmd ::= REPLACE",
92010 /* 178 */ "itemlist ::= itemlist COMMA expr",
92011 /* 179 */ "itemlist ::= expr",
92012 /* 180 */ "inscollist_opt ::=",
92013 /* 181 */ "inscollist_opt ::= LP inscollist RP",
92014 /* 182 */ "inscollist ::= inscollist COMMA nm",
92015 /* 183 */ "inscollist ::= nm",
92016 /* 184 */ "expr ::= term",
92017 /* 185 */ "expr ::= LP expr RP",
92018 /* 186 */ "term ::= NULL",
92019 /* 187 */ "expr ::= id",
92020 /* 188 */ "expr ::= JOIN_KW",
92021 /* 189 */ "expr ::= nm DOT nm",
92022 /* 190 */ "expr ::= nm DOT nm DOT nm",
92023 /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
92024 /* 192 */ "term ::= STRING",
92025 /* 193 */ "expr ::= REGISTER",
92026 /* 194 */ "expr ::= VARIABLE",
92027 /* 195 */ "expr ::= expr COLLATE ids",
92028 /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
92029 /* 197 */ "expr ::= ID LP distinct exprlist RP",
92030 /* 198 */ "expr ::= ID LP STAR RP",
92031 /* 199 */ "term ::= CTIME_KW",
92032 /* 200 */ "expr ::= expr AND expr",
92033 /* 201 */ "expr ::= expr OR expr",
92034 /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
92035 /* 203 */ "expr ::= expr EQ|NE expr",
92036 /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
92037 /* 205 */ "expr ::= expr PLUS|MINUS expr",
92038 /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
92039 /* 207 */ "expr ::= expr CONCAT expr",
92040 /* 208 */ "likeop ::= LIKE_KW",
92041 /* 209 */ "likeop ::= NOT LIKE_KW",
92042 /* 210 */ "likeop ::= MATCH",
92043 /* 211 */ "likeop ::= NOT MATCH",
92044 /* 212 */ "escape ::= ESCAPE expr",
92045 /* 213 */ "escape ::=",
92046 /* 214 */ "expr ::= expr likeop expr escape",
92047 /* 215 */ "expr ::= expr ISNULL|NOTNULL",
92048 /* 216 */ "expr ::= expr NOT NULL",
92049 /* 217 */ "expr ::= expr IS expr",
92050 /* 218 */ "expr ::= expr IS NOT expr",
92051 /* 219 */ "expr ::= NOT expr",
92052 /* 220 */ "expr ::= BITNOT expr",
92053 /* 221 */ "expr ::= MINUS expr",
92054 /* 222 */ "expr ::= PLUS expr",
92055 /* 223 */ "between_op ::= BETWEEN",
92056 /* 224 */ "between_op ::= NOT BETWEEN",
92057 /* 225 */ "expr ::= expr between_op expr AND expr",
92058 /* 226 */ "in_op ::= IN",
92059 /* 227 */ "in_op ::= NOT IN",
92060 /* 228 */ "expr ::= expr in_op LP exprlist RP",
92061 /* 229 */ "expr ::= LP select RP",
92062 /* 230 */ "expr ::= expr in_op LP select RP",
92063 /* 231 */ "expr ::= expr in_op nm dbnm",
92064 /* 232 */ "expr ::= EXISTS LP select RP",
92065 /* 233 */ "expr ::= CASE case_operand case_exprlist case_else END",
92066 /* 234 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
92067 /* 235 */ "case_exprlist ::= WHEN expr THEN expr",
92068 /* 236 */ "case_else ::= ELSE expr",
92069 /* 237 */ "case_else ::=",
92070 /* 238 */ "case_operand ::= expr",
92071 /* 239 */ "case_operand ::=",
92072 /* 240 */ "exprlist ::= nexprlist",
92073 /* 241 */ "exprlist ::=",
92074 /* 242 */ "nexprlist ::= nexprlist COMMA expr",
92075 /* 243 */ "nexprlist ::= expr",
92076 /* 244 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
92077 /* 245 */ "uniqueflag ::= UNIQUE",
92078 /* 246 */ "uniqueflag ::=",
92079 /* 247 */ "idxlist_opt ::=",
92080 /* 248 */ "idxlist_opt ::= LP idxlist RP",
92081 /* 249 */ "idxlist ::= idxlist COMMA nm collate sortorder",
92082 /* 250 */ "idxlist ::= nm collate sortorder",
92083 /* 251 */ "collate ::=",
92084 /* 252 */ "collate ::= COLLATE ids",
92085 /* 253 */ "cmd ::= DROP INDEX ifexists fullname",
92086 /* 254 */ "cmd ::= VACUUM",
92087 /* 255 */ "cmd ::= VACUUM nm",
92088 /* 256 */ "cmd ::= PRAGMA nm dbnm",
92089 /* 257 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
92090 /* 258 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
92091 /* 259 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
92092 /* 260 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
92093 /* 261 */ "nmnum ::= plus_num",
92094 /* 262 */ "nmnum ::= nm",
92095 /* 263 */ "nmnum ::= ON",
92096 /* 264 */ "nmnum ::= DELETE",
92097 /* 265 */ "nmnum ::= DEFAULT",
92098 /* 266 */ "plus_num ::= plus_opt number",
92099 /* 267 */ "minus_num ::= MINUS number",
92100 /* 268 */ "number ::= INTEGER|FLOAT",
92101 /* 269 */ "plus_opt ::= PLUS",
92102 /* 270 */ "plus_opt ::=",
92103 /* 271 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
92104 /* 272 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
92105 /* 273 */ "trigger_time ::= BEFORE",
92106 /* 274 */ "trigger_time ::= AFTER",
92107 /* 275 */ "trigger_time ::= INSTEAD OF",
92108 /* 276 */ "trigger_time ::=",
92109 /* 277 */ "trigger_event ::= DELETE|INSERT",
92110 /* 278 */ "trigger_event ::= UPDATE",
92111 /* 279 */ "trigger_event ::= UPDATE OF inscollist",
92112 /* 280 */ "foreach_clause ::=",
92113 /* 281 */ "foreach_clause ::= FOR EACH ROW",
92114 /* 282 */ "when_clause ::=",
92115 /* 283 */ "when_clause ::= WHEN expr",
92116 /* 284 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
92117 /* 285 */ "trigger_cmd_list ::= trigger_cmd SEMI",
92118 /* 286 */ "trnm ::= nm",
92119 /* 287 */ "trnm ::= nm DOT nm",
92120 /* 288 */ "tridxby ::=",
92121 /* 289 */ "tridxby ::= INDEXED BY nm",
92122 /* 290 */ "tridxby ::= NOT INDEXED",
92123 /* 291 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
92124 /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
92125 /* 293 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
92126 /* 294 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
92127 /* 295 */ "trigger_cmd ::= select",
92128 /* 296 */ "expr ::= RAISE LP IGNORE RP",
92129 /* 297 */ "expr ::= RAISE LP raisetype COMMA nm RP",
92130 /* 298 */ "raisetype ::= ROLLBACK",
92131 /* 299 */ "raisetype ::= ABORT",
92132 /* 300 */ "raisetype ::= FAIL",
92133 /* 301 */ "cmd ::= DROP TRIGGER ifexists fullname",
92134 /* 302 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
92135 /* 303 */ "cmd ::= DETACH database_kw_opt expr",
92136 /* 304 */ "key_opt ::=",
92137 /* 305 */ "key_opt ::= KEY expr",
92138 /* 306 */ "database_kw_opt ::= DATABASE",
92139 /* 307 */ "database_kw_opt ::=",
92140 /* 308 */ "cmd ::= REINDEX",
92141 /* 309 */ "cmd ::= REINDEX nm dbnm",
92142 /* 310 */ "cmd ::= ANALYZE",
92143 /* 311 */ "cmd ::= ANALYZE nm dbnm",
92144 /* 312 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
92145 /* 313 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
92146 /* 314 */ "add_column_fullname ::= fullname",
92147 /* 315 */ "kwcolumn_opt ::=",
92148 /* 316 */ "kwcolumn_opt ::= COLUMNKW",
92149 /* 317 */ "cmd ::= create_vtab",
92150 /* 318 */ "cmd ::= create_vtab LP vtabarglist RP",
92151 /* 319 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
92152 /* 320 */ "vtabarglist ::= vtabarg",
92153 /* 321 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
92154 /* 322 */ "vtabarg ::=",
92155 /* 323 */ "vtabarg ::= vtabarg vtabargtoken",
92156 /* 324 */ "vtabargtoken ::= ANY",
92157 /* 325 */ "vtabargtoken ::= lp anylist RP",
92158 /* 326 */ "lp ::= LP",
92159 /* 327 */ "anylist ::=",
92160 /* 328 */ "anylist ::= anylist LP anylist RP",
92161 /* 329 */ "anylist ::= anylist ANY",
92162};
92163#endif /* NDEBUG */
92164
92165
92166#if YYSTACKDEPTH<=0
92167/*
92168** Try to increase the size of the parser stack.
92169*/
92170static void yyGrowStack(yyParser *p){
92171  int newSize;
92172  yyStackEntry *pNew;
92173
92174  newSize = p->yystksz*2 + 100;
92175  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
92176  if( pNew ){
92177    p->yystack = pNew;
92178    p->yystksz = newSize;
92179#ifndef NDEBUG
92180    if( yyTraceFILE ){
92181      fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
92182              yyTracePrompt, p->yystksz);
92183    }
92184#endif
92185  }
92186}
92187#endif
92188
92189/*
92190** This function allocates a new parser.
92191** The only argument is a pointer to a function which works like
92192** malloc.
92193**
92194** Inputs:
92195** A pointer to the function used to allocate memory.
92196**
92197** Outputs:
92198** A pointer to a parser.  This pointer is used in subsequent calls
92199** to sqlite3Parser and sqlite3ParserFree.
92200*/
92201SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
92202  yyParser *pParser;
92203  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
92204  if( pParser ){
92205    pParser->yyidx = -1;
92206#ifdef YYTRACKMAXSTACKDEPTH
92207    pParser->yyidxMax = 0;
92208#endif
92209#if YYSTACKDEPTH<=0
92210    pParser->yystack = NULL;
92211    pParser->yystksz = 0;
92212    yyGrowStack(pParser);
92213#endif
92214  }
92215  return pParser;
92216}
92217
92218/* The following function deletes the value associated with a
92219** symbol.  The symbol can be either a terminal or nonterminal.
92220** "yymajor" is the symbol code, and "yypminor" is a pointer to
92221** the value.
92222*/
92223static void yy_destructor(
92224  yyParser *yypParser,    /* The parser */
92225  YYCODETYPE yymajor,     /* Type code for object to destroy */
92226  YYMINORTYPE *yypminor   /* The object to be destroyed */
92227){
92228  sqlite3ParserARG_FETCH;
92229  switch( yymajor ){
92230    /* Here is inserted the actions which take place when a
92231    ** terminal or non-terminal is destroyed.  This can happen
92232    ** when the symbol is popped from the stack during a
92233    ** reduce or during error processing or when a parser is
92234    ** being destroyed before it is finished parsing.
92235    **
92236    ** Note: during a reduce, the only symbols destroyed are those
92237    ** which appear on the RHS of the rule, but which are not used
92238    ** inside the C code.
92239    */
92240    case 160: /* select */
92241    case 194: /* oneselect */
92242{
92243sqlite3SelectDelete(pParse->db, (yypminor->yy3));
92244}
92245      break;
92246    case 174: /* term */
92247    case 175: /* expr */
92248    case 223: /* escape */
92249{
92250sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
92251}
92252      break;
92253    case 179: /* idxlist_opt */
92254    case 187: /* idxlist */
92255    case 197: /* selcollist */
92256    case 200: /* groupby_opt */
92257    case 202: /* orderby_opt */
92258    case 204: /* sclp */
92259    case 214: /* sortlist */
92260    case 216: /* nexprlist */
92261    case 217: /* setlist */
92262    case 220: /* itemlist */
92263    case 221: /* exprlist */
92264    case 227: /* case_exprlist */
92265{
92266sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
92267}
92268      break;
92269    case 193: /* fullname */
92270    case 198: /* from */
92271    case 206: /* seltablist */
92272    case 207: /* stl_prefix */
92273{
92274sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
92275}
92276      break;
92277    case 199: /* where_opt */
92278    case 201: /* having_opt */
92279    case 210: /* on_opt */
92280    case 215: /* sortitem */
92281    case 226: /* case_operand */
92282    case 228: /* case_else */
92283    case 239: /* when_clause */
92284    case 244: /* key_opt */
92285{
92286sqlite3ExprDelete(pParse->db, (yypminor->yy132));
92287}
92288      break;
92289    case 211: /* using_opt */
92290    case 213: /* inscollist */
92291    case 219: /* inscollist_opt */
92292{
92293sqlite3IdListDelete(pParse->db, (yypminor->yy408));
92294}
92295      break;
92296    case 235: /* trigger_cmd_list */
92297    case 240: /* trigger_cmd */
92298{
92299sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
92300}
92301      break;
92302    case 237: /* trigger_event */
92303{
92304sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
92305}
92306      break;
92307    default:  break;   /* If no destructor action specified: do nothing */
92308  }
92309}
92310
92311/*
92312** Pop the parser's stack once.
92313**
92314** If there is a destructor routine associated with the token which
92315** is popped from the stack, then call it.
92316**
92317** Return the major token number for the symbol popped.
92318*/
92319static int yy_pop_parser_stack(yyParser *pParser){
92320  YYCODETYPE yymajor;
92321  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
92322
92323  /* There is no mechanism by which the parser stack can be popped below
92324  ** empty in SQLite.  */
92325  if( NEVER(pParser->yyidx<0) ) return 0;
92326#ifndef NDEBUG
92327  if( yyTraceFILE && pParser->yyidx>=0 ){
92328    fprintf(yyTraceFILE,"%sPopping %s\n",
92329      yyTracePrompt,
92330      yyTokenName[yytos->major]);
92331  }
92332#endif
92333  yymajor = yytos->major;
92334  yy_destructor(pParser, yymajor, &yytos->minor);
92335  pParser->yyidx--;
92336  return yymajor;
92337}
92338
92339/*
92340** Deallocate and destroy a parser.  Destructors are all called for
92341** all stack elements before shutting the parser down.
92342**
92343** Inputs:
92344** <ul>
92345** <li>  A pointer to the parser.  This should be a pointer
92346**       obtained from sqlite3ParserAlloc.
92347** <li>  A pointer to a function used to reclaim memory obtained
92348**       from malloc.
92349** </ul>
92350*/
92351SQLITE_PRIVATE void sqlite3ParserFree(
92352  void *p,                    /* The parser to be deleted */
92353  void (*freeProc)(void*)     /* Function used to reclaim memory */
92354){
92355  yyParser *pParser = (yyParser*)p;
92356  /* In SQLite, we never try to destroy a parser that was not successfully
92357  ** created in the first place. */
92358  if( NEVER(pParser==0) ) return;
92359  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
92360#if YYSTACKDEPTH<=0
92361  free(pParser->yystack);
92362#endif
92363  (*freeProc)((void*)pParser);
92364}
92365
92366/*
92367** Return the peak depth of the stack for a parser.
92368*/
92369#ifdef YYTRACKMAXSTACKDEPTH
92370SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
92371  yyParser *pParser = (yyParser*)p;
92372  return pParser->yyidxMax;
92373}
92374#endif
92375
92376/*
92377** Find the appropriate action for a parser given the terminal
92378** look-ahead token iLookAhead.
92379**
92380** If the look-ahead token is YYNOCODE, then check to see if the action is
92381** independent of the look-ahead.  If it is, return the action, otherwise
92382** return YY_NO_ACTION.
92383*/
92384static int yy_find_shift_action(
92385  yyParser *pParser,        /* The parser */
92386  YYCODETYPE iLookAhead     /* The look-ahead token */
92387){
92388  int i;
92389  int stateno = pParser->yystack[pParser->yyidx].stateno;
92390
92391  if( stateno>YY_SHIFT_COUNT
92392   || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
92393    return yy_default[stateno];
92394  }
92395  assert( iLookAhead!=YYNOCODE );
92396  i += iLookAhead;
92397  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
92398    if( iLookAhead>0 ){
92399#ifdef YYFALLBACK
92400      YYCODETYPE iFallback;            /* Fallback token */
92401      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
92402             && (iFallback = yyFallback[iLookAhead])!=0 ){
92403#ifndef NDEBUG
92404        if( yyTraceFILE ){
92405          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
92406             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
92407        }
92408#endif
92409        return yy_find_shift_action(pParser, iFallback);
92410      }
92411#endif
92412#ifdef YYWILDCARD
92413      {
92414        int j = i - iLookAhead + YYWILDCARD;
92415        if(
92416#if YY_SHIFT_MIN+YYWILDCARD<0
92417          j>=0 &&
92418#endif
92419#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
92420          j<YY_ACTTAB_COUNT &&
92421#endif
92422          yy_lookahead[j]==YYWILDCARD
92423        ){
92424#ifndef NDEBUG
92425          if( yyTraceFILE ){
92426            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
92427               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
92428          }
92429#endif /* NDEBUG */
92430          return yy_action[j];
92431        }
92432      }
92433#endif /* YYWILDCARD */
92434    }
92435    return yy_default[stateno];
92436  }else{
92437    return yy_action[i];
92438  }
92439}
92440
92441/*
92442** Find the appropriate action for a parser given the non-terminal
92443** look-ahead token iLookAhead.
92444**
92445** If the look-ahead token is YYNOCODE, then check to see if the action is
92446** independent of the look-ahead.  If it is, return the action, otherwise
92447** return YY_NO_ACTION.
92448*/
92449static int yy_find_reduce_action(
92450  int stateno,              /* Current state number */
92451  YYCODETYPE iLookAhead     /* The look-ahead token */
92452){
92453  int i;
92454#ifdef YYERRORSYMBOL
92455  if( stateno>YY_REDUCE_COUNT ){
92456    return yy_default[stateno];
92457  }
92458#else
92459  assert( stateno<=YY_REDUCE_COUNT );
92460#endif
92461  i = yy_reduce_ofst[stateno];
92462  assert( i!=YY_REDUCE_USE_DFLT );
92463  assert( iLookAhead!=YYNOCODE );
92464  i += iLookAhead;
92465#ifdef YYERRORSYMBOL
92466  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
92467    return yy_default[stateno];
92468  }
92469#else
92470  assert( i>=0 && i<YY_ACTTAB_COUNT );
92471  assert( yy_lookahead[i]==iLookAhead );
92472#endif
92473  return yy_action[i];
92474}
92475
92476/*
92477** The following routine is called if the stack overflows.
92478*/
92479static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
92480   sqlite3ParserARG_FETCH;
92481   yypParser->yyidx--;
92482#ifndef NDEBUG
92483   if( yyTraceFILE ){
92484     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
92485   }
92486#endif
92487   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
92488   /* Here code is inserted which will execute if the parser
92489   ** stack every overflows */
92490
92491  UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
92492  sqlite3ErrorMsg(pParse, "parser stack overflow");
92493  pParse->parseError = 1;
92494   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
92495}
92496
92497/*
92498** Perform a shift action.
92499*/
92500static void yy_shift(
92501  yyParser *yypParser,          /* The parser to be shifted */
92502  int yyNewState,               /* The new state to shift in */
92503  int yyMajor,                  /* The major token to shift in */
92504  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
92505){
92506  yyStackEntry *yytos;
92507  yypParser->yyidx++;
92508#ifdef YYTRACKMAXSTACKDEPTH
92509  if( yypParser->yyidx>yypParser->yyidxMax ){
92510    yypParser->yyidxMax = yypParser->yyidx;
92511  }
92512#endif
92513#if YYSTACKDEPTH>0
92514  if( yypParser->yyidx>=YYSTACKDEPTH ){
92515    yyStackOverflow(yypParser, yypMinor);
92516    return;
92517  }
92518#else
92519  if( yypParser->yyidx>=yypParser->yystksz ){
92520    yyGrowStack(yypParser);
92521    if( yypParser->yyidx>=yypParser->yystksz ){
92522      yyStackOverflow(yypParser, yypMinor);
92523      return;
92524    }
92525  }
92526#endif
92527  yytos = &yypParser->yystack[yypParser->yyidx];
92528  yytos->stateno = (YYACTIONTYPE)yyNewState;
92529  yytos->major = (YYCODETYPE)yyMajor;
92530  yytos->minor = *yypMinor;
92531#ifndef NDEBUG
92532  if( yyTraceFILE && yypParser->yyidx>0 ){
92533    int i;
92534    fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
92535    fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
92536    for(i=1; i<=yypParser->yyidx; i++)
92537      fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
92538    fprintf(yyTraceFILE,"\n");
92539  }
92540#endif
92541}
92542
92543/* The following table contains information about every rule that
92544** is used during the reduce.
92545*/
92546static const struct {
92547  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
92548  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
92549} yyRuleInfo[] = {
92550  { 142, 1 },
92551  { 143, 2 },
92552  { 143, 1 },
92553  { 144, 1 },
92554  { 144, 3 },
92555  { 145, 0 },
92556  { 145, 1 },
92557  { 145, 3 },
92558  { 146, 1 },
92559  { 147, 3 },
92560  { 149, 0 },
92561  { 149, 1 },
92562  { 149, 2 },
92563  { 148, 0 },
92564  { 148, 1 },
92565  { 148, 1 },
92566  { 148, 1 },
92567  { 147, 2 },
92568  { 147, 2 },
92569  { 147, 2 },
92570  { 151, 1 },
92571  { 151, 0 },
92572  { 147, 2 },
92573  { 147, 3 },
92574  { 147, 5 },
92575  { 147, 2 },
92576  { 152, 6 },
92577  { 154, 1 },
92578  { 156, 0 },
92579  { 156, 3 },
92580  { 155, 1 },
92581  { 155, 0 },
92582  { 153, 4 },
92583  { 153, 2 },
92584  { 158, 3 },
92585  { 158, 1 },
92586  { 161, 3 },
92587  { 162, 1 },
92588  { 165, 1 },
92589  { 165, 1 },
92590  { 166, 1 },
92591  { 150, 1 },
92592  { 150, 1 },
92593  { 150, 1 },
92594  { 163, 0 },
92595  { 163, 1 },
92596  { 167, 1 },
92597  { 167, 4 },
92598  { 167, 6 },
92599  { 168, 1 },
92600  { 168, 2 },
92601  { 169, 1 },
92602  { 169, 1 },
92603  { 164, 2 },
92604  { 164, 0 },
92605  { 172, 3 },
92606  { 172, 1 },
92607  { 173, 2 },
92608  { 173, 4 },
92609  { 173, 3 },
92610  { 173, 3 },
92611  { 173, 2 },
92612  { 173, 2 },
92613  { 173, 3 },
92614  { 173, 5 },
92615  { 173, 2 },
92616  { 173, 4 },
92617  { 173, 4 },
92618  { 173, 1 },
92619  { 173, 2 },
92620  { 178, 0 },
92621  { 178, 1 },
92622  { 180, 0 },
92623  { 180, 2 },
92624  { 182, 2 },
92625  { 182, 3 },
92626  { 182, 3 },
92627  { 182, 3 },
92628  { 183, 2 },
92629  { 183, 2 },
92630  { 183, 1 },
92631  { 183, 1 },
92632  { 183, 2 },
92633  { 181, 3 },
92634  { 181, 2 },
92635  { 184, 0 },
92636  { 184, 2 },
92637  { 184, 2 },
92638  { 159, 0 },
92639  { 159, 2 },
92640  { 185, 3 },
92641  { 185, 2 },
92642  { 185, 1 },
92643  { 186, 2 },
92644  { 186, 7 },
92645  { 186, 5 },
92646  { 186, 5 },
92647  { 186, 10 },
92648  { 188, 0 },
92649  { 188, 1 },
92650  { 176, 0 },
92651  { 176, 3 },
92652  { 189, 0 },
92653  { 189, 2 },
92654  { 190, 1 },
92655  { 190, 1 },
92656  { 190, 1 },
92657  { 147, 4 },
92658  { 192, 2 },
92659  { 192, 0 },
92660  { 147, 8 },
92661  { 147, 4 },
92662  { 147, 1 },
92663  { 160, 1 },
92664  { 160, 3 },
92665  { 195, 1 },
92666  { 195, 2 },
92667  { 195, 1 },
92668  { 194, 9 },
92669  { 196, 1 },
92670  { 196, 1 },
92671  { 196, 0 },
92672  { 204, 2 },
92673  { 204, 0 },
92674  { 197, 3 },
92675  { 197, 2 },
92676  { 197, 4 },
92677  { 205, 2 },
92678  { 205, 1 },
92679  { 205, 0 },
92680  { 198, 0 },
92681  { 198, 2 },
92682  { 207, 2 },
92683  { 207, 0 },
92684  { 206, 7 },
92685  { 206, 7 },
92686  { 206, 7 },
92687  { 157, 0 },
92688  { 157, 2 },
92689  { 193, 2 },
92690  { 208, 1 },
92691  { 208, 2 },
92692  { 208, 3 },
92693  { 208, 4 },
92694  { 210, 2 },
92695  { 210, 0 },
92696  { 209, 0 },
92697  { 209, 3 },
92698  { 209, 2 },
92699  { 211, 4 },
92700  { 211, 0 },
92701  { 202, 0 },
92702  { 202, 3 },
92703  { 214, 4 },
92704  { 214, 2 },
92705  { 215, 1 },
92706  { 177, 1 },
92707  { 177, 1 },
92708  { 177, 0 },
92709  { 200, 0 },
92710  { 200, 3 },
92711  { 201, 0 },
92712  { 201, 2 },
92713  { 203, 0 },
92714  { 203, 2 },
92715  { 203, 4 },
92716  { 203, 4 },
92717  { 147, 5 },
92718  { 199, 0 },
92719  { 199, 2 },
92720  { 147, 7 },
92721  { 217, 5 },
92722  { 217, 3 },
92723  { 147, 8 },
92724  { 147, 5 },
92725  { 147, 6 },
92726  { 218, 2 },
92727  { 218, 1 },
92728  { 220, 3 },
92729  { 220, 1 },
92730  { 219, 0 },
92731  { 219, 3 },
92732  { 213, 3 },
92733  { 213, 1 },
92734  { 175, 1 },
92735  { 175, 3 },
92736  { 174, 1 },
92737  { 175, 1 },
92738  { 175, 1 },
92739  { 175, 3 },
92740  { 175, 5 },
92741  { 174, 1 },
92742  { 174, 1 },
92743  { 175, 1 },
92744  { 175, 1 },
92745  { 175, 3 },
92746  { 175, 6 },
92747  { 175, 5 },
92748  { 175, 4 },
92749  { 174, 1 },
92750  { 175, 3 },
92751  { 175, 3 },
92752  { 175, 3 },
92753  { 175, 3 },
92754  { 175, 3 },
92755  { 175, 3 },
92756  { 175, 3 },
92757  { 175, 3 },
92758  { 222, 1 },
92759  { 222, 2 },
92760  { 222, 1 },
92761  { 222, 2 },
92762  { 223, 2 },
92763  { 223, 0 },
92764  { 175, 4 },
92765  { 175, 2 },
92766  { 175, 3 },
92767  { 175, 3 },
92768  { 175, 4 },
92769  { 175, 2 },
92770  { 175, 2 },
92771  { 175, 2 },
92772  { 175, 2 },
92773  { 224, 1 },
92774  { 224, 2 },
92775  { 175, 5 },
92776  { 225, 1 },
92777  { 225, 2 },
92778  { 175, 5 },
92779  { 175, 3 },
92780  { 175, 5 },
92781  { 175, 4 },
92782  { 175, 4 },
92783  { 175, 5 },
92784  { 227, 5 },
92785  { 227, 4 },
92786  { 228, 2 },
92787  { 228, 0 },
92788  { 226, 1 },
92789  { 226, 0 },
92790  { 221, 1 },
92791  { 221, 0 },
92792  { 216, 3 },
92793  { 216, 1 },
92794  { 147, 11 },
92795  { 229, 1 },
92796  { 229, 0 },
92797  { 179, 0 },
92798  { 179, 3 },
92799  { 187, 5 },
92800  { 187, 3 },
92801  { 230, 0 },
92802  { 230, 2 },
92803  { 147, 4 },
92804  { 147, 1 },
92805  { 147, 2 },
92806  { 147, 3 },
92807  { 147, 5 },
92808  { 147, 6 },
92809  { 147, 5 },
92810  { 147, 6 },
92811  { 231, 1 },
92812  { 231, 1 },
92813  { 231, 1 },
92814  { 231, 1 },
92815  { 231, 1 },
92816  { 170, 2 },
92817  { 171, 2 },
92818  { 233, 1 },
92819  { 232, 1 },
92820  { 232, 0 },
92821  { 147, 5 },
92822  { 234, 11 },
92823  { 236, 1 },
92824  { 236, 1 },
92825  { 236, 2 },
92826  { 236, 0 },
92827  { 237, 1 },
92828  { 237, 1 },
92829  { 237, 3 },
92830  { 238, 0 },
92831  { 238, 3 },
92832  { 239, 0 },
92833  { 239, 2 },
92834  { 235, 3 },
92835  { 235, 2 },
92836  { 241, 1 },
92837  { 241, 3 },
92838  { 242, 0 },
92839  { 242, 3 },
92840  { 242, 2 },
92841  { 240, 7 },
92842  { 240, 8 },
92843  { 240, 5 },
92844  { 240, 5 },
92845  { 240, 1 },
92846  { 175, 4 },
92847  { 175, 6 },
92848  { 191, 1 },
92849  { 191, 1 },
92850  { 191, 1 },
92851  { 147, 4 },
92852  { 147, 6 },
92853  { 147, 3 },
92854  { 244, 0 },
92855  { 244, 2 },
92856  { 243, 1 },
92857  { 243, 0 },
92858  { 147, 1 },
92859  { 147, 3 },
92860  { 147, 1 },
92861  { 147, 3 },
92862  { 147, 6 },
92863  { 147, 6 },
92864  { 245, 1 },
92865  { 246, 0 },
92866  { 246, 1 },
92867  { 147, 1 },
92868  { 147, 4 },
92869  { 247, 7 },
92870  { 248, 1 },
92871  { 248, 3 },
92872  { 249, 0 },
92873  { 249, 2 },
92874  { 250, 1 },
92875  { 250, 3 },
92876  { 251, 1 },
92877  { 252, 0 },
92878  { 252, 4 },
92879  { 252, 2 },
92880};
92881
92882static void yy_accept(yyParser*);  /* Forward Declaration */
92883
92884/*
92885** Perform a reduce action and the shift that must immediately
92886** follow the reduce.
92887*/
92888static void yy_reduce(
92889  yyParser *yypParser,         /* The parser */
92890  int yyruleno                 /* Number of the rule by which to reduce */
92891){
92892  int yygoto;                     /* The next state */
92893  int yyact;                      /* The next action */
92894  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
92895  yyStackEntry *yymsp;            /* The top of the parser's stack */
92896  int yysize;                     /* Amount to pop the stack */
92897  sqlite3ParserARG_FETCH;
92898  yymsp = &yypParser->yystack[yypParser->yyidx];
92899#ifndef NDEBUG
92900  if( yyTraceFILE && yyruleno>=0
92901        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
92902    fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
92903      yyRuleName[yyruleno]);
92904  }
92905#endif /* NDEBUG */
92906
92907  /* Silence complaints from purify about yygotominor being uninitialized
92908  ** in some cases when it is copied into the stack after the following
92909  ** switch.  yygotominor is uninitialized when a rule reduces that does
92910  ** not set the value of its left-hand side nonterminal.  Leaving the
92911  ** value of the nonterminal uninitialized is utterly harmless as long
92912  ** as the value is never used.  So really the only thing this code
92913  ** accomplishes is to quieten purify.
92914  **
92915  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
92916  ** without this code, their parser segfaults.  I'm not sure what there
92917  ** parser is doing to make this happen.  This is the second bug report
92918  ** from wireshark this week.  Clearly they are stressing Lemon in ways
92919  ** that it has not been previously stressed...  (SQLite ticket #2172)
92920  */
92921  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
92922  yygotominor = yyzerominor;
92923
92924
92925  switch( yyruleno ){
92926  /* Beginning here are the reduction cases.  A typical example
92927  ** follows:
92928  **   case 0:
92929  **  #line <lineno> <grammarfile>
92930  **     { ... }           // User supplied code
92931  **  #line <lineno> <thisfile>
92932  **     break;
92933  */
92934      case 5: /* explain ::= */
92935{ sqlite3BeginParse(pParse, 0); }
92936        break;
92937      case 6: /* explain ::= EXPLAIN */
92938{ sqlite3BeginParse(pParse, 1); }
92939        break;
92940      case 7: /* explain ::= EXPLAIN QUERY PLAN */
92941{ sqlite3BeginParse(pParse, 2); }
92942        break;
92943      case 8: /* cmdx ::= cmd */
92944{ sqlite3FinishCoding(pParse); }
92945        break;
92946      case 9: /* cmd ::= BEGIN transtype trans_opt */
92947{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
92948        break;
92949      case 13: /* transtype ::= */
92950{yygotominor.yy328 = TK_DEFERRED;}
92951        break;
92952      case 14: /* transtype ::= DEFERRED */
92953      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
92954      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
92955      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
92956      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
92957{yygotominor.yy328 = yymsp[0].major;}
92958        break;
92959      case 17: /* cmd ::= COMMIT trans_opt */
92960      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
92961{sqlite3CommitTransaction(pParse);}
92962        break;
92963      case 19: /* cmd ::= ROLLBACK trans_opt */
92964{sqlite3RollbackTransaction(pParse);}
92965        break;
92966      case 22: /* cmd ::= SAVEPOINT nm */
92967{
92968  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
92969}
92970        break;
92971      case 23: /* cmd ::= RELEASE savepoint_opt nm */
92972{
92973  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
92974}
92975        break;
92976      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
92977{
92978  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
92979}
92980        break;
92981      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
92982{
92983   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
92984}
92985        break;
92986      case 27: /* createkw ::= CREATE */
92987{
92988  pParse->db->lookaside.bEnabled = 0;
92989  yygotominor.yy0 = yymsp[0].minor.yy0;
92990}
92991        break;
92992      case 28: /* ifnotexists ::= */
92993      case 31: /* temp ::= */ yytestcase(yyruleno==31);
92994      case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
92995      case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
92996      case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
92997      case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
92998      case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
92999      case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
93000      case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
93001      case 121: /* distinct ::= */ yytestcase(yyruleno==121);
93002      case 223: /* between_op ::= BETWEEN */ yytestcase(yyruleno==223);
93003      case 226: /* in_op ::= IN */ yytestcase(yyruleno==226);
93004{yygotominor.yy328 = 0;}
93005        break;
93006      case 29: /* ifnotexists ::= IF NOT EXISTS */
93007      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
93008      case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
93009      case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
93010      case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
93011      case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
93012      case 224: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==224);
93013      case 227: /* in_op ::= NOT IN */ yytestcase(yyruleno==227);
93014{yygotominor.yy328 = 1;}
93015        break;
93016      case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
93017{
93018  sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
93019}
93020        break;
93021      case 33: /* create_table_args ::= AS select */
93022{
93023  sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy3);
93024  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
93025}
93026        break;
93027      case 36: /* column ::= columnid type carglist */
93028{
93029  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
93030  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
93031}
93032        break;
93033      case 37: /* columnid ::= nm */
93034{
93035  sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
93036  yygotominor.yy0 = yymsp[0].minor.yy0;
93037}
93038        break;
93039      case 38: /* id ::= ID */
93040      case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
93041      case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
93042      case 41: /* nm ::= id */ yytestcase(yyruleno==41);
93043      case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
93044      case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
93045      case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
93046      case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
93047      case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
93048      case 128: /* as ::= ids */ yytestcase(yyruleno==128);
93049      case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
93050      case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
93051      case 252: /* collate ::= COLLATE ids */ yytestcase(yyruleno==252);
93052      case 261: /* nmnum ::= plus_num */ yytestcase(yyruleno==261);
93053      case 262: /* nmnum ::= nm */ yytestcase(yyruleno==262);
93054      case 263: /* nmnum ::= ON */ yytestcase(yyruleno==263);
93055      case 264: /* nmnum ::= DELETE */ yytestcase(yyruleno==264);
93056      case 265: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==265);
93057      case 266: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==266);
93058      case 267: /* minus_num ::= MINUS number */ yytestcase(yyruleno==267);
93059      case 268: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==268);
93060      case 286: /* trnm ::= nm */ yytestcase(yyruleno==286);
93061{yygotominor.yy0 = yymsp[0].minor.yy0;}
93062        break;
93063      case 45: /* type ::= typetoken */
93064{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
93065        break;
93066      case 47: /* typetoken ::= typename LP signed RP */
93067{
93068  yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
93069  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
93070}
93071        break;
93072      case 48: /* typetoken ::= typename LP signed COMMA signed RP */
93073{
93074  yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
93075  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
93076}
93077        break;
93078      case 50: /* typename ::= typename ids */
93079{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);}
93080        break;
93081      case 57: /* ccons ::= DEFAULT term */
93082      case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
93083{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
93084        break;
93085      case 58: /* ccons ::= DEFAULT LP expr RP */
93086{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
93087        break;
93088      case 60: /* ccons ::= DEFAULT MINUS term */
93089{
93090  ExprSpan v;
93091  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
93092  v.zStart = yymsp[-1].minor.yy0.z;
93093  v.zEnd = yymsp[0].minor.yy346.zEnd;
93094  sqlite3AddDefaultValue(pParse,&v);
93095}
93096        break;
93097      case 61: /* ccons ::= DEFAULT id */
93098{
93099  ExprSpan v;
93100  spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
93101  sqlite3AddDefaultValue(pParse,&v);
93102}
93103        break;
93104      case 63: /* ccons ::= NOT NULL onconf */
93105{sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
93106        break;
93107      case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
93108{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
93109        break;
93110      case 65: /* ccons ::= UNIQUE onconf */
93111{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
93112        break;
93113      case 66: /* ccons ::= CHECK LP expr RP */
93114{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
93115        break;
93116      case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
93117{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
93118        break;
93119      case 68: /* ccons ::= defer_subclause */
93120{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
93121        break;
93122      case 69: /* ccons ::= COLLATE ids */
93123{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
93124        break;
93125      case 72: /* refargs ::= */
93126{ yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
93127        break;
93128      case 73: /* refargs ::= refargs refarg */
93129{ yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
93130        break;
93131      case 74: /* refarg ::= MATCH nm */
93132      case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
93133{ yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
93134        break;
93135      case 76: /* refarg ::= ON DELETE refact */
93136{ yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
93137        break;
93138      case 77: /* refarg ::= ON UPDATE refact */
93139{ yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
93140        break;
93141      case 78: /* refact ::= SET NULL */
93142{ yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
93143        break;
93144      case 79: /* refact ::= SET DEFAULT */
93145{ yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
93146        break;
93147      case 80: /* refact ::= CASCADE */
93148{ yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
93149        break;
93150      case 81: /* refact ::= RESTRICT */
93151{ yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
93152        break;
93153      case 82: /* refact ::= NO ACTION */
93154{ yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
93155        break;
93156      case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
93157      case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
93158      case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
93159      case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
93160{yygotominor.yy328 = yymsp[0].minor.yy328;}
93161        break;
93162      case 88: /* conslist_opt ::= */
93163{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
93164        break;
93165      case 89: /* conslist_opt ::= COMMA conslist */
93166{yygotominor.yy0 = yymsp[-1].minor.yy0;}
93167        break;
93168      case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
93169{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
93170        break;
93171      case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
93172{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
93173        break;
93174      case 96: /* tcons ::= CHECK LP expr RP onconf */
93175{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
93176        break;
93177      case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
93178{
93179    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
93180    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
93181}
93182        break;
93183      case 100: /* onconf ::= */
93184{yygotominor.yy328 = OE_Default;}
93185        break;
93186      case 102: /* orconf ::= */
93187{yygotominor.yy186 = OE_Default;}
93188        break;
93189      case 103: /* orconf ::= OR resolvetype */
93190{yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
93191        break;
93192      case 105: /* resolvetype ::= IGNORE */
93193{yygotominor.yy328 = OE_Ignore;}
93194        break;
93195      case 106: /* resolvetype ::= REPLACE */
93196{yygotominor.yy328 = OE_Replace;}
93197        break;
93198      case 107: /* cmd ::= DROP TABLE ifexists fullname */
93199{
93200  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
93201}
93202        break;
93203      case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
93204{
93205  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);
93206}
93207        break;
93208      case 111: /* cmd ::= DROP VIEW ifexists fullname */
93209{
93210  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
93211}
93212        break;
93213      case 112: /* cmd ::= select */
93214{
93215  SelectDest dest = {SRT_Output, 0, 0, 0, 0};
93216  sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
93217  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
93218}
93219        break;
93220      case 113: /* select ::= oneselect */
93221{yygotominor.yy3 = yymsp[0].minor.yy3;}
93222        break;
93223      case 114: /* select ::= select multiselect_op oneselect */
93224{
93225  if( yymsp[0].minor.yy3 ){
93226    yymsp[0].minor.yy3->op = (u8)yymsp[-1].minor.yy328;
93227    yymsp[0].minor.yy3->pPrior = yymsp[-2].minor.yy3;
93228  }else{
93229    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
93230  }
93231  yygotominor.yy3 = yymsp[0].minor.yy3;
93232}
93233        break;
93234      case 116: /* multiselect_op ::= UNION ALL */
93235{yygotominor.yy328 = TK_ALL;}
93236        break;
93237      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
93238{
93239  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.yy328,yymsp[0].minor.yy476.pLimit,yymsp[0].minor.yy476.pOffset);
93240}
93241        break;
93242      case 122: /* sclp ::= selcollist COMMA */
93243      case 248: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==248);
93244{yygotominor.yy14 = yymsp[-1].minor.yy14;}
93245        break;
93246      case 123: /* sclp ::= */
93247      case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
93248      case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
93249      case 241: /* exprlist ::= */ yytestcase(yyruleno==241);
93250      case 247: /* idxlist_opt ::= */ yytestcase(yyruleno==247);
93251{yygotominor.yy14 = 0;}
93252        break;
93253      case 124: /* selcollist ::= sclp expr as */
93254{
93255   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
93256   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
93257   sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
93258}
93259        break;
93260      case 125: /* selcollist ::= sclp STAR */
93261{
93262  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
93263  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
93264}
93265        break;
93266      case 126: /* selcollist ::= sclp nm DOT STAR */
93267{
93268  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
93269  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
93270  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
93271  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
93272}
93273        break;
93274      case 129: /* as ::= */
93275{yygotominor.yy0.n = 0;}
93276        break;
93277      case 130: /* from ::= */
93278{yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
93279        break;
93280      case 131: /* from ::= FROM seltablist */
93281{
93282  yygotominor.yy65 = yymsp[0].minor.yy65;
93283  sqlite3SrcListShiftJoinType(yygotominor.yy65);
93284}
93285        break;
93286      case 132: /* stl_prefix ::= seltablist joinop */
93287{
93288   yygotominor.yy65 = yymsp[-1].minor.yy65;
93289   if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
93290}
93291        break;
93292      case 133: /* stl_prefix ::= */
93293{yygotominor.yy65 = 0;}
93294        break;
93295      case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
93296{
93297  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);
93298  sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
93299}
93300        break;
93301      case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
93302{
93303    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);
93304  }
93305        break;
93306      case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
93307{
93308    if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
93309      yygotominor.yy65 = yymsp[-4].minor.yy65;
93310    }else{
93311      Select *pSubquery;
93312      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
93313      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,0,0,0);
93314      yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
93315    }
93316  }
93317        break;
93318      case 137: /* dbnm ::= */
93319      case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
93320{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
93321        break;
93322      case 139: /* fullname ::= nm dbnm */
93323{yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
93324        break;
93325      case 140: /* joinop ::= COMMA|JOIN */
93326{ yygotominor.yy328 = JT_INNER; }
93327        break;
93328      case 141: /* joinop ::= JOIN_KW JOIN */
93329{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
93330        break;
93331      case 142: /* joinop ::= JOIN_KW nm JOIN */
93332{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
93333        break;
93334      case 143: /* joinop ::= JOIN_KW nm nm JOIN */
93335{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
93336        break;
93337      case 144: /* on_opt ::= ON expr */
93338      case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
93339      case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
93340      case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
93341      case 236: /* case_else ::= ELSE expr */ yytestcase(yyruleno==236);
93342      case 238: /* case_operand ::= expr */ yytestcase(yyruleno==238);
93343{yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
93344        break;
93345      case 145: /* on_opt ::= */
93346      case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
93347      case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
93348      case 237: /* case_else ::= */ yytestcase(yyruleno==237);
93349      case 239: /* case_operand ::= */ yytestcase(yyruleno==239);
93350{yygotominor.yy132 = 0;}
93351        break;
93352      case 148: /* indexed_opt ::= NOT INDEXED */
93353{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
93354        break;
93355      case 149: /* using_opt ::= USING LP inscollist RP */
93356      case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
93357{yygotominor.yy408 = yymsp[-1].minor.yy408;}
93358        break;
93359      case 150: /* using_opt ::= */
93360      case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
93361{yygotominor.yy408 = 0;}
93362        break;
93363      case 152: /* orderby_opt ::= ORDER BY sortlist */
93364      case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
93365      case 240: /* exprlist ::= nexprlist */ yytestcase(yyruleno==240);
93366{yygotominor.yy14 = yymsp[0].minor.yy14;}
93367        break;
93368      case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
93369{
93370  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy132);
93371  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
93372}
93373        break;
93374      case 154: /* sortlist ::= sortitem sortorder */
93375{
93376  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy132);
93377  if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
93378}
93379        break;
93380      case 156: /* sortorder ::= ASC */
93381      case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
93382{yygotominor.yy328 = SQLITE_SO_ASC;}
93383        break;
93384      case 157: /* sortorder ::= DESC */
93385{yygotominor.yy328 = SQLITE_SO_DESC;}
93386        break;
93387      case 163: /* limit_opt ::= */
93388{yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
93389        break;
93390      case 164: /* limit_opt ::= LIMIT expr */
93391{yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
93392        break;
93393      case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
93394{yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
93395        break;
93396      case 166: /* limit_opt ::= LIMIT expr COMMA expr */
93397{yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
93398        break;
93399      case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
93400{
93401  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
93402  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
93403}
93404        break;
93405      case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
93406{
93407  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
93408  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
93409  sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
93410}
93411        break;
93412      case 171: /* setlist ::= setlist COMMA nm EQ expr */
93413{
93414  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
93415  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
93416}
93417        break;
93418      case 172: /* setlist ::= nm EQ expr */
93419{
93420  yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
93421  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
93422}
93423        break;
93424      case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
93425{sqlite3Insert(pParse, yymsp[-5].minor.yy65, yymsp[-1].minor.yy14, 0, yymsp[-4].minor.yy408, yymsp[-7].minor.yy186);}
93426        break;
93427      case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
93428{sqlite3Insert(pParse, yymsp[-2].minor.yy65, 0, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);}
93429        break;
93430      case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
93431{sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);}
93432        break;
93433      case 176: /* insert_cmd ::= INSERT orconf */
93434{yygotominor.yy186 = yymsp[0].minor.yy186;}
93435        break;
93436      case 177: /* insert_cmd ::= REPLACE */
93437{yygotominor.yy186 = OE_Replace;}
93438        break;
93439      case 178: /* itemlist ::= itemlist COMMA expr */
93440      case 242: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==242);
93441{yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
93442        break;
93443      case 179: /* itemlist ::= expr */
93444      case 243: /* nexprlist ::= expr */ yytestcase(yyruleno==243);
93445{yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
93446        break;
93447      case 182: /* inscollist ::= inscollist COMMA nm */
93448{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
93449        break;
93450      case 183: /* inscollist ::= nm */
93451{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
93452        break;
93453      case 184: /* expr ::= term */
93454      case 212: /* escape ::= ESCAPE expr */ yytestcase(yyruleno==212);
93455{yygotominor.yy346 = yymsp[0].minor.yy346;}
93456        break;
93457      case 185: /* expr ::= LP expr RP */
93458{yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
93459        break;
93460      case 186: /* term ::= NULL */
93461      case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
93462      case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
93463{spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
93464        break;
93465      case 187: /* expr ::= id */
93466      case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
93467{spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
93468        break;
93469      case 189: /* expr ::= nm DOT nm */
93470{
93471  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
93472  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
93473  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
93474  spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
93475}
93476        break;
93477      case 190: /* expr ::= nm DOT nm DOT nm */
93478{
93479  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
93480  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
93481  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
93482  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
93483  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
93484  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
93485}
93486        break;
93487      case 193: /* expr ::= REGISTER */
93488{
93489  /* When doing a nested parse, one can include terms in an expression
93490  ** that look like this:   #1 #2 ...  These terms refer to registers
93491  ** in the virtual machine.  #N is the N-th register. */
93492  if( pParse->nested==0 ){
93493    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
93494    yygotominor.yy346.pExpr = 0;
93495  }else{
93496    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
93497    if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
93498  }
93499  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
93500}
93501        break;
93502      case 194: /* expr ::= VARIABLE */
93503{
93504  spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
93505  sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
93506  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
93507}
93508        break;
93509      case 195: /* expr ::= expr COLLATE ids */
93510{
93511  yygotominor.yy346.pExpr = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
93512  yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
93513  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93514}
93515        break;
93516      case 196: /* expr ::= CAST LP expr AS typetoken RP */
93517{
93518  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
93519  spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
93520}
93521        break;
93522      case 197: /* expr ::= ID LP distinct exprlist RP */
93523{
93524  if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
93525    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
93526  }
93527  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
93528  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
93529  if( yymsp[-2].minor.yy328 && yygotominor.yy346.pExpr ){
93530    yygotominor.yy346.pExpr->flags |= EP_Distinct;
93531  }
93532}
93533        break;
93534      case 198: /* expr ::= ID LP STAR RP */
93535{
93536  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
93537  spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
93538}
93539        break;
93540      case 199: /* term ::= CTIME_KW */
93541{
93542  /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
93543  ** treated as functions that return constants */
93544  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
93545  if( yygotominor.yy346.pExpr ){
93546    yygotominor.yy346.pExpr->op = TK_CONST_FUNC;
93547  }
93548  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
93549}
93550        break;
93551      case 200: /* expr ::= expr AND expr */
93552      case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
93553      case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
93554      case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
93555      case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
93556      case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
93557      case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
93558      case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
93559{spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
93560        break;
93561      case 208: /* likeop ::= LIKE_KW */
93562      case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
93563{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 0;}
93564        break;
93565      case 209: /* likeop ::= NOT LIKE_KW */
93566      case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
93567{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 1;}
93568        break;
93569      case 213: /* escape ::= */
93570{memset(&yygotominor.yy346,0,sizeof(yygotominor.yy346));}
93571        break;
93572      case 214: /* expr ::= expr likeop expr escape */
93573{
93574  ExprList *pList;
93575  pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy346.pExpr);
93576  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy346.pExpr);
93577  if( yymsp[0].minor.yy346.pExpr ){
93578    pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
93579  }
93580  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy96.eOperator);
93581  if( yymsp[-2].minor.yy96.not ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93582  yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
93583  yygotominor.yy346.zEnd = yymsp[-1].minor.yy346.zEnd;
93584  if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
93585}
93586        break;
93587      case 215: /* expr ::= expr ISNULL|NOTNULL */
93588{spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
93589        break;
93590      case 216: /* expr ::= expr NOT NULL */
93591{spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
93592        break;
93593      case 217: /* expr ::= expr IS expr */
93594{
93595  spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
93596  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
93597}
93598        break;
93599      case 218: /* expr ::= expr IS NOT expr */
93600{
93601  spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
93602  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
93603}
93604        break;
93605      case 219: /* expr ::= NOT expr */
93606      case 220: /* expr ::= BITNOT expr */ yytestcase(yyruleno==220);
93607{spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
93608        break;
93609      case 221: /* expr ::= MINUS expr */
93610{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
93611        break;
93612      case 222: /* expr ::= PLUS expr */
93613{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
93614        break;
93615      case 225: /* expr ::= expr between_op expr AND expr */
93616{
93617  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
93618  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
93619  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
93620  if( yygotominor.yy346.pExpr ){
93621    yygotominor.yy346.pExpr->x.pList = pList;
93622  }else{
93623    sqlite3ExprListDelete(pParse->db, pList);
93624  }
93625  if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93626  yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
93627  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
93628}
93629        break;
93630      case 228: /* expr ::= expr in_op LP exprlist RP */
93631{
93632    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
93633    if( yygotominor.yy346.pExpr ){
93634      yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
93635      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93636    }else{
93637      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
93638    }
93639    if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93640    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
93641    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93642  }
93643        break;
93644      case 229: /* expr ::= LP select RP */
93645{
93646    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
93647    if( yygotominor.yy346.pExpr ){
93648      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
93649      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
93650      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93651    }else{
93652      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
93653    }
93654    yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
93655    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93656  }
93657        break;
93658      case 230: /* expr ::= expr in_op LP select RP */
93659{
93660    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
93661    if( yygotominor.yy346.pExpr ){
93662      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
93663      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
93664      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93665    }else{
93666      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
93667    }
93668    if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93669    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
93670    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93671  }
93672        break;
93673      case 231: /* expr ::= expr in_op nm dbnm */
93674{
93675    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
93676    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
93677    if( yygotominor.yy346.pExpr ){
93678      yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
93679      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
93680      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93681    }else{
93682      sqlite3SrcListDelete(pParse->db, pSrc);
93683    }
93684    if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93685    yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
93686    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];
93687  }
93688        break;
93689      case 232: /* expr ::= EXISTS LP select RP */
93690{
93691    Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
93692    if( p ){
93693      p->x.pSelect = yymsp[-1].minor.yy3;
93694      ExprSetProperty(p, EP_xIsSelect);
93695      sqlite3ExprSetHeight(pParse, p);
93696    }else{
93697      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
93698    }
93699    yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
93700    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93701  }
93702        break;
93703      case 233: /* expr ::= CASE case_operand case_exprlist case_else END */
93704{
93705  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, yymsp[-1].minor.yy132, 0);
93706  if( yygotominor.yy346.pExpr ){
93707    yygotominor.yy346.pExpr->x.pList = yymsp[-2].minor.yy14;
93708    sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93709  }else{
93710    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
93711  }
93712  yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
93713  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93714}
93715        break;
93716      case 234: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
93717{
93718  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
93719  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
93720}
93721        break;
93722      case 235: /* case_exprlist ::= WHEN expr THEN expr */
93723{
93724  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
93725  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
93726}
93727        break;
93728      case 244: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
93729{
93730  sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
93731                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy14, yymsp[-9].minor.yy328,
93732                      &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy328);
93733}
93734        break;
93735      case 245: /* uniqueflag ::= UNIQUE */
93736      case 299: /* raisetype ::= ABORT */ yytestcase(yyruleno==299);
93737{yygotominor.yy328 = OE_Abort;}
93738        break;
93739      case 246: /* uniqueflag ::= */
93740{yygotominor.yy328 = OE_None;}
93741        break;
93742      case 249: /* idxlist ::= idxlist COMMA nm collate sortorder */
93743{
93744  Expr *p = 0;
93745  if( yymsp[-1].minor.yy0.n>0 ){
93746    p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
93747    sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
93748  }
93749  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
93750  sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
93751  sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
93752  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
93753}
93754        break;
93755      case 250: /* idxlist ::= nm collate sortorder */
93756{
93757  Expr *p = 0;
93758  if( yymsp[-1].minor.yy0.n>0 ){
93759    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
93760    sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
93761  }
93762  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
93763  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
93764  sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
93765  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
93766}
93767        break;
93768      case 251: /* collate ::= */
93769{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
93770        break;
93771      case 253: /* cmd ::= DROP INDEX ifexists fullname */
93772{sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
93773        break;
93774      case 254: /* cmd ::= VACUUM */
93775      case 255: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==255);
93776{sqlite3Vacuum(pParse);}
93777        break;
93778      case 256: /* cmd ::= PRAGMA nm dbnm */
93779{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
93780        break;
93781      case 257: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
93782{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
93783        break;
93784      case 258: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
93785{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
93786        break;
93787      case 259: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
93788{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
93789        break;
93790      case 260: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
93791{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
93792        break;
93793      case 271: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
93794{
93795  Token all;
93796  all.z = yymsp[-3].minor.yy0.z;
93797  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
93798  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
93799}
93800        break;
93801      case 272: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
93802{
93803  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);
93804  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
93805}
93806        break;
93807      case 273: /* trigger_time ::= BEFORE */
93808      case 276: /* trigger_time ::= */ yytestcase(yyruleno==276);
93809{ yygotominor.yy328 = TK_BEFORE; }
93810        break;
93811      case 274: /* trigger_time ::= AFTER */
93812{ yygotominor.yy328 = TK_AFTER;  }
93813        break;
93814      case 275: /* trigger_time ::= INSTEAD OF */
93815{ yygotominor.yy328 = TK_INSTEAD;}
93816        break;
93817      case 277: /* trigger_event ::= DELETE|INSERT */
93818      case 278: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==278);
93819{yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
93820        break;
93821      case 279: /* trigger_event ::= UPDATE OF inscollist */
93822{yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
93823        break;
93824      case 282: /* when_clause ::= */
93825      case 304: /* key_opt ::= */ yytestcase(yyruleno==304);
93826{ yygotominor.yy132 = 0; }
93827        break;
93828      case 283: /* when_clause ::= WHEN expr */
93829      case 305: /* key_opt ::= KEY expr */ yytestcase(yyruleno==305);
93830{ yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
93831        break;
93832      case 284: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
93833{
93834  assert( yymsp[-2].minor.yy473!=0 );
93835  yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
93836  yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
93837  yygotominor.yy473 = yymsp[-2].minor.yy473;
93838}
93839        break;
93840      case 285: /* trigger_cmd_list ::= trigger_cmd SEMI */
93841{
93842  assert( yymsp[-1].minor.yy473!=0 );
93843  yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
93844  yygotominor.yy473 = yymsp[-1].minor.yy473;
93845}
93846        break;
93847      case 287: /* trnm ::= nm DOT nm */
93848{
93849  yygotominor.yy0 = yymsp[0].minor.yy0;
93850  sqlite3ErrorMsg(pParse,
93851        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
93852        "statements within triggers");
93853}
93854        break;
93855      case 289: /* tridxby ::= INDEXED BY nm */
93856{
93857  sqlite3ErrorMsg(pParse,
93858        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
93859        "within triggers");
93860}
93861        break;
93862      case 290: /* tridxby ::= NOT INDEXED */
93863{
93864  sqlite3ErrorMsg(pParse,
93865        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
93866        "within triggers");
93867}
93868        break;
93869      case 291: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
93870{ yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
93871        break;
93872      case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
93873{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy408, yymsp[-1].minor.yy14, 0, yymsp[-7].minor.yy186);}
93874        break;
93875      case 293: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
93876{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, 0, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
93877        break;
93878      case 294: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
93879{yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
93880        break;
93881      case 295: /* trigger_cmd ::= select */
93882{yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
93883        break;
93884      case 296: /* expr ::= RAISE LP IGNORE RP */
93885{
93886  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
93887  if( yygotominor.yy346.pExpr ){
93888    yygotominor.yy346.pExpr->affinity = OE_Ignore;
93889  }
93890  yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
93891  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93892}
93893        break;
93894      case 297: /* expr ::= RAISE LP raisetype COMMA nm RP */
93895{
93896  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
93897  if( yygotominor.yy346.pExpr ) {
93898    yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
93899  }
93900  yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
93901  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93902}
93903        break;
93904      case 298: /* raisetype ::= ROLLBACK */
93905{yygotominor.yy328 = OE_Rollback;}
93906        break;
93907      case 300: /* raisetype ::= FAIL */
93908{yygotominor.yy328 = OE_Fail;}
93909        break;
93910      case 301: /* cmd ::= DROP TRIGGER ifexists fullname */
93911{
93912  sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
93913}
93914        break;
93915      case 302: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
93916{
93917  sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
93918}
93919        break;
93920      case 303: /* cmd ::= DETACH database_kw_opt expr */
93921{
93922  sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
93923}
93924        break;
93925      case 308: /* cmd ::= REINDEX */
93926{sqlite3Reindex(pParse, 0, 0);}
93927        break;
93928      case 309: /* cmd ::= REINDEX nm dbnm */
93929{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
93930        break;
93931      case 310: /* cmd ::= ANALYZE */
93932{sqlite3Analyze(pParse, 0, 0);}
93933        break;
93934      case 311: /* cmd ::= ANALYZE nm dbnm */
93935{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
93936        break;
93937      case 312: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
93938{
93939  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
93940}
93941        break;
93942      case 313: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
93943{
93944  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
93945}
93946        break;
93947      case 314: /* add_column_fullname ::= fullname */
93948{
93949  pParse->db->lookaside.bEnabled = 0;
93950  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
93951}
93952        break;
93953      case 317: /* cmd ::= create_vtab */
93954{sqlite3VtabFinishParse(pParse,0);}
93955        break;
93956      case 318: /* cmd ::= create_vtab LP vtabarglist RP */
93957{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
93958        break;
93959      case 319: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
93960{
93961    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
93962}
93963        break;
93964      case 322: /* vtabarg ::= */
93965{sqlite3VtabArgInit(pParse);}
93966        break;
93967      case 324: /* vtabargtoken ::= ANY */
93968      case 325: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==325);
93969      case 326: /* lp ::= LP */ yytestcase(yyruleno==326);
93970{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
93971        break;
93972      default:
93973      /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
93974      /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
93975      /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
93976      /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
93977      /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
93978      /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
93979      /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
93980      /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
93981      /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
93982      /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
93983      /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
93984      /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
93985      /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
93986      /* (44) type ::= */ yytestcase(yyruleno==44);
93987      /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
93988      /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
93989      /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
93990      /* (54) carglist ::= */ yytestcase(yyruleno==54);
93991      /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
93992      /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
93993      /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
93994      /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
93995      /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
93996      /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
93997      /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
93998      /* (269) plus_opt ::= PLUS */ yytestcase(yyruleno==269);
93999      /* (270) plus_opt ::= */ yytestcase(yyruleno==270);
94000      /* (280) foreach_clause ::= */ yytestcase(yyruleno==280);
94001      /* (281) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==281);
94002      /* (288) tridxby ::= */ yytestcase(yyruleno==288);
94003      /* (306) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==306);
94004      /* (307) database_kw_opt ::= */ yytestcase(yyruleno==307);
94005      /* (315) kwcolumn_opt ::= */ yytestcase(yyruleno==315);
94006      /* (316) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==316);
94007      /* (320) vtabarglist ::= vtabarg */ yytestcase(yyruleno==320);
94008      /* (321) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==321);
94009      /* (323) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==323);
94010      /* (327) anylist ::= */ yytestcase(yyruleno==327);
94011      /* (328) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==328);
94012      /* (329) anylist ::= anylist ANY */ yytestcase(yyruleno==329);
94013        break;
94014  };
94015  yygoto = yyRuleInfo[yyruleno].lhs;
94016  yysize = yyRuleInfo[yyruleno].nrhs;
94017  yypParser->yyidx -= yysize;
94018  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
94019  if( yyact < YYNSTATE ){
94020#ifdef NDEBUG
94021    /* If we are not debugging and the reduce action popped at least
94022    ** one element off the stack, then we can push the new element back
94023    ** onto the stack here, and skip the stack overflow test in yy_shift().
94024    ** That gives a significant speed improvement. */
94025    if( yysize ){
94026      yypParser->yyidx++;
94027      yymsp -= yysize-1;
94028      yymsp->stateno = (YYACTIONTYPE)yyact;
94029      yymsp->major = (YYCODETYPE)yygoto;
94030      yymsp->minor = yygotominor;
94031    }else
94032#endif
94033    {
94034      yy_shift(yypParser,yyact,yygoto,&yygotominor);
94035    }
94036  }else{
94037    assert( yyact == YYNSTATE + YYNRULE + 1 );
94038    yy_accept(yypParser);
94039  }
94040}
94041
94042/*
94043** The following code executes when the parse fails
94044*/
94045#ifndef YYNOERRORRECOVERY
94046static void yy_parse_failed(
94047  yyParser *yypParser           /* The parser */
94048){
94049  sqlite3ParserARG_FETCH;
94050#ifndef NDEBUG
94051  if( yyTraceFILE ){
94052    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
94053  }
94054#endif
94055  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
94056  /* Here code is inserted which will be executed whenever the
94057  ** parser fails */
94058  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
94059}
94060#endif /* YYNOERRORRECOVERY */
94061
94062/*
94063** The following code executes when a syntax error first occurs.
94064*/
94065static void yy_syntax_error(
94066  yyParser *yypParser,           /* The parser */
94067  int yymajor,                   /* The major type of the error token */
94068  YYMINORTYPE yyminor            /* The minor type of the error token */
94069){
94070  sqlite3ParserARG_FETCH;
94071#define TOKEN (yyminor.yy0)
94072
94073  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
94074  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
94075  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
94076  pParse->parseError = 1;
94077  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
94078}
94079
94080/*
94081** The following is executed when the parser accepts
94082*/
94083static void yy_accept(
94084  yyParser *yypParser           /* The parser */
94085){
94086  sqlite3ParserARG_FETCH;
94087#ifndef NDEBUG
94088  if( yyTraceFILE ){
94089    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
94090  }
94091#endif
94092  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
94093  /* Here code is inserted which will be executed whenever the
94094  ** parser accepts */
94095  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
94096}
94097
94098/* The main parser program.
94099** The first argument is a pointer to a structure obtained from
94100** "sqlite3ParserAlloc" which describes the current state of the parser.
94101** The second argument is the major token number.  The third is
94102** the minor token.  The fourth optional argument is whatever the
94103** user wants (and specified in the grammar) and is available for
94104** use by the action routines.
94105**
94106** Inputs:
94107** <ul>
94108** <li> A pointer to the parser (an opaque structure.)
94109** <li> The major token number.
94110** <li> The minor token number.
94111** <li> An option argument of a grammar-specified type.
94112** </ul>
94113**
94114** Outputs:
94115** None.
94116*/
94117SQLITE_PRIVATE void sqlite3Parser(
94118  void *yyp,                   /* The parser */
94119  int yymajor,                 /* The major token code number */
94120  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
94121  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
94122){
94123  YYMINORTYPE yyminorunion;
94124  int yyact;            /* The parser action. */
94125  int yyendofinput;     /* True if we are at the end of input */
94126#ifdef YYERRORSYMBOL
94127  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
94128#endif
94129  yyParser *yypParser;  /* The parser */
94130
94131  /* (re)initialize the parser, if necessary */
94132  yypParser = (yyParser*)yyp;
94133  if( yypParser->yyidx<0 ){
94134#if YYSTACKDEPTH<=0
94135    if( yypParser->yystksz <=0 ){
94136      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
94137      yyminorunion = yyzerominor;
94138      yyStackOverflow(yypParser, &yyminorunion);
94139      return;
94140    }
94141#endif
94142    yypParser->yyidx = 0;
94143    yypParser->yyerrcnt = -1;
94144    yypParser->yystack[0].stateno = 0;
94145    yypParser->yystack[0].major = 0;
94146  }
94147  yyminorunion.yy0 = yyminor;
94148  yyendofinput = (yymajor==0);
94149  sqlite3ParserARG_STORE;
94150
94151#ifndef NDEBUG
94152  if( yyTraceFILE ){
94153    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
94154  }
94155#endif
94156
94157  do{
94158    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
94159    if( yyact<YYNSTATE ){
94160      assert( !yyendofinput );  /* Impossible to shift the $ token */
94161      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
94162      yypParser->yyerrcnt--;
94163      yymajor = YYNOCODE;
94164    }else if( yyact < YYNSTATE + YYNRULE ){
94165      yy_reduce(yypParser,yyact-YYNSTATE);
94166    }else{
94167      assert( yyact == YY_ERROR_ACTION );
94168#ifdef YYERRORSYMBOL
94169      int yymx;
94170#endif
94171#ifndef NDEBUG
94172      if( yyTraceFILE ){
94173        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
94174      }
94175#endif
94176#ifdef YYERRORSYMBOL
94177      /* A syntax error has occurred.
94178      ** The response to an error depends upon whether or not the
94179      ** grammar defines an error token "ERROR".
94180      **
94181      ** This is what we do if the grammar does define ERROR:
94182      **
94183      **  * Call the %syntax_error function.
94184      **
94185      **  * Begin popping the stack until we enter a state where
94186      **    it is legal to shift the error symbol, then shift
94187      **    the error symbol.
94188      **
94189      **  * Set the error count to three.
94190      **
94191      **  * Begin accepting and shifting new tokens.  No new error
94192      **    processing will occur until three tokens have been
94193      **    shifted successfully.
94194      **
94195      */
94196      if( yypParser->yyerrcnt<0 ){
94197        yy_syntax_error(yypParser,yymajor,yyminorunion);
94198      }
94199      yymx = yypParser->yystack[yypParser->yyidx].major;
94200      if( yymx==YYERRORSYMBOL || yyerrorhit ){
94201#ifndef NDEBUG
94202        if( yyTraceFILE ){
94203          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
94204             yyTracePrompt,yyTokenName[yymajor]);
94205        }
94206#endif
94207        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
94208        yymajor = YYNOCODE;
94209      }else{
94210         while(
94211          yypParser->yyidx >= 0 &&
94212          yymx != YYERRORSYMBOL &&
94213          (yyact = yy_find_reduce_action(
94214                        yypParser->yystack[yypParser->yyidx].stateno,
94215                        YYERRORSYMBOL)) >= YYNSTATE
94216        ){
94217          yy_pop_parser_stack(yypParser);
94218        }
94219        if( yypParser->yyidx < 0 || yymajor==0 ){
94220          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
94221          yy_parse_failed(yypParser);
94222          yymajor = YYNOCODE;
94223        }else if( yymx!=YYERRORSYMBOL ){
94224          YYMINORTYPE u2;
94225          u2.YYERRSYMDT = 0;
94226          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
94227        }
94228      }
94229      yypParser->yyerrcnt = 3;
94230      yyerrorhit = 1;
94231#elif defined(YYNOERRORRECOVERY)
94232      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
94233      ** do any kind of error recovery.  Instead, simply invoke the syntax
94234      ** error routine and continue going as if nothing had happened.
94235      **
94236      ** Applications can set this macro (for example inside %include) if
94237      ** they intend to abandon the parse upon the first syntax error seen.
94238      */
94239      yy_syntax_error(yypParser,yymajor,yyminorunion);
94240      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
94241      yymajor = YYNOCODE;
94242
94243#else  /* YYERRORSYMBOL is not defined */
94244      /* This is what we do if the grammar does not define ERROR:
94245      **
94246      **  * Report an error message, and throw away the input token.
94247      **
94248      **  * If the input token is $, then fail the parse.
94249      **
94250      ** As before, subsequent error messages are suppressed until
94251      ** three input tokens have been successfully shifted.
94252      */
94253      if( yypParser->yyerrcnt<=0 ){
94254        yy_syntax_error(yypParser,yymajor,yyminorunion);
94255      }
94256      yypParser->yyerrcnt = 3;
94257      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
94258      if( yyendofinput ){
94259        yy_parse_failed(yypParser);
94260      }
94261      yymajor = YYNOCODE;
94262#endif
94263    }
94264  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
94265  return;
94266}
94267
94268/************** End of parse.c ***********************************************/
94269/************** Begin file tokenize.c ****************************************/
94270/*
94271** 2001 September 15
94272**
94273** The author disclaims copyright to this source code.  In place of
94274** a legal notice, here is a blessing:
94275**
94276**    May you do good and not evil.
94277**    May you find forgiveness for yourself and forgive others.
94278**    May you share freely, never taking more than you give.
94279**
94280*************************************************************************
94281** An tokenizer for SQL
94282**
94283** This file contains C code that splits an SQL input string up into
94284** individual tokens and sends those tokens one-by-one over to the
94285** parser for analysis.
94286*/
94287
94288/*
94289** The charMap() macro maps alphabetic characters into their
94290** lower-case ASCII equivalent.  On ASCII machines, this is just
94291** an upper-to-lower case map.  On EBCDIC machines we also need
94292** to adjust the encoding.  Only alphabetic characters and underscores
94293** need to be translated.
94294*/
94295#ifdef SQLITE_ASCII
94296# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
94297#endif
94298#ifdef SQLITE_EBCDIC
94299# define charMap(X) ebcdicToAscii[(unsigned char)X]
94300const unsigned char ebcdicToAscii[] = {
94301/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
94302   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
94303   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
94304   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
94305   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
94306   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
94307   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
94308   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
94309   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
94310   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
94311   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
94312   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
94313   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
94314   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
94315   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
94316   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
94317   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
94318};
94319#endif
94320
94321/*
94322** The sqlite3KeywordCode function looks up an identifier to determine if
94323** it is a keyword.  If it is a keyword, the token code of that keyword is
94324** returned.  If the input is not a keyword, TK_ID is returned.
94325**
94326** The implementation of this routine was generated by a program,
94327** mkkeywordhash.h, located in the tool subdirectory of the distribution.
94328** The output of the mkkeywordhash.c program is written into a file
94329** named keywordhash.h and then included into this source file by
94330** the #include below.
94331*/
94332/************** Include keywordhash.h in the middle of tokenize.c ************/
94333/************** Begin file keywordhash.h *************************************/
94334/***** This file contains automatically generated code ******
94335**
94336** The code in this file has been automatically generated by
94337**
94338**   sqlite/tool/mkkeywordhash.c
94339**
94340** The code in this file implements a function that determines whether
94341** or not a given identifier is really an SQL keyword.  The same thing
94342** might be implemented more directly using a hand-written hash table.
94343** But by using this automatically generated code, the size of the code
94344** is substantially reduced.  This is important for embedded applications
94345** on platforms with limited memory.
94346*/
94347/* Hash score: 175 */
94348static int keywordCode(const char *z, int n){
94349  /* zText[] encodes 811 bytes of keywords in 541 bytes */
94350  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
94351  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
94352  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
94353  /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
94354  /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
94355  /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
94356  /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
94357  /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
94358  /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
94359  /*   INITIALLY                                                          */
94360  static const char zText[540] = {
94361    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
94362    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
94363    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
94364    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
94365    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
94366    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
94367    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
94368    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
94369    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
94370    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
94371    'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
94372    'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
94373    'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
94374    'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
94375    'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
94376    'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
94377    'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
94378    'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
94379    'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
94380    'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
94381    'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
94382    'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
94383    'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
94384    'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
94385    'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
94386    'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
94387    'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
94388    'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
94389    'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
94390    'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
94391  };
94392  static const unsigned char aHash[127] = {
94393      72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
94394      42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
94395     118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
94396       0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
94397       0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
94398      92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
94399      96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
94400      39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
94401      58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
94402      29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
94403  };
94404  static const unsigned char aNext[121] = {
94405       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
94406       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
94407       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
94408       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
94409       0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
94410      62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
94411      61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
94412       0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
94413     103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
94414      35,  64,   0,   0,
94415  };
94416  static const unsigned char aLen[121] = {
94417       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
94418       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
94419      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
94420       4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
94421       5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
94422       7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
94423       7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
94424       6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
94425       4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
94426       6,   4,   9,   3,
94427  };
94428  static const unsigned short int aOffset[121] = {
94429       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
94430      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
94431      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
94432     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
94433     203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
94434     248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
94435     326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
94436     387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
94437     462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
94438     521, 527, 531, 536,
94439  };
94440  static const unsigned char aCode[121] = {
94441    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
94442    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
94443    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
94444    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
94445    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
94446    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
94447    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
94448    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
94449    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
94450    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
94451    TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
94452    TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
94453    TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
94454    TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
94455    TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
94456    TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
94457    TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
94458    TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
94459    TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
94460    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
94461    TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
94462    TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
94463    TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
94464    TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
94465    TK_ALL,
94466  };
94467  int h, i;
94468  if( n<2 ) return TK_ID;
94469  h = ((charMap(z[0])*4) ^
94470      (charMap(z[n-1])*3) ^
94471      n) % 127;
94472  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
94473    if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
94474      testcase( i==0 ); /* REINDEX */
94475      testcase( i==1 ); /* INDEXED */
94476      testcase( i==2 ); /* INDEX */
94477      testcase( i==3 ); /* DESC */
94478      testcase( i==4 ); /* ESCAPE */
94479      testcase( i==5 ); /* EACH */
94480      testcase( i==6 ); /* CHECK */
94481      testcase( i==7 ); /* KEY */
94482      testcase( i==8 ); /* BEFORE */
94483      testcase( i==9 ); /* FOREIGN */
94484      testcase( i==10 ); /* FOR */
94485      testcase( i==11 ); /* IGNORE */
94486      testcase( i==12 ); /* REGEXP */
94487      testcase( i==13 ); /* EXPLAIN */
94488      testcase( i==14 ); /* INSTEAD */
94489      testcase( i==15 ); /* ADD */
94490      testcase( i==16 ); /* DATABASE */
94491      testcase( i==17 ); /* AS */
94492      testcase( i==18 ); /* SELECT */
94493      testcase( i==19 ); /* TABLE */
94494      testcase( i==20 ); /* LEFT */
94495      testcase( i==21 ); /* THEN */
94496      testcase( i==22 ); /* END */
94497      testcase( i==23 ); /* DEFERRABLE */
94498      testcase( i==24 ); /* ELSE */
94499      testcase( i==25 ); /* EXCEPT */
94500      testcase( i==26 ); /* TRANSACTION */
94501      testcase( i==27 ); /* ACTION */
94502      testcase( i==28 ); /* ON */
94503      testcase( i==29 ); /* NATURAL */
94504      testcase( i==30 ); /* ALTER */
94505      testcase( i==31 ); /* RAISE */
94506      testcase( i==32 ); /* EXCLUSIVE */
94507      testcase( i==33 ); /* EXISTS */
94508      testcase( i==34 ); /* SAVEPOINT */
94509      testcase( i==35 ); /* INTERSECT */
94510      testcase( i==36 ); /* TRIGGER */
94511      testcase( i==37 ); /* REFERENCES */
94512      testcase( i==38 ); /* CONSTRAINT */
94513      testcase( i==39 ); /* INTO */
94514      testcase( i==40 ); /* OFFSET */
94515      testcase( i==41 ); /* OF */
94516      testcase( i==42 ); /* SET */
94517      testcase( i==43 ); /* TEMPORARY */
94518      testcase( i==44 ); /* TEMP */
94519      testcase( i==45 ); /* OR */
94520      testcase( i==46 ); /* UNIQUE */
94521      testcase( i==47 ); /* QUERY */
94522      testcase( i==48 ); /* ATTACH */
94523      testcase( i==49 ); /* HAVING */
94524      testcase( i==50 ); /* GROUP */
94525      testcase( i==51 ); /* UPDATE */
94526      testcase( i==52 ); /* BEGIN */
94527      testcase( i==53 ); /* INNER */
94528      testcase( i==54 ); /* RELEASE */
94529      testcase( i==55 ); /* BETWEEN */
94530      testcase( i==56 ); /* NOTNULL */
94531      testcase( i==57 ); /* NOT */
94532      testcase( i==58 ); /* NO */
94533      testcase( i==59 ); /* NULL */
94534      testcase( i==60 ); /* LIKE */
94535      testcase( i==61 ); /* CASCADE */
94536      testcase( i==62 ); /* ASC */
94537      testcase( i==63 ); /* DELETE */
94538      testcase( i==64 ); /* CASE */
94539      testcase( i==65 ); /* COLLATE */
94540      testcase( i==66 ); /* CREATE */
94541      testcase( i==67 ); /* CURRENT_DATE */
94542      testcase( i==68 ); /* DETACH */
94543      testcase( i==69 ); /* IMMEDIATE */
94544      testcase( i==70 ); /* JOIN */
94545      testcase( i==71 ); /* INSERT */
94546      testcase( i==72 ); /* MATCH */
94547      testcase( i==73 ); /* PLAN */
94548      testcase( i==74 ); /* ANALYZE */
94549      testcase( i==75 ); /* PRAGMA */
94550      testcase( i==76 ); /* ABORT */
94551      testcase( i==77 ); /* VALUES */
94552      testcase( i==78 ); /* VIRTUAL */
94553      testcase( i==79 ); /* LIMIT */
94554      testcase( i==80 ); /* WHEN */
94555      testcase( i==81 ); /* WHERE */
94556      testcase( i==82 ); /* RENAME */
94557      testcase( i==83 ); /* AFTER */
94558      testcase( i==84 ); /* REPLACE */
94559      testcase( i==85 ); /* AND */
94560      testcase( i==86 ); /* DEFAULT */
94561      testcase( i==87 ); /* AUTOINCREMENT */
94562      testcase( i==88 ); /* TO */
94563      testcase( i==89 ); /* IN */
94564      testcase( i==90 ); /* CAST */
94565      testcase( i==91 ); /* COLUMN */
94566      testcase( i==92 ); /* COMMIT */
94567      testcase( i==93 ); /* CONFLICT */
94568      testcase( i==94 ); /* CROSS */
94569      testcase( i==95 ); /* CURRENT_TIMESTAMP */
94570      testcase( i==96 ); /* CURRENT_TIME */
94571      testcase( i==97 ); /* PRIMARY */
94572      testcase( i==98 ); /* DEFERRED */
94573      testcase( i==99 ); /* DISTINCT */
94574      testcase( i==100 ); /* IS */
94575      testcase( i==101 ); /* DROP */
94576      testcase( i==102 ); /* FAIL */
94577      testcase( i==103 ); /* FROM */
94578      testcase( i==104 ); /* FULL */
94579      testcase( i==105 ); /* GLOB */
94580      testcase( i==106 ); /* BY */
94581      testcase( i==107 ); /* IF */
94582      testcase( i==108 ); /* ISNULL */
94583      testcase( i==109 ); /* ORDER */
94584      testcase( i==110 ); /* RESTRICT */
94585      testcase( i==111 ); /* OUTER */
94586      testcase( i==112 ); /* RIGHT */
94587      testcase( i==113 ); /* ROLLBACK */
94588      testcase( i==114 ); /* ROW */
94589      testcase( i==115 ); /* UNION */
94590      testcase( i==116 ); /* USING */
94591      testcase( i==117 ); /* VACUUM */
94592      testcase( i==118 ); /* VIEW */
94593      testcase( i==119 ); /* INITIALLY */
94594      testcase( i==120 ); /* ALL */
94595      return aCode[i];
94596    }
94597  }
94598  return TK_ID;
94599}
94600SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
94601  return keywordCode((char*)z, n);
94602}
94603#define SQLITE_N_KEYWORD 121
94604
94605/************** End of keywordhash.h *****************************************/
94606/************** Continuing where we left off in tokenize.c *******************/
94607
94608
94609/*
94610** If X is a character that can be used in an identifier then
94611** IdChar(X) will be true.  Otherwise it is false.
94612**
94613** For ASCII, any character with the high-order bit set is
94614** allowed in an identifier.  For 7-bit characters,
94615** sqlite3IsIdChar[X] must be 1.
94616**
94617** For EBCDIC, the rules are more complex but have the same
94618** end result.
94619**
94620** Ticket #1066.  the SQL standard does not allow '$' in the
94621** middle of identfiers.  But many SQL implementations do.
94622** SQLite will allow '$' in identifiers for compatibility.
94623** But the feature is undocumented.
94624*/
94625#ifdef SQLITE_ASCII
94626#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
94627#endif
94628#ifdef SQLITE_EBCDIC
94629SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
94630/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
94631    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
94632    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
94633    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
94634    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
94635    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
94636    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
94637    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
94638    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
94639    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
94640    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
94641    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
94642    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
94643};
94644#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
94645#endif
94646
94647
94648/*
94649** Return the length of the token that begins at z[0].
94650** Store the token type in *tokenType before returning.
94651*/
94652SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
94653  int i, c;
94654  switch( *z ){
94655    case ' ': case '\t': case '\n': case '\f': case '\r': {
94656      testcase( z[0]==' ' );
94657      testcase( z[0]=='\t' );
94658      testcase( z[0]=='\n' );
94659      testcase( z[0]=='\f' );
94660      testcase( z[0]=='\r' );
94661      for(i=1; sqlite3Isspace(z[i]); i++){}
94662      *tokenType = TK_SPACE;
94663      return i;
94664    }
94665    case '-': {
94666      if( z[1]=='-' ){
94667        /* IMP: R-15891-05542 -- syntax diagram for comments */
94668        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
94669        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
94670        return i;
94671      }
94672      *tokenType = TK_MINUS;
94673      return 1;
94674    }
94675    case '(': {
94676      *tokenType = TK_LP;
94677      return 1;
94678    }
94679    case ')': {
94680      *tokenType = TK_RP;
94681      return 1;
94682    }
94683    case ';': {
94684      *tokenType = TK_SEMI;
94685      return 1;
94686    }
94687    case '+': {
94688      *tokenType = TK_PLUS;
94689      return 1;
94690    }
94691    case '*': {
94692      *tokenType = TK_STAR;
94693      return 1;
94694    }
94695    case '/': {
94696      if( z[1]!='*' || z[2]==0 ){
94697        *tokenType = TK_SLASH;
94698        return 1;
94699      }
94700      /* IMP: R-15891-05542 -- syntax diagram for comments */
94701      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
94702      if( c ) i++;
94703      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
94704      return i;
94705    }
94706    case '%': {
94707      *tokenType = TK_REM;
94708      return 1;
94709    }
94710    case '=': {
94711      *tokenType = TK_EQ;
94712      return 1 + (z[1]=='=');
94713    }
94714    case '<': {
94715      if( (c=z[1])=='=' ){
94716        *tokenType = TK_LE;
94717        return 2;
94718      }else if( c=='>' ){
94719        *tokenType = TK_NE;
94720        return 2;
94721      }else if( c=='<' ){
94722        *tokenType = TK_LSHIFT;
94723        return 2;
94724      }else{
94725        *tokenType = TK_LT;
94726        return 1;
94727      }
94728    }
94729    case '>': {
94730      if( (c=z[1])=='=' ){
94731        *tokenType = TK_GE;
94732        return 2;
94733      }else if( c=='>' ){
94734        *tokenType = TK_RSHIFT;
94735        return 2;
94736      }else{
94737        *tokenType = TK_GT;
94738        return 1;
94739      }
94740    }
94741    case '!': {
94742      if( z[1]!='=' ){
94743        *tokenType = TK_ILLEGAL;
94744        return 2;
94745      }else{
94746        *tokenType = TK_NE;
94747        return 2;
94748      }
94749    }
94750    case '|': {
94751      if( z[1]!='|' ){
94752        *tokenType = TK_BITOR;
94753        return 1;
94754      }else{
94755        *tokenType = TK_CONCAT;
94756        return 2;
94757      }
94758    }
94759    case ',': {
94760      *tokenType = TK_COMMA;
94761      return 1;
94762    }
94763    case '&': {
94764      *tokenType = TK_BITAND;
94765      return 1;
94766    }
94767    case '~': {
94768      *tokenType = TK_BITNOT;
94769      return 1;
94770    }
94771    case '`':
94772    case '\'':
94773    case '"': {
94774      int delim = z[0];
94775      testcase( delim=='`' );
94776      testcase( delim=='\'' );
94777      testcase( delim=='"' );
94778      for(i=1; (c=z[i])!=0; i++){
94779        if( c==delim ){
94780          if( z[i+1]==delim ){
94781            i++;
94782          }else{
94783            break;
94784          }
94785        }
94786      }
94787      if( c=='\'' ){
94788        *tokenType = TK_STRING;
94789        return i+1;
94790      }else if( c!=0 ){
94791        *tokenType = TK_ID;
94792        return i+1;
94793      }else{
94794        *tokenType = TK_ILLEGAL;
94795        return i;
94796      }
94797    }
94798    case '.': {
94799#ifndef SQLITE_OMIT_FLOATING_POINT
94800      if( !sqlite3Isdigit(z[1]) )
94801#endif
94802      {
94803        *tokenType = TK_DOT;
94804        return 1;
94805      }
94806      /* If the next character is a digit, this is a floating point
94807      ** number that begins with ".".  Fall thru into the next case */
94808    }
94809    case '0': case '1': case '2': case '3': case '4':
94810    case '5': case '6': case '7': case '8': case '9': {
94811      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
94812      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
94813      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
94814      testcase( z[0]=='9' );
94815      *tokenType = TK_INTEGER;
94816      for(i=0; sqlite3Isdigit(z[i]); i++){}
94817#ifndef SQLITE_OMIT_FLOATING_POINT
94818      if( z[i]=='.' ){
94819        i++;
94820        while( sqlite3Isdigit(z[i]) ){ i++; }
94821        *tokenType = TK_FLOAT;
94822      }
94823      if( (z[i]=='e' || z[i]=='E') &&
94824           ( sqlite3Isdigit(z[i+1])
94825            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
94826           )
94827      ){
94828        i += 2;
94829        while( sqlite3Isdigit(z[i]) ){ i++; }
94830        *tokenType = TK_FLOAT;
94831      }
94832#endif
94833      while( IdChar(z[i]) ){
94834        *tokenType = TK_ILLEGAL;
94835        i++;
94836      }
94837      return i;
94838    }
94839    case '[': {
94840      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
94841      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
94842      return i;
94843    }
94844    case '?': {
94845      *tokenType = TK_VARIABLE;
94846      for(i=1; sqlite3Isdigit(z[i]); i++){}
94847      return i;
94848    }
94849    case '#': {
94850      for(i=1; sqlite3Isdigit(z[i]); i++){}
94851      if( i>1 ){
94852        /* Parameters of the form #NNN (where NNN is a number) are used
94853        ** internally by sqlite3NestedParse.  */
94854        *tokenType = TK_REGISTER;
94855        return i;
94856      }
94857      /* Fall through into the next case if the '#' is not followed by
94858      ** a digit. Try to match #AAAA where AAAA is a parameter name. */
94859    }
94860#ifndef SQLITE_OMIT_TCL_VARIABLE
94861    case '$':
94862#endif
94863    case '@':  /* For compatibility with MS SQL Server */
94864    case ':': {
94865      int n = 0;
94866      testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
94867      *tokenType = TK_VARIABLE;
94868      for(i=1; (c=z[i])!=0; i++){
94869        if( IdChar(c) ){
94870          n++;
94871#ifndef SQLITE_OMIT_TCL_VARIABLE
94872        }else if( c=='(' && n>0 ){
94873          do{
94874            i++;
94875          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
94876          if( c==')' ){
94877            i++;
94878          }else{
94879            *tokenType = TK_ILLEGAL;
94880          }
94881          break;
94882        }else if( c==':' && z[i+1]==':' ){
94883          i++;
94884#endif
94885        }else{
94886          break;
94887        }
94888      }
94889      if( n==0 ) *tokenType = TK_ILLEGAL;
94890      return i;
94891    }
94892#ifndef SQLITE_OMIT_BLOB_LITERAL
94893    case 'x': case 'X': {
94894      testcase( z[0]=='x' ); testcase( z[0]=='X' );
94895      if( z[1]=='\'' ){
94896        *tokenType = TK_BLOB;
94897        for(i=2; (c=z[i])!=0 && c!='\''; i++){
94898          if( !sqlite3Isxdigit(c) ){
94899            *tokenType = TK_ILLEGAL;
94900          }
94901        }
94902        if( i%2 || !c ) *tokenType = TK_ILLEGAL;
94903        if( c ) i++;
94904        return i;
94905      }
94906      /* Otherwise fall through to the next case */
94907    }
94908#endif
94909    default: {
94910      if( !IdChar(*z) ){
94911        break;
94912      }
94913      for(i=1; IdChar(z[i]); i++){}
94914      *tokenType = keywordCode((char*)z, i);
94915      return i;
94916    }
94917  }
94918  *tokenType = TK_ILLEGAL;
94919  return 1;
94920}
94921
94922/*
94923** Run the parser on the given SQL string.  The parser structure is
94924** passed in.  An SQLITE_ status code is returned.  If an error occurs
94925** then an and attempt is made to write an error message into
94926** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
94927** error message.
94928*/
94929SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
94930  int nErr = 0;                   /* Number of errors encountered */
94931  int i;                          /* Loop counter */
94932  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
94933  int tokenType;                  /* type of the next token */
94934  int lastTokenParsed = -1;       /* type of the previous token */
94935  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
94936  sqlite3 *db = pParse->db;       /* The database connection */
94937  int mxSqlLen;                   /* Max length of an SQL string */
94938
94939
94940  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
94941  if( db->activeVdbeCnt==0 ){
94942    db->u1.isInterrupted = 0;
94943  }
94944  pParse->rc = SQLITE_OK;
94945  pParse->zTail = zSql;
94946  i = 0;
94947  assert( pzErrMsg!=0 );
94948  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
94949  if( pEngine==0 ){
94950    db->mallocFailed = 1;
94951    return SQLITE_NOMEM;
94952  }
94953  assert( pParse->pNewTable==0 );
94954  assert( pParse->pNewTrigger==0 );
94955  assert( pParse->nVar==0 );
94956  assert( pParse->nVarExpr==0 );
94957  assert( pParse->nVarExprAlloc==0 );
94958  assert( pParse->apVarExpr==0 );
94959  enableLookaside = db->lookaside.bEnabled;
94960  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
94961  while( !db->mallocFailed && zSql[i]!=0 ){
94962    assert( i>=0 );
94963    pParse->sLastToken.z = &zSql[i];
94964    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
94965    i += pParse->sLastToken.n;
94966    if( i>mxSqlLen ){
94967      pParse->rc = SQLITE_TOOBIG;
94968      break;
94969    }
94970    switch( tokenType ){
94971      case TK_SPACE: {
94972        if( db->u1.isInterrupted ){
94973          sqlite3ErrorMsg(pParse, "interrupt");
94974          pParse->rc = SQLITE_INTERRUPT;
94975          goto abort_parse;
94976        }
94977        break;
94978      }
94979      case TK_ILLEGAL: {
94980        sqlite3DbFree(db, *pzErrMsg);
94981        *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
94982                        &pParse->sLastToken);
94983        nErr++;
94984        goto abort_parse;
94985      }
94986      case TK_SEMI: {
94987        pParse->zTail = &zSql[i];
94988        /* Fall thru into the default case */
94989      }
94990      default: {
94991        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
94992        lastTokenParsed = tokenType;
94993        if( pParse->rc!=SQLITE_OK ){
94994          goto abort_parse;
94995        }
94996        break;
94997      }
94998    }
94999  }
95000abort_parse:
95001  if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
95002    if( lastTokenParsed!=TK_SEMI ){
95003      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
95004      pParse->zTail = &zSql[i];
95005    }
95006    sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
95007  }
95008#ifdef YYTRACKMAXSTACKDEPTH
95009  sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
95010      sqlite3ParserStackPeak(pEngine)
95011  );
95012#endif /* YYDEBUG */
95013  sqlite3ParserFree(pEngine, sqlite3_free);
95014  db->lookaside.bEnabled = enableLookaside;
95015  if( db->mallocFailed ){
95016    pParse->rc = SQLITE_NOMEM;
95017  }
95018  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
95019    sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
95020  }
95021  assert( pzErrMsg!=0 );
95022  if( pParse->zErrMsg ){
95023    *pzErrMsg = pParse->zErrMsg;
95024    sqlite3_log(pParse->rc, "%s", *pzErrMsg);
95025    pParse->zErrMsg = 0;
95026    nErr++;
95027  }
95028  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
95029    sqlite3VdbeDelete(pParse->pVdbe);
95030    pParse->pVdbe = 0;
95031  }
95032#ifndef SQLITE_OMIT_SHARED_CACHE
95033  if( pParse->nested==0 ){
95034    sqlite3DbFree(db, pParse->aTableLock);
95035    pParse->aTableLock = 0;
95036    pParse->nTableLock = 0;
95037  }
95038#endif
95039#ifndef SQLITE_OMIT_VIRTUALTABLE
95040  sqlite3DbFree(db, pParse->apVtabLock);
95041#endif
95042
95043  if( !IN_DECLARE_VTAB ){
95044    /* If the pParse->declareVtab flag is set, do not delete any table
95045    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
95046    ** will take responsibility for freeing the Table structure.
95047    */
95048    sqlite3DeleteTable(pParse->pNewTable);
95049  }
95050
95051  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
95052  sqlite3DbFree(db, pParse->apVarExpr);
95053  sqlite3DbFree(db, pParse->aAlias);
95054  while( pParse->pAinc ){
95055    AutoincInfo *p = pParse->pAinc;
95056    pParse->pAinc = p->pNext;
95057    sqlite3DbFree(db, p);
95058  }
95059  while( pParse->pZombieTab ){
95060    Table *p = pParse->pZombieTab;
95061    pParse->pZombieTab = p->pNextZombie;
95062    sqlite3DeleteTable(p);
95063  }
95064  if( nErr>0 && pParse->rc==SQLITE_OK ){
95065    pParse->rc = SQLITE_ERROR;
95066  }
95067  return nErr;
95068}
95069
95070/************** End of tokenize.c ********************************************/
95071/************** Begin file complete.c ****************************************/
95072/*
95073** 2001 September 15
95074**
95075** The author disclaims copyright to this source code.  In place of
95076** a legal notice, here is a blessing:
95077**
95078**    May you do good and not evil.
95079**    May you find forgiveness for yourself and forgive others.
95080**    May you share freely, never taking more than you give.
95081**
95082*************************************************************************
95083** An tokenizer for SQL
95084**
95085** This file contains C code that implements the sqlite3_complete() API.
95086** This code used to be part of the tokenizer.c source file.  But by
95087** separating it out, the code will be automatically omitted from
95088** static links that do not use it.
95089*/
95090#ifndef SQLITE_OMIT_COMPLETE
95091
95092/*
95093** This is defined in tokenize.c.  We just have to import the definition.
95094*/
95095#ifndef SQLITE_AMALGAMATION
95096#ifdef SQLITE_ASCII
95097#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
95098#endif
95099#ifdef SQLITE_EBCDIC
95100SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
95101#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
95102#endif
95103#endif /* SQLITE_AMALGAMATION */
95104
95105
95106/*
95107** Token types used by the sqlite3_complete() routine.  See the header
95108** comments on that procedure for additional information.
95109*/
95110#define tkSEMI    0
95111#define tkWS      1
95112#define tkOTHER   2
95113#ifndef SQLITE_OMIT_TRIGGER
95114#define tkEXPLAIN 3
95115#define tkCREATE  4
95116#define tkTEMP    5
95117#define tkTRIGGER 6
95118#define tkEND     7
95119#endif
95120
95121/*
95122** Return TRUE if the given SQL string ends in a semicolon.
95123**
95124** Special handling is require for CREATE TRIGGER statements.
95125** Whenever the CREATE TRIGGER keywords are seen, the statement
95126** must end with ";END;".
95127**
95128** This implementation uses a state machine with 8 states:
95129**
95130**   (0) INVALID   We have not yet seen a non-whitespace character.
95131**
95132**   (1) START     At the beginning or end of an SQL statement.  This routine
95133**                 returns 1 if it ends in the START state and 0 if it ends
95134**                 in any other state.
95135**
95136**   (2) NORMAL    We are in the middle of statement which ends with a single
95137**                 semicolon.
95138**
95139**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
95140**                 a statement.
95141**
95142**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
95143**                 statement, possibly preceeded by EXPLAIN and/or followed by
95144**                 TEMP or TEMPORARY
95145**
95146**   (5) TRIGGER   We are in the middle of a trigger definition that must be
95147**                 ended by a semicolon, the keyword END, and another semicolon.
95148**
95149**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
95150**                 the end of a trigger definition.
95151**
95152**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
95153**                 of a trigger difinition.
95154**
95155** Transitions between states above are determined by tokens extracted
95156** from the input.  The following tokens are significant:
95157**
95158**   (0) tkSEMI      A semicolon.
95159**   (1) tkWS        Whitespace.
95160**   (2) tkOTHER     Any other SQL token.
95161**   (3) tkEXPLAIN   The "explain" keyword.
95162**   (4) tkCREATE    The "create" keyword.
95163**   (5) tkTEMP      The "temp" or "temporary" keyword.
95164**   (6) tkTRIGGER   The "trigger" keyword.
95165**   (7) tkEND       The "end" keyword.
95166**
95167** Whitespace never causes a state transition and is always ignored.
95168** This means that a SQL string of all whitespace is invalid.
95169**
95170** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
95171** to recognize the end of a trigger can be omitted.  All we have to do
95172** is look for a semicolon that is not part of an string or comment.
95173*/
95174SQLITE_API int sqlite3_complete(const char *zSql){
95175  u8 state = 0;   /* Current state, using numbers defined in header comment */
95176  u8 token;       /* Value of the next token */
95177
95178#ifndef SQLITE_OMIT_TRIGGER
95179  /* A complex statement machine used to detect the end of a CREATE TRIGGER
95180  ** statement.  This is the normal case.
95181  */
95182  static const u8 trans[8][8] = {
95183                     /* Token:                                                */
95184     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
95185     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
95186     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
95187     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
95188     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
95189     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
95190     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
95191     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
95192     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
95193  };
95194#else
95195  /* If triggers are not supported by this compile then the statement machine
95196  ** used to detect the end of a statement is much simplier
95197  */
95198  static const u8 trans[3][3] = {
95199                     /* Token:           */
95200     /* State:       **  SEMI  WS  OTHER */
95201     /* 0 INVALID: */ {    1,  0,     2, },
95202     /* 1   START: */ {    1,  1,     2, },
95203     /* 2  NORMAL: */ {    1,  2,     2, },
95204  };
95205#endif /* SQLITE_OMIT_TRIGGER */
95206
95207  while( *zSql ){
95208    switch( *zSql ){
95209      case ';': {  /* A semicolon */
95210        token = tkSEMI;
95211        break;
95212      }
95213      case ' ':
95214      case '\r':
95215      case '\t':
95216      case '\n':
95217      case '\f': {  /* White space is ignored */
95218        token = tkWS;
95219        break;
95220      }
95221      case '/': {   /* C-style comments */
95222        if( zSql[1]!='*' ){
95223          token = tkOTHER;
95224          break;
95225        }
95226        zSql += 2;
95227        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
95228        if( zSql[0]==0 ) return 0;
95229        zSql++;
95230        token = tkWS;
95231        break;
95232      }
95233      case '-': {   /* SQL-style comments from "--" to end of line */
95234        if( zSql[1]!='-' ){
95235          token = tkOTHER;
95236          break;
95237        }
95238        while( *zSql && *zSql!='\n' ){ zSql++; }
95239        if( *zSql==0 ) return state==1;
95240        token = tkWS;
95241        break;
95242      }
95243      case '[': {   /* Microsoft-style identifiers in [...] */
95244        zSql++;
95245        while( *zSql && *zSql!=']' ){ zSql++; }
95246        if( *zSql==0 ) return 0;
95247        token = tkOTHER;
95248        break;
95249      }
95250      case '`':     /* Grave-accent quoted symbols used by MySQL */
95251      case '"':     /* single- and double-quoted strings */
95252      case '\'': {
95253        int c = *zSql;
95254        zSql++;
95255        while( *zSql && *zSql!=c ){ zSql++; }
95256        if( *zSql==0 ) return 0;
95257        token = tkOTHER;
95258        break;
95259      }
95260      default: {
95261#ifdef SQLITE_EBCDIC
95262        unsigned char c;
95263#endif
95264        if( IdChar((u8)*zSql) ){
95265          /* Keywords and unquoted identifiers */
95266          int nId;
95267          for(nId=1; IdChar(zSql[nId]); nId++){}
95268#ifdef SQLITE_OMIT_TRIGGER
95269          token = tkOTHER;
95270#else
95271          switch( *zSql ){
95272            case 'c': case 'C': {
95273              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
95274                token = tkCREATE;
95275              }else{
95276                token = tkOTHER;
95277              }
95278              break;
95279            }
95280            case 't': case 'T': {
95281              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
95282                token = tkTRIGGER;
95283              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
95284                token = tkTEMP;
95285              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
95286                token = tkTEMP;
95287              }else{
95288                token = tkOTHER;
95289              }
95290              break;
95291            }
95292            case 'e':  case 'E': {
95293              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
95294                token = tkEND;
95295              }else
95296#ifndef SQLITE_OMIT_EXPLAIN
95297              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
95298                token = tkEXPLAIN;
95299              }else
95300#endif
95301              {
95302                token = tkOTHER;
95303              }
95304              break;
95305            }
95306            default: {
95307              token = tkOTHER;
95308              break;
95309            }
95310          }
95311#endif /* SQLITE_OMIT_TRIGGER */
95312          zSql += nId-1;
95313        }else{
95314          /* Operators and special symbols */
95315          token = tkOTHER;
95316        }
95317        break;
95318      }
95319    }
95320    state = trans[state][token];
95321    zSql++;
95322  }
95323  return state==1;
95324}
95325
95326#ifndef SQLITE_OMIT_UTF16
95327/*
95328** This routine is the same as the sqlite3_complete() routine described
95329** above, except that the parameter is required to be UTF-16 encoded, not
95330** UTF-8.
95331*/
95332SQLITE_API int sqlite3_complete16(const void *zSql){
95333  sqlite3_value *pVal;
95334  char const *zSql8;
95335  int rc = SQLITE_NOMEM;
95336
95337#ifndef SQLITE_OMIT_AUTOINIT
95338  rc = sqlite3_initialize();
95339  if( rc ) return rc;
95340#endif
95341  pVal = sqlite3ValueNew(0);
95342  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
95343  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
95344  if( zSql8 ){
95345    rc = sqlite3_complete(zSql8);
95346  }else{
95347    rc = SQLITE_NOMEM;
95348  }
95349  sqlite3ValueFree(pVal);
95350  return sqlite3ApiExit(0, rc);
95351}
95352#endif /* SQLITE_OMIT_UTF16 */
95353#endif /* SQLITE_OMIT_COMPLETE */
95354
95355/************** End of complete.c ********************************************/
95356/************** Begin file main.c ********************************************/
95357/*
95358** 2001 September 15
95359**
95360** The author disclaims copyright to this source code.  In place of
95361** a legal notice, here is a blessing:
95362**
95363**    May you do good and not evil.
95364**    May you find forgiveness for yourself and forgive others.
95365**    May you share freely, never taking more than you give.
95366**
95367*************************************************************************
95368** Main file for the SQLite library.  The routines in this file
95369** implement the programmer interface to the library.  Routines in
95370** other files are for internal use by SQLite and should not be
95371** accessed by users of the library.
95372*/
95373
95374#ifdef SQLITE_ENABLE_FTS3
95375/************** Include fts3.h in the middle of main.c ***********************/
95376/************** Begin file fts3.h ********************************************/
95377/*
95378** 2006 Oct 10
95379**
95380** The author disclaims copyright to this source code.  In place of
95381** a legal notice, here is a blessing:
95382**
95383**    May you do good and not evil.
95384**    May you find forgiveness for yourself and forgive others.
95385**    May you share freely, never taking more than you give.
95386**
95387******************************************************************************
95388**
95389** This header file is used by programs that want to link against the
95390** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
95391*/
95392
95393#if 0
95394extern "C" {
95395#endif  /* __cplusplus */
95396
95397SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
95398
95399#if 0
95400}  /* extern "C" */
95401#endif  /* __cplusplus */
95402
95403/************** End of fts3.h ************************************************/
95404/************** Continuing where we left off in main.c ***********************/
95405#endif
95406#ifdef SQLITE_ENABLE_RTREE
95407/************** Include rtree.h in the middle of main.c **********************/
95408/************** Begin file rtree.h *******************************************/
95409/*
95410** 2008 May 26
95411**
95412** The author disclaims copyright to this source code.  In place of
95413** a legal notice, here is a blessing:
95414**
95415**    May you do good and not evil.
95416**    May you find forgiveness for yourself and forgive others.
95417**    May you share freely, never taking more than you give.
95418**
95419******************************************************************************
95420**
95421** This header file is used by programs that want to link against the
95422** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
95423*/
95424
95425#if 0
95426extern "C" {
95427#endif  /* __cplusplus */
95428
95429SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
95430
95431#if 0
95432}  /* extern "C" */
95433#endif  /* __cplusplus */
95434
95435/************** End of rtree.h ***********************************************/
95436/************** Continuing where we left off in main.c ***********************/
95437#endif
95438#ifdef SQLITE_ENABLE_ICU
95439/************** Include sqliteicu.h in the middle of main.c ******************/
95440/************** Begin file sqliteicu.h ***************************************/
95441/*
95442** 2008 May 26
95443**
95444** The author disclaims copyright to this source code.  In place of
95445** a legal notice, here is a blessing:
95446**
95447**    May you do good and not evil.
95448**    May you find forgiveness for yourself and forgive others.
95449**    May you share freely, never taking more than you give.
95450**
95451******************************************************************************
95452**
95453** This header file is used by programs that want to link against the
95454** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
95455*/
95456
95457#if 0
95458extern "C" {
95459#endif  /* __cplusplus */
95460
95461SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
95462
95463#if 0
95464}  /* extern "C" */
95465#endif  /* __cplusplus */
95466
95467
95468/************** End of sqliteicu.h *******************************************/
95469/************** Continuing where we left off in main.c ***********************/
95470#endif
95471
95472/*
95473** The version of the library
95474*/
95475#ifndef SQLITE_AMALGAMATION
95476SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
95477#endif
95478SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
95479SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
95480SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
95481SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
95482
95483#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
95484/*
95485** If the following function pointer is not NULL and if
95486** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
95487** I/O active are written using this function.  These messages
95488** are intended for debugging activity only.
95489*/
95490SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
95491#endif
95492
95493/*
95494** If the following global variable points to a string which is the
95495** name of a directory, then that directory will be used to store
95496** temporary files.
95497**
95498** See also the "PRAGMA temp_store_directory" SQL command.
95499*/
95500SQLITE_API char *sqlite3_temp_directory = 0;
95501
95502/*
95503** Initialize SQLite.
95504**
95505** This routine must be called to initialize the memory allocation,
95506** VFS, and mutex subsystems prior to doing any serious work with
95507** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
95508** this routine will be called automatically by key routines such as
95509** sqlite3_open().
95510**
95511** This routine is a no-op except on its very first call for the process,
95512** or for the first call after a call to sqlite3_shutdown.
95513**
95514** The first thread to call this routine runs the initialization to
95515** completion.  If subsequent threads call this routine before the first
95516** thread has finished the initialization process, then the subsequent
95517** threads must block until the first thread finishes with the initialization.
95518**
95519** The first thread might call this routine recursively.  Recursive
95520** calls to this routine should not block, of course.  Otherwise the
95521** initialization process would never complete.
95522**
95523** Let X be the first thread to enter this routine.  Let Y be some other
95524** thread.  Then while the initial invocation of this routine by X is
95525** incomplete, it is required that:
95526**
95527**    *  Calls to this routine from Y must block until the outer-most
95528**       call by X completes.
95529**
95530**    *  Recursive calls to this routine from thread X return immediately
95531**       without blocking.
95532*/
95533SQLITE_API int sqlite3_initialize(void){
95534  sqlite3_mutex *pMaster;                      /* The main static mutex */
95535  int rc;                                      /* Result code */
95536
95537#ifdef SQLITE_OMIT_WSD
95538  rc = sqlite3_wsd_init(4096, 24);
95539  if( rc!=SQLITE_OK ){
95540    return rc;
95541  }
95542#endif
95543
95544  /* If SQLite is already completely initialized, then this call
95545  ** to sqlite3_initialize() should be a no-op.  But the initialization
95546  ** must be complete.  So isInit must not be set until the very end
95547  ** of this routine.
95548  */
95549  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
95550
95551  /* Make sure the mutex subsystem is initialized.  If unable to
95552  ** initialize the mutex subsystem, return early with the error.
95553  ** If the system is so sick that we are unable to allocate a mutex,
95554  ** there is not much SQLite is going to be able to do.
95555  **
95556  ** The mutex subsystem must take care of serializing its own
95557  ** initialization.
95558  */
95559  rc = sqlite3MutexInit();
95560  if( rc ) return rc;
95561
95562  /* Initialize the malloc() system and the recursive pInitMutex mutex.
95563  ** This operation is protected by the STATIC_MASTER mutex.  Note that
95564  ** MutexAlloc() is called for a static mutex prior to initializing the
95565  ** malloc subsystem - this implies that the allocation of a static
95566  ** mutex must not require support from the malloc subsystem.
95567  */
95568  pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
95569  sqlite3_mutex_enter(pMaster);
95570  sqlite3GlobalConfig.isMutexInit = 1;
95571  if( !sqlite3GlobalConfig.isMallocInit ){
95572    rc = sqlite3MallocInit();
95573  }
95574  if( rc==SQLITE_OK ){
95575    sqlite3GlobalConfig.isMallocInit = 1;
95576    if( !sqlite3GlobalConfig.pInitMutex ){
95577      sqlite3GlobalConfig.pInitMutex =
95578           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
95579      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
95580        rc = SQLITE_NOMEM;
95581      }
95582    }
95583  }
95584  if( rc==SQLITE_OK ){
95585    sqlite3GlobalConfig.nRefInitMutex++;
95586  }
95587  sqlite3_mutex_leave(pMaster);
95588
95589  /* If rc is not SQLITE_OK at this point, then either the malloc
95590  ** subsystem could not be initialized or the system failed to allocate
95591  ** the pInitMutex mutex. Return an error in either case.  */
95592  if( rc!=SQLITE_OK ){
95593    return rc;
95594  }
95595
95596  /* Do the rest of the initialization under the recursive mutex so
95597  ** that we will be able to handle recursive calls into
95598  ** sqlite3_initialize().  The recursive calls normally come through
95599  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
95600  ** recursive calls might also be possible.
95601  */
95602  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
95603  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
95604    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
95605    sqlite3GlobalConfig.inProgress = 1;
95606    memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
95607    sqlite3RegisterGlobalFunctions();
95608    if( sqlite3GlobalConfig.isPCacheInit==0 ){
95609      rc = sqlite3PcacheInitialize();
95610    }
95611    if( rc==SQLITE_OK ){
95612      sqlite3GlobalConfig.isPCacheInit = 1;
95613      rc = sqlite3OsInit();
95614    }
95615    if( rc==SQLITE_OK ){
95616      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
95617          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
95618      sqlite3GlobalConfig.isInit = 1;
95619    }
95620    sqlite3GlobalConfig.inProgress = 0;
95621  }
95622  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
95623
95624  /* Go back under the static mutex and clean up the recursive
95625  ** mutex to prevent a resource leak.
95626  */
95627  sqlite3_mutex_enter(pMaster);
95628  sqlite3GlobalConfig.nRefInitMutex--;
95629  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
95630    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
95631    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
95632    sqlite3GlobalConfig.pInitMutex = 0;
95633  }
95634  sqlite3_mutex_leave(pMaster);
95635
95636  /* The following is just a sanity check to make sure SQLite has
95637  ** been compiled correctly.  It is important to run this code, but
95638  ** we don't want to run it too often and soak up CPU cycles for no
95639  ** reason.  So we run it once during initialization.
95640  */
95641#ifndef NDEBUG
95642#ifndef SQLITE_OMIT_FLOATING_POINT
95643  /* This section of code's only "output" is via assert() statements. */
95644  if ( rc==SQLITE_OK ){
95645    u64 x = (((u64)1)<<63)-1;
95646    double y;
95647    assert(sizeof(x)==8);
95648    assert(sizeof(x)==sizeof(y));
95649    memcpy(&y, &x, 8);
95650    assert( sqlite3IsNaN(y) );
95651  }
95652#endif
95653#endif
95654
95655  return rc;
95656}
95657
95658/*
95659** Undo the effects of sqlite3_initialize().  Must not be called while
95660** there are outstanding database connections or memory allocations or
95661** while any part of SQLite is otherwise in use in any thread.  This
95662** routine is not threadsafe.  But it is safe to invoke this routine
95663** on when SQLite is already shut down.  If SQLite is already shut down
95664** when this routine is invoked, then this routine is a harmless no-op.
95665*/
95666SQLITE_API int sqlite3_shutdown(void){
95667  if( sqlite3GlobalConfig.isInit ){
95668    sqlite3_os_end();
95669    sqlite3_reset_auto_extension();
95670    sqlite3GlobalConfig.isInit = 0;
95671  }
95672  if( sqlite3GlobalConfig.isPCacheInit ){
95673    sqlite3PcacheShutdown();
95674    sqlite3GlobalConfig.isPCacheInit = 0;
95675  }
95676  if( sqlite3GlobalConfig.isMallocInit ){
95677    sqlite3MallocEnd();
95678    sqlite3GlobalConfig.isMallocInit = 0;
95679  }
95680  if( sqlite3GlobalConfig.isMutexInit ){
95681    sqlite3MutexEnd();
95682    sqlite3GlobalConfig.isMutexInit = 0;
95683  }
95684
95685  return SQLITE_OK;
95686}
95687
95688/*
95689** This API allows applications to modify the global configuration of
95690** the SQLite library at run-time.
95691**
95692** This routine should only be called when there are no outstanding
95693** database connections or memory allocations.  This routine is not
95694** threadsafe.  Failure to heed these warnings can lead to unpredictable
95695** behavior.
95696*/
95697SQLITE_API int sqlite3_config(int op, ...){
95698  va_list ap;
95699  int rc = SQLITE_OK;
95700
95701  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
95702  ** the SQLite library is in use. */
95703  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
95704
95705  va_start(ap, op);
95706  switch( op ){
95707
95708    /* Mutex configuration options are only available in a threadsafe
95709    ** compile.
95710    */
95711#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
95712    case SQLITE_CONFIG_SINGLETHREAD: {
95713      /* Disable all mutexing */
95714      sqlite3GlobalConfig.bCoreMutex = 0;
95715      sqlite3GlobalConfig.bFullMutex = 0;
95716      break;
95717    }
95718    case SQLITE_CONFIG_MULTITHREAD: {
95719      /* Disable mutexing of database connections */
95720      /* Enable mutexing of core data structures */
95721      sqlite3GlobalConfig.bCoreMutex = 1;
95722      sqlite3GlobalConfig.bFullMutex = 0;
95723      break;
95724    }
95725    case SQLITE_CONFIG_SERIALIZED: {
95726      /* Enable all mutexing */
95727      sqlite3GlobalConfig.bCoreMutex = 1;
95728      sqlite3GlobalConfig.bFullMutex = 1;
95729      break;
95730    }
95731    case SQLITE_CONFIG_MUTEX: {
95732      /* Specify an alternative mutex implementation */
95733      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
95734      break;
95735    }
95736    case SQLITE_CONFIG_GETMUTEX: {
95737      /* Retrieve the current mutex implementation */
95738      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
95739      break;
95740    }
95741#endif
95742
95743
95744    case SQLITE_CONFIG_MALLOC: {
95745      /* Specify an alternative malloc implementation */
95746      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
95747      break;
95748    }
95749    case SQLITE_CONFIG_GETMALLOC: {
95750      /* Retrieve the current malloc() implementation */
95751      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
95752      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
95753      break;
95754    }
95755    case SQLITE_CONFIG_MEMSTATUS: {
95756      /* Enable or disable the malloc status collection */
95757      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
95758      break;
95759    }
95760    case SQLITE_CONFIG_SCRATCH: {
95761      /* Designate a buffer for scratch memory space */
95762      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
95763      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
95764      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
95765      break;
95766    }
95767    case SQLITE_CONFIG_PAGECACHE: {
95768      /* Designate a buffer for page cache memory space */
95769      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
95770      sqlite3GlobalConfig.szPage = va_arg(ap, int);
95771      sqlite3GlobalConfig.nPage = va_arg(ap, int);
95772      break;
95773    }
95774
95775    case SQLITE_CONFIG_PCACHE: {
95776      /* Specify an alternative page cache implementation */
95777      sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
95778      break;
95779    }
95780
95781    case SQLITE_CONFIG_GETPCACHE: {
95782      if( sqlite3GlobalConfig.pcache.xInit==0 ){
95783        sqlite3PCacheSetDefault();
95784      }
95785      *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
95786      break;
95787    }
95788
95789#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
95790    case SQLITE_CONFIG_HEAP: {
95791      /* Designate a buffer for heap memory space */
95792      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
95793      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
95794      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
95795
95796      if( sqlite3GlobalConfig.pHeap==0 ){
95797        /* If the heap pointer is NULL, then restore the malloc implementation
95798        ** back to NULL pointers too.  This will cause the malloc to go
95799        ** back to its default implementation when sqlite3_initialize() is
95800        ** run.
95801        */
95802        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
95803      }else{
95804        /* The heap pointer is not NULL, then install one of the
95805        ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
95806        ** ENABLE_MEMSYS5 is defined, return an error.
95807        */
95808#ifdef SQLITE_ENABLE_MEMSYS3
95809        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
95810#endif
95811#ifdef SQLITE_ENABLE_MEMSYS5
95812        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
95813#endif
95814      }
95815      break;
95816    }
95817#endif
95818
95819    case SQLITE_CONFIG_LOOKASIDE: {
95820      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
95821      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
95822      break;
95823    }
95824
95825    /* Record a pointer to the logger funcction and its first argument.
95826    ** The default is NULL.  Logging is disabled if the function pointer is
95827    ** NULL.
95828    */
95829    case SQLITE_CONFIG_LOG: {
95830      sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
95831      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
95832      break;
95833    }
95834
95835    default: {
95836      rc = SQLITE_ERROR;
95837      break;
95838    }
95839  }
95840  va_end(ap);
95841  return rc;
95842}
95843
95844/*
95845** Set up the lookaside buffers for a database connection.
95846** Return SQLITE_OK on success.
95847** If lookaside is already active, return SQLITE_BUSY.
95848**
95849** The sz parameter is the number of bytes in each lookaside slot.
95850** The cnt parameter is the number of slots.  If pStart is NULL the
95851** space for the lookaside memory is obtained from sqlite3_malloc().
95852** If pStart is not NULL then it is sz*cnt bytes of memory to use for
95853** the lookaside memory.
95854*/
95855static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
95856  void *pStart;
95857  if( db->lookaside.nOut ){
95858    return SQLITE_BUSY;
95859  }
95860  /* Free any existing lookaside buffer for this handle before
95861  ** allocating a new one so we don't have to have space for
95862  ** both at the same time.
95863  */
95864  if( db->lookaside.bMalloced ){
95865    sqlite3_free(db->lookaside.pStart);
95866  }
95867  /* The size of a lookaside slot needs to be larger than a pointer
95868  ** to be useful.
95869  */
95870  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
95871  if( cnt<0 ) cnt = 0;
95872  if( sz==0 || cnt==0 ){
95873    sz = 0;
95874    pStart = 0;
95875  }else if( pBuf==0 ){
95876    sz = ROUND8(sz);
95877    sqlite3BeginBenignMalloc();
95878    pStart = sqlite3Malloc( sz*cnt );
95879    sqlite3EndBenignMalloc();
95880  }else{
95881    sz = ROUNDDOWN8(sz);
95882    pStart = pBuf;
95883  }
95884  db->lookaside.pStart = pStart;
95885  db->lookaside.pFree = 0;
95886  db->lookaside.sz = (u16)sz;
95887  if( pStart ){
95888    int i;
95889    LookasideSlot *p;
95890    assert( sz > (int)sizeof(LookasideSlot*) );
95891    p = (LookasideSlot*)pStart;
95892    for(i=cnt-1; i>=0; i--){
95893      p->pNext = db->lookaside.pFree;
95894      db->lookaside.pFree = p;
95895      p = (LookasideSlot*)&((u8*)p)[sz];
95896    }
95897    db->lookaside.pEnd = p;
95898    db->lookaside.bEnabled = 1;
95899    db->lookaside.bMalloced = pBuf==0 ?1:0;
95900  }else{
95901    db->lookaside.pEnd = 0;
95902    db->lookaside.bEnabled = 0;
95903    db->lookaside.bMalloced = 0;
95904  }
95905  return SQLITE_OK;
95906}
95907
95908/*
95909** Return the mutex associated with a database connection.
95910*/
95911SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
95912  return db->mutex;
95913}
95914
95915/*
95916** Configuration settings for an individual database connection
95917*/
95918SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
95919  va_list ap;
95920  int rc;
95921  va_start(ap, op);
95922  switch( op ){
95923    case SQLITE_DBCONFIG_LOOKASIDE: {
95924      void *pBuf = va_arg(ap, void*);
95925      int sz = va_arg(ap, int);
95926      int cnt = va_arg(ap, int);
95927      rc = setupLookaside(db, pBuf, sz, cnt);
95928      break;
95929    }
95930    default: {
95931      rc = SQLITE_ERROR;
95932      break;
95933    }
95934  }
95935  va_end(ap);
95936  return rc;
95937}
95938
95939
95940/*
95941** Return true if the buffer z[0..n-1] contains all spaces.
95942*/
95943static int allSpaces(const char *z, int n){
95944  while( n>0 && z[n-1]==' ' ){ n--; }
95945  return n==0;
95946}
95947
95948/*
95949** This is the default collating function named "BINARY" which is always
95950** available.
95951**
95952** If the padFlag argument is not NULL then space padding at the end
95953** of strings is ignored.  This implements the RTRIM collation.
95954*/
95955static int binCollFunc(
95956  void *padFlag,
95957  int nKey1, const void *pKey1,
95958  int nKey2, const void *pKey2
95959){
95960  int rc, n;
95961  n = nKey1<nKey2 ? nKey1 : nKey2;
95962  rc = memcmp(pKey1, pKey2, n);
95963  if( rc==0 ){
95964    if( padFlag
95965     && allSpaces(((char*)pKey1)+n, nKey1-n)
95966     && allSpaces(((char*)pKey2)+n, nKey2-n)
95967    ){
95968      /* Leave rc unchanged at 0 */
95969    }else{
95970      rc = nKey1 - nKey2;
95971    }
95972  }
95973  return rc;
95974}
95975
95976/*
95977** Another built-in collating sequence: NOCASE.
95978**
95979** This collating sequence is intended to be used for "case independant
95980** comparison". SQLite's knowledge of upper and lower case equivalents
95981** extends only to the 26 characters used in the English language.
95982**
95983** At the moment there is only a UTF-8 implementation.
95984*/
95985static int nocaseCollatingFunc(
95986  void *NotUsed,
95987  int nKey1, const void *pKey1,
95988  int nKey2, const void *pKey2
95989){
95990  int r = sqlite3StrNICmp(
95991      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
95992  UNUSED_PARAMETER(NotUsed);
95993  if( 0==r ){
95994    r = nKey1-nKey2;
95995  }
95996  return r;
95997}
95998
95999/*
96000** Return the ROWID of the most recent insert
96001*/
96002SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
96003  return db->lastRowid;
96004}
96005
96006/*
96007** Return the number of changes in the most recent call to sqlite3_exec().
96008*/
96009SQLITE_API int sqlite3_changes(sqlite3 *db){
96010  return db->nChange;
96011}
96012
96013/*
96014** Return the number of changes since the database handle was opened.
96015*/
96016SQLITE_API int sqlite3_total_changes(sqlite3 *db){
96017  return db->nTotalChange;
96018}
96019
96020/*
96021** Close all open savepoints. This function only manipulates fields of the
96022** database handle object, it does not close any savepoints that may be open
96023** at the b-tree/pager level.
96024*/
96025SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
96026  while( db->pSavepoint ){
96027    Savepoint *pTmp = db->pSavepoint;
96028    db->pSavepoint = pTmp->pNext;
96029    sqlite3DbFree(db, pTmp);
96030  }
96031  db->nSavepoint = 0;
96032  db->nStatement = 0;
96033  db->isTransactionSavepoint = 0;
96034}
96035
96036/*
96037** Close an existing SQLite database
96038*/
96039SQLITE_API int sqlite3_close(sqlite3 *db){
96040  HashElem *i;
96041  int j;
96042
96043  if( !db ){
96044    return SQLITE_OK;
96045  }
96046  if( !sqlite3SafetyCheckSickOrOk(db) ){
96047    return SQLITE_MISUSE_BKPT;
96048  }
96049  sqlite3_mutex_enter(db->mutex);
96050
96051  sqlite3ResetInternalSchema(db, 0);
96052
96053  /* If a transaction is open, the ResetInternalSchema() call above
96054  ** will not have called the xDisconnect() method on any virtual
96055  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
96056  ** call will do so. We need to do this before the check for active
96057  ** SQL statements below, as the v-table implementation may be storing
96058  ** some prepared statements internally.
96059  */
96060  sqlite3VtabRollback(db);
96061
96062  /* If there are any outstanding VMs, return SQLITE_BUSY. */
96063  if( db->pVdbe ){
96064    sqlite3Error(db, SQLITE_BUSY,
96065        "unable to close due to unfinalised statements");
96066    sqlite3_mutex_leave(db->mutex);
96067    return SQLITE_BUSY;
96068  }
96069  assert( sqlite3SafetyCheckSickOrOk(db) );
96070
96071  for(j=0; j<db->nDb; j++){
96072    Btree *pBt = db->aDb[j].pBt;
96073    if( pBt && sqlite3BtreeIsInBackup(pBt) ){
96074      sqlite3Error(db, SQLITE_BUSY,
96075          "unable to close due to unfinished backup operation");
96076      sqlite3_mutex_leave(db->mutex);
96077      return SQLITE_BUSY;
96078    }
96079  }
96080
96081  /* Free any outstanding Savepoint structures. */
96082  sqlite3CloseSavepoints(db);
96083
96084  for(j=0; j<db->nDb; j++){
96085    struct Db *pDb = &db->aDb[j];
96086    if( pDb->pBt ){
96087      sqlite3BtreeClose(pDb->pBt);
96088      pDb->pBt = 0;
96089      if( j!=1 ){
96090        pDb->pSchema = 0;
96091      }
96092    }
96093  }
96094  sqlite3ResetInternalSchema(db, 0);
96095
96096  /* Tell the code in notify.c that the connection no longer holds any
96097  ** locks and does not require any further unlock-notify callbacks.
96098  */
96099  sqlite3ConnectionClosed(db);
96100
96101  assert( db->nDb<=2 );
96102  assert( db->aDb==db->aDbStatic );
96103  for(j=0; j<ArraySize(db->aFunc.a); j++){
96104    FuncDef *pNext, *pHash, *p;
96105    for(p=db->aFunc.a[j]; p; p=pHash){
96106      pHash = p->pHash;
96107      while( p ){
96108        pNext = p->pNext;
96109        sqlite3DbFree(db, p);
96110        p = pNext;
96111      }
96112    }
96113  }
96114  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
96115    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
96116    /* Invoke any destructors registered for collation sequence user data. */
96117    for(j=0; j<3; j++){
96118      if( pColl[j].xDel ){
96119        pColl[j].xDel(pColl[j].pUser);
96120      }
96121    }
96122    sqlite3DbFree(db, pColl);
96123  }
96124  sqlite3HashClear(&db->aCollSeq);
96125#ifndef SQLITE_OMIT_VIRTUALTABLE
96126  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
96127    Module *pMod = (Module *)sqliteHashData(i);
96128    if( pMod->xDestroy ){
96129      pMod->xDestroy(pMod->pAux);
96130    }
96131    sqlite3DbFree(db, pMod);
96132  }
96133  sqlite3HashClear(&db->aModule);
96134#endif
96135
96136  sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
96137  if( db->pErr ){
96138    sqlite3ValueFree(db->pErr);
96139  }
96140  sqlite3CloseExtensions(db);
96141
96142  db->magic = SQLITE_MAGIC_ERROR;
96143
96144  /* The temp-database schema is allocated differently from the other schema
96145  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
96146  ** So it needs to be freed here. Todo: Why not roll the temp schema into
96147  ** the same sqliteMalloc() as the one that allocates the database
96148  ** structure?
96149  */
96150  sqlite3DbFree(db, db->aDb[1].pSchema);
96151  sqlite3_mutex_leave(db->mutex);
96152  db->magic = SQLITE_MAGIC_CLOSED;
96153  sqlite3_mutex_free(db->mutex);
96154  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
96155  if( db->lookaside.bMalloced ){
96156    sqlite3_free(db->lookaside.pStart);
96157  }
96158  sqlite3_free(db);
96159  return SQLITE_OK;
96160}
96161
96162/*
96163** Rollback all database files.
96164*/
96165SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
96166  int i;
96167  int inTrans = 0;
96168  assert( sqlite3_mutex_held(db->mutex) );
96169  sqlite3BeginBenignMalloc();
96170  for(i=0; i<db->nDb; i++){
96171    if( db->aDb[i].pBt ){
96172      if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
96173        inTrans = 1;
96174      }
96175      sqlite3BtreeRollback(db->aDb[i].pBt);
96176      db->aDb[i].inTrans = 0;
96177    }
96178  }
96179  sqlite3VtabRollback(db);
96180  sqlite3EndBenignMalloc();
96181
96182  if( db->flags&SQLITE_InternChanges ){
96183    sqlite3ExpirePreparedStatements(db);
96184    sqlite3ResetInternalSchema(db, 0);
96185  }
96186
96187  /* Any deferred constraint violations have now been resolved. */
96188  db->nDeferredCons = 0;
96189
96190  /* If one has been configured, invoke the rollback-hook callback */
96191  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
96192    db->xRollbackCallback(db->pRollbackArg);
96193  }
96194}
96195
96196/*
96197** Return a static string that describes the kind of error specified in the
96198** argument.
96199*/
96200SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
96201  static const char* const aMsg[] = {
96202    /* SQLITE_OK          */ "not an error",
96203    /* SQLITE_ERROR       */ "SQL logic error or missing database",
96204    /* SQLITE_INTERNAL    */ 0,
96205    /* SQLITE_PERM        */ "access permission denied",
96206    /* SQLITE_ABORT       */ "callback requested query abort",
96207    /* SQLITE_BUSY        */ "database is locked",
96208    /* SQLITE_LOCKED      */ "database table is locked",
96209    /* SQLITE_NOMEM       */ "out of memory",
96210    /* SQLITE_READONLY    */ "attempt to write a readonly database",
96211    /* SQLITE_INTERRUPT   */ "interrupted",
96212    /* SQLITE_IOERR       */ "disk I/O error",
96213    /* SQLITE_CORRUPT     */ "database disk image is malformed",
96214    /* SQLITE_NOTFOUND    */ 0,
96215    /* SQLITE_FULL        */ "database or disk is full",
96216    /* SQLITE_CANTOPEN    */ "unable to open database file",
96217    /* SQLITE_PROTOCOL    */ 0,
96218    /* SQLITE_EMPTY       */ "table contains no data",
96219    /* SQLITE_SCHEMA      */ "database schema has changed",
96220    /* SQLITE_TOOBIG      */ "string or blob too big",
96221    /* SQLITE_CONSTRAINT  */ "constraint failed",
96222    /* SQLITE_MISMATCH    */ "datatype mismatch",
96223    /* SQLITE_MISUSE      */ "library routine called out of sequence",
96224    /* SQLITE_NOLFS       */ "large file support is disabled",
96225    /* SQLITE_AUTH        */ "authorization denied",
96226    /* SQLITE_FORMAT      */ "auxiliary database format error",
96227    /* SQLITE_RANGE       */ "bind or column index out of range",
96228    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
96229  };
96230  rc &= 0xff;
96231  if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
96232    return aMsg[rc];
96233  }else{
96234    return "unknown error";
96235  }
96236}
96237
96238/*
96239** This routine implements a busy callback that sleeps and tries
96240** again until a timeout value is reached.  The timeout value is
96241** an integer number of milliseconds passed in as the first
96242** argument.
96243*/
96244static int sqliteDefaultBusyCallback(
96245 void *ptr,               /* Database connection */
96246 int count                /* Number of times table has been busy */
96247){
96248#if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
96249  static const u8 delays[] =
96250     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
96251  static const u8 totals[] =
96252     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
96253# define NDELAY (sizeof(delays)/sizeof(delays[0]))
96254  sqlite3 *db = (sqlite3 *)ptr;
96255  int timeout = db->busyTimeout;
96256  int delay, prior;
96257
96258  assert( count>=0 );
96259  if( count < NDELAY ){
96260    delay = delays[count];
96261    prior = totals[count];
96262  }else{
96263    delay = delays[NDELAY-1];
96264    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
96265  }
96266  if( prior + delay > timeout ){
96267    delay = timeout - prior;
96268    if( delay<=0 ) return 0;
96269  }
96270  sqlite3OsSleep(db->pVfs, delay*1000);
96271  return 1;
96272#else
96273  sqlite3 *db = (sqlite3 *)ptr;
96274  int timeout = ((sqlite3 *)ptr)->busyTimeout;
96275  if( (count+1)*1000 > timeout ){
96276    return 0;
96277  }
96278  sqlite3OsSleep(db->pVfs, 1000000);
96279  return 1;
96280#endif
96281}
96282
96283/*
96284** Invoke the given busy handler.
96285**
96286** This routine is called when an operation failed with a lock.
96287** If this routine returns non-zero, the lock is retried.  If it
96288** returns 0, the operation aborts with an SQLITE_BUSY error.
96289*/
96290SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
96291  int rc;
96292  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
96293  rc = p->xFunc(p->pArg, p->nBusy);
96294  if( rc==0 ){
96295    p->nBusy = -1;
96296  }else{
96297    p->nBusy++;
96298  }
96299  return rc;
96300}
96301
96302/*
96303** This routine sets the busy callback for an Sqlite database to the
96304** given callback function with the given argument.
96305*/
96306SQLITE_API int sqlite3_busy_handler(
96307  sqlite3 *db,
96308  int (*xBusy)(void*,int),
96309  void *pArg
96310){
96311  sqlite3_mutex_enter(db->mutex);
96312  db->busyHandler.xFunc = xBusy;
96313  db->busyHandler.pArg = pArg;
96314  db->busyHandler.nBusy = 0;
96315  sqlite3_mutex_leave(db->mutex);
96316  return SQLITE_OK;
96317}
96318
96319#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
96320/*
96321** This routine sets the progress callback for an Sqlite database to the
96322** given callback function with the given argument. The progress callback will
96323** be invoked every nOps opcodes.
96324*/
96325SQLITE_API void sqlite3_progress_handler(
96326  sqlite3 *db,
96327  int nOps,
96328  int (*xProgress)(void*),
96329  void *pArg
96330){
96331  sqlite3_mutex_enter(db->mutex);
96332  if( nOps>0 ){
96333    db->xProgress = xProgress;
96334    db->nProgressOps = nOps;
96335    db->pProgressArg = pArg;
96336  }else{
96337    db->xProgress = 0;
96338    db->nProgressOps = 0;
96339    db->pProgressArg = 0;
96340  }
96341  sqlite3_mutex_leave(db->mutex);
96342}
96343#endif
96344
96345
96346/*
96347** This routine installs a default busy handler that waits for the
96348** specified number of milliseconds before returning 0.
96349*/
96350SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
96351  if( ms>0 ){
96352    db->busyTimeout = ms;
96353    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
96354  }else{
96355    sqlite3_busy_handler(db, 0, 0);
96356  }
96357  return SQLITE_OK;
96358}
96359
96360/*
96361** Cause any pending operation to stop at its earliest opportunity.
96362*/
96363SQLITE_API void sqlite3_interrupt(sqlite3 *db){
96364  db->u1.isInterrupted = 1;
96365}
96366
96367
96368/*
96369** This function is exactly the same as sqlite3_create_function(), except
96370** that it is designed to be called by internal code. The difference is
96371** that if a malloc() fails in sqlite3_create_function(), an error code
96372** is returned and the mallocFailed flag cleared.
96373*/
96374SQLITE_PRIVATE int sqlite3CreateFunc(
96375  sqlite3 *db,
96376  const char *zFunctionName,
96377  int nArg,
96378  int enc,
96379  void *pUserData,
96380  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
96381  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
96382  void (*xFinal)(sqlite3_context*)
96383){
96384  FuncDef *p;
96385  int nName;
96386
96387  assert( sqlite3_mutex_held(db->mutex) );
96388  if( zFunctionName==0 ||
96389      (xFunc && (xFinal || xStep)) ||
96390      (!xFunc && (xFinal && !xStep)) ||
96391      (!xFunc && (!xFinal && xStep)) ||
96392      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
96393      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
96394    return SQLITE_MISUSE_BKPT;
96395  }
96396
96397#ifndef SQLITE_OMIT_UTF16
96398  /* If SQLITE_UTF16 is specified as the encoding type, transform this
96399  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
96400  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
96401  **
96402  ** If SQLITE_ANY is specified, add three versions of the function
96403  ** to the hash table.
96404  */
96405  if( enc==SQLITE_UTF16 ){
96406    enc = SQLITE_UTF16NATIVE;
96407  }else if( enc==SQLITE_ANY ){
96408    int rc;
96409    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
96410         pUserData, xFunc, xStep, xFinal);
96411    if( rc==SQLITE_OK ){
96412      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
96413          pUserData, xFunc, xStep, xFinal);
96414    }
96415    if( rc!=SQLITE_OK ){
96416      return rc;
96417    }
96418    enc = SQLITE_UTF16BE;
96419  }
96420#else
96421  enc = SQLITE_UTF8;
96422#endif
96423
96424  /* Check if an existing function is being overridden or deleted. If so,
96425  ** and there are active VMs, then return SQLITE_BUSY. If a function
96426  ** is being overridden/deleted but there are no active VMs, allow the
96427  ** operation to continue but invalidate all precompiled statements.
96428  */
96429  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
96430  if( p && p->iPrefEnc==enc && p->nArg==nArg ){
96431    if( db->activeVdbeCnt ){
96432      sqlite3Error(db, SQLITE_BUSY,
96433        "unable to delete/modify user-function due to active statements");
96434      assert( !db->mallocFailed );
96435      return SQLITE_BUSY;
96436    }else{
96437      sqlite3ExpirePreparedStatements(db);
96438    }
96439  }
96440
96441  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
96442  assert(p || db->mallocFailed);
96443  if( !p ){
96444    return SQLITE_NOMEM;
96445  }
96446  p->flags = 0;
96447  p->xFunc = xFunc;
96448  p->xStep = xStep;
96449  p->xFinalize = xFinal;
96450  p->pUserData = pUserData;
96451  p->nArg = (u16)nArg;
96452  return SQLITE_OK;
96453}
96454
96455/*
96456** Create new user functions.
96457*/
96458SQLITE_API int sqlite3_create_function(
96459  sqlite3 *db,
96460  const char *zFunctionName,
96461  int nArg,
96462  int enc,
96463  void *p,
96464  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
96465  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
96466  void (*xFinal)(sqlite3_context*)
96467){
96468  int rc;
96469  sqlite3_mutex_enter(db->mutex);
96470  rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
96471  rc = sqlite3ApiExit(db, rc);
96472  sqlite3_mutex_leave(db->mutex);
96473  return rc;
96474}
96475
96476#ifndef SQLITE_OMIT_UTF16
96477SQLITE_API int sqlite3_create_function16(
96478  sqlite3 *db,
96479  const void *zFunctionName,
96480  int nArg,
96481  int eTextRep,
96482  void *p,
96483  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
96484  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
96485  void (*xFinal)(sqlite3_context*)
96486){
96487  int rc;
96488  char *zFunc8;
96489  sqlite3_mutex_enter(db->mutex);
96490  assert( !db->mallocFailed );
96491  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
96492  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
96493  sqlite3DbFree(db, zFunc8);
96494  rc = sqlite3ApiExit(db, rc);
96495  sqlite3_mutex_leave(db->mutex);
96496  return rc;
96497}
96498#endif
96499
96500
96501/*
96502** Declare that a function has been overloaded by a virtual table.
96503**
96504** If the function already exists as a regular global function, then
96505** this routine is a no-op.  If the function does not exist, then create
96506** a new one that always throws a run-time error.
96507**
96508** When virtual tables intend to provide an overloaded function, they
96509** should call this routine to make sure the global function exists.
96510** A global function must exist in order for name resolution to work
96511** properly.
96512*/
96513SQLITE_API int sqlite3_overload_function(
96514  sqlite3 *db,
96515  const char *zName,
96516  int nArg
96517){
96518  int nName = sqlite3Strlen30(zName);
96519  int rc;
96520  sqlite3_mutex_enter(db->mutex);
96521  if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
96522    sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
96523                      0, sqlite3InvalidFunction, 0, 0);
96524  }
96525  rc = sqlite3ApiExit(db, SQLITE_OK);
96526  sqlite3_mutex_leave(db->mutex);
96527  return rc;
96528}
96529
96530#ifndef SQLITE_OMIT_TRACE
96531/*
96532** Register a trace function.  The pArg from the previously registered trace
96533** is returned.
96534**
96535** A NULL trace function means that no tracing is executes.  A non-NULL
96536** trace is a pointer to a function that is invoked at the start of each
96537** SQL statement.
96538*/
96539SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
96540  void *pOld;
96541  sqlite3_mutex_enter(db->mutex);
96542  pOld = db->pTraceArg;
96543  db->xTrace = xTrace;
96544  db->pTraceArg = pArg;
96545  sqlite3_mutex_leave(db->mutex);
96546  return pOld;
96547}
96548/*
96549** Register a profile function.  The pArg from the previously registered
96550** profile function is returned.
96551**
96552** A NULL profile function means that no profiling is executes.  A non-NULL
96553** profile is a pointer to a function that is invoked at the conclusion of
96554** each SQL statement that is run.
96555*/
96556SQLITE_API void *sqlite3_profile(
96557  sqlite3 *db,
96558  void (*xProfile)(void*,const char*,sqlite_uint64),
96559  void *pArg
96560){
96561  void *pOld;
96562  sqlite3_mutex_enter(db->mutex);
96563  pOld = db->pProfileArg;
96564  db->xProfile = xProfile;
96565  db->pProfileArg = pArg;
96566  sqlite3_mutex_leave(db->mutex);
96567  return pOld;
96568}
96569#endif /* SQLITE_OMIT_TRACE */
96570
96571/*** EXPERIMENTAL ***
96572**
96573** Register a function to be invoked when a transaction comments.
96574** If the invoked function returns non-zero, then the commit becomes a
96575** rollback.
96576*/
96577SQLITE_API void *sqlite3_commit_hook(
96578  sqlite3 *db,              /* Attach the hook to this database */
96579  int (*xCallback)(void*),  /* Function to invoke on each commit */
96580  void *pArg                /* Argument to the function */
96581){
96582  void *pOld;
96583  sqlite3_mutex_enter(db->mutex);
96584  pOld = db->pCommitArg;
96585  db->xCommitCallback = xCallback;
96586  db->pCommitArg = pArg;
96587  sqlite3_mutex_leave(db->mutex);
96588  return pOld;
96589}
96590
96591/*
96592** Register a callback to be invoked each time a row is updated,
96593** inserted or deleted using this database connection.
96594*/
96595SQLITE_API void *sqlite3_update_hook(
96596  sqlite3 *db,              /* Attach the hook to this database */
96597  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
96598  void *pArg                /* Argument to the function */
96599){
96600  void *pRet;
96601  sqlite3_mutex_enter(db->mutex);
96602  pRet = db->pUpdateArg;
96603  db->xUpdateCallback = xCallback;
96604  db->pUpdateArg = pArg;
96605  sqlite3_mutex_leave(db->mutex);
96606  return pRet;
96607}
96608
96609/*
96610** Register a callback to be invoked each time a transaction is rolled
96611** back by this database connection.
96612*/
96613SQLITE_API void *sqlite3_rollback_hook(
96614  sqlite3 *db,              /* Attach the hook to this database */
96615  void (*xCallback)(void*), /* Callback function */
96616  void *pArg                /* Argument to the function */
96617){
96618  void *pRet;
96619  sqlite3_mutex_enter(db->mutex);
96620  pRet = db->pRollbackArg;
96621  db->xRollbackCallback = xCallback;
96622  db->pRollbackArg = pArg;
96623  sqlite3_mutex_leave(db->mutex);
96624  return pRet;
96625}
96626
96627/*
96628** This function returns true if main-memory should be used instead of
96629** a temporary file for transient pager files and statement journals.
96630** The value returned depends on the value of db->temp_store (runtime
96631** parameter) and the compile time value of SQLITE_TEMP_STORE. The
96632** following table describes the relationship between these two values
96633** and this functions return value.
96634**
96635**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
96636**   -----------------     --------------     ------------------------------
96637**   0                     any                file      (return 0)
96638**   1                     1                  file      (return 0)
96639**   1                     2                  memory    (return 1)
96640**   1                     0                  file      (return 0)
96641**   2                     1                  file      (return 0)
96642**   2                     2                  memory    (return 1)
96643**   2                     0                  memory    (return 1)
96644**   3                     any                memory    (return 1)
96645*/
96646SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
96647#if SQLITE_TEMP_STORE==1
96648  return ( db->temp_store==2 );
96649#endif
96650#if SQLITE_TEMP_STORE==2
96651  return ( db->temp_store!=1 );
96652#endif
96653#if SQLITE_TEMP_STORE==3
96654  return 1;
96655#endif
96656#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
96657  return 0;
96658#endif
96659}
96660
96661/*
96662** This routine is called to create a connection to a database BTree
96663** driver.  If zFilename is the name of a file, then that file is
96664** opened and used.  If zFilename is the magic name ":memory:" then
96665** the database is stored in memory (and is thus forgotten as soon as
96666** the connection is closed.)  If zFilename is NULL then the database
96667** is a "virtual" database for transient use only and is deleted as
96668** soon as the connection is closed.
96669**
96670** A virtual database can be either a disk file (that is automatically
96671** deleted when the file is closed) or it an be held entirely in memory.
96672** The sqlite3TempInMemory() function is used to determine which.
96673*/
96674SQLITE_PRIVATE int sqlite3BtreeFactory(
96675  sqlite3 *db,              /* Main database when opening aux otherwise 0 */
96676  const char *zFilename,    /* Name of the file containing the BTree database */
96677  int omitJournal,          /* if TRUE then do not journal this file */
96678  int nCache,               /* How many pages in the page cache */
96679  int vfsFlags,             /* Flags passed through to vfsOpen */
96680  Btree **ppBtree           /* Pointer to new Btree object written here */
96681){
96682  int btFlags = 0;
96683  int rc;
96684
96685  assert( sqlite3_mutex_held(db->mutex) );
96686  assert( ppBtree != 0);
96687  if( omitJournal ){
96688    btFlags |= BTREE_OMIT_JOURNAL;
96689  }
96690  if( db->flags & SQLITE_NoReadlock ){
96691    btFlags |= BTREE_NO_READLOCK;
96692  }
96693#ifndef SQLITE_OMIT_MEMORYDB
96694  if( zFilename==0 && sqlite3TempInMemory(db) ){
96695    zFilename = ":memory:";
96696  }
96697#endif
96698
96699  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
96700    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
96701  }
96702  rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
96703
96704  /* If the B-Tree was successfully opened, set the pager-cache size to the
96705  ** default value. Except, if the call to BtreeOpen() returned a handle
96706  ** open on an existing shared pager-cache, do not change the pager-cache
96707  ** size.
96708  */
96709  if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
96710    sqlite3BtreeSetCacheSize(*ppBtree, nCache);
96711  }
96712  return rc;
96713}
96714
96715/*
96716** Return UTF-8 encoded English language explanation of the most recent
96717** error.
96718*/
96719SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
96720  const char *z;
96721  if( !db ){
96722    return sqlite3ErrStr(SQLITE_NOMEM);
96723  }
96724  if( !sqlite3SafetyCheckSickOrOk(db) ){
96725    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
96726  }
96727  sqlite3_mutex_enter(db->mutex);
96728  if( db->mallocFailed ){
96729    z = sqlite3ErrStr(SQLITE_NOMEM);
96730  }else{
96731    z = (char*)sqlite3_value_text(db->pErr);
96732    assert( !db->mallocFailed );
96733    if( z==0 ){
96734      z = sqlite3ErrStr(db->errCode);
96735    }
96736  }
96737  sqlite3_mutex_leave(db->mutex);
96738  return z;
96739}
96740
96741#ifndef SQLITE_OMIT_UTF16
96742/*
96743** Return UTF-16 encoded English language explanation of the most recent
96744** error.
96745*/
96746SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
96747  static const u16 outOfMem[] = {
96748    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
96749  };
96750  static const u16 misuse[] = {
96751    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
96752    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
96753    'c', 'a', 'l', 'l', 'e', 'd', ' ',
96754    'o', 'u', 't', ' ',
96755    'o', 'f', ' ',
96756    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
96757  };
96758
96759  const void *z;
96760  if( !db ){
96761    return (void *)outOfMem;
96762  }
96763  if( !sqlite3SafetyCheckSickOrOk(db) ){
96764    return (void *)misuse;
96765  }
96766  sqlite3_mutex_enter(db->mutex);
96767  if( db->mallocFailed ){
96768    z = (void *)outOfMem;
96769  }else{
96770    z = sqlite3_value_text16(db->pErr);
96771    if( z==0 ){
96772      sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
96773           SQLITE_UTF8, SQLITE_STATIC);
96774      z = sqlite3_value_text16(db->pErr);
96775    }
96776    /* A malloc() may have failed within the call to sqlite3_value_text16()
96777    ** above. If this is the case, then the db->mallocFailed flag needs to
96778    ** be cleared before returning. Do this directly, instead of via
96779    ** sqlite3ApiExit(), to avoid setting the database handle error message.
96780    */
96781    db->mallocFailed = 0;
96782  }
96783  sqlite3_mutex_leave(db->mutex);
96784  return z;
96785}
96786#endif /* SQLITE_OMIT_UTF16 */
96787
96788/*
96789** Return the most recent error code generated by an SQLite routine. If NULL is
96790** passed to this function, we assume a malloc() failed during sqlite3_open().
96791*/
96792SQLITE_API int sqlite3_errcode(sqlite3 *db){
96793  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
96794    return SQLITE_MISUSE_BKPT;
96795  }
96796  if( !db || db->mallocFailed ){
96797    return SQLITE_NOMEM;
96798  }
96799  return db->errCode & db->errMask;
96800}
96801SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
96802  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
96803    return SQLITE_MISUSE_BKPT;
96804  }
96805  if( !db || db->mallocFailed ){
96806    return SQLITE_NOMEM;
96807  }
96808  return db->errCode;
96809}
96810
96811/*
96812** Create a new collating function for database "db".  The name is zName
96813** and the encoding is enc.
96814*/
96815static int createCollation(
96816  sqlite3* db,
96817  const char *zName,
96818  u8 enc,
96819  u8 collType,
96820  void* pCtx,
96821  int(*xCompare)(void*,int,const void*,int,const void*),
96822  void(*xDel)(void*)
96823){
96824  CollSeq *pColl;
96825  int enc2;
96826  int nName = sqlite3Strlen30(zName);
96827
96828  assert( sqlite3_mutex_held(db->mutex) );
96829
96830  /* If SQLITE_UTF16 is specified as the encoding type, transform this
96831  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
96832  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
96833  */
96834  enc2 = enc;
96835  testcase( enc2==SQLITE_UTF16 );
96836  testcase( enc2==SQLITE_UTF16_ALIGNED );
96837  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
96838    enc2 = SQLITE_UTF16NATIVE;
96839  }
96840  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
96841    return SQLITE_MISUSE_BKPT;
96842  }
96843
96844  /* Check if this call is removing or replacing an existing collation
96845  ** sequence. If so, and there are active VMs, return busy. If there
96846  ** are no active VMs, invalidate any pre-compiled statements.
96847  */
96848  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
96849  if( pColl && pColl->xCmp ){
96850    if( db->activeVdbeCnt ){
96851      sqlite3Error(db, SQLITE_BUSY,
96852        "unable to delete/modify collation sequence due to active statements");
96853      return SQLITE_BUSY;
96854    }
96855    sqlite3ExpirePreparedStatements(db);
96856
96857    /* If collation sequence pColl was created directly by a call to
96858    ** sqlite3_create_collation, and not generated by synthCollSeq(),
96859    ** then any copies made by synthCollSeq() need to be invalidated.
96860    ** Also, collation destructor - CollSeq.xDel() - function may need
96861    ** to be called.
96862    */
96863    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
96864      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
96865      int j;
96866      for(j=0; j<3; j++){
96867        CollSeq *p = &aColl[j];
96868        if( p->enc==pColl->enc ){
96869          if( p->xDel ){
96870            p->xDel(p->pUser);
96871          }
96872          p->xCmp = 0;
96873        }
96874      }
96875    }
96876  }
96877
96878  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
96879  if( pColl ){
96880    pColl->xCmp = xCompare;
96881    pColl->pUser = pCtx;
96882    pColl->xDel = xDel;
96883    pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
96884    pColl->type = collType;
96885  }
96886  sqlite3Error(db, SQLITE_OK, 0);
96887  return SQLITE_OK;
96888}
96889
96890
96891/*
96892** This array defines hard upper bounds on limit values.  The
96893** initializer must be kept in sync with the SQLITE_LIMIT_*
96894** #defines in sqlite3.h.
96895*/
96896static const int aHardLimit[] = {
96897  SQLITE_MAX_LENGTH,
96898  SQLITE_MAX_SQL_LENGTH,
96899  SQLITE_MAX_COLUMN,
96900  SQLITE_MAX_EXPR_DEPTH,
96901  SQLITE_MAX_COMPOUND_SELECT,
96902  SQLITE_MAX_VDBE_OP,
96903  SQLITE_MAX_FUNCTION_ARG,
96904  SQLITE_MAX_ATTACHED,
96905  SQLITE_MAX_LIKE_PATTERN_LENGTH,
96906  SQLITE_MAX_VARIABLE_NUMBER,
96907  SQLITE_MAX_TRIGGER_DEPTH,
96908};
96909
96910/*
96911** Make sure the hard limits are set to reasonable values
96912*/
96913#if SQLITE_MAX_LENGTH<100
96914# error SQLITE_MAX_LENGTH must be at least 100
96915#endif
96916#if SQLITE_MAX_SQL_LENGTH<100
96917# error SQLITE_MAX_SQL_LENGTH must be at least 100
96918#endif
96919#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
96920# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
96921#endif
96922#if SQLITE_MAX_COMPOUND_SELECT<2
96923# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
96924#endif
96925#if SQLITE_MAX_VDBE_OP<40
96926# error SQLITE_MAX_VDBE_OP must be at least 40
96927#endif
96928#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
96929# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
96930#endif
96931#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
96932# error SQLITE_MAX_ATTACHED must be between 0 and 30
96933#endif
96934#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
96935# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
96936#endif
96937#if SQLITE_MAX_COLUMN>32767
96938# error SQLITE_MAX_COLUMN must not exceed 32767
96939#endif
96940#if SQLITE_MAX_TRIGGER_DEPTH<1
96941# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
96942#endif
96943
96944
96945/*
96946** Change the value of a limit.  Report the old value.
96947** If an invalid limit index is supplied, report -1.
96948** Make no changes but still report the old value if the
96949** new limit is negative.
96950**
96951** A new lower limit does not shrink existing constructs.
96952** It merely prevents new constructs that exceed the limit
96953** from forming.
96954*/
96955SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
96956  int oldLimit;
96957  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
96958    return -1;
96959  }
96960  oldLimit = db->aLimit[limitId];
96961  if( newLimit>=0 ){
96962    if( newLimit>aHardLimit[limitId] ){
96963      newLimit = aHardLimit[limitId];
96964    }
96965    db->aLimit[limitId] = newLimit;
96966  }
96967  return oldLimit;
96968}
96969
96970/*
96971** This routine does the work of opening a database on behalf of
96972** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
96973** is UTF-8 encoded.
96974*/
96975static int openDatabase(
96976  const char *zFilename, /* Database filename UTF-8 encoded */
96977  sqlite3 **ppDb,        /* OUT: Returned database handle */
96978  unsigned flags,        /* Operational flags */
96979  const char *zVfs       /* Name of the VFS to use */
96980){
96981  sqlite3 *db;
96982  int rc;
96983  int isThreadsafe;
96984
96985  *ppDb = 0;
96986#ifndef SQLITE_OMIT_AUTOINIT
96987  rc = sqlite3_initialize();
96988  if( rc ) return rc;
96989#endif
96990
96991  if( sqlite3GlobalConfig.bCoreMutex==0 ){
96992    isThreadsafe = 0;
96993  }else if( flags & SQLITE_OPEN_NOMUTEX ){
96994    isThreadsafe = 0;
96995  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
96996    isThreadsafe = 1;
96997  }else{
96998    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
96999  }
97000  if( flags & SQLITE_OPEN_PRIVATECACHE ){
97001    flags &= ~SQLITE_OPEN_SHAREDCACHE;
97002  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
97003    flags |= SQLITE_OPEN_SHAREDCACHE;
97004  }
97005
97006  /* Remove harmful bits from the flags parameter
97007  **
97008  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
97009  ** dealt with in the previous code block.  Besides these, the only
97010  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
97011  ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE.  Silently mask
97012  ** off all other flags.
97013  */
97014  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
97015               SQLITE_OPEN_EXCLUSIVE |
97016               SQLITE_OPEN_MAIN_DB |
97017               SQLITE_OPEN_TEMP_DB |
97018               SQLITE_OPEN_TRANSIENT_DB |
97019               SQLITE_OPEN_MAIN_JOURNAL |
97020               SQLITE_OPEN_TEMP_JOURNAL |
97021               SQLITE_OPEN_SUBJOURNAL |
97022               SQLITE_OPEN_MASTER_JOURNAL |
97023               SQLITE_OPEN_NOMUTEX |
97024               SQLITE_OPEN_FULLMUTEX
97025             );
97026
97027  /* Allocate the sqlite data structure */
97028  db = sqlite3MallocZero( sizeof(sqlite3) );
97029  if( db==0 ) goto opendb_out;
97030  if( isThreadsafe ){
97031    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
97032    if( db->mutex==0 ){
97033      sqlite3_free(db);
97034      db = 0;
97035      goto opendb_out;
97036    }
97037  }
97038  sqlite3_mutex_enter(db->mutex);
97039  db->errMask = 0xff;
97040  db->nDb = 2;
97041  db->magic = SQLITE_MAGIC_BUSY;
97042  db->aDb = db->aDbStatic;
97043
97044  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
97045  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
97046  db->autoCommit = 1;
97047  db->nextAutovac = -1;
97048  db->nextPagesize = 0;
97049  db->flags |= SQLITE_ShortColNames
97050#if SQLITE_DEFAULT_FILE_FORMAT<4
97051                 | SQLITE_LegacyFileFmt
97052#endif
97053#ifdef SQLITE_ENABLE_LOAD_EXTENSION
97054                 | SQLITE_LoadExtension
97055#endif
97056#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
97057                 | SQLITE_RecTriggers
97058#endif
97059      ;
97060  sqlite3HashInit(&db->aCollSeq);
97061#ifndef SQLITE_OMIT_VIRTUALTABLE
97062  sqlite3HashInit(&db->aModule);
97063#endif
97064
97065  db->pVfs = sqlite3_vfs_find(zVfs);
97066  if( !db->pVfs ){
97067    rc = SQLITE_ERROR;
97068    sqlite3Error(db, rc, "no such vfs: %s", zVfs);
97069    goto opendb_out;
97070  }
97071
97072  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
97073  ** and UTF-16, so add a version for each to avoid any unnecessary
97074  ** conversions. The only error that can occur here is a malloc() failure.
97075  */
97076  createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
97077                  binCollFunc, 0);
97078  createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
97079                  binCollFunc, 0);
97080  createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
97081                  binCollFunc, 0);
97082  createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
97083                  binCollFunc, 0);
97084  if( db->mallocFailed ){
97085    goto opendb_out;
97086  }
97087  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
97088  assert( db->pDfltColl!=0 );
97089
97090  /* Also add a UTF-8 case-insensitive collation sequence. */
97091  createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
97092                  nocaseCollatingFunc, 0);
97093
97094  /* Open the backend database driver */
97095  db->openFlags = flags;
97096  rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
97097                           flags | SQLITE_OPEN_MAIN_DB,
97098                           &db->aDb[0].pBt);
97099  if( rc!=SQLITE_OK ){
97100    if( rc==SQLITE_IOERR_NOMEM ){
97101      rc = SQLITE_NOMEM;
97102    }
97103    sqlite3Error(db, rc, 0);
97104    goto opendb_out;
97105  }
97106  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
97107  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
97108
97109
97110  /* The default safety_level for the main database is 'full'; for the temp
97111  ** database it is 'NONE'. This matches the pager layer defaults.
97112  */
97113  db->aDb[0].zName = "main";
97114  db->aDb[0].safety_level = 3;
97115  db->aDb[1].zName = "temp";
97116  db->aDb[1].safety_level = 1;
97117
97118  db->magic = SQLITE_MAGIC_OPEN;
97119  if( db->mallocFailed ){
97120    goto opendb_out;
97121  }
97122
97123  /* Register all built-in functions, but do not attempt to read the
97124  ** database schema yet. This is delayed until the first time the database
97125  ** is accessed.
97126  */
97127  sqlite3Error(db, SQLITE_OK, 0);
97128  sqlite3RegisterBuiltinFunctions(db);
97129
97130  /* Load automatic extensions - extensions that have been registered
97131  ** using the sqlite3_automatic_extension() API.
97132  */
97133  sqlite3AutoLoadExtensions(db);
97134  rc = sqlite3_errcode(db);
97135  if( rc!=SQLITE_OK ){
97136    goto opendb_out;
97137  }
97138
97139#ifdef SQLITE_ENABLE_FTS1
97140  if( !db->mallocFailed ){
97141    extern int sqlite3Fts1Init(sqlite3*);
97142    rc = sqlite3Fts1Init(db);
97143  }
97144#endif
97145
97146#ifdef SQLITE_ENABLE_FTS2
97147  if( !db->mallocFailed && rc==SQLITE_OK ){
97148    extern int sqlite3Fts2Init(sqlite3*);
97149    rc = sqlite3Fts2Init(db);
97150  }
97151#endif
97152
97153#ifdef SQLITE_ENABLE_FTS3
97154  if( !db->mallocFailed && rc==SQLITE_OK ){
97155    rc = sqlite3Fts3Init(db);
97156  }
97157#endif
97158
97159#ifdef SQLITE_ENABLE_ICU
97160  if( !db->mallocFailed && rc==SQLITE_OK ){
97161    rc = sqlite3IcuInit(db);
97162  }
97163#endif
97164
97165#ifdef SQLITE_ENABLE_RTREE
97166  if( !db->mallocFailed && rc==SQLITE_OK){
97167    rc = sqlite3RtreeInit(db);
97168  }
97169#endif
97170
97171  sqlite3Error(db, rc, 0);
97172
97173  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
97174  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
97175  ** mode.  Doing nothing at all also makes NORMAL the default.
97176  */
97177#ifdef SQLITE_DEFAULT_LOCKING_MODE
97178  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
97179  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
97180                          SQLITE_DEFAULT_LOCKING_MODE);
97181#endif
97182
97183  /* Enable the lookaside-malloc subsystem */
97184  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
97185                        sqlite3GlobalConfig.nLookaside);
97186
97187opendb_out:
97188  if( db ){
97189    assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
97190    sqlite3_mutex_leave(db->mutex);
97191  }
97192  rc = sqlite3_errcode(db);
97193  if( rc==SQLITE_NOMEM ){
97194    sqlite3_close(db);
97195    db = 0;
97196  }else if( rc!=SQLITE_OK ){
97197    db->magic = SQLITE_MAGIC_SICK;
97198  }
97199  *ppDb = db;
97200  return sqlite3ApiExit(0, rc);
97201}
97202
97203/*
97204** Open a new database handle.
97205*/
97206SQLITE_API int sqlite3_open(
97207  const char *zFilename,
97208  sqlite3 **ppDb
97209){
97210  return openDatabase(zFilename, ppDb,
97211                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
97212}
97213SQLITE_API int sqlite3_open_v2(
97214  const char *filename,   /* Database filename (UTF-8) */
97215  sqlite3 **ppDb,         /* OUT: SQLite db handle */
97216  int flags,              /* Flags */
97217  const char *zVfs        /* Name of VFS module to use */
97218){
97219  return openDatabase(filename, ppDb, flags, zVfs);
97220}
97221
97222#ifndef SQLITE_OMIT_UTF16
97223/*
97224** Open a new database handle.
97225*/
97226SQLITE_API int sqlite3_open16(
97227  const void *zFilename,
97228  sqlite3 **ppDb
97229){
97230  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
97231  sqlite3_value *pVal;
97232  int rc;
97233
97234  assert( zFilename );
97235  assert( ppDb );
97236  *ppDb = 0;
97237#ifndef SQLITE_OMIT_AUTOINIT
97238  rc = sqlite3_initialize();
97239  if( rc ) return rc;
97240#endif
97241  pVal = sqlite3ValueNew(0);
97242  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
97243  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
97244  if( zFilename8 ){
97245    rc = openDatabase(zFilename8, ppDb,
97246                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
97247    assert( *ppDb || rc==SQLITE_NOMEM );
97248    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
97249      ENC(*ppDb) = SQLITE_UTF16NATIVE;
97250    }
97251  }else{
97252    rc = SQLITE_NOMEM;
97253  }
97254  sqlite3ValueFree(pVal);
97255
97256  return sqlite3ApiExit(0, rc);
97257}
97258#endif /* SQLITE_OMIT_UTF16 */
97259
97260/*
97261** Register a new collation sequence with the database handle db.
97262*/
97263SQLITE_API int sqlite3_create_collation(
97264  sqlite3* db,
97265  const char *zName,
97266  int enc,
97267  void* pCtx,
97268  int(*xCompare)(void*,int,const void*,int,const void*)
97269){
97270  int rc;
97271  sqlite3_mutex_enter(db->mutex);
97272  assert( !db->mallocFailed );
97273  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
97274  rc = sqlite3ApiExit(db, rc);
97275  sqlite3_mutex_leave(db->mutex);
97276  return rc;
97277}
97278
97279/*
97280** Register a new collation sequence with the database handle db.
97281*/
97282SQLITE_API int sqlite3_create_collation_v2(
97283  sqlite3* db,
97284  const char *zName,
97285  int enc,
97286  void* pCtx,
97287  int(*xCompare)(void*,int,const void*,int,const void*),
97288  void(*xDel)(void*)
97289){
97290  int rc;
97291  sqlite3_mutex_enter(db->mutex);
97292  assert( !db->mallocFailed );
97293  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
97294  rc = sqlite3ApiExit(db, rc);
97295  sqlite3_mutex_leave(db->mutex);
97296  return rc;
97297}
97298
97299#ifndef SQLITE_OMIT_UTF16
97300/*
97301** Register a new collation sequence with the database handle db.
97302*/
97303SQLITE_API int sqlite3_create_collation16(
97304  sqlite3* db,
97305  const void *zName,
97306  int enc,
97307  void* pCtx,
97308  int(*xCompare)(void*,int,const void*,int,const void*)
97309){
97310  int rc = SQLITE_OK;
97311  char *zName8;
97312  sqlite3_mutex_enter(db->mutex);
97313  assert( !db->mallocFailed );
97314  zName8 = sqlite3Utf16to8(db, zName, -1);
97315  if( zName8 ){
97316    rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
97317    sqlite3DbFree(db, zName8);
97318  }
97319  rc = sqlite3ApiExit(db, rc);
97320  sqlite3_mutex_leave(db->mutex);
97321  return rc;
97322}
97323#endif /* SQLITE_OMIT_UTF16 */
97324
97325/*
97326** Register a collation sequence factory callback with the database handle
97327** db. Replace any previously installed collation sequence factory.
97328*/
97329SQLITE_API int sqlite3_collation_needed(
97330  sqlite3 *db,
97331  void *pCollNeededArg,
97332  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
97333){
97334  sqlite3_mutex_enter(db->mutex);
97335  db->xCollNeeded = xCollNeeded;
97336  db->xCollNeeded16 = 0;
97337  db->pCollNeededArg = pCollNeededArg;
97338  sqlite3_mutex_leave(db->mutex);
97339  return SQLITE_OK;
97340}
97341
97342#ifndef SQLITE_OMIT_UTF16
97343/*
97344** Register a collation sequence factory callback with the database handle
97345** db. Replace any previously installed collation sequence factory.
97346*/
97347SQLITE_API int sqlite3_collation_needed16(
97348  sqlite3 *db,
97349  void *pCollNeededArg,
97350  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
97351){
97352  sqlite3_mutex_enter(db->mutex);
97353  db->xCollNeeded = 0;
97354  db->xCollNeeded16 = xCollNeeded16;
97355  db->pCollNeededArg = pCollNeededArg;
97356  sqlite3_mutex_leave(db->mutex);
97357  return SQLITE_OK;
97358}
97359#endif /* SQLITE_OMIT_UTF16 */
97360
97361#ifndef SQLITE_OMIT_GLOBALRECOVER
97362#ifndef SQLITE_OMIT_DEPRECATED
97363/*
97364** This function is now an anachronism. It used to be used to recover from a
97365** malloc() failure, but SQLite now does this automatically.
97366*/
97367SQLITE_API int sqlite3_global_recover(void){
97368  return SQLITE_OK;
97369}
97370#endif
97371#endif
97372
97373/*
97374** Test to see whether or not the database connection is in autocommit
97375** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
97376** by default.  Autocommit is disabled by a BEGIN statement and reenabled
97377** by the next COMMIT or ROLLBACK.
97378**
97379******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
97380*/
97381SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
97382  return db->autoCommit;
97383}
97384
97385/*
97386** The following routines are subtitutes for constants SQLITE_CORRUPT,
97387** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
97388** constants.  They server two purposes:
97389**
97390**   1.  Serve as a convenient place to set a breakpoint in a debugger
97391**       to detect when version error conditions occurs.
97392**
97393**   2.  Invoke sqlite3_log() to provide the source code location where
97394**       a low-level error is first detected.
97395*/
97396SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
97397  testcase( sqlite3GlobalConfig.xLog!=0 );
97398  sqlite3_log(SQLITE_CORRUPT,
97399              "database corruption found by source line %d", lineno);
97400  return SQLITE_CORRUPT;
97401}
97402SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
97403  testcase( sqlite3GlobalConfig.xLog!=0 );
97404  sqlite3_log(SQLITE_MISUSE, "misuse detected by source line %d", lineno);
97405  return SQLITE_MISUSE;
97406}
97407SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
97408  testcase( sqlite3GlobalConfig.xLog!=0 );
97409  sqlite3_log(SQLITE_CANTOPEN, "cannot open file at source line %d", lineno);
97410  return SQLITE_CANTOPEN;
97411}
97412
97413
97414#ifndef SQLITE_OMIT_DEPRECATED
97415/*
97416** This is a convenience routine that makes sure that all thread-specific
97417** data for this thread has been deallocated.
97418**
97419** SQLite no longer uses thread-specific data so this routine is now a
97420** no-op.  It is retained for historical compatibility.
97421*/
97422SQLITE_API void sqlite3_thread_cleanup(void){
97423}
97424#endif
97425
97426/*
97427** Return meta information about a specific column of a database table.
97428** See comment in sqlite3.h (sqlite.h.in) for details.
97429*/
97430#ifdef SQLITE_ENABLE_COLUMN_METADATA
97431SQLITE_API int sqlite3_table_column_metadata(
97432  sqlite3 *db,                /* Connection handle */
97433  const char *zDbName,        /* Database name or NULL */
97434  const char *zTableName,     /* Table name */
97435  const char *zColumnName,    /* Column name */
97436  char const **pzDataType,    /* OUTPUT: Declared data type */
97437  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
97438  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
97439  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
97440  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
97441){
97442  int rc;
97443  char *zErrMsg = 0;
97444  Table *pTab = 0;
97445  Column *pCol = 0;
97446  int iCol;
97447
97448  char const *zDataType = 0;
97449  char const *zCollSeq = 0;
97450  int notnull = 0;
97451  int primarykey = 0;
97452  int autoinc = 0;
97453
97454  /* Ensure the database schema has been loaded */
97455  sqlite3_mutex_enter(db->mutex);
97456  sqlite3BtreeEnterAll(db);
97457  rc = sqlite3Init(db, &zErrMsg);
97458  if( SQLITE_OK!=rc ){
97459    goto error_out;
97460  }
97461
97462  /* Locate the table in question */
97463  pTab = sqlite3FindTable(db, zTableName, zDbName);
97464  if( !pTab || pTab->pSelect ){
97465    pTab = 0;
97466    goto error_out;
97467  }
97468
97469  /* Find the column for which info is requested */
97470  if( sqlite3IsRowid(zColumnName) ){
97471    iCol = pTab->iPKey;
97472    if( iCol>=0 ){
97473      pCol = &pTab->aCol[iCol];
97474    }
97475  }else{
97476    for(iCol=0; iCol<pTab->nCol; iCol++){
97477      pCol = &pTab->aCol[iCol];
97478      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
97479        break;
97480      }
97481    }
97482    if( iCol==pTab->nCol ){
97483      pTab = 0;
97484      goto error_out;
97485    }
97486  }
97487
97488  /* The following block stores the meta information that will be returned
97489  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
97490  ** and autoinc. At this point there are two possibilities:
97491  **
97492  **     1. The specified column name was rowid", "oid" or "_rowid_"
97493  **        and there is no explicitly declared IPK column.
97494  **
97495  **     2. The table is not a view and the column name identified an
97496  **        explicitly declared column. Copy meta information from *pCol.
97497  */
97498  if( pCol ){
97499    zDataType = pCol->zType;
97500    zCollSeq = pCol->zColl;
97501    notnull = pCol->notNull!=0;
97502    primarykey  = pCol->isPrimKey!=0;
97503    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
97504  }else{
97505    zDataType = "INTEGER";
97506    primarykey = 1;
97507  }
97508  if( !zCollSeq ){
97509    zCollSeq = "BINARY";
97510  }
97511
97512error_out:
97513  sqlite3BtreeLeaveAll(db);
97514
97515  /* Whether the function call succeeded or failed, set the output parameters
97516  ** to whatever their local counterparts contain. If an error did occur,
97517  ** this has the effect of zeroing all output parameters.
97518  */
97519  if( pzDataType ) *pzDataType = zDataType;
97520  if( pzCollSeq ) *pzCollSeq = zCollSeq;
97521  if( pNotNull ) *pNotNull = notnull;
97522  if( pPrimaryKey ) *pPrimaryKey = primarykey;
97523  if( pAutoinc ) *pAutoinc = autoinc;
97524
97525  if( SQLITE_OK==rc && !pTab ){
97526    sqlite3DbFree(db, zErrMsg);
97527    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
97528        zColumnName);
97529    rc = SQLITE_ERROR;
97530  }
97531  sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
97532  sqlite3DbFree(db, zErrMsg);
97533  rc = sqlite3ApiExit(db, rc);
97534  sqlite3_mutex_leave(db->mutex);
97535  return rc;
97536}
97537#endif
97538
97539/*
97540** Sleep for a little while.  Return the amount of time slept.
97541*/
97542SQLITE_API int sqlite3_sleep(int ms){
97543  sqlite3_vfs *pVfs;
97544  int rc;
97545  pVfs = sqlite3_vfs_find(0);
97546  if( pVfs==0 ) return 0;
97547
97548  /* This function works in milliseconds, but the underlying OsSleep()
97549  ** API uses microseconds. Hence the 1000's.
97550  */
97551  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
97552  return rc;
97553}
97554
97555/*
97556** Enable or disable the extended result codes.
97557*/
97558SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
97559  sqlite3_mutex_enter(db->mutex);
97560  db->errMask = onoff ? 0xffffffff : 0xff;
97561  sqlite3_mutex_leave(db->mutex);
97562  return SQLITE_OK;
97563}
97564
97565/*
97566** Invoke the xFileControl method on a particular database.
97567*/
97568SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
97569  int rc = SQLITE_ERROR;
97570  int iDb;
97571  sqlite3_mutex_enter(db->mutex);
97572  if( zDbName==0 ){
97573    iDb = 0;
97574  }else{
97575    for(iDb=0; iDb<db->nDb; iDb++){
97576      if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
97577    }
97578  }
97579  if( iDb<db->nDb ){
97580    Btree *pBtree = db->aDb[iDb].pBt;
97581    if( pBtree ){
97582      Pager *pPager;
97583      sqlite3_file *fd;
97584      sqlite3BtreeEnter(pBtree);
97585      pPager = sqlite3BtreePager(pBtree);
97586      assert( pPager!=0 );
97587      fd = sqlite3PagerFile(pPager);
97588      assert( fd!=0 );
97589      if( fd->pMethods ){
97590        rc = sqlite3OsFileControl(fd, op, pArg);
97591      }
97592      sqlite3BtreeLeave(pBtree);
97593    }
97594  }
97595  sqlite3_mutex_leave(db->mutex);
97596  return rc;
97597}
97598
97599/*
97600** Interface to the testing logic.
97601*/
97602SQLITE_API int sqlite3_test_control(int op, ...){
97603  int rc = 0;
97604#ifndef SQLITE_OMIT_BUILTIN_TEST
97605  va_list ap;
97606  va_start(ap, op);
97607  switch( op ){
97608
97609    /*
97610    ** Save the current state of the PRNG.
97611    */
97612    case SQLITE_TESTCTRL_PRNG_SAVE: {
97613      sqlite3PrngSaveState();
97614      break;
97615    }
97616
97617    /*
97618    ** Restore the state of the PRNG to the last state saved using
97619    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
97620    ** this verb acts like PRNG_RESET.
97621    */
97622    case SQLITE_TESTCTRL_PRNG_RESTORE: {
97623      sqlite3PrngRestoreState();
97624      break;
97625    }
97626
97627    /*
97628    ** Reset the PRNG back to its uninitialized state.  The next call
97629    ** to sqlite3_randomness() will reseed the PRNG using a single call
97630    ** to the xRandomness method of the default VFS.
97631    */
97632    case SQLITE_TESTCTRL_PRNG_RESET: {
97633      sqlite3PrngResetState();
97634      break;
97635    }
97636
97637    /*
97638    **  sqlite3_test_control(BITVEC_TEST, size, program)
97639    **
97640    ** Run a test against a Bitvec object of size.  The program argument
97641    ** is an array of integers that defines the test.  Return -1 on a
97642    ** memory allocation error, 0 on success, or non-zero for an error.
97643    ** See the sqlite3BitvecBuiltinTest() for additional information.
97644    */
97645    case SQLITE_TESTCTRL_BITVEC_TEST: {
97646      int sz = va_arg(ap, int);
97647      int *aProg = va_arg(ap, int*);
97648      rc = sqlite3BitvecBuiltinTest(sz, aProg);
97649      break;
97650    }
97651
97652    /*
97653    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
97654    **
97655    ** Register hooks to call to indicate which malloc() failures
97656    ** are benign.
97657    */
97658    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
97659      typedef void (*void_function)(void);
97660      void_function xBenignBegin;
97661      void_function xBenignEnd;
97662      xBenignBegin = va_arg(ap, void_function);
97663      xBenignEnd = va_arg(ap, void_function);
97664      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
97665      break;
97666    }
97667
97668    /*
97669    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
97670    **
97671    ** Set the PENDING byte to the value in the argument, if X>0.
97672    ** Make no changes if X==0.  Return the value of the pending byte
97673    ** as it existing before this routine was called.
97674    **
97675    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
97676    ** an incompatible database file format.  Changing the PENDING byte
97677    ** while any database connection is open results in undefined and
97678    ** dileterious behavior.
97679    */
97680    case SQLITE_TESTCTRL_PENDING_BYTE: {
97681      unsigned int newVal = va_arg(ap, unsigned int);
97682      rc = sqlite3PendingByte;
97683      if( newVal ) sqlite3PendingByte = newVal;
97684      break;
97685    }
97686
97687    /*
97688    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
97689    **
97690    ** This action provides a run-time test to see whether or not
97691    ** assert() was enabled at compile-time.  If X is true and assert()
97692    ** is enabled, then the return value is true.  If X is true and
97693    ** assert() is disabled, then the return value is zero.  If X is
97694    ** false and assert() is enabled, then the assertion fires and the
97695    ** process aborts.  If X is false and assert() is disabled, then the
97696    ** return value is zero.
97697    */
97698    case SQLITE_TESTCTRL_ASSERT: {
97699      volatile int x = 0;
97700      assert( (x = va_arg(ap,int))!=0 );
97701      rc = x;
97702      break;
97703    }
97704
97705
97706    /*
97707    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
97708    **
97709    ** This action provides a run-time test to see how the ALWAYS and
97710    ** NEVER macros were defined at compile-time.
97711    **
97712    ** The return value is ALWAYS(X).
97713    **
97714    ** The recommended test is X==2.  If the return value is 2, that means
97715    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
97716    ** default setting.  If the return value is 1, then ALWAYS() is either
97717    ** hard-coded to true or else it asserts if its argument is false.
97718    ** The first behavior (hard-coded to true) is the case if
97719    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
97720    ** behavior (assert if the argument to ALWAYS() is false) is the case if
97721    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
97722    **
97723    ** The run-time test procedure might look something like this:
97724    **
97725    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
97726    **      // ALWAYS() and NEVER() are no-op pass-through macros
97727    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
97728    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
97729    **    }else{
97730    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
97731    **    }
97732    */
97733    case SQLITE_TESTCTRL_ALWAYS: {
97734      int x = va_arg(ap,int);
97735      rc = ALWAYS(x);
97736      break;
97737    }
97738
97739    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
97740    **
97741    ** Set the nReserve size to N for the main database on the database
97742    ** connection db.
97743    */
97744    case SQLITE_TESTCTRL_RESERVE: {
97745      sqlite3 *db = va_arg(ap, sqlite3*);
97746      int x = va_arg(ap,int);
97747      sqlite3_mutex_enter(db->mutex);
97748      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
97749      sqlite3_mutex_leave(db->mutex);
97750      break;
97751    }
97752
97753    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
97754    **
97755    ** Enable or disable various optimizations for testing purposes.  The
97756    ** argument N is a bitmask of optimizations to be disabled.  For normal
97757    ** operation N should be 0.  The idea is that a test program (like the
97758    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
97759    ** with various optimizations disabled to verify that the same answer
97760    ** is obtained in every case.
97761    */
97762    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
97763      sqlite3 *db = va_arg(ap, sqlite3*);
97764      int x = va_arg(ap,int);
97765      db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
97766      break;
97767    }
97768
97769#ifdef SQLITE_N_KEYWORD
97770    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
97771    **
97772    ** If zWord is a keyword recognized by the parser, then return the
97773    ** number of keywords.  Or if zWord is not a keyword, return 0.
97774    **
97775    ** This test feature is only available in the amalgamation since
97776    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
97777    ** is built using separate source files.
97778    */
97779    case SQLITE_TESTCTRL_ISKEYWORD: {
97780      const char *zWord = va_arg(ap, const char*);
97781      int n = sqlite3Strlen30(zWord);
97782      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
97783      break;
97784    }
97785#endif
97786
97787  }
97788  va_end(ap);
97789#endif /* SQLITE_OMIT_BUILTIN_TEST */
97790  return rc;
97791}
97792
97793/************** End of main.c ************************************************/
97794/************** Begin file notify.c ******************************************/
97795/*
97796** 2009 March 3
97797**
97798** The author disclaims copyright to this source code.  In place of
97799** a legal notice, here is a blessing:
97800**
97801**    May you do good and not evil.
97802**    May you find forgiveness for yourself and forgive others.
97803**    May you share freely, never taking more than you give.
97804**
97805*************************************************************************
97806**
97807** This file contains the implementation of the sqlite3_unlock_notify()
97808** API method and its associated functionality.
97809*/
97810
97811/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
97812#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
97813
97814/*
97815** Public interfaces:
97816**
97817**   sqlite3ConnectionBlocked()
97818**   sqlite3ConnectionUnlocked()
97819**   sqlite3ConnectionClosed()
97820**   sqlite3_unlock_notify()
97821*/
97822
97823#define assertMutexHeld() \
97824  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
97825
97826/*
97827** Head of a linked list of all sqlite3 objects created by this process
97828** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
97829** is not NULL. This variable may only accessed while the STATIC_MASTER
97830** mutex is held.
97831*/
97832static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
97833
97834#ifndef NDEBUG
97835/*
97836** This function is a complex assert() that verifies the following
97837** properties of the blocked connections list:
97838**
97839**   1) Each entry in the list has a non-NULL value for either
97840**      pUnlockConnection or pBlockingConnection, or both.
97841**
97842**   2) All entries in the list that share a common value for
97843**      xUnlockNotify are grouped together.
97844**
97845**   3) If the argument db is not NULL, then none of the entries in the
97846**      blocked connections list have pUnlockConnection or pBlockingConnection
97847**      set to db. This is used when closing connection db.
97848*/
97849static void checkListProperties(sqlite3 *db){
97850  sqlite3 *p;
97851  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
97852    int seen = 0;
97853    sqlite3 *p2;
97854
97855    /* Verify property (1) */
97856    assert( p->pUnlockConnection || p->pBlockingConnection );
97857
97858    /* Verify property (2) */
97859    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
97860      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
97861      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
97862      assert( db==0 || p->pUnlockConnection!=db );
97863      assert( db==0 || p->pBlockingConnection!=db );
97864    }
97865  }
97866}
97867#else
97868# define checkListProperties(x)
97869#endif
97870
97871/*
97872** Remove connection db from the blocked connections list. If connection
97873** db is not currently a part of the list, this function is a no-op.
97874*/
97875static void removeFromBlockedList(sqlite3 *db){
97876  sqlite3 **pp;
97877  assertMutexHeld();
97878  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
97879    if( *pp==db ){
97880      *pp = (*pp)->pNextBlocked;
97881      break;
97882    }
97883  }
97884}
97885
97886/*
97887** Add connection db to the blocked connections list. It is assumed
97888** that it is not already a part of the list.
97889*/
97890static void addToBlockedList(sqlite3 *db){
97891  sqlite3 **pp;
97892  assertMutexHeld();
97893  for(
97894    pp=&sqlite3BlockedList;
97895    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
97896    pp=&(*pp)->pNextBlocked
97897  );
97898  db->pNextBlocked = *pp;
97899  *pp = db;
97900}
97901
97902/*
97903** Obtain the STATIC_MASTER mutex.
97904*/
97905static void enterMutex(void){
97906  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
97907  checkListProperties(0);
97908}
97909
97910/*
97911** Release the STATIC_MASTER mutex.
97912*/
97913static void leaveMutex(void){
97914  assertMutexHeld();
97915  checkListProperties(0);
97916  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
97917}
97918
97919/*
97920** Register an unlock-notify callback.
97921**
97922** This is called after connection "db" has attempted some operation
97923** but has received an SQLITE_LOCKED error because another connection
97924** (call it pOther) in the same process was busy using the same shared
97925** cache.  pOther is found by looking at db->pBlockingConnection.
97926**
97927** If there is no blocking connection, the callback is invoked immediately,
97928** before this routine returns.
97929**
97930** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
97931** a deadlock.
97932**
97933** Otherwise, make arrangements to invoke xNotify when pOther drops
97934** its locks.
97935**
97936** Each call to this routine overrides any prior callbacks registered
97937** on the same "db".  If xNotify==0 then any prior callbacks are immediately
97938** cancelled.
97939*/
97940SQLITE_API int sqlite3_unlock_notify(
97941  sqlite3 *db,
97942  void (*xNotify)(void **, int),
97943  void *pArg
97944){
97945  int rc = SQLITE_OK;
97946
97947  sqlite3_mutex_enter(db->mutex);
97948  enterMutex();
97949
97950  if( xNotify==0 ){
97951    removeFromBlockedList(db);
97952    db->pUnlockConnection = 0;
97953    db->xUnlockNotify = 0;
97954    db->pUnlockArg = 0;
97955  }else if( 0==db->pBlockingConnection ){
97956    /* The blocking transaction has been concluded. Or there never was a
97957    ** blocking transaction. In either case, invoke the notify callback
97958    ** immediately.
97959    */
97960    xNotify(&pArg, 1);
97961  }else{
97962    sqlite3 *p;
97963
97964    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
97965    if( p ){
97966      rc = SQLITE_LOCKED;              /* Deadlock detected. */
97967    }else{
97968      db->pUnlockConnection = db->pBlockingConnection;
97969      db->xUnlockNotify = xNotify;
97970      db->pUnlockArg = pArg;
97971      removeFromBlockedList(db);
97972      addToBlockedList(db);
97973    }
97974  }
97975
97976  leaveMutex();
97977  assert( !db->mallocFailed );
97978  sqlite3Error(db, rc, (rc?"database is deadlocked":0));
97979  sqlite3_mutex_leave(db->mutex);
97980  return rc;
97981}
97982
97983/*
97984** This function is called while stepping or preparing a statement
97985** associated with connection db. The operation will return SQLITE_LOCKED
97986** to the user because it requires a lock that will not be available
97987** until connection pBlocker concludes its current transaction.
97988*/
97989SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
97990  enterMutex();
97991  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
97992    addToBlockedList(db);
97993  }
97994  db->pBlockingConnection = pBlocker;
97995  leaveMutex();
97996}
97997
97998/*
97999** This function is called when
98000** the transaction opened by database db has just finished. Locks held
98001** by database connection db have been released.
98002**
98003** This function loops through each entry in the blocked connections
98004** list and does the following:
98005**
98006**   1) If the sqlite3.pBlockingConnection member of a list entry is
98007**      set to db, then set pBlockingConnection=0.
98008**
98009**   2) If the sqlite3.pUnlockConnection member of a list entry is
98010**      set to db, then invoke the configured unlock-notify callback and
98011**      set pUnlockConnection=0.
98012**
98013**   3) If the two steps above mean that pBlockingConnection==0 and
98014**      pUnlockConnection==0, remove the entry from the blocked connections
98015**      list.
98016*/
98017SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
98018  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
98019  int nArg = 0;                            /* Number of entries in aArg[] */
98020  sqlite3 **pp;                            /* Iterator variable */
98021  void **aArg;               /* Arguments to the unlock callback */
98022  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
98023  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
98024
98025  aArg = aStatic;
98026  enterMutex();         /* Enter STATIC_MASTER mutex */
98027
98028  /* This loop runs once for each entry in the blocked-connections list. */
98029  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
98030    sqlite3 *p = *pp;
98031
98032    /* Step 1. */
98033    if( p->pBlockingConnection==db ){
98034      p->pBlockingConnection = 0;
98035    }
98036
98037    /* Step 2. */
98038    if( p->pUnlockConnection==db ){
98039      assert( p->xUnlockNotify );
98040      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
98041        xUnlockNotify(aArg, nArg);
98042        nArg = 0;
98043      }
98044
98045      sqlite3BeginBenignMalloc();
98046      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
98047      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
98048      if( (!aDyn && nArg==(int)ArraySize(aStatic))
98049       || (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*)))
98050      ){
98051        /* The aArg[] array needs to grow. */
98052        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
98053        if( pNew ){
98054          memcpy(pNew, aArg, nArg*sizeof(void *));
98055          sqlite3_free(aDyn);
98056          aDyn = aArg = pNew;
98057        }else{
98058          /* This occurs when the array of context pointers that need to
98059          ** be passed to the unlock-notify callback is larger than the
98060          ** aStatic[] array allocated on the stack and the attempt to
98061          ** allocate a larger array from the heap has failed.
98062          **
98063          ** This is a difficult situation to handle. Returning an error
98064          ** code to the caller is insufficient, as even if an error code
98065          ** is returned the transaction on connection db will still be
98066          ** closed and the unlock-notify callbacks on blocked connections
98067          ** will go unissued. This might cause the application to wait
98068          ** indefinitely for an unlock-notify callback that will never
98069          ** arrive.
98070          **
98071          ** Instead, invoke the unlock-notify callback with the context
98072          ** array already accumulated. We can then clear the array and
98073          ** begin accumulating any further context pointers without
98074          ** requiring any dynamic allocation. This is sub-optimal because
98075          ** it means that instead of one callback with a large array of
98076          ** context pointers the application will receive two or more
98077          ** callbacks with smaller arrays of context pointers, which will
98078          ** reduce the applications ability to prioritize multiple
98079          ** connections. But it is the best that can be done under the
98080          ** circumstances.
98081          */
98082          xUnlockNotify(aArg, nArg);
98083          nArg = 0;
98084        }
98085      }
98086      sqlite3EndBenignMalloc();
98087
98088      aArg[nArg++] = p->pUnlockArg;
98089      xUnlockNotify = p->xUnlockNotify;
98090      p->pUnlockConnection = 0;
98091      p->xUnlockNotify = 0;
98092      p->pUnlockArg = 0;
98093    }
98094
98095    /* Step 3. */
98096    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
98097      /* Remove connection p from the blocked connections list. */
98098      *pp = p->pNextBlocked;
98099      p->pNextBlocked = 0;
98100    }else{
98101      pp = &p->pNextBlocked;
98102    }
98103  }
98104
98105  if( nArg!=0 ){
98106    xUnlockNotify(aArg, nArg);
98107  }
98108  sqlite3_free(aDyn);
98109  leaveMutex();         /* Leave STATIC_MASTER mutex */
98110}
98111
98112/*
98113** This is called when the database connection passed as an argument is
98114** being closed. The connection is removed from the blocked list.
98115*/
98116SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
98117  sqlite3ConnectionUnlocked(db);
98118  enterMutex();
98119  removeFromBlockedList(db);
98120  checkListProperties(db);
98121  leaveMutex();
98122}
98123#endif
98124
98125/************** End of notify.c **********************************************/
98126/************** Begin file fts3.c ********************************************/
98127/*
98128** 2006 Oct 10
98129**
98130** The author disclaims copyright to this source code.  In place of
98131** a legal notice, here is a blessing:
98132**
98133**    May you do good and not evil.
98134**    May you find forgiveness for yourself and forgive others.
98135**    May you share freely, never taking more than you give.
98136**
98137******************************************************************************
98138**
98139** This is an SQLite module implementing full-text search.
98140*/
98141
98142/*
98143** The code in this file is only compiled if:
98144**
98145**     * The FTS3 module is being built as an extension
98146**       (in which case SQLITE_CORE is not defined), or
98147**
98148**     * The FTS3 module is being built into the core of
98149**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
98150*/
98151
98152/* TODO(shess) Consider exporting this comment to an HTML file or the
98153** wiki.
98154*/
98155/* The full-text index is stored in a series of b+tree (-like)
98156** structures called segments which map terms to doclists.  The
98157** structures are like b+trees in layout, but are constructed from the
98158** bottom up in optimal fashion and are not updatable.  Since trees
98159** are built from the bottom up, things will be described from the
98160** bottom up.
98161**
98162**
98163**** Varints ****
98164** The basic unit of encoding is a variable-length integer called a
98165** varint.  We encode variable-length integers in little-endian order
98166** using seven bits * per byte as follows:
98167**
98168** KEY:
98169**         A = 0xxxxxxx    7 bits of data and one flag bit
98170**         B = 1xxxxxxx    7 bits of data and one flag bit
98171**
98172**  7 bits - A
98173** 14 bits - BA
98174** 21 bits - BBA
98175** and so on.
98176**
98177** This is identical to how sqlite encodes varints (see util.c).
98178**
98179**
98180**** Document lists ****
98181** A doclist (document list) holds a docid-sorted list of hits for a
98182** given term.  Doclists hold docids, and can optionally associate
98183** token positions and offsets with docids.
98184**
98185** A DL_POSITIONS_OFFSETS doclist is stored like this:
98186**
98187** array {
98188**   varint docid;
98189**   array {                (position list for column 0)
98190**     varint position;     (delta from previous position plus POS_BASE)
98191**     varint startOffset;  (delta from previous startOffset)
98192**     varint endOffset;    (delta from startOffset)
98193**   }
98194**   array {
98195**     varint POS_COLUMN;   (marks start of position list for new column)
98196**     varint column;       (index of new column)
98197**     array {
98198**       varint position;   (delta from previous position plus POS_BASE)
98199**       varint startOffset;(delta from previous startOffset)
98200**       varint endOffset;  (delta from startOffset)
98201**     }
98202**   }
98203**   varint POS_END;        (marks end of positions for this document.
98204** }
98205**
98206** Here, array { X } means zero or more occurrences of X, adjacent in
98207** memory.  A "position" is an index of a token in the token stream
98208** generated by the tokenizer, while an "offset" is a byte offset,
98209** both based at 0.  Note that POS_END and POS_COLUMN occur in the
98210** same logical place as the position element, and act as sentinals
98211** ending a position list array.
98212**
98213** A DL_POSITIONS doclist omits the startOffset and endOffset
98214** information.  A DL_DOCIDS doclist omits both the position and
98215** offset information, becoming an array of varint-encoded docids.
98216**
98217** On-disk data is stored as type DL_DEFAULT, so we don't serialize
98218** the type.  Due to how deletion is implemented in the segmentation
98219** system, on-disk doclists MUST store at least positions.
98220**
98221**
98222**** Segment leaf nodes ****
98223** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
98224** nodes are written using LeafWriter, and read using LeafReader (to
98225** iterate through a single leaf node's data) and LeavesReader (to
98226** iterate through a segment's entire leaf layer).  Leaf nodes have
98227** the format:
98228**
98229** varint iHeight;             (height from leaf level, always 0)
98230** varint nTerm;               (length of first term)
98231** char pTerm[nTerm];          (content of first term)
98232** varint nDoclist;            (length of term's associated doclist)
98233** char pDoclist[nDoclist];    (content of doclist)
98234** array {
98235**                             (further terms are delta-encoded)
98236**   varint nPrefix;           (length of prefix shared with previous term)
98237**   varint nSuffix;           (length of unshared suffix)
98238**   char pTermSuffix[nSuffix];(unshared suffix of next term)
98239**   varint nDoclist;          (length of term's associated doclist)
98240**   char pDoclist[nDoclist];  (content of doclist)
98241** }
98242**
98243** Here, array { X } means zero or more occurrences of X, adjacent in
98244** memory.
98245**
98246** Leaf nodes are broken into blocks which are stored contiguously in
98247** the %_segments table in sorted order.  This means that when the end
98248** of a node is reached, the next term is in the node with the next
98249** greater node id.
98250**
98251** New data is spilled to a new leaf node when the current node
98252** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
98253** larger than STANDALONE_MIN (default 1024) is placed in a standalone
98254** node (a leaf node with a single term and doclist).  The goal of
98255** these settings is to pack together groups of small doclists while
98256** making it efficient to directly access large doclists.  The
98257** assumption is that large doclists represent terms which are more
98258** likely to be query targets.
98259**
98260** TODO(shess) It may be useful for blocking decisions to be more
98261** dynamic.  For instance, it may make more sense to have a 2.5k leaf
98262** node rather than splitting into 2k and .5k nodes.  My intuition is
98263** that this might extend through 2x or 4x the pagesize.
98264**
98265**
98266**** Segment interior nodes ****
98267** Segment interior nodes store blockids for subtree nodes and terms
98268** to describe what data is stored by the each subtree.  Interior
98269** nodes are written using InteriorWriter, and read using
98270** InteriorReader.  InteriorWriters are created as needed when
98271** SegmentWriter creates new leaf nodes, or when an interior node
98272** itself grows too big and must be split.  The format of interior
98273** nodes:
98274**
98275** varint iHeight;           (height from leaf level, always >0)
98276** varint iBlockid;          (block id of node's leftmost subtree)
98277** optional {
98278**   varint nTerm;           (length of first term)
98279**   char pTerm[nTerm];      (content of first term)
98280**   array {
98281**                                (further terms are delta-encoded)
98282**     varint nPrefix;            (length of shared prefix with previous term)
98283**     varint nSuffix;            (length of unshared suffix)
98284**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
98285**   }
98286** }
98287**
98288** Here, optional { X } means an optional element, while array { X }
98289** means zero or more occurrences of X, adjacent in memory.
98290**
98291** An interior node encodes n terms separating n+1 subtrees.  The
98292** subtree blocks are contiguous, so only the first subtree's blockid
98293** is encoded.  The subtree at iBlockid will contain all terms less
98294** than the first term encoded (or all terms if no term is encoded).
98295** Otherwise, for terms greater than or equal to pTerm[i] but less
98296** than pTerm[i+1], the subtree for that term will be rooted at
98297** iBlockid+i.  Interior nodes only store enough term data to
98298** distinguish adjacent children (if the rightmost term of the left
98299** child is "something", and the leftmost term of the right child is
98300** "wicked", only "w" is stored).
98301**
98302** New data is spilled to a new interior node at the same height when
98303** the current node exceeds INTERIOR_MAX bytes (default 2048).
98304** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
98305** interior nodes and making the tree too skinny.  The interior nodes
98306** at a given height are naturally tracked by interior nodes at
98307** height+1, and so on.
98308**
98309**
98310**** Segment directory ****
98311** The segment directory in table %_segdir stores meta-information for
98312** merging and deleting segments, and also the root node of the
98313** segment's tree.
98314**
98315** The root node is the top node of the segment's tree after encoding
98316** the entire segment, restricted to ROOT_MAX bytes (default 1024).
98317** This could be either a leaf node or an interior node.  If the top
98318** node requires more than ROOT_MAX bytes, it is flushed to %_segments
98319** and a new root interior node is generated (which should always fit
98320** within ROOT_MAX because it only needs space for 2 varints, the
98321** height and the blockid of the previous root).
98322**
98323** The meta-information in the segment directory is:
98324**   level               - segment level (see below)
98325**   idx                 - index within level
98326**                       - (level,idx uniquely identify a segment)
98327**   start_block         - first leaf node
98328**   leaves_end_block    - last leaf node
98329**   end_block           - last block (including interior nodes)
98330**   root                - contents of root node
98331**
98332** If the root node is a leaf node, then start_block,
98333** leaves_end_block, and end_block are all 0.
98334**
98335**
98336**** Segment merging ****
98337** To amortize update costs, segments are grouped into levels and
98338** merged in batches.  Each increase in level represents exponentially
98339** more documents.
98340**
98341** New documents (actually, document updates) are tokenized and
98342** written individually (using LeafWriter) to a level 0 segment, with
98343** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
98344** level 0 segments are merged into a single level 1 segment.  Level 1
98345** is populated like level 0, and eventually MERGE_COUNT level 1
98346** segments are merged to a single level 2 segment (representing
98347** MERGE_COUNT^2 updates), and so on.
98348**
98349** A segment merge traverses all segments at a given level in
98350** parallel, performing a straightforward sorted merge.  Since segment
98351** leaf nodes are written in to the %_segments table in order, this
98352** merge traverses the underlying sqlite disk structures efficiently.
98353** After the merge, all segment blocks from the merged level are
98354** deleted.
98355**
98356** MERGE_COUNT controls how often we merge segments.  16 seems to be
98357** somewhat of a sweet spot for insertion performance.  32 and 64 show
98358** very similar performance numbers to 16 on insertion, though they're
98359** a tiny bit slower (perhaps due to more overhead in merge-time
98360** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
98361** 16, 2 about 66% slower than 16.
98362**
98363** At query time, high MERGE_COUNT increases the number of segments
98364** which need to be scanned and merged.  For instance, with 100k docs
98365** inserted:
98366**
98367**    MERGE_COUNT   segments
98368**       16           25
98369**        8           12
98370**        4           10
98371**        2            6
98372**
98373** This appears to have only a moderate impact on queries for very
98374** frequent terms (which are somewhat dominated by segment merge
98375** costs), and infrequent and non-existent terms still seem to be fast
98376** even with many segments.
98377**
98378** TODO(shess) That said, it would be nice to have a better query-side
98379** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
98380** optimizations to things like doclist merging will swing the sweet
98381** spot around.
98382**
98383**
98384**
98385**** Handling of deletions and updates ****
98386** Since we're using a segmented structure, with no docid-oriented
98387** index into the term index, we clearly cannot simply update the term
98388** index when a document is deleted or updated.  For deletions, we
98389** write an empty doclist (varint(docid) varint(POS_END)), for updates
98390** we simply write the new doclist.  Segment merges overwrite older
98391** data for a particular docid with newer data, so deletes or updates
98392** will eventually overtake the earlier data and knock it out.  The
98393** query logic likewise merges doclists so that newer data knocks out
98394** older data.
98395**
98396** TODO(shess) Provide a VACUUM type operation to clear out all
98397** deletions and duplications.  This would basically be a forced merge
98398** into a single segment.
98399*/
98400
98401#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
98402
98403#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
98404# define SQLITE_CORE 1
98405#endif
98406
98407/************** Include fts3Int.h in the middle of fts3.c ********************/
98408/************** Begin file fts3Int.h *****************************************/
98409/*
98410** 2009 Nov 12
98411**
98412** The author disclaims copyright to this source code.  In place of
98413** a legal notice, here is a blessing:
98414**
98415**    May you do good and not evil.
98416**    May you find forgiveness for yourself and forgive others.
98417**    May you share freely, never taking more than you give.
98418**
98419******************************************************************************
98420**
98421*/
98422
98423#ifndef _FTSINT_H
98424#define _FTSINT_H
98425
98426#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
98427# define NDEBUG 1
98428#endif
98429
98430/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
98431/************** Begin file fts3_tokenizer.h **********************************/
98432/*
98433** 2006 July 10
98434**
98435** The author disclaims copyright to this source code.
98436**
98437*************************************************************************
98438** Defines the interface to tokenizers used by fulltext-search.  There
98439** are three basic components:
98440**
98441** sqlite3_tokenizer_module is a singleton defining the tokenizer
98442** interface functions.  This is essentially the class structure for
98443** tokenizers.
98444**
98445** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
98446** including customization information defined at creation time.
98447**
98448** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
98449** tokens from a particular input.
98450*/
98451#ifndef _FTS3_TOKENIZER_H_
98452#define _FTS3_TOKENIZER_H_
98453
98454/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
98455** If tokenizers are to be allowed to call sqlite3_*() functions, then
98456** we will need a way to register the API consistently.
98457*/
98458
98459/*
98460** Structures used by the tokenizer interface. When a new tokenizer
98461** implementation is registered, the caller provides a pointer to
98462** an sqlite3_tokenizer_module containing pointers to the callback
98463** functions that make up an implementation.
98464**
98465** When an fts3 table is created, it passes any arguments passed to
98466** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
98467** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
98468** implementation. The xCreate() function in turn returns an
98469** sqlite3_tokenizer structure representing the specific tokenizer to
98470** be used for the fts3 table (customized by the tokenizer clause arguments).
98471**
98472** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
98473** method is called. It returns an sqlite3_tokenizer_cursor object
98474** that may be used to tokenize a specific input buffer based on
98475** the tokenization rules supplied by a specific sqlite3_tokenizer
98476** object.
98477*/
98478typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
98479typedef struct sqlite3_tokenizer sqlite3_tokenizer;
98480typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
98481
98482struct sqlite3_tokenizer_module {
98483
98484  /*
98485  ** Structure version. Should always be set to 0.
98486  */
98487  int iVersion;
98488
98489  /*
98490  ** Create a new tokenizer. The values in the argv[] array are the
98491  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
98492  ** TABLE statement that created the fts3 table. For example, if
98493  ** the following SQL is executed:
98494  **
98495  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
98496  **
98497  ** then argc is set to 2, and the argv[] array contains pointers
98498  ** to the strings "arg1" and "arg2".
98499  **
98500  ** This method should return either SQLITE_OK (0), or an SQLite error
98501  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
98502  ** to point at the newly created tokenizer structure. The generic
98503  ** sqlite3_tokenizer.pModule variable should not be initialised by
98504  ** this callback. The caller will do so.
98505  */
98506  int (*xCreate)(
98507    int argc,                           /* Size of argv array */
98508    const char *const*argv,             /* Tokenizer argument strings */
98509    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
98510  );
98511
98512  /*
98513  ** Destroy an existing tokenizer. The fts3 module calls this method
98514  ** exactly once for each successful call to xCreate().
98515  */
98516  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
98517
98518  /*
98519  ** Create a tokenizer cursor to tokenize an input buffer. The caller
98520  ** is responsible for ensuring that the input buffer remains valid
98521  ** until the cursor is closed (using the xClose() method).
98522  */
98523  int (*xOpen)(
98524    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
98525    const char *pInput, int nBytes,      /* Input buffer */
98526    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
98527  );
98528
98529  /*
98530  ** Destroy an existing tokenizer cursor. The fts3 module calls this
98531  ** method exactly once for each successful call to xOpen().
98532  */
98533  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
98534
98535  /*
98536  ** Retrieve the next token from the tokenizer cursor pCursor. This
98537  ** method should either return SQLITE_OK and set the values of the
98538  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
98539  ** the end of the buffer has been reached, or an SQLite error code.
98540  **
98541  ** *ppToken should be set to point at a buffer containing the
98542  ** normalized version of the token (i.e. after any case-folding and/or
98543  ** stemming has been performed). *pnBytes should be set to the length
98544  ** of this buffer in bytes. The input text that generated the token is
98545  ** identified by the byte offsets returned in *piStartOffset and
98546  ** *piEndOffset. *piStartOffset should be set to the index of the first
98547  ** byte of the token in the input buffer. *piEndOffset should be set
98548  ** to the index of the first byte just past the end of the token in
98549  ** the input buffer.
98550  **
98551  ** The buffer *ppToken is set to point at is managed by the tokenizer
98552  ** implementation. It is only required to be valid until the next call
98553  ** to xNext() or xClose().
98554  */
98555  /* TODO(shess) current implementation requires pInput to be
98556  ** nul-terminated.  This should either be fixed, or pInput/nBytes
98557  ** should be converted to zInput.
98558  */
98559  int (*xNext)(
98560    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
98561    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
98562    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
98563    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
98564    int *piPosition      /* OUT: Number of tokens returned before this one */
98565  );
98566};
98567
98568struct sqlite3_tokenizer {
98569  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
98570  /* Tokenizer implementations will typically add additional fields */
98571};
98572
98573struct sqlite3_tokenizer_cursor {
98574  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
98575  /* Tokenizer implementations will typically add additional fields */
98576};
98577
98578int fts3_global_term_cnt(int iTerm, int iCol);
98579int fts3_term_cnt(int iTerm, int iCol);
98580
98581
98582#endif /* _FTS3_TOKENIZER_H_ */
98583
98584/************** End of fts3_tokenizer.h **************************************/
98585/************** Continuing where we left off in fts3Int.h ********************/
98586/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
98587/************** Begin file fts3_hash.h ***************************************/
98588/*
98589** 2001 September 22
98590**
98591** The author disclaims copyright to this source code.  In place of
98592** a legal notice, here is a blessing:
98593**
98594**    May you do good and not evil.
98595**    May you find forgiveness for yourself and forgive others.
98596**    May you share freely, never taking more than you give.
98597**
98598*************************************************************************
98599** This is the header file for the generic hash-table implemenation
98600** used in SQLite.  We've modified it slightly to serve as a standalone
98601** hash table implementation for the full-text indexing module.
98602**
98603*/
98604#ifndef _FTS3_HASH_H_
98605#define _FTS3_HASH_H_
98606
98607/* Forward declarations of structures. */
98608typedef struct Fts3Hash Fts3Hash;
98609typedef struct Fts3HashElem Fts3HashElem;
98610
98611/* A complete hash table is an instance of the following structure.
98612** The internals of this structure are intended to be opaque -- client
98613** code should not attempt to access or modify the fields of this structure
98614** directly.  Change this structure only by using the routines below.
98615** However, many of the "procedures" and "functions" for modifying and
98616** accessing this structure are really macros, so we can't really make
98617** this structure opaque.
98618*/
98619struct Fts3Hash {
98620  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
98621  char copyKey;           /* True if copy of key made on insert */
98622  int count;              /* Number of entries in this table */
98623  Fts3HashElem *first;    /* The first element of the array */
98624  int htsize;             /* Number of buckets in the hash table */
98625  struct _fts3ht {        /* the hash table */
98626    int count;               /* Number of entries with this hash */
98627    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
98628  } *ht;
98629};
98630
98631/* Each element in the hash table is an instance of the following
98632** structure.  All elements are stored on a single doubly-linked list.
98633**
98634** Again, this structure is intended to be opaque, but it can't really
98635** be opaque because it is used by macros.
98636*/
98637struct Fts3HashElem {
98638  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
98639  void *data;                /* Data associated with this element */
98640  void *pKey; int nKey;      /* Key associated with this element */
98641};
98642
98643/*
98644** There are 2 different modes of operation for a hash table:
98645**
98646**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
98647**                           (including the null-terminator, if any).  Case
98648**                           is respected in comparisons.
98649**
98650**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
98651**                           memcmp() is used to compare keys.
98652**
98653** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
98654*/
98655#define FTS3_HASH_STRING    1
98656#define FTS3_HASH_BINARY    2
98657
98658/*
98659** Access routines.  To delete, insert a NULL pointer.
98660*/
98661SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
98662SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
98663SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
98664SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
98665SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
98666
98667/*
98668** Shorthand for the functions above
98669*/
98670#define fts3HashInit     sqlite3Fts3HashInit
98671#define fts3HashInsert   sqlite3Fts3HashInsert
98672#define fts3HashFind     sqlite3Fts3HashFind
98673#define fts3HashClear    sqlite3Fts3HashClear
98674#define fts3HashFindElem sqlite3Fts3HashFindElem
98675
98676/*
98677** Macros for looping over all elements of a hash table.  The idiom is
98678** like this:
98679**
98680**   Fts3Hash h;
98681**   Fts3HashElem *p;
98682**   ...
98683**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
98684**     SomeStructure *pData = fts3HashData(p);
98685**     // do something with pData
98686**   }
98687*/
98688#define fts3HashFirst(H)  ((H)->first)
98689#define fts3HashNext(E)   ((E)->next)
98690#define fts3HashData(E)   ((E)->data)
98691#define fts3HashKey(E)    ((E)->pKey)
98692#define fts3HashKeysize(E) ((E)->nKey)
98693
98694/*
98695** Number of entries in a hash table
98696*/
98697#define fts3HashCount(H)  ((H)->count)
98698
98699#endif /* _FTS3_HASH_H_ */
98700
98701/************** End of fts3_hash.h *******************************************/
98702/************** Continuing where we left off in fts3Int.h ********************/
98703
98704/*
98705** This constant controls how often segments are merged. Once there are
98706** FTS3_MERGE_COUNT segments of level N, they are merged into a single
98707** segment of level N+1.
98708*/
98709#define FTS3_MERGE_COUNT 16
98710
98711/*
98712** This is the maximum amount of data (in bytes) to store in the
98713** Fts3Table.pendingTerms hash table. Normally, the hash table is
98714** populated as documents are inserted/updated/deleted in a transaction
98715** and used to create a new segment when the transaction is committed.
98716** However if this limit is reached midway through a transaction, a new
98717** segment is created and the hash table cleared immediately.
98718*/
98719#define FTS3_MAX_PENDING_DATA (1*1024*1024)
98720
98721/*
98722** Macro to return the number of elements in an array. SQLite has a
98723** similar macro called ArraySize(). Use a different name to avoid
98724** a collision when building an amalgamation with built-in FTS3.
98725*/
98726#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
98727
98728/*
98729** Maximum length of a varint encoded integer. The varint format is different
98730** from that used by SQLite, so the maximum length is 10, not 9.
98731*/
98732#define FTS3_VARINT_MAX 10
98733
98734/*
98735** This section provides definitions to allow the
98736** FTS3 extension to be compiled outside of the
98737** amalgamation.
98738*/
98739#ifndef SQLITE_AMALGAMATION
98740/*
98741** Macros indicating that conditional expressions are always true or
98742** false.
98743*/
98744# define ALWAYS(x) (x)
98745# define NEVER(X)  (x)
98746/*
98747** Internal types used by SQLite.
98748*/
98749typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
98750typedef short int i16;            /* 2-byte (or larger) signed integer */
98751typedef unsigned int u32;         /* 4-byte unsigned integer */
98752typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
98753/*
98754** Macro used to suppress compiler warnings for unused parameters.
98755*/
98756#define UNUSED_PARAMETER(x) (void)(x)
98757#endif
98758
98759typedef struct Fts3Table Fts3Table;
98760typedef struct Fts3Cursor Fts3Cursor;
98761typedef struct Fts3Expr Fts3Expr;
98762typedef struct Fts3Phrase Fts3Phrase;
98763typedef struct Fts3SegReader Fts3SegReader;
98764typedef struct Fts3SegFilter Fts3SegFilter;
98765
98766/*
98767** A connection to a fulltext index is an instance of the following
98768** structure. The xCreate and xConnect methods create an instance
98769** of this structure and xDestroy and xDisconnect free that instance.
98770** All other methods receive a pointer to the structure as one of their
98771** arguments.
98772*/
98773struct Fts3Table {
98774  sqlite3_vtab base;              /* Base class used by SQLite core */
98775  sqlite3 *db;                    /* The database connection */
98776  const char *zDb;                /* logical database name */
98777  const char *zName;              /* virtual table name */
98778  int nColumn;                    /* number of named columns in virtual table */
98779  char **azColumn;                /* column names.  malloced */
98780  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
98781
98782  /* Precompiled statements used by the implementation. Each of these
98783  ** statements is run and reset within a single virtual table API call.
98784  */
98785  sqlite3_stmt *aStmt[18];
98786
98787  /* Pointer to string containing the SQL:
98788  **
98789  ** "SELECT block FROM %_segments WHERE blockid BETWEEN ? AND ?
98790  **    ORDER BY blockid"
98791  */
98792  char *zSelectLeaves;
98793  int nLeavesStmt;                /* Valid statements in aLeavesStmt */
98794  int nLeavesTotal;               /* Total number of prepared leaves stmts */
98795  int nLeavesAlloc;               /* Allocated size of aLeavesStmt */
98796  sqlite3_stmt **aLeavesStmt;     /* Array of prepared zSelectLeaves stmts */
98797
98798  int nNodeSize;                  /* Soft limit for node size */
98799
98800  /* The following hash table is used to buffer pending index updates during
98801  ** transactions. Variable nPendingData estimates the memory size of the
98802  ** pending data, including hash table overhead, but not malloc overhead.
98803  ** When nPendingData exceeds nMaxPendingData, the buffer is flushed
98804  ** automatically. Variable iPrevDocid is the docid of the most recently
98805  ** inserted record.
98806  */
98807  int nMaxPendingData;
98808  int nPendingData;
98809  sqlite_int64 iPrevDocid;
98810  Fts3Hash pendingTerms;
98811};
98812
98813/*
98814** When the core wants to read from the virtual table, it creates a
98815** virtual table cursor (an instance of the following structure) using
98816** the xOpen method. Cursors are destroyed using the xClose method.
98817*/
98818struct Fts3Cursor {
98819  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
98820  i16 eSearch;                    /* Search strategy (see below) */
98821  u8 isEof;                       /* True if at End Of Results */
98822  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
98823  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
98824  Fts3Expr *pExpr;                /* Parsed MATCH query string */
98825  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
98826  char *pNextId;                  /* Pointer into the body of aDoclist */
98827  char *aDoclist;                 /* List of docids for full-text queries */
98828  int nDoclist;                   /* Size of buffer at aDoclist */
98829  int isMatchinfoOk;              /* True when aMatchinfo[] matches iPrevId */
98830  u32 *aMatchinfo;
98831};
98832
98833/*
98834** The Fts3Cursor.eSearch member is always set to one of the following.
98835** Actualy, Fts3Cursor.eSearch can be greater than or equal to
98836** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
98837** of the column to be searched.  For example, in
98838**
98839**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
98840**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
98841**
98842** Because the LHS of the MATCH operator is 2nd column "b",
98843** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
98844** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
98845** indicating that all columns should be searched,
98846** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
98847*/
98848#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
98849#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
98850#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
98851
98852/*
98853** A "phrase" is a sequence of one or more tokens that must match in
98854** sequence.  A single token is the base case and the most common case.
98855** For a sequence of tokens contained in "...", nToken will be the number
98856** of tokens in the string.
98857*/
98858struct Fts3Phrase {
98859  int nToken;                /* Number of tokens in the phrase */
98860  int iColumn;               /* Index of column this phrase must match */
98861  int isNot;                 /* Phrase prefixed by unary not (-) operator */
98862  struct PhraseToken {
98863    char *z;                 /* Text of the token */
98864    int n;                   /* Number of bytes in buffer pointed to by z */
98865    int isPrefix;            /* True if token ends in with a "*" character */
98866  } aToken[1];               /* One entry for each token in the phrase */
98867};
98868
98869/*
98870** A tree of these objects forms the RHS of a MATCH operator.
98871**
98872** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
98873** is true, then aDoclist points to a malloced buffer, size nDoclist bytes,
98874** containing the results of the NEAR or phrase query in FTS3 doclist
98875** format. As usual, the initial "Length" field found in doclists stored
98876** on disk is omitted from this buffer.
98877**
98878** Variable pCurrent always points to the start of a docid field within
98879** aDoclist. Since the doclist is usually scanned in docid order, this can
98880** be used to accelerate seeking to the required docid within the doclist.
98881*/
98882struct Fts3Expr {
98883  int eType;                 /* One of the FTSQUERY_XXX values defined below */
98884  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
98885  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
98886  Fts3Expr *pLeft;           /* Left operand */
98887  Fts3Expr *pRight;          /* Right operand */
98888  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
98889
98890  int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
98891  char *aDoclist;            /* Buffer containing doclist */
98892  int nDoclist;              /* Size of aDoclist in bytes */
98893
98894  sqlite3_int64 iCurrent;
98895  char *pCurrent;
98896};
98897
98898/*
98899** Candidate values for Fts3Query.eType. Note that the order of the first
98900** four values is in order of precedence when parsing expressions. For
98901** example, the following:
98902**
98903**   "a OR b AND c NOT d NEAR e"
98904**
98905** is equivalent to:
98906**
98907**   "a OR (b AND (c NOT (d NEAR e)))"
98908*/
98909#define FTSQUERY_NEAR   1
98910#define FTSQUERY_NOT    2
98911#define FTSQUERY_AND    3
98912#define FTSQUERY_OR     4
98913#define FTSQUERY_PHRASE 5
98914
98915
98916/* fts3_init.c */
98917SQLITE_PRIVATE int sqlite3Fts3DeleteVtab(int, sqlite3_vtab *);
98918SQLITE_PRIVATE int sqlite3Fts3InitVtab(int, sqlite3*, void*, int, const char*const*,
98919                        sqlite3_vtab **, char **);
98920
98921/* fts3_write.c */
98922SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
98923SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
98924SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
98925SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
98926SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(Fts3Table *,int, sqlite3_int64,
98927  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
98928SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
98929SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *, Fts3SegReader *);
98930SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
98931  Fts3Table *, Fts3SegReader **, int, Fts3SegFilter *,
98932  int (*)(Fts3Table *, void *, char *, int, char *, int),  void *
98933);
98934SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char const**, int*);
98935SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
98936
98937/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
98938#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
98939#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
98940#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
98941#define FTS3_SEGMENT_PREFIX        0x00000008
98942
98943/* Type passed as 4th argument to SegmentReaderIterate() */
98944struct Fts3SegFilter {
98945  const char *zTerm;
98946  int nTerm;
98947  int iCol;
98948  int flags;
98949};
98950
98951/* fts3.c */
98952SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
98953SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
98954SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
98955SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
98956SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
98957
98958SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
98959SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *, Fts3Expr *);
98960
98961/* fts3_tokenizer.c */
98962SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
98963SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
98964SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash,
98965  const char *, sqlite3_tokenizer **, const char **, char **
98966);
98967
98968/* fts3_snippet.c */
98969SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
98970SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context*, Fts3Cursor*,
98971  const char *, const char *, const char *
98972);
98973SQLITE_PRIVATE void sqlite3Fts3Snippet2(sqlite3_context *, Fts3Cursor *, const char *,
98974  const char *, const char *, int, int
98975);
98976SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *);
98977
98978/* fts3_expr.c */
98979SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *,
98980  char **, int, int, const char *, int, Fts3Expr **
98981);
98982SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
98983#ifdef SQLITE_TEST
98984SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
98985#endif
98986
98987#endif /* _FTSINT_H */
98988
98989/************** End of fts3Int.h *********************************************/
98990/************** Continuing where we left off in fts3.c ***********************/
98991
98992
98993#ifndef SQLITE_CORE
98994  SQLITE_EXTENSION_INIT1
98995#endif
98996
98997/*
98998** Write a 64-bit variable-length integer to memory starting at p[0].
98999** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
99000** The number of bytes written is returned.
99001*/
99002SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
99003  unsigned char *q = (unsigned char *) p;
99004  sqlite_uint64 vu = v;
99005  do{
99006    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
99007    vu >>= 7;
99008  }while( vu!=0 );
99009  q[-1] &= 0x7f;  /* turn off high bit in final byte */
99010  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
99011  return (int) (q - (unsigned char *)p);
99012}
99013
99014/*
99015** Read a 64-bit variable-length integer from memory starting at p[0].
99016** Return the number of bytes read, or 0 on error.
99017** The value is stored in *v.
99018*/
99019SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
99020  const unsigned char *q = (const unsigned char *) p;
99021  sqlite_uint64 x = 0, y = 1;
99022  while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
99023    x += y * (*q++ & 0x7f);
99024    y <<= 7;
99025  }
99026  x += y * (*q++);
99027  *v = (sqlite_int64) x;
99028  return (int) (q - (unsigned char *)p);
99029}
99030
99031/*
99032** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
99033** 32-bit integer before it is returned.
99034*/
99035SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
99036 sqlite_int64 i;
99037 int ret = sqlite3Fts3GetVarint(p, &i);
99038 *pi = (int) i;
99039 return ret;
99040}
99041
99042/*
99043** Return the number of bytes required to store the value passed as the
99044** first argument in varint form.
99045*/
99046SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
99047  int i = 0;
99048  do{
99049    i++;
99050    v >>= 7;
99051  }while( v!=0 );
99052  return i;
99053}
99054
99055/*
99056** Convert an SQL-style quoted string into a normal string by removing
99057** the quote characters.  The conversion is done in-place.  If the
99058** input does not begin with a quote character, then this routine
99059** is a no-op.
99060**
99061** Examples:
99062**
99063**     "abc"   becomes   abc
99064**     'xyz'   becomes   xyz
99065**     [pqr]   becomes   pqr
99066**     `mno`   becomes   mno
99067**
99068*/
99069SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
99070  char quote;                     /* Quote character (if any ) */
99071
99072  quote = z[0];
99073  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
99074    int iIn = 1;                  /* Index of next byte to read from input */
99075    int iOut = 0;                 /* Index of next byte to write to output */
99076
99077    /* If the first byte was a '[', then the close-quote character is a ']' */
99078    if( quote=='[' ) quote = ']';
99079
99080    while( ALWAYS(z[iIn]) ){
99081      if( z[iIn]==quote ){
99082        if( z[iIn+1]!=quote ) break;
99083        z[iOut++] = quote;
99084        iIn += 2;
99085      }else{
99086        z[iOut++] = z[iIn++];
99087      }
99088    }
99089    z[iOut] = '\0';
99090  }
99091}
99092
99093static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
99094  sqlite3_int64 iVal;
99095  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
99096  *pVal += iVal;
99097}
99098
99099static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
99100  if( *pp>=pEnd ){
99101    *pp = 0;
99102  }else{
99103    fts3GetDeltaVarint(pp, pVal);
99104  }
99105}
99106
99107/*
99108** The xDisconnect() virtual table method.
99109*/
99110static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
99111  Fts3Table *p = (Fts3Table *)pVtab;
99112  int i;
99113
99114  assert( p->nPendingData==0 );
99115
99116  /* Free any prepared statements held */
99117  for(i=0; i<SizeofArray(p->aStmt); i++){
99118    sqlite3_finalize(p->aStmt[i]);
99119  }
99120  for(i=0; i<p->nLeavesStmt; i++){
99121    sqlite3_finalize(p->aLeavesStmt[i]);
99122  }
99123  sqlite3_free(p->zSelectLeaves);
99124  sqlite3_free(p->aLeavesStmt);
99125
99126  /* Invoke the tokenizer destructor to free the tokenizer. */
99127  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
99128
99129  sqlite3_free(p);
99130  return SQLITE_OK;
99131}
99132
99133/*
99134** The xDestroy() virtual table method.
99135*/
99136static int fts3DestroyMethod(sqlite3_vtab *pVtab){
99137  int rc;                         /* Return code */
99138  Fts3Table *p = (Fts3Table *)pVtab;
99139
99140  /* Create a script to drop the underlying three storage tables. */
99141  char *zSql = sqlite3_mprintf(
99142      "DROP TABLE IF EXISTS %Q.'%q_content';"
99143      "DROP TABLE IF EXISTS %Q.'%q_segments';"
99144      "DROP TABLE IF EXISTS %Q.'%q_segdir';",
99145      p->zDb, p->zName, p->zDb, p->zName, p->zDb, p->zName
99146  );
99147
99148  /* If malloc has failed, set rc to SQLITE_NOMEM. Otherwise, try to
99149  ** execute the SQL script created above.
99150  */
99151  if( zSql ){
99152    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
99153    sqlite3_free(zSql);
99154  }else{
99155    rc = SQLITE_NOMEM;
99156  }
99157
99158  /* If everything has worked, invoke fts3DisconnectMethod() to free the
99159  ** memory associated with the Fts3Table structure and return SQLITE_OK.
99160  ** Otherwise, return an SQLite error code.
99161  */
99162  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
99163}
99164
99165
99166/*
99167** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
99168** passed as the first argument. This is done as part of the xConnect()
99169** and xCreate() methods.
99170*/
99171static int fts3DeclareVtab(Fts3Table *p){
99172  int i;                          /* Iterator variable */
99173  int rc;                         /* Return code */
99174  char *zSql;                     /* SQL statement passed to declare_vtab() */
99175  char *zCols;                    /* List of user defined columns */
99176
99177  /* Create a list of user columns for the virtual table */
99178  zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
99179  for(i=1; zCols && i<p->nColumn; i++){
99180    zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
99181  }
99182
99183  /* Create the whole "CREATE TABLE" statement to pass to SQLite */
99184  zSql = sqlite3_mprintf(
99185      "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
99186  );
99187
99188  if( !zCols || !zSql ){
99189    rc = SQLITE_NOMEM;
99190  }else{
99191    rc = sqlite3_declare_vtab(p->db, zSql);
99192  }
99193
99194  sqlite3_free(zSql);
99195  sqlite3_free(zCols);
99196  return rc;
99197}
99198
99199/*
99200** Create the backing store tables (%_content, %_segments and %_segdir)
99201** required by the FTS3 table passed as the only argument. This is done
99202** as part of the vtab xCreate() method.
99203*/
99204static int fts3CreateTables(Fts3Table *p){
99205  int rc;                         /* Return code */
99206  int i;                          /* Iterator variable */
99207  char *zContentCols;             /* Columns of %_content table */
99208  char *zSql;                     /* SQL script to create required tables */
99209
99210  /* Create a list of user columns for the content table */
99211  zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
99212  for(i=0; zContentCols && i<p->nColumn; i++){
99213    char *z = p->azColumn[i];
99214    zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
99215  }
99216
99217  /* Create the whole SQL script */
99218  zSql = sqlite3_mprintf(
99219      "CREATE TABLE %Q.'%q_content'(%s);"
99220      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);"
99221      "CREATE TABLE %Q.'%q_segdir'("
99222        "level INTEGER,"
99223        "idx INTEGER,"
99224        "start_block INTEGER,"
99225        "leaves_end_block INTEGER,"
99226        "end_block INTEGER,"
99227        "root BLOB,"
99228        "PRIMARY KEY(level, idx)"
99229      ");",
99230      p->zDb, p->zName, zContentCols, p->zDb, p->zName, p->zDb, p->zName
99231  );
99232
99233  /* Unless a malloc() failure has occurred, execute the SQL script to
99234  ** create the tables used to store data for this FTS3 virtual table.
99235  */
99236  if( zContentCols==0 || zSql==0 ){
99237    rc = SQLITE_NOMEM;
99238  }else{
99239    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
99240  }
99241
99242  sqlite3_free(zSql);
99243  sqlite3_free(zContentCols);
99244  return rc;
99245}
99246
99247/*
99248** This function is the implementation of both the xConnect and xCreate
99249** methods of the FTS3 virtual table.
99250**
99251** The argv[] array contains the following:
99252**
99253**   argv[0]   -> module name
99254**   argv[1]   -> database name
99255**   argv[2]   -> table name
99256**   argv[...] -> "column name" and other module argument fields.
99257*/
99258static int fts3InitVtab(
99259  int isCreate,                   /* True for xCreate, false for xConnect */
99260  sqlite3 *db,                    /* The SQLite database connection */
99261  void *pAux,                     /* Hash table containing tokenizers */
99262  int argc,                       /* Number of elements in argv array */
99263  const char * const *argv,       /* xCreate/xConnect argument array */
99264  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
99265  char **pzErr                    /* Write any error message here */
99266){
99267  Fts3Hash *pHash = (Fts3Hash *)pAux;
99268  Fts3Table *p;                   /* Pointer to allocated vtab */
99269  int rc;                         /* Return code */
99270  int i;                          /* Iterator variable */
99271  int nByte;                      /* Size of allocation used for *p */
99272  int iCol;
99273  int nString = 0;
99274  int nCol = 0;
99275  char *zCsr;
99276  int nDb;
99277  int nName;
99278
99279  const char *zTokenizer = 0;               /* Name of tokenizer to use */
99280  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
99281
99282  nDb = (int)strlen(argv[1]) + 1;
99283  nName = (int)strlen(argv[2]) + 1;
99284  for(i=3; i<argc; i++){
99285    char const *z = argv[i];
99286    rc = sqlite3Fts3InitTokenizer(pHash, z, &pTokenizer, &zTokenizer, pzErr);
99287    if( rc!=SQLITE_OK ){
99288      return rc;
99289    }
99290    if( z!=zTokenizer ){
99291      nString += (int)(strlen(z) + 1);
99292    }
99293  }
99294  nCol = argc - 3 - (zTokenizer!=0);
99295  if( zTokenizer==0 ){
99296    rc = sqlite3Fts3InitTokenizer(pHash, 0, &pTokenizer, 0, pzErr);
99297    if( rc!=SQLITE_OK ){
99298      return rc;
99299    }
99300    assert( pTokenizer );
99301  }
99302
99303  if( nCol==0 ){
99304    nCol = 1;
99305  }
99306
99307  /* Allocate and populate the Fts3Table structure. */
99308  nByte = sizeof(Fts3Table) +              /* Fts3Table */
99309          nCol * sizeof(char *) +              /* azColumn */
99310          nName +                              /* zName */
99311          nDb +                                /* zDb */
99312          nString;                             /* Space for azColumn strings */
99313  p = (Fts3Table*)sqlite3_malloc(nByte);
99314  if( p==0 ){
99315    rc = SQLITE_NOMEM;
99316    goto fts3_init_out;
99317  }
99318  memset(p, 0, nByte);
99319
99320  p->db = db;
99321  p->nColumn = nCol;
99322  p->nPendingData = 0;
99323  p->azColumn = (char **)&p[1];
99324  p->pTokenizer = pTokenizer;
99325  p->nNodeSize = 1000;
99326  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
99327  zCsr = (char *)&p->azColumn[nCol];
99328
99329  fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
99330
99331  /* Fill in the zName and zDb fields of the vtab structure. */
99332  p->zName = zCsr;
99333  memcpy(zCsr, argv[2], nName);
99334  zCsr += nName;
99335  p->zDb = zCsr;
99336  memcpy(zCsr, argv[1], nDb);
99337  zCsr += nDb;
99338
99339  /* Fill in the azColumn array */
99340  iCol = 0;
99341  for(i=3; i<argc; i++){
99342    if( argv[i]!=zTokenizer ){
99343      char *z;
99344      int n;
99345      z = (char *)sqlite3Fts3NextToken(argv[i], &n);
99346      memcpy(zCsr, z, n);
99347      zCsr[n] = '\0';
99348      sqlite3Fts3Dequote(zCsr);
99349      p->azColumn[iCol++] = zCsr;
99350      zCsr += n+1;
99351      assert( zCsr <= &((char *)p)[nByte] );
99352    }
99353  }
99354  if( iCol==0 ){
99355    assert( nCol==1 );
99356    p->azColumn[0] = "content";
99357  }
99358
99359  /* If this is an xCreate call, create the underlying tables in the
99360  ** database. TODO: For xConnect(), it could verify that said tables exist.
99361  */
99362  if( isCreate ){
99363    rc = fts3CreateTables(p);
99364    if( rc!=SQLITE_OK ) goto fts3_init_out;
99365  }
99366
99367  rc = fts3DeclareVtab(p);
99368  if( rc!=SQLITE_OK ) goto fts3_init_out;
99369
99370  *ppVTab = &p->base;
99371
99372fts3_init_out:
99373  assert( p || (pTokenizer && rc!=SQLITE_OK) );
99374  if( rc!=SQLITE_OK ){
99375    if( p ){
99376      fts3DisconnectMethod((sqlite3_vtab *)p);
99377    }else{
99378      pTokenizer->pModule->xDestroy(pTokenizer);
99379    }
99380  }
99381  return rc;
99382}
99383
99384/*
99385** The xConnect() and xCreate() methods for the virtual table. All the
99386** work is done in function fts3InitVtab().
99387*/
99388static int fts3ConnectMethod(
99389  sqlite3 *db,                    /* Database connection */
99390  void *pAux,                     /* Pointer to tokenizer hash table */
99391  int argc,                       /* Number of elements in argv array */
99392  const char * const *argv,       /* xCreate/xConnect argument array */
99393  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
99394  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
99395){
99396  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
99397}
99398static int fts3CreateMethod(
99399  sqlite3 *db,                    /* Database connection */
99400  void *pAux,                     /* Pointer to tokenizer hash table */
99401  int argc,                       /* Number of elements in argv array */
99402  const char * const *argv,       /* xCreate/xConnect argument array */
99403  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
99404  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
99405){
99406  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
99407}
99408
99409/*
99410** Implementation of the xBestIndex method for FTS3 tables. There
99411** are three possible strategies, in order of preference:
99412**
99413**   1. Direct lookup by rowid or docid.
99414**   2. Full-text search using a MATCH operator on a non-docid column.
99415**   3. Linear scan of %_content table.
99416*/
99417static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
99418  Fts3Table *p = (Fts3Table *)pVTab;
99419  int i;                          /* Iterator variable */
99420  int iCons = -1;                 /* Index of constraint to use */
99421
99422  /* By default use a full table scan. This is an expensive option,
99423  ** so search through the constraints to see if a more efficient
99424  ** strategy is possible.
99425  */
99426  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
99427  pInfo->estimatedCost = 500000;
99428  for(i=0; i<pInfo->nConstraint; i++){
99429    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
99430    if( pCons->usable==0 ) continue;
99431
99432    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
99433    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
99434     && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
99435    ){
99436      pInfo->idxNum = FTS3_DOCID_SEARCH;
99437      pInfo->estimatedCost = 1.0;
99438      iCons = i;
99439    }
99440
99441    /* A MATCH constraint. Use a full-text search.
99442    **
99443    ** If there is more than one MATCH constraint available, use the first
99444    ** one encountered. If there is both a MATCH constraint and a direct
99445    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
99446    ** though the rowid/docid lookup is faster than a MATCH query, selecting
99447    ** it would lead to an "unable to use function MATCH in the requested
99448    ** context" error.
99449    */
99450    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
99451     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
99452    ){
99453      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
99454      pInfo->estimatedCost = 2.0;
99455      iCons = i;
99456      break;
99457    }
99458  }
99459
99460  if( iCons>=0 ){
99461    pInfo->aConstraintUsage[iCons].argvIndex = 1;
99462    pInfo->aConstraintUsage[iCons].omit = 1;
99463  }
99464  return SQLITE_OK;
99465}
99466
99467/*
99468** Implementation of xOpen method.
99469*/
99470static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
99471  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
99472
99473  UNUSED_PARAMETER(pVTab);
99474
99475  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
99476  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
99477  ** if the allocation fails, return SQLITE_NOMEM.
99478  */
99479  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
99480  if( !pCsr ){
99481    return SQLITE_NOMEM;
99482  }
99483  memset(pCsr, 0, sizeof(Fts3Cursor));
99484  return SQLITE_OK;
99485}
99486
99487/****************************************************************/
99488/****************************************************************/
99489/****************************************************************/
99490/****************************************************************/
99491
99492
99493/*
99494** Close the cursor.  For additional information see the documentation
99495** on the xClose method of the virtual table interface.
99496*/
99497static int fulltextClose(sqlite3_vtab_cursor *pCursor){
99498  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
99499  sqlite3_finalize(pCsr->pStmt);
99500  sqlite3Fts3ExprFree(pCsr->pExpr);
99501  sqlite3_free(pCsr->aDoclist);
99502  sqlite3_free(pCsr->aMatchinfo);
99503  sqlite3_free(pCsr);
99504  return SQLITE_OK;
99505}
99506
99507static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
99508  if( pCsr->isRequireSeek ){
99509    pCsr->isRequireSeek = 0;
99510    sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
99511    if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
99512      return SQLITE_OK;
99513    }else{
99514      int rc = sqlite3_reset(pCsr->pStmt);
99515      if( rc==SQLITE_OK ){
99516        /* If no row was found and no error has occured, then the %_content
99517        ** table is missing a row that is present in the full-text index.
99518        ** The data structures are corrupt.
99519        */
99520        rc = SQLITE_CORRUPT;
99521      }
99522      pCsr->isEof = 1;
99523      if( pContext ){
99524        sqlite3_result_error_code(pContext, rc);
99525      }
99526      return rc;
99527    }
99528  }else{
99529    return SQLITE_OK;
99530  }
99531}
99532
99533static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
99534  int rc = SQLITE_OK;             /* Return code */
99535  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
99536
99537  if( pCsr->aDoclist==0 ){
99538    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
99539      pCsr->isEof = 1;
99540      rc = sqlite3_reset(pCsr->pStmt);
99541    }
99542  }else if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
99543    pCsr->isEof = 1;
99544  }else{
99545    sqlite3_reset(pCsr->pStmt);
99546    fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
99547    pCsr->isRequireSeek = 1;
99548    pCsr->isMatchinfoOk = 1;
99549  }
99550  return rc;
99551}
99552
99553
99554/*
99555** The buffer pointed to by argument zNode (size nNode bytes) contains the
99556** root node of a b-tree segment. The segment is guaranteed to be at least
99557** one level high (i.e. the root node is not also a leaf). If successful,
99558** this function locates the leaf node of the segment that may contain the
99559** term specified by arguments zTerm and nTerm and writes its block number
99560** to *piLeaf.
99561**
99562** It is possible that the returned leaf node does not contain the specified
99563** term. However, if the segment does contain said term, it is stored on
99564** the identified leaf node. Because this function only inspects interior
99565** segment nodes (and never loads leaf nodes into memory), it is not possible
99566** to be sure.
99567**
99568** If an error occurs, an error code other than SQLITE_OK is returned.
99569*/
99570static int fts3SelectLeaf(
99571  Fts3Table *p,                   /* Virtual table handle */
99572  const char *zTerm,              /* Term to select leaves for */
99573  int nTerm,                      /* Size of term zTerm in bytes */
99574  const char *zNode,              /* Buffer containing segment interior node */
99575  int nNode,                      /* Size of buffer at zNode */
99576  sqlite3_int64 *piLeaf           /* Selected leaf node */
99577){
99578  int rc = SQLITE_OK;             /* Return code */
99579  const char *zCsr = zNode;       /* Cursor to iterate through node */
99580  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
99581  char *zBuffer = 0;              /* Buffer to load terms into */
99582  int nAlloc = 0;                 /* Size of allocated buffer */
99583
99584  while( 1 ){
99585    int isFirstTerm = 1;          /* True when processing first term on page */
99586    int iHeight;                  /* Height of this node in tree */
99587    sqlite3_int64 iChild;         /* Block id of child node to descend to */
99588    int nBlock;                   /* Size of child node in bytes */
99589
99590    zCsr += sqlite3Fts3GetVarint32(zCsr, &iHeight);
99591    zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
99592
99593    while( zCsr<zEnd ){
99594      int cmp;                    /* memcmp() result */
99595      int nSuffix;                /* Size of term suffix */
99596      int nPrefix = 0;            /* Size of term prefix */
99597      int nBuffer;                /* Total term size */
99598
99599      /* Load the next term on the node into zBuffer */
99600      if( !isFirstTerm ){
99601        zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
99602      }
99603      isFirstTerm = 0;
99604      zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
99605      if( nPrefix+nSuffix>nAlloc ){
99606        char *zNew;
99607        nAlloc = (nPrefix+nSuffix) * 2;
99608        zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
99609        if( !zNew ){
99610          sqlite3_free(zBuffer);
99611          return SQLITE_NOMEM;
99612        }
99613        zBuffer = zNew;
99614      }
99615      memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
99616      nBuffer = nPrefix + nSuffix;
99617      zCsr += nSuffix;
99618
99619      /* Compare the term we are searching for with the term just loaded from
99620      ** the interior node. If the specified term is greater than or equal
99621      ** to the term from the interior node, then all terms on the sub-tree
99622      ** headed by node iChild are smaller than zTerm. No need to search
99623      ** iChild.
99624      **
99625      ** If the interior node term is larger than the specified term, then
99626      ** the tree headed by iChild may contain the specified term.
99627      */
99628      cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
99629      if( cmp<0 || (cmp==0 && nBuffer>nTerm) ) break;
99630      iChild++;
99631    };
99632
99633    /* If (iHeight==1), the children of this interior node are leaves. The
99634    ** specified term may be present on leaf node iChild.
99635    */
99636    if( iHeight==1 ){
99637      *piLeaf = iChild;
99638      break;
99639    }
99640
99641    /* Descend to interior node iChild. */
99642    rc = sqlite3Fts3ReadBlock(p, iChild, &zCsr, &nBlock);
99643    if( rc!=SQLITE_OK ) break;
99644    zEnd = &zCsr[nBlock];
99645  }
99646  sqlite3_free(zBuffer);
99647  return rc;
99648}
99649
99650/*
99651** This function is used to create delta-encoded serialized lists of FTS3
99652** varints. Each call to this function appends a single varint to a list.
99653*/
99654static void fts3PutDeltaVarint(
99655  char **pp,                      /* IN/OUT: Output pointer */
99656  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
99657  sqlite3_int64 iVal              /* Write this value to the list */
99658){
99659  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
99660  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
99661  *piPrev = iVal;
99662}
99663
99664/*
99665** When this function is called, *ppPoslist is assumed to point to the
99666** start of a position-list.
99667*/
99668static void fts3PoslistCopy(char **pp, char **ppPoslist){
99669  char *pEnd = *ppPoslist;
99670  char c = 0;
99671
99672  /* The end of a position list is marked by a zero encoded as an FTS3
99673  ** varint. A single 0x00 byte. Except, if the 0x00 byte is preceded by
99674  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
99675  ** of some other, multi-byte, value.
99676  **
99677  ** The following block moves pEnd to point to the first byte that is not
99678  ** immediately preceded by a byte with the 0x80 bit set. Then increments
99679  ** pEnd once more so that it points to the byte immediately following the
99680  ** last byte in the position-list.
99681  */
99682  while( *pEnd | c ) c = *pEnd++ & 0x80;
99683  pEnd++;
99684
99685  if( pp ){
99686    int n = (int)(pEnd - *ppPoslist);
99687    char *p = *pp;
99688    memcpy(p, *ppPoslist, n);
99689    p += n;
99690    *pp = p;
99691  }
99692  *ppPoslist = pEnd;
99693}
99694
99695static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
99696  char *pEnd = *ppPoslist;
99697  char c = 0;
99698
99699  /* A column-list is terminated by either a 0x01 or 0x00. */
99700  while( 0xFE & (*pEnd | c) ) c = *pEnd++ & 0x80;
99701  if( pp ){
99702    int n = (int)(pEnd - *ppPoslist);
99703    char *p = *pp;
99704    memcpy(p, *ppPoslist, n);
99705    p += n;
99706    *pp = p;
99707  }
99708  *ppPoslist = pEnd;
99709}
99710
99711/*
99712** Value used to signify the end of an offset-list. This is safe because
99713** it is not possible to have a document with 2^31 terms.
99714*/
99715#define OFFSET_LIST_END 0x7fffffff
99716
99717/*
99718** This function is used to help parse offset-lists. When this function is
99719** called, *pp may point to the start of the next varint in the offset-list
99720** being parsed, or it may point to 1 byte past the end of the offset-list
99721** (in which case **pp will be 0x00 or 0x01).
99722**
99723** If *pp points past the end of the current offset list, set *pi to
99724** OFFSET_LIST_END and return. Otherwise, read the next varint from *pp,
99725** increment the current value of *pi by the value read, and set *pp to
99726** point to the next value before returning.
99727*/
99728static void fts3ReadNextPos(
99729  char **pp,                      /* IN/OUT: Pointer into offset-list buffer */
99730  sqlite3_int64 *pi               /* IN/OUT: Value read from offset-list */
99731){
99732  if( **pp&0xFE ){
99733    fts3GetDeltaVarint(pp, pi);
99734    *pi -= 2;
99735  }else{
99736    *pi = OFFSET_LIST_END;
99737  }
99738}
99739
99740/*
99741** If parameter iCol is not 0, write an 0x01 byte followed by the value of
99742** iCol encoded as a varint to *pp.
99743**
99744** Set *pp to point to the byte just after the last byte written before
99745** returning (do not modify it if iCol==0). Return the total number of bytes
99746** written (0 if iCol==0).
99747*/
99748static int fts3PutColNumber(char **pp, int iCol){
99749  int n = 0;                      /* Number of bytes written */
99750  if( iCol ){
99751    char *p = *pp;                /* Output pointer */
99752    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
99753    *p = 0x01;
99754    *pp = &p[n];
99755  }
99756  return n;
99757}
99758
99759/*
99760**
99761*/
99762static void fts3PoslistMerge(
99763  char **pp,                      /* Output buffer */
99764  char **pp1,                     /* Left input list */
99765  char **pp2                      /* Right input list */
99766){
99767  char *p = *pp;
99768  char *p1 = *pp1;
99769  char *p2 = *pp2;
99770
99771  while( *p1 || *p2 ){
99772    int iCol1;
99773    int iCol2;
99774
99775    if( *p1==0x01 ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
99776    else if( *p1==0x00 ) iCol1 = OFFSET_LIST_END;
99777    else iCol1 = 0;
99778
99779    if( *p2==0x01 ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
99780    else if( *p2==0x00 ) iCol2 = OFFSET_LIST_END;
99781    else iCol2 = 0;
99782
99783    if( iCol1==iCol2 ){
99784      sqlite3_int64 i1 = 0;
99785      sqlite3_int64 i2 = 0;
99786      sqlite3_int64 iPrev = 0;
99787      int n = fts3PutColNumber(&p, iCol1);
99788      p1 += n;
99789      p2 += n;
99790
99791      /* At this point, both p1 and p2 point to the start of offset-lists.
99792      ** An offset-list is a list of non-negative delta-encoded varints, each
99793      ** incremented by 2 before being stored. Each list is terminated by a 0
99794      ** or 1 value (0x00 or 0x01). The following block merges the two lists
99795      ** and writes the results to buffer p. p is left pointing to the byte
99796      ** after the list written. No terminator (0x00 or 0x01) is written to
99797      ** the output.
99798      */
99799      fts3GetDeltaVarint(&p1, &i1);
99800      fts3GetDeltaVarint(&p2, &i2);
99801      do {
99802        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
99803        iPrev -= 2;
99804        if( i1==i2 ){
99805          fts3ReadNextPos(&p1, &i1);
99806          fts3ReadNextPos(&p2, &i2);
99807        }else if( i1<i2 ){
99808          fts3ReadNextPos(&p1, &i1);
99809        }else{
99810          fts3ReadNextPos(&p2, &i2);
99811        }
99812      }while( i1!=OFFSET_LIST_END || i2!=OFFSET_LIST_END );
99813    }else if( iCol1<iCol2 ){
99814      p1 += fts3PutColNumber(&p, iCol1);
99815      fts3ColumnlistCopy(&p, &p1);
99816    }else{
99817      p2 += fts3PutColNumber(&p, iCol2);
99818      fts3ColumnlistCopy(&p, &p2);
99819    }
99820  }
99821
99822  *p++ = '\0';
99823  *pp = p;
99824  *pp1 = p1 + 1;
99825  *pp2 = p2 + 1;
99826}
99827
99828/*
99829** nToken==1 searches for adjacent positions.
99830*/
99831static int fts3PoslistPhraseMerge(
99832  char **pp,                      /* Output buffer */
99833  int nToken,                     /* Maximum difference in token positions */
99834  int isSaveLeft,                 /* Save the left position */
99835  char **pp1,                     /* Left input list */
99836  char **pp2                      /* Right input list */
99837){
99838  char *p = (pp ? *pp : 0);
99839  char *p1 = *pp1;
99840  char *p2 = *pp2;
99841
99842  int iCol1 = 0;
99843  int iCol2 = 0;
99844  assert( *p1!=0 && *p2!=0 );
99845  if( *p1==0x01 ){
99846    p1++;
99847    p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
99848  }
99849  if( *p2==0x01 ){
99850    p2++;
99851    p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
99852  }
99853
99854  while( 1 ){
99855    if( iCol1==iCol2 ){
99856      char *pSave = p;
99857      sqlite3_int64 iPrev = 0;
99858      sqlite3_int64 iPos1 = 0;
99859      sqlite3_int64 iPos2 = 0;
99860
99861      if( pp && iCol1 ){
99862        *p++ = 0x01;
99863        p += sqlite3Fts3PutVarint(p, iCol1);
99864      }
99865
99866      assert( *p1!=0x00 && *p2!=0x00 && *p1!=0x01 && *p2!=0x01 );
99867      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
99868      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
99869
99870      while( 1 ){
99871        if( iPos2>iPos1 && iPos2<=iPos1+nToken ){
99872          sqlite3_int64 iSave;
99873          if( !pp ){
99874            fts3PoslistCopy(0, &p2);
99875            fts3PoslistCopy(0, &p1);
99876            *pp1 = p1;
99877            *pp2 = p2;
99878            return 1;
99879          }
99880          iSave = isSaveLeft ? iPos1 : iPos2;
99881          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
99882          pSave = 0;
99883        }
99884        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
99885          if( (*p2&0xFE)==0 ) break;
99886          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
99887        }else{
99888          if( (*p1&0xFE)==0 ) break;
99889          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
99890        }
99891      }
99892
99893      if( pSave ){
99894        assert( pp && p );
99895        p = pSave;
99896      }
99897
99898      fts3ColumnlistCopy(0, &p1);
99899      fts3ColumnlistCopy(0, &p2);
99900      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
99901      if( 0==*p1 || 0==*p2 ) break;
99902
99903      p1++;
99904      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
99905      p2++;
99906      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
99907    }
99908
99909    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
99910    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
99911    ** end of the position list, or the 0x01 that precedes the next
99912    ** column-number in the position list.
99913    */
99914    else if( iCol1<iCol2 ){
99915      fts3ColumnlistCopy(0, &p1);
99916      if( 0==*p1 ) break;
99917      p1++;
99918      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
99919    }else{
99920      fts3ColumnlistCopy(0, &p2);
99921      if( 0==*p2 ) break;
99922      p2++;
99923      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
99924    }
99925  }
99926
99927  fts3PoslistCopy(0, &p2);
99928  fts3PoslistCopy(0, &p1);
99929  *pp1 = p1;
99930  *pp2 = p2;
99931  if( !pp || *pp==p ){
99932    return 0;
99933  }
99934  *p++ = 0x00;
99935  *pp = p;
99936  return 1;
99937}
99938
99939/*
99940** Merge two position-lists as required by the NEAR operator.
99941*/
99942static int fts3PoslistNearMerge(
99943  char **pp,                      /* Output buffer */
99944  char *aTmp,                     /* Temporary buffer space */
99945  int nRight,                     /* Maximum difference in token positions */
99946  int nLeft,                      /* Maximum difference in token positions */
99947  char **pp1,                     /* IN/OUT: Left input list */
99948  char **pp2                      /* IN/OUT: Right input list */
99949){
99950  char *p1 = *pp1;
99951  char *p2 = *pp2;
99952
99953  if( !pp ){
99954    if( fts3PoslistPhraseMerge(0, nRight, 0, pp1, pp2) ) return 1;
99955    *pp1 = p1;
99956    *pp2 = p2;
99957    return fts3PoslistPhraseMerge(0, nLeft, 0, pp2, pp1);
99958  }else{
99959    char *pTmp1 = aTmp;
99960    char *pTmp2;
99961    char *aTmp2;
99962    int res = 1;
99963
99964    fts3PoslistPhraseMerge(&pTmp1, nRight, 0, pp1, pp2);
99965    aTmp2 = pTmp2 = pTmp1;
99966    *pp1 = p1;
99967    *pp2 = p2;
99968    fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, pp2, pp1);
99969    if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
99970      fts3PoslistMerge(pp, &aTmp, &aTmp2);
99971    }else if( pTmp1!=aTmp ){
99972      fts3PoslistCopy(pp, &aTmp);
99973    }else if( pTmp2!=aTmp2 ){
99974      fts3PoslistCopy(pp, &aTmp2);
99975    }else{
99976      res = 0;
99977    }
99978
99979    return res;
99980  }
99981}
99982
99983/*
99984** Values that may be used as the first parameter to fts3DoclistMerge().
99985*/
99986#define MERGE_NOT        2        /* D + D -> D */
99987#define MERGE_AND        3        /* D + D -> D */
99988#define MERGE_OR         4        /* D + D -> D */
99989#define MERGE_POS_OR     5        /* P + P -> P */
99990#define MERGE_PHRASE     6        /* P + P -> D */
99991#define MERGE_POS_PHRASE 7        /* P + P -> P */
99992#define MERGE_NEAR       8        /* P + P -> D */
99993#define MERGE_POS_NEAR   9        /* P + P -> P */
99994
99995/*
99996** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
99997** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
99998** which is guaranteed to be large enough to hold the results. The number
99999** of bytes written to aBuffer is stored in *pnBuffer before returning.
100000**
100001** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
100002** occurs while allocating a temporary buffer as part of the merge operation,
100003** SQLITE_NOMEM is returned.
100004*/
100005static int fts3DoclistMerge(
100006  int mergetype,                  /* One of the MERGE_XXX constants */
100007  int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
100008  int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
100009  char *aBuffer,                  /* Pre-allocated output buffer */
100010  int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
100011  char *a1,                       /* Buffer containing first doclist */
100012  int n1,                         /* Size of buffer a1 */
100013  char *a2,                       /* Buffer containing second doclist */
100014  int n2                          /* Size of buffer a2 */
100015){
100016  sqlite3_int64 i1 = 0;
100017  sqlite3_int64 i2 = 0;
100018  sqlite3_int64 iPrev = 0;
100019
100020  char *p = aBuffer;
100021  char *p1 = a1;
100022  char *p2 = a2;
100023  char *pEnd1 = &a1[n1];
100024  char *pEnd2 = &a2[n2];
100025
100026  assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR
100027       || mergetype==MERGE_AND    || mergetype==MERGE_NOT
100028       || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
100029       || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
100030  );
100031
100032  if( !aBuffer ){
100033    *pnBuffer = 0;
100034    return SQLITE_NOMEM;
100035  }
100036
100037  /* Read the first docid from each doclist */
100038  fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100039  fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100040
100041  switch( mergetype ){
100042    case MERGE_OR:
100043    case MERGE_POS_OR:
100044      while( p1 || p2 ){
100045        if( p2 && p1 && i1==i2 ){
100046          fts3PutDeltaVarint(&p, &iPrev, i1);
100047          if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
100048          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100049          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100050        }else if( !p2 || (p1 && i1<i2) ){
100051          fts3PutDeltaVarint(&p, &iPrev, i1);
100052          if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
100053          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100054        }else{
100055          fts3PutDeltaVarint(&p, &iPrev, i2);
100056          if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
100057          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100058        }
100059      }
100060      break;
100061
100062    case MERGE_AND:
100063      while( p1 && p2 ){
100064        if( i1==i2 ){
100065          fts3PutDeltaVarint(&p, &iPrev, i1);
100066          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100067          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100068        }else if( i1<i2 ){
100069          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100070        }else{
100071          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100072        }
100073      }
100074      break;
100075
100076    case MERGE_NOT:
100077      while( p1 ){
100078        if( p2 && i1==i2 ){
100079          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100080          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100081        }else if( !p2 || i1<i2 ){
100082          fts3PutDeltaVarint(&p, &iPrev, i1);
100083          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100084        }else{
100085          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100086        }
100087      }
100088      break;
100089
100090    case MERGE_POS_PHRASE:
100091    case MERGE_PHRASE: {
100092      char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
100093      while( p1 && p2 ){
100094        if( i1==i2 ){
100095          char *pSave = p;
100096          sqlite3_int64 iPrevSave = iPrev;
100097          fts3PutDeltaVarint(&p, &iPrev, i1);
100098          if( 0==fts3PoslistPhraseMerge(ppPos, 1, 0, &p1, &p2) ){
100099            p = pSave;
100100            iPrev = iPrevSave;
100101          }
100102          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100103          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100104        }else if( i1<i2 ){
100105          fts3PoslistCopy(0, &p1);
100106          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100107        }else{
100108          fts3PoslistCopy(0, &p2);
100109          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100110        }
100111      }
100112      break;
100113    }
100114
100115    default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
100116      char *aTmp = 0;
100117      char **ppPos = 0;
100118      if( mergetype==MERGE_POS_NEAR ){
100119        ppPos = &p;
100120        aTmp = sqlite3_malloc(2*(n1+n2+1));
100121        if( !aTmp ){
100122          return SQLITE_NOMEM;
100123        }
100124      }
100125
100126      while( p1 && p2 ){
100127        if( i1==i2 ){
100128          char *pSave = p;
100129          sqlite3_int64 iPrevSave = iPrev;
100130          fts3PutDeltaVarint(&p, &iPrev, i1);
100131
100132          if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
100133            iPrev = iPrevSave;
100134            p = pSave;
100135          }
100136
100137          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100138          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100139        }else if( i1<i2 ){
100140          fts3PoslistCopy(0, &p1);
100141          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
100142        }else{
100143          fts3PoslistCopy(0, &p2);
100144          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
100145        }
100146      }
100147      sqlite3_free(aTmp);
100148      break;
100149    }
100150  }
100151
100152  *pnBuffer = (int)(p-aBuffer);
100153  return SQLITE_OK;
100154}
100155
100156/*
100157** A pointer to an instance of this structure is used as the context
100158** argument to sqlite3Fts3SegReaderIterate()
100159*/
100160typedef struct TermSelect TermSelect;
100161struct TermSelect {
100162  int isReqPos;
100163  char *aOutput;                  /* Malloc'd output buffer */
100164  int nOutput;                    /* Size of output in bytes */
100165};
100166
100167/*
100168** This function is used as the sqlite3Fts3SegReaderIterate() callback when
100169** querying the full-text index for a doclist associated with a term or
100170** term-prefix.
100171*/
100172static int fts3TermSelectCb(
100173  Fts3Table *p,                   /* Virtual table object */
100174  void *pContext,                 /* Pointer to TermSelect structure */
100175  char *zTerm,
100176  int nTerm,
100177  char *aDoclist,
100178  int nDoclist
100179){
100180  TermSelect *pTS = (TermSelect *)pContext;
100181  int nNew = pTS->nOutput + nDoclist;
100182  char *aNew = sqlite3_malloc(nNew);
100183
100184  UNUSED_PARAMETER(p);
100185  UNUSED_PARAMETER(zTerm);
100186  UNUSED_PARAMETER(nTerm);
100187
100188  if( !aNew ){
100189    return SQLITE_NOMEM;
100190  }
100191
100192  if( pTS->nOutput==0 ){
100193    /* If this is the first term selected, copy the doclist to the output
100194    ** buffer using memcpy(). TODO: Add a way to transfer control of the
100195    ** aDoclist buffer from the caller so as to avoid the memcpy().
100196    */
100197    memcpy(aNew, aDoclist, nDoclist);
100198  }else{
100199    /* The output buffer is not empty. Merge doclist aDoclist with the
100200    ** existing output. This can only happen with prefix-searches (as
100201    ** searches for exact terms return exactly one doclist).
100202    */
100203    int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
100204    fts3DoclistMerge(mergetype, 0, 0,
100205        aNew, &nNew, pTS->aOutput, pTS->nOutput, aDoclist, nDoclist
100206    );
100207  }
100208
100209  sqlite3_free(pTS->aOutput);
100210  pTS->aOutput = aNew;
100211  pTS->nOutput = nNew;
100212
100213  return SQLITE_OK;
100214}
100215
100216/*
100217** This function retreives the doclist for the specified term (or term
100218** prefix) from the database.
100219**
100220** The returned doclist may be in one of two formats, depending on the
100221** value of parameter isReqPos. If isReqPos is zero, then the doclist is
100222** a sorted list of delta-compressed docids. If isReqPos is non-zero,
100223** then the returned list is in the same format as is stored in the
100224** database without the found length specifier at the start of on-disk
100225** doclists.
100226*/
100227static int fts3TermSelect(
100228  Fts3Table *p,                   /* Virtual table handle */
100229  int iColumn,                    /* Column to query (or -ve for all columns) */
100230  const char *zTerm,              /* Term to query for */
100231  int nTerm,                      /* Size of zTerm in bytes */
100232  int isPrefix,                   /* True for a prefix search */
100233  int isReqPos,                   /* True to include position lists in output */
100234  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
100235  char **ppOut                    /* OUT: Malloced result buffer */
100236){
100237  int i;
100238  TermSelect tsc;
100239  Fts3SegFilter filter;           /* Segment term filter configuration */
100240  Fts3SegReader **apSegment;      /* Array of segments to read data from */
100241  int nSegment = 0;               /* Size of apSegment array */
100242  int nAlloc = 16;                /* Allocated size of segment array */
100243  int rc;                         /* Return code */
100244  sqlite3_stmt *pStmt = 0;        /* SQL statement to scan %_segdir table */
100245  int iAge = 0;                   /* Used to assign ages to segments */
100246
100247  apSegment = (Fts3SegReader **)sqlite3_malloc(sizeof(Fts3SegReader*)*nAlloc);
100248  if( !apSegment ) return SQLITE_NOMEM;
100249  rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &apSegment[0]);
100250  if( rc!=SQLITE_OK ) goto finished;
100251  if( apSegment[0] ){
100252    nSegment = 1;
100253  }
100254
100255  /* Loop through the entire %_segdir table. For each segment, create a
100256  ** Fts3SegReader to iterate through the subset of the segment leaves
100257  ** that may contain a term that matches zTerm/nTerm. For non-prefix
100258  ** searches, this is always a single leaf. For prefix searches, this
100259  ** may be a contiguous block of leaves.
100260  **
100261  ** The code in this loop does not actually load any leaves into memory
100262  ** (unless the root node happens to be a leaf). It simply examines the
100263  ** b-tree structure to determine which leaves need to be inspected.
100264  */
100265  rc = sqlite3Fts3AllSegdirs(p, &pStmt);
100266  while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
100267    Fts3SegReader *pNew = 0;
100268    int nRoot = sqlite3_column_bytes(pStmt, 4);
100269    char const *zRoot = sqlite3_column_blob(pStmt, 4);
100270    if( sqlite3_column_int64(pStmt, 1)==0 ){
100271      /* The entire segment is stored on the root node (which must be a
100272      ** leaf). Do not bother inspecting any data in this case, just
100273      ** create a Fts3SegReader to scan the single leaf.
100274      */
100275      rc = sqlite3Fts3SegReaderNew(p, iAge, 0, 0, 0, zRoot, nRoot, &pNew);
100276    }else{
100277      int rc2;                    /* Return value of sqlite3Fts3ReadBlock() */
100278      sqlite3_int64 i1;           /* Blockid of leaf that may contain zTerm */
100279      rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &i1);
100280      if( rc==SQLITE_OK ){
100281        sqlite3_int64 i2 = sqlite3_column_int64(pStmt, 2);
100282        rc = sqlite3Fts3SegReaderNew(p, iAge, i1, i2, 0, 0, 0, &pNew);
100283      }
100284
100285      /* The following call to ReadBlock() serves to reset the SQL statement
100286      ** used to retrieve blocks of data from the %_segments table. If it is
100287      ** not reset here, then it may remain classified as an active statement
100288      ** by SQLite, which may lead to "DROP TABLE" or "DETACH" commands
100289      ** failing.
100290      */
100291      rc2 = sqlite3Fts3ReadBlock(p, 0, 0, 0);
100292      if( rc==SQLITE_OK ){
100293        rc = rc2;
100294      }
100295    }
100296    iAge++;
100297
100298    /* If a new Fts3SegReader was allocated, add it to the apSegment array. */
100299    assert( pNew!=0 || rc!=SQLITE_OK );
100300    if( pNew ){
100301      if( nSegment==nAlloc ){
100302        Fts3SegReader **pArray;
100303        nAlloc += 16;
100304        pArray = (Fts3SegReader **)sqlite3_realloc(
100305            apSegment, nAlloc*sizeof(Fts3SegReader *)
100306        );
100307        if( !pArray ){
100308          sqlite3Fts3SegReaderFree(p, pNew);
100309          rc = SQLITE_NOMEM;
100310          goto finished;
100311        }
100312        apSegment = pArray;
100313      }
100314      apSegment[nSegment++] = pNew;
100315    }
100316  }
100317  if( rc!=SQLITE_DONE ){
100318    assert( rc!=SQLITE_OK );
100319    goto finished;
100320  }
100321
100322  memset(&tsc, 0, sizeof(TermSelect));
100323  tsc.isReqPos = isReqPos;
100324
100325  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY
100326        | (isPrefix ? FTS3_SEGMENT_PREFIX : 0)
100327        | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
100328        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
100329  filter.iCol = iColumn;
100330  filter.zTerm = zTerm;
100331  filter.nTerm = nTerm;
100332
100333  rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment, &filter,
100334      fts3TermSelectCb, (void *)&tsc
100335  );
100336
100337  if( rc==SQLITE_OK ){
100338    *ppOut = tsc.aOutput;
100339    *pnOut = tsc.nOutput;
100340  }else{
100341    sqlite3_free(tsc.aOutput);
100342  }
100343
100344finished:
100345  sqlite3_reset(pStmt);
100346  for(i=0; i<nSegment; i++){
100347    sqlite3Fts3SegReaderFree(p, apSegment[i]);
100348  }
100349  sqlite3_free(apSegment);
100350  return rc;
100351}
100352
100353
100354/*
100355** Return a DocList corresponding to the phrase *pPhrase.
100356*/
100357static int fts3PhraseSelect(
100358  Fts3Table *p,                   /* Virtual table handle */
100359  Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
100360  int isReqPos,                   /* True if output should contain positions */
100361  char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
100362  int *pnOut                      /* OUT: Size of buffer at *paOut */
100363){
100364  char *pOut = 0;
100365  int nOut = 0;
100366  int rc = SQLITE_OK;
100367  int ii;
100368  int iCol = pPhrase->iColumn;
100369  int isTermPos = (pPhrase->nToken>1 || isReqPos);
100370
100371  for(ii=0; ii<pPhrase->nToken; ii++){
100372    struct PhraseToken *pTok = &pPhrase->aToken[ii];
100373    char *z = pTok->z;            /* Next token of the phrase */
100374    int n = pTok->n;              /* Size of z in bytes */
100375    int isPrefix = pTok->isPrefix;/* True if token is a prefix */
100376    char *pList;                  /* Pointer to token doclist */
100377    int nList;                    /* Size of buffer at pList */
100378
100379    rc = fts3TermSelect(p, iCol, z, n, isPrefix, isTermPos, &nList, &pList);
100380    if( rc!=SQLITE_OK ) break;
100381
100382    if( ii==0 ){
100383      pOut = pList;
100384      nOut = nList;
100385    }else{
100386      /* Merge the new term list and the current output. If this is the
100387      ** last term in the phrase, and positions are not required in the
100388      ** output of this function, the positions can be dropped as part
100389      ** of this merge. Either way, the result of this merge will be
100390      ** smaller than nList bytes. The code in fts3DoclistMerge() is written
100391      ** so that it is safe to use pList as the output as well as an input
100392      ** in this case.
100393      */
100394      int mergetype = MERGE_POS_PHRASE;
100395      if( ii==pPhrase->nToken-1 && !isReqPos ){
100396        mergetype = MERGE_PHRASE;
100397      }
100398      fts3DoclistMerge(mergetype, 0, 0, pList, &nOut, pOut, nOut, pList, nList);
100399      sqlite3_free(pOut);
100400      pOut = pList;
100401    }
100402    assert( nOut==0 || pOut!=0 );
100403  }
100404
100405  if( rc==SQLITE_OK ){
100406    *paOut = pOut;
100407    *pnOut = nOut;
100408  }else{
100409    sqlite3_free(pOut);
100410  }
100411  return rc;
100412}
100413
100414/*
100415** Evaluate the full-text expression pExpr against fts3 table pTab. Store
100416** the resulting doclist in *paOut and *pnOut.
100417*/
100418static int evalFts3Expr(
100419  Fts3Table *p,                   /* Virtual table handle */
100420  Fts3Expr *pExpr,                /* Parsed fts3 expression */
100421  char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
100422  int *pnOut,                     /* OUT: Size of buffer at *paOut */
100423  int isReqPos                    /* Require positions in output buffer */
100424){
100425  int rc = SQLITE_OK;             /* Return code */
100426
100427  /* Zero the output parameters. */
100428  *paOut = 0;
100429  *pnOut = 0;
100430
100431  if( pExpr ){
100432    assert( pExpr->eType==FTSQUERY_PHRASE
100433         || pExpr->eType==FTSQUERY_NEAR
100434         || isReqPos==0
100435    );
100436    if( pExpr->eType==FTSQUERY_PHRASE ){
100437      rc = fts3PhraseSelect(p, pExpr->pPhrase,
100438          isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
100439          paOut, pnOut
100440      );
100441    }else{
100442      char *aLeft;
100443      char *aRight;
100444      int nLeft;
100445      int nRight;
100446
100447      if( 0==(rc = evalFts3Expr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
100448       && 0==(rc = evalFts3Expr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
100449      ){
100450        assert( pExpr->eType==FTSQUERY_NEAR || pExpr->eType==FTSQUERY_OR
100451            || pExpr->eType==FTSQUERY_AND  || pExpr->eType==FTSQUERY_NOT
100452        );
100453        switch( pExpr->eType ){
100454          case FTSQUERY_NEAR: {
100455            Fts3Expr *pLeft;
100456            Fts3Expr *pRight;
100457            int mergetype = isReqPos ? MERGE_POS_NEAR : MERGE_NEAR;
100458            int nParam1;
100459            int nParam2;
100460            char *aBuffer;
100461
100462            if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
100463              mergetype = MERGE_POS_NEAR;
100464            }
100465            pLeft = pExpr->pLeft;
100466            while( pLeft->eType==FTSQUERY_NEAR ){
100467              pLeft=pLeft->pRight;
100468            }
100469            pRight = pExpr->pRight;
100470            assert( pRight->eType==FTSQUERY_PHRASE );
100471            assert( pLeft->eType==FTSQUERY_PHRASE );
100472
100473            nParam1 = pExpr->nNear+1;
100474            nParam2 = nParam1+pLeft->pPhrase->nToken+pRight->pPhrase->nToken-2;
100475            aBuffer = sqlite3_malloc(nLeft+nRight+1);
100476            rc = fts3DoclistMerge(mergetype, nParam1, nParam2, aBuffer,
100477                pnOut, aLeft, nLeft, aRight, nRight
100478            );
100479            if( rc!=SQLITE_OK ){
100480              sqlite3_free(aBuffer);
100481            }else{
100482              *paOut = aBuffer;
100483            }
100484            sqlite3_free(aLeft);
100485            break;
100486          }
100487
100488          case FTSQUERY_OR: {
100489            /* Allocate a buffer for the output. The maximum size is the
100490            ** sum of the sizes of the two input buffers. The +1 term is
100491            ** so that a buffer of zero bytes is never allocated - this can
100492            ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
100493            */
100494            char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
100495            rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
100496                aLeft, nLeft, aRight, nRight
100497            );
100498            *paOut = aBuffer;
100499            sqlite3_free(aLeft);
100500            break;
100501          }
100502
100503          default: {
100504            assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
100505            fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
100506                aLeft, nLeft, aRight, nRight
100507            );
100508            *paOut = aLeft;
100509            break;
100510          }
100511        }
100512      }
100513      sqlite3_free(aRight);
100514    }
100515  }
100516
100517  return rc;
100518}
100519
100520/*
100521** This is the xFilter interface for the virtual table.  See
100522** the virtual table xFilter method documentation for additional
100523** information.
100524**
100525** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
100526** the %_content table.
100527**
100528** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
100529** in the %_content table.
100530**
100531** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
100532** column on the left-hand side of the MATCH operator is column
100533** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
100534** side of the MATCH operator.
100535*/
100536/* TODO(shess) Upgrade the cursor initialization and destruction to
100537** account for fts3FilterMethod() being called multiple times on the
100538** same cursor. The current solution is very fragile. Apply fix to
100539** fts3 as appropriate.
100540*/
100541static int fts3FilterMethod(
100542  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
100543  int idxNum,                     /* Strategy index */
100544  const char *idxStr,             /* Unused */
100545  int nVal,                       /* Number of elements in apVal */
100546  sqlite3_value **apVal           /* Arguments for the indexing scheme */
100547){
100548  const char *azSql[] = {
100549    "SELECT * FROM %Q.'%q_content' WHERE docid = ?", /* non-full-table-scan */
100550    "SELECT * FROM %Q.'%q_content'",                 /* full-table-scan */
100551  };
100552  int rc;                         /* Return code */
100553  char *zSql;                     /* SQL statement used to access %_content */
100554  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
100555  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
100556
100557  UNUSED_PARAMETER(idxStr);
100558  UNUSED_PARAMETER(nVal);
100559
100560  assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
100561  assert( nVal==0 || nVal==1 );
100562  assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
100563
100564  /* In case the cursor has been used before, clear it now. */
100565  sqlite3_finalize(pCsr->pStmt);
100566  sqlite3_free(pCsr->aDoclist);
100567  sqlite3Fts3ExprFree(pCsr->pExpr);
100568  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
100569
100570  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
100571  ** statement loops through all rows of the %_content table. For a
100572  ** full-text query or docid lookup, the statement retrieves a single
100573  ** row by docid.
100574  */
100575  zSql = sqlite3_mprintf(azSql[idxNum==FTS3_FULLSCAN_SEARCH], p->zDb, p->zName);
100576  if( !zSql ){
100577    rc = SQLITE_NOMEM;
100578  }else{
100579    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
100580    sqlite3_free(zSql);
100581  }
100582  if( rc!=SQLITE_OK ) return rc;
100583  pCsr->eSearch = (i16)idxNum;
100584
100585  if( idxNum==FTS3_DOCID_SEARCH ){
100586    rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
100587  }else if( idxNum!=FTS3_FULLSCAN_SEARCH ){
100588    int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
100589    const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
100590
100591    if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
100592      return SQLITE_NOMEM;
100593    }
100594
100595    rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn,
100596        iCol, zQuery, -1, &pCsr->pExpr
100597    );
100598    if( rc!=SQLITE_OK ) return rc;
100599
100600    rc = evalFts3Expr(p, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
100601    pCsr->pNextId = pCsr->aDoclist;
100602    pCsr->iPrevId = 0;
100603  }
100604
100605  if( rc!=SQLITE_OK ) return rc;
100606  return fts3NextMethod(pCursor);
100607}
100608
100609/*
100610** This is the xEof method of the virtual table. SQLite calls this
100611** routine to find out if it has reached the end of a result set.
100612*/
100613static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
100614  return ((Fts3Cursor *)pCursor)->isEof;
100615}
100616
100617/*
100618** This is the xRowid method. The SQLite core calls this routine to
100619** retrieve the rowid for the current row of the result set. fts3
100620** exposes %_content.docid as the rowid for the virtual table. The
100621** rowid should be written to *pRowid.
100622*/
100623static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
100624  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
100625  if( pCsr->aDoclist ){
100626    *pRowid = pCsr->iPrevId;
100627  }else{
100628    *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
100629  }
100630  return SQLITE_OK;
100631}
100632
100633/*
100634** This is the xColumn method, called by SQLite to request a value from
100635** the row that the supplied cursor currently points to.
100636*/
100637static int fts3ColumnMethod(
100638  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
100639  sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
100640  int iCol                        /* Index of column to read value from */
100641){
100642  int rc;                         /* Return Code */
100643  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
100644  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
100645
100646  /* The column value supplied by SQLite must be in range. */
100647  assert( iCol>=0 && iCol<=p->nColumn+1 );
100648
100649  if( iCol==p->nColumn+1 ){
100650    /* This call is a request for the "docid" column. Since "docid" is an
100651    ** alias for "rowid", use the xRowid() method to obtain the value.
100652    */
100653    sqlite3_int64 iRowid;
100654    rc = fts3RowidMethod(pCursor, &iRowid);
100655    sqlite3_result_int64(pContext, iRowid);
100656  }else if( iCol==p->nColumn ){
100657    /* The extra column whose name is the same as the table.
100658    ** Return a blob which is a pointer to the cursor.
100659    */
100660    sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
100661    rc = SQLITE_OK;
100662  }else{
100663    rc = fts3CursorSeek(0, pCsr);
100664    if( rc==SQLITE_OK ){
100665      sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
100666    }
100667  }
100668  return rc;
100669}
100670
100671/*
100672** This function is the implementation of the xUpdate callback used by
100673** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
100674** inserted, updated or deleted.
100675*/
100676static int fts3UpdateMethod(
100677  sqlite3_vtab *pVtab,            /* Virtual table handle */
100678  int nArg,                       /* Size of argument array */
100679  sqlite3_value **apVal,          /* Array of arguments */
100680  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
100681){
100682  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
100683}
100684
100685/*
100686** Implementation of xSync() method. Flush the contents of the pending-terms
100687** hash-table to the database.
100688*/
100689static int fts3SyncMethod(sqlite3_vtab *pVtab){
100690  return sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
100691}
100692
100693/*
100694** Implementation of xBegin() method. This is a no-op.
100695*/
100696static int fts3BeginMethod(sqlite3_vtab *pVtab){
100697  UNUSED_PARAMETER(pVtab);
100698  assert( ((Fts3Table *)pVtab)->nPendingData==0 );
100699  return SQLITE_OK;
100700}
100701
100702/*
100703** Implementation of xCommit() method. This is a no-op. The contents of
100704** the pending-terms hash-table have already been flushed into the database
100705** by fts3SyncMethod().
100706*/
100707static int fts3CommitMethod(sqlite3_vtab *pVtab){
100708  UNUSED_PARAMETER(pVtab);
100709  assert( ((Fts3Table *)pVtab)->nPendingData==0 );
100710  return SQLITE_OK;
100711}
100712
100713/*
100714** Implementation of xRollback(). Discard the contents of the pending-terms
100715** hash-table. Any changes made to the database are reverted by SQLite.
100716*/
100717static int fts3RollbackMethod(sqlite3_vtab *pVtab){
100718  sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
100719  return SQLITE_OK;
100720}
100721
100722/*
100723** Load the doclist associated with expression pExpr to pExpr->aDoclist.
100724** The loaded doclist contains positions as well as the document ids.
100725** This is used by the matchinfo(), snippet() and offsets() auxillary
100726** functions.
100727*/
100728SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *pTab, Fts3Expr *pExpr){
100729  return evalFts3Expr(pTab, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
100730}
100731
100732/*
100733** After ExprLoadDoclist() (see above) has been called, this function is
100734** used to iterate through the position lists that make up the doclist
100735** stored in pExpr->aDoclist.
100736*/
100737SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
100738  Fts3Expr *pExpr,                /* Access this expressions doclist */
100739  sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
100740  int iCol                        /* Column of requested pos-list */
100741){
100742  assert( pExpr->isLoaded );
100743  if( pExpr->aDoclist ){
100744    char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
100745    char *pCsr = pExpr->pCurrent;
100746
100747    assert( pCsr );
100748    while( pCsr<pEnd ){
100749      if( pExpr->iCurrent<iDocid ){
100750        fts3PoslistCopy(0, &pCsr);
100751        fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
100752        pExpr->pCurrent = pCsr;
100753      }else{
100754        if( pExpr->iCurrent==iDocid ){
100755          int iThis = 0;
100756          if( iCol<0 ){
100757            /* If iCol is negative, return a pointer to the start of the
100758            ** position-list (instead of a pointer to the start of a list
100759            ** of offsets associated with a specific column).
100760            */
100761            return pCsr;
100762          }
100763          while( iThis<iCol ){
100764            fts3ColumnlistCopy(0, &pCsr);
100765            if( *pCsr==0x00 ) return 0;
100766            pCsr++;
100767            pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
100768          }
100769          if( iCol==iThis ) return pCsr;
100770        }
100771        return 0;
100772      }
100773    }
100774  }
100775
100776  return 0;
100777}
100778
100779/*
100780** Helper function used by the implementation of the overloaded snippet(),
100781** offsets() and optimize() SQL functions.
100782**
100783** If the value passed as the third argument is a blob of size
100784** sizeof(Fts3Cursor*), then the blob contents are copied to the
100785** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
100786** message is written to context pContext and SQLITE_ERROR returned. The
100787** string passed via zFunc is used as part of the error message.
100788*/
100789static int fts3FunctionArg(
100790  sqlite3_context *pContext,      /* SQL function call context */
100791  const char *zFunc,              /* Function name */
100792  sqlite3_value *pVal,            /* argv[0] passed to function */
100793  Fts3Cursor **ppCsr         /* OUT: Store cursor handle here */
100794){
100795  Fts3Cursor *pRet;
100796  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
100797   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
100798  ){
100799    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
100800    sqlite3_result_error(pContext, zErr, -1);
100801    sqlite3_free(zErr);
100802    return SQLITE_ERROR;
100803  }
100804  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
100805  *ppCsr = pRet;
100806  return SQLITE_OK;
100807}
100808
100809/*
100810** Implementation of the snippet() function for FTS3
100811*/
100812static void fts3SnippetFunc(
100813  sqlite3_context *pContext,      /* SQLite function call context */
100814  int nVal,                       /* Size of apVal[] array */
100815  sqlite3_value **apVal           /* Array of arguments */
100816){
100817  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100818  const char *zStart = "<b>";
100819  const char *zEnd = "</b>";
100820  const char *zEllipsis = "<b>...</b>";
100821
100822  /* There must be at least one argument passed to this function (otherwise
100823  ** the non-overloaded version would have been called instead of this one).
100824  */
100825  assert( nVal>=1 );
100826
100827  if( nVal>4 ){
100828    sqlite3_result_error(pContext,
100829        "wrong number of arguments to function snippet()", -1);
100830    return;
100831  }
100832  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
100833
100834  switch( nVal ){
100835    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
100836    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
100837    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
100838  }
100839  if( !zEllipsis || !zEnd || !zStart ){
100840    sqlite3_result_error_nomem(pContext);
100841  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
100842    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis);
100843  }
100844}
100845
100846/*
100847** Implementation of the snippet2() function for FTS3
100848*/
100849static void fts3Snippet2Func(
100850  sqlite3_context *pContext,      /* SQLite function call context */
100851  int nVal,                       /* Size of apVal[] array */
100852  sqlite3_value **apVal           /* Array of arguments */
100853){
100854  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100855  const char *zStart = "<b>";
100856  const char *zEnd = "</b>";
100857  const char *zEllipsis = "<b>...</b>";
100858  int iCol = -1;
100859  int nToken = 10;
100860
100861  /* There must be at least one argument passed to this function (otherwise
100862  ** the non-overloaded version would have been called instead of this one).
100863  */
100864  assert( nVal>=1 );
100865
100866  if( nVal>6 ){
100867    sqlite3_result_error(pContext,
100868        "wrong number of arguments to function snippet()", -1);
100869    return;
100870  }
100871  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
100872
100873  switch( nVal ){
100874    case 6: nToken = sqlite3_value_int(apVal[5]);
100875    case 5: iCol = sqlite3_value_int(apVal[4]);
100876    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
100877    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
100878    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
100879  }
100880  if( !zEllipsis || !zEnd || !zStart ){
100881    sqlite3_result_error_nomem(pContext);
100882  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
100883    sqlite3Fts3Snippet2(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
100884  }
100885}
100886
100887/*
100888** Implementation of the offsets() function for FTS3
100889*/
100890static void fts3OffsetsFunc(
100891  sqlite3_context *pContext,      /* SQLite function call context */
100892  int nVal,                       /* Size of argument array */
100893  sqlite3_value **apVal           /* Array of arguments */
100894){
100895  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100896
100897  UNUSED_PARAMETER(nVal);
100898
100899  assert( nVal==1 );
100900  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
100901  assert( pCsr );
100902  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
100903    sqlite3Fts3Offsets(pContext, pCsr);
100904  }
100905}
100906
100907/*
100908** Implementation of the special optimize() function for FTS3. This
100909** function merges all segments in the database to a single segment.
100910** Example usage is:
100911**
100912**   SELECT optimize(t) FROM t LIMIT 1;
100913**
100914** where 't' is the name of an FTS3 table.
100915*/
100916static void fts3OptimizeFunc(
100917  sqlite3_context *pContext,      /* SQLite function call context */
100918  int nVal,                       /* Size of argument array */
100919  sqlite3_value **apVal           /* Array of arguments */
100920){
100921  int rc;                         /* Return code */
100922  Fts3Table *p;                   /* Virtual table handle */
100923  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
100924
100925  UNUSED_PARAMETER(nVal);
100926
100927  assert( nVal==1 );
100928  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
100929  p = (Fts3Table *)pCursor->base.pVtab;
100930  assert( p );
100931
100932  rc = sqlite3Fts3Optimize(p);
100933
100934  switch( rc ){
100935    case SQLITE_OK:
100936      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
100937      break;
100938    case SQLITE_DONE:
100939      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
100940      break;
100941    default:
100942      sqlite3_result_error_code(pContext, rc);
100943      break;
100944  }
100945}
100946
100947/*
100948** Implementation of the matchinfo() function for FTS3
100949*/
100950static void fts3MatchinfoFunc(
100951  sqlite3_context *pContext,      /* SQLite function call context */
100952  int nVal,                       /* Size of argument array */
100953  sqlite3_value **apVal           /* Array of arguments */
100954){
100955  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100956
100957  if( nVal!=1 ){
100958    sqlite3_result_error(pContext,
100959        "wrong number of arguments to function matchinfo()", -1);
100960    return;
100961  }
100962
100963  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
100964    sqlite3Fts3Matchinfo(pContext, pCsr);
100965  }
100966}
100967
100968/*
100969** This routine implements the xFindFunction method for the FTS3
100970** virtual table.
100971*/
100972static int fts3FindFunctionMethod(
100973  sqlite3_vtab *pVtab,            /* Virtual table handle */
100974  int nArg,                       /* Number of SQL function arguments */
100975  const char *zName,              /* Name of SQL function */
100976  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
100977  void **ppArg                    /* Unused */
100978){
100979  struct Overloaded {
100980    const char *zName;
100981    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
100982  } aOverload[] = {
100983    { "snippet", fts3SnippetFunc },
100984    { "snippet2", fts3Snippet2Func },
100985    { "offsets", fts3OffsetsFunc },
100986    { "optimize", fts3OptimizeFunc },
100987    { "matchinfo", fts3MatchinfoFunc },
100988  };
100989  int i;                          /* Iterator variable */
100990
100991  UNUSED_PARAMETER(pVtab);
100992  UNUSED_PARAMETER(nArg);
100993  UNUSED_PARAMETER(ppArg);
100994
100995  for(i=0; i<SizeofArray(aOverload); i++){
100996    if( strcmp(zName, aOverload[i].zName)==0 ){
100997      *pxFunc = aOverload[i].xFunc;
100998      return 1;
100999    }
101000  }
101001
101002  /* No function of the specified name was found. Return 0. */
101003  return 0;
101004}
101005
101006/*
101007** Implementation of FTS3 xRename method. Rename an fts3 table.
101008*/
101009static int fts3RenameMethod(
101010  sqlite3_vtab *pVtab,            /* Virtual table handle */
101011  const char *zName               /* New name of table */
101012){
101013  Fts3Table *p = (Fts3Table *)pVtab;
101014  int rc = SQLITE_NOMEM;          /* Return Code */
101015  char *zSql;                     /* SQL script to run to rename tables */
101016
101017  zSql = sqlite3_mprintf(
101018    "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
101019    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
101020    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
101021    , p->zDb, p->zName, zName
101022    , p->zDb, p->zName, zName
101023    , p->zDb, p->zName, zName
101024  );
101025  if( zSql ){
101026    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
101027    sqlite3_free(zSql);
101028  }
101029  return rc;
101030}
101031
101032static const sqlite3_module fts3Module = {
101033  /* iVersion      */ 0,
101034  /* xCreate       */ fts3CreateMethod,
101035  /* xConnect      */ fts3ConnectMethod,
101036  /* xBestIndex    */ fts3BestIndexMethod,
101037  /* xDisconnect   */ fts3DisconnectMethod,
101038  /* xDestroy      */ fts3DestroyMethod,
101039  /* xOpen         */ fts3OpenMethod,
101040  /* xClose        */ fulltextClose,
101041  /* xFilter       */ fts3FilterMethod,
101042  /* xNext         */ fts3NextMethod,
101043  /* xEof          */ fts3EofMethod,
101044  /* xColumn       */ fts3ColumnMethod,
101045  /* xRowid        */ fts3RowidMethod,
101046  /* xUpdate       */ fts3UpdateMethod,
101047  /* xBegin        */ fts3BeginMethod,
101048  /* xSync         */ fts3SyncMethod,
101049  /* xCommit       */ fts3CommitMethod,
101050  /* xRollback     */ fts3RollbackMethod,
101051  /* xFindFunction */ fts3FindFunctionMethod,
101052  /* xRename */       fts3RenameMethod,
101053};
101054
101055/*
101056** This function is registered as the module destructor (called when an
101057** FTS3 enabled database connection is closed). It frees the memory
101058** allocated for the tokenizer hash table.
101059*/
101060static void hashDestroy(void *p){
101061  Fts3Hash *pHash = (Fts3Hash *)p;
101062  sqlite3Fts3HashClear(pHash);
101063  sqlite3_free(pHash);
101064}
101065
101066/*
101067** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
101068** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
101069** two forward declarations are for functions declared in these files
101070** used to retrieve the respective implementations.
101071**
101072** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
101073** to by the argument to point a the "simple" tokenizer implementation.
101074** Function ...PorterTokenizerModule() sets *pModule to point to the
101075** porter tokenizer/stemmer implementation.
101076*/
101077SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
101078SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
101079SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
101080
101081/*
101082** Initialise the fts3 extension. If this extension is built as part
101083** of the sqlite library, then this function is called directly by
101084** SQLite. If fts3 is built as a dynamically loadable extension, this
101085** function is called by the sqlite3_extension_init() entry point.
101086*/
101087SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
101088  int rc = SQLITE_OK;
101089  Fts3Hash *pHash = 0;
101090  const sqlite3_tokenizer_module *pSimple = 0;
101091  const sqlite3_tokenizer_module *pPorter = 0;
101092
101093#ifdef SQLITE_ENABLE_ICU
101094  const sqlite3_tokenizer_module *pIcu = 0;
101095  sqlite3Fts3IcuTokenizerModule(&pIcu);
101096#endif
101097
101098  sqlite3Fts3SimpleTokenizerModule(&pSimple);
101099  sqlite3Fts3PorterTokenizerModule(&pPorter);
101100
101101  /* Allocate and initialise the hash-table used to store tokenizers. */
101102  pHash = sqlite3_malloc(sizeof(Fts3Hash));
101103  if( !pHash ){
101104    rc = SQLITE_NOMEM;
101105  }else{
101106    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
101107  }
101108
101109  /* Load the built-in tokenizers into the hash table */
101110  if( rc==SQLITE_OK ){
101111    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
101112     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
101113#ifdef SQLITE_ENABLE_ICU
101114     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
101115#endif
101116    ){
101117      rc = SQLITE_NOMEM;
101118    }
101119  }
101120
101121#ifdef SQLITE_TEST
101122  if( rc==SQLITE_OK ){
101123    rc = sqlite3Fts3ExprInitTestInterface(db);
101124  }
101125#endif
101126
101127  /* Create the virtual table wrapper around the hash-table and overload
101128  ** the two scalar functions. If this is successful, register the
101129  ** module with sqlite.
101130  */
101131  if( SQLITE_OK==rc
101132   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
101133   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
101134   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet2", -1))
101135   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
101136   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", -1))
101137   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
101138  ){
101139    return sqlite3_create_module_v2(
101140        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
101141    );
101142  }
101143
101144  /* An error has occurred. Delete the hash table and return the error code. */
101145  assert( rc!=SQLITE_OK );
101146  if( pHash ){
101147    sqlite3Fts3HashClear(pHash);
101148    sqlite3_free(pHash);
101149  }
101150  return rc;
101151}
101152
101153#if !SQLITE_CORE
101154SQLITE_API int sqlite3_extension_init(
101155  sqlite3 *db,
101156  char **pzErrMsg,
101157  const sqlite3_api_routines *pApi
101158){
101159  SQLITE_EXTENSION_INIT2(pApi)
101160  return sqlite3Fts3Init(db);
101161}
101162#endif
101163
101164#endif
101165
101166/************** End of fts3.c ************************************************/
101167/************** Begin file fts3_expr.c ***************************************/
101168/*
101169** 2008 Nov 28
101170**
101171** The author disclaims copyright to this source code.  In place of
101172** a legal notice, here is a blessing:
101173**
101174**    May you do good and not evil.
101175**    May you find forgiveness for yourself and forgive others.
101176**    May you share freely, never taking more than you give.
101177**
101178******************************************************************************
101179**
101180** This module contains code that implements a parser for fts3 query strings
101181** (the right-hand argument to the MATCH operator). Because the supported
101182** syntax is relatively simple, the whole tokenizer/parser system is
101183** hand-coded.
101184*/
101185#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
101186
101187/*
101188** By default, this module parses the legacy syntax that has been
101189** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
101190** is defined, then it uses the new syntax. The differences between
101191** the new and the old syntaxes are:
101192**
101193**  a) The new syntax supports parenthesis. The old does not.
101194**
101195**  b) The new syntax supports the AND and NOT operators. The old does not.
101196**
101197**  c) The old syntax supports the "-" token qualifier. This is not
101198**     supported by the new syntax (it is replaced by the NOT operator).
101199**
101200**  d) When using the old syntax, the OR operator has a greater precedence
101201**     than an implicit AND. When using the new, both implicity and explicit
101202**     AND operators have a higher precedence than OR.
101203**
101204** If compiled with SQLITE_TEST defined, then this module exports the
101205** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
101206** to zero causes the module to use the old syntax. If it is set to
101207** non-zero the new syntax is activated. This is so both syntaxes can
101208** be tested using a single build of testfixture.
101209**
101210** The following describes the syntax supported by the fts3 MATCH
101211** operator in a similar format to that used by the lemon parser
101212** generator. This module does not use actually lemon, it uses a
101213** custom parser.
101214**
101215**   query ::= andexpr (OR andexpr)*.
101216**
101217**   andexpr ::= notexpr (AND? notexpr)*.
101218**
101219**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
101220**   notexpr ::= LP query RP.
101221**
101222**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
101223**
101224**   distance_opt ::= .
101225**   distance_opt ::= / INTEGER.
101226**
101227**   phrase ::= TOKEN.
101228**   phrase ::= COLUMN:TOKEN.
101229**   phrase ::= "TOKEN TOKEN TOKEN...".
101230*/
101231
101232#ifdef SQLITE_TEST
101233SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
101234#else
101235# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
101236#  define sqlite3_fts3_enable_parentheses 1
101237# else
101238#  define sqlite3_fts3_enable_parentheses 0
101239# endif
101240#endif
101241
101242/*
101243** Default span for NEAR operators.
101244*/
101245#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
101246
101247
101248typedef struct ParseContext ParseContext;
101249struct ParseContext {
101250  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
101251  const char **azCol;                 /* Array of column names for fts3 table */
101252  int nCol;                           /* Number of entries in azCol[] */
101253  int iDefaultCol;                    /* Default column to query */
101254  sqlite3_context *pCtx;              /* Write error message here */
101255  int nNest;                          /* Number of nested brackets */
101256};
101257
101258/*
101259** This function is equivalent to the standard isspace() function.
101260**
101261** The standard isspace() can be awkward to use safely, because although it
101262** is defined to accept an argument of type int, its behaviour when passed
101263** an integer that falls outside of the range of the unsigned char type
101264** is undefined (and sometimes, "undefined" means segfault). This wrapper
101265** is defined to accept an argument of type char, and always returns 0 for
101266** any values that fall outside of the range of the unsigned char type (i.e.
101267** negative values).
101268*/
101269static int fts3isspace(char c){
101270  return (c&0x80)==0 ? isspace(c) : 0;
101271}
101272
101273/*
101274** Extract the next token from buffer z (length n) using the tokenizer
101275** and other information (column names etc.) in pParse. Create an Fts3Expr
101276** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
101277** single token and set *ppExpr to point to it. If the end of the buffer is
101278** reached before a token is found, set *ppExpr to zero. It is the
101279** responsibility of the caller to eventually deallocate the allocated
101280** Fts3Expr structure (if any) by passing it to sqlite3_free().
101281**
101282** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
101283** fails.
101284*/
101285static int getNextToken(
101286  ParseContext *pParse,                   /* fts3 query parse context */
101287  int iCol,                               /* Value for Fts3Phrase.iColumn */
101288  const char *z, int n,                   /* Input string */
101289  Fts3Expr **ppExpr,                      /* OUT: expression */
101290  int *pnConsumed                         /* OUT: Number of bytes consumed */
101291){
101292  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
101293  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
101294  int rc;
101295  sqlite3_tokenizer_cursor *pCursor;
101296  Fts3Expr *pRet = 0;
101297  int nConsumed = 0;
101298
101299  rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
101300  if( rc==SQLITE_OK ){
101301    const char *zToken;
101302    int nToken, iStart, iEnd, iPosition;
101303    int nByte;                               /* total space to allocate */
101304
101305    pCursor->pTokenizer = pTokenizer;
101306    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
101307
101308    if( rc==SQLITE_OK ){
101309      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
101310      pRet = (Fts3Expr *)sqlite3_malloc(nByte);
101311      if( !pRet ){
101312        rc = SQLITE_NOMEM;
101313      }else{
101314        memset(pRet, 0, nByte);
101315        pRet->eType = FTSQUERY_PHRASE;
101316        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
101317        pRet->pPhrase->nToken = 1;
101318        pRet->pPhrase->iColumn = iCol;
101319        pRet->pPhrase->aToken[0].n = nToken;
101320        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
101321        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
101322
101323        if( iEnd<n && z[iEnd]=='*' ){
101324          pRet->pPhrase->aToken[0].isPrefix = 1;
101325          iEnd++;
101326        }
101327        if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
101328          pRet->pPhrase->isNot = 1;
101329        }
101330      }
101331      nConsumed = iEnd;
101332    }
101333
101334    pModule->xClose(pCursor);
101335  }
101336
101337  *pnConsumed = nConsumed;
101338  *ppExpr = pRet;
101339  return rc;
101340}
101341
101342
101343/*
101344** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
101345** then free the old allocation.
101346*/
101347static void *fts3ReallocOrFree(void *pOrig, int nNew){
101348  void *pRet = sqlite3_realloc(pOrig, nNew);
101349  if( !pRet ){
101350    sqlite3_free(pOrig);
101351  }
101352  return pRet;
101353}
101354
101355/*
101356** Buffer zInput, length nInput, contains the contents of a quoted string
101357** that appeared as part of an fts3 query expression. Neither quote character
101358** is included in the buffer. This function attempts to tokenize the entire
101359** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
101360** containing the results.
101361**
101362** If successful, SQLITE_OK is returned and *ppExpr set to point at the
101363** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
101364** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
101365** to 0.
101366*/
101367static int getNextString(
101368  ParseContext *pParse,                   /* fts3 query parse context */
101369  const char *zInput, int nInput,         /* Input string */
101370  Fts3Expr **ppExpr                       /* OUT: expression */
101371){
101372  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
101373  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
101374  int rc;
101375  Fts3Expr *p = 0;
101376  sqlite3_tokenizer_cursor *pCursor = 0;
101377  char *zTemp = 0;
101378  int nTemp = 0;
101379
101380  rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
101381  if( rc==SQLITE_OK ){
101382    int ii;
101383    pCursor->pTokenizer = pTokenizer;
101384    for(ii=0; rc==SQLITE_OK; ii++){
101385      const char *zToken;
101386      int nToken, iBegin, iEnd, iPos;
101387      rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
101388      if( rc==SQLITE_OK ){
101389        int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
101390        p = fts3ReallocOrFree(p, nByte+ii*sizeof(struct PhraseToken));
101391        zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
101392        if( !p || !zTemp ){
101393          goto no_mem;
101394        }
101395        if( ii==0 ){
101396          memset(p, 0, nByte);
101397          p->pPhrase = (Fts3Phrase *)&p[1];
101398        }
101399        p->pPhrase = (Fts3Phrase *)&p[1];
101400        p->pPhrase->nToken = ii+1;
101401        p->pPhrase->aToken[ii].n = nToken;
101402        memcpy(&zTemp[nTemp], zToken, nToken);
101403        nTemp += nToken;
101404        if( iEnd<nInput && zInput[iEnd]=='*' ){
101405          p->pPhrase->aToken[ii].isPrefix = 1;
101406        }else{
101407          p->pPhrase->aToken[ii].isPrefix = 0;
101408        }
101409      }
101410    }
101411
101412    pModule->xClose(pCursor);
101413    pCursor = 0;
101414  }
101415
101416  if( rc==SQLITE_DONE ){
101417    int jj;
101418    char *zNew = NULL;
101419    int nNew = 0;
101420    int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
101421    nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(struct PhraseToken);
101422    p = fts3ReallocOrFree(p, nByte + nTemp);
101423    if( !p ){
101424      goto no_mem;
101425    }
101426    if( zTemp ){
101427      zNew = &(((char *)p)[nByte]);
101428      memcpy(zNew, zTemp, nTemp);
101429    }else{
101430      memset(p, 0, nByte+nTemp);
101431    }
101432    p->pPhrase = (Fts3Phrase *)&p[1];
101433    for(jj=0; jj<p->pPhrase->nToken; jj++){
101434      p->pPhrase->aToken[jj].z = &zNew[nNew];
101435      nNew += p->pPhrase->aToken[jj].n;
101436    }
101437    sqlite3_free(zTemp);
101438    p->eType = FTSQUERY_PHRASE;
101439    p->pPhrase->iColumn = pParse->iDefaultCol;
101440    rc = SQLITE_OK;
101441  }
101442
101443  *ppExpr = p;
101444  return rc;
101445no_mem:
101446
101447  if( pCursor ){
101448    pModule->xClose(pCursor);
101449  }
101450  sqlite3_free(zTemp);
101451  sqlite3_free(p);
101452  *ppExpr = 0;
101453  return SQLITE_NOMEM;
101454}
101455
101456/*
101457** Function getNextNode(), which is called by fts3ExprParse(), may itself
101458** call fts3ExprParse(). So this forward declaration is required.
101459*/
101460static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
101461
101462/*
101463** The output variable *ppExpr is populated with an allocated Fts3Expr
101464** structure, or set to 0 if the end of the input buffer is reached.
101465**
101466** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
101467** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
101468** If SQLITE_ERROR is returned, pContext is populated with an error message.
101469*/
101470static int getNextNode(
101471  ParseContext *pParse,                   /* fts3 query parse context */
101472  const char *z, int n,                   /* Input string */
101473  Fts3Expr **ppExpr,                      /* OUT: expression */
101474  int *pnConsumed                         /* OUT: Number of bytes consumed */
101475){
101476  static const struct Fts3Keyword {
101477    char *z;                              /* Keyword text */
101478    unsigned char n;                      /* Length of the keyword */
101479    unsigned char parenOnly;              /* Only valid in paren mode */
101480    unsigned char eType;                  /* Keyword code */
101481  } aKeyword[] = {
101482    { "OR" ,  2, 0, FTSQUERY_OR   },
101483    { "AND",  3, 1, FTSQUERY_AND  },
101484    { "NOT",  3, 1, FTSQUERY_NOT  },
101485    { "NEAR", 4, 0, FTSQUERY_NEAR }
101486  };
101487  int ii;
101488  int iCol;
101489  int iColLen;
101490  int rc;
101491  Fts3Expr *pRet = 0;
101492
101493  const char *zInput = z;
101494  int nInput = n;
101495
101496  /* Skip over any whitespace before checking for a keyword, an open or
101497  ** close bracket, or a quoted string.
101498  */
101499  while( nInput>0 && fts3isspace(*zInput) ){
101500    nInput--;
101501    zInput++;
101502  }
101503  if( nInput==0 ){
101504    return SQLITE_DONE;
101505  }
101506
101507  /* See if we are dealing with a keyword. */
101508  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
101509    const struct Fts3Keyword *pKey = &aKeyword[ii];
101510
101511    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
101512      continue;
101513    }
101514
101515    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
101516      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
101517      int nKey = pKey->n;
101518      char cNext;
101519
101520      /* If this is a "NEAR" keyword, check for an explicit nearness. */
101521      if( pKey->eType==FTSQUERY_NEAR ){
101522        assert( nKey==4 );
101523        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
101524          nNear = 0;
101525          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
101526            nNear = nNear * 10 + (zInput[nKey] - '0');
101527          }
101528        }
101529      }
101530
101531      /* At this point this is probably a keyword. But for that to be true,
101532      ** the next byte must contain either whitespace, an open or close
101533      ** parenthesis, a quote character, or EOF.
101534      */
101535      cNext = zInput[nKey];
101536      if( fts3isspace(cNext)
101537       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
101538      ){
101539        pRet = (Fts3Expr *)sqlite3_malloc(sizeof(Fts3Expr));
101540        if( !pRet ){
101541          return SQLITE_NOMEM;
101542        }
101543        memset(pRet, 0, sizeof(Fts3Expr));
101544        pRet->eType = pKey->eType;
101545        pRet->nNear = nNear;
101546        *ppExpr = pRet;
101547        *pnConsumed = (int)((zInput - z) + nKey);
101548        return SQLITE_OK;
101549      }
101550
101551      /* Turns out that wasn't a keyword after all. This happens if the
101552      ** user has supplied a token such as "ORacle". Continue.
101553      */
101554    }
101555  }
101556
101557  /* Check for an open bracket. */
101558  if( sqlite3_fts3_enable_parentheses ){
101559    if( *zInput=='(' ){
101560      int nConsumed;
101561      int rc;
101562      pParse->nNest++;
101563      rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
101564      if( rc==SQLITE_OK && !*ppExpr ){
101565        rc = SQLITE_DONE;
101566      }
101567      *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
101568      return rc;
101569    }
101570
101571    /* Check for a close bracket. */
101572    if( *zInput==')' ){
101573      pParse->nNest--;
101574      *pnConsumed = (int)((zInput - z) + 1);
101575      return SQLITE_DONE;
101576    }
101577  }
101578
101579  /* See if we are dealing with a quoted phrase. If this is the case, then
101580  ** search for the closing quote and pass the whole string to getNextString()
101581  ** for processing. This is easy to do, as fts3 has no syntax for escaping
101582  ** a quote character embedded in a string.
101583  */
101584  if( *zInput=='"' ){
101585    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
101586    *pnConsumed = (int)((zInput - z) + ii + 1);
101587    if( ii==nInput ){
101588      return SQLITE_ERROR;
101589    }
101590    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
101591  }
101592
101593
101594  /* If control flows to this point, this must be a regular token, or
101595  ** the end of the input. Read a regular token using the sqlite3_tokenizer
101596  ** interface. Before doing so, figure out if there is an explicit
101597  ** column specifier for the token.
101598  **
101599  ** TODO: Strangely, it is not possible to associate a column specifier
101600  ** with a quoted phrase, only with a single token. Not sure if this was
101601  ** an implementation artifact or an intentional decision when fts3 was
101602  ** first implemented. Whichever it was, this module duplicates the
101603  ** limitation.
101604  */
101605  iCol = pParse->iDefaultCol;
101606  iColLen = 0;
101607  for(ii=0; ii<pParse->nCol; ii++){
101608    const char *zStr = pParse->azCol[ii];
101609    int nStr = (int)strlen(zStr);
101610    if( nInput>nStr && zInput[nStr]==':'
101611     && sqlite3_strnicmp(zStr, zInput, nStr)==0
101612    ){
101613      iCol = ii;
101614      iColLen = (int)((zInput - z) + nStr + 1);
101615      break;
101616    }
101617  }
101618  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
101619  *pnConsumed += iColLen;
101620  return rc;
101621}
101622
101623/*
101624** The argument is an Fts3Expr structure for a binary operator (any type
101625** except an FTSQUERY_PHRASE). Return an integer value representing the
101626** precedence of the operator. Lower values have a higher precedence (i.e.
101627** group more tightly). For example, in the C language, the == operator
101628** groups more tightly than ||, and would therefore have a higher precedence.
101629**
101630** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
101631** is defined), the order of the operators in precedence from highest to
101632** lowest is:
101633**
101634**   NEAR
101635**   NOT
101636**   AND (including implicit ANDs)
101637**   OR
101638**
101639** Note that when using the old query syntax, the OR operator has a higher
101640** precedence than the AND operator.
101641*/
101642static int opPrecedence(Fts3Expr *p){
101643  assert( p->eType!=FTSQUERY_PHRASE );
101644  if( sqlite3_fts3_enable_parentheses ){
101645    return p->eType;
101646  }else if( p->eType==FTSQUERY_NEAR ){
101647    return 1;
101648  }else if( p->eType==FTSQUERY_OR ){
101649    return 2;
101650  }
101651  assert( p->eType==FTSQUERY_AND );
101652  return 3;
101653}
101654
101655/*
101656** Argument ppHead contains a pointer to the current head of a query
101657** expression tree being parsed. pPrev is the expression node most recently
101658** inserted into the tree. This function adds pNew, which is always a binary
101659** operator node, into the expression tree based on the relative precedence
101660** of pNew and the existing nodes of the tree. This may result in the head
101661** of the tree changing, in which case *ppHead is set to the new root node.
101662*/
101663static void insertBinaryOperator(
101664  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
101665  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
101666  Fts3Expr *pNew           /* New binary node to insert into expression tree */
101667){
101668  Fts3Expr *pSplit = pPrev;
101669  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
101670    pSplit = pSplit->pParent;
101671  }
101672
101673  if( pSplit->pParent ){
101674    assert( pSplit->pParent->pRight==pSplit );
101675    pSplit->pParent->pRight = pNew;
101676    pNew->pParent = pSplit->pParent;
101677  }else{
101678    *ppHead = pNew;
101679  }
101680  pNew->pLeft = pSplit;
101681  pSplit->pParent = pNew;
101682}
101683
101684/*
101685** Parse the fts3 query expression found in buffer z, length n. This function
101686** returns either when the end of the buffer is reached or an unmatched
101687** closing bracket - ')' - is encountered.
101688**
101689** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
101690** parsed form of the expression and *pnConsumed is set to the number of
101691** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
101692** (out of memory error) or SQLITE_ERROR (parse error) is returned.
101693*/
101694static int fts3ExprParse(
101695  ParseContext *pParse,                   /* fts3 query parse context */
101696  const char *z, int n,                   /* Text of MATCH query */
101697  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
101698  int *pnConsumed                         /* OUT: Number of bytes consumed */
101699){
101700  Fts3Expr *pRet = 0;
101701  Fts3Expr *pPrev = 0;
101702  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
101703  int nIn = n;
101704  const char *zIn = z;
101705  int rc = SQLITE_OK;
101706  int isRequirePhrase = 1;
101707
101708  while( rc==SQLITE_OK ){
101709    Fts3Expr *p = 0;
101710    int nByte = 0;
101711    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
101712    if( rc==SQLITE_OK ){
101713      int isPhrase;
101714
101715      if( !sqlite3_fts3_enable_parentheses
101716       && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot
101717      ){
101718        /* Create an implicit NOT operator. */
101719        Fts3Expr *pNot = sqlite3_malloc(sizeof(Fts3Expr));
101720        if( !pNot ){
101721          sqlite3Fts3ExprFree(p);
101722          rc = SQLITE_NOMEM;
101723          goto exprparse_out;
101724        }
101725        memset(pNot, 0, sizeof(Fts3Expr));
101726        pNot->eType = FTSQUERY_NOT;
101727        pNot->pRight = p;
101728        if( pNotBranch ){
101729          pNot->pLeft = pNotBranch;
101730        }
101731        pNotBranch = pNot;
101732        p = pPrev;
101733      }else{
101734        int eType = p->eType;
101735        assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
101736        isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
101737
101738        /* The isRequirePhrase variable is set to true if a phrase or
101739        ** an expression contained in parenthesis is required. If a
101740        ** binary operator (AND, OR, NOT or NEAR) is encounted when
101741        ** isRequirePhrase is set, this is a syntax error.
101742        */
101743        if( !isPhrase && isRequirePhrase ){
101744          sqlite3Fts3ExprFree(p);
101745          rc = SQLITE_ERROR;
101746          goto exprparse_out;
101747        }
101748
101749        if( isPhrase && !isRequirePhrase ){
101750          /* Insert an implicit AND operator. */
101751          Fts3Expr *pAnd;
101752          assert( pRet && pPrev );
101753          pAnd = sqlite3_malloc(sizeof(Fts3Expr));
101754          if( !pAnd ){
101755            sqlite3Fts3ExprFree(p);
101756            rc = SQLITE_NOMEM;
101757            goto exprparse_out;
101758          }
101759          memset(pAnd, 0, sizeof(Fts3Expr));
101760          pAnd->eType = FTSQUERY_AND;
101761          insertBinaryOperator(&pRet, pPrev, pAnd);
101762          pPrev = pAnd;
101763        }
101764
101765        /* This test catches attempts to make either operand of a NEAR
101766        ** operator something other than a phrase. For example, either of
101767        ** the following:
101768        **
101769        **    (bracketed expression) NEAR phrase
101770        **    phrase NEAR (bracketed expression)
101771        **
101772        ** Return an error in either case.
101773        */
101774        if( pPrev && (
101775            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
101776         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
101777        )){
101778          sqlite3Fts3ExprFree(p);
101779          rc = SQLITE_ERROR;
101780          goto exprparse_out;
101781        }
101782
101783        if( isPhrase ){
101784          if( pRet ){
101785            assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
101786            pPrev->pRight = p;
101787            p->pParent = pPrev;
101788          }else{
101789            pRet = p;
101790          }
101791        }else{
101792          insertBinaryOperator(&pRet, pPrev, p);
101793        }
101794        isRequirePhrase = !isPhrase;
101795      }
101796      assert( nByte>0 );
101797    }
101798    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
101799    nIn -= nByte;
101800    zIn += nByte;
101801    pPrev = p;
101802  }
101803
101804  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
101805    rc = SQLITE_ERROR;
101806  }
101807
101808  if( rc==SQLITE_DONE ){
101809    rc = SQLITE_OK;
101810    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
101811      if( !pRet ){
101812        rc = SQLITE_ERROR;
101813      }else{
101814        Fts3Expr *pIter = pNotBranch;
101815        while( pIter->pLeft ){
101816          pIter = pIter->pLeft;
101817        }
101818        pIter->pLeft = pRet;
101819        pRet = pNotBranch;
101820      }
101821    }
101822  }
101823  *pnConsumed = n - nIn;
101824
101825exprparse_out:
101826  if( rc!=SQLITE_OK ){
101827    sqlite3Fts3ExprFree(pRet);
101828    sqlite3Fts3ExprFree(pNotBranch);
101829    pRet = 0;
101830  }
101831  *ppExpr = pRet;
101832  return rc;
101833}
101834
101835/*
101836** Parameters z and n contain a pointer to and length of a buffer containing
101837** an fts3 query expression, respectively. This function attempts to parse the
101838** query expression and create a tree of Fts3Expr structures representing the
101839** parsed expression. If successful, *ppExpr is set to point to the head
101840** of the parsed expression tree and SQLITE_OK is returned. If an error
101841** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
101842** error) is returned and *ppExpr is set to 0.
101843**
101844** If parameter n is a negative number, then z is assumed to point to a
101845** nul-terminated string and the length is determined using strlen().
101846**
101847** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
101848** use to normalize query tokens while parsing the expression. The azCol[]
101849** array, which is assumed to contain nCol entries, should contain the names
101850** of each column in the target fts3 table, in order from left to right.
101851** Column names must be nul-terminated strings.
101852**
101853** The iDefaultCol parameter should be passed the index of the table column
101854** that appears on the left-hand-side of the MATCH operator (the default
101855** column to match against for tokens for which a column name is not explicitly
101856** specified as part of the query string), or -1 if tokens may by default
101857** match any table column.
101858*/
101859SQLITE_PRIVATE int sqlite3Fts3ExprParse(
101860  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
101861  char **azCol,                       /* Array of column names for fts3 table */
101862  int nCol,                           /* Number of entries in azCol[] */
101863  int iDefaultCol,                    /* Default column to query */
101864  const char *z, int n,               /* Text of MATCH query */
101865  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
101866){
101867  int nParsed;
101868  int rc;
101869  ParseContext sParse;
101870  sParse.pTokenizer = pTokenizer;
101871  sParse.azCol = (const char **)azCol;
101872  sParse.nCol = nCol;
101873  sParse.iDefaultCol = iDefaultCol;
101874  sParse.nNest = 0;
101875  if( z==0 ){
101876    *ppExpr = 0;
101877    return SQLITE_OK;
101878  }
101879  if( n<0 ){
101880    n = (int)strlen(z);
101881  }
101882  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
101883
101884  /* Check for mismatched parenthesis */
101885  if( rc==SQLITE_OK && sParse.nNest ){
101886    rc = SQLITE_ERROR;
101887    sqlite3Fts3ExprFree(*ppExpr);
101888    *ppExpr = 0;
101889  }
101890
101891  return rc;
101892}
101893
101894/*
101895** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
101896*/
101897SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
101898  if( p ){
101899    sqlite3Fts3ExprFree(p->pLeft);
101900    sqlite3Fts3ExprFree(p->pRight);
101901    sqlite3_free(p->aDoclist);
101902    sqlite3_free(p);
101903  }
101904}
101905
101906/****************************************************************************
101907*****************************************************************************
101908** Everything after this point is just test code.
101909*/
101910
101911#ifdef SQLITE_TEST
101912
101913
101914/*
101915** Function to query the hash-table of tokenizers (see README.tokenizers).
101916*/
101917static int queryTestTokenizer(
101918  sqlite3 *db,
101919  const char *zName,
101920  const sqlite3_tokenizer_module **pp
101921){
101922  int rc;
101923  sqlite3_stmt *pStmt;
101924  const char zSql[] = "SELECT fts3_tokenizer(?)";
101925
101926  *pp = 0;
101927  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
101928  if( rc!=SQLITE_OK ){
101929    return rc;
101930  }
101931
101932  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
101933  if( SQLITE_ROW==sqlite3_step(pStmt) ){
101934    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
101935      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
101936    }
101937  }
101938
101939  return sqlite3_finalize(pStmt);
101940}
101941
101942/*
101943** This function is part of the test interface for the query parser. It
101944** writes a text representation of the query expression pExpr into the
101945** buffer pointed to by argument zBuf. It is assumed that zBuf is large
101946** enough to store the required text representation.
101947*/
101948static void exprToString(Fts3Expr *pExpr, char *zBuf){
101949  switch( pExpr->eType ){
101950    case FTSQUERY_PHRASE: {
101951      Fts3Phrase *pPhrase = pExpr->pPhrase;
101952      int i;
101953      zBuf += sprintf(zBuf, "PHRASE %d %d", pPhrase->iColumn, pPhrase->isNot);
101954      for(i=0; i<pPhrase->nToken; i++){
101955        zBuf += sprintf(zBuf," %.*s",pPhrase->aToken[i].n,pPhrase->aToken[i].z);
101956        zBuf += sprintf(zBuf,"%s", (pPhrase->aToken[i].isPrefix?"+":""));
101957      }
101958      return;
101959    }
101960
101961    case FTSQUERY_NEAR:
101962      zBuf += sprintf(zBuf, "NEAR/%d ", pExpr->nNear);
101963      break;
101964    case FTSQUERY_NOT:
101965      zBuf += sprintf(zBuf, "NOT ");
101966      break;
101967    case FTSQUERY_AND:
101968      zBuf += sprintf(zBuf, "AND ");
101969      break;
101970    case FTSQUERY_OR:
101971      zBuf += sprintf(zBuf, "OR ");
101972      break;
101973  }
101974
101975  zBuf += sprintf(zBuf, "{");
101976  exprToString(pExpr->pLeft, zBuf);
101977  zBuf += strlen(zBuf);
101978  zBuf += sprintf(zBuf, "} ");
101979
101980  zBuf += sprintf(zBuf, "{");
101981  exprToString(pExpr->pRight, zBuf);
101982  zBuf += strlen(zBuf);
101983  zBuf += sprintf(zBuf, "}");
101984}
101985
101986/*
101987** This is the implementation of a scalar SQL function used to test the
101988** expression parser. It should be called as follows:
101989**
101990**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
101991**
101992** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
101993** to parse the query expression (see README.tokenizers). The second argument
101994** is the query expression to parse. Each subsequent argument is the name
101995** of a column of the fts3 table that the query expression may refer to.
101996** For example:
101997**
101998**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
101999*/
102000static void fts3ExprTest(
102001  sqlite3_context *context,
102002  int argc,
102003  sqlite3_value **argv
102004){
102005  sqlite3_tokenizer_module const *pModule = 0;
102006  sqlite3_tokenizer *pTokenizer = 0;
102007  int rc;
102008  char **azCol = 0;
102009  const char *zExpr;
102010  int nExpr;
102011  int nCol;
102012  int ii;
102013  Fts3Expr *pExpr;
102014  sqlite3 *db = sqlite3_context_db_handle(context);
102015
102016  if( argc<3 ){
102017    sqlite3_result_error(context,
102018        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
102019    );
102020    return;
102021  }
102022
102023  rc = queryTestTokenizer(db,
102024                          (const char *)sqlite3_value_text(argv[0]), &pModule);
102025  if( rc==SQLITE_NOMEM ){
102026    sqlite3_result_error_nomem(context);
102027    goto exprtest_out;
102028  }else if( !pModule ){
102029    sqlite3_result_error(context, "No such tokenizer module", -1);
102030    goto exprtest_out;
102031  }
102032
102033  rc = pModule->xCreate(0, 0, &pTokenizer);
102034  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
102035  if( rc==SQLITE_NOMEM ){
102036    sqlite3_result_error_nomem(context);
102037    goto exprtest_out;
102038  }
102039  pTokenizer->pModule = pModule;
102040
102041  zExpr = (const char *)sqlite3_value_text(argv[1]);
102042  nExpr = sqlite3_value_bytes(argv[1]);
102043  nCol = argc-2;
102044  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
102045  if( !azCol ){
102046    sqlite3_result_error_nomem(context);
102047    goto exprtest_out;
102048  }
102049  for(ii=0; ii<nCol; ii++){
102050    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
102051  }
102052
102053  rc = sqlite3Fts3ExprParse(
102054      pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
102055  );
102056  if( rc==SQLITE_NOMEM ){
102057    sqlite3_result_error_nomem(context);
102058    goto exprtest_out;
102059  }else if( rc==SQLITE_OK ){
102060    char zBuf[4096];
102061    exprToString(pExpr, zBuf);
102062    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
102063    sqlite3Fts3ExprFree(pExpr);
102064  }else{
102065    sqlite3_result_error(context, "Error parsing expression", -1);
102066  }
102067
102068exprtest_out:
102069  if( pModule && pTokenizer ){
102070    rc = pModule->xDestroy(pTokenizer);
102071  }
102072  sqlite3_free(azCol);
102073}
102074
102075/*
102076** Register the query expression parser test function fts3_exprtest()
102077** with database connection db.
102078*/
102079SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
102080  return sqlite3_create_function(
102081      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
102082  );
102083}
102084
102085#endif
102086#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
102087
102088/************** End of fts3_expr.c *******************************************/
102089/************** Begin file fts3_hash.c ***************************************/
102090/*
102091** 2001 September 22
102092**
102093** The author disclaims copyright to this source code.  In place of
102094** a legal notice, here is a blessing:
102095**
102096**    May you do good and not evil.
102097**    May you find forgiveness for yourself and forgive others.
102098**    May you share freely, never taking more than you give.
102099**
102100*************************************************************************
102101** This is the implementation of generic hash-tables used in SQLite.
102102** We've modified it slightly to serve as a standalone hash table
102103** implementation for the full-text indexing module.
102104*/
102105
102106/*
102107** The code in this file is only compiled if:
102108**
102109**     * The FTS3 module is being built as an extension
102110**       (in which case SQLITE_CORE is not defined), or
102111**
102112**     * The FTS3 module is being built into the core of
102113**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
102114*/
102115#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
102116
102117
102118
102119/*
102120** Malloc and Free functions
102121*/
102122static void *fts3HashMalloc(int n){
102123  void *p = sqlite3_malloc(n);
102124  if( p ){
102125    memset(p, 0, n);
102126  }
102127  return p;
102128}
102129static void fts3HashFree(void *p){
102130  sqlite3_free(p);
102131}
102132
102133/* Turn bulk memory into a hash table object by initializing the
102134** fields of the Hash structure.
102135**
102136** "pNew" is a pointer to the hash table that is to be initialized.
102137** keyClass is one of the constants
102138** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
102139** determines what kind of key the hash table will use.  "copyKey" is
102140** true if the hash table should make its own private copy of keys and
102141** false if it should just use the supplied pointer.
102142*/
102143SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
102144  assert( pNew!=0 );
102145  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
102146  pNew->keyClass = keyClass;
102147  pNew->copyKey = copyKey;
102148  pNew->first = 0;
102149  pNew->count = 0;
102150  pNew->htsize = 0;
102151  pNew->ht = 0;
102152}
102153
102154/* Remove all entries from a hash table.  Reclaim all memory.
102155** Call this routine to delete a hash table or to reset a hash table
102156** to the empty state.
102157*/
102158SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
102159  Fts3HashElem *elem;         /* For looping over all elements of the table */
102160
102161  assert( pH!=0 );
102162  elem = pH->first;
102163  pH->first = 0;
102164  fts3HashFree(pH->ht);
102165  pH->ht = 0;
102166  pH->htsize = 0;
102167  while( elem ){
102168    Fts3HashElem *next_elem = elem->next;
102169    if( pH->copyKey && elem->pKey ){
102170      fts3HashFree(elem->pKey);
102171    }
102172    fts3HashFree(elem);
102173    elem = next_elem;
102174  }
102175  pH->count = 0;
102176}
102177
102178/*
102179** Hash and comparison functions when the mode is FTS3_HASH_STRING
102180*/
102181static int fts3StrHash(const void *pKey, int nKey){
102182  const char *z = (const char *)pKey;
102183  int h = 0;
102184  if( nKey<=0 ) nKey = (int) strlen(z);
102185  while( nKey > 0  ){
102186    h = (h<<3) ^ h ^ *z++;
102187    nKey--;
102188  }
102189  return h & 0x7fffffff;
102190}
102191static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
102192  if( n1!=n2 ) return 1;
102193  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
102194}
102195
102196/*
102197** Hash and comparison functions when the mode is FTS3_HASH_BINARY
102198*/
102199static int fts3BinHash(const void *pKey, int nKey){
102200  int h = 0;
102201  const char *z = (const char *)pKey;
102202  while( nKey-- > 0 ){
102203    h = (h<<3) ^ h ^ *(z++);
102204  }
102205  return h & 0x7fffffff;
102206}
102207static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
102208  if( n1!=n2 ) return 1;
102209  return memcmp(pKey1,pKey2,n1);
102210}
102211
102212/*
102213** Return a pointer to the appropriate hash function given the key class.
102214**
102215** The C syntax in this function definition may be unfamilar to some
102216** programmers, so we provide the following additional explanation:
102217**
102218** The name of the function is "ftsHashFunction".  The function takes a
102219** single parameter "keyClass".  The return value of ftsHashFunction()
102220** is a pointer to another function.  Specifically, the return value
102221** of ftsHashFunction() is a pointer to a function that takes two parameters
102222** with types "const void*" and "int" and returns an "int".
102223*/
102224static int (*ftsHashFunction(int keyClass))(const void*,int){
102225  if( keyClass==FTS3_HASH_STRING ){
102226    return &fts3StrHash;
102227  }else{
102228    assert( keyClass==FTS3_HASH_BINARY );
102229    return &fts3BinHash;
102230  }
102231}
102232
102233/*
102234** Return a pointer to the appropriate hash function given the key class.
102235**
102236** For help in interpreted the obscure C code in the function definition,
102237** see the header comment on the previous function.
102238*/
102239static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
102240  if( keyClass==FTS3_HASH_STRING ){
102241    return &fts3StrCompare;
102242  }else{
102243    assert( keyClass==FTS3_HASH_BINARY );
102244    return &fts3BinCompare;
102245  }
102246}
102247
102248/* Link an element into the hash table
102249*/
102250static void fts3HashInsertElement(
102251  Fts3Hash *pH,            /* The complete hash table */
102252  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
102253  Fts3HashElem *pNew       /* The element to be inserted */
102254){
102255  Fts3HashElem *pHead;     /* First element already in pEntry */
102256  pHead = pEntry->chain;
102257  if( pHead ){
102258    pNew->next = pHead;
102259    pNew->prev = pHead->prev;
102260    if( pHead->prev ){ pHead->prev->next = pNew; }
102261    else             { pH->first = pNew; }
102262    pHead->prev = pNew;
102263  }else{
102264    pNew->next = pH->first;
102265    if( pH->first ){ pH->first->prev = pNew; }
102266    pNew->prev = 0;
102267    pH->first = pNew;
102268  }
102269  pEntry->count++;
102270  pEntry->chain = pNew;
102271}
102272
102273
102274/* Resize the hash table so that it cantains "new_size" buckets.
102275** "new_size" must be a power of 2.  The hash table might fail
102276** to resize if sqliteMalloc() fails.
102277**
102278** Return non-zero if a memory allocation error occurs.
102279*/
102280static int fts3Rehash(Fts3Hash *pH, int new_size){
102281  struct _fts3ht *new_ht;          /* The new hash table */
102282  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
102283  int (*xHash)(const void*,int);   /* The hash function */
102284
102285  assert( (new_size & (new_size-1))==0 );
102286  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
102287  if( new_ht==0 ) return 1;
102288  fts3HashFree(pH->ht);
102289  pH->ht = new_ht;
102290  pH->htsize = new_size;
102291  xHash = ftsHashFunction(pH->keyClass);
102292  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
102293    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
102294    next_elem = elem->next;
102295    fts3HashInsertElement(pH, &new_ht[h], elem);
102296  }
102297  return 0;
102298}
102299
102300/* This function (for internal use only) locates an element in an
102301** hash table that matches the given key.  The hash for this key has
102302** already been computed and is passed as the 4th parameter.
102303*/
102304static Fts3HashElem *fts3FindElementByHash(
102305  const Fts3Hash *pH, /* The pH to be searched */
102306  const void *pKey,   /* The key we are searching for */
102307  int nKey,
102308  int h               /* The hash for this key. */
102309){
102310  Fts3HashElem *elem;            /* Used to loop thru the element list */
102311  int count;                     /* Number of elements left to test */
102312  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
102313
102314  if( pH->ht ){
102315    struct _fts3ht *pEntry = &pH->ht[h];
102316    elem = pEntry->chain;
102317    count = pEntry->count;
102318    xCompare = ftsCompareFunction(pH->keyClass);
102319    while( count-- && elem ){
102320      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
102321        return elem;
102322      }
102323      elem = elem->next;
102324    }
102325  }
102326  return 0;
102327}
102328
102329/* Remove a single entry from the hash table given a pointer to that
102330** element and a hash on the element's key.
102331*/
102332static void fts3RemoveElementByHash(
102333  Fts3Hash *pH,         /* The pH containing "elem" */
102334  Fts3HashElem* elem,   /* The element to be removed from the pH */
102335  int h                 /* Hash value for the element */
102336){
102337  struct _fts3ht *pEntry;
102338  if( elem->prev ){
102339    elem->prev->next = elem->next;
102340  }else{
102341    pH->first = elem->next;
102342  }
102343  if( elem->next ){
102344    elem->next->prev = elem->prev;
102345  }
102346  pEntry = &pH->ht[h];
102347  if( pEntry->chain==elem ){
102348    pEntry->chain = elem->next;
102349  }
102350  pEntry->count--;
102351  if( pEntry->count<=0 ){
102352    pEntry->chain = 0;
102353  }
102354  if( pH->copyKey && elem->pKey ){
102355    fts3HashFree(elem->pKey);
102356  }
102357  fts3HashFree( elem );
102358  pH->count--;
102359  if( pH->count<=0 ){
102360    assert( pH->first==0 );
102361    assert( pH->count==0 );
102362    fts3HashClear(pH);
102363  }
102364}
102365
102366SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
102367  const Fts3Hash *pH,
102368  const void *pKey,
102369  int nKey
102370){
102371  int h;                          /* A hash on key */
102372  int (*xHash)(const void*,int);  /* The hash function */
102373
102374  if( pH==0 || pH->ht==0 ) return 0;
102375  xHash = ftsHashFunction(pH->keyClass);
102376  assert( xHash!=0 );
102377  h = (*xHash)(pKey,nKey);
102378  assert( (pH->htsize & (pH->htsize-1))==0 );
102379  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
102380}
102381
102382/*
102383** Attempt to locate an element of the hash table pH with a key
102384** that matches pKey,nKey.  Return the data for this element if it is
102385** found, or NULL if there is no match.
102386*/
102387SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
102388  Fts3HashElem *pElem;            /* The element that matches key (if any) */
102389
102390  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
102391  return pElem ? pElem->data : 0;
102392}
102393
102394/* Insert an element into the hash table pH.  The key is pKey,nKey
102395** and the data is "data".
102396**
102397** If no element exists with a matching key, then a new
102398** element is created.  A copy of the key is made if the copyKey
102399** flag is set.  NULL is returned.
102400**
102401** If another element already exists with the same key, then the
102402** new data replaces the old data and the old data is returned.
102403** The key is not copied in this instance.  If a malloc fails, then
102404** the new data is returned and the hash table is unchanged.
102405**
102406** If the "data" parameter to this function is NULL, then the
102407** element corresponding to "key" is removed from the hash table.
102408*/
102409SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
102410  Fts3Hash *pH,        /* The hash table to insert into */
102411  const void *pKey,    /* The key */
102412  int nKey,            /* Number of bytes in the key */
102413  void *data           /* The data */
102414){
102415  int hraw;                 /* Raw hash value of the key */
102416  int h;                    /* the hash of the key modulo hash table size */
102417  Fts3HashElem *elem;       /* Used to loop thru the element list */
102418  Fts3HashElem *new_elem;   /* New element added to the pH */
102419  int (*xHash)(const void*,int);  /* The hash function */
102420
102421  assert( pH!=0 );
102422  xHash = ftsHashFunction(pH->keyClass);
102423  assert( xHash!=0 );
102424  hraw = (*xHash)(pKey, nKey);
102425  assert( (pH->htsize & (pH->htsize-1))==0 );
102426  h = hraw & (pH->htsize-1);
102427  elem = fts3FindElementByHash(pH,pKey,nKey,h);
102428  if( elem ){
102429    void *old_data = elem->data;
102430    if( data==0 ){
102431      fts3RemoveElementByHash(pH,elem,h);
102432    }else{
102433      elem->data = data;
102434    }
102435    return old_data;
102436  }
102437  if( data==0 ) return 0;
102438  if( (pH->htsize==0 && fts3Rehash(pH,8))
102439   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
102440  ){
102441    pH->count = 0;
102442    return data;
102443  }
102444  assert( pH->htsize>0 );
102445  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
102446  if( new_elem==0 ) return data;
102447  if( pH->copyKey && pKey!=0 ){
102448    new_elem->pKey = fts3HashMalloc( nKey );
102449    if( new_elem->pKey==0 ){
102450      fts3HashFree(new_elem);
102451      return data;
102452    }
102453    memcpy((void*)new_elem->pKey, pKey, nKey);
102454  }else{
102455    new_elem->pKey = (void*)pKey;
102456  }
102457  new_elem->nKey = nKey;
102458  pH->count++;
102459  assert( pH->htsize>0 );
102460  assert( (pH->htsize & (pH->htsize-1))==0 );
102461  h = hraw & (pH->htsize-1);
102462  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
102463  new_elem->data = data;
102464  return 0;
102465}
102466
102467#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
102468
102469/************** End of fts3_hash.c *******************************************/
102470/************** Begin file fts3_porter.c *************************************/
102471/*
102472** 2006 September 30
102473**
102474** The author disclaims copyright to this source code.  In place of
102475** a legal notice, here is a blessing:
102476**
102477**    May you do good and not evil.
102478**    May you find forgiveness for yourself and forgive others.
102479**    May you share freely, never taking more than you give.
102480**
102481*************************************************************************
102482** Implementation of the full-text-search tokenizer that implements
102483** a Porter stemmer.
102484*/
102485
102486/*
102487** The code in this file is only compiled if:
102488**
102489**     * The FTS3 module is being built as an extension
102490**       (in which case SQLITE_CORE is not defined), or
102491**
102492**     * The FTS3 module is being built into the core of
102493**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
102494*/
102495#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
102496
102497
102498
102499
102500/*
102501** Class derived from sqlite3_tokenizer
102502*/
102503typedef struct porter_tokenizer {
102504  sqlite3_tokenizer base;      /* Base class */
102505} porter_tokenizer;
102506
102507/*
102508** Class derived from sqlit3_tokenizer_cursor
102509*/
102510typedef struct porter_tokenizer_cursor {
102511  sqlite3_tokenizer_cursor base;
102512  const char *zInput;          /* input we are tokenizing */
102513  int nInput;                  /* size of the input */
102514  int iOffset;                 /* current position in zInput */
102515  int iToken;                  /* index of next token to be returned */
102516  char *zToken;                /* storage for current token */
102517  int nAllocated;              /* space allocated to zToken buffer */
102518} porter_tokenizer_cursor;
102519
102520
102521/*
102522** Create a new tokenizer instance.
102523*/
102524static int porterCreate(
102525  int argc, const char * const *argv,
102526  sqlite3_tokenizer **ppTokenizer
102527){
102528  porter_tokenizer *t;
102529
102530  UNUSED_PARAMETER(argc);
102531  UNUSED_PARAMETER(argv);
102532
102533  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
102534  if( t==NULL ) return SQLITE_NOMEM;
102535  memset(t, 0, sizeof(*t));
102536  *ppTokenizer = &t->base;
102537  return SQLITE_OK;
102538}
102539
102540/*
102541** Destroy a tokenizer
102542*/
102543static int porterDestroy(sqlite3_tokenizer *pTokenizer){
102544  sqlite3_free(pTokenizer);
102545  return SQLITE_OK;
102546}
102547
102548/*
102549** Prepare to begin tokenizing a particular string.  The input
102550** string to be tokenized is zInput[0..nInput-1].  A cursor
102551** used to incrementally tokenize this string is returned in
102552** *ppCursor.
102553*/
102554static int porterOpen(
102555  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
102556  const char *zInput, int nInput,        /* String to be tokenized */
102557  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
102558){
102559  porter_tokenizer_cursor *c;
102560
102561  UNUSED_PARAMETER(pTokenizer);
102562
102563  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
102564  if( c==NULL ) return SQLITE_NOMEM;
102565
102566  c->zInput = zInput;
102567  if( zInput==0 ){
102568    c->nInput = 0;
102569  }else if( nInput<0 ){
102570    c->nInput = (int)strlen(zInput);
102571  }else{
102572    c->nInput = nInput;
102573  }
102574  c->iOffset = 0;                 /* start tokenizing at the beginning */
102575  c->iToken = 0;
102576  c->zToken = NULL;               /* no space allocated, yet. */
102577  c->nAllocated = 0;
102578
102579  *ppCursor = &c->base;
102580  return SQLITE_OK;
102581}
102582
102583/*
102584** Close a tokenization cursor previously opened by a call to
102585** porterOpen() above.
102586*/
102587static int porterClose(sqlite3_tokenizer_cursor *pCursor){
102588  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
102589  sqlite3_free(c->zToken);
102590  sqlite3_free(c);
102591  return SQLITE_OK;
102592}
102593/*
102594** Vowel or consonant
102595*/
102596static const char cType[] = {
102597   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
102598   1, 1, 1, 2, 1
102599};
102600
102601/*
102602** isConsonant() and isVowel() determine if their first character in
102603** the string they point to is a consonant or a vowel, according
102604** to Porter ruls.
102605**
102606** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
102607** 'Y' is a consonant unless it follows another consonant,
102608** in which case it is a vowel.
102609**
102610** In these routine, the letters are in reverse order.  So the 'y' rule
102611** is that 'y' is a consonant unless it is followed by another
102612** consonent.
102613*/
102614static int isVowel(const char*);
102615static int isConsonant(const char *z){
102616  int j;
102617  char x = *z;
102618  if( x==0 ) return 0;
102619  assert( x>='a' && x<='z' );
102620  j = cType[x-'a'];
102621  if( j<2 ) return j;
102622  return z[1]==0 || isVowel(z + 1);
102623}
102624static int isVowel(const char *z){
102625  int j;
102626  char x = *z;
102627  if( x==0 ) return 0;
102628  assert( x>='a' && x<='z' );
102629  j = cType[x-'a'];
102630  if( j<2 ) return 1-j;
102631  return isConsonant(z + 1);
102632}
102633
102634/*
102635** Let any sequence of one or more vowels be represented by V and let
102636** C be sequence of one or more consonants.  Then every word can be
102637** represented as:
102638**
102639**           [C] (VC){m} [V]
102640**
102641** In prose:  A word is an optional consonant followed by zero or
102642** vowel-consonant pairs followed by an optional vowel.  "m" is the
102643** number of vowel consonant pairs.  This routine computes the value
102644** of m for the first i bytes of a word.
102645**
102646** Return true if the m-value for z is 1 or more.  In other words,
102647** return true if z contains at least one vowel that is followed
102648** by a consonant.
102649**
102650** In this routine z[] is in reverse order.  So we are really looking
102651** for an instance of of a consonant followed by a vowel.
102652*/
102653static int m_gt_0(const char *z){
102654  while( isVowel(z) ){ z++; }
102655  if( *z==0 ) return 0;
102656  while( isConsonant(z) ){ z++; }
102657  return *z!=0;
102658}
102659
102660/* Like mgt0 above except we are looking for a value of m which is
102661** exactly 1
102662*/
102663static int m_eq_1(const char *z){
102664  while( isVowel(z) ){ z++; }
102665  if( *z==0 ) return 0;
102666  while( isConsonant(z) ){ z++; }
102667  if( *z==0 ) return 0;
102668  while( isVowel(z) ){ z++; }
102669  if( *z==0 ) return 1;
102670  while( isConsonant(z) ){ z++; }
102671  return *z==0;
102672}
102673
102674/* Like mgt0 above except we are looking for a value of m>1 instead
102675** or m>0
102676*/
102677static int m_gt_1(const char *z){
102678  while( isVowel(z) ){ z++; }
102679  if( *z==0 ) return 0;
102680  while( isConsonant(z) ){ z++; }
102681  if( *z==0 ) return 0;
102682  while( isVowel(z) ){ z++; }
102683  if( *z==0 ) return 0;
102684  while( isConsonant(z) ){ z++; }
102685  return *z!=0;
102686}
102687
102688/*
102689** Return TRUE if there is a vowel anywhere within z[0..n-1]
102690*/
102691static int hasVowel(const char *z){
102692  while( isConsonant(z) ){ z++; }
102693  return *z!=0;
102694}
102695
102696/*
102697** Return TRUE if the word ends in a double consonant.
102698**
102699** The text is reversed here. So we are really looking at
102700** the first two characters of z[].
102701*/
102702static int doubleConsonant(const char *z){
102703  return isConsonant(z) && z[0]==z[1];
102704}
102705
102706/*
102707** Return TRUE if the word ends with three letters which
102708** are consonant-vowel-consonent and where the final consonant
102709** is not 'w', 'x', or 'y'.
102710**
102711** The word is reversed here.  So we are really checking the
102712** first three letters and the first one cannot be in [wxy].
102713*/
102714static int star_oh(const char *z){
102715  return
102716    isConsonant(z) &&
102717    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
102718    isVowel(z+1) &&
102719    isConsonant(z+2);
102720}
102721
102722/*
102723** If the word ends with zFrom and xCond() is true for the stem
102724** of the word that preceeds the zFrom ending, then change the
102725** ending to zTo.
102726**
102727** The input word *pz and zFrom are both in reverse order.  zTo
102728** is in normal order.
102729**
102730** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
102731** match.  Not that TRUE is returned even if xCond() fails and
102732** no substitution occurs.
102733*/
102734static int stem(
102735  char **pz,             /* The word being stemmed (Reversed) */
102736  const char *zFrom,     /* If the ending matches this... (Reversed) */
102737  const char *zTo,       /* ... change the ending to this (not reversed) */
102738  int (*xCond)(const char*)   /* Condition that must be true */
102739){
102740  char *z = *pz;
102741  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
102742  if( *zFrom!=0 ) return 0;
102743  if( xCond && !xCond(z) ) return 1;
102744  while( *zTo ){
102745    *(--z) = *(zTo++);
102746  }
102747  *pz = z;
102748  return 1;
102749}
102750
102751/*
102752** This is the fallback stemmer used when the porter stemmer is
102753** inappropriate.  The input word is copied into the output with
102754** US-ASCII case folding.  If the input word is too long (more
102755** than 20 bytes if it contains no digits or more than 6 bytes if
102756** it contains digits) then word is truncated to 20 or 6 bytes
102757** by taking 10 or 3 bytes from the beginning and end.
102758*/
102759static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
102760  int i, mx, j;
102761  int hasDigit = 0;
102762  for(i=0; i<nIn; i++){
102763    char c = zIn[i];
102764    if( c>='A' && c<='Z' ){
102765      zOut[i] = c - 'A' + 'a';
102766    }else{
102767      if( c>='0' && c<='9' ) hasDigit = 1;
102768      zOut[i] = c;
102769    }
102770  }
102771  mx = hasDigit ? 3 : 10;
102772  if( nIn>mx*2 ){
102773    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
102774      zOut[j] = zOut[i];
102775    }
102776    i = j;
102777  }
102778  zOut[i] = 0;
102779  *pnOut = i;
102780}
102781
102782
102783/*
102784** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
102785** zOut is at least big enough to hold nIn bytes.  Write the actual
102786** size of the output word (exclusive of the '\0' terminator) into *pnOut.
102787**
102788** Any upper-case characters in the US-ASCII character set ([A-Z])
102789** are converted to lower case.  Upper-case UTF characters are
102790** unchanged.
102791**
102792** Words that are longer than about 20 bytes are stemmed by retaining
102793** a few bytes from the beginning and the end of the word.  If the
102794** word contains digits, 3 bytes are taken from the beginning and
102795** 3 bytes from the end.  For long words without digits, 10 bytes
102796** are taken from each end.  US-ASCII case folding still applies.
102797**
102798** If the input word contains not digits but does characters not
102799** in [a-zA-Z] then no stemming is attempted and this routine just
102800** copies the input into the input into the output with US-ASCII
102801** case folding.
102802**
102803** Stemming never increases the length of the word.  So there is
102804** no chance of overflowing the zOut buffer.
102805*/
102806static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
102807  int i, j;
102808  char zReverse[28];
102809  char *z, *z2;
102810  if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
102811    /* The word is too big or too small for the porter stemmer.
102812    ** Fallback to the copy stemmer */
102813    copy_stemmer(zIn, nIn, zOut, pnOut);
102814    return;
102815  }
102816  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
102817    char c = zIn[i];
102818    if( c>='A' && c<='Z' ){
102819      zReverse[j] = c + 'a' - 'A';
102820    }else if( c>='a' && c<='z' ){
102821      zReverse[j] = c;
102822    }else{
102823      /* The use of a character not in [a-zA-Z] means that we fallback
102824      ** to the copy stemmer */
102825      copy_stemmer(zIn, nIn, zOut, pnOut);
102826      return;
102827    }
102828  }
102829  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
102830  z = &zReverse[j+1];
102831
102832
102833  /* Step 1a */
102834  if( z[0]=='s' ){
102835    if(
102836     !stem(&z, "sess", "ss", 0) &&
102837     !stem(&z, "sei", "i", 0)  &&
102838     !stem(&z, "ss", "ss", 0)
102839    ){
102840      z++;
102841    }
102842  }
102843
102844  /* Step 1b */
102845  z2 = z;
102846  if( stem(&z, "dee", "ee", m_gt_0) ){
102847    /* Do nothing.  The work was all in the test */
102848  }else if(
102849     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
102850      && z!=z2
102851  ){
102852     if( stem(&z, "ta", "ate", 0) ||
102853         stem(&z, "lb", "ble", 0) ||
102854         stem(&z, "zi", "ize", 0) ){
102855       /* Do nothing.  The work was all in the test */
102856     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
102857       z++;
102858     }else if( m_eq_1(z) && star_oh(z) ){
102859       *(--z) = 'e';
102860     }
102861  }
102862
102863  /* Step 1c */
102864  if( z[0]=='y' && hasVowel(z+1) ){
102865    z[0] = 'i';
102866  }
102867
102868  /* Step 2 */
102869  switch( z[1] ){
102870   case 'a':
102871     stem(&z, "lanoita", "ate", m_gt_0) ||
102872     stem(&z, "lanoit", "tion", m_gt_0);
102873     break;
102874   case 'c':
102875     stem(&z, "icne", "ence", m_gt_0) ||
102876     stem(&z, "icna", "ance", m_gt_0);
102877     break;
102878   case 'e':
102879     stem(&z, "rezi", "ize", m_gt_0);
102880     break;
102881   case 'g':
102882     stem(&z, "igol", "log", m_gt_0);
102883     break;
102884   case 'l':
102885     stem(&z, "ilb", "ble", m_gt_0) ||
102886     stem(&z, "illa", "al", m_gt_0) ||
102887     stem(&z, "iltne", "ent", m_gt_0) ||
102888     stem(&z, "ile", "e", m_gt_0) ||
102889     stem(&z, "ilsuo", "ous", m_gt_0);
102890     break;
102891   case 'o':
102892     stem(&z, "noitazi", "ize", m_gt_0) ||
102893     stem(&z, "noita", "ate", m_gt_0) ||
102894     stem(&z, "rota", "ate", m_gt_0);
102895     break;
102896   case 's':
102897     stem(&z, "msila", "al", m_gt_0) ||
102898     stem(&z, "ssenevi", "ive", m_gt_0) ||
102899     stem(&z, "ssenluf", "ful", m_gt_0) ||
102900     stem(&z, "ssensuo", "ous", m_gt_0);
102901     break;
102902   case 't':
102903     stem(&z, "itila", "al", m_gt_0) ||
102904     stem(&z, "itivi", "ive", m_gt_0) ||
102905     stem(&z, "itilib", "ble", m_gt_0);
102906     break;
102907  }
102908
102909  /* Step 3 */
102910  switch( z[0] ){
102911   case 'e':
102912     stem(&z, "etaci", "ic", m_gt_0) ||
102913     stem(&z, "evita", "", m_gt_0)   ||
102914     stem(&z, "ezila", "al", m_gt_0);
102915     break;
102916   case 'i':
102917     stem(&z, "itici", "ic", m_gt_0);
102918     break;
102919   case 'l':
102920     stem(&z, "laci", "ic", m_gt_0) ||
102921     stem(&z, "luf", "", m_gt_0);
102922     break;
102923   case 's':
102924     stem(&z, "ssen", "", m_gt_0);
102925     break;
102926  }
102927
102928  /* Step 4 */
102929  switch( z[1] ){
102930   case 'a':
102931     if( z[0]=='l' && m_gt_1(z+2) ){
102932       z += 2;
102933     }
102934     break;
102935   case 'c':
102936     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
102937       z += 4;
102938     }
102939     break;
102940   case 'e':
102941     if( z[0]=='r' && m_gt_1(z+2) ){
102942       z += 2;
102943     }
102944     break;
102945   case 'i':
102946     if( z[0]=='c' && m_gt_1(z+2) ){
102947       z += 2;
102948     }
102949     break;
102950   case 'l':
102951     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
102952       z += 4;
102953     }
102954     break;
102955   case 'n':
102956     if( z[0]=='t' ){
102957       if( z[2]=='a' ){
102958         if( m_gt_1(z+3) ){
102959           z += 3;
102960         }
102961       }else if( z[2]=='e' ){
102962         stem(&z, "tneme", "", m_gt_1) ||
102963         stem(&z, "tnem", "", m_gt_1) ||
102964         stem(&z, "tne", "", m_gt_1);
102965       }
102966     }
102967     break;
102968   case 'o':
102969     if( z[0]=='u' ){
102970       if( m_gt_1(z+2) ){
102971         z += 2;
102972       }
102973     }else if( z[3]=='s' || z[3]=='t' ){
102974       stem(&z, "noi", "", m_gt_1);
102975     }
102976     break;
102977   case 's':
102978     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
102979       z += 3;
102980     }
102981     break;
102982   case 't':
102983     stem(&z, "eta", "", m_gt_1) ||
102984     stem(&z, "iti", "", m_gt_1);
102985     break;
102986   case 'u':
102987     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
102988       z += 3;
102989     }
102990     break;
102991   case 'v':
102992   case 'z':
102993     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
102994       z += 3;
102995     }
102996     break;
102997  }
102998
102999  /* Step 5a */
103000  if( z[0]=='e' ){
103001    if( m_gt_1(z+1) ){
103002      z++;
103003    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
103004      z++;
103005    }
103006  }
103007
103008  /* Step 5b */
103009  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
103010    z++;
103011  }
103012
103013  /* z[] is now the stemmed word in reverse order.  Flip it back
103014  ** around into forward order and return.
103015  */
103016  *pnOut = i = (int)strlen(z);
103017  zOut[i] = 0;
103018  while( *z ){
103019    zOut[--i] = *(z++);
103020  }
103021}
103022
103023/*
103024** Characters that can be part of a token.  We assume any character
103025** whose value is greater than 0x80 (any UTF character) can be
103026** part of a token.  In other words, delimiters all must have
103027** values of 0x7f or lower.
103028*/
103029static const char porterIdChar[] = {
103030/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
103031    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
103032    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
103033    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
103034    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
103035    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
103036};
103037#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
103038
103039/*
103040** Extract the next token from a tokenization cursor.  The cursor must
103041** have been opened by a prior call to porterOpen().
103042*/
103043static int porterNext(
103044  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
103045  const char **pzToken,               /* OUT: *pzToken is the token text */
103046  int *pnBytes,                       /* OUT: Number of bytes in token */
103047  int *piStartOffset,                 /* OUT: Starting offset of token */
103048  int *piEndOffset,                   /* OUT: Ending offset of token */
103049  int *piPosition                     /* OUT: Position integer of token */
103050){
103051  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
103052  const char *z = c->zInput;
103053
103054  while( c->iOffset<c->nInput ){
103055    int iStartOffset, ch;
103056
103057    /* Scan past delimiter characters */
103058    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
103059      c->iOffset++;
103060    }
103061
103062    /* Count non-delimiter characters. */
103063    iStartOffset = c->iOffset;
103064    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
103065      c->iOffset++;
103066    }
103067
103068    if( c->iOffset>iStartOffset ){
103069      int n = c->iOffset-iStartOffset;
103070      if( n>c->nAllocated ){
103071        c->nAllocated = n+20;
103072        c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
103073        if( c->zToken==NULL ) return SQLITE_NOMEM;
103074      }
103075      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
103076      *pzToken = c->zToken;
103077      *piStartOffset = iStartOffset;
103078      *piEndOffset = c->iOffset;
103079      *piPosition = c->iToken++;
103080      return SQLITE_OK;
103081    }
103082  }
103083  return SQLITE_DONE;
103084}
103085
103086/*
103087** The set of routines that implement the porter-stemmer tokenizer
103088*/
103089static const sqlite3_tokenizer_module porterTokenizerModule = {
103090  0,
103091  porterCreate,
103092  porterDestroy,
103093  porterOpen,
103094  porterClose,
103095  porterNext,
103096};
103097
103098/*
103099** Allocate a new porter tokenizer.  Return a pointer to the new
103100** tokenizer in *ppModule
103101*/
103102SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
103103  sqlite3_tokenizer_module const**ppModule
103104){
103105  *ppModule = &porterTokenizerModule;
103106}
103107
103108#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
103109
103110/************** End of fts3_porter.c *****************************************/
103111/************** Begin file fts3_tokenizer.c **********************************/
103112/*
103113** 2007 June 22
103114**
103115** The author disclaims copyright to this source code.  In place of
103116** a legal notice, here is a blessing:
103117**
103118**    May you do good and not evil.
103119**    May you find forgiveness for yourself and forgive others.
103120**    May you share freely, never taking more than you give.
103121**
103122******************************************************************************
103123**
103124** This is part of an SQLite module implementing full-text search.
103125** This particular file implements the generic tokenizer interface.
103126*/
103127
103128/*
103129** The code in this file is only compiled if:
103130**
103131**     * The FTS3 module is being built as an extension
103132**       (in which case SQLITE_CORE is not defined), or
103133**
103134**     * The FTS3 module is being built into the core of
103135**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
103136*/
103137#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
103138
103139#ifndef SQLITE_CORE
103140  SQLITE_EXTENSION_INIT1
103141#endif
103142
103143
103144/*
103145** Implementation of the SQL scalar function for accessing the underlying
103146** hash table. This function may be called as follows:
103147**
103148**   SELECT <function-name>(<key-name>);
103149**   SELECT <function-name>(<key-name>, <pointer>);
103150**
103151** where <function-name> is the name passed as the second argument
103152** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
103153**
103154** If the <pointer> argument is specified, it must be a blob value
103155** containing a pointer to be stored as the hash data corresponding
103156** to the string <key-name>. If <pointer> is not specified, then
103157** the string <key-name> must already exist in the has table. Otherwise,
103158** an error is returned.
103159**
103160** Whether or not the <pointer> argument is specified, the value returned
103161** is a blob containing the pointer stored as the hash data corresponding
103162** to string <key-name> (after the hash-table is updated, if applicable).
103163*/
103164static void scalarFunc(
103165  sqlite3_context *context,
103166  int argc,
103167  sqlite3_value **argv
103168){
103169  Fts3Hash *pHash;
103170  void *pPtr = 0;
103171  const unsigned char *zName;
103172  int nName;
103173
103174  assert( argc==1 || argc==2 );
103175
103176  pHash = (Fts3Hash *)sqlite3_user_data(context);
103177
103178  zName = sqlite3_value_text(argv[0]);
103179  nName = sqlite3_value_bytes(argv[0])+1;
103180
103181  if( argc==2 ){
103182    void *pOld;
103183    int n = sqlite3_value_bytes(argv[1]);
103184    if( n!=sizeof(pPtr) ){
103185      sqlite3_result_error(context, "argument type mismatch", -1);
103186      return;
103187    }
103188    pPtr = *(void **)sqlite3_value_blob(argv[1]);
103189    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
103190    if( pOld==pPtr ){
103191      sqlite3_result_error(context, "out of memory", -1);
103192      return;
103193    }
103194  }else{
103195    pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
103196    if( !pPtr ){
103197      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
103198      sqlite3_result_error(context, zErr, -1);
103199      sqlite3_free(zErr);
103200      return;
103201    }
103202  }
103203
103204  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
103205}
103206
103207static int fts3IsIdChar(char c){
103208  static const char isFtsIdChar[] = {
103209      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
103210      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
103211      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
103212      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
103213      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
103214      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
103215      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
103216      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
103217  };
103218  return (c&0x80 || isFtsIdChar[(int)(c)]);
103219}
103220
103221SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
103222  const char *z1;
103223  const char *z2 = 0;
103224
103225  /* Find the start of the next token. */
103226  z1 = zStr;
103227  while( z2==0 ){
103228    char c = *z1;
103229    switch( c ){
103230      case '\0': return 0;        /* No more tokens here */
103231      case '\'':
103232      case '"':
103233      case '`': {
103234        z2 = z1;
103235        while( *++z2 && (*z2!=c || *++z2==c) );
103236        break;
103237      }
103238      case '[':
103239        z2 = &z1[1];
103240        while( *z2 && z2[0]!=']' ) z2++;
103241        if( *z2 ) z2++;
103242        break;
103243
103244      default:
103245        if( fts3IsIdChar(*z1) ){
103246          z2 = &z1[1];
103247          while( fts3IsIdChar(*z2) ) z2++;
103248        }else{
103249          z1++;
103250        }
103251    }
103252  }
103253
103254  *pn = (int)(z2-z1);
103255  return z1;
103256}
103257
103258SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
103259  Fts3Hash *pHash,                /* Tokenizer hash table */
103260  const char *zArg,               /* Possible tokenizer specification */
103261  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
103262  const char **pzTokenizer,       /* OUT: Set to zArg if is tokenizer */
103263  char **pzErr                    /* OUT: Set to malloced error message */
103264){
103265  int rc;
103266  char *z = (char *)zArg;
103267  int n;
103268  char *zCopy;
103269  char *zEnd;                     /* Pointer to nul-term of zCopy */
103270  sqlite3_tokenizer_module *m;
103271
103272  if( !z ){
103273    zCopy = sqlite3_mprintf("simple");
103274  }else{
103275    if( sqlite3_strnicmp(z, "tokenize", 8) || fts3IsIdChar(z[8])){
103276      return SQLITE_OK;
103277    }
103278    zCopy = sqlite3_mprintf("%s", &z[8]);
103279    *pzTokenizer = zArg;
103280  }
103281  if( !zCopy ){
103282    return SQLITE_NOMEM;
103283  }
103284
103285  zEnd = &zCopy[strlen(zCopy)];
103286
103287  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
103288  z[n] = '\0';
103289  sqlite3Fts3Dequote(z);
103290
103291  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, z, (int)strlen(z)+1);
103292  if( !m ){
103293    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
103294    rc = SQLITE_ERROR;
103295  }else{
103296    char const **aArg = 0;
103297    int iArg = 0;
103298    z = &z[n+1];
103299    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
103300      int nNew = sizeof(char *)*(iArg+1);
103301      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
103302      if( !aNew ){
103303        sqlite3_free(zCopy);
103304        sqlite3_free((void *)aArg);
103305        return SQLITE_NOMEM;
103306      }
103307      aArg = aNew;
103308      aArg[iArg++] = z;
103309      z[n] = '\0';
103310      sqlite3Fts3Dequote(z);
103311      z = &z[n+1];
103312    }
103313    rc = m->xCreate(iArg, aArg, ppTok);
103314    assert( rc!=SQLITE_OK || *ppTok );
103315    if( rc!=SQLITE_OK ){
103316      *pzErr = sqlite3_mprintf("unknown tokenizer");
103317    }else{
103318      (*ppTok)->pModule = m;
103319    }
103320    sqlite3_free((void *)aArg);
103321  }
103322
103323  sqlite3_free(zCopy);
103324  return rc;
103325}
103326
103327
103328#ifdef SQLITE_TEST
103329
103330
103331/*
103332** Implementation of a special SQL scalar function for testing tokenizers
103333** designed to be used in concert with the Tcl testing framework. This
103334** function must be called with two arguments:
103335**
103336**   SELECT <function-name>(<key-name>, <input-string>);
103337**   SELECT <function-name>(<key-name>, <pointer>);
103338**
103339** where <function-name> is the name passed as the second argument
103340** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
103341** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
103342**
103343** The return value is a string that may be interpreted as a Tcl
103344** list. For each token in the <input-string>, three elements are
103345** added to the returned list. The first is the token position, the
103346** second is the token text (folded, stemmed, etc.) and the third is the
103347** substring of <input-string> associated with the token. For example,
103348** using the built-in "simple" tokenizer:
103349**
103350**   SELECT fts_tokenizer_test('simple', 'I don't see how');
103351**
103352** will return the string:
103353**
103354**   "{0 i I 1 dont don't 2 see see 3 how how}"
103355**
103356*/
103357static void testFunc(
103358  sqlite3_context *context,
103359  int argc,
103360  sqlite3_value **argv
103361){
103362  Fts3Hash *pHash;
103363  sqlite3_tokenizer_module *p;
103364  sqlite3_tokenizer *pTokenizer = 0;
103365  sqlite3_tokenizer_cursor *pCsr = 0;
103366
103367  const char *zErr = 0;
103368
103369  const char *zName;
103370  int nName;
103371  const char *zInput;
103372  int nInput;
103373
103374  const char *zArg = 0;
103375
103376  const char *zToken;
103377  int nToken;
103378  int iStart;
103379  int iEnd;
103380  int iPos;
103381
103382  Tcl_Obj *pRet;
103383
103384  assert( argc==2 || argc==3 );
103385
103386  nName = sqlite3_value_bytes(argv[0]);
103387  zName = (const char *)sqlite3_value_text(argv[0]);
103388  nInput = sqlite3_value_bytes(argv[argc-1]);
103389  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
103390
103391  if( argc==3 ){
103392    zArg = (const char *)sqlite3_value_text(argv[1]);
103393  }
103394
103395  pHash = (Fts3Hash *)sqlite3_user_data(context);
103396  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
103397
103398  if( !p ){
103399    char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
103400    sqlite3_result_error(context, zErr, -1);
103401    sqlite3_free(zErr);
103402    return;
103403  }
103404
103405  pRet = Tcl_NewObj();
103406  Tcl_IncrRefCount(pRet);
103407
103408  if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
103409    zErr = "error in xCreate()";
103410    goto finish;
103411  }
103412  pTokenizer->pModule = p;
103413  if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
103414    zErr = "error in xOpen()";
103415    goto finish;
103416  }
103417  pCsr->pTokenizer = pTokenizer;
103418
103419  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
103420    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
103421    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
103422    zToken = &zInput[iStart];
103423    nToken = iEnd-iStart;
103424    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
103425  }
103426
103427  if( SQLITE_OK!=p->xClose(pCsr) ){
103428    zErr = "error in xClose()";
103429    goto finish;
103430  }
103431  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
103432    zErr = "error in xDestroy()";
103433    goto finish;
103434  }
103435
103436finish:
103437  if( zErr ){
103438    sqlite3_result_error(context, zErr, -1);
103439  }else{
103440    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
103441  }
103442  Tcl_DecrRefCount(pRet);
103443}
103444
103445static
103446int registerTokenizer(
103447  sqlite3 *db,
103448  char *zName,
103449  const sqlite3_tokenizer_module *p
103450){
103451  int rc;
103452  sqlite3_stmt *pStmt;
103453  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
103454
103455  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
103456  if( rc!=SQLITE_OK ){
103457    return rc;
103458  }
103459
103460  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
103461  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
103462  sqlite3_step(pStmt);
103463
103464  return sqlite3_finalize(pStmt);
103465}
103466
103467static
103468int queryTokenizer(
103469  sqlite3 *db,
103470  char *zName,
103471  const sqlite3_tokenizer_module **pp
103472){
103473  int rc;
103474  sqlite3_stmt *pStmt;
103475  const char zSql[] = "SELECT fts3_tokenizer(?)";
103476
103477  *pp = 0;
103478  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
103479  if( rc!=SQLITE_OK ){
103480    return rc;
103481  }
103482
103483  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
103484  if( SQLITE_ROW==sqlite3_step(pStmt) ){
103485    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
103486      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
103487    }
103488  }
103489
103490  return sqlite3_finalize(pStmt);
103491}
103492
103493SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
103494
103495/*
103496** Implementation of the scalar function fts3_tokenizer_internal_test().
103497** This function is used for testing only, it is not included in the
103498** build unless SQLITE_TEST is defined.
103499**
103500** The purpose of this is to test that the fts3_tokenizer() function
103501** can be used as designed by the C-code in the queryTokenizer and
103502** registerTokenizer() functions above. These two functions are repeated
103503** in the README.tokenizer file as an example, so it is important to
103504** test them.
103505**
103506** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
103507** function with no arguments. An assert() will fail if a problem is
103508** detected. i.e.:
103509**
103510**     SELECT fts3_tokenizer_internal_test();
103511**
103512*/
103513static void intTestFunc(
103514  sqlite3_context *context,
103515  int argc,
103516  sqlite3_value **argv
103517){
103518  int rc;
103519  const sqlite3_tokenizer_module *p1;
103520  const sqlite3_tokenizer_module *p2;
103521  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
103522
103523  UNUSED_PARAMETER(argc);
103524  UNUSED_PARAMETER(argv);
103525
103526  /* Test the query function */
103527  sqlite3Fts3SimpleTokenizerModule(&p1);
103528  rc = queryTokenizer(db, "simple", &p2);
103529  assert( rc==SQLITE_OK );
103530  assert( p1==p2 );
103531  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
103532  assert( rc==SQLITE_ERROR );
103533  assert( p2==0 );
103534  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
103535
103536  /* Test the storage function */
103537  rc = registerTokenizer(db, "nosuchtokenizer", p1);
103538  assert( rc==SQLITE_OK );
103539  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
103540  assert( rc==SQLITE_OK );
103541  assert( p2==p1 );
103542
103543  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
103544}
103545
103546#endif
103547
103548/*
103549** Set up SQL objects in database db used to access the contents of
103550** the hash table pointed to by argument pHash. The hash table must
103551** been initialised to use string keys, and to take a private copy
103552** of the key when a value is inserted. i.e. by a call similar to:
103553**
103554**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
103555**
103556** This function adds a scalar function (see header comment above
103557** scalarFunc() in this file for details) and, if ENABLE_TABLE is
103558** defined at compilation time, a temporary virtual table (see header
103559** comment above struct HashTableVtab) to the database schema. Both
103560** provide read/write access to the contents of *pHash.
103561**
103562** The third argument to this function, zName, is used as the name
103563** of both the scalar and, if created, the virtual table.
103564*/
103565SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
103566  sqlite3 *db,
103567  Fts3Hash *pHash,
103568  const char *zName
103569){
103570  int rc = SQLITE_OK;
103571  void *p = (void *)pHash;
103572  const int any = SQLITE_ANY;
103573
103574#ifdef SQLITE_TEST
103575  char *zTest = 0;
103576  char *zTest2 = 0;
103577  void *pdb = (void *)db;
103578  zTest = sqlite3_mprintf("%s_test", zName);
103579  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
103580  if( !zTest || !zTest2 ){
103581    rc = SQLITE_NOMEM;
103582  }
103583#endif
103584
103585  if( SQLITE_OK!=rc
103586   || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
103587   || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
103588#ifdef SQLITE_TEST
103589   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
103590   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
103591   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
103592#endif
103593   );
103594
103595#ifdef SQLITE_TEST
103596  sqlite3_free(zTest);
103597  sqlite3_free(zTest2);
103598#endif
103599
103600  return rc;
103601}
103602
103603#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
103604
103605/************** End of fts3_tokenizer.c **************************************/
103606/************** Begin file fts3_tokenizer1.c *********************************/
103607/*
103608** 2006 Oct 10
103609**
103610** The author disclaims copyright to this source code.  In place of
103611** a legal notice, here is a blessing:
103612**
103613**    May you do good and not evil.
103614**    May you find forgiveness for yourself and forgive others.
103615**    May you share freely, never taking more than you give.
103616**
103617******************************************************************************
103618**
103619** Implementation of the "simple" full-text-search tokenizer.
103620*/
103621
103622/*
103623** The code in this file is only compiled if:
103624**
103625**     * The FTS3 module is being built as an extension
103626**       (in which case SQLITE_CORE is not defined), or
103627**
103628**     * The FTS3 module is being built into the core of
103629**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
103630*/
103631#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
103632
103633
103634
103635
103636typedef struct simple_tokenizer {
103637  sqlite3_tokenizer base;
103638  char delim[128];             /* flag ASCII delimiters */
103639} simple_tokenizer;
103640
103641typedef struct simple_tokenizer_cursor {
103642  sqlite3_tokenizer_cursor base;
103643  const char *pInput;          /* input we are tokenizing */
103644  int nBytes;                  /* size of the input */
103645  int iOffset;                 /* current position in pInput */
103646  int iToken;                  /* index of next token to be returned */
103647  char *pToken;                /* storage for current token */
103648  int nTokenAllocated;         /* space allocated to zToken buffer */
103649} simple_tokenizer_cursor;
103650
103651
103652static int simpleDelim(simple_tokenizer *t, unsigned char c){
103653  return c<0x80 && t->delim[c];
103654}
103655
103656/*
103657** Create a new tokenizer instance.
103658*/
103659static int simpleCreate(
103660  int argc, const char * const *argv,
103661  sqlite3_tokenizer **ppTokenizer
103662){
103663  simple_tokenizer *t;
103664
103665  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
103666  if( t==NULL ) return SQLITE_NOMEM;
103667  memset(t, 0, sizeof(*t));
103668
103669  /* TODO(shess) Delimiters need to remain the same from run to run,
103670  ** else we need to reindex.  One solution would be a meta-table to
103671  ** track such information in the database, then we'd only want this
103672  ** information on the initial create.
103673  */
103674  if( argc>1 ){
103675    int i, n = (int)strlen(argv[1]);
103676    for(i=0; i<n; i++){
103677      unsigned char ch = argv[1][i];
103678      /* We explicitly don't support UTF-8 delimiters for now. */
103679      if( ch>=0x80 ){
103680        sqlite3_free(t);
103681        return SQLITE_ERROR;
103682      }
103683      t->delim[ch] = 1;
103684    }
103685  } else {
103686    /* Mark non-alphanumeric ASCII characters as delimiters */
103687    int i;
103688    for(i=1; i<0x80; i++){
103689      t->delim[i] = !isalnum(i) ? -1 : 0;
103690    }
103691  }
103692
103693  *ppTokenizer = &t->base;
103694  return SQLITE_OK;
103695}
103696
103697/*
103698** Destroy a tokenizer
103699*/
103700static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
103701  sqlite3_free(pTokenizer);
103702  return SQLITE_OK;
103703}
103704
103705/*
103706** Prepare to begin tokenizing a particular string.  The input
103707** string to be tokenized is pInput[0..nBytes-1].  A cursor
103708** used to incrementally tokenize this string is returned in
103709** *ppCursor.
103710*/
103711static int simpleOpen(
103712  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
103713  const char *pInput, int nBytes,        /* String to be tokenized */
103714  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
103715){
103716  simple_tokenizer_cursor *c;
103717
103718  UNUSED_PARAMETER(pTokenizer);
103719
103720  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
103721  if( c==NULL ) return SQLITE_NOMEM;
103722
103723  c->pInput = pInput;
103724  if( pInput==0 ){
103725    c->nBytes = 0;
103726  }else if( nBytes<0 ){
103727    c->nBytes = (int)strlen(pInput);
103728  }else{
103729    c->nBytes = nBytes;
103730  }
103731  c->iOffset = 0;                 /* start tokenizing at the beginning */
103732  c->iToken = 0;
103733  c->pToken = NULL;               /* no space allocated, yet. */
103734  c->nTokenAllocated = 0;
103735
103736  *ppCursor = &c->base;
103737  return SQLITE_OK;
103738}
103739
103740/*
103741** Close a tokenization cursor previously opened by a call to
103742** simpleOpen() above.
103743*/
103744static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
103745  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
103746  sqlite3_free(c->pToken);
103747  sqlite3_free(c);
103748  return SQLITE_OK;
103749}
103750
103751/*
103752** Extract the next token from a tokenization cursor.  The cursor must
103753** have been opened by a prior call to simpleOpen().
103754*/
103755static int simpleNext(
103756  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
103757  const char **ppToken,               /* OUT: *ppToken is the token text */
103758  int *pnBytes,                       /* OUT: Number of bytes in token */
103759  int *piStartOffset,                 /* OUT: Starting offset of token */
103760  int *piEndOffset,                   /* OUT: Ending offset of token */
103761  int *piPosition                     /* OUT: Position integer of token */
103762){
103763  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
103764  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
103765  unsigned char *p = (unsigned char *)c->pInput;
103766
103767  while( c->iOffset<c->nBytes ){
103768    int iStartOffset;
103769
103770    /* Scan past delimiter characters */
103771    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
103772      c->iOffset++;
103773    }
103774
103775    /* Count non-delimiter characters. */
103776    iStartOffset = c->iOffset;
103777    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
103778      c->iOffset++;
103779    }
103780
103781    if( c->iOffset>iStartOffset ){
103782      int i, n = c->iOffset-iStartOffset;
103783      if( n>c->nTokenAllocated ){
103784        c->nTokenAllocated = n+20;
103785        c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
103786        if( c->pToken==NULL ) return SQLITE_NOMEM;
103787      }
103788      for(i=0; i<n; i++){
103789        /* TODO(shess) This needs expansion to handle UTF-8
103790        ** case-insensitivity.
103791        */
103792        unsigned char ch = p[iStartOffset+i];
103793        c->pToken[i] = (char)(ch<0x80 ? tolower(ch) : ch);
103794      }
103795      *ppToken = c->pToken;
103796      *pnBytes = n;
103797      *piStartOffset = iStartOffset;
103798      *piEndOffset = c->iOffset;
103799      *piPosition = c->iToken++;
103800
103801      return SQLITE_OK;
103802    }
103803  }
103804  return SQLITE_DONE;
103805}
103806
103807/*
103808** The set of routines that implement the simple tokenizer
103809*/
103810static const sqlite3_tokenizer_module simpleTokenizerModule = {
103811  0,
103812  simpleCreate,
103813  simpleDestroy,
103814  simpleOpen,
103815  simpleClose,
103816  simpleNext,
103817};
103818
103819/*
103820** Allocate a new simple tokenizer.  Return a pointer to the new
103821** tokenizer in *ppModule
103822*/
103823SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
103824  sqlite3_tokenizer_module const**ppModule
103825){
103826  *ppModule = &simpleTokenizerModule;
103827}
103828
103829#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
103830
103831/************** End of fts3_tokenizer1.c *************************************/
103832/************** Begin file fts3_write.c **************************************/
103833/*
103834** 2009 Oct 23
103835**
103836** The author disclaims copyright to this source code.  In place of
103837** a legal notice, here is a blessing:
103838**
103839**    May you do good and not evil.
103840**    May you find forgiveness for yourself and forgive others.
103841**    May you share freely, never taking more than you give.
103842**
103843******************************************************************************
103844**
103845** This file is part of the SQLite FTS3 extension module. Specifically,
103846** this file contains code to insert, update and delete rows from FTS3
103847** tables. It also contains code to merge FTS3 b-tree segments. Some
103848** of the sub-routines used to merge segments are also used by the query
103849** code in fts3.c.
103850*/
103851
103852#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
103853
103854
103855typedef struct PendingList PendingList;
103856typedef struct SegmentNode SegmentNode;
103857typedef struct SegmentWriter SegmentWriter;
103858
103859/*
103860** Data structure used while accumulating terms in the pending-terms hash
103861** table. The hash table entry maps from term (a string) to a malloc'd
103862** instance of this structure.
103863*/
103864struct PendingList {
103865  int nData;
103866  char *aData;
103867  int nSpace;
103868  sqlite3_int64 iLastDocid;
103869  sqlite3_int64 iLastCol;
103870  sqlite3_int64 iLastPos;
103871};
103872
103873/*
103874** An instance of this structure is used to iterate through the terms on
103875** a contiguous set of segment b-tree leaf nodes. Although the details of
103876** this structure are only manipulated by code in this file, opaque handles
103877** of type Fts3SegReader* are also used by code in fts3.c to iterate through
103878** terms when querying the full-text index. See functions:
103879**
103880**   sqlite3Fts3SegReaderNew()
103881**   sqlite3Fts3SegReaderFree()
103882**   sqlite3Fts3SegReaderIterate()
103883**
103884** Methods used to manipulate Fts3SegReader structures:
103885**
103886**   fts3SegReaderNext()
103887**   fts3SegReaderFirstDocid()
103888**   fts3SegReaderNextDocid()
103889*/
103890struct Fts3SegReader {
103891  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
103892  sqlite3_int64 iStartBlock;
103893  sqlite3_int64 iEndBlock;
103894  sqlite3_stmt *pStmt;            /* SQL Statement to access leaf nodes */
103895  char *aNode;                    /* Pointer to node data (or NULL) */
103896  int nNode;                      /* Size of buffer at aNode (or 0) */
103897  int nTermAlloc;                 /* Allocated size of zTerm buffer */
103898  Fts3HashElem **ppNextElem;
103899
103900  /* Variables set by fts3SegReaderNext(). These may be read directly
103901  ** by the caller. They are valid from the time SegmentReaderNew() returns
103902  ** until SegmentReaderNext() returns something other than SQLITE_OK
103903  ** (i.e. SQLITE_DONE).
103904  */
103905  int nTerm;                      /* Number of bytes in current term */
103906  char *zTerm;                    /* Pointer to current term */
103907  char *aDoclist;                 /* Pointer to doclist of current entry */
103908  int nDoclist;                   /* Size of doclist in current entry */
103909
103910  /* The following variables are used to iterate through the current doclist */
103911  char *pOffsetList;
103912  sqlite3_int64 iDocid;
103913};
103914
103915#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
103916
103917/*
103918** An instance of this structure is used to create a segment b-tree in the
103919** database. The internal details of this type are only accessed by the
103920** following functions:
103921**
103922**   fts3SegWriterAdd()
103923**   fts3SegWriterFlush()
103924**   fts3SegWriterFree()
103925*/
103926struct SegmentWriter {
103927  SegmentNode *pTree;             /* Pointer to interior tree structure */
103928  sqlite3_int64 iFirst;           /* First slot in %_segments written */
103929  sqlite3_int64 iFree;            /* Next free slot in %_segments */
103930  char *zTerm;                    /* Pointer to previous term buffer */
103931  int nTerm;                      /* Number of bytes in zTerm */
103932  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
103933  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
103934  int nSize;                      /* Size of allocation at aData */
103935  int nData;                      /* Bytes of data in aData */
103936  char *aData;                    /* Pointer to block from malloc() */
103937};
103938
103939/*
103940** Type SegmentNode is used by the following three functions to create
103941** the interior part of the segment b+-tree structures (everything except
103942** the leaf nodes). These functions and type are only ever used by code
103943** within the fts3SegWriterXXX() family of functions described above.
103944**
103945**   fts3NodeAddTerm()
103946**   fts3NodeWrite()
103947**   fts3NodeFree()
103948*/
103949struct SegmentNode {
103950  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
103951  SegmentNode *pRight;            /* Pointer to right-sibling */
103952  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
103953  int nEntry;                     /* Number of terms written to node so far */
103954  char *zTerm;                    /* Pointer to previous term buffer */
103955  int nTerm;                      /* Number of bytes in zTerm */
103956  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
103957  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
103958  int nData;                      /* Bytes of valid data so far */
103959  char *aData;                    /* Node data */
103960};
103961
103962/*
103963** Valid values for the second argument to fts3SqlStmt().
103964*/
103965#define SQL_DELETE_CONTENT             0
103966#define SQL_IS_EMPTY                   1
103967#define SQL_DELETE_ALL_CONTENT         2
103968#define SQL_DELETE_ALL_SEGMENTS        3
103969#define SQL_DELETE_ALL_SEGDIR          4
103970#define SQL_SELECT_CONTENT_BY_ROWID    5
103971#define SQL_NEXT_SEGMENT_INDEX         6
103972#define SQL_INSERT_SEGMENTS            7
103973#define SQL_NEXT_SEGMENTS_ID           8
103974#define SQL_INSERT_SEGDIR              9
103975#define SQL_SELECT_LEVEL              10
103976#define SQL_SELECT_ALL_LEVEL          11
103977#define SQL_SELECT_LEVEL_COUNT        12
103978#define SQL_SELECT_SEGDIR_COUNT_MAX   13
103979#define SQL_DELETE_SEGDIR_BY_LEVEL    14
103980#define SQL_DELETE_SEGMENTS_RANGE     15
103981#define SQL_CONTENT_INSERT            16
103982#define SQL_GET_BLOCK                 17
103983
103984/*
103985** This function is used to obtain an SQLite prepared statement handle
103986** for the statement identified by the second argument. If successful,
103987** *pp is set to the requested statement handle and SQLITE_OK returned.
103988** Otherwise, an SQLite error code is returned and *pp is set to 0.
103989**
103990** If argument apVal is not NULL, then it must point to an array with
103991** at least as many entries as the requested statement has bound
103992** parameters. The values are bound to the statements parameters before
103993** returning.
103994*/
103995static int fts3SqlStmt(
103996  Fts3Table *p,                   /* Virtual table handle */
103997  int eStmt,                      /* One of the SQL_XXX constants above */
103998  sqlite3_stmt **pp,              /* OUT: Statement handle */
103999  sqlite3_value **apVal           /* Values to bind to statement */
104000){
104001  const char *azSql[] = {
104002/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
104003/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
104004/* 2  */  "DELETE FROM %Q.'%q_content'",
104005/* 3  */  "DELETE FROM %Q.'%q_segments'",
104006/* 4  */  "DELETE FROM %Q.'%q_segdir'",
104007/* 5  */  "SELECT * FROM %Q.'%q_content' WHERE rowid=?",
104008/* 6  */  "SELECT coalesce(max(idx)+1, 0) FROM %Q.'%q_segdir' WHERE level=?",
104009/* 7  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
104010/* 8  */  "SELECT coalesce(max(blockid)+1, 1) FROM %Q.'%q_segments'",
104011/* 9  */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
104012
104013          /* Return segments in order from oldest to newest.*/
104014/* 10 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
104015            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
104016/* 11 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
104017            "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
104018
104019/* 12 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
104020/* 13 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
104021
104022/* 14 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
104023/* 15 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
104024/* 16 */  "INSERT INTO %Q.'%q_content' VALUES(%z)",
104025/* 17 */  "SELECT block FROM %Q.'%q_segments' WHERE blockid = ?",
104026  };
104027  int rc = SQLITE_OK;
104028  sqlite3_stmt *pStmt;
104029
104030  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
104031  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
104032
104033  pStmt = p->aStmt[eStmt];
104034  if( !pStmt ){
104035    char *zSql;
104036    if( eStmt==SQL_CONTENT_INSERT ){
104037      int i;                      /* Iterator variable */
104038      char *zVarlist;             /* The "?, ?, ..." string */
104039      zVarlist = (char *)sqlite3_malloc(2*p->nColumn+2);
104040      if( !zVarlist ){
104041        *pp = 0;
104042        return SQLITE_NOMEM;
104043      }
104044      zVarlist[0] = '?';
104045      zVarlist[p->nColumn*2+1] = '\0';
104046      for(i=1; i<=p->nColumn; i++){
104047        zVarlist[i*2-1] = ',';
104048        zVarlist[i*2] = '?';
104049      }
104050      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, zVarlist);
104051    }else{
104052      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
104053    }
104054    if( !zSql ){
104055      rc = SQLITE_NOMEM;
104056    }else{
104057      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
104058      sqlite3_free(zSql);
104059      assert( rc==SQLITE_OK || pStmt==0 );
104060      p->aStmt[eStmt] = pStmt;
104061    }
104062  }
104063  if( apVal ){
104064    int i;
104065    int nParam = sqlite3_bind_parameter_count(pStmt);
104066    for(i=0; rc==SQLITE_OK && i<nParam; i++){
104067      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
104068    }
104069  }
104070  *pp = pStmt;
104071  return rc;
104072}
104073
104074/*
104075** Similar to fts3SqlStmt(). Except, after binding the parameters in
104076** array apVal[] to the SQL statement identified by eStmt, the statement
104077** is executed.
104078**
104079** Returns SQLITE_OK if the statement is successfully executed, or an
104080** SQLite error code otherwise.
104081*/
104082static int fts3SqlExec(Fts3Table *p, int eStmt, sqlite3_value **apVal){
104083  sqlite3_stmt *pStmt;
104084  int rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
104085  if( rc==SQLITE_OK ){
104086    sqlite3_step(pStmt);
104087    rc = sqlite3_reset(pStmt);
104088  }
104089  return rc;
104090}
104091
104092
104093/*
104094** Read a single block from the %_segments table. If the specified block
104095** does not exist, return SQLITE_CORRUPT. If some other error (malloc, IO
104096** etc.) occurs, return the appropriate SQLite error code.
104097**
104098** Otherwise, if successful, set *pzBlock to point to a buffer containing
104099** the block read from the database, and *pnBlock to the size of the read
104100** block in bytes.
104101**
104102** WARNING: The returned buffer is only valid until the next call to
104103** sqlite3Fts3ReadBlock().
104104*/
104105SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
104106  Fts3Table *p,
104107  sqlite3_int64 iBlock,
104108  char const **pzBlock,
104109  int *pnBlock
104110){
104111  sqlite3_stmt *pStmt;
104112  int rc = fts3SqlStmt(p, SQL_GET_BLOCK, &pStmt, 0);
104113  if( rc!=SQLITE_OK ) return rc;
104114  sqlite3_reset(pStmt);
104115
104116  if( pzBlock ){
104117    sqlite3_bind_int64(pStmt, 1, iBlock);
104118    rc = sqlite3_step(pStmt);
104119    if( rc!=SQLITE_ROW ){
104120      return (rc==SQLITE_DONE ? SQLITE_CORRUPT : rc);
104121    }
104122
104123    *pnBlock = sqlite3_column_bytes(pStmt, 0);
104124    *pzBlock = (char *)sqlite3_column_blob(pStmt, 0);
104125    if( sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
104126      return SQLITE_CORRUPT;
104127    }
104128  }
104129  return SQLITE_OK;
104130}
104131
104132/*
104133** Set *ppStmt to a statement handle that may be used to iterate through
104134** all rows in the %_segdir table, from oldest to newest. If successful,
104135** return SQLITE_OK. If an error occurs while preparing the statement,
104136** return an SQLite error code.
104137**
104138** There is only ever one instance of this SQL statement compiled for
104139** each FTS3 table.
104140**
104141** The statement returns the following columns from the %_segdir table:
104142**
104143**   0: idx
104144**   1: start_block
104145**   2: leaves_end_block
104146**   3: end_block
104147**   4: root
104148*/
104149SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, sqlite3_stmt **ppStmt){
104150  return fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, ppStmt, 0);
104151}
104152
104153
104154/*
104155** Append a single varint to a PendingList buffer. SQLITE_OK is returned
104156** if successful, or an SQLite error code otherwise.
104157**
104158** This function also serves to allocate the PendingList structure itself.
104159** For example, to create a new PendingList structure containing two
104160** varints:
104161**
104162**   PendingList *p = 0;
104163**   fts3PendingListAppendVarint(&p, 1);
104164**   fts3PendingListAppendVarint(&p, 2);
104165*/
104166static int fts3PendingListAppendVarint(
104167  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
104168  sqlite3_int64 i                 /* Value to append to data */
104169){
104170  PendingList *p = *pp;
104171
104172  /* Allocate or grow the PendingList as required. */
104173  if( !p ){
104174    p = sqlite3_malloc(sizeof(*p) + 100);
104175    if( !p ){
104176      return SQLITE_NOMEM;
104177    }
104178    p->nSpace = 100;
104179    p->aData = (char *)&p[1];
104180    p->nData = 0;
104181  }
104182  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
104183    int nNew = p->nSpace * 2;
104184    p = sqlite3_realloc(p, sizeof(*p) + nNew);
104185    if( !p ){
104186      sqlite3_free(*pp);
104187      *pp = 0;
104188      return SQLITE_NOMEM;
104189    }
104190    p->nSpace = nNew;
104191    p->aData = (char *)&p[1];
104192  }
104193
104194  /* Append the new serialized varint to the end of the list. */
104195  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
104196  p->aData[p->nData] = '\0';
104197  *pp = p;
104198  return SQLITE_OK;
104199}
104200
104201/*
104202** Add a docid/column/position entry to a PendingList structure. Non-zero
104203** is returned if the structure is sqlite3_realloced as part of adding
104204** the entry. Otherwise, zero.
104205**
104206** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
104207** Zero is always returned in this case. Otherwise, if no OOM error occurs,
104208** it is set to SQLITE_OK.
104209*/
104210static int fts3PendingListAppend(
104211  PendingList **pp,               /* IN/OUT: PendingList structure */
104212  sqlite3_int64 iDocid,           /* Docid for entry to add */
104213  sqlite3_int64 iCol,             /* Column for entry to add */
104214  sqlite3_int64 iPos,             /* Position of term for entry to add */
104215  int *pRc                        /* OUT: Return code */
104216){
104217  PendingList *p = *pp;
104218  int rc = SQLITE_OK;
104219
104220  assert( !p || p->iLastDocid<=iDocid );
104221
104222  if( !p || p->iLastDocid!=iDocid ){
104223    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
104224    if( p ){
104225      assert( p->nData<p->nSpace );
104226      assert( p->aData[p->nData]==0 );
104227      p->nData++;
104228    }
104229    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
104230      goto pendinglistappend_out;
104231    }
104232    p->iLastCol = -1;
104233    p->iLastPos = 0;
104234    p->iLastDocid = iDocid;
104235  }
104236  if( iCol>0 && p->iLastCol!=iCol ){
104237    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
104238     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
104239    ){
104240      goto pendinglistappend_out;
104241    }
104242    p->iLastCol = iCol;
104243    p->iLastPos = 0;
104244  }
104245  if( iCol>=0 ){
104246    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
104247    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
104248    if( rc==SQLITE_OK ){
104249      p->iLastPos = iPos;
104250    }
104251  }
104252
104253 pendinglistappend_out:
104254  *pRc = rc;
104255  if( p!=*pp ){
104256    *pp = p;
104257    return 1;
104258  }
104259  return 0;
104260}
104261
104262/*
104263** Tokenize the nul-terminated string zText and add all tokens to the
104264** pending-terms hash-table. The docid used is that currently stored in
104265** p->iPrevDocid, and the column is specified by argument iCol.
104266**
104267** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
104268*/
104269static int fts3PendingTermsAdd(Fts3Table *p, const char *zText, int iCol){
104270  int rc;
104271  int iStart;
104272  int iEnd;
104273  int iPos;
104274
104275  char const *zToken;
104276  int nToken;
104277
104278  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
104279  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
104280  sqlite3_tokenizer_cursor *pCsr;
104281  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
104282      const char**,int*,int*,int*,int*);
104283
104284  assert( pTokenizer && pModule );
104285
104286  rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
104287  if( rc!=SQLITE_OK ){
104288    return rc;
104289  }
104290  pCsr->pTokenizer = pTokenizer;
104291
104292  xNext = pModule->xNext;
104293  while( SQLITE_OK==rc
104294      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
104295  ){
104296    PendingList *pList;
104297
104298    /* Positions cannot be negative; we use -1 as a terminator internally.
104299    ** Tokens must have a non-zero length.
104300    */
104301    if( iPos<0 || !zToken || nToken<=0 ){
104302      rc = SQLITE_ERROR;
104303      break;
104304    }
104305
104306    pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
104307    if( pList ){
104308      p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
104309    }
104310    if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
104311      if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
104312        /* Malloc failed while inserting the new entry. This can only
104313        ** happen if there was no previous entry for this token.
104314        */
104315        assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
104316        sqlite3_free(pList);
104317        rc = SQLITE_NOMEM;
104318      }
104319    }
104320    if( rc==SQLITE_OK ){
104321      p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
104322    }
104323  }
104324
104325  pModule->xClose(pCsr);
104326  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
104327}
104328
104329/*
104330** Calling this function indicates that subsequent calls to
104331** fts3PendingTermsAdd() are to add term/position-list pairs for the
104332** contents of the document with docid iDocid.
104333*/
104334static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
104335  /* TODO(shess) Explore whether partially flushing the buffer on
104336  ** forced-flush would provide better performance.  I suspect that if
104337  ** we ordered the doclists by size and flushed the largest until the
104338  ** buffer was half empty, that would let the less frequent terms
104339  ** generate longer doclists.
104340  */
104341  if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
104342    int rc = sqlite3Fts3PendingTermsFlush(p);
104343    if( rc!=SQLITE_OK ) return rc;
104344  }
104345  p->iPrevDocid = iDocid;
104346  return SQLITE_OK;
104347}
104348
104349SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
104350  Fts3HashElem *pElem;
104351  for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
104352    sqlite3_free(fts3HashData(pElem));
104353  }
104354  fts3HashClear(&p->pendingTerms);
104355  p->nPendingData = 0;
104356}
104357
104358/*
104359** This function is called by the xUpdate() method as part of an INSERT
104360** operation. It adds entries for each term in the new record to the
104361** pendingTerms hash table.
104362**
104363** Argument apVal is the same as the similarly named argument passed to
104364** fts3InsertData(). Parameter iDocid is the docid of the new row.
104365*/
104366static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal){
104367  int i;                          /* Iterator variable */
104368  for(i=2; i<p->nColumn+2; i++){
104369    const char *zText = (const char *)sqlite3_value_text(apVal[i]);
104370    if( zText ){
104371      int rc = fts3PendingTermsAdd(p, zText, i-2);
104372      if( rc!=SQLITE_OK ){
104373        return rc;
104374      }
104375    }
104376  }
104377  return SQLITE_OK;
104378}
104379
104380/*
104381** This function is called by the xUpdate() method for an INSERT operation.
104382** The apVal parameter is passed a copy of the apVal argument passed by
104383** SQLite to the xUpdate() method. i.e:
104384**
104385**   apVal[0]                Not used for INSERT.
104386**   apVal[1]                rowid
104387**   apVal[2]                Left-most user-defined column
104388**   ...
104389**   apVal[p->nColumn+1]     Right-most user-defined column
104390**   apVal[p->nColumn+2]     Hidden column with same name as table
104391**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
104392*/
104393static int fts3InsertData(
104394  Fts3Table *p,                   /* Full-text table */
104395  sqlite3_value **apVal,          /* Array of values to insert */
104396  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
104397){
104398  int rc;                         /* Return code */
104399  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
104400
104401  /* Locate the statement handle used to insert data into the %_content
104402  ** table. The SQL for this statement is:
104403  **
104404  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
104405  **
104406  ** The statement features N '?' variables, where N is the number of user
104407  ** defined columns in the FTS3 table, plus one for the docid field.
104408  */
104409  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
104410  if( rc!=SQLITE_OK ){
104411    return rc;
104412  }
104413
104414  /* There is a quirk here. The users INSERT statement may have specified
104415  ** a value for the "rowid" field, for the "docid" field, or for both.
104416  ** Which is a problem, since "rowid" and "docid" are aliases for the
104417  ** same value. For example:
104418  **
104419  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
104420  **
104421  ** In FTS3, this is an error. It is an error to specify non-NULL values
104422  ** for both docid and some other rowid alias.
104423  */
104424  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
104425    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
104426     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
104427    ){
104428      /* A rowid/docid conflict. */
104429      return SQLITE_ERROR;
104430    }
104431    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
104432    if( rc!=SQLITE_OK ) return rc;
104433  }
104434
104435  /* Execute the statement to insert the record. Set *piDocid to the
104436  ** new docid value.
104437  */
104438  sqlite3_step(pContentInsert);
104439  rc = sqlite3_reset(pContentInsert);
104440
104441  *piDocid = sqlite3_last_insert_rowid(p->db);
104442  return rc;
104443}
104444
104445
104446
104447/*
104448** Remove all data from the FTS3 table. Clear the hash table containing
104449** pending terms.
104450*/
104451static int fts3DeleteAll(Fts3Table *p){
104452  int rc;                         /* Return code */
104453
104454  /* Discard the contents of the pending-terms hash table. */
104455  sqlite3Fts3PendingTermsClear(p);
104456
104457  /* Delete everything from the %_content, %_segments and %_segdir tables. */
104458  rc = fts3SqlExec(p, SQL_DELETE_ALL_CONTENT, 0);
104459  if( rc==SQLITE_OK ){
104460    rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGMENTS, 0);
104461  }
104462  if( rc==SQLITE_OK ){
104463    rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGDIR, 0);
104464  }
104465  return rc;
104466}
104467
104468/*
104469** The first element in the apVal[] array is assumed to contain the docid
104470** (an integer) of a row about to be deleted. Remove all terms from the
104471** full-text index.
104472*/
104473static int fts3DeleteTerms(Fts3Table *p, sqlite3_value **apVal){
104474  int rc;
104475  sqlite3_stmt *pSelect;
104476
104477  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
104478  if( rc==SQLITE_OK ){
104479    if( SQLITE_ROW==sqlite3_step(pSelect) ){
104480      int i;
104481      for(i=1; i<=p->nColumn; i++){
104482        const char *zText = (const char *)sqlite3_column_text(pSelect, i);
104483        rc = fts3PendingTermsAdd(p, zText, -1);
104484        if( rc!=SQLITE_OK ){
104485          sqlite3_reset(pSelect);
104486          return rc;
104487        }
104488      }
104489    }
104490    rc = sqlite3_reset(pSelect);
104491  }else{
104492    sqlite3_reset(pSelect);
104493  }
104494  return rc;
104495}
104496
104497/*
104498** Forward declaration to account for the circular dependency between
104499** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
104500*/
104501static int fts3SegmentMerge(Fts3Table *, int);
104502
104503/*
104504** This function allocates a new level iLevel index in the segdir table.
104505** Usually, indexes are allocated within a level sequentially starting
104506** with 0, so the allocated index is one greater than the value returned
104507** by:
104508**
104509**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
104510**
104511** However, if there are already FTS3_MERGE_COUNT indexes at the requested
104512** level, they are merged into a single level (iLevel+1) segment and the
104513** allocated index is 0.
104514**
104515** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
104516** returned. Otherwise, an SQLite error code is returned.
104517*/
104518static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
104519  int rc;                         /* Return Code */
104520  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
104521  int iNext = 0;                  /* Result of query pNextIdx */
104522
104523  /* Set variable iNext to the next available segdir index at level iLevel. */
104524  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
104525  if( rc==SQLITE_OK ){
104526    sqlite3_bind_int(pNextIdx, 1, iLevel);
104527    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
104528      iNext = sqlite3_column_int(pNextIdx, 0);
104529    }
104530    rc = sqlite3_reset(pNextIdx);
104531  }
104532
104533  if( rc==SQLITE_OK ){
104534    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
104535    ** full, merge all segments in level iLevel into a single iLevel+1
104536    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
104537    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
104538    */
104539    if( iNext>=FTS3_MERGE_COUNT ){
104540      rc = fts3SegmentMerge(p, iLevel);
104541      *piIdx = 0;
104542    }else{
104543      *piIdx = iNext;
104544    }
104545  }
104546
104547  return rc;
104548}
104549
104550/*
104551** Move the iterator passed as the first argument to the next term in the
104552** segment. If successful, SQLITE_OK is returned. If there is no next term,
104553** SQLITE_DONE. Otherwise, an SQLite error code.
104554*/
104555static int fts3SegReaderNext(Fts3SegReader *pReader){
104556  char *pNext;                    /* Cursor variable */
104557  int nPrefix;                    /* Number of bytes in term prefix */
104558  int nSuffix;                    /* Number of bytes in term suffix */
104559
104560  if( !pReader->aDoclist ){
104561    pNext = pReader->aNode;
104562  }else{
104563    pNext = &pReader->aDoclist[pReader->nDoclist];
104564  }
104565
104566  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
104567    int rc;
104568    if( fts3SegReaderIsPending(pReader) ){
104569      Fts3HashElem *pElem = *(pReader->ppNextElem);
104570      if( pElem==0 ){
104571        pReader->aNode = 0;
104572      }else{
104573        PendingList *pList = (PendingList *)fts3HashData(pElem);
104574        pReader->zTerm = (char *)fts3HashKey(pElem);
104575        pReader->nTerm = fts3HashKeysize(pElem);
104576        pReader->nNode = pReader->nDoclist = pList->nData + 1;
104577        pReader->aNode = pReader->aDoclist = pList->aData;
104578        pReader->ppNextElem++;
104579        assert( pReader->aNode );
104580      }
104581      return SQLITE_OK;
104582    }
104583    if( !pReader->pStmt ){
104584      pReader->aNode = 0;
104585      return SQLITE_OK;
104586    }
104587    rc = sqlite3_step(pReader->pStmt);
104588    if( rc!=SQLITE_ROW ){
104589      pReader->aNode = 0;
104590      return (rc==SQLITE_DONE ? SQLITE_OK : rc);
104591    }
104592    pReader->nNode = sqlite3_column_bytes(pReader->pStmt, 0);
104593    pReader->aNode = (char *)sqlite3_column_blob(pReader->pStmt, 0);
104594    pNext = pReader->aNode;
104595  }
104596
104597  pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
104598  pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
104599
104600  if( nPrefix+nSuffix>pReader->nTermAlloc ){
104601    int nNew = (nPrefix+nSuffix)*2;
104602    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
104603    if( !zNew ){
104604      return SQLITE_NOMEM;
104605    }
104606    pReader->zTerm = zNew;
104607    pReader->nTermAlloc = nNew;
104608  }
104609  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
104610  pReader->nTerm = nPrefix+nSuffix;
104611  pNext += nSuffix;
104612  pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
104613  assert( pNext<&pReader->aNode[pReader->nNode] );
104614  pReader->aDoclist = pNext;
104615  pReader->pOffsetList = 0;
104616  return SQLITE_OK;
104617}
104618
104619/*
104620** Set the SegReader to point to the first docid in the doclist associated
104621** with the current term.
104622*/
104623static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
104624  int n;
104625  assert( pReader->aDoclist );
104626  assert( !pReader->pOffsetList );
104627  n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
104628  pReader->pOffsetList = &pReader->aDoclist[n];
104629}
104630
104631/*
104632** Advance the SegReader to point to the next docid in the doclist
104633** associated with the current term.
104634**
104635** If arguments ppOffsetList and pnOffsetList are not NULL, then
104636** *ppOffsetList is set to point to the first column-offset list
104637** in the doclist entry (i.e. immediately past the docid varint).
104638** *pnOffsetList is set to the length of the set of column-offset
104639** lists, not including the nul-terminator byte. For example:
104640*/
104641static void fts3SegReaderNextDocid(
104642  Fts3SegReader *pReader,
104643  char **ppOffsetList,
104644  int *pnOffsetList
104645){
104646  char *p = pReader->pOffsetList;
104647  char c = 0;
104648
104649  /* Pointer p currently points at the first byte of an offset list. The
104650  ** following two lines advance it to point one byte past the end of
104651  ** the same offset list.
104652  */
104653  while( *p | c ) c = *p++ & 0x80;
104654  p++;
104655
104656  /* If required, populate the output variables with a pointer to and the
104657  ** size of the previous offset-list.
104658  */
104659  if( ppOffsetList ){
104660    *ppOffsetList = pReader->pOffsetList;
104661    *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
104662  }
104663
104664  /* If there are no more entries in the doclist, set pOffsetList to
104665  ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
104666  ** Fts3SegReader.pOffsetList to point to the next offset list before
104667  ** returning.
104668  */
104669  if( p>=&pReader->aDoclist[pReader->nDoclist] ){
104670    pReader->pOffsetList = 0;
104671  }else{
104672    sqlite3_int64 iDelta;
104673    pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
104674    pReader->iDocid += iDelta;
104675  }
104676}
104677
104678/*
104679** Free all allocations associated with the iterator passed as the
104680** second argument.
104681*/
104682SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *p, Fts3SegReader *pReader){
104683  if( pReader ){
104684    if( pReader->pStmt ){
104685      /* Move the leaf-range SELECT statement to the aLeavesStmt[] array,
104686      ** so that it can be reused when required by another query.
104687      */
104688      assert( p->nLeavesStmt<p->nLeavesTotal );
104689      sqlite3_reset(pReader->pStmt);
104690      p->aLeavesStmt[p->nLeavesStmt++] = pReader->pStmt;
104691    }
104692    if( !fts3SegReaderIsPending(pReader) ){
104693      sqlite3_free(pReader->zTerm);
104694    }
104695    sqlite3_free(pReader);
104696  }
104697}
104698
104699/*
104700** Allocate a new SegReader object.
104701*/
104702SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
104703  Fts3Table *p,                   /* Virtual table handle */
104704  int iAge,                       /* Segment "age". */
104705  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
104706  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
104707  sqlite3_int64 iEndBlock,        /* Final block of segment */
104708  const char *zRoot,              /* Buffer containing root node */
104709  int nRoot,                      /* Size of buffer containing root node */
104710  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
104711){
104712  int rc = SQLITE_OK;             /* Return code */
104713  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
104714  int nExtra = 0;                 /* Bytes to allocate segment root node */
104715
104716  if( iStartLeaf==0 ){
104717    nExtra = nRoot;
104718  }
104719
104720  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
104721  if( !pReader ){
104722    return SQLITE_NOMEM;
104723  }
104724  memset(pReader, 0, sizeof(Fts3SegReader));
104725  pReader->iStartBlock = iStartLeaf;
104726  pReader->iIdx = iAge;
104727  pReader->iEndBlock = iEndBlock;
104728
104729  if( nExtra ){
104730    /* The entire segment is stored in the root node. */
104731    pReader->aNode = (char *)&pReader[1];
104732    pReader->nNode = nRoot;
104733    memcpy(pReader->aNode, zRoot, nRoot);
104734  }else{
104735    /* If the text of the SQL statement to iterate through a contiguous
104736    ** set of entries in the %_segments table has not yet been composed,
104737    ** compose it now.
104738    */
104739    if( !p->zSelectLeaves ){
104740      p->zSelectLeaves = sqlite3_mprintf(
104741          "SELECT block FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ? "
104742          "ORDER BY blockid", p->zDb, p->zName
104743      );
104744      if( !p->zSelectLeaves ){
104745        rc = SQLITE_NOMEM;
104746        goto finished;
104747      }
104748    }
104749
104750    /* If there are no free statements in the aLeavesStmt[] array, prepare
104751    ** a new statement now. Otherwise, reuse a prepared statement from
104752    ** aLeavesStmt[].
104753    */
104754    if( p->nLeavesStmt==0 ){
104755      if( p->nLeavesTotal==p->nLeavesAlloc ){
104756        int nNew = p->nLeavesAlloc + 16;
104757        sqlite3_stmt **aNew = (sqlite3_stmt **)sqlite3_realloc(
104758            p->aLeavesStmt, nNew*sizeof(sqlite3_stmt *)
104759        );
104760        if( !aNew ){
104761          rc = SQLITE_NOMEM;
104762          goto finished;
104763        }
104764        p->nLeavesAlloc = nNew;
104765        p->aLeavesStmt = aNew;
104766      }
104767      rc = sqlite3_prepare_v2(p->db, p->zSelectLeaves, -1, &pReader->pStmt, 0);
104768      if( rc!=SQLITE_OK ){
104769        goto finished;
104770      }
104771      p->nLeavesTotal++;
104772    }else{
104773      pReader->pStmt = p->aLeavesStmt[--p->nLeavesStmt];
104774    }
104775
104776    /* Bind the start and end leaf blockids to the prepared SQL statement. */
104777    sqlite3_bind_int64(pReader->pStmt, 1, iStartLeaf);
104778    sqlite3_bind_int64(pReader->pStmt, 2, iEndLeaf);
104779  }
104780  rc = fts3SegReaderNext(pReader);
104781
104782 finished:
104783  if( rc==SQLITE_OK ){
104784    *ppReader = pReader;
104785  }else{
104786    sqlite3Fts3SegReaderFree(p, pReader);
104787  }
104788  return rc;
104789}
104790
104791/*
104792** This is a comparison function used as a qsort() callback when sorting
104793** an array of pending terms by term. This occurs as part of flushing
104794** the contents of the pending-terms hash table to the database.
104795*/
104796static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
104797  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
104798  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
104799  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
104800  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
104801
104802  int n = (n1<n2 ? n1 : n2);
104803  int c = memcmp(z1, z2, n);
104804  if( c==0 ){
104805    c = n1 - n2;
104806  }
104807  return c;
104808}
104809
104810/*
104811** This function is used to allocate an Fts3SegReader that iterates through
104812** a subset of the terms stored in the Fts3Table.pendingTerms array.
104813*/
104814SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
104815  Fts3Table *p,                   /* Virtual table handle */
104816  const char *zTerm,              /* Term to search for */
104817  int nTerm,                      /* Size of buffer zTerm */
104818  int isPrefix,                   /* True for a term-prefix query */
104819  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
104820){
104821  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
104822  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
104823  int nElem = 0;                  /* Size of array at aElem */
104824  int rc = SQLITE_OK;             /* Return Code */
104825
104826  if( isPrefix ){
104827    int nAlloc = 0;               /* Size of allocated array at aElem */
104828    Fts3HashElem *pE = 0;         /* Iterator variable */
104829
104830    for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
104831      char *zKey = (char *)fts3HashKey(pE);
104832      int nKey = fts3HashKeysize(pE);
104833      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
104834        if( nElem==nAlloc ){
104835          Fts3HashElem **aElem2;
104836          nAlloc += 16;
104837          aElem2 = (Fts3HashElem **)sqlite3_realloc(
104838              aElem, nAlloc*sizeof(Fts3HashElem *)
104839          );
104840          if( !aElem2 ){
104841            rc = SQLITE_NOMEM;
104842            nElem = 0;
104843            break;
104844          }
104845          aElem = aElem2;
104846        }
104847        aElem[nElem++] = pE;
104848      }
104849    }
104850
104851    /* If more than one term matches the prefix, sort the Fts3HashElem
104852    ** objects in term order using qsort(). This uses the same comparison
104853    ** callback as is used when flushing terms to disk.
104854    */
104855    if( nElem>1 ){
104856      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
104857    }
104858
104859  }else{
104860    Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
104861    if( pE ){
104862      aElem = &pE;
104863      nElem = 1;
104864    }
104865  }
104866
104867  if( nElem>0 ){
104868    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
104869    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
104870    if( !pReader ){
104871      rc = SQLITE_NOMEM;
104872    }else{
104873      memset(pReader, 0, nByte);
104874      pReader->iIdx = 0x7FFFFFFF;
104875      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
104876      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
104877      fts3SegReaderNext(pReader);
104878    }
104879  }
104880
104881  if( isPrefix ){
104882    sqlite3_free(aElem);
104883  }
104884  *ppReader = pReader;
104885  return rc;
104886}
104887
104888
104889/*
104890** The second argument to this function is expected to be a statement of
104891** the form:
104892**
104893**   SELECT
104894**     idx,                  -- col 0
104895**     start_block,          -- col 1
104896**     leaves_end_block,     -- col 2
104897**     end_block,            -- col 3
104898**     root                  -- col 4
104899**   FROM %_segdir ...
104900**
104901** This function allocates and initializes a Fts3SegReader structure to
104902** iterate through the terms stored in the segment identified by the
104903** current row that pStmt is pointing to.
104904**
104905** If successful, the Fts3SegReader is left pointing to the first term
104906** in the segment and SQLITE_OK is returned. Otherwise, an SQLite error
104907** code is returned.
104908*/
104909static int fts3SegReaderNew(
104910  Fts3Table *p,                   /* Virtual table handle */
104911  sqlite3_stmt *pStmt,            /* See above */
104912  int iAge,                       /* Segment "age". */
104913  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
104914){
104915  return sqlite3Fts3SegReaderNew(p, iAge,
104916      sqlite3_column_int64(pStmt, 1),
104917      sqlite3_column_int64(pStmt, 2),
104918      sqlite3_column_int64(pStmt, 3),
104919      sqlite3_column_blob(pStmt, 4),
104920      sqlite3_column_bytes(pStmt, 4),
104921      ppReader
104922  );
104923}
104924
104925/*
104926** Compare the entries pointed to by two Fts3SegReader structures.
104927** Comparison is as follows:
104928**
104929**   1) EOF is greater than not EOF.
104930**
104931**   2) The current terms (if any) are compared using memcmp(). If one
104932**      term is a prefix of another, the longer term is considered the
104933**      larger.
104934**
104935**   3) By segment age. An older segment is considered larger.
104936*/
104937static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
104938  int rc;
104939  if( pLhs->aNode && pRhs->aNode ){
104940    int rc2 = pLhs->nTerm - pRhs->nTerm;
104941    if( rc2<0 ){
104942      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
104943    }else{
104944      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
104945    }
104946    if( rc==0 ){
104947      rc = rc2;
104948    }
104949  }else{
104950    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
104951  }
104952  if( rc==0 ){
104953    rc = pRhs->iIdx - pLhs->iIdx;
104954  }
104955  assert( rc!=0 );
104956  return rc;
104957}
104958
104959/*
104960** A different comparison function for SegReader structures. In this
104961** version, it is assumed that each SegReader points to an entry in
104962** a doclist for identical terms. Comparison is made as follows:
104963**
104964**   1) EOF (end of doclist in this case) is greater than not EOF.
104965**
104966**   2) By current docid.
104967**
104968**   3) By segment age. An older segment is considered larger.
104969*/
104970static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
104971  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
104972  if( rc==0 ){
104973    if( pLhs->iDocid==pRhs->iDocid ){
104974      rc = pRhs->iIdx - pLhs->iIdx;
104975    }else{
104976      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
104977    }
104978  }
104979  assert( pLhs->aNode && pRhs->aNode );
104980  return rc;
104981}
104982
104983/*
104984** Compare the term that the Fts3SegReader object passed as the first argument
104985** points to with the term specified by arguments zTerm and nTerm.
104986**
104987** If the pSeg iterator is already at EOF, return 0. Otherwise, return
104988** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
104989** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
104990*/
104991static int fts3SegReaderTermCmp(
104992  Fts3SegReader *pSeg,            /* Segment reader object */
104993  const char *zTerm,              /* Term to compare to */
104994  int nTerm                       /* Size of term zTerm in bytes */
104995){
104996  int res = 0;
104997  if( pSeg->aNode ){
104998    if( pSeg->nTerm>nTerm ){
104999      res = memcmp(pSeg->zTerm, zTerm, nTerm);
105000    }else{
105001      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
105002    }
105003    if( res==0 ){
105004      res = pSeg->nTerm-nTerm;
105005    }
105006  }
105007  return res;
105008}
105009
105010/*
105011** Argument apSegment is an array of nSegment elements. It is known that
105012** the final (nSegment-nSuspect) members are already in sorted order
105013** (according to the comparison function provided). This function shuffles
105014** the array around until all entries are in sorted order.
105015*/
105016static void fts3SegReaderSort(
105017  Fts3SegReader **apSegment,                     /* Array to sort entries of */
105018  int nSegment,                                  /* Size of apSegment array */
105019  int nSuspect,                                  /* Unsorted entry count */
105020  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
105021){
105022  int i;                          /* Iterator variable */
105023
105024  assert( nSuspect<=nSegment );
105025
105026  if( nSuspect==nSegment ) nSuspect--;
105027  for(i=nSuspect-1; i>=0; i--){
105028    int j;
105029    for(j=i; j<(nSegment-1); j++){
105030      Fts3SegReader *pTmp;
105031      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
105032      pTmp = apSegment[j+1];
105033      apSegment[j+1] = apSegment[j];
105034      apSegment[j] = pTmp;
105035    }
105036  }
105037
105038#ifndef NDEBUG
105039  /* Check that the list really is sorted now. */
105040  for(i=0; i<(nSuspect-1); i++){
105041    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
105042  }
105043#endif
105044}
105045
105046/*
105047** Insert a record into the %_segments table.
105048*/
105049static int fts3WriteSegment(
105050  Fts3Table *p,                   /* Virtual table handle */
105051  sqlite3_int64 iBlock,           /* Block id for new block */
105052  char *z,                        /* Pointer to buffer containing block data */
105053  int n                           /* Size of buffer z in bytes */
105054){
105055  sqlite3_stmt *pStmt;
105056  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
105057  if( rc==SQLITE_OK ){
105058    sqlite3_bind_int64(pStmt, 1, iBlock);
105059    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
105060    sqlite3_step(pStmt);
105061    rc = sqlite3_reset(pStmt);
105062  }
105063  return rc;
105064}
105065
105066/*
105067** Insert a record into the %_segdir table.
105068*/
105069static int fts3WriteSegdir(
105070  Fts3Table *p,                   /* Virtual table handle */
105071  int iLevel,                     /* Value for "level" field */
105072  int iIdx,                       /* Value for "idx" field */
105073  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
105074  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
105075  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
105076  char *zRoot,                    /* Blob value for "root" field */
105077  int nRoot                       /* Number of bytes in buffer zRoot */
105078){
105079  sqlite3_stmt *pStmt;
105080  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
105081  if( rc==SQLITE_OK ){
105082    sqlite3_bind_int(pStmt, 1, iLevel);
105083    sqlite3_bind_int(pStmt, 2, iIdx);
105084    sqlite3_bind_int64(pStmt, 3, iStartBlock);
105085    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
105086    sqlite3_bind_int64(pStmt, 5, iEndBlock);
105087    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
105088    sqlite3_step(pStmt);
105089    rc = sqlite3_reset(pStmt);
105090  }
105091  return rc;
105092}
105093
105094/*
105095** Return the size of the common prefix (if any) shared by zPrev and
105096** zNext, in bytes. For example,
105097**
105098**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
105099**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
105100**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
105101*/
105102static int fts3PrefixCompress(
105103  const char *zPrev,              /* Buffer containing previous term */
105104  int nPrev,                      /* Size of buffer zPrev in bytes */
105105  const char *zNext,              /* Buffer containing next term */
105106  int nNext                       /* Size of buffer zNext in bytes */
105107){
105108  int n;
105109  UNUSED_PARAMETER(nNext);
105110  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
105111  return n;
105112}
105113
105114/*
105115** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
105116** (according to memcmp) than the previous term.
105117*/
105118static int fts3NodeAddTerm(
105119  Fts3Table *p,               /* Virtual table handle */
105120  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
105121  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
105122  const char *zTerm,              /* Pointer to buffer containing term */
105123  int nTerm                       /* Size of term in bytes */
105124){
105125  SegmentNode *pTree = *ppTree;
105126  int rc;
105127  SegmentNode *pNew;
105128
105129  /* First try to append the term to the current node. Return early if
105130  ** this is possible.
105131  */
105132  if( pTree ){
105133    int nData = pTree->nData;     /* Current size of node in bytes */
105134    int nReq = nData;             /* Required space after adding zTerm */
105135    int nPrefix;                  /* Number of bytes of prefix compression */
105136    int nSuffix;                  /* Suffix length */
105137
105138    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
105139    nSuffix = nTerm-nPrefix;
105140
105141    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
105142    if( nReq<=p->nNodeSize || !pTree->zTerm ){
105143
105144      if( nReq>p->nNodeSize ){
105145        /* An unusual case: this is the first term to be added to the node
105146        ** and the static node buffer (p->nNodeSize bytes) is not large
105147        ** enough. Use a separately malloced buffer instead This wastes
105148        ** p->nNodeSize bytes, but since this scenario only comes about when
105149        ** the database contain two terms that share a prefix of almost 2KB,
105150        ** this is not expected to be a serious problem.
105151        */
105152        assert( pTree->aData==(char *)&pTree[1] );
105153        pTree->aData = (char *)sqlite3_malloc(nReq);
105154        if( !pTree->aData ){
105155          return SQLITE_NOMEM;
105156        }
105157      }
105158
105159      if( pTree->zTerm ){
105160        /* There is no prefix-length field for first term in a node */
105161        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
105162      }
105163
105164      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
105165      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
105166      pTree->nData = nData + nSuffix;
105167      pTree->nEntry++;
105168
105169      if( isCopyTerm ){
105170        if( pTree->nMalloc<nTerm ){
105171          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
105172          if( !zNew ){
105173            return SQLITE_NOMEM;
105174          }
105175          pTree->nMalloc = nTerm*2;
105176          pTree->zMalloc = zNew;
105177        }
105178        pTree->zTerm = pTree->zMalloc;
105179        memcpy(pTree->zTerm, zTerm, nTerm);
105180        pTree->nTerm = nTerm;
105181      }else{
105182        pTree->zTerm = (char *)zTerm;
105183        pTree->nTerm = nTerm;
105184      }
105185      return SQLITE_OK;
105186    }
105187  }
105188
105189  /* If control flows to here, it was not possible to append zTerm to the
105190  ** current node. Create a new node (a right-sibling of the current node).
105191  ** If this is the first node in the tree, the term is added to it.
105192  **
105193  ** Otherwise, the term is not added to the new node, it is left empty for
105194  ** now. Instead, the term is inserted into the parent of pTree. If pTree
105195  ** has no parent, one is created here.
105196  */
105197  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
105198  if( !pNew ){
105199    return SQLITE_NOMEM;
105200  }
105201  memset(pNew, 0, sizeof(SegmentNode));
105202  pNew->nData = 1 + FTS3_VARINT_MAX;
105203  pNew->aData = (char *)&pNew[1];
105204
105205  if( pTree ){
105206    SegmentNode *pParent = pTree->pParent;
105207    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
105208    if( pTree->pParent==0 ){
105209      pTree->pParent = pParent;
105210    }
105211    pTree->pRight = pNew;
105212    pNew->pLeftmost = pTree->pLeftmost;
105213    pNew->pParent = pParent;
105214    pNew->zMalloc = pTree->zMalloc;
105215    pNew->nMalloc = pTree->nMalloc;
105216    pTree->zMalloc = 0;
105217  }else{
105218    pNew->pLeftmost = pNew;
105219    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
105220  }
105221
105222  *ppTree = pNew;
105223  return rc;
105224}
105225
105226/*
105227** Helper function for fts3NodeWrite().
105228*/
105229static int fts3TreeFinishNode(
105230  SegmentNode *pTree,
105231  int iHeight,
105232  sqlite3_int64 iLeftChild
105233){
105234  int nStart;
105235  assert( iHeight>=1 && iHeight<128 );
105236  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
105237  pTree->aData[nStart] = (char)iHeight;
105238  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
105239  return nStart;
105240}
105241
105242/*
105243** Write the buffer for the segment node pTree and all of its peers to the
105244** database. Then call this function recursively to write the parent of
105245** pTree and its peers to the database.
105246**
105247** Except, if pTree is a root node, do not write it to the database. Instead,
105248** set output variables *paRoot and *pnRoot to contain the root node.
105249**
105250** If successful, SQLITE_OK is returned and output variable *piLast is
105251** set to the largest blockid written to the database (or zero if no
105252** blocks were written to the db). Otherwise, an SQLite error code is
105253** returned.
105254*/
105255static int fts3NodeWrite(
105256  Fts3Table *p,                   /* Virtual table handle */
105257  SegmentNode *pTree,             /* SegmentNode handle */
105258  int iHeight,                    /* Height of this node in tree */
105259  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
105260  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
105261  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
105262  char **paRoot,                  /* OUT: Data for root node */
105263  int *pnRoot                     /* OUT: Size of root node in bytes */
105264){
105265  int rc = SQLITE_OK;
105266
105267  if( !pTree->pParent ){
105268    /* Root node of the tree. */
105269    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
105270    *piLast = iFree-1;
105271    *pnRoot = pTree->nData - nStart;
105272    *paRoot = &pTree->aData[nStart];
105273  }else{
105274    SegmentNode *pIter;
105275    sqlite3_int64 iNextFree = iFree;
105276    sqlite3_int64 iNextLeaf = iLeaf;
105277    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
105278      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
105279      int nWrite = pIter->nData - nStart;
105280
105281      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
105282      iNextFree++;
105283      iNextLeaf += (pIter->nEntry+1);
105284    }
105285    if( rc==SQLITE_OK ){
105286      assert( iNextLeaf==iFree );
105287      rc = fts3NodeWrite(
105288          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
105289      );
105290    }
105291  }
105292
105293  return rc;
105294}
105295
105296/*
105297** Free all memory allocations associated with the tree pTree.
105298*/
105299static void fts3NodeFree(SegmentNode *pTree){
105300  if( pTree ){
105301    SegmentNode *p = pTree->pLeftmost;
105302    fts3NodeFree(p->pParent);
105303    while( p ){
105304      SegmentNode *pRight = p->pRight;
105305      if( p->aData!=(char *)&p[1] ){
105306        sqlite3_free(p->aData);
105307      }
105308      assert( pRight==0 || p->zMalloc==0 );
105309      sqlite3_free(p->zMalloc);
105310      sqlite3_free(p);
105311      p = pRight;
105312    }
105313  }
105314}
105315
105316/*
105317** Add a term to the segment being constructed by the SegmentWriter object
105318** *ppWriter. When adding the first term to a segment, *ppWriter should
105319** be passed NULL. This function will allocate a new SegmentWriter object
105320** and return it via the input/output variable *ppWriter in this case.
105321**
105322** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
105323*/
105324static int fts3SegWriterAdd(
105325  Fts3Table *p,                   /* Virtual table handle */
105326  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
105327  int isCopyTerm,                 /* True if buffer zTerm must be copied */
105328  const char *zTerm,              /* Pointer to buffer containing term */
105329  int nTerm,                      /* Size of term in bytes */
105330  const char *aDoclist,           /* Pointer to buffer containing doclist */
105331  int nDoclist                    /* Size of doclist in bytes */
105332){
105333  int nPrefix;                    /* Size of term prefix in bytes */
105334  int nSuffix;                    /* Size of term suffix in bytes */
105335  int nReq;                       /* Number of bytes required on leaf page */
105336  int nData;
105337  SegmentWriter *pWriter = *ppWriter;
105338
105339  if( !pWriter ){
105340    int rc;
105341    sqlite3_stmt *pStmt;
105342
105343    /* Allocate the SegmentWriter structure */
105344    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
105345    if( !pWriter ) return SQLITE_NOMEM;
105346    memset(pWriter, 0, sizeof(SegmentWriter));
105347    *ppWriter = pWriter;
105348
105349    /* Allocate a buffer in which to accumulate data */
105350    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
105351    if( !pWriter->aData ) return SQLITE_NOMEM;
105352    pWriter->nSize = p->nNodeSize;
105353
105354    /* Find the next free blockid in the %_segments table */
105355    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
105356    if( rc!=SQLITE_OK ) return rc;
105357    if( SQLITE_ROW==sqlite3_step(pStmt) ){
105358      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
105359      pWriter->iFirst = pWriter->iFree;
105360    }
105361    rc = sqlite3_reset(pStmt);
105362    if( rc!=SQLITE_OK ) return rc;
105363  }
105364  nData = pWriter->nData;
105365
105366  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
105367  nSuffix = nTerm-nPrefix;
105368
105369  /* Figure out how many bytes are required by this new entry */
105370  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
105371    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
105372    nSuffix +                               /* Term suffix */
105373    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
105374    nDoclist;                               /* Doclist data */
105375
105376  if( nData>0 && nData+nReq>p->nNodeSize ){
105377    int rc;
105378
105379    /* The current leaf node is full. Write it out to the database. */
105380    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
105381    if( rc!=SQLITE_OK ) return rc;
105382
105383    /* Add the current term to the interior node tree. The term added to
105384    ** the interior tree must:
105385    **
105386    **   a) be greater than the largest term on the leaf node just written
105387    **      to the database (still available in pWriter->zTerm), and
105388    **
105389    **   b) be less than or equal to the term about to be added to the new
105390    **      leaf node (zTerm/nTerm).
105391    **
105392    ** In other words, it must be the prefix of zTerm 1 byte longer than
105393    ** the common prefix (if any) of zTerm and pWriter->zTerm.
105394    */
105395    assert( nPrefix<nTerm );
105396    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
105397    if( rc!=SQLITE_OK ) return rc;
105398
105399    nData = 0;
105400    pWriter->nTerm = 0;
105401
105402    nPrefix = 0;
105403    nSuffix = nTerm;
105404    nReq = 1 +                              /* varint containing prefix size */
105405      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
105406      nTerm +                               /* Term suffix */
105407      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
105408      nDoclist;                             /* Doclist data */
105409  }
105410
105411  /* If the buffer currently allocated is too small for this entry, realloc
105412  ** the buffer to make it large enough.
105413  */
105414  if( nReq>pWriter->nSize ){
105415    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
105416    if( !aNew ) return SQLITE_NOMEM;
105417    pWriter->aData = aNew;
105418    pWriter->nSize = nReq;
105419  }
105420  assert( nData+nReq<=pWriter->nSize );
105421
105422  /* Append the prefix-compressed term and doclist to the buffer. */
105423  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
105424  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
105425  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
105426  nData += nSuffix;
105427  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
105428  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
105429  pWriter->nData = nData + nDoclist;
105430
105431  /* Save the current term so that it can be used to prefix-compress the next.
105432  ** If the isCopyTerm parameter is true, then the buffer pointed to by
105433  ** zTerm is transient, so take a copy of the term data. Otherwise, just
105434  ** store a copy of the pointer.
105435  */
105436  if( isCopyTerm ){
105437    if( nTerm>pWriter->nMalloc ){
105438      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
105439      if( !zNew ){
105440        return SQLITE_NOMEM;
105441      }
105442      pWriter->nMalloc = nTerm*2;
105443      pWriter->zMalloc = zNew;
105444      pWriter->zTerm = zNew;
105445    }
105446    assert( pWriter->zTerm==pWriter->zMalloc );
105447    memcpy(pWriter->zTerm, zTerm, nTerm);
105448  }else{
105449    pWriter->zTerm = (char *)zTerm;
105450  }
105451  pWriter->nTerm = nTerm;
105452
105453  return SQLITE_OK;
105454}
105455
105456/*
105457** Flush all data associated with the SegmentWriter object pWriter to the
105458** database. This function must be called after all terms have been added
105459** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
105460** returned. Otherwise, an SQLite error code.
105461*/
105462static int fts3SegWriterFlush(
105463  Fts3Table *p,                   /* Virtual table handle */
105464  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
105465  int iLevel,                     /* Value for 'level' column of %_segdir */
105466  int iIdx                        /* Value for 'idx' column of %_segdir */
105467){
105468  int rc;                         /* Return code */
105469  if( pWriter->pTree ){
105470    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
105471    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
105472    char *zRoot = NULL;           /* Pointer to buffer containing root node */
105473    int nRoot = 0;                /* Size of buffer zRoot */
105474
105475    iLastLeaf = pWriter->iFree;
105476    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
105477    if( rc==SQLITE_OK ){
105478      rc = fts3NodeWrite(p, pWriter->pTree, 1,
105479          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
105480    }
105481    if( rc==SQLITE_OK ){
105482      rc = fts3WriteSegdir(
105483          p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
105484    }
105485  }else{
105486    /* The entire tree fits on the root node. Write it to the segdir table. */
105487    rc = fts3WriteSegdir(
105488        p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
105489  }
105490  return rc;
105491}
105492
105493/*
105494** Release all memory held by the SegmentWriter object passed as the
105495** first argument.
105496*/
105497static void fts3SegWriterFree(SegmentWriter *pWriter){
105498  if( pWriter ){
105499    sqlite3_free(pWriter->aData);
105500    sqlite3_free(pWriter->zMalloc);
105501    fts3NodeFree(pWriter->pTree);
105502    sqlite3_free(pWriter);
105503  }
105504}
105505
105506/*
105507** The first value in the apVal[] array is assumed to contain an integer.
105508** This function tests if there exist any documents with docid values that
105509** are different from that integer. i.e. if deleting the document with docid
105510** apVal[0] would mean the FTS3 table were empty.
105511**
105512** If successful, *pisEmpty is set to true if the table is empty except for
105513** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
105514** error occurs, an SQLite error code is returned.
105515*/
105516static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
105517  sqlite3_stmt *pStmt;
105518  int rc;
105519  rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
105520  if( rc==SQLITE_OK ){
105521    if( SQLITE_ROW==sqlite3_step(pStmt) ){
105522      *pisEmpty = sqlite3_column_int(pStmt, 0);
105523    }
105524    rc = sqlite3_reset(pStmt);
105525  }
105526  return rc;
105527}
105528
105529/*
105530** Set *pnSegment to the number of segments of level iLevel in the database.
105531**
105532** Return SQLITE_OK if successful, or an SQLite error code if not.
105533*/
105534static int fts3SegmentCount(Fts3Table *p, int iLevel, int *pnSegment){
105535  sqlite3_stmt *pStmt;
105536  int rc;
105537
105538  assert( iLevel>=0 );
105539  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_COUNT, &pStmt, 0);
105540  if( rc!=SQLITE_OK ) return rc;
105541  sqlite3_bind_int(pStmt, 1, iLevel);
105542  if( SQLITE_ROW==sqlite3_step(pStmt) ){
105543    *pnSegment = sqlite3_column_int(pStmt, 0);
105544  }
105545  return sqlite3_reset(pStmt);
105546}
105547
105548/*
105549** Set *pnSegment to the total number of segments in the database. Set
105550** *pnMax to the largest segment level in the database (segment levels
105551** are stored in the 'level' column of the %_segdir table).
105552**
105553** Return SQLITE_OK if successful, or an SQLite error code if not.
105554*/
105555static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
105556  sqlite3_stmt *pStmt;
105557  int rc;
105558
105559  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
105560  if( rc!=SQLITE_OK ) return rc;
105561  if( SQLITE_ROW==sqlite3_step(pStmt) ){
105562    *pnSegment = sqlite3_column_int(pStmt, 0);
105563    *pnMax = sqlite3_column_int(pStmt, 1);
105564  }
105565  return sqlite3_reset(pStmt);
105566}
105567
105568/*
105569** This function is used after merging multiple segments into a single large
105570** segment to delete the old, now redundant, segment b-trees. Specifically,
105571** it:
105572**
105573**   1) Deletes all %_segments entries for the segments associated with
105574**      each of the SegReader objects in the array passed as the third
105575**      argument, and
105576**
105577**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
105578**      entries regardless of level if (iLevel<0).
105579**
105580** SQLITE_OK is returned if successful, otherwise an SQLite error code.
105581*/
105582static int fts3DeleteSegdir(
105583  Fts3Table *p,                   /* Virtual table handle */
105584  int iLevel,                     /* Level of %_segdir entries to delete */
105585  Fts3SegReader **apSegment,      /* Array of SegReader objects */
105586  int nReader                     /* Size of array apSegment */
105587){
105588  int rc;                         /* Return Code */
105589  int i;                          /* Iterator variable */
105590  sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
105591
105592  rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
105593  for(i=0; rc==SQLITE_OK && i<nReader; i++){
105594    Fts3SegReader *pSegment = apSegment[i];
105595    if( pSegment->iStartBlock ){
105596      sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
105597      sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
105598      sqlite3_step(pDelete);
105599      rc = sqlite3_reset(pDelete);
105600    }
105601  }
105602  if( rc!=SQLITE_OK ){
105603    return rc;
105604  }
105605
105606  if( iLevel>=0 ){
105607    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
105608    if( rc==SQLITE_OK ){
105609      sqlite3_bind_int(pDelete, 1, iLevel);
105610      sqlite3_step(pDelete);
105611      rc = sqlite3_reset(pDelete);
105612    }
105613  }else{
105614    rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGDIR, 0);
105615  }
105616
105617  return rc;
105618}
105619
105620/*
105621** When this function is called, buffer *ppList (size *pnList bytes) contains
105622** a position list that may (or may not) feature multiple columns. This
105623** function adjusts the pointer *ppList and the length *pnList so that they
105624** identify the subset of the position list that corresponds to column iCol.
105625**
105626** If there are no entries in the input position list for column iCol, then
105627** *pnList is set to zero before returning.
105628*/
105629static void fts3ColumnFilter(
105630  int iCol,                       /* Column to filter on */
105631  char **ppList,                  /* IN/OUT: Pointer to position list */
105632  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
105633){
105634  char *pList = *ppList;
105635  int nList = *pnList;
105636  char *pEnd = &pList[nList];
105637  int iCurrent = 0;
105638  char *p = pList;
105639
105640  assert( iCol>=0 );
105641  while( 1 ){
105642    char c = 0;
105643    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
105644
105645    if( iCol==iCurrent ){
105646      nList = (int)(p - pList);
105647      break;
105648    }
105649
105650    nList -= (int)(p - pList);
105651    pList = p;
105652    if( nList==0 ){
105653      break;
105654    }
105655    p = &pList[1];
105656    p += sqlite3Fts3GetVarint32(p, &iCurrent);
105657  }
105658
105659  *ppList = pList;
105660  *pnList = nList;
105661}
105662
105663/*
105664** sqlite3Fts3SegReaderIterate() callback used when merging multiple
105665** segments to create a single, larger segment.
105666*/
105667static int fts3MergeCallback(
105668  Fts3Table *p,                   /* FTS3 Virtual table handle */
105669  void *pContext,                 /* Pointer to SegmentWriter* to write with */
105670  char *zTerm,                    /* Term to write to the db */
105671  int nTerm,                      /* Number of bytes in zTerm */
105672  char *aDoclist,                 /* Doclist associated with zTerm */
105673  int nDoclist                    /* Number of bytes in doclist */
105674){
105675  SegmentWriter **ppW = (SegmentWriter **)pContext;
105676  return fts3SegWriterAdd(p, ppW, 1, zTerm, nTerm, aDoclist, nDoclist);
105677}
105678
105679/*
105680** sqlite3Fts3SegReaderIterate() callback used when flushing the contents
105681** of the pending-terms hash table to the database.
105682*/
105683static int fts3FlushCallback(
105684  Fts3Table *p,                   /* FTS3 Virtual table handle */
105685  void *pContext,                 /* Pointer to SegmentWriter* to write with */
105686  char *zTerm,                    /* Term to write to the db */
105687  int nTerm,                      /* Number of bytes in zTerm */
105688  char *aDoclist,                 /* Doclist associated with zTerm */
105689  int nDoclist                    /* Number of bytes in doclist */
105690){
105691  SegmentWriter **ppW = (SegmentWriter **)pContext;
105692  return fts3SegWriterAdd(p, ppW, 0, zTerm, nTerm, aDoclist, nDoclist);
105693}
105694
105695/*
105696** This function is used to iterate through a contiguous set of terms
105697** stored in the full-text index. It merges data contained in one or
105698** more segments to support this.
105699**
105700** The second argument is passed an array of pointers to SegReader objects
105701** allocated with sqlite3Fts3SegReaderNew(). This function merges the range
105702** of terms selected by each SegReader. If a single term is present in
105703** more than one segment, the associated doclists are merged. For each
105704** term and (possibly merged) doclist in the merged range, the callback
105705** function xFunc is invoked with its arguments set as follows.
105706**
105707**   arg 0: Copy of 'p' parameter passed to this function
105708**   arg 1: Copy of 'pContext' parameter passed to this function
105709**   arg 2: Pointer to buffer containing term
105710**   arg 3: Size of arg 2 buffer in bytes
105711**   arg 4: Pointer to buffer containing doclist
105712**   arg 5: Size of arg 2 buffer in bytes
105713**
105714** The 4th argument to this function is a pointer to a structure of type
105715** Fts3SegFilter, defined in fts3Int.h. The contents of this structure
105716** further restrict the range of terms that callbacks are made for and
105717** modify the behaviour of this function. See comments above structure
105718** definition for details.
105719*/
105720SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
105721  Fts3Table *p,                   /* Virtual table handle */
105722  Fts3SegReader **apSegment,      /* Array of Fts3SegReader objects */
105723  int nSegment,                   /* Size of apSegment array */
105724  Fts3SegFilter *pFilter,         /* Restrictions on range of iteration */
105725  int (*xFunc)(Fts3Table *, void *, char *, int, char *, int),  /* Callback */
105726  void *pContext                  /* Callback context (2nd argument) */
105727){
105728  int i;                          /* Iterator variable */
105729  char *aBuffer = 0;              /* Buffer to merge doclists in */
105730  int nAlloc = 0;                 /* Allocated size of aBuffer buffer */
105731  int rc = SQLITE_OK;             /* Return code */
105732
105733  int isIgnoreEmpty =  (pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
105734  int isRequirePos =   (pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
105735  int isColFilter =    (pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
105736  int isPrefix =       (pFilter->flags & FTS3_SEGMENT_PREFIX);
105737
105738  /* If there are zero segments, this function is a no-op. This scenario
105739  ** comes about only when reading from an empty database.
105740  */
105741  if( nSegment==0 ) goto finished;
105742
105743  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
105744  ** for, then advance each segment iterator until it points to a term of
105745  ** equal or greater value than the specified term. This prevents many
105746  ** unnecessary merge/sort operations for the case where single segment
105747  ** b-tree leaf nodes contain more than one term.
105748  */
105749  if( pFilter->zTerm ){
105750    int nTerm = pFilter->nTerm;
105751    const char *zTerm = pFilter->zTerm;
105752    for(i=0; i<nSegment; i++){
105753      Fts3SegReader *pSeg = apSegment[i];
105754      while( fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 ){
105755        rc = fts3SegReaderNext(pSeg);
105756        if( rc!=SQLITE_OK ) goto finished; }
105757    }
105758  }
105759
105760  fts3SegReaderSort(apSegment, nSegment, nSegment, fts3SegReaderCmp);
105761  while( apSegment[0]->aNode ){
105762    int nTerm = apSegment[0]->nTerm;
105763    char *zTerm = apSegment[0]->zTerm;
105764    int nMerge = 1;
105765
105766    /* If this is a prefix-search, and if the term that apSegment[0] points
105767    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
105768    ** required callbacks have been made. In this case exit early.
105769    **
105770    ** Similarly, if this is a search for an exact match, and the first term
105771    ** of segment apSegment[0] is not a match, exit early.
105772    */
105773    if( pFilter->zTerm ){
105774      if( nTerm<pFilter->nTerm
105775       || (!isPrefix && nTerm>pFilter->nTerm)
105776       || memcmp(zTerm, pFilter->zTerm, pFilter->nTerm)
105777    ){
105778        goto finished;
105779      }
105780    }
105781
105782    while( nMerge<nSegment
105783        && apSegment[nMerge]->aNode
105784        && apSegment[nMerge]->nTerm==nTerm
105785        && 0==memcmp(zTerm, apSegment[nMerge]->zTerm, nTerm)
105786    ){
105787      nMerge++;
105788    }
105789
105790    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
105791    if( nMerge==1 && !isIgnoreEmpty ){
105792      Fts3SegReader *p0 = apSegment[0];
105793      rc = xFunc(p, pContext, zTerm, nTerm, p0->aDoclist, p0->nDoclist);
105794      if( rc!=SQLITE_OK ) goto finished;
105795    }else{
105796      int nDoclist = 0;           /* Size of doclist */
105797      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
105798
105799      /* The current term of the first nMerge entries in the array
105800      ** of Fts3SegReader objects is the same. The doclists must be merged
105801      ** and a single term added to the new segment.
105802      */
105803      for(i=0; i<nMerge; i++){
105804        fts3SegReaderFirstDocid(apSegment[i]);
105805      }
105806      fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
105807      while( apSegment[0]->pOffsetList ){
105808        int j;                    /* Number of segments that share a docid */
105809        char *pList;
105810        int nList;
105811        int nByte;
105812        sqlite3_int64 iDocid = apSegment[0]->iDocid;
105813        fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
105814        j = 1;
105815        while( j<nMerge
105816            && apSegment[j]->pOffsetList
105817            && apSegment[j]->iDocid==iDocid
105818        ){
105819          fts3SegReaderNextDocid(apSegment[j], 0, 0);
105820          j++;
105821        }
105822
105823        if( isColFilter ){
105824          fts3ColumnFilter(pFilter->iCol, &pList, &nList);
105825        }
105826
105827        if( !isIgnoreEmpty || nList>0 ){
105828          nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
105829          if( nDoclist+nByte>nAlloc ){
105830            char *aNew;
105831            nAlloc = nDoclist+nByte*2;
105832            aNew = sqlite3_realloc(aBuffer, nAlloc);
105833            if( !aNew ){
105834              rc = SQLITE_NOMEM;
105835              goto finished;
105836            }
105837            aBuffer = aNew;
105838          }
105839          nDoclist += sqlite3Fts3PutVarint(&aBuffer[nDoclist], iDocid-iPrev);
105840          iPrev = iDocid;
105841          if( isRequirePos ){
105842            memcpy(&aBuffer[nDoclist], pList, nList);
105843            nDoclist += nList;
105844            aBuffer[nDoclist++] = '\0';
105845          }
105846        }
105847
105848        fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
105849      }
105850
105851      if( nDoclist>0 ){
105852        rc = xFunc(p, pContext, zTerm, nTerm, aBuffer, nDoclist);
105853        if( rc!=SQLITE_OK ) goto finished;
105854      }
105855    }
105856
105857    /* If there is a term specified to filter on, and this is not a prefix
105858    ** search, return now. The callback that corresponds to the required
105859    ** term (if such a term exists in the index) has already been made.
105860    */
105861    if( pFilter->zTerm && !isPrefix ){
105862      goto finished;
105863    }
105864
105865    for(i=0; i<nMerge; i++){
105866      rc = fts3SegReaderNext(apSegment[i]);
105867      if( rc!=SQLITE_OK ) goto finished;
105868    }
105869    fts3SegReaderSort(apSegment, nSegment, nMerge, fts3SegReaderCmp);
105870  }
105871
105872 finished:
105873  sqlite3_free(aBuffer);
105874  return rc;
105875}
105876
105877/*
105878** Merge all level iLevel segments in the database into a single
105879** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
105880** single segment with a level equal to the numerically largest level
105881** currently present in the database.
105882**
105883** If this function is called with iLevel<0, but there is only one
105884** segment in the database, SQLITE_DONE is returned immediately.
105885** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
105886** an SQLite error code is returned.
105887*/
105888static int fts3SegmentMerge(Fts3Table *p, int iLevel){
105889  int i;                          /* Iterator variable */
105890  int rc;                         /* Return code */
105891  int iIdx;                       /* Index of new segment */
105892  int iNewLevel;                  /* Level to create new segment at */
105893  sqlite3_stmt *pStmt = 0;
105894  SegmentWriter *pWriter = 0;
105895  int nSegment = 0;               /* Number of segments being merged */
105896  Fts3SegReader **apSegment = 0;  /* Array of Segment iterators */
105897  Fts3SegReader *pPending = 0;    /* Iterator for pending-terms */
105898  Fts3SegFilter filter;           /* Segment term filter condition */
105899
105900  if( iLevel<0 ){
105901    /* This call is to merge all segments in the database to a single
105902    ** segment. The level of the new segment is equal to the the numerically
105903    ** greatest segment level currently present in the database. The index
105904    ** of the new segment is always 0.
105905    */
105906    iIdx = 0;
105907    rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pPending);
105908    if( rc!=SQLITE_OK ) goto finished;
105909    rc = fts3SegmentCountMax(p, &nSegment, &iNewLevel);
105910    if( rc!=SQLITE_OK ) goto finished;
105911    nSegment += (pPending!=0);
105912    if( nSegment<=1 ){
105913      return SQLITE_DONE;
105914    }
105915  }else{
105916    /* This call is to merge all segments at level iLevel. Find the next
105917    ** available segment index at level iLevel+1. The call to
105918    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
105919    ** a single iLevel+2 segment if necessary.
105920    */
105921    iNewLevel = iLevel+1;
105922    rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
105923    if( rc!=SQLITE_OK ) goto finished;
105924    rc = fts3SegmentCount(p, iLevel, &nSegment);
105925    if( rc!=SQLITE_OK ) goto finished;
105926  }
105927  assert( nSegment>0 );
105928  assert( iNewLevel>=0 );
105929
105930  /* Allocate space for an array of pointers to segment iterators. */
105931  apSegment = (Fts3SegReader**)sqlite3_malloc(sizeof(Fts3SegReader *)*nSegment);
105932  if( !apSegment ){
105933    rc = SQLITE_NOMEM;
105934    goto finished;
105935  }
105936  memset(apSegment, 0, sizeof(Fts3SegReader *)*nSegment);
105937
105938  /* Allocate a Fts3SegReader structure for each segment being merged. A
105939  ** Fts3SegReader stores the state data required to iterate through all
105940  ** entries on all leaves of a single segment.
105941  */
105942  assert( SQL_SELECT_LEVEL+1==SQL_SELECT_ALL_LEVEL);
105943  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL+(iLevel<0), &pStmt, 0);
105944  if( rc!=SQLITE_OK ) goto finished;
105945  sqlite3_bind_int(pStmt, 1, iLevel);
105946  for(i=0; SQLITE_ROW==(sqlite3_step(pStmt)); i++){
105947    rc = fts3SegReaderNew(p, pStmt, i, &apSegment[i]);
105948    if( rc!=SQLITE_OK ){
105949      goto finished;
105950    }
105951  }
105952  rc = sqlite3_reset(pStmt);
105953  if( pPending ){
105954    apSegment[i] = pPending;
105955    pPending = 0;
105956  }
105957  pStmt = 0;
105958  if( rc!=SQLITE_OK ) goto finished;
105959
105960  memset(&filter, 0, sizeof(Fts3SegFilter));
105961  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
105962  filter.flags |= (iLevel<0 ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
105963  rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment,
105964      &filter, fts3MergeCallback, (void *)&pWriter
105965  );
105966  if( rc!=SQLITE_OK ) goto finished;
105967
105968  rc = fts3DeleteSegdir(p, iLevel, apSegment, nSegment);
105969  if( rc==SQLITE_OK ){
105970    rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
105971  }
105972
105973 finished:
105974  fts3SegWriterFree(pWriter);
105975  if( apSegment ){
105976    for(i=0; i<nSegment; i++){
105977      sqlite3Fts3SegReaderFree(p, apSegment[i]);
105978    }
105979    sqlite3_free(apSegment);
105980  }
105981  sqlite3Fts3SegReaderFree(p, pPending);
105982  sqlite3_reset(pStmt);
105983  return rc;
105984}
105985
105986
105987/*
105988** Flush the contents of pendingTerms to a level 0 segment.
105989*/
105990SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
105991  int rc;                         /* Return Code */
105992  int idx;                        /* Index of new segment created */
105993  SegmentWriter *pWriter = 0;     /* Used to write the segment */
105994  Fts3SegReader *pReader = 0;     /* Used to iterate through the hash table */
105995
105996  /* Allocate a SegReader object to iterate through the contents of the
105997  ** pending-terms table. If an error occurs, or if there are no terms
105998  ** in the pending-terms table, return immediately.
105999  */
106000  rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pReader);
106001  if( rc!=SQLITE_OK || pReader==0 ){
106002    return rc;
106003  }
106004
106005  /* Determine the next index at level 0. If level 0 is already full, this
106006  ** call may merge all existing level 0 segments into a single level 1
106007  ** segment.
106008  */
106009  rc = fts3AllocateSegdirIdx(p, 0, &idx);
106010
106011  /* If no errors have occured, iterate through the contents of the
106012  ** pending-terms hash table using the Fts3SegReader iterator. The callback
106013  ** writes each term (along with its doclist) to the database via the
106014  ** SegmentWriter handle pWriter.
106015  */
106016  if( rc==SQLITE_OK ){
106017    void *c = (void *)&pWriter;   /* SegReaderIterate() callback context */
106018    Fts3SegFilter f;              /* SegReaderIterate() parameters */
106019
106020    memset(&f, 0, sizeof(Fts3SegFilter));
106021    f.flags = FTS3_SEGMENT_REQUIRE_POS;
106022    rc = sqlite3Fts3SegReaderIterate(p, &pReader, 1, &f, fts3FlushCallback, c);
106023  }
106024  assert( pWriter || rc!=SQLITE_OK );
106025
106026  /* If no errors have occured, flush the SegmentWriter object to the
106027  ** database. Then delete the SegmentWriter and Fts3SegReader objects
106028  ** allocated by this function.
106029  */
106030  if( rc==SQLITE_OK ){
106031    rc = fts3SegWriterFlush(p, pWriter, 0, idx);
106032  }
106033  fts3SegWriterFree(pWriter);
106034  sqlite3Fts3SegReaderFree(p, pReader);
106035
106036  if( rc==SQLITE_OK ){
106037    sqlite3Fts3PendingTermsClear(p);
106038  }
106039  return rc;
106040}
106041
106042/*
106043** Handle a 'special' INSERT of the form:
106044**
106045**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
106046**
106047** Argument pVal contains the result of <expr>. Currently the only
106048** meaningful value to insert is the text 'optimize'.
106049*/
106050static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
106051  int rc;                         /* Return Code */
106052  const char *zVal = (const char *)sqlite3_value_text(pVal);
106053  int nVal = sqlite3_value_bytes(pVal);
106054
106055  if( !zVal ){
106056    return SQLITE_NOMEM;
106057  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
106058    rc = fts3SegmentMerge(p, -1);
106059    if( rc==SQLITE_DONE ){
106060      rc = SQLITE_OK;
106061    }else{
106062      sqlite3Fts3PendingTermsClear(p);
106063    }
106064#ifdef SQLITE_TEST
106065  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
106066    p->nNodeSize = atoi(&zVal[9]);
106067    rc = SQLITE_OK;
106068  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
106069    p->nMaxPendingData = atoi(&zVal[11]);
106070    rc = SQLITE_OK;
106071#endif
106072  }else{
106073    rc = SQLITE_ERROR;
106074  }
106075
106076  return rc;
106077}
106078
106079/*
106080** This function does the work for the xUpdate method of FTS3 virtual
106081** tables.
106082*/
106083SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
106084  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
106085  int nArg,                       /* Size of argument array */
106086  sqlite3_value **apVal,          /* Array of arguments */
106087  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
106088){
106089  Fts3Table *p = (Fts3Table *)pVtab;
106090  int rc = SQLITE_OK;             /* Return Code */
106091  int isRemove = 0;               /* True for an UPDATE or DELETE */
106092  sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
106093
106094
106095  /* If this is a DELETE or UPDATE operation, remove the old record. */
106096  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
106097    int isEmpty;
106098    rc = fts3IsEmpty(p, apVal, &isEmpty);
106099    if( rc==SQLITE_OK ){
106100      if( isEmpty ){
106101        /* Deleting this row means the whole table is empty. In this case
106102        ** delete the contents of all three tables and throw away any
106103        ** data in the pendingTerms hash table.
106104        */
106105        rc = fts3DeleteAll(p);
106106      }else{
106107        isRemove = 1;
106108        iRemove = sqlite3_value_int64(apVal[0]);
106109        rc = fts3PendingTermsDocid(p, iRemove);
106110        if( rc==SQLITE_OK ){
106111          rc = fts3DeleteTerms(p, apVal);
106112          if( rc==SQLITE_OK ){
106113            rc = fts3SqlExec(p, SQL_DELETE_CONTENT, apVal);
106114          }
106115        }
106116      }
106117    }
106118  }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
106119    return fts3SpecialInsert(p, apVal[p->nColumn+2]);
106120  }
106121
106122  /* If this is an INSERT or UPDATE operation, insert the new record. */
106123  if( nArg>1 && rc==SQLITE_OK ){
106124    rc = fts3InsertData(p, apVal, pRowid);
106125    if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
106126      rc = fts3PendingTermsDocid(p, *pRowid);
106127    }
106128    if( rc==SQLITE_OK ){
106129      rc = fts3InsertTerms(p, apVal);
106130    }
106131  }
106132
106133  return rc;
106134}
106135
106136/*
106137** Flush any data in the pending-terms hash table to disk. If successful,
106138** merge all segments in the database (including the new segment, if
106139** there was any data to flush) into a single segment.
106140*/
106141SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
106142  int rc;
106143  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
106144  if( rc==SQLITE_OK ){
106145    rc = fts3SegmentMerge(p, -1);
106146    if( rc==SQLITE_OK ){
106147      rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
106148      if( rc==SQLITE_OK ){
106149        sqlite3Fts3PendingTermsClear(p);
106150      }
106151    }else{
106152      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
106153      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
106154    }
106155  }
106156  return rc;
106157}
106158
106159#endif
106160
106161/************** End of fts3_write.c ******************************************/
106162/************** Begin file fts3_snippet.c ************************************/
106163/*
106164** 2009 Oct 23
106165**
106166** The author disclaims copyright to this source code.  In place of
106167** a legal notice, here is a blessing:
106168**
106169**    May you do good and not evil.
106170**    May you find forgiveness for yourself and forgive others.
106171**    May you share freely, never taking more than you give.
106172**
106173******************************************************************************
106174*/
106175
106176#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
106177
106178
106179typedef struct Snippet Snippet;
106180
106181/*
106182** An instance of the following structure keeps track of generated
106183** matching-word offset information and snippets.
106184*/
106185struct Snippet {
106186  int nMatch;                     /* Total number of matches */
106187  int nAlloc;                     /* Space allocated for aMatch[] */
106188  struct snippetMatch {  /* One entry for each matching term */
106189    char snStatus;       /* Status flag for use while constructing snippets */
106190    short int nByte;     /* Number of bytes in the term */
106191    short int iCol;      /* The column that contains the match */
106192    short int iTerm;     /* The index in Query.pTerms[] of the matching term */
106193    int iToken;          /* The index of the matching document token */
106194    int iStart;          /* The offset to the first character of the term */
106195  } *aMatch;                      /* Points to space obtained from malloc */
106196  char *zOffset;                  /* Text rendering of aMatch[] */
106197  int nOffset;                    /* strlen(zOffset) */
106198  char *zSnippet;                 /* Snippet text */
106199  int nSnippet;                   /* strlen(zSnippet) */
106200};
106201
106202
106203/* It is not safe to call isspace(), tolower(), or isalnum() on
106204** hi-bit-set characters.  This is the same solution used in the
106205** tokenizer.
106206*/
106207static int fts3snippetIsspace(char c){
106208  return (c&0x80)==0 ? isspace(c) : 0;
106209}
106210
106211
106212/*
106213** A StringBuffer object holds a zero-terminated string that grows
106214** arbitrarily by appending.  Space to hold the string is obtained
106215** from sqlite3_malloc().  After any memory allocation failure,
106216** StringBuffer.z is set to NULL and no further allocation is attempted.
106217*/
106218typedef struct StringBuffer {
106219  char *z;         /* Text of the string.  Space from malloc. */
106220  int nUsed;       /* Number bytes of z[] used, not counting \000 terminator */
106221  int nAlloc;      /* Bytes allocated for z[] */
106222} StringBuffer;
106223
106224
106225/*
106226** Initialize a new StringBuffer.
106227*/
106228static void fts3SnippetSbInit(StringBuffer *p){
106229  p->nAlloc = 100;
106230  p->nUsed = 0;
106231  p->z = sqlite3_malloc( p->nAlloc );
106232}
106233
106234/*
106235** Append text to the string buffer.
106236*/
106237static void fts3SnippetAppend(StringBuffer *p, const char *zNew, int nNew){
106238  if( p->z==0 ) return;
106239  if( nNew<0 ) nNew = (int)strlen(zNew);
106240  if( p->nUsed + nNew >= p->nAlloc ){
106241    int nAlloc;
106242    char *zNew;
106243
106244    nAlloc = p->nUsed + nNew + p->nAlloc;
106245    zNew = sqlite3_realloc(p->z, nAlloc);
106246    if( zNew==0 ){
106247      sqlite3_free(p->z);
106248      p->z = 0;
106249      return;
106250    }
106251    p->z = zNew;
106252    p->nAlloc = nAlloc;
106253  }
106254  memcpy(&p->z[p->nUsed], zNew, nNew);
106255  p->nUsed += nNew;
106256  p->z[p->nUsed] = 0;
106257}
106258
106259/* If the StringBuffer ends in something other than white space, add a
106260** single space character to the end.
106261*/
106262static void fts3SnippetAppendWhiteSpace(StringBuffer *p){
106263  if( p->z && p->nUsed && !fts3snippetIsspace(p->z[p->nUsed-1]) ){
106264    fts3SnippetAppend(p, " ", 1);
106265  }
106266}
106267
106268/* Remove white space from the end of the StringBuffer */
106269static void fts3SnippetTrimWhiteSpace(StringBuffer *p){
106270  if( p->z ){
106271    while( p->nUsed && fts3snippetIsspace(p->z[p->nUsed-1]) ){
106272      p->nUsed--;
106273    }
106274    p->z[p->nUsed] = 0;
106275  }
106276}
106277
106278/*
106279** Release all memory associated with the Snippet structure passed as
106280** an argument.
106281*/
106282static void fts3SnippetFree(Snippet *p){
106283  if( p ){
106284    sqlite3_free(p->aMatch);
106285    sqlite3_free(p->zOffset);
106286    sqlite3_free(p->zSnippet);
106287    sqlite3_free(p);
106288  }
106289}
106290
106291/*
106292** Append a single entry to the p->aMatch[] log.
106293*/
106294static int snippetAppendMatch(
106295  Snippet *p,               /* Append the entry to this snippet */
106296  int iCol, int iTerm,      /* The column and query term */
106297  int iToken,               /* Matching token in document */
106298  int iStart, int nByte     /* Offset and size of the match */
106299){
106300  int i;
106301  struct snippetMatch *pMatch;
106302  if( p->nMatch+1>=p->nAlloc ){
106303    struct snippetMatch *pNew;
106304    p->nAlloc = p->nAlloc*2 + 10;
106305    pNew = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
106306    if( pNew==0 ){
106307      p->aMatch = 0;
106308      p->nMatch = 0;
106309      p->nAlloc = 0;
106310      return SQLITE_NOMEM;
106311    }
106312    p->aMatch = pNew;
106313  }
106314  i = p->nMatch++;
106315  pMatch = &p->aMatch[i];
106316  pMatch->iCol = (short)iCol;
106317  pMatch->iTerm = (short)iTerm;
106318  pMatch->iToken = iToken;
106319  pMatch->iStart = iStart;
106320  pMatch->nByte = (short)nByte;
106321  return SQLITE_OK;
106322}
106323
106324/*
106325** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
106326*/
106327#define FTS3_ROTOR_SZ   (32)
106328#define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
106329
106330/*
106331** Function to iterate through the tokens of a compiled expression.
106332**
106333** Except, skip all tokens on the right-hand side of a NOT operator.
106334** This function is used to find tokens as part of snippet and offset
106335** generation and we do nt want snippets and offsets to report matches
106336** for tokens on the RHS of a NOT.
106337*/
106338static int fts3NextExprToken(Fts3Expr **ppExpr, int *piToken){
106339  Fts3Expr *p = *ppExpr;
106340  int iToken = *piToken;
106341  if( iToken<0 ){
106342    /* In this case the expression p is the root of an expression tree.
106343    ** Move to the first token in the expression tree.
106344    */
106345    while( p->pLeft ){
106346      p = p->pLeft;
106347    }
106348    iToken = 0;
106349  }else{
106350    assert(p && p->eType==FTSQUERY_PHRASE );
106351    if( iToken<(p->pPhrase->nToken-1) ){
106352      iToken++;
106353    }else{
106354      iToken = 0;
106355      while( p->pParent && p->pParent->pLeft!=p ){
106356        assert( p->pParent->pRight==p );
106357        p = p->pParent;
106358      }
106359      p = p->pParent;
106360      if( p ){
106361        assert( p->pRight!=0 );
106362        p = p->pRight;
106363        while( p->pLeft ){
106364          p = p->pLeft;
106365        }
106366      }
106367    }
106368  }
106369
106370  *ppExpr = p;
106371  *piToken = iToken;
106372  return p?1:0;
106373}
106374
106375/*
106376** Return TRUE if the expression node pExpr is located beneath the
106377** RHS of a NOT operator.
106378*/
106379static int fts3ExprBeneathNot(Fts3Expr *p){
106380  Fts3Expr *pParent;
106381  while( p ){
106382    pParent = p->pParent;
106383    if( pParent && pParent->eType==FTSQUERY_NOT && pParent->pRight==p ){
106384      return 1;
106385    }
106386    p = pParent;
106387  }
106388  return 0;
106389}
106390
106391/*
106392** Add entries to pSnippet->aMatch[] for every match that occurs against
106393** document zDoc[0..nDoc-1] which is stored in column iColumn.
106394*/
106395static int snippetOffsetsOfColumn(
106396  Fts3Cursor *pCur,         /* The fulltest search cursor */
106397  Snippet *pSnippet,             /* The Snippet object to be filled in */
106398  int iColumn,                   /* Index of fulltext table column */
106399  const char *zDoc,              /* Text of the fulltext table column */
106400  int nDoc                       /* Length of zDoc in bytes */
106401){
106402  const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
106403  sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
106404  sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
106405  Fts3Table *pVtab;                /* The full text index */
106406  int nColumn;                         /* Number of columns in the index */
106407  int i, j;                            /* Loop counters */
106408  int rc;                              /* Return code */
106409  unsigned int match, prevMatch;       /* Phrase search bitmasks */
106410  const char *zToken;                  /* Next token from the tokenizer */
106411  int nToken;                          /* Size of zToken */
106412  int iBegin, iEnd, iPos;              /* Offsets of beginning and end */
106413
106414  /* The following variables keep a circular buffer of the last
106415  ** few tokens */
106416  unsigned int iRotor = 0;             /* Index of current token */
106417  int iRotorBegin[FTS3_ROTOR_SZ];      /* Beginning offset of token */
106418  int iRotorLen[FTS3_ROTOR_SZ];        /* Length of token */
106419
106420  pVtab =  (Fts3Table *)pCur->base.pVtab;
106421  nColumn = pVtab->nColumn;
106422  pTokenizer = pVtab->pTokenizer;
106423  pTModule = pTokenizer->pModule;
106424  rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
106425  if( rc ) return rc;
106426  pTCursor->pTokenizer = pTokenizer;
106427
106428  prevMatch = 0;
106429  while( (rc = pTModule->xNext(pTCursor, &zToken, &nToken,
106430                               &iBegin, &iEnd, &iPos))==SQLITE_OK ){
106431    Fts3Expr *pIter = pCur->pExpr;
106432    int iIter = -1;
106433    iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
106434    iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
106435    match = 0;
106436    for(i=0; i<(FTS3_ROTOR_SZ-1) && fts3NextExprToken(&pIter, &iIter); i++){
106437      int nPhrase;                    /* Number of tokens in current phrase */
106438      struct PhraseToken *pToken;     /* Current token */
106439      int iCol;                       /* Column index */
106440
106441      if( fts3ExprBeneathNot(pIter) ) continue;
106442      nPhrase = pIter->pPhrase->nToken;
106443      pToken = &pIter->pPhrase->aToken[iIter];
106444      iCol = pIter->pPhrase->iColumn;
106445      if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
106446      if( pToken->n>nToken ) continue;
106447      if( !pToken->isPrefix && pToken->n<nToken ) continue;
106448      assert( pToken->n<=nToken );
106449      if( memcmp(pToken->z, zToken, pToken->n) ) continue;
106450      if( iIter>0 && (prevMatch & (1<<i))==0 ) continue;
106451      match |= 1<<i;
106452      if( i==(FTS3_ROTOR_SZ-2) || nPhrase==iIter+1 ){
106453        for(j=nPhrase-1; j>=0; j--){
106454          int k = (iRotor-j) & FTS3_ROTOR_MASK;
106455          rc = snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
106456                                  iRotorBegin[k], iRotorLen[k]);
106457          if( rc ) goto end_offsets_of_column;
106458        }
106459      }
106460    }
106461    prevMatch = match<<1;
106462    iRotor++;
106463  }
106464end_offsets_of_column:
106465  pTModule->xClose(pTCursor);
106466  return rc==SQLITE_DONE ? SQLITE_OK : rc;
106467}
106468
106469/*
106470** Remove entries from the pSnippet structure to account for the NEAR
106471** operator. When this is called, pSnippet contains the list of token
106472** offsets produced by treating all NEAR operators as AND operators.
106473** This function removes any entries that should not be present after
106474** accounting for the NEAR restriction. For example, if the queried
106475** document is:
106476**
106477**     "A B C D E A"
106478**
106479** and the query is:
106480**
106481**     A NEAR/0 E
106482**
106483** then when this function is called the Snippet contains token offsets
106484** 0, 4 and 5. This function removes the "0" entry (because the first A
106485** is not near enough to an E).
106486**
106487** When this function is called, the value pointed to by parameter piLeft is
106488** the integer id of the left-most token in the expression tree headed by
106489** pExpr. This function increments *piLeft by the total number of tokens
106490** in the expression tree headed by pExpr.
106491**
106492** Return 1 if any trimming occurs.  Return 0 if no trimming is required.
106493*/
106494static int trimSnippetOffsets(
106495  Fts3Expr *pExpr,      /* The search expression */
106496  Snippet *pSnippet,    /* The set of snippet offsets to be trimmed */
106497  int *piLeft           /* Index of left-most token in pExpr */
106498){
106499  if( pExpr ){
106500    if( trimSnippetOffsets(pExpr->pLeft, pSnippet, piLeft) ){
106501      return 1;
106502    }
106503
106504    switch( pExpr->eType ){
106505      case FTSQUERY_PHRASE:
106506        *piLeft += pExpr->pPhrase->nToken;
106507        break;
106508      case FTSQUERY_NEAR: {
106509        /* The right-hand-side of a NEAR operator is always a phrase. The
106510        ** left-hand-side is either a phrase or an expression tree that is
106511        ** itself headed by a NEAR operator. The following initializations
106512        ** set local variable iLeft to the token number of the left-most
106513        ** token in the right-hand phrase, and iRight to the right most
106514        ** token in the same phrase. For example, if we had:
106515        **
106516        **     <col> MATCH '"abc def" NEAR/2 "ghi jkl"'
106517        **
106518        ** then iLeft will be set to 2 (token number of ghi) and nToken will
106519        ** be set to 4.
106520        */
106521        Fts3Expr *pLeft = pExpr->pLeft;
106522        Fts3Expr *pRight = pExpr->pRight;
106523        int iLeft = *piLeft;
106524        int nNear = pExpr->nNear;
106525        int nToken = pRight->pPhrase->nToken;
106526        int jj, ii;
106527        if( pLeft->eType==FTSQUERY_NEAR ){
106528          pLeft = pLeft->pRight;
106529        }
106530        assert( pRight->eType==FTSQUERY_PHRASE );
106531        assert( pLeft->eType==FTSQUERY_PHRASE );
106532        nToken += pLeft->pPhrase->nToken;
106533
106534        for(ii=0; ii<pSnippet->nMatch; ii++){
106535          struct snippetMatch *p = &pSnippet->aMatch[ii];
106536          if( p->iTerm==iLeft ){
106537            int isOk = 0;
106538            /* Snippet ii is an occurence of query term iLeft in the document.
106539            ** It occurs at position (p->iToken) of the document. We now
106540            ** search for an instance of token (iLeft-1) somewhere in the
106541            ** range (p->iToken - nNear)...(p->iToken + nNear + nToken) within
106542            ** the set of snippetMatch structures. If one is found, proceed.
106543            ** If one cannot be found, then remove snippets ii..(ii+N-1)
106544            ** from the matching snippets, where N is the number of tokens
106545            ** in phrase pRight->pPhrase.
106546            */
106547            for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
106548              struct snippetMatch *p2 = &pSnippet->aMatch[jj];
106549              if( p2->iTerm==(iLeft-1) ){
106550                if( p2->iToken>=(p->iToken-nNear-1)
106551                 && p2->iToken<(p->iToken+nNear+nToken)
106552                ){
106553                  isOk = 1;
106554                }
106555              }
106556            }
106557            if( !isOk ){
106558              int kk;
106559              for(kk=0; kk<pRight->pPhrase->nToken; kk++){
106560                pSnippet->aMatch[kk+ii].iTerm = -2;
106561              }
106562              return 1;
106563            }
106564          }
106565          if( p->iTerm==(iLeft-1) ){
106566            int isOk = 0;
106567            for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
106568              struct snippetMatch *p2 = &pSnippet->aMatch[jj];
106569              if( p2->iTerm==iLeft ){
106570                if( p2->iToken<=(p->iToken+nNear+1)
106571                 && p2->iToken>(p->iToken-nNear-nToken)
106572                ){
106573                  isOk = 1;
106574                }
106575              }
106576            }
106577            if( !isOk ){
106578              int kk;
106579              for(kk=0; kk<pLeft->pPhrase->nToken; kk++){
106580                pSnippet->aMatch[ii-kk].iTerm = -2;
106581              }
106582              return 1;
106583            }
106584          }
106585        }
106586        break;
106587      }
106588    }
106589
106590    if( trimSnippetOffsets(pExpr->pRight, pSnippet, piLeft) ){
106591      return 1;
106592    }
106593  }
106594  return 0;
106595}
106596
106597/*
106598** Compute all offsets for the current row of the query.
106599** If the offsets have already been computed, this routine is a no-op.
106600*/
106601static int snippetAllOffsets(Fts3Cursor *pCsr, Snippet **ppSnippet){
106602  Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;  /* The FTS3 virtual table */
106603  int nColumn;           /* Number of columns.  Docid does count */
106604  int iColumn;           /* Index of of a column */
106605  int i;                 /* Loop index */
106606  int iFirst;            /* First column to search */
106607  int iLast;             /* Last coumn to search */
106608  int iTerm = 0;
106609  Snippet *pSnippet;
106610  int rc = SQLITE_OK;
106611
106612  if( pCsr->pExpr==0 ){
106613    return SQLITE_OK;
106614  }
106615
106616  pSnippet = (Snippet *)sqlite3_malloc(sizeof(Snippet));
106617  *ppSnippet = pSnippet;
106618  if( !pSnippet ){
106619    return SQLITE_NOMEM;
106620  }
106621  memset(pSnippet, 0, sizeof(Snippet));
106622
106623  nColumn = p->nColumn;
106624  iColumn = (pCsr->eSearch - 2);
106625  if( iColumn<0 || iColumn>=nColumn ){
106626    /* Look for matches over all columns of the full-text index */
106627    iFirst = 0;
106628    iLast = nColumn-1;
106629  }else{
106630    /* Look for matches in the iColumn-th column of the index only */
106631    iFirst = iColumn;
106632    iLast = iColumn;
106633  }
106634  for(i=iFirst; rc==SQLITE_OK && i<=iLast; i++){
106635    const char *zDoc;
106636    int nDoc;
106637    zDoc = (const char*)sqlite3_column_text(pCsr->pStmt, i+1);
106638    nDoc = sqlite3_column_bytes(pCsr->pStmt, i+1);
106639    if( zDoc==0 && sqlite3_column_type(pCsr->pStmt, i+1)!=SQLITE_NULL ){
106640      rc = SQLITE_NOMEM;
106641    }else{
106642      rc = snippetOffsetsOfColumn(pCsr, pSnippet, i, zDoc, nDoc);
106643    }
106644  }
106645
106646  while( trimSnippetOffsets(pCsr->pExpr, pSnippet, &iTerm) ){
106647    iTerm = 0;
106648  }
106649
106650  return rc;
106651}
106652
106653/*
106654** Convert the information in the aMatch[] array of the snippet
106655** into the string zOffset[0..nOffset-1]. This string is used as
106656** the return of the SQL offsets() function.
106657*/
106658static void snippetOffsetText(Snippet *p){
106659  int i;
106660  int cnt = 0;
106661  StringBuffer sb;
106662  char zBuf[200];
106663  if( p->zOffset ) return;
106664  fts3SnippetSbInit(&sb);
106665  for(i=0; i<p->nMatch; i++){
106666    struct snippetMatch *pMatch = &p->aMatch[i];
106667    if( pMatch->iTerm>=0 ){
106668      /* If snippetMatch.iTerm is less than 0, then the match was
106669      ** discarded as part of processing the NEAR operator (see the
106670      ** trimSnippetOffsetsForNear() function for details). Ignore
106671      ** it in this case
106672      */
106673      zBuf[0] = ' ';
106674      sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
106675          pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
106676      fts3SnippetAppend(&sb, zBuf, -1);
106677      cnt++;
106678    }
106679  }
106680  p->zOffset = sb.z;
106681  p->nOffset = sb.z ? sb.nUsed : 0;
106682}
106683
106684/*
106685** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
106686** of matching words some of which might be in zDoc.  zDoc is column
106687** number iCol.
106688**
106689** iBreak is suggested spot in zDoc where we could begin or end an
106690** excerpt.  Return a value similar to iBreak but possibly adjusted
106691** to be a little left or right so that the break point is better.
106692*/
106693static int wordBoundary(
106694  int iBreak,                   /* The suggested break point */
106695  const char *zDoc,             /* Document text */
106696  int nDoc,                     /* Number of bytes in zDoc[] */
106697  struct snippetMatch *aMatch,  /* Matching words */
106698  int nMatch,                   /* Number of entries in aMatch[] */
106699  int iCol                      /* The column number for zDoc[] */
106700){
106701  int i;
106702  if( iBreak<=10 ){
106703    return 0;
106704  }
106705  if( iBreak>=nDoc-10 ){
106706    return nDoc;
106707  }
106708  for(i=0; ALWAYS(i<nMatch) && aMatch[i].iCol<iCol; i++){}
106709  while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
106710  if( i<nMatch ){
106711    if( aMatch[i].iStart<iBreak+10 ){
106712      return aMatch[i].iStart;
106713    }
106714    if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
106715      return aMatch[i-1].iStart;
106716    }
106717  }
106718  for(i=1; i<=10; i++){
106719    if( fts3snippetIsspace(zDoc[iBreak-i]) ){
106720      return iBreak - i + 1;
106721    }
106722    if( fts3snippetIsspace(zDoc[iBreak+i]) ){
106723      return iBreak + i + 1;
106724    }
106725  }
106726  return iBreak;
106727}
106728
106729
106730
106731/*
106732** Allowed values for Snippet.aMatch[].snStatus
106733*/
106734#define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
106735#define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */
106736
106737/*
106738** Generate the text of a snippet.
106739*/
106740static void snippetText(
106741  Fts3Cursor *pCursor,   /* The cursor we need the snippet for */
106742  Snippet *pSnippet,
106743  const char *zStartMark,     /* Markup to appear before each match */
106744  const char *zEndMark,       /* Markup to appear after each match */
106745  const char *zEllipsis       /* Ellipsis mark */
106746){
106747  int i, j;
106748  struct snippetMatch *aMatch;
106749  int nMatch;
106750  int nDesired;
106751  StringBuffer sb;
106752  int tailCol;
106753  int tailOffset;
106754  int iCol;
106755  int nDoc;
106756  const char *zDoc;
106757  int iStart, iEnd;
106758  int tailEllipsis = 0;
106759  int iMatch;
106760
106761
106762  sqlite3_free(pSnippet->zSnippet);
106763  pSnippet->zSnippet = 0;
106764  aMatch = pSnippet->aMatch;
106765  nMatch = pSnippet->nMatch;
106766  fts3SnippetSbInit(&sb);
106767
106768  for(i=0; i<nMatch; i++){
106769    aMatch[i].snStatus = SNIPPET_IGNORE;
106770  }
106771  nDesired = 0;
106772  for(i=0; i<FTS3_ROTOR_SZ; i++){
106773    for(j=0; j<nMatch; j++){
106774      if( aMatch[j].iTerm==i ){
106775        aMatch[j].snStatus = SNIPPET_DESIRED;
106776        nDesired++;
106777        break;
106778      }
106779    }
106780  }
106781
106782  iMatch = 0;
106783  tailCol = -1;
106784  tailOffset = 0;
106785  for(i=0; i<nMatch && nDesired>0; i++){
106786    if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
106787    nDesired--;
106788    iCol = aMatch[i].iCol;
106789    zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
106790    nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
106791    iStart = aMatch[i].iStart - 40;
106792    iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
106793    if( iStart<=10 ){
106794      iStart = 0;
106795    }
106796    if( iCol==tailCol && iStart<=tailOffset+20 ){
106797      iStart = tailOffset;
106798    }
106799    if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
106800      fts3SnippetTrimWhiteSpace(&sb);
106801      fts3SnippetAppendWhiteSpace(&sb);
106802      fts3SnippetAppend(&sb, zEllipsis, -1);
106803      fts3SnippetAppendWhiteSpace(&sb);
106804    }
106805    iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
106806    iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
106807    if( iEnd>=nDoc-10 ){
106808      iEnd = nDoc;
106809      tailEllipsis = 0;
106810    }else{
106811      tailEllipsis = 1;
106812    }
106813    while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
106814    while( iStart<iEnd ){
106815      while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
106816             && aMatch[iMatch].iCol<=iCol ){
106817        iMatch++;
106818      }
106819      if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
106820             && aMatch[iMatch].iCol==iCol ){
106821        fts3SnippetAppend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
106822        iStart = aMatch[iMatch].iStart;
106823        fts3SnippetAppend(&sb, zStartMark, -1);
106824        fts3SnippetAppend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
106825        fts3SnippetAppend(&sb, zEndMark, -1);
106826        iStart += aMatch[iMatch].nByte;
106827        for(j=iMatch+1; j<nMatch; j++){
106828          if( aMatch[j].iTerm==aMatch[iMatch].iTerm
106829              && aMatch[j].snStatus==SNIPPET_DESIRED ){
106830            nDesired--;
106831            aMatch[j].snStatus = SNIPPET_IGNORE;
106832          }
106833        }
106834      }else{
106835        fts3SnippetAppend(&sb, &zDoc[iStart], iEnd - iStart);
106836        iStart = iEnd;
106837      }
106838    }
106839    tailCol = iCol;
106840    tailOffset = iEnd;
106841  }
106842  fts3SnippetTrimWhiteSpace(&sb);
106843  if( tailEllipsis ){
106844    fts3SnippetAppendWhiteSpace(&sb);
106845    fts3SnippetAppend(&sb, zEllipsis, -1);
106846  }
106847  pSnippet->zSnippet = sb.z;
106848  pSnippet->nSnippet = sb.z ? sb.nUsed : 0;
106849}
106850
106851SQLITE_PRIVATE void sqlite3Fts3Offsets(
106852  sqlite3_context *pCtx,          /* SQLite function call context */
106853  Fts3Cursor *pCsr                /* Cursor object */
106854){
106855  Snippet *p;                     /* Snippet structure */
106856  int rc = snippetAllOffsets(pCsr, &p);
106857  if( rc==SQLITE_OK ){
106858    snippetOffsetText(p);
106859    if( p->zOffset ){
106860      sqlite3_result_text(pCtx, p->zOffset, p->nOffset, SQLITE_TRANSIENT);
106861    }else{
106862      sqlite3_result_error_nomem(pCtx);
106863    }
106864  }else{
106865    sqlite3_result_error_nomem(pCtx);
106866  }
106867  fts3SnippetFree(p);
106868}
106869
106870SQLITE_PRIVATE void sqlite3Fts3Snippet(
106871  sqlite3_context *pCtx,          /* SQLite function call context */
106872  Fts3Cursor *pCsr,               /* Cursor object */
106873  const char *zStart,             /* Snippet start text - "<b>" */
106874  const char *zEnd,               /* Snippet end text - "</b>" */
106875  const char *zEllipsis           /* Snippet ellipsis text - "<b>...</b>" */
106876){
106877  Snippet *p;                     /* Snippet structure */
106878  int rc = snippetAllOffsets(pCsr, &p);
106879  if( rc==SQLITE_OK ){
106880    snippetText(pCsr, p, zStart, zEnd, zEllipsis);
106881    if( p->zSnippet ){
106882      sqlite3_result_text(pCtx, p->zSnippet, p->nSnippet, SQLITE_TRANSIENT);
106883    }else{
106884      sqlite3_result_error_nomem(pCtx);
106885    }
106886  }else{
106887    sqlite3_result_error_nomem(pCtx);
106888  }
106889  fts3SnippetFree(p);
106890}
106891
106892/*************************************************************************
106893** Below this point is the alternative, experimental snippet() implementation.
106894*/
106895
106896#define SNIPPET_BUFFER_CHUNK  64
106897#define SNIPPET_BUFFER_SIZE   SNIPPET_BUFFER_CHUNK*4
106898#define SNIPPET_BUFFER_MASK   (SNIPPET_BUFFER_SIZE-1)
106899
106900static void fts3GetDeltaPosition(char **pp, int *piPos){
106901  int iVal;
106902  *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
106903  *piPos += (iVal-2);
106904}
106905
106906/*
106907** Iterate through all phrase nodes in an FTS3 query, except those that
106908** are part of a sub-tree that is the right-hand-side of a NOT operator.
106909** For each phrase node found, the supplied callback function is invoked.
106910**
106911** If the callback function returns anything other than SQLITE_OK,
106912** the iteration is abandoned and the error code returned immediately.
106913** Otherwise, SQLITE_OK is returned after a callback has been made for
106914** all eligible phrase nodes.
106915*/
106916static int fts3ExprIterate(
106917  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
106918  int (*x)(Fts3Expr *, void *),   /* Callback function to invoke for phrases */
106919  void *pCtx                      /* Second argument to pass to callback */
106920){
106921  int rc;
106922  int eType = pExpr->eType;
106923  if( eType==FTSQUERY_NOT ){
106924    rc = SQLITE_OK;
106925  }else if( eType!=FTSQUERY_PHRASE ){
106926    assert( pExpr->pLeft && pExpr->pRight );
106927    rc = fts3ExprIterate(pExpr->pLeft, x, pCtx);
106928    if( rc==SQLITE_OK ){
106929      rc = fts3ExprIterate(pExpr->pRight, x, pCtx);
106930    }
106931  }else{
106932    rc = x(pExpr, pCtx);
106933  }
106934  return rc;
106935}
106936
106937typedef struct LoadDoclistCtx LoadDoclistCtx;
106938struct LoadDoclistCtx {
106939  Fts3Table *pTab;                /* FTS3 Table */
106940  int nPhrase;                    /* Number of phrases so far */
106941};
106942
106943static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, void *ctx){
106944  int rc = SQLITE_OK;
106945  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
106946  p->nPhrase++;
106947  if( pExpr->isLoaded==0 ){
106948    rc = sqlite3Fts3ExprLoadDoclist(p->pTab, pExpr);
106949    pExpr->isLoaded = 1;
106950    if( rc==SQLITE_OK && pExpr->aDoclist ){
106951      pExpr->pCurrent = pExpr->aDoclist;
106952      pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent,&pExpr->iCurrent);
106953    }
106954  }
106955  return rc;
106956}
106957
106958static int fts3ExprLoadDoclists(Fts3Cursor *pCsr, int *pnPhrase){
106959  int rc;
106960  LoadDoclistCtx sCtx = {0, 0};
106961  sCtx.pTab = (Fts3Table *)pCsr->base.pVtab;
106962  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
106963  *pnPhrase = sCtx.nPhrase;
106964  return rc;
106965}
106966
106967/*
106968** Each call to this function populates a chunk of a snippet-buffer
106969** SNIPPET_BUFFER_CHUNK bytes in size.
106970**
106971** Return true if the end of the data has been reached (and all subsequent
106972** calls to fts3LoadSnippetBuffer() with the same arguments will be no-ops),
106973** or false otherwise.
106974*/
106975static int fts3LoadSnippetBuffer(
106976  int iPos,                       /* Document token offset to load data for */
106977  u8 *aBuffer,                    /* Circular snippet buffer to populate */
106978  int nList,                      /* Number of position lists in appList */
106979  char **apList,                  /* IN/OUT: nList position list pointers */
106980  int *aiPrev                     /* IN/OUT: Previous positions read */
106981){
106982  int i;
106983  int nFin = 0;
106984
106985  assert( (iPos&(SNIPPET_BUFFER_CHUNK-1))==0 );
106986
106987  memset(&aBuffer[iPos&SNIPPET_BUFFER_MASK], 0, SNIPPET_BUFFER_CHUNK);
106988
106989  for(i=0; i<nList; i++){
106990    int iPrev = aiPrev[i];
106991    char *pList = apList[i];
106992
106993    if( !pList ){
106994      nFin++;
106995      continue;
106996    }
106997
106998    while( iPrev<(iPos+SNIPPET_BUFFER_CHUNK) ){
106999      if( iPrev>=iPos ){
107000        aBuffer[iPrev&SNIPPET_BUFFER_MASK] = (u8)(i+1);
107001      }
107002      if( 0==((*pList)&0xFE) ){
107003        nFin++;
107004        break;
107005      }
107006      fts3GetDeltaPosition(&pList, &iPrev);
107007    }
107008
107009    aiPrev[i] = iPrev;
107010    apList[i] = pList;
107011  }
107012
107013  return (nFin==nList);
107014}
107015
107016typedef struct SnippetCtx SnippetCtx;
107017struct SnippetCtx {
107018  Fts3Cursor *pCsr;
107019  int iCol;
107020  int iPhrase;
107021  int *aiPrev;
107022  int *anToken;
107023  char **apList;
107024};
107025
107026static int fts3SnippetFindPositions(Fts3Expr *pExpr, void *ctx){
107027  SnippetCtx *p = (SnippetCtx *)ctx;
107028  int iPhrase = p->iPhrase++;
107029  char *pCsr;
107030
107031  p->anToken[iPhrase] = pExpr->pPhrase->nToken;
107032  pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
107033
107034  if( pCsr ){
107035    int iVal;
107036    pCsr += sqlite3Fts3GetVarint32(pCsr, &iVal);
107037    p->apList[iPhrase] = pCsr;
107038    p->aiPrev[iPhrase] = iVal-2;
107039  }
107040  return SQLITE_OK;
107041}
107042
107043static void fts3SnippetCnt(
107044  int iIdx,
107045  int nSnippet,
107046  int *anCnt,
107047  u8 *aBuffer,
107048  int *anToken,
107049  u64 *pHlmask
107050){
107051  int iSub =  (iIdx-1)&SNIPPET_BUFFER_MASK;
107052  int iAdd =  (iIdx+nSnippet-1)&SNIPPET_BUFFER_MASK;
107053  int iSub2 = (iIdx+(nSnippet/3)-1)&SNIPPET_BUFFER_MASK;
107054  int iAdd2 = (iIdx+(nSnippet*2/3)-1)&SNIPPET_BUFFER_MASK;
107055
107056  u64 h = *pHlmask;
107057
107058  anCnt[ aBuffer[iSub]  ]--;
107059  anCnt[ aBuffer[iSub2] ]--;
107060  anCnt[ aBuffer[iAdd]  ]++;
107061  anCnt[ aBuffer[iAdd2] ]++;
107062
107063  h = h >> 1;
107064  if( aBuffer[iAdd] ){
107065    int j;
107066    for(j=anToken[aBuffer[iAdd]-1]; j>=1; j--){
107067      h |= (u64)1 << (nSnippet-j);
107068    }
107069  }
107070  *pHlmask = h;
107071}
107072
107073static int fts3SnippetScore(int n, int *anCnt){
107074  int j;
107075  int iScore = 0;
107076  for(j=1; j<=n; j++){
107077    int nCnt = anCnt[j];
107078    iScore += nCnt + (nCnt ? 1000 : 0);
107079  }
107080  return iScore;
107081}
107082
107083static int fts3BestSnippet(
107084  int nSnippet,                   /* Desired snippet length */
107085  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
107086  int iCol,                       /* Index of column to create snippet from */
107087  int *piPos,                     /* OUT: Starting token for best snippet */
107088  u64 *pHlmask                    /* OUT: Highlight mask for best snippet */
107089){
107090  int rc;                         /* Return Code */
107091  u8 aBuffer[SNIPPET_BUFFER_SIZE];/* Circular snippet buffer */
107092  int *aiPrev;                    /* Used by fts3LoadSnippetBuffer() */
107093  int *anToken;                   /* Number of tokens in each phrase */
107094  char **apList;                  /* Array of position lists */
107095  int *anCnt;                     /* Running totals of phrase occurences */
107096  int nList;
107097
107098  int i;
107099
107100  u64 hlmask = 0;                 /* Current mask of highlighted terms */
107101  u64 besthlmask = 0;             /* Mask of highlighted terms for iBestPos */
107102  int iBestPos = 0;               /* Starting position of 'best' snippet */
107103  int iBestScore = 0;             /* Score of best snippet higher->better */
107104  SnippetCtx sCtx;
107105
107106  /* Iterate through the phrases in the expression to count them. The same
107107  ** callback makes sure the doclists are loaded for each phrase.
107108  */
107109  rc = fts3ExprLoadDoclists(pCsr, &nList);
107110  if( rc!=SQLITE_OK ){
107111    return rc;
107112  }
107113
107114  /* Now that it is known how many phrases there are, allocate and zero
107115  ** the required arrays using malloc().
107116  */
107117  apList = sqlite3_malloc(
107118      sizeof(u8*)*nList +         /* apList */
107119      sizeof(int)*(nList) +       /* anToken */
107120      sizeof(int)*nList +         /* aiPrev */
107121      sizeof(int)*(nList+1)       /* anCnt */
107122  );
107123  if( !apList ){
107124    return SQLITE_NOMEM;
107125  }
107126  memset(apList, 0, sizeof(u8*)*nList+sizeof(int)*nList+sizeof(int)*nList);
107127  anToken = (int *)&apList[nList];
107128  aiPrev = &anToken[nList];
107129  anCnt = &aiPrev[nList];
107130
107131  /* Initialize the contents of the aiPrev and aiList arrays. */
107132  sCtx.pCsr = pCsr;
107133  sCtx.iCol = iCol;
107134  sCtx.apList = apList;
107135  sCtx.aiPrev = aiPrev;
107136  sCtx.anToken = anToken;
107137  sCtx.iPhrase = 0;
107138  (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sCtx);
107139
107140  /* Load the first two chunks of data into the buffer. */
107141  memset(aBuffer, 0, SNIPPET_BUFFER_SIZE);
107142  fts3LoadSnippetBuffer(0, aBuffer, nList, apList, aiPrev);
107143  fts3LoadSnippetBuffer(SNIPPET_BUFFER_CHUNK, aBuffer, nList, apList, aiPrev);
107144
107145  /* Set the initial contents of the highlight-mask and anCnt[] array. */
107146  for(i=1-nSnippet; i<=0; i++){
107147    fts3SnippetCnt(i, nSnippet, anCnt, aBuffer, anToken, &hlmask);
107148  }
107149  iBestScore = fts3SnippetScore(nList, anCnt);
107150  besthlmask = hlmask;
107151  iBestPos = 0;
107152
107153  for(i=1; 1; i++){
107154    int iScore;
107155
107156    if( 0==(i&(SNIPPET_BUFFER_CHUNK-1)) ){
107157      int iLoad = i + SNIPPET_BUFFER_CHUNK;
107158      if( fts3LoadSnippetBuffer(iLoad, aBuffer, nList, apList, aiPrev) ) break;
107159    }
107160
107161    /* Figure out how highly a snippet starting at token offset i scores
107162    ** according to fts3SnippetScore(). If it is higher than any previously
107163    ** considered position, save the current position, score and hlmask as
107164    ** the best snippet candidate found so far.
107165    */
107166    fts3SnippetCnt(i, nSnippet, anCnt, aBuffer, anToken, &hlmask);
107167    iScore = fts3SnippetScore(nList, anCnt);
107168    if( iScore>iBestScore ){
107169      iBestPos = i;
107170      iBestScore = iScore;
107171      besthlmask = hlmask;
107172    }
107173  }
107174
107175  sqlite3_free(apList);
107176  *piPos = iBestPos;
107177  *pHlmask = besthlmask;
107178  return SQLITE_OK;
107179}
107180
107181typedef struct StrBuffer StrBuffer;
107182struct StrBuffer {
107183  char *z;
107184  int n;
107185  int nAlloc;
107186};
107187
107188static int fts3StringAppend(
107189  StrBuffer *pStr,
107190  const char *zAppend,
107191  int nAppend
107192){
107193  if( nAppend<0 ){
107194    nAppend = (int)strlen(zAppend);
107195  }
107196
107197  if( pStr->n+nAppend+1>=pStr->nAlloc ){
107198    int nAlloc = pStr->nAlloc+nAppend+100;
107199    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
107200    if( !zNew ){
107201      return SQLITE_NOMEM;
107202    }
107203    pStr->z = zNew;
107204    pStr->nAlloc = nAlloc;
107205  }
107206
107207  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
107208  pStr->n += nAppend;
107209  pStr->z[pStr->n] = '\0';
107210
107211  return SQLITE_OK;
107212}
107213
107214static int fts3SnippetText(
107215  Fts3Cursor *pCsr,               /* FTS3 Cursor */
107216  const char *zDoc,               /* Document to extract snippet from */
107217  int nDoc,                       /* Size of zDoc in bytes */
107218  int nSnippet,                   /* Number of tokens in extracted snippet */
107219  int iPos,                       /* Index of first document token in snippet */
107220  u64 hlmask,                     /* Bitmask of terms to highlight in snippet */
107221  const char *zOpen,              /* String inserted before highlighted term */
107222  const char *zClose,             /* String inserted after highlighted term */
107223  const char *zEllipsis,
107224  char **pzSnippet                /* OUT: Snippet text */
107225){
107226  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
107227  int rc;                         /* Return code */
107228  int iCurrent = 0;
107229  int iStart = 0;
107230  int iEnd;
107231
107232  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
107233  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
107234  const char *ZDUMMY;             /* Dummy arguments used with tokenizer */
107235  int DUMMY1, DUMMY2, DUMMY3;     /* Dummy arguments used with tokenizer */
107236
107237  StrBuffer res = {0, 0, 0};   /* Result string */
107238
107239  /* Open a token cursor on the document. Read all tokens up to and
107240  ** including token iPos (the first token of the snippet). Set variable
107241  ** iStart to the byte offset in zDoc of the start of token iPos.
107242  */
107243  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
107244  rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
107245  while( rc==SQLITE_OK && iCurrent<iPos ){
107246    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iStart, &DUMMY2, &iCurrent);
107247  }
107248  iEnd = iStart;
107249
107250  if( rc==SQLITE_OK && iStart>0 ){
107251    rc = fts3StringAppend(&res, zEllipsis, -1);
107252  }
107253
107254  while( rc==SQLITE_OK ){
107255    int iBegin;
107256    int iFin;
107257    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
107258
107259    if( rc==SQLITE_OK ){
107260      if( iCurrent>=(iPos+nSnippet) ){
107261        rc = SQLITE_DONE;
107262      }else{
107263        iEnd = iFin;
107264        if( hlmask & ((u64)1 << (iCurrent-iPos)) ){
107265          if( fts3StringAppend(&res, &zDoc[iStart], iBegin-iStart)
107266           || fts3StringAppend(&res, zOpen, -1)
107267           || fts3StringAppend(&res, &zDoc[iBegin], iEnd-iBegin)
107268           || fts3StringAppend(&res, zClose, -1)
107269          ){
107270            rc = SQLITE_NOMEM;
107271          }
107272          iStart = iEnd;
107273        }
107274      }
107275    }
107276  }
107277  assert( rc!=SQLITE_OK );
107278  if( rc==SQLITE_DONE ){
107279    rc = fts3StringAppend(&res, &zDoc[iStart], iEnd-iStart);
107280    if( rc==SQLITE_OK ){
107281      rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
107282      if( rc==SQLITE_OK ){
107283        rc = fts3StringAppend(&res, zEllipsis, -1);
107284      }else if( rc==SQLITE_DONE ){
107285        rc = fts3StringAppend(&res, &zDoc[iEnd], -1);
107286      }
107287    }
107288  }
107289
107290  pMod->xClose(pC);
107291  if( rc!=SQLITE_OK ){
107292    sqlite3_free(res.z);
107293  }else{
107294    *pzSnippet = res.z;
107295  }
107296  return rc;
107297}
107298
107299
107300/*
107301** An instance of this structure is used to collect the 'global' part of
107302** the matchinfo statistics. The 'global' part consists of the following:
107303**
107304**   1. The number of phrases in the query (nPhrase).
107305**
107306**   2. The number of columns in the FTS3 table (nCol).
107307**
107308**   3. A matrix of (nPhrase*nCol) integers containing the sum of the
107309**      number of hits for each phrase in each column across all rows
107310**      of the table.
107311**
107312** The total size of the global matchinfo array, assuming the number of
107313** columns is N and the number of phrases is P is:
107314**
107315**   2 + P*(N+1)
107316**
107317** The number of hits for the 3rd phrase in the second column is found
107318** using the expression:
107319**
107320**   aGlobal[2 + P*(1+2) + 1]
107321*/
107322typedef struct MatchInfo MatchInfo;
107323struct MatchInfo {
107324  Fts3Table *pTab;                /* FTS3 Table */
107325  Fts3Cursor *pCursor;            /* FTS3 Cursor */
107326  int iPhrase;                    /* Number of phrases so far */
107327  int nCol;                       /* Number of columns in table */
107328  u32 *aGlobal;                   /* Pre-allocated buffer */
107329};
107330
107331/*
107332** This function is used to count the entries in a column-list (delta-encoded
107333** list of term offsets within a single column of a single row).
107334*/
107335static int fts3ColumnlistCount(char **ppCollist){
107336  char *pEnd = *ppCollist;
107337  char c = 0;
107338  int nEntry = 0;
107339
107340  /* A column-list is terminated by either a 0x01 or 0x00. */
107341  while( 0xFE & (*pEnd | c) ){
107342    c = *pEnd++ & 0x80;
107343    if( !c ) nEntry++;
107344  }
107345
107346  *ppCollist = pEnd;
107347  return nEntry;
107348}
107349
107350static void fts3LoadColumnlistCounts(char **pp, u32 *aOut){
107351  char *pCsr = *pp;
107352  while( *pCsr ){
107353    sqlite3_int64 iCol = 0;
107354    if( *pCsr==0x01 ){
107355      pCsr++;
107356      pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
107357    }
107358    aOut[iCol] += fts3ColumnlistCount(&pCsr);
107359  }
107360  pCsr++;
107361  *pp = pCsr;
107362}
107363
107364/*
107365** fts3ExprIterate() callback used to collect the "global" matchinfo stats
107366** for a single query.
107367*/
107368static int fts3ExprGlobalMatchinfoCb(
107369  Fts3Expr *pExpr,                /* Phrase expression node */
107370  void *pCtx                      /* Pointer to MatchInfo structure */
107371){
107372  MatchInfo *p = (MatchInfo *)pCtx;
107373  char *pCsr;
107374  char *pEnd;
107375  const int iStart = 2 + p->nCol*p->iPhrase;
107376
107377  assert( pExpr->isLoaded );
107378
107379  /* Fill in the global hit count matrix row for this phrase. */
107380  pCsr = pExpr->aDoclist;
107381  pEnd = &pExpr->aDoclist[pExpr->nDoclist];
107382  while( pCsr<pEnd ){
107383    while( *pCsr++ & 0x80 );
107384    fts3LoadColumnlistCounts(&pCsr, &p->aGlobal[iStart]);
107385  }
107386
107387  p->iPhrase++;
107388  return SQLITE_OK;
107389}
107390
107391static int fts3ExprLocalMatchinfoCb(
107392  Fts3Expr *pExpr,                /* Phrase expression node */
107393  void *pCtx                      /* Pointer to MatchInfo structure */
107394){
107395  MatchInfo *p = (MatchInfo *)pCtx;
107396  int iPhrase = p->iPhrase++;
107397
107398  if( pExpr->aDoclist ){
107399    char *pCsr;
107400    int iOffset = 2 + p->nCol*(p->aGlobal[0]+iPhrase);
107401
107402    memset(&p->aGlobal[iOffset], 0, p->nCol*sizeof(u32));
107403    pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
107404    if( pCsr ) fts3LoadColumnlistCounts(&pCsr, &p->aGlobal[iOffset]);
107405  }
107406
107407  return SQLITE_OK;
107408}
107409
107410/*
107411** Populate pCsr->aMatchinfo[] with data for the current row. The 'matchinfo'
107412** data is an array of 32-bit unsigned integers (C type u32).
107413*/
107414static int fts3GetMatchinfo(Fts3Cursor *pCsr){
107415  MatchInfo g;
107416  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
107417  if( pCsr->aMatchinfo==0 ){
107418    int rc;
107419    int nPhrase;
107420    int nMatchinfo;
107421
107422    g.pTab = pTab;
107423    g.nCol = pTab->nColumn;
107424    g.iPhrase = 0;
107425    rc = fts3ExprLoadDoclists(pCsr, &nPhrase);
107426    if( rc!=SQLITE_OK ){
107427      return rc;
107428    }
107429
107430    nMatchinfo = 2 + 2*g.nCol*nPhrase;
107431
107432    g.iPhrase = 0;
107433    g.aGlobal = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo);
107434    if( !g.aGlobal ){
107435      return SQLITE_NOMEM;
107436    }
107437    memset(g.aGlobal, 0, sizeof(u32)*nMatchinfo);
107438
107439    g.aGlobal[0] = nPhrase;
107440    g.aGlobal[1] = g.nCol;
107441    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprGlobalMatchinfoCb, (void *)&g);
107442
107443    pCsr->aMatchinfo = g.aGlobal;
107444  }
107445
107446  g.pTab = pTab;
107447  g.pCursor = pCsr;
107448  g.nCol = pTab->nColumn;
107449  g.iPhrase = 0;
107450  g.aGlobal = pCsr->aMatchinfo;
107451
107452  if( pCsr->isMatchinfoOk ){
107453    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLocalMatchinfoCb, (void *)&g);
107454    pCsr->isMatchinfoOk = 0;
107455  }
107456
107457  return SQLITE_OK;
107458}
107459
107460SQLITE_PRIVATE void sqlite3Fts3Snippet2(
107461  sqlite3_context *pCtx,          /* SQLite function call context */
107462  Fts3Cursor *pCsr,               /* Cursor object */
107463  const char *zStart,             /* Snippet start text - "<b>" */
107464  const char *zEnd,               /* Snippet end text - "</b>" */
107465  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
107466  int iCol,                       /* Extract snippet from this column */
107467  int nToken                      /* Approximate number of tokens in snippet */
107468){
107469  int rc;
107470  int iPos = 0;
107471  u64 hlmask = 0;
107472  char *z = 0;
107473  int nDoc;
107474  const char *zDoc;
107475
107476  rc = fts3BestSnippet(nToken, pCsr, iCol, &iPos, &hlmask);
107477
107478  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
107479  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
107480
107481  if( rc==SQLITE_OK ){
107482    rc = fts3SnippetText(
107483        pCsr, zDoc, nDoc, nToken, iPos, hlmask, zStart, zEnd, zEllipsis, &z);
107484  }
107485  if( rc!=SQLITE_OK ){
107486    sqlite3_result_error_code(pCtx, rc);
107487  }else{
107488    sqlite3_result_text(pCtx, z, -1, sqlite3_free);
107489  }
107490}
107491
107492SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *pContext, Fts3Cursor *pCsr){
107493  int rc = fts3GetMatchinfo(pCsr);
107494  if( rc!=SQLITE_OK ){
107495    sqlite3_result_error_code(pContext, rc);
107496  }else{
107497    int n = sizeof(u32)*(2+pCsr->aMatchinfo[0]*pCsr->aMatchinfo[1]*2);
107498    sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
107499  }
107500}
107501
107502#endif
107503
107504/************** End of fts3_snippet.c ****************************************/
107505/************** Begin file rtree.c *******************************************/
107506/*
107507** 2001 September 15
107508**
107509** The author disclaims copyright to this source code.  In place of
107510** a legal notice, here is a blessing:
107511**
107512**    May you do good and not evil.
107513**    May you find forgiveness for yourself and forgive others.
107514**    May you share freely, never taking more than you give.
107515**
107516*************************************************************************
107517** This file contains code for implementations of the r-tree and r*-tree
107518** algorithms packaged as an SQLite virtual table module.
107519*/
107520
107521#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
107522
107523/*
107524** This file contains an implementation of a couple of different variants
107525** of the r-tree algorithm. See the README file for further details. The
107526** same data-structure is used for all, but the algorithms for insert and
107527** delete operations vary. The variants used are selected at compile time
107528** by defining the following symbols:
107529*/
107530
107531/* Either, both or none of the following may be set to activate
107532** r*tree variant algorithms.
107533*/
107534#define VARIANT_RSTARTREE_CHOOSESUBTREE 0
107535#define VARIANT_RSTARTREE_REINSERT      1
107536
107537/*
107538** Exactly one of the following must be set to 1.
107539*/
107540#define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
107541#define VARIANT_GUTTMAN_LINEAR_SPLIT    0
107542#define VARIANT_RSTARTREE_SPLIT         1
107543
107544#define VARIANT_GUTTMAN_SPLIT \
107545        (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
107546
107547#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
107548  #define PickNext QuadraticPickNext
107549  #define PickSeeds QuadraticPickSeeds
107550  #define AssignCells splitNodeGuttman
107551#endif
107552#if VARIANT_GUTTMAN_LINEAR_SPLIT
107553  #define PickNext LinearPickNext
107554  #define PickSeeds LinearPickSeeds
107555  #define AssignCells splitNodeGuttman
107556#endif
107557#if VARIANT_RSTARTREE_SPLIT
107558  #define AssignCells splitNodeStartree
107559#endif
107560
107561
107562#ifndef SQLITE_CORE
107563  SQLITE_EXTENSION_INIT1
107564#else
107565#endif
107566
107567
107568#ifndef SQLITE_AMALGAMATION
107569typedef sqlite3_int64 i64;
107570typedef unsigned char u8;
107571typedef unsigned int u32;
107572#endif
107573
107574typedef struct Rtree Rtree;
107575typedef struct RtreeCursor RtreeCursor;
107576typedef struct RtreeNode RtreeNode;
107577typedef struct RtreeCell RtreeCell;
107578typedef struct RtreeConstraint RtreeConstraint;
107579typedef union RtreeCoord RtreeCoord;
107580
107581/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
107582#define RTREE_MAX_DIMENSIONS 5
107583
107584/* Size of hash table Rtree.aHash. This hash table is not expected to
107585** ever contain very many entries, so a fixed number of buckets is
107586** used.
107587*/
107588#define HASHSIZE 128
107589
107590/*
107591** An rtree virtual-table object.
107592*/
107593struct Rtree {
107594  sqlite3_vtab base;
107595  sqlite3 *db;                /* Host database connection */
107596  int iNodeSize;              /* Size in bytes of each node in the node table */
107597  int nDim;                   /* Number of dimensions */
107598  int nBytesPerCell;          /* Bytes consumed per cell */
107599  int iDepth;                 /* Current depth of the r-tree structure */
107600  char *zDb;                  /* Name of database containing r-tree table */
107601  char *zName;                /* Name of r-tree table */
107602  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
107603  int nBusy;                  /* Current number of users of this structure */
107604
107605  /* List of nodes removed during a CondenseTree operation. List is
107606  ** linked together via the pointer normally used for hash chains -
107607  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
107608  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
107609  */
107610  RtreeNode *pDeleted;
107611  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
107612
107613  /* Statements to read/write/delete a record from xxx_node */
107614  sqlite3_stmt *pReadNode;
107615  sqlite3_stmt *pWriteNode;
107616  sqlite3_stmt *pDeleteNode;
107617
107618  /* Statements to read/write/delete a record from xxx_rowid */
107619  sqlite3_stmt *pReadRowid;
107620  sqlite3_stmt *pWriteRowid;
107621  sqlite3_stmt *pDeleteRowid;
107622
107623  /* Statements to read/write/delete a record from xxx_parent */
107624  sqlite3_stmt *pReadParent;
107625  sqlite3_stmt *pWriteParent;
107626  sqlite3_stmt *pDeleteParent;
107627
107628  int eCoordType;
107629};
107630
107631/* Possible values for eCoordType: */
107632#define RTREE_COORD_REAL32 0
107633#define RTREE_COORD_INT32  1
107634
107635/*
107636** The minimum number of cells allowed for a node is a third of the
107637** maximum. In Gutman's notation:
107638**
107639**     m = M/3
107640**
107641** If an R*-tree "Reinsert" operation is required, the same number of
107642** cells are removed from the overfull node and reinserted into the tree.
107643*/
107644#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
107645#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
107646#define RTREE_MAXCELLS 51
107647
107648/*
107649** An rtree cursor object.
107650*/
107651struct RtreeCursor {
107652  sqlite3_vtab_cursor base;
107653  RtreeNode *pNode;                 /* Node cursor is currently pointing at */
107654  int iCell;                        /* Index of current cell in pNode */
107655  int iStrategy;                    /* Copy of idxNum search parameter */
107656  int nConstraint;                  /* Number of entries in aConstraint */
107657  RtreeConstraint *aConstraint;     /* Search constraints. */
107658};
107659
107660union RtreeCoord {
107661  float f;
107662  int i;
107663};
107664
107665/*
107666** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
107667** formatted as a double. This macro assumes that local variable pRtree points
107668** to the Rtree structure associated with the RtreeCoord.
107669*/
107670#define DCOORD(coord) (                           \
107671  (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
107672    ((double)coord.f) :                           \
107673    ((double)coord.i)                             \
107674)
107675
107676/*
107677** A search constraint.
107678*/
107679struct RtreeConstraint {
107680  int iCoord;                       /* Index of constrained coordinate */
107681  int op;                           /* Constraining operation */
107682  double rValue;                    /* Constraint value. */
107683};
107684
107685/* Possible values for RtreeConstraint.op */
107686#define RTREE_EQ 0x41
107687#define RTREE_LE 0x42
107688#define RTREE_LT 0x43
107689#define RTREE_GE 0x44
107690#define RTREE_GT 0x45
107691
107692/*
107693** An rtree structure node.
107694**
107695** Data format (RtreeNode.zData):
107696**
107697**   1. If the node is the root node (node 1), then the first 2 bytes
107698**      of the node contain the tree depth as a big-endian integer.
107699**      For non-root nodes, the first 2 bytes are left unused.
107700**
107701**   2. The next 2 bytes contain the number of entries currently
107702**      stored in the node.
107703**
107704**   3. The remainder of the node contains the node entries. Each entry
107705**      consists of a single 8-byte integer followed by an even number
107706**      of 4-byte coordinates. For leaf nodes the integer is the rowid
107707**      of a record. For internal nodes it is the node number of a
107708**      child page.
107709*/
107710struct RtreeNode {
107711  RtreeNode *pParent;               /* Parent node */
107712  i64 iNode;
107713  int nRef;
107714  int isDirty;
107715  u8 *zData;
107716  RtreeNode *pNext;                 /* Next node in this hash chain */
107717};
107718#define NCELL(pNode) readInt16(&(pNode)->zData[2])
107719
107720/*
107721** Structure to store a deserialized rtree record.
107722*/
107723struct RtreeCell {
107724  i64 iRowid;
107725  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
107726};
107727
107728#ifndef MAX
107729# define MAX(x,y) ((x) < (y) ? (y) : (x))
107730#endif
107731#ifndef MIN
107732# define MIN(x,y) ((x) > (y) ? (y) : (x))
107733#endif
107734
107735/*
107736** Functions to deserialize a 16 bit integer, 32 bit real number and
107737** 64 bit integer. The deserialized value is returned.
107738*/
107739static int readInt16(u8 *p){
107740  return (p[0]<<8) + p[1];
107741}
107742static void readCoord(u8 *p, RtreeCoord *pCoord){
107743  u32 i = (
107744    (((u32)p[0]) << 24) +
107745    (((u32)p[1]) << 16) +
107746    (((u32)p[2]) <<  8) +
107747    (((u32)p[3]) <<  0)
107748  );
107749  *(u32 *)pCoord = i;
107750}
107751static i64 readInt64(u8 *p){
107752  return (
107753    (((i64)p[0]) << 56) +
107754    (((i64)p[1]) << 48) +
107755    (((i64)p[2]) << 40) +
107756    (((i64)p[3]) << 32) +
107757    (((i64)p[4]) << 24) +
107758    (((i64)p[5]) << 16) +
107759    (((i64)p[6]) <<  8) +
107760    (((i64)p[7]) <<  0)
107761  );
107762}
107763
107764/*
107765** Functions to serialize a 16 bit integer, 32 bit real number and
107766** 64 bit integer. The value returned is the number of bytes written
107767** to the argument buffer (always 2, 4 and 8 respectively).
107768*/
107769static int writeInt16(u8 *p, int i){
107770  p[0] = (i>> 8)&0xFF;
107771  p[1] = (i>> 0)&0xFF;
107772  return 2;
107773}
107774static int writeCoord(u8 *p, RtreeCoord *pCoord){
107775  u32 i;
107776  assert( sizeof(RtreeCoord)==4 );
107777  assert( sizeof(u32)==4 );
107778  i = *(u32 *)pCoord;
107779  p[0] = (i>>24)&0xFF;
107780  p[1] = (i>>16)&0xFF;
107781  p[2] = (i>> 8)&0xFF;
107782  p[3] = (i>> 0)&0xFF;
107783  return 4;
107784}
107785static int writeInt64(u8 *p, i64 i){
107786  p[0] = (i>>56)&0xFF;
107787  p[1] = (i>>48)&0xFF;
107788  p[2] = (i>>40)&0xFF;
107789  p[3] = (i>>32)&0xFF;
107790  p[4] = (i>>24)&0xFF;
107791  p[5] = (i>>16)&0xFF;
107792  p[6] = (i>> 8)&0xFF;
107793  p[7] = (i>> 0)&0xFF;
107794  return 8;
107795}
107796
107797/*
107798** Increment the reference count of node p.
107799*/
107800static void nodeReference(RtreeNode *p){
107801  if( p ){
107802    p->nRef++;
107803  }
107804}
107805
107806/*
107807** Clear the content of node p (set all bytes to 0x00).
107808*/
107809static void nodeZero(Rtree *pRtree, RtreeNode *p){
107810  if( p ){
107811    memset(&p->zData[2], 0, pRtree->iNodeSize-2);
107812    p->isDirty = 1;
107813  }
107814}
107815
107816/*
107817** Given a node number iNode, return the corresponding key to use
107818** in the Rtree.aHash table.
107819*/
107820static int nodeHash(i64 iNode){
107821  return (
107822    (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
107823    (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
107824  ) % HASHSIZE;
107825}
107826
107827/*
107828** Search the node hash table for node iNode. If found, return a pointer
107829** to it. Otherwise, return 0.
107830*/
107831static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
107832  RtreeNode *p;
107833  assert( iNode!=0 );
107834  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
107835  return p;
107836}
107837
107838/*
107839** Add node pNode to the node hash table.
107840*/
107841static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
107842  if( pNode ){
107843    int iHash;
107844    assert( pNode->pNext==0 );
107845    iHash = nodeHash(pNode->iNode);
107846    pNode->pNext = pRtree->aHash[iHash];
107847    pRtree->aHash[iHash] = pNode;
107848  }
107849}
107850
107851/*
107852** Remove node pNode from the node hash table.
107853*/
107854static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
107855  RtreeNode **pp;
107856  if( pNode->iNode!=0 ){
107857    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
107858    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
107859    *pp = pNode->pNext;
107860    pNode->pNext = 0;
107861  }
107862}
107863
107864/*
107865** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
107866** indicating that node has not yet been assigned a node number. It is
107867** assigned a node number when nodeWrite() is called to write the
107868** node contents out to the database.
107869*/
107870static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
107871  RtreeNode *pNode;
107872  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
107873  if( pNode ){
107874    memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
107875    pNode->zData = (u8 *)&pNode[1];
107876    pNode->nRef = 1;
107877    pNode->pParent = pParent;
107878    pNode->isDirty = 1;
107879    nodeReference(pParent);
107880  }
107881  return pNode;
107882}
107883
107884/*
107885** Obtain a reference to an r-tree node.
107886*/
107887static int
107888nodeAcquire(
107889  Rtree *pRtree,             /* R-tree structure */
107890  i64 iNode,                 /* Node number to load */
107891  RtreeNode *pParent,        /* Either the parent node or NULL */
107892  RtreeNode **ppNode         /* OUT: Acquired node */
107893){
107894  int rc;
107895  RtreeNode *pNode;
107896
107897  /* Check if the requested node is already in the hash table. If so,
107898  ** increase its reference count and return it.
107899  */
107900  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
107901    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
107902    if( pParent && !pNode->pParent ){
107903      nodeReference(pParent);
107904      pNode->pParent = pParent;
107905    }
107906    pNode->nRef++;
107907    *ppNode = pNode;
107908    return SQLITE_OK;
107909  }
107910
107911  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
107912  if( !pNode ){
107913    *ppNode = 0;
107914    return SQLITE_NOMEM;
107915  }
107916  pNode->pParent = pParent;
107917  pNode->zData = (u8 *)&pNode[1];
107918  pNode->nRef = 1;
107919  pNode->iNode = iNode;
107920  pNode->isDirty = 0;
107921  pNode->pNext = 0;
107922
107923  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
107924  rc = sqlite3_step(pRtree->pReadNode);
107925  if( rc==SQLITE_ROW ){
107926    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
107927    memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
107928    nodeReference(pParent);
107929  }else{
107930    sqlite3_free(pNode);
107931    pNode = 0;
107932  }
107933
107934  *ppNode = pNode;
107935  rc = sqlite3_reset(pRtree->pReadNode);
107936
107937  if( rc==SQLITE_OK && iNode==1 ){
107938    pRtree->iDepth = readInt16(pNode->zData);
107939  }
107940
107941  assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
107942  nodeHashInsert(pRtree, pNode);
107943
107944  return rc;
107945}
107946
107947/*
107948** Overwrite cell iCell of node pNode with the contents of pCell.
107949*/
107950static void nodeOverwriteCell(
107951  Rtree *pRtree,
107952  RtreeNode *pNode,
107953  RtreeCell *pCell,
107954  int iCell
107955){
107956  int ii;
107957  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
107958  p += writeInt64(p, pCell->iRowid);
107959  for(ii=0; ii<(pRtree->nDim*2); ii++){
107960    p += writeCoord(p, &pCell->aCoord[ii]);
107961  }
107962  pNode->isDirty = 1;
107963}
107964
107965/*
107966** Remove cell the cell with index iCell from node pNode.
107967*/
107968static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
107969  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
107970  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
107971  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
107972  memmove(pDst, pSrc, nByte);
107973  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
107974  pNode->isDirty = 1;
107975}
107976
107977/*
107978** Insert the contents of cell pCell into node pNode. If the insert
107979** is successful, return SQLITE_OK.
107980**
107981** If there is not enough free space in pNode, return SQLITE_FULL.
107982*/
107983static int
107984nodeInsertCell(
107985  Rtree *pRtree,
107986  RtreeNode *pNode,
107987  RtreeCell *pCell
107988){
107989  int nCell;                    /* Current number of cells in pNode */
107990  int nMaxCell;                 /* Maximum number of cells for pNode */
107991
107992  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
107993  nCell = NCELL(pNode);
107994
107995  assert(nCell<=nMaxCell);
107996
107997  if( nCell<nMaxCell ){
107998    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
107999    writeInt16(&pNode->zData[2], nCell+1);
108000    pNode->isDirty = 1;
108001  }
108002
108003  return (nCell==nMaxCell);
108004}
108005
108006/*
108007** If the node is dirty, write it out to the database.
108008*/
108009static int
108010nodeWrite(Rtree *pRtree, RtreeNode *pNode){
108011  int rc = SQLITE_OK;
108012  if( pNode->isDirty ){
108013    sqlite3_stmt *p = pRtree->pWriteNode;
108014    if( pNode->iNode ){
108015      sqlite3_bind_int64(p, 1, pNode->iNode);
108016    }else{
108017      sqlite3_bind_null(p, 1);
108018    }
108019    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
108020    sqlite3_step(p);
108021    pNode->isDirty = 0;
108022    rc = sqlite3_reset(p);
108023    if( pNode->iNode==0 && rc==SQLITE_OK ){
108024      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
108025      nodeHashInsert(pRtree, pNode);
108026    }
108027  }
108028  return rc;
108029}
108030
108031/*
108032** Release a reference to a node. If the node is dirty and the reference
108033** count drops to zero, the node data is written to the database.
108034*/
108035static int
108036nodeRelease(Rtree *pRtree, RtreeNode *pNode){
108037  int rc = SQLITE_OK;
108038  if( pNode ){
108039    assert( pNode->nRef>0 );
108040    pNode->nRef--;
108041    if( pNode->nRef==0 ){
108042      if( pNode->iNode==1 ){
108043        pRtree->iDepth = -1;
108044      }
108045      if( pNode->pParent ){
108046        rc = nodeRelease(pRtree, pNode->pParent);
108047      }
108048      if( rc==SQLITE_OK ){
108049        rc = nodeWrite(pRtree, pNode);
108050      }
108051      nodeHashDelete(pRtree, pNode);
108052      sqlite3_free(pNode);
108053    }
108054  }
108055  return rc;
108056}
108057
108058/*
108059** Return the 64-bit integer value associated with cell iCell of
108060** node pNode. If pNode is a leaf node, this is a rowid. If it is
108061** an internal node, then the 64-bit integer is a child page number.
108062*/
108063static i64 nodeGetRowid(
108064  Rtree *pRtree,
108065  RtreeNode *pNode,
108066  int iCell
108067){
108068  assert( iCell<NCELL(pNode) );
108069  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
108070}
108071
108072/*
108073** Return coordinate iCoord from cell iCell in node pNode.
108074*/
108075static void nodeGetCoord(
108076  Rtree *pRtree,
108077  RtreeNode *pNode,
108078  int iCell,
108079  int iCoord,
108080  RtreeCoord *pCoord           /* Space to write result to */
108081){
108082  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
108083}
108084
108085/*
108086** Deserialize cell iCell of node pNode. Populate the structure pointed
108087** to by pCell with the results.
108088*/
108089static void nodeGetCell(
108090  Rtree *pRtree,
108091  RtreeNode *pNode,
108092  int iCell,
108093  RtreeCell *pCell
108094){
108095  int ii;
108096  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
108097  for(ii=0; ii<pRtree->nDim*2; ii++){
108098    nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
108099  }
108100}
108101
108102
108103/* Forward declaration for the function that does the work of
108104** the virtual table module xCreate() and xConnect() methods.
108105*/
108106static int rtreeInit(
108107  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
108108);
108109
108110/*
108111** Rtree virtual table module xCreate method.
108112*/
108113static int rtreeCreate(
108114  sqlite3 *db,
108115  void *pAux,
108116  int argc, const char *const*argv,
108117  sqlite3_vtab **ppVtab,
108118  char **pzErr
108119){
108120  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
108121}
108122
108123/*
108124** Rtree virtual table module xConnect method.
108125*/
108126static int rtreeConnect(
108127  sqlite3 *db,
108128  void *pAux,
108129  int argc, const char *const*argv,
108130  sqlite3_vtab **ppVtab,
108131  char **pzErr
108132){
108133  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
108134}
108135
108136/*
108137** Increment the r-tree reference count.
108138*/
108139static void rtreeReference(Rtree *pRtree){
108140  pRtree->nBusy++;
108141}
108142
108143/*
108144** Decrement the r-tree reference count. When the reference count reaches
108145** zero the structure is deleted.
108146*/
108147static void rtreeRelease(Rtree *pRtree){
108148  pRtree->nBusy--;
108149  if( pRtree->nBusy==0 ){
108150    sqlite3_finalize(pRtree->pReadNode);
108151    sqlite3_finalize(pRtree->pWriteNode);
108152    sqlite3_finalize(pRtree->pDeleteNode);
108153    sqlite3_finalize(pRtree->pReadRowid);
108154    sqlite3_finalize(pRtree->pWriteRowid);
108155    sqlite3_finalize(pRtree->pDeleteRowid);
108156    sqlite3_finalize(pRtree->pReadParent);
108157    sqlite3_finalize(pRtree->pWriteParent);
108158    sqlite3_finalize(pRtree->pDeleteParent);
108159    sqlite3_free(pRtree);
108160  }
108161}
108162
108163/*
108164** Rtree virtual table module xDisconnect method.
108165*/
108166static int rtreeDisconnect(sqlite3_vtab *pVtab){
108167  rtreeRelease((Rtree *)pVtab);
108168  return SQLITE_OK;
108169}
108170
108171/*
108172** Rtree virtual table module xDestroy method.
108173*/
108174static int rtreeDestroy(sqlite3_vtab *pVtab){
108175  Rtree *pRtree = (Rtree *)pVtab;
108176  int rc;
108177  char *zCreate = sqlite3_mprintf(
108178    "DROP TABLE '%q'.'%q_node';"
108179    "DROP TABLE '%q'.'%q_rowid';"
108180    "DROP TABLE '%q'.'%q_parent';",
108181    pRtree->zDb, pRtree->zName,
108182    pRtree->zDb, pRtree->zName,
108183    pRtree->zDb, pRtree->zName
108184  );
108185  if( !zCreate ){
108186    rc = SQLITE_NOMEM;
108187  }else{
108188    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
108189    sqlite3_free(zCreate);
108190  }
108191  if( rc==SQLITE_OK ){
108192    rtreeRelease(pRtree);
108193  }
108194
108195  return rc;
108196}
108197
108198/*
108199** Rtree virtual table module xOpen method.
108200*/
108201static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
108202  int rc = SQLITE_NOMEM;
108203  RtreeCursor *pCsr;
108204
108205  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
108206  if( pCsr ){
108207    memset(pCsr, 0, sizeof(RtreeCursor));
108208    pCsr->base.pVtab = pVTab;
108209    rc = SQLITE_OK;
108210  }
108211  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
108212
108213  return rc;
108214}
108215
108216/*
108217** Rtree virtual table module xClose method.
108218*/
108219static int rtreeClose(sqlite3_vtab_cursor *cur){
108220  Rtree *pRtree = (Rtree *)(cur->pVtab);
108221  int rc;
108222  RtreeCursor *pCsr = (RtreeCursor *)cur;
108223  sqlite3_free(pCsr->aConstraint);
108224  rc = nodeRelease(pRtree, pCsr->pNode);
108225  sqlite3_free(pCsr);
108226  return rc;
108227}
108228
108229/*
108230** Rtree virtual table module xEof method.
108231**
108232** Return non-zero if the cursor does not currently point to a valid
108233** record (i.e if the scan has finished), or zero otherwise.
108234*/
108235static int rtreeEof(sqlite3_vtab_cursor *cur){
108236  RtreeCursor *pCsr = (RtreeCursor *)cur;
108237  return (pCsr->pNode==0);
108238}
108239
108240/*
108241** Cursor pCursor currently points to a cell in a non-leaf page.
108242** Return true if the sub-tree headed by the cell is filtered
108243** (excluded) by the constraints in the pCursor->aConstraint[]
108244** array, or false otherwise.
108245*/
108246static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
108247  RtreeCell cell;
108248  int ii;
108249  int bRes = 0;
108250
108251  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
108252  for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
108253    RtreeConstraint *p = &pCursor->aConstraint[ii];
108254    double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
108255    double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
108256
108257    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
108258        || p->op==RTREE_GT || p->op==RTREE_EQ
108259    );
108260
108261    switch( p->op ){
108262      case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
108263      case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
108264      case RTREE_EQ:
108265        bRes = (p->rValue>cell_max || p->rValue<cell_min);
108266        break;
108267    }
108268  }
108269
108270  return bRes;
108271}
108272
108273/*
108274** Return true if the cell that cursor pCursor currently points to
108275** would be filtered (excluded) by the constraints in the
108276** pCursor->aConstraint[] array, or false otherwise.
108277**
108278** This function assumes that the cell is part of a leaf node.
108279*/
108280static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
108281  RtreeCell cell;
108282  int ii;
108283
108284  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
108285  for(ii=0; ii<pCursor->nConstraint; ii++){
108286    RtreeConstraint *p = &pCursor->aConstraint[ii];
108287    double coord = DCOORD(cell.aCoord[p->iCoord]);
108288    int res;
108289    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
108290        || p->op==RTREE_GT || p->op==RTREE_EQ
108291    );
108292    switch( p->op ){
108293      case RTREE_LE: res = (coord<=p->rValue); break;
108294      case RTREE_LT: res = (coord<p->rValue);  break;
108295      case RTREE_GE: res = (coord>=p->rValue); break;
108296      case RTREE_GT: res = (coord>p->rValue);  break;
108297      case RTREE_EQ: res = (coord==p->rValue); break;
108298    }
108299
108300    if( !res ) return 1;
108301  }
108302
108303  return 0;
108304}
108305
108306/*
108307** Cursor pCursor currently points at a node that heads a sub-tree of
108308** height iHeight (if iHeight==0, then the node is a leaf). Descend
108309** to point to the left-most cell of the sub-tree that matches the
108310** configured constraints.
108311*/
108312static int descendToCell(
108313  Rtree *pRtree,
108314  RtreeCursor *pCursor,
108315  int iHeight,
108316  int *pEof                 /* OUT: Set to true if cannot descend */
108317){
108318  int isEof;
108319  int rc;
108320  int ii;
108321  RtreeNode *pChild;
108322  sqlite3_int64 iRowid;
108323
108324  RtreeNode *pSavedNode = pCursor->pNode;
108325  int iSavedCell = pCursor->iCell;
108326
108327  assert( iHeight>=0 );
108328
108329  if( iHeight==0 ){
108330    isEof = testRtreeEntry(pRtree, pCursor);
108331  }else{
108332    isEof = testRtreeCell(pRtree, pCursor);
108333  }
108334  if( isEof || iHeight==0 ){
108335    *pEof = isEof;
108336    return SQLITE_OK;
108337  }
108338
108339  iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
108340  rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
108341  if( rc!=SQLITE_OK ){
108342    return rc;
108343  }
108344
108345  nodeRelease(pRtree, pCursor->pNode);
108346  pCursor->pNode = pChild;
108347  isEof = 1;
108348  for(ii=0; isEof && ii<NCELL(pChild); ii++){
108349    pCursor->iCell = ii;
108350    rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
108351    if( rc!=SQLITE_OK ){
108352      return rc;
108353    }
108354  }
108355
108356  if( isEof ){
108357    assert( pCursor->pNode==pChild );
108358    nodeReference(pSavedNode);
108359    nodeRelease(pRtree, pChild);
108360    pCursor->pNode = pSavedNode;
108361    pCursor->iCell = iSavedCell;
108362  }
108363
108364  *pEof = isEof;
108365  return SQLITE_OK;
108366}
108367
108368/*
108369** One of the cells in node pNode is guaranteed to have a 64-bit
108370** integer value equal to iRowid. Return the index of this cell.
108371*/
108372static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
108373  int ii;
108374  for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
108375    assert( ii<(NCELL(pNode)-1) );
108376  }
108377  return ii;
108378}
108379
108380/*
108381** Return the index of the cell containing a pointer to node pNode
108382** in its parent. If pNode is the root node, return -1.
108383*/
108384static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
108385  RtreeNode *pParent = pNode->pParent;
108386  if( pParent ){
108387    return nodeRowidIndex(pRtree, pParent, pNode->iNode);
108388  }
108389  return -1;
108390}
108391
108392/*
108393** Rtree virtual table module xNext method.
108394*/
108395static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
108396  Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
108397  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
108398  int rc = SQLITE_OK;
108399
108400  if( pCsr->iStrategy==1 ){
108401    /* This "scan" is a direct lookup by rowid. There is no next entry. */
108402    nodeRelease(pRtree, pCsr->pNode);
108403    pCsr->pNode = 0;
108404  }
108405
108406  else if( pCsr->pNode ){
108407    /* Move to the next entry that matches the configured constraints. */
108408    int iHeight = 0;
108409    while( pCsr->pNode ){
108410      RtreeNode *pNode = pCsr->pNode;
108411      int nCell = NCELL(pNode);
108412      for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
108413        int isEof;
108414        rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
108415        if( rc!=SQLITE_OK || !isEof ){
108416          return rc;
108417        }
108418      }
108419      pCsr->pNode = pNode->pParent;
108420      pCsr->iCell = nodeParentIndex(pRtree, pNode);
108421      nodeReference(pCsr->pNode);
108422      nodeRelease(pRtree, pNode);
108423      iHeight++;
108424    }
108425  }
108426
108427  return rc;
108428}
108429
108430/*
108431** Rtree virtual table module xRowid method.
108432*/
108433static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
108434  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
108435  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
108436
108437  assert(pCsr->pNode);
108438  *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
108439
108440  return SQLITE_OK;
108441}
108442
108443/*
108444** Rtree virtual table module xColumn method.
108445*/
108446static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
108447  Rtree *pRtree = (Rtree *)cur->pVtab;
108448  RtreeCursor *pCsr = (RtreeCursor *)cur;
108449
108450  if( i==0 ){
108451    i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
108452    sqlite3_result_int64(ctx, iRowid);
108453  }else{
108454    RtreeCoord c;
108455    nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
108456    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
108457      sqlite3_result_double(ctx, c.f);
108458    }else{
108459      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
108460      sqlite3_result_int(ctx, c.i);
108461    }
108462  }
108463
108464  return SQLITE_OK;
108465}
108466
108467/*
108468** Use nodeAcquire() to obtain the leaf node containing the record with
108469** rowid iRowid. If successful, set *ppLeaf to point to the node and
108470** return SQLITE_OK. If there is no such record in the table, set
108471** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
108472** to zero and return an SQLite error code.
108473*/
108474static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
108475  int rc;
108476  *ppLeaf = 0;
108477  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
108478  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
108479    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
108480    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
108481    sqlite3_reset(pRtree->pReadRowid);
108482  }else{
108483    rc = sqlite3_reset(pRtree->pReadRowid);
108484  }
108485  return rc;
108486}
108487
108488
108489/*
108490** Rtree virtual table module xFilter method.
108491*/
108492static int rtreeFilter(
108493  sqlite3_vtab_cursor *pVtabCursor,
108494  int idxNum, const char *idxStr,
108495  int argc, sqlite3_value **argv
108496){
108497  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
108498  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
108499
108500  RtreeNode *pRoot = 0;
108501  int ii;
108502  int rc = SQLITE_OK;
108503
108504  rtreeReference(pRtree);
108505
108506  sqlite3_free(pCsr->aConstraint);
108507  pCsr->aConstraint = 0;
108508  pCsr->iStrategy = idxNum;
108509
108510  if( idxNum==1 ){
108511    /* Special case - lookup by rowid. */
108512    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
108513    i64 iRowid = sqlite3_value_int64(argv[0]);
108514    rc = findLeafNode(pRtree, iRowid, &pLeaf);
108515    pCsr->pNode = pLeaf;
108516    if( pLeaf && rc==SQLITE_OK ){
108517      pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
108518    }
108519  }else{
108520    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
108521    ** with the configured constraints.
108522    */
108523    if( argc>0 ){
108524      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
108525      pCsr->nConstraint = argc;
108526      if( !pCsr->aConstraint ){
108527        rc = SQLITE_NOMEM;
108528      }else{
108529        assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
108530        for(ii=0; ii<argc; ii++){
108531          RtreeConstraint *p = &pCsr->aConstraint[ii];
108532          p->op = idxStr[ii*2];
108533          p->iCoord = idxStr[ii*2+1]-'a';
108534          p->rValue = sqlite3_value_double(argv[ii]);
108535        }
108536      }
108537    }
108538
108539    if( rc==SQLITE_OK ){
108540      pCsr->pNode = 0;
108541      rc = nodeAcquire(pRtree, 1, 0, &pRoot);
108542    }
108543    if( rc==SQLITE_OK ){
108544      int isEof = 1;
108545      int nCell = NCELL(pRoot);
108546      pCsr->pNode = pRoot;
108547      for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
108548        assert( pCsr->pNode==pRoot );
108549        rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
108550        if( !isEof ){
108551          break;
108552        }
108553      }
108554      if( rc==SQLITE_OK && isEof ){
108555        assert( pCsr->pNode==pRoot );
108556        nodeRelease(pRtree, pRoot);
108557        pCsr->pNode = 0;
108558      }
108559      assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
108560    }
108561  }
108562
108563  rtreeRelease(pRtree);
108564  return rc;
108565}
108566
108567/*
108568** Rtree virtual table module xBestIndex method. There are three
108569** table scan strategies to choose from (in order from most to
108570** least desirable):
108571**
108572**   idxNum     idxStr        Strategy
108573**   ------------------------------------------------
108574**     1        Unused        Direct lookup by rowid.
108575**     2        See below     R-tree query.
108576**     3        Unused        Full table scan.
108577**   ------------------------------------------------
108578**
108579** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
108580** 2 is used, idxStr is formatted to contain 2 bytes for each
108581** constraint used. The first two bytes of idxStr correspond to
108582** the constraint in sqlite3_index_info.aConstraintUsage[] with
108583** (argvIndex==1) etc.
108584**
108585** The first of each pair of bytes in idxStr identifies the constraint
108586** operator as follows:
108587**
108588**   Operator    Byte Value
108589**   ----------------------
108590**      =        0x41 ('A')
108591**     <=        0x42 ('B')
108592**      <        0x43 ('C')
108593**     >=        0x44 ('D')
108594**      >        0x45 ('E')
108595**   ----------------------
108596**
108597** The second of each pair of bytes identifies the coordinate column
108598** to which the constraint applies. The leftmost coordinate column
108599** is 'a', the second from the left 'b' etc.
108600*/
108601static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
108602  int rc = SQLITE_OK;
108603  int ii, cCol;
108604
108605  int iIdx = 0;
108606  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
108607  memset(zIdxStr, 0, sizeof(zIdxStr));
108608
108609  assert( pIdxInfo->idxStr==0 );
108610  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
108611    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
108612
108613    if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
108614      /* We have an equality constraint on the rowid. Use strategy 1. */
108615      int jj;
108616      for(jj=0; jj<ii; jj++){
108617        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
108618        pIdxInfo->aConstraintUsage[jj].omit = 0;
108619      }
108620      pIdxInfo->idxNum = 1;
108621      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
108622      pIdxInfo->aConstraintUsage[jj].omit = 1;
108623
108624      /* This strategy involves a two rowid lookups on an B-Tree structures
108625      ** and then a linear search of an R-Tree node. This should be
108626      ** considered almost as quick as a direct rowid lookup (for which
108627      ** sqlite uses an internal cost of 0.0).
108628      */
108629      pIdxInfo->estimatedCost = 10.0;
108630      return SQLITE_OK;
108631    }
108632
108633    if( p->usable && p->iColumn>0 ){
108634      u8 op = 0;
108635      switch( p->op ){
108636        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
108637        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
108638        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
108639        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
108640        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
108641      }
108642      if( op ){
108643        /* Make sure this particular constraint has not been used before.
108644        ** If it has been used before, ignore it.
108645        **
108646        ** A <= or < can be used if there is a prior >= or >.
108647        ** A >= or > can be used if there is a prior < or <=.
108648        ** A <= or < is disqualified if there is a prior <=, <, or ==.
108649        ** A >= or > is disqualified if there is a prior >=, >, or ==.
108650        ** A == is disqualifed if there is any prior constraint.
108651        */
108652        int j, opmsk;
108653        static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
108654        assert( compatible[RTREE_EQ & 7]==0 );
108655        assert( compatible[RTREE_LT & 7]==1 );
108656        assert( compatible[RTREE_LE & 7]==1 );
108657        assert( compatible[RTREE_GT & 7]==2 );
108658        assert( compatible[RTREE_GE & 7]==2 );
108659        cCol = p->iColumn - 1 + 'a';
108660        opmsk = compatible[op & 7];
108661        for(j=0; j<iIdx; j+=2){
108662          if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
108663            op = 0;
108664            break;
108665          }
108666        }
108667      }
108668      if( op ){
108669        assert( iIdx<sizeof(zIdxStr)-1 );
108670        zIdxStr[iIdx++] = op;
108671        zIdxStr[iIdx++] = cCol;
108672        pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
108673        pIdxInfo->aConstraintUsage[ii].omit = 1;
108674      }
108675    }
108676  }
108677
108678  pIdxInfo->idxNum = 2;
108679  pIdxInfo->needToFreeIdxStr = 1;
108680  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
108681    return SQLITE_NOMEM;
108682  }
108683  assert( iIdx>=0 );
108684  pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
108685  return rc;
108686}
108687
108688/*
108689** Return the N-dimensional volumn of the cell stored in *p.
108690*/
108691static float cellArea(Rtree *pRtree, RtreeCell *p){
108692  float area = 1.0;
108693  int ii;
108694  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108695    area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
108696  }
108697  return area;
108698}
108699
108700/*
108701** Return the margin length of cell p. The margin length is the sum
108702** of the objects size in each dimension.
108703*/
108704static float cellMargin(Rtree *pRtree, RtreeCell *p){
108705  float margin = 0.0;
108706  int ii;
108707  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108708    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
108709  }
108710  return margin;
108711}
108712
108713/*
108714** Store the union of cells p1 and p2 in p1.
108715*/
108716static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
108717  int ii;
108718  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
108719    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108720      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
108721      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
108722    }
108723  }else{
108724    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108725      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
108726      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
108727    }
108728  }
108729}
108730
108731/*
108732** Return true if the area covered by p2 is a subset of the area covered
108733** by p1. False otherwise.
108734*/
108735static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
108736  int ii;
108737  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
108738  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108739    RtreeCoord *a1 = &p1->aCoord[ii];
108740    RtreeCoord *a2 = &p2->aCoord[ii];
108741    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
108742     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
108743    ){
108744      return 0;
108745    }
108746  }
108747  return 1;
108748}
108749
108750/*
108751** Return the amount cell p would grow by if it were unioned with pCell.
108752*/
108753static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
108754  float area;
108755  RtreeCell cell;
108756  memcpy(&cell, p, sizeof(RtreeCell));
108757  area = cellArea(pRtree, &cell);
108758  cellUnion(pRtree, &cell, pCell);
108759  return (cellArea(pRtree, &cell)-area);
108760}
108761
108762#if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
108763static float cellOverlap(
108764  Rtree *pRtree,
108765  RtreeCell *p,
108766  RtreeCell *aCell,
108767  int nCell,
108768  int iExclude
108769){
108770  int ii;
108771  float overlap = 0.0;
108772  for(ii=0; ii<nCell; ii++){
108773    if( ii!=iExclude ){
108774      int jj;
108775      float o = 1.0;
108776      for(jj=0; jj<(pRtree->nDim*2); jj+=2){
108777        double x1;
108778        double x2;
108779
108780        x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
108781        x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
108782
108783        if( x2<x1 ){
108784          o = 0.0;
108785          break;
108786        }else{
108787          o = o * (x2-x1);
108788        }
108789      }
108790      overlap += o;
108791    }
108792  }
108793  return overlap;
108794}
108795#endif
108796
108797#if VARIANT_RSTARTREE_CHOOSESUBTREE
108798static float cellOverlapEnlargement(
108799  Rtree *pRtree,
108800  RtreeCell *p,
108801  RtreeCell *pInsert,
108802  RtreeCell *aCell,
108803  int nCell,
108804  int iExclude
108805){
108806  float before;
108807  float after;
108808  before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
108809  cellUnion(pRtree, p, pInsert);
108810  after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
108811  return after-before;
108812}
108813#endif
108814
108815
108816/*
108817** This function implements the ChooseLeaf algorithm from Gutman[84].
108818** ChooseSubTree in r*tree terminology.
108819*/
108820static int ChooseLeaf(
108821  Rtree *pRtree,               /* Rtree table */
108822  RtreeCell *pCell,            /* Cell to insert into rtree */
108823  int iHeight,                 /* Height of sub-tree rooted at pCell */
108824  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
108825){
108826  int rc;
108827  int ii;
108828  RtreeNode *pNode;
108829  rc = nodeAcquire(pRtree, 1, 0, &pNode);
108830
108831  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
108832    int iCell;
108833    sqlite3_int64 iBest;
108834
108835    float fMinGrowth;
108836    float fMinArea;
108837    float fMinOverlap;
108838
108839    int nCell = NCELL(pNode);
108840    RtreeCell cell;
108841    RtreeNode *pChild;
108842
108843    RtreeCell *aCell = 0;
108844
108845#if VARIANT_RSTARTREE_CHOOSESUBTREE
108846    if( ii==(pRtree->iDepth-1) ){
108847      int jj;
108848      aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
108849      if( !aCell ){
108850        rc = SQLITE_NOMEM;
108851        nodeRelease(pRtree, pNode);
108852        pNode = 0;
108853        continue;
108854      }
108855      for(jj=0; jj<nCell; jj++){
108856        nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
108857      }
108858    }
108859#endif
108860
108861    /* Select the child node which will be enlarged the least if pCell
108862    ** is inserted into it. Resolve ties by choosing the entry with
108863    ** the smallest area.
108864    */
108865    for(iCell=0; iCell<nCell; iCell++){
108866      float growth;
108867      float area;
108868      float overlap = 0.0;
108869      nodeGetCell(pRtree, pNode, iCell, &cell);
108870      growth = cellGrowth(pRtree, &cell, pCell);
108871      area = cellArea(pRtree, &cell);
108872#if VARIANT_RSTARTREE_CHOOSESUBTREE
108873      if( ii==(pRtree->iDepth-1) ){
108874        overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
108875      }
108876#endif
108877      if( (iCell==0)
108878       || (overlap<fMinOverlap)
108879       || (overlap==fMinOverlap && growth<fMinGrowth)
108880       || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
108881      ){
108882        fMinOverlap = overlap;
108883        fMinGrowth = growth;
108884        fMinArea = area;
108885        iBest = cell.iRowid;
108886      }
108887    }
108888
108889    sqlite3_free(aCell);
108890    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
108891    nodeRelease(pRtree, pNode);
108892    pNode = pChild;
108893  }
108894
108895  *ppLeaf = pNode;
108896  return rc;
108897}
108898
108899/*
108900** A cell with the same content as pCell has just been inserted into
108901** the node pNode. This function updates the bounding box cells in
108902** all ancestor elements.
108903*/
108904static void AdjustTree(
108905  Rtree *pRtree,                    /* Rtree table */
108906  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
108907  RtreeCell *pCell                  /* This cell was just inserted */
108908){
108909  RtreeNode *p = pNode;
108910  while( p->pParent ){
108911    RtreeCell cell;
108912    RtreeNode *pParent = p->pParent;
108913    int iCell = nodeParentIndex(pRtree, p);
108914
108915    nodeGetCell(pRtree, pParent, iCell, &cell);
108916    if( !cellContains(pRtree, &cell, pCell) ){
108917      cellUnion(pRtree, &cell, pCell);
108918      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
108919    }
108920
108921    p = pParent;
108922  }
108923}
108924
108925/*
108926** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
108927*/
108928static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
108929  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
108930  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
108931  sqlite3_step(pRtree->pWriteRowid);
108932  return sqlite3_reset(pRtree->pWriteRowid);
108933}
108934
108935/*
108936** Write mapping (iNode->iPar) to the <rtree>_parent table.
108937*/
108938static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
108939  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
108940  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
108941  sqlite3_step(pRtree->pWriteParent);
108942  return sqlite3_reset(pRtree->pWriteParent);
108943}
108944
108945static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
108946
108947#if VARIANT_GUTTMAN_LINEAR_SPLIT
108948/*
108949** Implementation of the linear variant of the PickNext() function from
108950** Guttman[84].
108951*/
108952static RtreeCell *LinearPickNext(
108953  Rtree *pRtree,
108954  RtreeCell *aCell,
108955  int nCell,
108956  RtreeCell *pLeftBox,
108957  RtreeCell *pRightBox,
108958  int *aiUsed
108959){
108960  int ii;
108961  for(ii=0; aiUsed[ii]; ii++);
108962  aiUsed[ii] = 1;
108963  return &aCell[ii];
108964}
108965
108966/*
108967** Implementation of the linear variant of the PickSeeds() function from
108968** Guttman[84].
108969*/
108970static void LinearPickSeeds(
108971  Rtree *pRtree,
108972  RtreeCell *aCell,
108973  int nCell,
108974  int *piLeftSeed,
108975  int *piRightSeed
108976){
108977  int i;
108978  int iLeftSeed = 0;
108979  int iRightSeed = 1;
108980  float maxNormalInnerWidth = 0.0;
108981
108982  /* Pick two "seed" cells from the array of cells. The algorithm used
108983  ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
108984  ** indices of the two seed cells in the array are stored in local
108985  ** variables iLeftSeek and iRightSeed.
108986  */
108987  for(i=0; i<pRtree->nDim; i++){
108988    float x1 = DCOORD(aCell[0].aCoord[i*2]);
108989    float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
108990    float x3 = x1;
108991    float x4 = x2;
108992    int jj;
108993
108994    int iCellLeft = 0;
108995    int iCellRight = 0;
108996
108997    for(jj=1; jj<nCell; jj++){
108998      float left = DCOORD(aCell[jj].aCoord[i*2]);
108999      float right = DCOORD(aCell[jj].aCoord[i*2+1]);
109000
109001      if( left<x1 ) x1 = left;
109002      if( right>x4 ) x4 = right;
109003      if( left>x3 ){
109004        x3 = left;
109005        iCellRight = jj;
109006      }
109007      if( right<x2 ){
109008        x2 = right;
109009        iCellLeft = jj;
109010      }
109011    }
109012
109013    if( x4!=x1 ){
109014      float normalwidth = (x3 - x2) / (x4 - x1);
109015      if( normalwidth>maxNormalInnerWidth ){
109016        iLeftSeed = iCellLeft;
109017        iRightSeed = iCellRight;
109018      }
109019    }
109020  }
109021
109022  *piLeftSeed = iLeftSeed;
109023  *piRightSeed = iRightSeed;
109024}
109025#endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
109026
109027#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
109028/*
109029** Implementation of the quadratic variant of the PickNext() function from
109030** Guttman[84].
109031*/
109032static RtreeCell *QuadraticPickNext(
109033  Rtree *pRtree,
109034  RtreeCell *aCell,
109035  int nCell,
109036  RtreeCell *pLeftBox,
109037  RtreeCell *pRightBox,
109038  int *aiUsed
109039){
109040  #define FABS(a) ((a)<0.0?-1.0*(a):(a))
109041
109042  int iSelect = -1;
109043  float fDiff;
109044  int ii;
109045  for(ii=0; ii<nCell; ii++){
109046    if( aiUsed[ii]==0 ){
109047      float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
109048      float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
109049      float diff = FABS(right-left);
109050      if( iSelect<0 || diff>fDiff ){
109051        fDiff = diff;
109052        iSelect = ii;
109053      }
109054    }
109055  }
109056  aiUsed[iSelect] = 1;
109057  return &aCell[iSelect];
109058}
109059
109060/*
109061** Implementation of the quadratic variant of the PickSeeds() function from
109062** Guttman[84].
109063*/
109064static void QuadraticPickSeeds(
109065  Rtree *pRtree,
109066  RtreeCell *aCell,
109067  int nCell,
109068  int *piLeftSeed,
109069  int *piRightSeed
109070){
109071  int ii;
109072  int jj;
109073
109074  int iLeftSeed = 0;
109075  int iRightSeed = 1;
109076  float fWaste = 0.0;
109077
109078  for(ii=0; ii<nCell; ii++){
109079    for(jj=ii+1; jj<nCell; jj++){
109080      float right = cellArea(pRtree, &aCell[jj]);
109081      float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
109082      float waste = growth - right;
109083
109084      if( waste>fWaste ){
109085        iLeftSeed = ii;
109086        iRightSeed = jj;
109087        fWaste = waste;
109088      }
109089    }
109090  }
109091
109092  *piLeftSeed = iLeftSeed;
109093  *piRightSeed = iRightSeed;
109094}
109095#endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
109096
109097/*
109098** Arguments aIdx, aDistance and aSpare all point to arrays of size
109099** nIdx. The aIdx array contains the set of integers from 0 to
109100** (nIdx-1) in no particular order. This function sorts the values
109101** in aIdx according to the indexed values in aDistance. For
109102** example, assuming the inputs:
109103**
109104**   aIdx      = { 0,   1,   2,   3 }
109105**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
109106**
109107** this function sets the aIdx array to contain:
109108**
109109**   aIdx      = { 0,   1,   2,   3 }
109110**
109111** The aSpare array is used as temporary working space by the
109112** sorting algorithm.
109113*/
109114static void SortByDistance(
109115  int *aIdx,
109116  int nIdx,
109117  float *aDistance,
109118  int *aSpare
109119){
109120  if( nIdx>1 ){
109121    int iLeft = 0;
109122    int iRight = 0;
109123
109124    int nLeft = nIdx/2;
109125    int nRight = nIdx-nLeft;
109126    int *aLeft = aIdx;
109127    int *aRight = &aIdx[nLeft];
109128
109129    SortByDistance(aLeft, nLeft, aDistance, aSpare);
109130    SortByDistance(aRight, nRight, aDistance, aSpare);
109131
109132    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
109133    aLeft = aSpare;
109134
109135    while( iLeft<nLeft || iRight<nRight ){
109136      if( iLeft==nLeft ){
109137        aIdx[iLeft+iRight] = aRight[iRight];
109138        iRight++;
109139      }else if( iRight==nRight ){
109140        aIdx[iLeft+iRight] = aLeft[iLeft];
109141        iLeft++;
109142      }else{
109143        float fLeft = aDistance[aLeft[iLeft]];
109144        float fRight = aDistance[aRight[iRight]];
109145        if( fLeft<fRight ){
109146          aIdx[iLeft+iRight] = aLeft[iLeft];
109147          iLeft++;
109148        }else{
109149          aIdx[iLeft+iRight] = aRight[iRight];
109150          iRight++;
109151        }
109152      }
109153    }
109154
109155#if 0
109156    /* Check that the sort worked */
109157    {
109158      int jj;
109159      for(jj=1; jj<nIdx; jj++){
109160        float left = aDistance[aIdx[jj-1]];
109161        float right = aDistance[aIdx[jj]];
109162        assert( left<=right );
109163      }
109164    }
109165#endif
109166  }
109167}
109168
109169/*
109170** Arguments aIdx, aCell and aSpare all point to arrays of size
109171** nIdx. The aIdx array contains the set of integers from 0 to
109172** (nIdx-1) in no particular order. This function sorts the values
109173** in aIdx according to dimension iDim of the cells in aCell. The
109174** minimum value of dimension iDim is considered first, the
109175** maximum used to break ties.
109176**
109177** The aSpare array is used as temporary working space by the
109178** sorting algorithm.
109179*/
109180static void SortByDimension(
109181  Rtree *pRtree,
109182  int *aIdx,
109183  int nIdx,
109184  int iDim,
109185  RtreeCell *aCell,
109186  int *aSpare
109187){
109188  if( nIdx>1 ){
109189
109190    int iLeft = 0;
109191    int iRight = 0;
109192
109193    int nLeft = nIdx/2;
109194    int nRight = nIdx-nLeft;
109195    int *aLeft = aIdx;
109196    int *aRight = &aIdx[nLeft];
109197
109198    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
109199    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
109200
109201    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
109202    aLeft = aSpare;
109203    while( iLeft<nLeft || iRight<nRight ){
109204      double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
109205      double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
109206      double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
109207      double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
109208      if( (iLeft!=nLeft) && ((iRight==nRight)
109209       || (xleft1<xright1)
109210       || (xleft1==xright1 && xleft2<xright2)
109211      )){
109212        aIdx[iLeft+iRight] = aLeft[iLeft];
109213        iLeft++;
109214      }else{
109215        aIdx[iLeft+iRight] = aRight[iRight];
109216        iRight++;
109217      }
109218    }
109219
109220#if 0
109221    /* Check that the sort worked */
109222    {
109223      int jj;
109224      for(jj=1; jj<nIdx; jj++){
109225        float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
109226        float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
109227        float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
109228        float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
109229        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
109230      }
109231    }
109232#endif
109233  }
109234}
109235
109236#if VARIANT_RSTARTREE_SPLIT
109237/*
109238** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
109239*/
109240static int splitNodeStartree(
109241  Rtree *pRtree,
109242  RtreeCell *aCell,
109243  int nCell,
109244  RtreeNode *pLeft,
109245  RtreeNode *pRight,
109246  RtreeCell *pBboxLeft,
109247  RtreeCell *pBboxRight
109248){
109249  int **aaSorted;
109250  int *aSpare;
109251  int ii;
109252
109253  int iBestDim;
109254  int iBestSplit;
109255  float fBestMargin;
109256
109257  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
109258
109259  aaSorted = (int **)sqlite3_malloc(nByte);
109260  if( !aaSorted ){
109261    return SQLITE_NOMEM;
109262  }
109263
109264  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
109265  memset(aaSorted, 0, nByte);
109266  for(ii=0; ii<pRtree->nDim; ii++){
109267    int jj;
109268    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
109269    for(jj=0; jj<nCell; jj++){
109270      aaSorted[ii][jj] = jj;
109271    }
109272    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
109273  }
109274
109275  for(ii=0; ii<pRtree->nDim; ii++){
109276    float margin = 0.0;
109277    float fBestOverlap;
109278    float fBestArea;
109279    int iBestLeft;
109280    int nLeft;
109281
109282    for(
109283      nLeft=RTREE_MINCELLS(pRtree);
109284      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
109285      nLeft++
109286    ){
109287      RtreeCell left;
109288      RtreeCell right;
109289      int kk;
109290      float overlap;
109291      float area;
109292
109293      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
109294      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
109295      for(kk=1; kk<(nCell-1); kk++){
109296        if( kk<nLeft ){
109297          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
109298        }else{
109299          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
109300        }
109301      }
109302      margin += cellMargin(pRtree, &left);
109303      margin += cellMargin(pRtree, &right);
109304      overlap = cellOverlap(pRtree, &left, &right, 1, -1);
109305      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
109306      if( (nLeft==RTREE_MINCELLS(pRtree))
109307       || (overlap<fBestOverlap)
109308       || (overlap==fBestOverlap && area<fBestArea)
109309      ){
109310        iBestLeft = nLeft;
109311        fBestOverlap = overlap;
109312        fBestArea = area;
109313      }
109314    }
109315
109316    if( ii==0 || margin<fBestMargin ){
109317      iBestDim = ii;
109318      fBestMargin = margin;
109319      iBestSplit = iBestLeft;
109320    }
109321  }
109322
109323  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
109324  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
109325  for(ii=0; ii<nCell; ii++){
109326    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
109327    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
109328    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
109329    nodeInsertCell(pRtree, pTarget, pCell);
109330    cellUnion(pRtree, pBbox, pCell);
109331  }
109332
109333  sqlite3_free(aaSorted);
109334  return SQLITE_OK;
109335}
109336#endif
109337
109338#if VARIANT_GUTTMAN_SPLIT
109339/*
109340** Implementation of the regular R-tree SplitNode from Guttman[1984].
109341*/
109342static int splitNodeGuttman(
109343  Rtree *pRtree,
109344  RtreeCell *aCell,
109345  int nCell,
109346  RtreeNode *pLeft,
109347  RtreeNode *pRight,
109348  RtreeCell *pBboxLeft,
109349  RtreeCell *pBboxRight
109350){
109351  int iLeftSeed = 0;
109352  int iRightSeed = 1;
109353  int *aiUsed;
109354  int i;
109355
109356  aiUsed = sqlite3_malloc(sizeof(int)*nCell);
109357  if( !aiUsed ){
109358    return SQLITE_NOMEM;
109359  }
109360  memset(aiUsed, 0, sizeof(int)*nCell);
109361
109362  PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
109363
109364  memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
109365  memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
109366  nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
109367  nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
109368  aiUsed[iLeftSeed] = 1;
109369  aiUsed[iRightSeed] = 1;
109370
109371  for(i=nCell-2; i>0; i--){
109372    RtreeCell *pNext;
109373    pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
109374    float diff =
109375      cellGrowth(pRtree, pBboxLeft, pNext) -
109376      cellGrowth(pRtree, pBboxRight, pNext)
109377    ;
109378    if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
109379     || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
109380    ){
109381      nodeInsertCell(pRtree, pRight, pNext);
109382      cellUnion(pRtree, pBboxRight, pNext);
109383    }else{
109384      nodeInsertCell(pRtree, pLeft, pNext);
109385      cellUnion(pRtree, pBboxLeft, pNext);
109386    }
109387  }
109388
109389  sqlite3_free(aiUsed);
109390  return SQLITE_OK;
109391}
109392#endif
109393
109394static int updateMapping(
109395  Rtree *pRtree,
109396  i64 iRowid,
109397  RtreeNode *pNode,
109398  int iHeight
109399){
109400  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
109401  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
109402  if( iHeight>0 ){
109403    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
109404    if( pChild ){
109405      nodeRelease(pRtree, pChild->pParent);
109406      nodeReference(pNode);
109407      pChild->pParent = pNode;
109408    }
109409  }
109410  return xSetMapping(pRtree, iRowid, pNode->iNode);
109411}
109412
109413static int SplitNode(
109414  Rtree *pRtree,
109415  RtreeNode *pNode,
109416  RtreeCell *pCell,
109417  int iHeight
109418){
109419  int i;
109420  int newCellIsRight = 0;
109421
109422  int rc = SQLITE_OK;
109423  int nCell = NCELL(pNode);
109424  RtreeCell *aCell;
109425  int *aiUsed;
109426
109427  RtreeNode *pLeft = 0;
109428  RtreeNode *pRight = 0;
109429
109430  RtreeCell leftbbox;
109431  RtreeCell rightbbox;
109432
109433  /* Allocate an array and populate it with a copy of pCell and
109434  ** all cells from node pLeft. Then zero the original node.
109435  */
109436  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
109437  if( !aCell ){
109438    rc = SQLITE_NOMEM;
109439    goto splitnode_out;
109440  }
109441  aiUsed = (int *)&aCell[nCell+1];
109442  memset(aiUsed, 0, sizeof(int)*(nCell+1));
109443  for(i=0; i<nCell; i++){
109444    nodeGetCell(pRtree, pNode, i, &aCell[i]);
109445  }
109446  nodeZero(pRtree, pNode);
109447  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
109448  nCell++;
109449
109450  if( pNode->iNode==1 ){
109451    pRight = nodeNew(pRtree, pNode, 1);
109452    pLeft = nodeNew(pRtree, pNode, 1);
109453    pRtree->iDepth++;
109454    pNode->isDirty = 1;
109455    writeInt16(pNode->zData, pRtree->iDepth);
109456  }else{
109457    pLeft = pNode;
109458    pRight = nodeNew(pRtree, pLeft->pParent, 1);
109459    nodeReference(pLeft);
109460  }
109461
109462  if( !pLeft || !pRight ){
109463    rc = SQLITE_NOMEM;
109464    goto splitnode_out;
109465  }
109466
109467  memset(pLeft->zData, 0, pRtree->iNodeSize);
109468  memset(pRight->zData, 0, pRtree->iNodeSize);
109469
109470  rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
109471  if( rc!=SQLITE_OK ){
109472    goto splitnode_out;
109473  }
109474
109475  /* Ensure both child nodes have node numbers assigned to them. */
109476  if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
109477   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
109478  ){
109479    goto splitnode_out;
109480  }
109481
109482  rightbbox.iRowid = pRight->iNode;
109483  leftbbox.iRowid = pLeft->iNode;
109484
109485  if( pNode->iNode==1 ){
109486    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
109487    if( rc!=SQLITE_OK ){
109488      goto splitnode_out;
109489    }
109490  }else{
109491    RtreeNode *pParent = pLeft->pParent;
109492    int iCell = nodeParentIndex(pRtree, pLeft);
109493    nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
109494    AdjustTree(pRtree, pParent, &leftbbox);
109495  }
109496  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
109497    goto splitnode_out;
109498  }
109499
109500  for(i=0; i<NCELL(pRight); i++){
109501    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
109502    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
109503    if( iRowid==pCell->iRowid ){
109504      newCellIsRight = 1;
109505    }
109506    if( rc!=SQLITE_OK ){
109507      goto splitnode_out;
109508    }
109509  }
109510  if( pNode->iNode==1 ){
109511    for(i=0; i<NCELL(pLeft); i++){
109512      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
109513      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
109514      if( rc!=SQLITE_OK ){
109515        goto splitnode_out;
109516      }
109517    }
109518  }else if( newCellIsRight==0 ){
109519    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
109520  }
109521
109522  if( rc==SQLITE_OK ){
109523    rc = nodeRelease(pRtree, pRight);
109524    pRight = 0;
109525  }
109526  if( rc==SQLITE_OK ){
109527    rc = nodeRelease(pRtree, pLeft);
109528    pLeft = 0;
109529  }
109530
109531splitnode_out:
109532  nodeRelease(pRtree, pRight);
109533  nodeRelease(pRtree, pLeft);
109534  sqlite3_free(aCell);
109535  return rc;
109536}
109537
109538static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
109539  int rc = SQLITE_OK;
109540  if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
109541    sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
109542    if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
109543      i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
109544      rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
109545    }else{
109546      rc = SQLITE_ERROR;
109547    }
109548    sqlite3_reset(pRtree->pReadParent);
109549    if( rc==SQLITE_OK ){
109550      rc = fixLeafParent(pRtree, pLeaf->pParent);
109551    }
109552  }
109553  return rc;
109554}
109555
109556static int deleteCell(Rtree *, RtreeNode *, int, int);
109557
109558static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
109559  int rc;
109560  RtreeNode *pParent;
109561  int iCell;
109562
109563  assert( pNode->nRef==1 );
109564
109565  /* Remove the entry in the parent cell. */
109566  iCell = nodeParentIndex(pRtree, pNode);
109567  pParent = pNode->pParent;
109568  pNode->pParent = 0;
109569  if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1))
109570   || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
109571  ){
109572    return rc;
109573  }
109574
109575  /* Remove the xxx_node entry. */
109576  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
109577  sqlite3_step(pRtree->pDeleteNode);
109578  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
109579    return rc;
109580  }
109581
109582  /* Remove the xxx_parent entry. */
109583  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
109584  sqlite3_step(pRtree->pDeleteParent);
109585  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
109586    return rc;
109587  }
109588
109589  /* Remove the node from the in-memory hash table and link it into
109590  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
109591  */
109592  nodeHashDelete(pRtree, pNode);
109593  pNode->iNode = iHeight;
109594  pNode->pNext = pRtree->pDeleted;
109595  pNode->nRef++;
109596  pRtree->pDeleted = pNode;
109597
109598  return SQLITE_OK;
109599}
109600
109601static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
109602  RtreeNode *pParent = pNode->pParent;
109603  if( pParent ){
109604    int ii;
109605    int nCell = NCELL(pNode);
109606    RtreeCell box;                            /* Bounding box for pNode */
109607    nodeGetCell(pRtree, pNode, 0, &box);
109608    for(ii=1; ii<nCell; ii++){
109609      RtreeCell cell;
109610      nodeGetCell(pRtree, pNode, ii, &cell);
109611      cellUnion(pRtree, &box, &cell);
109612    }
109613    box.iRowid = pNode->iNode;
109614    ii = nodeParentIndex(pRtree, pNode);
109615    nodeOverwriteCell(pRtree, pParent, &box, ii);
109616    fixBoundingBox(pRtree, pParent);
109617  }
109618}
109619
109620/*
109621** Delete the cell at index iCell of node pNode. After removing the
109622** cell, adjust the r-tree data structure if required.
109623*/
109624static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
109625  int rc;
109626
109627  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
109628    return rc;
109629  }
109630
109631  /* Remove the cell from the node. This call just moves bytes around
109632  ** the in-memory node image, so it cannot fail.
109633  */
109634  nodeDeleteCell(pRtree, pNode, iCell);
109635
109636  /* If the node is not the tree root and now has less than the minimum
109637  ** number of cells, remove it from the tree. Otherwise, update the
109638  ** cell in the parent node so that it tightly contains the updated
109639  ** node.
109640  */
109641  if( pNode->iNode!=1 ){
109642    RtreeNode *pParent = pNode->pParent;
109643    if( (pParent->iNode!=1 || NCELL(pParent)!=1)
109644     && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
109645    ){
109646      rc = removeNode(pRtree, pNode, iHeight);
109647    }else{
109648      fixBoundingBox(pRtree, pNode);
109649    }
109650  }
109651
109652  return rc;
109653}
109654
109655static int Reinsert(
109656  Rtree *pRtree,
109657  RtreeNode *pNode,
109658  RtreeCell *pCell,
109659  int iHeight
109660){
109661  int *aOrder;
109662  int *aSpare;
109663  RtreeCell *aCell;
109664  float *aDistance;
109665  int nCell;
109666  float aCenterCoord[RTREE_MAX_DIMENSIONS];
109667  int iDim;
109668  int ii;
109669  int rc = SQLITE_OK;
109670
109671  memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
109672
109673  nCell = NCELL(pNode)+1;
109674
109675  /* Allocate the buffers used by this operation. The allocation is
109676  ** relinquished before this function returns.
109677  */
109678  aCell = (RtreeCell *)sqlite3_malloc(nCell * (
109679    sizeof(RtreeCell) +         /* aCell array */
109680    sizeof(int)       +         /* aOrder array */
109681    sizeof(int)       +         /* aSpare array */
109682    sizeof(float)               /* aDistance array */
109683  ));
109684  if( !aCell ){
109685    return SQLITE_NOMEM;
109686  }
109687  aOrder    = (int *)&aCell[nCell];
109688  aSpare    = (int *)&aOrder[nCell];
109689  aDistance = (float *)&aSpare[nCell];
109690
109691  for(ii=0; ii<nCell; ii++){
109692    if( ii==(nCell-1) ){
109693      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
109694    }else{
109695      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
109696    }
109697    aOrder[ii] = ii;
109698    for(iDim=0; iDim<pRtree->nDim; iDim++){
109699      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
109700      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
109701    }
109702  }
109703  for(iDim=0; iDim<pRtree->nDim; iDim++){
109704    aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
109705  }
109706
109707  for(ii=0; ii<nCell; ii++){
109708    aDistance[ii] = 0.0;
109709    for(iDim=0; iDim<pRtree->nDim; iDim++){
109710      float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) -
109711          DCOORD(aCell[ii].aCoord[iDim*2]);
109712      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
109713    }
109714  }
109715
109716  SortByDistance(aOrder, nCell, aDistance, aSpare);
109717  nodeZero(pRtree, pNode);
109718
109719  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
109720    RtreeCell *p = &aCell[aOrder[ii]];
109721    nodeInsertCell(pRtree, pNode, p);
109722    if( p->iRowid==pCell->iRowid ){
109723      if( iHeight==0 ){
109724        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
109725      }else{
109726        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
109727      }
109728    }
109729  }
109730  if( rc==SQLITE_OK ){
109731    fixBoundingBox(pRtree, pNode);
109732  }
109733  for(; rc==SQLITE_OK && ii<nCell; ii++){
109734    /* Find a node to store this cell in. pNode->iNode currently contains
109735    ** the height of the sub-tree headed by the cell.
109736    */
109737    RtreeNode *pInsert;
109738    RtreeCell *p = &aCell[aOrder[ii]];
109739    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
109740    if( rc==SQLITE_OK ){
109741      int rc2;
109742      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
109743      rc2 = nodeRelease(pRtree, pInsert);
109744      if( rc==SQLITE_OK ){
109745        rc = rc2;
109746      }
109747    }
109748  }
109749
109750  sqlite3_free(aCell);
109751  return rc;
109752}
109753
109754/*
109755** Insert cell pCell into node pNode. Node pNode is the head of a
109756** subtree iHeight high (leaf nodes have iHeight==0).
109757*/
109758static int rtreeInsertCell(
109759  Rtree *pRtree,
109760  RtreeNode *pNode,
109761  RtreeCell *pCell,
109762  int iHeight
109763){
109764  int rc = SQLITE_OK;
109765  if( iHeight>0 ){
109766    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
109767    if( pChild ){
109768      nodeRelease(pRtree, pChild->pParent);
109769      nodeReference(pNode);
109770      pChild->pParent = pNode;
109771    }
109772  }
109773  if( nodeInsertCell(pRtree, pNode, pCell) ){
109774#if VARIANT_RSTARTREE_REINSERT
109775    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
109776      rc = SplitNode(pRtree, pNode, pCell, iHeight);
109777    }else{
109778      pRtree->iReinsertHeight = iHeight;
109779      rc = Reinsert(pRtree, pNode, pCell, iHeight);
109780    }
109781#else
109782    rc = SplitNode(pRtree, pNode, pCell, iHeight);
109783#endif
109784  }else{
109785    AdjustTree(pRtree, pNode, pCell);
109786    if( iHeight==0 ){
109787      rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
109788    }else{
109789      rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
109790    }
109791  }
109792  return rc;
109793}
109794
109795static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
109796  int ii;
109797  int rc = SQLITE_OK;
109798  int nCell = NCELL(pNode);
109799
109800  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
109801    RtreeNode *pInsert;
109802    RtreeCell cell;
109803    nodeGetCell(pRtree, pNode, ii, &cell);
109804
109805    /* Find a node to store this cell in. pNode->iNode currently contains
109806    ** the height of the sub-tree headed by the cell.
109807    */
109808    rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
109809    if( rc==SQLITE_OK ){
109810      int rc2;
109811      rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
109812      rc2 = nodeRelease(pRtree, pInsert);
109813      if( rc==SQLITE_OK ){
109814        rc = rc2;
109815      }
109816    }
109817  }
109818  return rc;
109819}
109820
109821/*
109822** Select a currently unused rowid for a new r-tree record.
109823*/
109824static int newRowid(Rtree *pRtree, i64 *piRowid){
109825  int rc;
109826  sqlite3_bind_null(pRtree->pWriteRowid, 1);
109827  sqlite3_bind_null(pRtree->pWriteRowid, 2);
109828  sqlite3_step(pRtree->pWriteRowid);
109829  rc = sqlite3_reset(pRtree->pWriteRowid);
109830  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
109831  return rc;
109832}
109833
109834#ifndef NDEBUG
109835static int hashIsEmpty(Rtree *pRtree){
109836  int ii;
109837  for(ii=0; ii<HASHSIZE; ii++){
109838    assert( !pRtree->aHash[ii] );
109839  }
109840  return 1;
109841}
109842#endif
109843
109844/*
109845** The xUpdate method for rtree module virtual tables.
109846*/
109847static int rtreeUpdate(
109848  sqlite3_vtab *pVtab,
109849  int nData,
109850  sqlite3_value **azData,
109851  sqlite_int64 *pRowid
109852){
109853  Rtree *pRtree = (Rtree *)pVtab;
109854  int rc = SQLITE_OK;
109855
109856  rtreeReference(pRtree);
109857
109858  assert(nData>=1);
109859  assert(hashIsEmpty(pRtree));
109860
109861  /* If azData[0] is not an SQL NULL value, it is the rowid of a
109862  ** record to delete from the r-tree table. The following block does
109863  ** just that.
109864  */
109865  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
109866    i64 iDelete;                /* The rowid to delete */
109867    RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
109868    int iCell;                  /* Index of iDelete cell in pLeaf */
109869    RtreeNode *pRoot;
109870
109871    /* Obtain a reference to the root node to initialise Rtree.iDepth */
109872    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
109873
109874    /* Obtain a reference to the leaf node that contains the entry
109875    ** about to be deleted.
109876    */
109877    if( rc==SQLITE_OK ){
109878      iDelete = sqlite3_value_int64(azData[0]);
109879      rc = findLeafNode(pRtree, iDelete, &pLeaf);
109880    }
109881
109882    /* Delete the cell in question from the leaf node. */
109883    if( rc==SQLITE_OK ){
109884      int rc2;
109885      iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
109886      rc = deleteCell(pRtree, pLeaf, iCell, 0);
109887      rc2 = nodeRelease(pRtree, pLeaf);
109888      if( rc==SQLITE_OK ){
109889        rc = rc2;
109890      }
109891    }
109892
109893    /* Delete the corresponding entry in the <rtree>_rowid table. */
109894    if( rc==SQLITE_OK ){
109895      sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
109896      sqlite3_step(pRtree->pDeleteRowid);
109897      rc = sqlite3_reset(pRtree->pDeleteRowid);
109898    }
109899
109900    /* Check if the root node now has exactly one child. If so, remove
109901    ** it, schedule the contents of the child for reinsertion and
109902    ** reduce the tree height by one.
109903    **
109904    ** This is equivalent to copying the contents of the child into
109905    ** the root node (the operation that Gutman's paper says to perform
109906    ** in this scenario).
109907    */
109908    if( rc==SQLITE_OK && pRtree->iDepth>0 ){
109909      if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
109910        RtreeNode *pChild;
109911        i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
109912        rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
109913        if( rc==SQLITE_OK ){
109914          rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
109915        }
109916        if( rc==SQLITE_OK ){
109917          pRtree->iDepth--;
109918          writeInt16(pRoot->zData, pRtree->iDepth);
109919          pRoot->isDirty = 1;
109920        }
109921      }
109922    }
109923
109924    /* Re-insert the contents of any underfull nodes removed from the tree. */
109925    for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
109926      if( rc==SQLITE_OK ){
109927        rc = reinsertNodeContent(pRtree, pLeaf);
109928      }
109929      pRtree->pDeleted = pLeaf->pNext;
109930      sqlite3_free(pLeaf);
109931    }
109932
109933    /* Release the reference to the root node. */
109934    if( rc==SQLITE_OK ){
109935      rc = nodeRelease(pRtree, pRoot);
109936    }else{
109937      nodeRelease(pRtree, pRoot);
109938    }
109939  }
109940
109941  /* If the azData[] array contains more than one element, elements
109942  ** (azData[2]..azData[argc-1]) contain a new record to insert into
109943  ** the r-tree structure.
109944  */
109945  if( rc==SQLITE_OK && nData>1 ){
109946    /* Insert a new record into the r-tree */
109947    RtreeCell cell;
109948    int ii;
109949    RtreeNode *pLeaf;
109950
109951    /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
109952    assert( nData==(pRtree->nDim*2 + 3) );
109953    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
109954      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
109955        cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
109956        cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
109957        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
109958          rc = SQLITE_CONSTRAINT;
109959          goto constraint;
109960        }
109961      }
109962    }else{
109963      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
109964        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
109965        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
109966        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
109967          rc = SQLITE_CONSTRAINT;
109968          goto constraint;
109969        }
109970      }
109971    }
109972
109973    /* Figure out the rowid of the new row. */
109974    if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
109975      rc = newRowid(pRtree, &cell.iRowid);
109976    }else{
109977      cell.iRowid = sqlite3_value_int64(azData[2]);
109978      sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
109979      if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
109980        sqlite3_reset(pRtree->pReadRowid);
109981        rc = SQLITE_CONSTRAINT;
109982        goto constraint;
109983      }
109984      rc = sqlite3_reset(pRtree->pReadRowid);
109985    }
109986
109987    if( rc==SQLITE_OK ){
109988      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
109989    }
109990    if( rc==SQLITE_OK ){
109991      int rc2;
109992      pRtree->iReinsertHeight = -1;
109993      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
109994      rc2 = nodeRelease(pRtree, pLeaf);
109995      if( rc==SQLITE_OK ){
109996        rc = rc2;
109997      }
109998    }
109999  }
110000
110001constraint:
110002  rtreeRelease(pRtree);
110003  return rc;
110004}
110005
110006/*
110007** The xRename method for rtree module virtual tables.
110008*/
110009static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
110010  Rtree *pRtree = (Rtree *)pVtab;
110011  int rc = SQLITE_NOMEM;
110012  char *zSql = sqlite3_mprintf(
110013    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
110014    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
110015    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
110016    , pRtree->zDb, pRtree->zName, zNewName
110017    , pRtree->zDb, pRtree->zName, zNewName
110018    , pRtree->zDb, pRtree->zName, zNewName
110019  );
110020  if( zSql ){
110021    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
110022    sqlite3_free(zSql);
110023  }
110024  return rc;
110025}
110026
110027static sqlite3_module rtreeModule = {
110028  0,                         /* iVersion */
110029  rtreeCreate,                /* xCreate - create a table */
110030  rtreeConnect,               /* xConnect - connect to an existing table */
110031  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
110032  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
110033  rtreeDestroy,               /* xDestroy - Drop a table */
110034  rtreeOpen,                  /* xOpen - open a cursor */
110035  rtreeClose,                 /* xClose - close a cursor */
110036  rtreeFilter,                /* xFilter - configure scan constraints */
110037  rtreeNext,                  /* xNext - advance a cursor */
110038  rtreeEof,                   /* xEof */
110039  rtreeColumn,                /* xColumn - read data */
110040  rtreeRowid,                 /* xRowid - read data */
110041  rtreeUpdate,                /* xUpdate - write data */
110042  0,                          /* xBegin - begin transaction */
110043  0,                          /* xSync - sync transaction */
110044  0,                          /* xCommit - commit transaction */
110045  0,                          /* xRollback - rollback transaction */
110046  0,                          /* xFindFunction - function overloading */
110047  rtreeRename                 /* xRename - rename the table */
110048};
110049
110050static int rtreeSqlInit(
110051  Rtree *pRtree,
110052  sqlite3 *db,
110053  const char *zDb,
110054  const char *zPrefix,
110055  int isCreate
110056){
110057  int rc = SQLITE_OK;
110058
110059  #define N_STATEMENT 9
110060  static const char *azSql[N_STATEMENT] = {
110061    /* Read and write the xxx_node table */
110062    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
110063    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
110064    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
110065
110066    /* Read and write the xxx_rowid table */
110067    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
110068    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
110069    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
110070
110071    /* Read and write the xxx_parent table */
110072    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
110073    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
110074    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
110075  };
110076  sqlite3_stmt **appStmt[N_STATEMENT];
110077  int i;
110078
110079  pRtree->db = db;
110080
110081  if( isCreate ){
110082    char *zCreate = sqlite3_mprintf(
110083"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
110084"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
110085"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
110086"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
110087      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
110088    );
110089    if( !zCreate ){
110090      return SQLITE_NOMEM;
110091    }
110092    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
110093    sqlite3_free(zCreate);
110094    if( rc!=SQLITE_OK ){
110095      return rc;
110096    }
110097  }
110098
110099  appStmt[0] = &pRtree->pReadNode;
110100  appStmt[1] = &pRtree->pWriteNode;
110101  appStmt[2] = &pRtree->pDeleteNode;
110102  appStmt[3] = &pRtree->pReadRowid;
110103  appStmt[4] = &pRtree->pWriteRowid;
110104  appStmt[5] = &pRtree->pDeleteRowid;
110105  appStmt[6] = &pRtree->pReadParent;
110106  appStmt[7] = &pRtree->pWriteParent;
110107  appStmt[8] = &pRtree->pDeleteParent;
110108
110109  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
110110    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
110111    if( zSql ){
110112      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
110113    }else{
110114      rc = SQLITE_NOMEM;
110115    }
110116    sqlite3_free(zSql);
110117  }
110118
110119  return rc;
110120}
110121
110122/*
110123** This routine queries database handle db for the page-size used by
110124** database zDb. If successful, the page-size in bytes is written to
110125** *piPageSize and SQLITE_OK returned. Otherwise, and an SQLite error
110126** code is returned.
110127*/
110128static int getPageSize(sqlite3 *db, const char *zDb, int *piPageSize){
110129  int rc = SQLITE_NOMEM;
110130  char *zSql;
110131  sqlite3_stmt *pStmt = 0;
110132
110133  zSql = sqlite3_mprintf("PRAGMA %Q.page_size", zDb);
110134  if( !zSql ){
110135    return SQLITE_NOMEM;
110136  }
110137
110138  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
110139  sqlite3_free(zSql);
110140  if( rc!=SQLITE_OK ){
110141    return rc;
110142  }
110143
110144  if( SQLITE_ROW==sqlite3_step(pStmt) ){
110145    *piPageSize = sqlite3_column_int(pStmt, 0);
110146  }
110147  return sqlite3_finalize(pStmt);
110148}
110149
110150/*
110151** This function is the implementation of both the xConnect and xCreate
110152** methods of the r-tree virtual table.
110153**
110154**   argv[0]   -> module name
110155**   argv[1]   -> database name
110156**   argv[2]   -> table name
110157**   argv[...] -> column names...
110158*/
110159static int rtreeInit(
110160  sqlite3 *db,                        /* Database connection */
110161  void *pAux,                         /* One of the RTREE_COORD_* constants */
110162  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
110163  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
110164  char **pzErr,                       /* OUT: Error message, if any */
110165  int isCreate                        /* True for xCreate, false for xConnect */
110166){
110167  int rc = SQLITE_OK;
110168  int iPageSize = 0;
110169  Rtree *pRtree;
110170  int nDb;              /* Length of string argv[1] */
110171  int nName;            /* Length of string argv[2] */
110172  int eCoordType = (int)pAux;
110173
110174  const char *aErrMsg[] = {
110175    0,                                                    /* 0 */
110176    "Wrong number of columns for an rtree table",         /* 1 */
110177    "Too few columns for an rtree table",                 /* 2 */
110178    "Too many columns for an rtree table"                 /* 3 */
110179  };
110180
110181  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
110182  if( aErrMsg[iErr] ){
110183    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
110184    return SQLITE_ERROR;
110185  }
110186
110187  rc = getPageSize(db, argv[1], &iPageSize);
110188  if( rc!=SQLITE_OK ){
110189    return rc;
110190  }
110191
110192  /* Allocate the sqlite3_vtab structure */
110193  nDb = strlen(argv[1]);
110194  nName = strlen(argv[2]);
110195  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
110196  if( !pRtree ){
110197    return SQLITE_NOMEM;
110198  }
110199  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
110200  pRtree->nBusy = 1;
110201  pRtree->base.pModule = &rtreeModule;
110202  pRtree->zDb = (char *)&pRtree[1];
110203  pRtree->zName = &pRtree->zDb[nDb+1];
110204  pRtree->nDim = (argc-4)/2;
110205  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
110206  pRtree->eCoordType = eCoordType;
110207  memcpy(pRtree->zDb, argv[1], nDb);
110208  memcpy(pRtree->zName, argv[2], nName);
110209
110210  /* Figure out the node size to use. By default, use 64 bytes less than
110211  ** the database page-size. This ensures that each node is stored on
110212  ** a single database page.
110213  **
110214  ** If the databasd page-size is so large that more than RTREE_MAXCELLS
110215  ** entries would fit in a single node, use a smaller node-size.
110216  */
110217  pRtree->iNodeSize = iPageSize-64;
110218  if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
110219    pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
110220  }
110221
110222  /* Create/Connect to the underlying relational database schema. If
110223  ** that is successful, call sqlite3_declare_vtab() to configure
110224  ** the r-tree table schema.
110225  */
110226  if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
110227    *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
110228  }else{
110229    char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
110230    char *zTmp;
110231    int ii;
110232    for(ii=4; zSql && ii<argc; ii++){
110233      zTmp = zSql;
110234      zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
110235      sqlite3_free(zTmp);
110236    }
110237    if( zSql ){
110238      zTmp = zSql;
110239      zSql = sqlite3_mprintf("%s);", zTmp);
110240      sqlite3_free(zTmp);
110241    }
110242    if( !zSql ){
110243      rc = SQLITE_NOMEM;
110244    }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
110245      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
110246    }
110247    sqlite3_free(zSql);
110248  }
110249
110250  if( rc==SQLITE_OK ){
110251    *ppVtab = (sqlite3_vtab *)pRtree;
110252  }else{
110253    rtreeRelease(pRtree);
110254  }
110255  return rc;
110256}
110257
110258
110259/*
110260** Implementation of a scalar function that decodes r-tree nodes to
110261** human readable strings. This can be used for debugging and analysis.
110262**
110263** The scalar function takes two arguments, a blob of data containing
110264** an r-tree node, and the number of dimensions the r-tree indexes.
110265** For a two-dimensional r-tree structure called "rt", to deserialize
110266** all nodes, a statement like:
110267**
110268**   SELECT rtreenode(2, data) FROM rt_node;
110269**
110270** The human readable string takes the form of a Tcl list with one
110271** entry for each cell in the r-tree node. Each entry is itself a
110272** list, containing the 8-byte rowid/pageno followed by the
110273** <num-dimension>*2 coordinates.
110274*/
110275static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
110276  char *zText = 0;
110277  RtreeNode node;
110278  Rtree tree;
110279  int ii;
110280
110281  memset(&node, 0, sizeof(RtreeNode));
110282  memset(&tree, 0, sizeof(Rtree));
110283  tree.nDim = sqlite3_value_int(apArg[0]);
110284  tree.nBytesPerCell = 8 + 8 * tree.nDim;
110285  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
110286
110287  for(ii=0; ii<NCELL(&node); ii++){
110288    char zCell[512];
110289    int nCell = 0;
110290    RtreeCell cell;
110291    int jj;
110292
110293    nodeGetCell(&tree, &node, ii, &cell);
110294    sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
110295    nCell = strlen(zCell);
110296    for(jj=0; jj<tree.nDim*2; jj++){
110297      sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
110298      nCell = strlen(zCell);
110299    }
110300
110301    if( zText ){
110302      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
110303      sqlite3_free(zText);
110304      zText = zTextNew;
110305    }else{
110306      zText = sqlite3_mprintf("{%s}", zCell);
110307    }
110308  }
110309
110310  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
110311}
110312
110313static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
110314  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
110315   || sqlite3_value_bytes(apArg[0])<2
110316  ){
110317    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
110318  }else{
110319    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
110320    sqlite3_result_int(ctx, readInt16(zBlob));
110321  }
110322}
110323
110324/*
110325** Register the r-tree module with database handle db. This creates the
110326** virtual table module "rtree" and the debugging/analysis scalar
110327** function "rtreenode".
110328*/
110329SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
110330  int rc = SQLITE_OK;
110331
110332  if( rc==SQLITE_OK ){
110333    int utf8 = SQLITE_UTF8;
110334    rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
110335  }
110336  if( rc==SQLITE_OK ){
110337    int utf8 = SQLITE_UTF8;
110338    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
110339  }
110340  if( rc==SQLITE_OK ){
110341    void *c = (void *)RTREE_COORD_REAL32;
110342    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
110343  }
110344  if( rc==SQLITE_OK ){
110345    void *c = (void *)RTREE_COORD_INT32;
110346    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
110347  }
110348
110349  return rc;
110350}
110351
110352#if !SQLITE_CORE
110353SQLITE_API int sqlite3_extension_init(
110354  sqlite3 *db,
110355  char **pzErrMsg,
110356  const sqlite3_api_routines *pApi
110357){
110358  SQLITE_EXTENSION_INIT2(pApi)
110359  return sqlite3RtreeInit(db);
110360}
110361#endif
110362
110363#endif
110364
110365/************** End of rtree.c ***********************************************/
110366/************** Begin file icu.c *********************************************/
110367/*
110368** 2007 May 6
110369**
110370** The author disclaims copyright to this source code.  In place of
110371** a legal notice, here is a blessing:
110372**
110373**    May you do good and not evil.
110374**    May you find forgiveness for yourself and forgive others.
110375**    May you share freely, never taking more than you give.
110376**
110377*************************************************************************
110378** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
110379**
110380** This file implements an integration between the ICU library
110381** ("International Components for Unicode", an open-source library
110382** for handling unicode data) and SQLite. The integration uses
110383** ICU to provide the following to SQLite:
110384**
110385**   * An implementation of the SQL regexp() function (and hence REGEXP
110386**     operator) using the ICU uregex_XX() APIs.
110387**
110388**   * Implementations of the SQL scalar upper() and lower() functions
110389**     for case mapping.
110390**
110391**   * Integration of ICU and SQLite collation seqences.
110392**
110393**   * An implementation of the LIKE operator that uses ICU to
110394**     provide case-independent matching.
110395*/
110396
110397#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
110398
110399/* Include ICU headers */
110400#include <unicode/utypes.h>
110401#include <unicode/uregex.h>
110402#include <unicode/ustring.h>
110403#include <unicode/ucol.h>
110404
110405
110406#ifndef SQLITE_CORE
110407  SQLITE_EXTENSION_INIT1
110408#else
110409#endif
110410
110411/*
110412** Maximum length (in bytes) of the pattern in a LIKE or GLOB
110413** operator.
110414*/
110415#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
110416# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
110417#endif
110418
110419/*
110420** Version of sqlite3_free() that is always a function, never a macro.
110421*/
110422static void xFree(void *p){
110423  sqlite3_free(p);
110424}
110425
110426/*
110427** Compare two UTF-8 strings for equality where the first string is
110428** a "LIKE" expression. Return true (1) if they are the same and
110429** false (0) if they are different.
110430*/
110431static int icuLikeCompare(
110432  const uint8_t *zPattern,   /* LIKE pattern */
110433  const uint8_t *zString,    /* The UTF-8 string to compare against */
110434  const UChar32 uEsc         /* The escape character */
110435){
110436  static const int MATCH_ONE = (UChar32)'_';
110437  static const int MATCH_ALL = (UChar32)'%';
110438
110439  int iPattern = 0;       /* Current byte index in zPattern */
110440  int iString = 0;        /* Current byte index in zString */
110441
110442  int prevEscape = 0;     /* True if the previous character was uEsc */
110443
110444  while( zPattern[iPattern]!=0 ){
110445
110446    /* Read (and consume) the next character from the input pattern. */
110447    UChar32 uPattern;
110448    U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
110449    assert(uPattern!=0);
110450
110451    /* There are now 4 possibilities:
110452    **
110453    **     1. uPattern is an unescaped match-all character "%",
110454    **     2. uPattern is an unescaped match-one character "_",
110455    **     3. uPattern is an unescaped escape character, or
110456    **     4. uPattern is to be handled as an ordinary character
110457    */
110458    if( !prevEscape && uPattern==MATCH_ALL ){
110459      /* Case 1. */
110460      uint8_t c;
110461
110462      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
110463      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
110464      ** test string.
110465      */
110466      while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
110467        if( c==MATCH_ONE ){
110468          if( zString[iString]==0 ) return 0;
110469          U8_FWD_1_UNSAFE(zString, iString);
110470        }
110471        iPattern++;
110472      }
110473
110474      if( zPattern[iPattern]==0 ) return 1;
110475
110476      while( zString[iString] ){
110477        if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
110478          return 1;
110479        }
110480        U8_FWD_1_UNSAFE(zString, iString);
110481      }
110482      return 0;
110483
110484    }else if( !prevEscape && uPattern==MATCH_ONE ){
110485      /* Case 2. */
110486      if( zString[iString]==0 ) return 0;
110487      U8_FWD_1_UNSAFE(zString, iString);
110488
110489    }else if( !prevEscape && uPattern==uEsc){
110490      /* Case 3. */
110491      prevEscape = 1;
110492
110493    }else{
110494      /* Case 4. */
110495      UChar32 uString;
110496      U8_NEXT_UNSAFE(zString, iString, uString);
110497      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
110498      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
110499      if( uString!=uPattern ){
110500        return 0;
110501      }
110502      prevEscape = 0;
110503    }
110504  }
110505
110506  return zString[iString]==0;
110507}
110508
110509/*
110510** Implementation of the like() SQL function.  This function implements
110511** the build-in LIKE operator.  The first argument to the function is the
110512** pattern and the second argument is the string.  So, the SQL statements:
110513**
110514**       A LIKE B
110515**
110516** is implemented as like(B, A). If there is an escape character E,
110517**
110518**       A LIKE B ESCAPE E
110519**
110520** is mapped to like(B, A, E).
110521*/
110522static void icuLikeFunc(
110523  sqlite3_context *context,
110524  int argc,
110525  sqlite3_value **argv
110526){
110527  const unsigned char *zA = sqlite3_value_text(argv[0]);
110528  const unsigned char *zB = sqlite3_value_text(argv[1]);
110529  UChar32 uEsc = 0;
110530
110531  /* Limit the length of the LIKE or GLOB pattern to avoid problems
110532  ** of deep recursion and N*N behavior in patternCompare().
110533  */
110534  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
110535    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
110536    return;
110537  }
110538
110539
110540  if( argc==3 ){
110541    /* The escape character string must consist of a single UTF-8 character.
110542    ** Otherwise, return an error.
110543    */
110544    int nE= sqlite3_value_bytes(argv[2]);
110545    const unsigned char *zE = sqlite3_value_text(argv[2]);
110546    int i = 0;
110547    if( zE==0 ) return;
110548    U8_NEXT(zE, i, nE, uEsc);
110549    if( i!=nE){
110550      sqlite3_result_error(context,
110551          "ESCAPE expression must be a single character", -1);
110552      return;
110553    }
110554  }
110555
110556  if( zA && zB ){
110557    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
110558  }
110559}
110560
110561/*
110562** This function is called when an ICU function called from within
110563** the implementation of an SQL scalar function returns an error.
110564**
110565** The scalar function context passed as the first argument is
110566** loaded with an error message based on the following two args.
110567*/
110568static void icuFunctionError(
110569  sqlite3_context *pCtx,       /* SQLite scalar function context */
110570  const char *zName,           /* Name of ICU function that failed */
110571  UErrorCode e                 /* Error code returned by ICU function */
110572){
110573  char zBuf[128];
110574  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
110575  zBuf[127] = '\0';
110576  sqlite3_result_error(pCtx, zBuf, -1);
110577}
110578
110579/*
110580** Function to delete compiled regexp objects. Registered as
110581** a destructor function with sqlite3_set_auxdata().
110582*/
110583static void icuRegexpDelete(void *p){
110584  URegularExpression *pExpr = (URegularExpression *)p;
110585  uregex_close(pExpr);
110586}
110587
110588/*
110589** Implementation of SQLite REGEXP operator. This scalar function takes
110590** two arguments. The first is a regular expression pattern to compile
110591** the second is a string to match against that pattern. If either
110592** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
110593** is 1 if the string matches the pattern, or 0 otherwise.
110594**
110595** SQLite maps the regexp() function to the regexp() operator such
110596** that the following two are equivalent:
110597**
110598**     zString REGEXP zPattern
110599**     regexp(zPattern, zString)
110600**
110601** Uses the following ICU regexp APIs:
110602**
110603**     uregex_open()
110604**     uregex_matches()
110605**     uregex_close()
110606*/
110607static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
110608  UErrorCode status = U_ZERO_ERROR;
110609  URegularExpression *pExpr;
110610  UBool res;
110611  const UChar *zString = sqlite3_value_text16(apArg[1]);
110612
110613  /* If the left hand side of the regexp operator is NULL,
110614  ** then the result is also NULL.
110615  */
110616  if( !zString ){
110617    return;
110618  }
110619
110620  pExpr = sqlite3_get_auxdata(p, 0);
110621  if( !pExpr ){
110622    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
110623    if( !zPattern ){
110624      return;
110625    }
110626    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
110627
110628    if( U_SUCCESS(status) ){
110629      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
110630    }else{
110631      assert(!pExpr);
110632      icuFunctionError(p, "uregex_open", status);
110633      return;
110634    }
110635  }
110636
110637  /* Configure the text that the regular expression operates on. */
110638  uregex_setText(pExpr, zString, -1, &status);
110639  if( !U_SUCCESS(status) ){
110640    icuFunctionError(p, "uregex_setText", status);
110641    return;
110642  }
110643
110644  /* Attempt the match */
110645  res = uregex_matches(pExpr, 0, &status);
110646  if( !U_SUCCESS(status) ){
110647    icuFunctionError(p, "uregex_matches", status);
110648    return;
110649  }
110650
110651  /* Set the text that the regular expression operates on to a NULL
110652  ** pointer. This is not really necessary, but it is tidier than
110653  ** leaving the regular expression object configured with an invalid
110654  ** pointer after this function returns.
110655  */
110656  uregex_setText(pExpr, 0, 0, &status);
110657
110658  /* Return 1 or 0. */
110659  sqlite3_result_int(p, res ? 1 : 0);
110660}
110661
110662/*
110663** Implementations of scalar functions for case mapping - upper() and
110664** lower(). Function upper() converts its input to upper-case (ABC).
110665** Function lower() converts to lower-case (abc).
110666**
110667** ICU provides two types of case mapping, "general" case mapping and
110668** "language specific". Refer to ICU documentation for the differences
110669** between the two.
110670**
110671** To utilise "general" case mapping, the upper() or lower() scalar
110672** functions are invoked with one argument:
110673**
110674**     upper('ABC') -> 'abc'
110675**     lower('abc') -> 'ABC'
110676**
110677** To access ICU "language specific" case mapping, upper() or lower()
110678** should be invoked with two arguments. The second argument is the name
110679** of the locale to use. Passing an empty string ("") or SQL NULL value
110680** as the second argument is the same as invoking the 1 argument version
110681** of upper() or lower().
110682**
110683**     lower('I', 'en_us') -> 'i'
110684**     lower('I', 'tr_tr') -> 'ı' (small dotless i)
110685**
110686** http://www.icu-project.org/userguide/posix.html#case_mappings
110687*/
110688static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
110689  const UChar *zInput;
110690  UChar *zOutput;
110691  int nInput;
110692  int nOutput;
110693
110694  UErrorCode status = U_ZERO_ERROR;
110695  const char *zLocale = 0;
110696
110697  assert(nArg==1 || nArg==2);
110698  if( nArg==2 ){
110699    zLocale = (const char *)sqlite3_value_text(apArg[1]);
110700  }
110701
110702  zInput = sqlite3_value_text16(apArg[0]);
110703  if( !zInput ){
110704    return;
110705  }
110706  nInput = sqlite3_value_bytes16(apArg[0]);
110707
110708  nOutput = nInput * 2 + 2;
110709  zOutput = sqlite3_malloc(nOutput);
110710  if( !zOutput ){
110711    return;
110712  }
110713
110714  if( sqlite3_user_data(p) ){
110715    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
110716  }else{
110717    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
110718  }
110719
110720  if( !U_SUCCESS(status) ){
110721    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
110722    return;
110723  }
110724
110725  sqlite3_result_text16(p, zOutput, -1, xFree);
110726}
110727
110728/*
110729** Collation sequence destructor function. The pCtx argument points to
110730** a UCollator structure previously allocated using ucol_open().
110731*/
110732static void icuCollationDel(void *pCtx){
110733  UCollator *p = (UCollator *)pCtx;
110734  ucol_close(p);
110735}
110736
110737/*
110738** Collation sequence comparison function. The pCtx argument points to
110739** a UCollator structure previously allocated using ucol_open().
110740*/
110741static int icuCollationColl(
110742  void *pCtx,
110743  int nLeft,
110744  const void *zLeft,
110745  int nRight,
110746  const void *zRight
110747){
110748  UCollationResult res;
110749  UCollator *p = (UCollator *)pCtx;
110750  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
110751  switch( res ){
110752    case UCOL_LESS:    return -1;
110753    case UCOL_GREATER: return +1;
110754    case UCOL_EQUAL:   return 0;
110755  }
110756  assert(!"Unexpected return value from ucol_strcoll()");
110757  return 0;
110758}
110759
110760/*
110761** Implementation of the scalar function icu_load_collation().
110762**
110763** This scalar function is used to add ICU collation based collation
110764** types to an SQLite database connection. It is intended to be called
110765** as follows:
110766**
110767**     SELECT icu_load_collation(<locale>, <collation-name>);
110768**
110769** Where <locale> is a string containing an ICU locale identifier (i.e.
110770** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
110771** collation sequence to create.
110772*/
110773static void icuLoadCollation(
110774  sqlite3_context *p,
110775  int nArg,
110776  sqlite3_value **apArg
110777){
110778  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
110779  UErrorCode status = U_ZERO_ERROR;
110780  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
110781  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
110782  UCollator *pUCollator;    /* ICU library collation object */
110783  int rc;                   /* Return code from sqlite3_create_collation_x() */
110784
110785  assert(nArg==2);
110786  zLocale = (const char *)sqlite3_value_text(apArg[0]);
110787  zName = (const char *)sqlite3_value_text(apArg[1]);
110788
110789  if( !zLocale || !zName ){
110790    return;
110791  }
110792
110793  pUCollator = ucol_open(zLocale, &status);
110794  if( !U_SUCCESS(status) ){
110795    icuFunctionError(p, "ucol_open", status);
110796    return;
110797  }
110798  assert(p);
110799
110800  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
110801      icuCollationColl, icuCollationDel
110802  );
110803  if( rc!=SQLITE_OK ){
110804    ucol_close(pUCollator);
110805    sqlite3_result_error(p, "Error registering collation function", -1);
110806  }
110807}
110808
110809/*
110810** Register the ICU extension functions with database db.
110811*/
110812SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
110813  struct IcuScalar {
110814    const char *zName;                        /* Function name */
110815    int nArg;                                 /* Number of arguments */
110816    int enc;                                  /* Optimal text encoding */
110817    void *pContext;                           /* sqlite3_user_data() context */
110818    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
110819  } scalars[] = {
110820    {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
110821
110822    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
110823    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
110824    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
110825    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
110826
110827    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
110828    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
110829    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
110830    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
110831
110832    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
110833    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
110834
110835    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
110836  };
110837
110838  int rc = SQLITE_OK;
110839  int i;
110840
110841  for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
110842    struct IcuScalar *p = &scalars[i];
110843    rc = sqlite3_create_function(
110844        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
110845    );
110846  }
110847
110848  return rc;
110849}
110850
110851#if !SQLITE_CORE
110852SQLITE_API int sqlite3_extension_init(
110853  sqlite3 *db,
110854  char **pzErrMsg,
110855  const sqlite3_api_routines *pApi
110856){
110857  SQLITE_EXTENSION_INIT2(pApi)
110858  return sqlite3IcuInit(db);
110859}
110860#endif
110861
110862#endif
110863
110864/************** End of icu.c *************************************************/
110865/************** Begin file fts3_icu.c ****************************************/
110866/*
110867** 2007 June 22
110868**
110869** The author disclaims copyright to this source code.  In place of
110870** a legal notice, here is a blessing:
110871**
110872**    May you do good and not evil.
110873**    May you find forgiveness for yourself and forgive others.
110874**    May you share freely, never taking more than you give.
110875**
110876*************************************************************************
110877** This file implements a tokenizer for fts3 based on the ICU library.
110878**
110879** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
110880*/
110881
110882#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
110883#ifdef SQLITE_ENABLE_ICU
110884
110885
110886#include <unicode/ubrk.h>
110887#include <unicode/utf16.h>
110888
110889typedef struct IcuTokenizer IcuTokenizer;
110890typedef struct IcuCursor IcuCursor;
110891
110892struct IcuTokenizer {
110893  sqlite3_tokenizer base;
110894  char *zLocale;
110895};
110896
110897struct IcuCursor {
110898  sqlite3_tokenizer_cursor base;
110899
110900  UBreakIterator *pIter;      /* ICU break-iterator object */
110901  int nChar;                  /* Number of UChar elements in pInput */
110902  UChar *aChar;               /* Copy of input using utf-16 encoding */
110903  int *aOffset;               /* Offsets of each character in utf-8 input */
110904
110905  int nBuffer;
110906  char *zBuffer;
110907
110908  int iToken;
110909};
110910
110911/*
110912** Create a new tokenizer instance.
110913*/
110914static int icuCreate(
110915  int argc,                            /* Number of entries in argv[] */
110916  const char * const *argv,            /* Tokenizer creation arguments */
110917  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
110918){
110919  IcuTokenizer *p;
110920  int n = 0;
110921
110922  if( argc>0 ){
110923    n = strlen(argv[0])+1;
110924  }
110925  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
110926  if( !p ){
110927    return SQLITE_NOMEM;
110928  }
110929  memset(p, 0, sizeof(IcuTokenizer));
110930
110931  if( n ){
110932    p->zLocale = (char *)&p[1];
110933    memcpy(p->zLocale, argv[0], n);
110934  }
110935
110936  *ppTokenizer = (sqlite3_tokenizer *)p;
110937
110938  return SQLITE_OK;
110939}
110940
110941/*
110942** Destroy a tokenizer
110943*/
110944static int icuDestroy(sqlite3_tokenizer *pTokenizer){
110945  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
110946  sqlite3_free(p);
110947  return SQLITE_OK;
110948}
110949
110950/*
110951** Prepare to begin tokenizing a particular string.  The input
110952** string to be tokenized is pInput[0..nBytes-1].  A cursor
110953** used to incrementally tokenize this string is returned in
110954** *ppCursor.
110955*/
110956static int icuOpen(
110957  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
110958  const char *zInput,                    /* Input string */
110959  int nInput,                            /* Length of zInput in bytes */
110960  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
110961){
110962  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
110963  IcuCursor *pCsr;
110964
110965  const int32_t opt = U_FOLD_CASE_DEFAULT;
110966  UErrorCode status = U_ZERO_ERROR;
110967  int nChar;
110968
110969  UChar32 c;
110970  int iInput = 0;
110971  int iOut = 0;
110972
110973  *ppCursor = 0;
110974
110975  if( nInput<0 ){
110976    nInput = strlen(zInput);
110977  }
110978  nChar = nInput+1;
110979  pCsr = (IcuCursor *)sqlite3_malloc(
110980      sizeof(IcuCursor) +                /* IcuCursor */
110981      nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
110982      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
110983  );
110984  if( !pCsr ){
110985    return SQLITE_NOMEM;
110986  }
110987  memset(pCsr, 0, sizeof(IcuCursor));
110988  pCsr->aChar = (UChar *)&pCsr[1];
110989  pCsr->aOffset = (int *)&pCsr->aChar[nChar];
110990
110991  pCsr->aOffset[iOut] = iInput;
110992  U8_NEXT(zInput, iInput, nInput, c);
110993  while( c>0 ){
110994    int isError = 0;
110995    c = u_foldCase(c, opt);
110996    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
110997    if( isError ){
110998      sqlite3_free(pCsr);
110999      return SQLITE_ERROR;
111000    }
111001    pCsr->aOffset[iOut] = iInput;
111002
111003    if( iInput<nInput ){
111004      U8_NEXT(zInput, iInput, nInput, c);
111005    }else{
111006      c = 0;
111007    }
111008  }
111009
111010  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
111011  if( !U_SUCCESS(status) ){
111012    sqlite3_free(pCsr);
111013    return SQLITE_ERROR;
111014  }
111015  pCsr->nChar = iOut;
111016
111017  ubrk_first(pCsr->pIter);
111018  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
111019  return SQLITE_OK;
111020}
111021
111022/*
111023** Close a tokenization cursor previously opened by a call to icuOpen().
111024*/
111025static int icuClose(sqlite3_tokenizer_cursor *pCursor){
111026  IcuCursor *pCsr = (IcuCursor *)pCursor;
111027  ubrk_close(pCsr->pIter);
111028  sqlite3_free(pCsr->zBuffer);
111029  sqlite3_free(pCsr);
111030  return SQLITE_OK;
111031}
111032
111033/*
111034** Extract the next token from a tokenization cursor.
111035*/
111036static int icuNext(
111037  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
111038  const char **ppToken,               /* OUT: *ppToken is the token text */
111039  int *pnBytes,                       /* OUT: Number of bytes in token */
111040  int *piStartOffset,                 /* OUT: Starting offset of token */
111041  int *piEndOffset,                   /* OUT: Ending offset of token */
111042  int *piPosition                     /* OUT: Position integer of token */
111043){
111044  IcuCursor *pCsr = (IcuCursor *)pCursor;
111045
111046  int iStart = 0;
111047  int iEnd = 0;
111048  int nByte = 0;
111049
111050  while( iStart==iEnd ){
111051    UChar32 c;
111052
111053    iStart = ubrk_current(pCsr->pIter);
111054    iEnd = ubrk_next(pCsr->pIter);
111055    if( iEnd==UBRK_DONE ){
111056      return SQLITE_DONE;
111057    }
111058
111059    while( iStart<iEnd ){
111060      int iWhite = iStart;
111061      U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
111062      if( u_isspace(c) ){
111063        iStart = iWhite;
111064      }else{
111065        break;
111066      }
111067    }
111068    assert(iStart<=iEnd);
111069  }
111070
111071  do {
111072    UErrorCode status = U_ZERO_ERROR;
111073    if( nByte ){
111074      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
111075      if( !zNew ){
111076        return SQLITE_NOMEM;
111077      }
111078      pCsr->zBuffer = zNew;
111079      pCsr->nBuffer = nByte;
111080    }
111081
111082    u_strToUTF8(
111083        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
111084        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
111085        &status                                  /* Output success/failure */
111086    );
111087  } while( nByte>pCsr->nBuffer );
111088
111089  *ppToken = pCsr->zBuffer;
111090  *pnBytes = nByte;
111091  *piStartOffset = pCsr->aOffset[iStart];
111092  *piEndOffset = pCsr->aOffset[iEnd];
111093  *piPosition = pCsr->iToken++;
111094
111095  return SQLITE_OK;
111096}
111097
111098/*
111099** The set of routines that implement the simple tokenizer
111100*/
111101static const sqlite3_tokenizer_module icuTokenizerModule = {
111102  0,                           /* iVersion */
111103  icuCreate,                   /* xCreate  */
111104  icuDestroy,                  /* xCreate  */
111105  icuOpen,                     /* xOpen    */
111106  icuClose,                    /* xClose   */
111107  icuNext,                     /* xNext    */
111108};
111109
111110/*
111111** Set *ppModule to point at the implementation of the ICU tokenizer.
111112*/
111113SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
111114  sqlite3_tokenizer_module const**ppModule
111115){
111116  *ppModule = &icuTokenizerModule;
111117}
111118
111119#endif /* defined(SQLITE_ENABLE_ICU) */
111120#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
111121
111122/************** End of fts3_icu.c ********************************************/
111123