sqlite3.c revision 78c28328355fbe2b1d8acc6ec70b532abc508f4e
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-01-05 15:30:36 28d0d7710761114a44a1a3a425a6883c661f06e7"
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** EXPERIMENTAL
1446**
1447** The sqlite3_config() interface is used to make global configuration
1448** changes to SQLite in order to tune SQLite to the specific needs of
1449** the application.  The default configuration is recommended for most
1450** applications and so this routine is usually not necessary.  It is
1451** provided to support rare applications with unusual needs.
1452**
1453** The sqlite3_config() interface is not threadsafe.  The application
1454** must insure that no other SQLite interfaces are invoked by other
1455** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1456** may only be invoked prior to library initialization using
1457** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1458** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1459** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1460** Note, however, that ^sqlite3_config() can be called as part of the
1461** implementation of an application-defined [sqlite3_os_init()].
1462**
1463** The first argument to sqlite3_config() is an integer
1464** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1465** what property of SQLite is to be configured.  Subsequent arguments
1466** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1467** in the first argument.
1468**
1469** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1470** ^If the option is unknown or SQLite is unable to set the option
1471** then this routine returns a non-zero [error code].
1472*/
1473SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
1474
1475/*
1476** CAPI3REF: Configure database connections
1477** EXPERIMENTAL
1478**
1479** The sqlite3_db_config() interface is used to make configuration
1480** changes to a [database connection].  The interface is similar to
1481** [sqlite3_config()] except that the changes apply to a single
1482** [database connection] (specified in the first argument).  The
1483** sqlite3_db_config() interface should only be used immediately after
1484** the database connection is created using [sqlite3_open()],
1485** [sqlite3_open16()], or [sqlite3_open_v2()].
1486**
1487** The second argument to sqlite3_db_config(D,V,...)  is the
1488** configuration verb - an integer code that indicates what
1489** aspect of the [database connection] is being configured.
1490** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1491** New verbs are likely to be added in future releases of SQLite.
1492** Additional arguments depend on the verb.
1493**
1494** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1495** the call is considered successful.
1496*/
1497SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
1498
1499/*
1500** CAPI3REF: Memory Allocation Routines
1501** EXPERIMENTAL
1502**
1503** An instance of this object defines the interface between SQLite
1504** and low-level memory allocation routines.
1505**
1506** This object is used in only one place in the SQLite interface.
1507** A pointer to an instance of this object is the argument to
1508** [sqlite3_config()] when the configuration option is
1509** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1510** By creating an instance of this object
1511** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1512** during configuration, an application can specify an alternative
1513** memory allocation subsystem for SQLite to use for all of its
1514** dynamic memory needs.
1515**
1516** Note that SQLite comes with several [built-in memory allocators]
1517** that are perfectly adequate for the overwhelming majority of applications
1518** and that this object is only useful to a tiny minority of applications
1519** with specialized memory allocation requirements.  This object is
1520** also used during testing of SQLite in order to specify an alternative
1521** memory allocator that simulates memory out-of-memory conditions in
1522** order to verify that SQLite recovers gracefully from such
1523** conditions.
1524**
1525** The xMalloc and xFree methods must work like the
1526** malloc() and free() functions from the standard C library.
1527** The xRealloc method must work like realloc() from the standard C library
1528** with the exception that if the second argument to xRealloc is zero,
1529** xRealloc must be a no-op - it must not perform any allocation or
1530** deallocation.  ^SQLite guarantees that the second argument to
1531** xRealloc is always a value returned by a prior call to xRoundup.
1532** And so in cases where xRoundup always returns a positive number,
1533** xRealloc can perform exactly as the standard library realloc() and
1534** still be in compliance with this specification.
1535**
1536** xSize should return the allocated size of a memory allocation
1537** previously obtained from xMalloc or xRealloc.  The allocated size
1538** is always at least as big as the requested size but may be larger.
1539**
1540** The xRoundup method returns what would be the allocated size of
1541** a memory allocation given a particular requested size.  Most memory
1542** allocators round up memory allocations at least to the next multiple
1543** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1544** Every memory allocation request coming in through [sqlite3_malloc()]
1545** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1546** that causes the corresponding memory allocation to fail.
1547**
1548** The xInit method initializes the memory allocator.  (For example,
1549** it might allocate any require mutexes or initialize internal data
1550** structures.  The xShutdown method is invoked (indirectly) by
1551** [sqlite3_shutdown()] and should deallocate any resources acquired
1552** by xInit.  The pAppData pointer is used as the only parameter to
1553** xInit and xShutdown.
1554**
1555** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1556** the xInit method, so the xInit method need not be threadsafe.  The
1557** xShutdown method is only called from [sqlite3_shutdown()] so it does
1558** not need to be threadsafe either.  For all other methods, SQLite
1559** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1560** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1561** it is by default) and so the methods are automatically serialized.
1562** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1563** methods must be threadsafe or else make their own arrangements for
1564** serialization.
1565**
1566** SQLite will never invoke xInit() more than once without an intervening
1567** call to xShutdown().
1568*/
1569typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1570struct sqlite3_mem_methods {
1571  void *(*xMalloc)(int);         /* Memory allocation function */
1572  void (*xFree)(void*);          /* Free a prior allocation */
1573  void *(*xRealloc)(void*,int);  /* Resize an allocation */
1574  int (*xSize)(void*);           /* Return the size of an allocation */
1575  int (*xRoundup)(int);          /* Round up request size to allocation size */
1576  int (*xInit)(void*);           /* Initialize the memory allocator */
1577  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1578  void *pAppData;                /* Argument to xInit() and xShutdown() */
1579};
1580
1581/*
1582** CAPI3REF: Configuration Options
1583** EXPERIMENTAL
1584**
1585** These constants are the available integer configuration options that
1586** can be passed as the first argument to the [sqlite3_config()] interface.
1587**
1588** New configuration options may be added in future releases of SQLite.
1589** Existing configuration options might be discontinued.  Applications
1590** should check the return code from [sqlite3_config()] to make sure that
1591** the call worked.  The [sqlite3_config()] interface will return a
1592** non-zero [error code] if a discontinued or unsupported configuration option
1593** is invoked.
1594**
1595** <dl>
1596** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1597** <dd>There are no arguments to this option.  ^This option sets the
1598** [threading mode] to Single-thread.  In other words, it disables
1599** all mutexing and puts SQLite into a mode where it can only be used
1600** by a single thread.   ^If SQLite is compiled with
1601** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1602** it is not possible to change the [threading mode] from its default
1603** value of Single-thread and so [sqlite3_config()] will return
1604** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1605** configuration option.</dd>
1606**
1607** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1608** <dd>There are no arguments to this option.  ^This option sets the
1609** [threading mode] to Multi-thread.  In other words, it disables
1610** mutexing on [database connection] and [prepared statement] objects.
1611** The application is responsible for serializing access to
1612** [database connections] and [prepared statements].  But other mutexes
1613** are enabled so that SQLite will be safe to use in a multi-threaded
1614** environment as long as no two threads attempt to use the same
1615** [database connection] at the same time.  ^If SQLite is compiled with
1616** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1617** it is not possible to set the Multi-thread [threading mode] and
1618** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1619** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1620**
1621** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1622** <dd>There are no arguments to this option.  ^This option sets the
1623** [threading mode] to Serialized. In other words, this option enables
1624** all mutexes including the recursive
1625** mutexes on [database connection] and [prepared statement] objects.
1626** In this mode (which is the default when SQLite is compiled with
1627** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1628** to [database connections] and [prepared statements] so that the
1629** application is free to use the same [database connection] or the
1630** same [prepared statement] in different threads at the same time.
1631** ^If SQLite is compiled with
1632** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1633** it is not possible to set the Serialized [threading mode] and
1634** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1635** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1636**
1637** <dt>SQLITE_CONFIG_MALLOC</dt>
1638** <dd> ^(This option takes a single argument which is a pointer to an
1639** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1640** alternative low-level memory allocation routines to be used in place of
1641** the memory allocation routines built into SQLite.)^ ^SQLite makes
1642** its own private copy of the content of the [sqlite3_mem_methods] structure
1643** before the [sqlite3_config()] call returns.</dd>
1644**
1645** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1646** <dd> ^(This option takes a single argument which is a pointer to an
1647** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1648** structure is filled with the currently defined memory allocation routines.)^
1649** This option can be used to overload the default memory allocation
1650** routines with a wrapper that simulations memory allocation failure or
1651** tracks memory usage, for example. </dd>
1652**
1653** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1654** <dd> ^This option takes single argument of type int, interpreted as a
1655** boolean, which enables or disables the collection of memory allocation
1656** statistics. ^(When memory allocation statistics are disabled, the
1657** following SQLite interfaces become non-operational:
1658**   <ul>
1659**   <li> [sqlite3_memory_used()]
1660**   <li> [sqlite3_memory_highwater()]
1661**   <li> [sqlite3_soft_heap_limit()]
1662**   <li> [sqlite3_status()]
1663**   </ul>)^
1664** ^Memory allocation statistics are enabled by default unless SQLite is
1665** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1666** allocation statistics are disabled by default.
1667** </dd>
1668**
1669** <dt>SQLITE_CONFIG_SCRATCH</dt>
1670** <dd> ^This option specifies a static memory buffer that SQLite can use for
1671** scratch memory.  There are three arguments:  A pointer an 8-byte
1672** aligned memory buffer from which the scrach allocations will be
1673** drawn, the size of each scratch allocation (sz),
1674** and the maximum number of scratch allocations (N).  The sz
1675** argument must be a multiple of 16. The sz parameter should be a few bytes
1676** larger than the actual scratch space required due to internal overhead.
1677** The first argument must be a pointer to an 8-byte aligned buffer
1678** of at least sz*N bytes of memory.
1679** ^SQLite will use no more than one scratch buffer per thread.  So
1680** N should be set to the expected maximum number of threads.  ^SQLite will
1681** never require a scratch buffer that is more than 6 times the database
1682** page size. ^If SQLite needs needs additional scratch memory beyond
1683** what is provided by this configuration option, then
1684** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1685**
1686** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1687** <dd> ^This option specifies a static memory buffer that SQLite can use for
1688** the database page cache with the default page cache implemenation.
1689** This configuration should not be used if an application-define page
1690** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1691** There are three arguments to this option: A pointer to 8-byte aligned
1692** memory, the size of each page buffer (sz), and the number of pages (N).
1693** The sz argument should be the size of the largest database page
1694** (a power of two between 512 and 32768) plus a little extra for each
1695** page header.  ^The page header size is 20 to 40 bytes depending on
1696** the host architecture.  ^It is harmless, apart from the wasted memory,
1697** to make sz a little too large.  The first
1698** argument should point to an allocation of at least sz*N bytes of memory.
1699** ^SQLite will use the memory provided by the first argument to satisfy its
1700** memory needs for the first N pages that it adds to cache.  ^If additional
1701** page cache memory is needed beyond what is provided by this option, then
1702** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1703** ^The implementation might use one or more of the N buffers to hold
1704** memory accounting information. The pointer in the first argument must
1705** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1706** will be undefined.</dd>
1707**
1708** <dt>SQLITE_CONFIG_HEAP</dt>
1709** <dd> ^This option specifies a static memory buffer that SQLite will use
1710** for all of its dynamic memory allocation needs beyond those provided
1711** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1712** There are three arguments: An 8-byte aligned pointer to the memory,
1713** the number of bytes in the memory buffer, and the minimum allocation size.
1714** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1715** to using its default memory allocator (the system malloc() implementation),
1716** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1717** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1718** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1719** allocator is engaged to handle all of SQLites memory allocation needs.
1720** The first pointer (the memory pointer) must be aligned to an 8-byte
1721** boundary or subsequent behavior of SQLite will be undefined.</dd>
1722**
1723** <dt>SQLITE_CONFIG_MUTEX</dt>
1724** <dd> ^(This option takes a single argument which is a pointer to an
1725** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1726** alternative low-level mutex routines to be used in place
1727** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1728** content of the [sqlite3_mutex_methods] structure before the call to
1729** [sqlite3_config()] returns. ^If SQLite is compiled with
1730** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1731** the entire mutexing subsystem is omitted from the build and hence calls to
1732** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1733** return [SQLITE_ERROR].</dd>
1734**
1735** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1736** <dd> ^(This option takes a single argument which is a pointer to an
1737** instance of the [sqlite3_mutex_methods] structure.  The
1738** [sqlite3_mutex_methods]
1739** structure is filled with the currently defined mutex routines.)^
1740** This option can be used to overload the default mutex allocation
1741** routines with a wrapper used to track mutex usage for performance
1742** profiling or testing, for example.   ^If SQLite is compiled with
1743** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1744** the entire mutexing subsystem is omitted from the build and hence calls to
1745** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1746** return [SQLITE_ERROR].</dd>
1747**
1748** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1749** <dd> ^(This option takes two arguments that determine the default
1750** memory allocation for the lookaside memory allocator on each
1751** [database connection].  The first argument is the
1752** size of each lookaside buffer slot and the second is the number of
1753** slots allocated to each database connection.)^  ^(This option sets the
1754** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1755** verb to [sqlite3_db_config()] can be used to change the lookaside
1756** configuration on individual connections.)^ </dd>
1757**
1758** <dt>SQLITE_CONFIG_PCACHE</dt>
1759** <dd> ^(This option takes a single argument which is a pointer to
1760** an [sqlite3_pcache_methods] object.  This object specifies the interface
1761** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1762** object and uses it for page cache memory allocations.</dd>
1763**
1764** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1765** <dd> ^(This option takes a single argument which is a pointer to an
1766** [sqlite3_pcache_methods] object.  SQLite copies of the current
1767** page cache implementation into that object.)^ </dd>
1768**
1769** </dl>
1770*/
1771#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1772#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1773#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1774#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1775#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1776#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1777#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1778#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1779#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1780#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1781#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1782/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
1783#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1784#define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1785#define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
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** Undo the hack that converts floating point types to integer for
6176** builds on processors without floating point support.
6177*/
6178#ifdef SQLITE_OMIT_FLOATING_POINT
6179# undef double
6180#endif
6181
6182#if 0
6183}  /* End of the 'extern "C"' block */
6184#endif
6185#endif
6186
6187
6188/************** End of sqlite3.h *********************************************/
6189// Begin Android Add
6190
6191#define SQLITE_BeginImmediate 0x00200000  /* Default BEGIN to IMMEDIATE */
6192#define fdatasync fsync
6193
6194#define LOG_TAG "sqlite3"
6195#include <utils/Log.h>
6196#include <cutils/log.h>
6197
6198// the following should match up with value in java/android/database/sqlite/SQLiteDatabase.java
6199#define EVENT_DB_CORRUPT 75004
6200
6201SQLITE_PRIVATE int sqlite3Corrupt(int corruption_type){
6202  // write an event to the log
6203  char buf[50];
6204  int payload_len = sprintf(buf, "corruption_type = %d", corruption_type);
6205  android_btWriteLog(EVENT_DB_CORRUPT, EVENT_TYPE_STRING, buf, payload_len);
6206  return SQLITE_CORRUPT;
6207}
6208
6209#define SQLITE_CORRUPT_BKPT(N) sqlite3Corrupt(N)
6210
6211// situations where DB corruption is reported
6212#define PAGE_NUM_0_CORRUPTION                 101
6213#define PAGER_OUT_OF_RANGE_CORRUPTION         102
6214#define INVALID_KEY_INTO_PTRMAP_CORRUPTION    103
6215#define INVALID_OFFSET_IN_PTRMAP_CORRUPTION   104
6216#define INVALID_PETYPE_CORRUPTION             105
6217#define CELL_INDEX_CORRUPTION                 106
6218#define CELL_INDEX_TOO_LOW_CORRUPTION         107
6219#define CELL_INDEX_INVALID_CORRUPTION         108
6220#define DEFRAG_PAGE_CORRUPTION                109
6221#define GAP_TOP_CORRUPTION                    110
6222#define FREE_SLOT_AVAIL_CORRUPTION            111
6223#define ALLOC_SPACE_CORRUPTION                112
6224#define FREE_SPACE_1_CORRUPTION               113
6225#define FREE_SPACE_2_CORRUPTION               114
6226#define FREE_SPACE_3_CORRUPTION               115
6227#define DECODE_FLAGS_CORRUPTION               116
6228#define BTREE_INITPAGE_1_CORRUPTION           117
6229#define TOO_MANY_CELLS_IN_PAGE_CORRUPTION     118
6230#define CELL_LOC_OUT_OF_RANGE_CORRUPTION      119
6231#define BTREE_INITPAGE_2_CORRUPTION           120
6232#define FREE_BLOCK_ERR_CORRUPTION             121
6233#define FREE_BLOCK_NOT_IN_ORDER_CORRUPTION    122
6234#define FREE_SPACE_ERR_CORRUPTION             123
6235#define MODIFY_PAGE_PTR_1_CORRUPTION          124
6236#define MODIFY_PAGE_PTR_2_CORRUPTION          125
6237#define INCR_VAC_STEP_1_CORRUPTION            126
6238#define AUTO_VAC_COMMIT_1_CORRUPTION          127
6239#define AUTO_VAC_COMMIT_2_CORRUPTION          128
6240#define ACCESS_PAYLOAD_1_CORRUPTION           129
6241#define DATA_CORRUPTION                       130
6242#define MOVE_TO_CHILD_1_CORRUPTION            131
6243#define MOVE_TO_CHILD_2_CORRUPTION            132
6244#define MOVE_TO_ROOT_1_CORRUPTION             133
6245#define MOVE_TO_ROOT_2_CORRUPTION             134
6246#define BTREE_PAGE_1_CORRUPTION               135
6247#define BTREE_PAGE_2_CORRUPTION               136
6248#define BTREE_PAGE_3_CORRUPTION               137
6249#define BTREE_PAGE_4_CORRUPTION               138
6250#define BTREE_PAGE_5_CORRUPTION               139
6251#define BTREE_PAGE_6_CORRUPTION               140
6252#define FREEPAGE2_1_CORRUPTION                141
6253#define CLEARCELL_CORRUPTION                  142
6254#define FILL_IN_CELL_1_CORRUPTION             143
6255#define DROP_CELL_CORRUPTION                  144
6256#define BALANCE_QUICK_CORRUPTION              145
6257#define BTREE_CREATE_TABLE_CORRUPTION         146
6258#define CLEAR_DB_PAGE_CORRUPTION              147
6259#define VDBE_INDEX_ROWID_CORRUPTION           148
6260#define OP_OPENWRITE_CORRUPTION               149
6261#define OVERSIZE_HEADER_CORRUPTION            150
6262#define UNSUPPORTED_FILE_FORMAT_CORRUPTION    151
6263
6264// End Android Add
6265/************** Continuing where we left off in sqliteInt.h ******************/
6266/************** Include hash.h in the middle of sqliteInt.h ******************/
6267/************** Begin file hash.h ********************************************/
6268/*
6269** 2001 September 22
6270**
6271** The author disclaims copyright to this source code.  In place of
6272** a legal notice, here is a blessing:
6273**
6274**    May you do good and not evil.
6275**    May you find forgiveness for yourself and forgive others.
6276**    May you share freely, never taking more than you give.
6277**
6278*************************************************************************
6279** This is the header file for the generic hash-table implemenation
6280** used in SQLite.
6281*/
6282#ifndef _SQLITE_HASH_H_
6283#define _SQLITE_HASH_H_
6284
6285/* Forward declarations of structures. */
6286typedef struct Hash Hash;
6287typedef struct HashElem HashElem;
6288
6289/* A complete hash table is an instance of the following structure.
6290** The internals of this structure are intended to be opaque -- client
6291** code should not attempt to access or modify the fields of this structure
6292** directly.  Change this structure only by using the routines below.
6293** However, some of the "procedures" and "functions" for modifying and
6294** accessing this structure are really macros, so we can't really make
6295** this structure opaque.
6296**
6297** All elements of the hash table are on a single doubly-linked list.
6298** Hash.first points to the head of this list.
6299**
6300** There are Hash.htsize buckets.  Each bucket points to a spot in
6301** the global doubly-linked list.  The contents of the bucket are the
6302** element pointed to plus the next _ht.count-1 elements in the list.
6303**
6304** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
6305** by a linear search of the global list.  For small tables, the
6306** Hash.ht table is never allocated because if there are few elements
6307** in the table, it is faster to do a linear search than to manage
6308** the hash table.
6309*/
6310struct Hash {
6311  unsigned int htsize;      /* Number of buckets in the hash table */
6312  unsigned int count;       /* Number of entries in this table */
6313  HashElem *first;          /* The first element of the array */
6314  struct _ht {              /* the hash table */
6315    int count;                 /* Number of entries with this hash */
6316    HashElem *chain;           /* Pointer to first entry with this hash */
6317  } *ht;
6318};
6319
6320/* Each element in the hash table is an instance of the following
6321** structure.  All elements are stored on a single doubly-linked list.
6322**
6323** Again, this structure is intended to be opaque, but it can't really
6324** be opaque because it is used by macros.
6325*/
6326struct HashElem {
6327  HashElem *next, *prev;       /* Next and previous elements in the table */
6328  void *data;                  /* Data associated with this element */
6329  const char *pKey; int nKey;  /* Key associated with this element */
6330};
6331
6332/*
6333** Access routines.  To delete, insert a NULL pointer.
6334*/
6335SQLITE_PRIVATE void sqlite3HashInit(Hash*);
6336SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
6337SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
6338SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6339
6340/*
6341** Macros for looping over all elements of a hash table.  The idiom is
6342** like this:
6343**
6344**   Hash h;
6345**   HashElem *p;
6346**   ...
6347**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
6348**     SomeStructure *pData = sqliteHashData(p);
6349**     // do something with pData
6350**   }
6351*/
6352#define sqliteHashFirst(H)  ((H)->first)
6353#define sqliteHashNext(E)   ((E)->next)
6354#define sqliteHashData(E)   ((E)->data)
6355/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
6356/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
6357
6358/*
6359** Number of entries in a hash table
6360*/
6361/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
6362
6363#endif /* _SQLITE_HASH_H_ */
6364
6365/************** End of hash.h ************************************************/
6366/************** Continuing where we left off in sqliteInt.h ******************/
6367/************** Include parse.h in the middle of sqliteInt.h *****************/
6368/************** Begin file parse.h *******************************************/
6369#define TK_SEMI                            1
6370#define TK_EXPLAIN                         2
6371#define TK_QUERY                           3
6372#define TK_PLAN                            4
6373#define TK_BEGIN                           5
6374#define TK_TRANSACTION                     6
6375#define TK_DEFERRED                        7
6376#define TK_IMMEDIATE                       8
6377#define TK_EXCLUSIVE                       9
6378#define TK_COMMIT                         10
6379#define TK_END                            11
6380#define TK_ROLLBACK                       12
6381#define TK_SAVEPOINT                      13
6382#define TK_RELEASE                        14
6383#define TK_TO                             15
6384#define TK_TABLE                          16
6385#define TK_CREATE                         17
6386#define TK_IF                             18
6387#define TK_NOT                            19
6388#define TK_EXISTS                         20
6389#define TK_TEMP                           21
6390#define TK_LP                             22
6391#define TK_RP                             23
6392#define TK_AS                             24
6393#define TK_COMMA                          25
6394#define TK_ID                             26
6395#define TK_INDEXED                        27
6396#define TK_ABORT                          28
6397#define TK_ACTION                         29
6398#define TK_AFTER                          30
6399#define TK_ANALYZE                        31
6400#define TK_ASC                            32
6401#define TK_ATTACH                         33
6402#define TK_BEFORE                         34
6403#define TK_BY                             35
6404#define TK_CASCADE                        36
6405#define TK_CAST                           37
6406#define TK_COLUMNKW                       38
6407#define TK_CONFLICT                       39
6408#define TK_DATABASE                       40
6409#define TK_DESC                           41
6410#define TK_DETACH                         42
6411#define TK_EACH                           43
6412#define TK_FAIL                           44
6413#define TK_FOR                            45
6414#define TK_IGNORE                         46
6415#define TK_INITIALLY                      47
6416#define TK_INSTEAD                        48
6417#define TK_LIKE_KW                        49
6418#define TK_MATCH                          50
6419#define TK_NO                             51
6420#define TK_KEY                            52
6421#define TK_OF                             53
6422#define TK_OFFSET                         54
6423#define TK_PRAGMA                         55
6424#define TK_RAISE                          56
6425#define TK_REPLACE                        57
6426#define TK_RESTRICT                       58
6427#define TK_ROW                            59
6428#define TK_TRIGGER                        60
6429#define TK_VACUUM                         61
6430#define TK_VIEW                           62
6431#define TK_VIRTUAL                        63
6432#define TK_REINDEX                        64
6433#define TK_RENAME                         65
6434#define TK_CTIME_KW                       66
6435#define TK_ANY                            67
6436#define TK_OR                             68
6437#define TK_AND                            69
6438#define TK_IS                             70
6439#define TK_BETWEEN                        71
6440#define TK_IN                             72
6441#define TK_ISNULL                         73
6442#define TK_NOTNULL                        74
6443#define TK_NE                             75
6444#define TK_EQ                             76
6445#define TK_GT                             77
6446#define TK_LE                             78
6447#define TK_LT                             79
6448#define TK_GE                             80
6449#define TK_ESCAPE                         81
6450#define TK_BITAND                         82
6451#define TK_BITOR                          83
6452#define TK_LSHIFT                         84
6453#define TK_RSHIFT                         85
6454#define TK_PLUS                           86
6455#define TK_MINUS                          87
6456#define TK_STAR                           88
6457#define TK_SLASH                          89
6458#define TK_REM                            90
6459#define TK_CONCAT                         91
6460#define TK_COLLATE                        92
6461#define TK_BITNOT                         93
6462#define TK_STRING                         94
6463#define TK_JOIN_KW                        95
6464#define TK_CONSTRAINT                     96
6465#define TK_DEFAULT                        97
6466#define TK_NULL                           98
6467#define TK_PRIMARY                        99
6468#define TK_UNIQUE                         100
6469#define TK_CHECK                          101
6470#define TK_REFERENCES                     102
6471#define TK_AUTOINCR                       103
6472#define TK_ON                             104
6473#define TK_INSERT                         105
6474#define TK_DELETE                         106
6475#define TK_UPDATE                         107
6476#define TK_SET                            108
6477#define TK_DEFERRABLE                     109
6478#define TK_FOREIGN                        110
6479#define TK_DROP                           111
6480#define TK_UNION                          112
6481#define TK_ALL                            113
6482#define TK_EXCEPT                         114
6483#define TK_INTERSECT                      115
6484#define TK_SELECT                         116
6485#define TK_DISTINCT                       117
6486#define TK_DOT                            118
6487#define TK_FROM                           119
6488#define TK_JOIN                           120
6489#define TK_USING                          121
6490#define TK_ORDER                          122
6491#define TK_GROUP                          123
6492#define TK_HAVING                         124
6493#define TK_LIMIT                          125
6494#define TK_WHERE                          126
6495#define TK_INTO                           127
6496#define TK_VALUES                         128
6497#define TK_INTEGER                        129
6498#define TK_FLOAT                          130
6499#define TK_BLOB                           131
6500#define TK_REGISTER                       132
6501#define TK_VARIABLE                       133
6502#define TK_CASE                           134
6503#define TK_WHEN                           135
6504#define TK_THEN                           136
6505#define TK_ELSE                           137
6506#define TK_INDEX                          138
6507#define TK_ALTER                          139
6508#define TK_ADD                            140
6509#define TK_TO_TEXT                        141
6510#define TK_TO_BLOB                        142
6511#define TK_TO_NUMERIC                     143
6512#define TK_TO_INT                         144
6513#define TK_TO_REAL                        145
6514#define TK_ISNOT                          146
6515#define TK_END_OF_FILE                    147
6516#define TK_ILLEGAL                        148
6517#define TK_SPACE                          149
6518#define TK_UNCLOSED_STRING                150
6519#define TK_FUNCTION                       151
6520#define TK_COLUMN                         152
6521#define TK_AGG_FUNCTION                   153
6522#define TK_AGG_COLUMN                     154
6523#define TK_CONST_FUNC                     155
6524#define TK_UMINUS                         156
6525#define TK_UPLUS                          157
6526
6527/************** End of parse.h ***********************************************/
6528/************** Continuing where we left off in sqliteInt.h ******************/
6529#include <stdio.h>
6530#include <stdlib.h>
6531#include <string.h>
6532#include <assert.h>
6533#include <stddef.h>
6534
6535/*
6536** If compiling for a processor that lacks floating point support,
6537** substitute integer for floating-point
6538*/
6539#ifdef SQLITE_OMIT_FLOATING_POINT
6540# define double sqlite_int64
6541# define LONGDOUBLE_TYPE sqlite_int64
6542# ifndef SQLITE_BIG_DBL
6543#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
6544# endif
6545# define SQLITE_OMIT_DATETIME_FUNCS 1
6546# define SQLITE_OMIT_TRACE 1
6547# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
6548# undef SQLITE_HAVE_ISNAN
6549#endif
6550#ifndef SQLITE_BIG_DBL
6551# define SQLITE_BIG_DBL (1e99)
6552#endif
6553
6554/*
6555** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
6556** afterward. Having this macro allows us to cause the C compiler
6557** to omit code used by TEMP tables without messy #ifndef statements.
6558*/
6559#ifdef SQLITE_OMIT_TEMPDB
6560#define OMIT_TEMPDB 1
6561#else
6562#define OMIT_TEMPDB 0
6563#endif
6564
6565/*
6566** If the following macro is set to 1, then NULL values are considered
6567** distinct when determining whether or not two entries are the same
6568** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
6569** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
6570** is the way things are suppose to work.
6571**
6572** If the following macro is set to 0, the NULLs are indistinct for
6573** a UNIQUE index.  In this mode, you can only have a single NULL entry
6574** for a column declared UNIQUE.  This is the way Informix and SQL Server
6575** work.
6576*/
6577#define NULL_DISTINCT_FOR_UNIQUE 1
6578
6579/*
6580** The "file format" number is an integer that is incremented whenever
6581** the VDBE-level file format changes.  The following macros define the
6582** the default file format for new databases and the maximum file format
6583** that the library can read.
6584*/
6585#define SQLITE_MAX_FILE_FORMAT 4
6586#ifndef SQLITE_DEFAULT_FILE_FORMAT
6587# define SQLITE_DEFAULT_FILE_FORMAT 1
6588#endif
6589
6590#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
6591# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
6592#endif
6593
6594/*
6595** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
6596** on the command-line
6597*/
6598#ifndef SQLITE_TEMP_STORE
6599# define SQLITE_TEMP_STORE 1
6600#endif
6601
6602/*
6603** GCC does not define the offsetof() macro so we'll have to do it
6604** ourselves.
6605*/
6606#ifndef offsetof
6607#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
6608#endif
6609
6610/*
6611** Check to see if this machine uses EBCDIC.  (Yes, believe it or
6612** not, there are still machines out there that use EBCDIC.)
6613*/
6614#if 'A' == '\301'
6615# define SQLITE_EBCDIC 1
6616#else
6617# define SQLITE_ASCII 1
6618#endif
6619
6620/*
6621** Integers of known sizes.  These typedefs might change for architectures
6622** where the sizes very.  Preprocessor macros are available so that the
6623** types can be conveniently redefined at compile-type.  Like this:
6624**
6625**         cc '-DUINTPTR_TYPE=long long int' ...
6626*/
6627#ifndef UINT32_TYPE
6628# ifdef HAVE_UINT32_T
6629#  define UINT32_TYPE uint32_t
6630# else
6631#  define UINT32_TYPE unsigned int
6632# endif
6633#endif
6634#ifndef UINT16_TYPE
6635# ifdef HAVE_UINT16_T
6636#  define UINT16_TYPE uint16_t
6637# else
6638#  define UINT16_TYPE unsigned short int
6639# endif
6640#endif
6641#ifndef INT16_TYPE
6642# ifdef HAVE_INT16_T
6643#  define INT16_TYPE int16_t
6644# else
6645#  define INT16_TYPE short int
6646# endif
6647#endif
6648#ifndef UINT8_TYPE
6649# ifdef HAVE_UINT8_T
6650#  define UINT8_TYPE uint8_t
6651# else
6652#  define UINT8_TYPE unsigned char
6653# endif
6654#endif
6655#ifndef INT8_TYPE
6656# ifdef HAVE_INT8_T
6657#  define INT8_TYPE int8_t
6658# else
6659#  define INT8_TYPE signed char
6660# endif
6661#endif
6662#ifndef LONGDOUBLE_TYPE
6663# define LONGDOUBLE_TYPE long double
6664#endif
6665typedef sqlite_int64 i64;          /* 8-byte signed integer */
6666typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
6667typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
6668typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
6669typedef INT16_TYPE i16;            /* 2-byte signed integer */
6670typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
6671typedef INT8_TYPE i8;              /* 1-byte signed integer */
6672
6673/*
6674** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
6675** that can be stored in a u32 without loss of data.  The value
6676** is 0x00000000ffffffff.  But because of quirks of some compilers, we
6677** have to specify the value in the less intuitive manner shown:
6678*/
6679#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
6680
6681/*
6682** Macros to determine whether the machine is big or little endian,
6683** evaluated at runtime.
6684*/
6685#ifdef SQLITE_AMALGAMATION
6686SQLITE_PRIVATE const int sqlite3one = 1;
6687#else
6688SQLITE_PRIVATE const int sqlite3one;
6689#endif
6690#if defined(i386) || defined(__i386__) || defined(_M_IX86)\
6691                             || defined(__x86_64) || defined(__x86_64__)
6692# define SQLITE_BIGENDIAN    0
6693# define SQLITE_LITTLEENDIAN 1
6694# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
6695#else
6696# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
6697# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
6698# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
6699#endif
6700
6701/*
6702** Constants for the largest and smallest possible 64-bit signed integers.
6703** These macros are designed to work correctly on both 32-bit and 64-bit
6704** compilers.
6705*/
6706#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
6707#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
6708
6709/*
6710** Round up a number to the next larger multiple of 8.  This is used
6711** to force 8-byte alignment on 64-bit architectures.
6712*/
6713#define ROUND8(x)     (((x)+7)&~7)
6714
6715/*
6716** Round down to the nearest multiple of 8
6717*/
6718#define ROUNDDOWN8(x) ((x)&~7)
6719
6720/*
6721** Assert that the pointer X is aligned to an 8-byte boundary.  This
6722** macro is used only within assert() to verify that the code gets
6723** all alignment restrictions correct.
6724**
6725** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
6726** underlying malloc() implemention might return us 4-byte aligned
6727** pointers.  In that case, only verify 4-byte alignment.
6728*/
6729#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
6730# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
6731#else
6732# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
6733#endif
6734
6735
6736/*
6737** An instance of the following structure is used to store the busy-handler
6738** callback for a given sqlite handle.
6739**
6740** The sqlite.busyHandler member of the sqlite struct contains the busy
6741** callback for the database handle. Each pager opened via the sqlite
6742** handle is passed a pointer to sqlite.busyHandler. The busy-handler
6743** callback is currently invoked only from within pager.c.
6744*/
6745typedef struct BusyHandler BusyHandler;
6746struct BusyHandler {
6747  int (*xFunc)(void *,int);  /* The busy callback */
6748  void *pArg;                /* First arg to busy callback */
6749  int nBusy;                 /* Incremented with each busy call */
6750};
6751
6752/*
6753** Name of the master database table.  The master database table
6754** is a special table that holds the names and attributes of all
6755** user tables and indices.
6756*/
6757#define MASTER_NAME       "sqlite_master"
6758#define TEMP_MASTER_NAME  "sqlite_temp_master"
6759
6760/*
6761** The root-page of the master database table.
6762*/
6763#define MASTER_ROOT       1
6764
6765/*
6766** The name of the schema table.
6767*/
6768#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
6769
6770/*
6771** A convenience macro that returns the number of elements in
6772** an array.
6773*/
6774#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
6775
6776/*
6777** The following value as a destructor means to use sqlite3DbFree().
6778** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
6779*/
6780#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
6781
6782/*
6783** When SQLITE_OMIT_WSD is defined, it means that the target platform does
6784** not support Writable Static Data (WSD) such as global and static variables.
6785** All variables must either be on the stack or dynamically allocated from
6786** the heap.  When WSD is unsupported, the variable declarations scattered
6787** throughout the SQLite code must become constants instead.  The SQLITE_WSD
6788** macro is used for this purpose.  And instead of referencing the variable
6789** directly, we use its constant as a key to lookup the run-time allocated
6790** buffer that holds real variable.  The constant is also the initializer
6791** for the run-time allocated buffer.
6792**
6793** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
6794** macros become no-ops and have zero performance impact.
6795*/
6796#ifdef SQLITE_OMIT_WSD
6797  #define SQLITE_WSD const
6798  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
6799  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
6800SQLITE_API   int sqlite3_wsd_init(int N, int J);
6801SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
6802#else
6803  #define SQLITE_WSD
6804  #define GLOBAL(t,v) v
6805  #define sqlite3GlobalConfig sqlite3Config
6806#endif
6807
6808/*
6809** The following macros are used to suppress compiler warnings and to
6810** make it clear to human readers when a function parameter is deliberately
6811** left unused within the body of a function. This usually happens when
6812** a function is called via a function pointer. For example the
6813** implementation of an SQL aggregate step callback may not use the
6814** parameter indicating the number of arguments passed to the aggregate,
6815** if it knows that this is enforced elsewhere.
6816**
6817** When a function parameter is not used at all within the body of a function,
6818** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
6819** However, these macros may also be used to suppress warnings related to
6820** parameters that may or may not be used depending on compilation options.
6821** For example those parameters only used in assert() statements. In these
6822** cases the parameters are named as per the usual conventions.
6823*/
6824#define UNUSED_PARAMETER(x) (void)(x)
6825#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
6826
6827/*
6828** Forward references to structures
6829*/
6830typedef struct AggInfo AggInfo;
6831typedef struct AuthContext AuthContext;
6832typedef struct AutoincInfo AutoincInfo;
6833typedef struct Bitvec Bitvec;
6834typedef struct RowSet RowSet;
6835typedef struct CollSeq CollSeq;
6836typedef struct Column Column;
6837typedef struct Db Db;
6838typedef struct Schema Schema;
6839typedef struct Expr Expr;
6840typedef struct ExprList ExprList;
6841typedef struct ExprSpan ExprSpan;
6842typedef struct FKey FKey;
6843typedef struct FuncDef FuncDef;
6844typedef struct FuncDefHash FuncDefHash;
6845typedef struct IdList IdList;
6846typedef struct Index Index;
6847typedef struct IndexSample IndexSample;
6848typedef struct KeyClass KeyClass;
6849typedef struct KeyInfo KeyInfo;
6850typedef struct Lookaside Lookaside;
6851typedef struct LookasideSlot LookasideSlot;
6852typedef struct Module Module;
6853typedef struct NameContext NameContext;
6854typedef struct Parse Parse;
6855typedef struct Savepoint Savepoint;
6856typedef struct Select Select;
6857typedef struct SrcList SrcList;
6858typedef struct StrAccum StrAccum;
6859typedef struct Table Table;
6860typedef struct TableLock TableLock;
6861typedef struct Token Token;
6862typedef struct TriggerPrg TriggerPrg;
6863typedef struct TriggerStep TriggerStep;
6864typedef struct Trigger Trigger;
6865typedef struct UnpackedRecord UnpackedRecord;
6866typedef struct VTable VTable;
6867typedef struct Walker Walker;
6868typedef struct WherePlan WherePlan;
6869typedef struct WhereInfo WhereInfo;
6870typedef struct WhereLevel WhereLevel;
6871
6872/*
6873** Defer sourcing vdbe.h and btree.h until after the "u8" and
6874** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
6875** pointer types (i.e. FuncDef) defined above.
6876*/
6877/************** Include btree.h in the middle of sqliteInt.h *****************/
6878/************** Begin file btree.h *******************************************/
6879/*
6880** 2001 September 15
6881**
6882** The author disclaims copyright to this source code.  In place of
6883** a legal notice, here is a blessing:
6884**
6885**    May you do good and not evil.
6886**    May you find forgiveness for yourself and forgive others.
6887**    May you share freely, never taking more than you give.
6888**
6889*************************************************************************
6890** This header file defines the interface that the sqlite B-Tree file
6891** subsystem.  See comments in the source code for a detailed description
6892** of what each interface routine does.
6893*/
6894#ifndef _BTREE_H_
6895#define _BTREE_H_
6896
6897/* TODO: This definition is just included so other modules compile. It
6898** needs to be revisited.
6899*/
6900#define SQLITE_N_BTREE_META 10
6901
6902/*
6903** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
6904** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
6905*/
6906#ifndef SQLITE_DEFAULT_AUTOVACUUM
6907  #define SQLITE_DEFAULT_AUTOVACUUM 0
6908#endif
6909
6910#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
6911#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
6912#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
6913
6914/*
6915** Forward declarations of structure
6916*/
6917typedef struct Btree Btree;
6918typedef struct BtCursor BtCursor;
6919typedef struct BtShared BtShared;
6920typedef struct BtreeMutexArray BtreeMutexArray;
6921
6922/*
6923** This structure records all of the Btrees that need to hold
6924** a mutex before we enter sqlite3VdbeExec().  The Btrees are
6925** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
6926** we can always lock and unlock them all quickly.
6927*/
6928struct BtreeMutexArray {
6929  int nMutex;
6930  Btree *aBtree[SQLITE_MAX_ATTACHED+1];
6931};
6932
6933
6934SQLITE_PRIVATE int sqlite3BtreeOpen(
6935  const char *zFilename,   /* Name of database file to open */
6936  sqlite3 *db,             /* Associated database connection */
6937  Btree **ppBtree,         /* Return open Btree* here */
6938  int flags,               /* Flags */
6939  int vfsFlags             /* Flags passed through to VFS open */
6940);
6941
6942/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
6943** following values.
6944**
6945** NOTE:  These values must match the corresponding PAGER_ values in
6946** pager.h.
6947*/
6948#define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
6949#define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
6950#define BTREE_MEMORY        4  /* In-memory DB.  No argument */
6951#define BTREE_READONLY      8  /* Open the database in read-only mode */
6952#define BTREE_READWRITE    16  /* Open for both reading and writing */
6953#define BTREE_CREATE       32  /* Create the database if it does not exist */
6954
6955SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
6956SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
6957SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
6958SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
6959SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
6960SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
6961SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
6962SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
6963SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
6964SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
6965SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
6966SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
6967SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
6968SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
6969SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
6970SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
6971SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
6972SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
6973SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
6974SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
6975SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
6976SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
6977SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
6978SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
6979
6980SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
6981SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
6982SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
6983
6984SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
6985
6986/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
6987** of the following flags:
6988*/
6989#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
6990#define BTREE_ZERODATA   2    /* Table has keys only - no data */
6991#define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
6992
6993SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
6994SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
6995SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
6996
6997SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
6998SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
6999
7000/*
7001** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
7002** should be one of the following values. The integer values are assigned
7003** to constants so that the offset of the corresponding field in an
7004** SQLite database header may be found using the following formula:
7005**
7006**   offset = 36 + (idx * 4)
7007**
7008** For example, the free-page-count field is located at byte offset 36 of
7009** the database file header. The incr-vacuum-flag field is located at
7010** byte offset 64 (== 36+4*7).
7011*/
7012#define BTREE_FREE_PAGE_COUNT     0
7013#define BTREE_SCHEMA_VERSION      1
7014#define BTREE_FILE_FORMAT         2
7015#define BTREE_DEFAULT_CACHE_SIZE  3
7016#define BTREE_LARGEST_ROOT_PAGE   4
7017#define BTREE_TEXT_ENCODING       5
7018#define BTREE_USER_VERSION        6
7019#define BTREE_INCR_VACUUM         7
7020
7021SQLITE_PRIVATE int sqlite3BtreeCursor(
7022  Btree*,                              /* BTree containing table to open */
7023  int iTable,                          /* Index of root page */
7024  int wrFlag,                          /* 1 for writing.  0 for read-only */
7025  struct KeyInfo*,                     /* First argument to compare function */
7026  BtCursor *pCursor                    /* Space to write cursor structure */
7027);
7028SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7029SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
7030
7031SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7032SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7033  BtCursor*,
7034  UnpackedRecord *pUnKey,
7035  i64 intKey,
7036  int bias,
7037  int *pRes
7038);
7039SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7040SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7041SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7042                                  const void *pData, int nData,
7043                                  int nZero, int bias, int seekResult);
7044SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7045SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7046SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7047SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7048SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7049SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7050SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7051SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7052SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7053SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7054SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7055SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
7056SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
7057
7058SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7059SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7060
7061SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7062SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7063SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7064
7065#ifndef NDEBUG
7066SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7067#endif
7068
7069#ifndef SQLITE_OMIT_BTREECOUNT
7070SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
7071#endif
7072
7073#ifdef SQLITE_TEST
7074SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7075SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7076#endif
7077
7078/*
7079** If we are not using shared cache, then there is no need to
7080** use mutexes to access the BtShared structures.  So make the
7081** Enter and Leave procedures no-ops.
7082*/
7083#ifndef SQLITE_OMIT_SHARED_CACHE
7084SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7085SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7086#else
7087# define sqlite3BtreeEnter(X)
7088# define sqlite3BtreeEnterAll(X)
7089#endif
7090
7091#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7092SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7093SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7094SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7095SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7096SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7097SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7098SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7099#ifndef NDEBUG
7100  /* These routines are used inside assert() statements only. */
7101SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7102SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7103#endif
7104#else
7105
7106# define sqlite3BtreeLeave(X)
7107# define sqlite3BtreeEnterCursor(X)
7108# define sqlite3BtreeLeaveCursor(X)
7109# define sqlite3BtreeLeaveAll(X)
7110# define sqlite3BtreeMutexArrayEnter(X)
7111# define sqlite3BtreeMutexArrayLeave(X)
7112# define sqlite3BtreeMutexArrayInsert(X,Y)
7113
7114# define sqlite3BtreeHoldsMutex(X) 1
7115# define sqlite3BtreeHoldsAllMutexes(X) 1
7116#endif
7117
7118
7119#endif /* _BTREE_H_ */
7120
7121/************** End of btree.h ***********************************************/
7122/************** Continuing where we left off in sqliteInt.h ******************/
7123/************** Include vdbe.h in the middle of sqliteInt.h ******************/
7124/************** Begin file vdbe.h ********************************************/
7125/*
7126** 2001 September 15
7127**
7128** The author disclaims copyright to this source code.  In place of
7129** a legal notice, here is a blessing:
7130**
7131**    May you do good and not evil.
7132**    May you find forgiveness for yourself and forgive others.
7133**    May you share freely, never taking more than you give.
7134**
7135*************************************************************************
7136** Header file for the Virtual DataBase Engine (VDBE)
7137**
7138** This header defines the interface to the virtual database engine
7139** or VDBE.  The VDBE implements an abstract machine that runs a
7140** simple program to access and modify the underlying database.
7141*/
7142#ifndef _SQLITE_VDBE_H_
7143#define _SQLITE_VDBE_H_
7144
7145/*
7146** A single VDBE is an opaque structure named "Vdbe".  Only routines
7147** in the source file sqliteVdbe.c are allowed to see the insides
7148** of this structure.
7149*/
7150typedef struct Vdbe Vdbe;
7151
7152/*
7153** The names of the following types declared in vdbeInt.h are required
7154** for the VdbeOp definition.
7155*/
7156typedef struct VdbeFunc VdbeFunc;
7157typedef struct Mem Mem;
7158typedef struct SubProgram SubProgram;
7159
7160/*
7161** A single instruction of the virtual machine has an opcode
7162** and as many as three operands.  The instruction is recorded
7163** as an instance of the following structure:
7164*/
7165struct VdbeOp {
7166  u8 opcode;          /* What operation to perform */
7167  signed char p4type; /* One of the P4_xxx constants for p4 */
7168  u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
7169  u8 p5;              /* Fifth parameter is an unsigned character */
7170  int p1;             /* First operand */
7171  int p2;             /* Second parameter (often the jump destination) */
7172  int p3;             /* The third parameter */
7173  union {             /* fourth parameter */
7174    int i;                 /* Integer value if p4type==P4_INT32 */
7175    void *p;               /* Generic pointer */
7176    char *z;               /* Pointer to data for string (char array) types */
7177    i64 *pI64;             /* Used when p4type is P4_INT64 */
7178    double *pReal;         /* Used when p4type is P4_REAL */
7179    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7180    VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7181    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7182    Mem *pMem;             /* Used when p4type is P4_MEM */
7183    VTable *pVtab;         /* Used when p4type is P4_VTAB */
7184    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7185    int *ai;               /* Used when p4type is P4_INTARRAY */
7186    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
7187  } p4;
7188#ifdef SQLITE_DEBUG
7189  char *zComment;          /* Comment to improve readability */
7190#endif
7191#ifdef VDBE_PROFILE
7192  int cnt;                 /* Number of times this instruction was executed */
7193  u64 cycles;              /* Total time spent executing this instruction */
7194#endif
7195};
7196typedef struct VdbeOp VdbeOp;
7197
7198
7199/*
7200** A sub-routine used to implement a trigger program.
7201*/
7202struct SubProgram {
7203  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
7204  int nOp;                      /* Elements in aOp[] */
7205  int nMem;                     /* Number of memory cells required */
7206  int nCsr;                     /* Number of cursors required */
7207  int nRef;                     /* Number of pointers to this structure */
7208  void *token;                  /* id that may be used to recursive triggers */
7209};
7210
7211/*
7212** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7213** it takes up less space.
7214*/
7215struct VdbeOpList {
7216  u8 opcode;          /* What operation to perform */
7217  signed char p1;     /* First operand */
7218  signed char p2;     /* Second parameter (often the jump destination) */
7219  signed char p3;     /* Third parameter */
7220};
7221typedef struct VdbeOpList VdbeOpList;
7222
7223/*
7224** Allowed values of VdbeOp.p4type
7225*/
7226#define P4_NOTUSED    0   /* The P4 parameter is not used */
7227#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7228#define P4_STATIC   (-2)  /* Pointer to a static string */
7229#define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7230#define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7231#define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7232#define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7233#define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7234#define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
7235#define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7236#define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7237#define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7238#define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7239#define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7240#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7241#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
7242
7243/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7244** is made.  That copy is freed when the Vdbe is finalized.  But if the
7245** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7246** gets freed when the Vdbe is finalized so it still should be obtained
7247** from a single sqliteMalloc().  But no copy is made and the calling
7248** function should *not* try to free the KeyInfo.
7249*/
7250#define P4_KEYINFO_HANDOFF (-16)
7251#define P4_KEYINFO_STATIC  (-17)
7252
7253/*
7254** The Vdbe.aColName array contains 5n Mem structures, where n is the
7255** number of columns of data returned by the statement.
7256*/
7257#define COLNAME_NAME     0
7258#define COLNAME_DECLTYPE 1
7259#define COLNAME_DATABASE 2
7260#define COLNAME_TABLE    3
7261#define COLNAME_COLUMN   4
7262#ifdef SQLITE_ENABLE_COLUMN_METADATA
7263# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
7264#else
7265# ifdef SQLITE_OMIT_DECLTYPE
7266#   define COLNAME_N      1      /* Store only the name */
7267# else
7268#   define COLNAME_N      2      /* Store the name and decltype */
7269# endif
7270#endif
7271
7272/*
7273** The following macro converts a relative address in the p2 field
7274** of a VdbeOp structure into a negative number so that
7275** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
7276** the macro again restores the address.
7277*/
7278#define ADDR(X)  (-1-(X))
7279
7280/*
7281** The makefile scans the vdbe.c source file and creates the "opcodes.h"
7282** header file that defines a number for each opcode used by the VDBE.
7283*/
7284/************** Include opcodes.h in the middle of vdbe.h ********************/
7285/************** Begin file opcodes.h *****************************************/
7286/* Automatically generated.  Do not edit */
7287/* See the mkopcodeh.awk script for details */
7288#define OP_Goto                                 1
7289#define OP_Gosub                                2
7290#define OP_Return                               3
7291#define OP_Yield                                4
7292#define OP_HaltIfNull                           5
7293#define OP_Halt                                 6
7294#define OP_Integer                              7
7295#define OP_Int64                                8
7296#define OP_Real                               130   /* same as TK_FLOAT    */
7297#define OP_String8                             94   /* same as TK_STRING   */
7298#define OP_String                               9
7299#define OP_Null                                10
7300#define OP_Blob                                11
7301#define OP_Variable                            12
7302#define OP_Move                                13
7303#define OP_Copy                                14
7304#define OP_SCopy                               15
7305#define OP_ResultRow                           16
7306#define OP_Concat                              91   /* same as TK_CONCAT   */
7307#define OP_Add                                 86   /* same as TK_PLUS     */
7308#define OP_Subtract                            87   /* same as TK_MINUS    */
7309#define OP_Multiply                            88   /* same as TK_STAR     */
7310#define OP_Divide                              89   /* same as TK_SLASH    */
7311#define OP_Remainder                           90   /* same as TK_REM      */
7312#define OP_CollSeq                             17
7313#define OP_Function                            18
7314#define OP_BitAnd                              82   /* same as TK_BITAND   */
7315#define OP_BitOr                               83   /* same as TK_BITOR    */
7316#define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
7317#define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
7318#define OP_AddImm                              20
7319#define OP_MustBeInt                           21
7320#define OP_RealAffinity                        22
7321#define OP_ToText                             141   /* same as TK_TO_TEXT  */
7322#define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
7323#define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
7324#define OP_ToInt                              144   /* same as TK_TO_INT   */
7325#define OP_ToReal                             145   /* same as TK_TO_REAL  */
7326#define OP_Eq                                  76   /* same as TK_EQ       */
7327#define OP_Ne                                  75   /* same as TK_NE       */
7328#define OP_Lt                                  79   /* same as TK_LT       */
7329#define OP_Le                                  78   /* same as TK_LE       */
7330#define OP_Gt                                  77   /* same as TK_GT       */
7331#define OP_Ge                                  80   /* same as TK_GE       */
7332#define OP_Permutation                         23
7333#define OP_Compare                             24
7334#define OP_Jump                                25
7335#define OP_And                                 69   /* same as TK_AND      */
7336#define OP_Or                                  68   /* same as TK_OR       */
7337#define OP_Not                                 19   /* same as TK_NOT      */
7338#define OP_BitNot                              93   /* same as TK_BITNOT   */
7339#define OP_If                                  26
7340#define OP_IfNot                               27
7341#define OP_IsNull                              73   /* same as TK_ISNULL   */
7342#define OP_NotNull                             74   /* same as TK_NOTNULL  */
7343#define OP_Column                              28
7344#define OP_Affinity                            29
7345#define OP_MakeRecord                          30
7346#define OP_Count                               31
7347#define OP_Savepoint                           32
7348#define OP_AutoCommit                          33
7349#define OP_Transaction                         34
7350#define OP_ReadCookie                          35
7351#define OP_SetCookie                           36
7352#define OP_VerifyCookie                        37
7353#define OP_OpenRead                            38
7354#define OP_OpenWrite                           39
7355#define OP_OpenEphemeral                       40
7356#define OP_OpenPseudo                          41
7357#define OP_Close                               42
7358#define OP_SeekLt                              43
7359#define OP_SeekLe                              44
7360#define OP_SeekGe                              45
7361#define OP_SeekGt                              46
7362#define OP_Seek                                47
7363#define OP_NotFound                            48
7364#define OP_Found                               49
7365#define OP_IsUnique                            50
7366#define OP_NotExists                           51
7367#define OP_Sequence                            52
7368#define OP_NewRowid                            53
7369#define OP_Insert                              54
7370#define OP_InsertInt                           55
7371#define OP_Delete                              56
7372#define OP_ResetCount                          57
7373#define OP_RowKey                              58
7374#define OP_RowData                             59
7375#define OP_Rowid                               60
7376#define OP_NullRow                             61
7377#define OP_Last                                62
7378#define OP_Sort                                63
7379#define OP_Rewind                              64
7380#define OP_Prev                                65
7381#define OP_Next                                66
7382#define OP_IdxInsert                           67
7383#define OP_IdxDelete                           70
7384#define OP_IdxRowid                            71
7385#define OP_IdxLT                               72
7386#define OP_IdxGE                               81
7387#define OP_Destroy                             92
7388#define OP_Clear                               95
7389#define OP_CreateIndex                         96
7390#define OP_CreateTable                         97
7391#define OP_ParseSchema                         98
7392#define OP_LoadAnalysis                        99
7393#define OP_DropTable                          100
7394#define OP_DropIndex                          101
7395#define OP_DropTrigger                        102
7396#define OP_IntegrityCk                        103
7397#define OP_RowSetAdd                          104
7398#define OP_RowSetRead                         105
7399#define OP_RowSetTest                         106
7400#define OP_Program                            107
7401#define OP_Param                              108
7402#define OP_FkCounter                          109
7403#define OP_FkIfZero                           110
7404#define OP_MemMax                             111
7405#define OP_IfPos                              112
7406#define OP_IfNeg                              113
7407#define OP_IfZero                             114
7408#define OP_AggStep                            115
7409#define OP_AggFinal                           116
7410#define OP_Vacuum                             117
7411#define OP_IncrVacuum                         118
7412#define OP_Expire                             119
7413#define OP_TableLock                          120
7414#define OP_VBegin                             121
7415#define OP_VCreate                            122
7416#define OP_VDestroy                           123
7417#define OP_VOpen                              124
7418#define OP_VFilter                            125
7419#define OP_VColumn                            126
7420#define OP_VNext                              127
7421#define OP_VRename                            128
7422#define OP_VUpdate                            129
7423#define OP_Pagecount                          131
7424#define OP_Trace                              132
7425#define OP_Noop                               133
7426#define OP_Explain                            134
7427
7428/* The following opcode values are never used */
7429#define OP_NotUsed_135                        135
7430#define OP_NotUsed_136                        136
7431#define OP_NotUsed_137                        137
7432#define OP_NotUsed_138                        138
7433#define OP_NotUsed_139                        139
7434#define OP_NotUsed_140                        140
7435
7436
7437/* Properties such as "out2" or "jump" that are specified in
7438** comments following the "case" for each opcode in the vdbe.c
7439** are encoded into bitvectors as follows:
7440*/
7441#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
7442#define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
7443#define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
7444#define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
7445#define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
7446#define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
7447#define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
7448#define OPFLG_INITIALIZER {\
7449/*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
7450/*   8 */ 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x24,\
7451/*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
7452/*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7453/*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
7454/*  40 */ 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x08,\
7455/*  48 */ 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00, 0x00,\
7456/*  56 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x01,\
7457/*  64 */ 0x01, 0x01, 0x01, 0x08, 0x4c, 0x4c, 0x00, 0x02,\
7458/*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
7459/*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
7460/*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x02, 0x24, 0x02, 0x00,\
7461/*  96 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7462/* 104 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
7463/* 112 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00,\
7464/* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01,\
7465/* 128 */ 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00,\
7466/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
7467/* 144 */ 0x04, 0x04,}
7468
7469/************** End of opcodes.h *********************************************/
7470/************** Continuing where we left off in vdbe.h ***********************/
7471
7472/*
7473** Prototypes for the VDBE interface.  See comments on the implementation
7474** for a description of what each of these routines does.
7475*/
7476SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
7477SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
7478SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
7479SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
7480SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
7481SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
7482SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
7483SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
7484SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
7485SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
7486SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
7487SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
7488SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
7489SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
7490SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
7491SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
7492SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
7493SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
7494SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
7495SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
7496SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
7497SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
7498SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
7499#ifdef SQLITE_DEBUG
7500SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
7501SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
7502#endif
7503SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
7504SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
7505SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
7506SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
7507SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
7508SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
7509SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
7510SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
7511SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
7512SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *, SubProgram *, int);
7513SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
7514SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
7515#ifndef SQLITE_OMIT_TRACE
7516SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
7517#endif
7518
7519SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
7520SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
7521SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
7522
7523
7524#ifndef NDEBUG
7525SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
7526# define VdbeComment(X)  sqlite3VdbeComment X
7527SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
7528# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
7529#else
7530# define VdbeComment(X)
7531# define VdbeNoopComment(X)
7532#endif
7533
7534#endif
7535
7536/************** End of vdbe.h ************************************************/
7537/************** Continuing where we left off in sqliteInt.h ******************/
7538/************** Include pager.h in the middle of sqliteInt.h *****************/
7539/************** Begin file pager.h *******************************************/
7540/*
7541** 2001 September 15
7542**
7543** The author disclaims copyright to this source code.  In place of
7544** a legal notice, here is a blessing:
7545**
7546**    May you do good and not evil.
7547**    May you find forgiveness for yourself and forgive others.
7548**    May you share freely, never taking more than you give.
7549**
7550*************************************************************************
7551** This header file defines the interface that the sqlite page cache
7552** subsystem.  The page cache subsystem reads and writes a file a page
7553** at a time and provides a journal for rollback.
7554*/
7555
7556#ifndef _PAGER_H_
7557#define _PAGER_H_
7558
7559/*
7560** Default maximum size for persistent journal files. A negative
7561** value means no limit. This value may be overridden using the
7562** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
7563*/
7564#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
7565  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
7566#endif
7567
7568/*
7569** The type used to represent a page number.  The first page in a file
7570** is called page 1.  0 is used to represent "not a page".
7571*/
7572typedef u32 Pgno;
7573
7574/*
7575** Each open file is managed by a separate instance of the "Pager" structure.
7576*/
7577typedef struct Pager Pager;
7578
7579/*
7580** Handle type for pages.
7581*/
7582typedef struct PgHdr DbPage;
7583
7584/*
7585** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
7586** reserved for working around a windows/posix incompatibility). It is
7587** used in the journal to signify that the remainder of the journal file
7588** is devoted to storing a master journal name - there are no more pages to
7589** roll back. See comments for function writeMasterJournal() in pager.c
7590** for details.
7591*/
7592#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
7593
7594/*
7595** Allowed values for the flags parameter to sqlite3PagerOpen().
7596**
7597** NOTE: These values must match the corresponding BTREE_ values in btree.h.
7598*/
7599#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
7600#define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
7601
7602/*
7603** Valid values for the second argument to sqlite3PagerLockingMode().
7604*/
7605#define PAGER_LOCKINGMODE_QUERY      -1
7606#define PAGER_LOCKINGMODE_NORMAL      0
7607#define PAGER_LOCKINGMODE_EXCLUSIVE   1
7608
7609/*
7610** Valid values for the second argument to sqlite3PagerJournalMode().
7611*/
7612#define PAGER_JOURNALMODE_QUERY      -1
7613#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
7614#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
7615#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
7616#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
7617#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
7618
7619/*
7620** The remainder of this file contains the declarations of the functions
7621** that make up the Pager sub-system API. See source code comments for
7622** a detailed description of each routine.
7623*/
7624
7625/* Open and close a Pager connection. */
7626SQLITE_PRIVATE int sqlite3PagerOpen(
7627  sqlite3_vfs*,
7628  Pager **ppPager,
7629  const char*,
7630  int,
7631  int,
7632  int,
7633  void(*)(DbPage*)
7634);
7635SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
7636SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
7637
7638/* Functions used to configure a Pager object. */
7639SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
7640SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*, int);
7641SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
7642SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
7643SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
7644SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
7645SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
7646SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
7647SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
7648
7649/* Functions used to obtain and release page references. */
7650SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
7651#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
7652SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
7653SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
7654SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
7655
7656/* Operations on page references. */
7657SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
7658SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
7659SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
7660SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
7661SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
7662SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
7663
7664/* Functions used to manage pager transactions and savepoints. */
7665SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
7666SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
7667SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
7668SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
7669SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7670SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
7671SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
7672SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
7673SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
7674
7675/* Functions used to query pager state and configuration. */
7676SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
7677SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
7678SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
7679SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
7680SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
7681SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
7682SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
7683SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
7684SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
7685
7686/* Functions used to truncate the database file. */
7687SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
7688
7689/* Functions to support testing and debugging. */
7690#if !defined(NDEBUG) || defined(SQLITE_TEST)
7691SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
7692SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
7693#endif
7694#ifdef SQLITE_TEST
7695SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
7696SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
7697  void disable_simulated_io_errors(void);
7698  void enable_simulated_io_errors(void);
7699#else
7700# define disable_simulated_io_errors()
7701# define enable_simulated_io_errors()
7702#endif
7703
7704#endif /* _PAGER_H_ */
7705
7706/************** End of pager.h ***********************************************/
7707/************** Continuing where we left off in sqliteInt.h ******************/
7708/************** Include pcache.h in the middle of sqliteInt.h ****************/
7709/************** Begin file pcache.h ******************************************/
7710/*
7711** 2008 August 05
7712**
7713** The author disclaims copyright to this source code.  In place of
7714** a legal notice, here is a blessing:
7715**
7716**    May you do good and not evil.
7717**    May you find forgiveness for yourself and forgive others.
7718**    May you share freely, never taking more than you give.
7719**
7720*************************************************************************
7721** This header file defines the interface that the sqlite page cache
7722** subsystem.
7723*/
7724
7725#ifndef _PCACHE_H_
7726
7727typedef struct PgHdr PgHdr;
7728typedef struct PCache PCache;
7729
7730/*
7731** Every page in the cache is controlled by an instance of the following
7732** structure.
7733*/
7734struct PgHdr {
7735  void *pData;                   /* Content of this page */
7736  void *pExtra;                  /* Extra content */
7737  PgHdr *pDirty;                 /* Transient list of dirty pages */
7738  Pgno pgno;                     /* Page number for this page */
7739  Pager *pPager;                 /* The pager this page is part of */
7740#ifdef SQLITE_CHECK_PAGES
7741  u32 pageHash;                  /* Hash of page content */
7742#endif
7743  u16 flags;                     /* PGHDR flags defined below */
7744
7745  /**********************************************************************
7746  ** Elements above are public.  All that follows is private to pcache.c
7747  ** and should not be accessed by other modules.
7748  */
7749  i16 nRef;                      /* Number of users of this page */
7750  PCache *pCache;                /* Cache that owns this page */
7751
7752  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
7753  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
7754};
7755
7756/* Bit values for PgHdr.flags */
7757#define PGHDR_DIRTY             0x002  /* Page has changed */
7758#define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
7759                                       ** writing this page to the database */
7760#define PGHDR_NEED_READ         0x008  /* Content is unread */
7761#define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
7762#define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
7763
7764/* Initialize and shutdown the page cache subsystem */
7765SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
7766SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
7767
7768/* Page cache buffer management:
7769** These routines implement SQLITE_CONFIG_PAGECACHE.
7770*/
7771SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
7772
7773/* Create a new pager cache.
7774** Under memory stress, invoke xStress to try to make pages clean.
7775** Only clean and unpinned pages can be reclaimed.
7776*/
7777SQLITE_PRIVATE void sqlite3PcacheOpen(
7778  int szPage,                    /* Size of every page */
7779  int szExtra,                   /* Extra space associated with each page */
7780  int bPurgeable,                /* True if pages are on backing store */
7781  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
7782  void *pStress,                 /* Argument to xStress */
7783  PCache *pToInit                /* Preallocated space for the PCache */
7784);
7785
7786/* Modify the page-size after the cache has been created. */
7787SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
7788
7789/* Return the size in bytes of a PCache object.  Used to preallocate
7790** storage space.
7791*/
7792SQLITE_PRIVATE int sqlite3PcacheSize(void);
7793
7794/* One release per successful fetch.  Page is pinned until released.
7795** Reference counted.
7796*/
7797SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
7798SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
7799
7800SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
7801SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
7802SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
7803SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
7804
7805/* Change a page number.  Used by incr-vacuum. */
7806SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
7807
7808/* Remove all pages with pgno>x.  Reset the cache if x==0 */
7809SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
7810
7811/* Get a list of all dirty pages in the cache, sorted by page number */
7812SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
7813
7814/* Reset and close the cache object */
7815SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
7816
7817/* Clear flags from pages of the page cache */
7818SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
7819
7820/* Discard the contents of the cache */
7821SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
7822
7823/* Return the total number of outstanding page references */
7824SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
7825
7826/* Increment the reference count of an existing page */
7827SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
7828
7829SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
7830
7831/* Return the total number of pages stored in the cache */
7832SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
7833
7834#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
7835/* Iterate through all dirty pages currently stored in the cache. This
7836** interface is only available if SQLITE_CHECK_PAGES is defined when the
7837** library is built.
7838*/
7839SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
7840#endif
7841
7842/* Set and get the suggested cache-size for the specified pager-cache.
7843**
7844** If no global maximum is configured, then the system attempts to limit
7845** the total number of pages cached by purgeable pager-caches to the sum
7846** of the suggested cache-sizes.
7847*/
7848SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
7849#ifdef SQLITE_TEST
7850SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
7851#endif
7852
7853#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
7854/* Try to return memory used by the pcache module to the main memory heap */
7855SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
7856#endif
7857
7858#ifdef SQLITE_TEST
7859SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
7860#endif
7861
7862SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
7863
7864#endif /* _PCACHE_H_ */
7865
7866/************** End of pcache.h **********************************************/
7867/************** Continuing where we left off in sqliteInt.h ******************/
7868
7869/************** Include os.h in the middle of sqliteInt.h ********************/
7870/************** Begin file os.h **********************************************/
7871/*
7872** 2001 September 16
7873**
7874** The author disclaims copyright to this source code.  In place of
7875** a legal notice, here is a blessing:
7876**
7877**    May you do good and not evil.
7878**    May you find forgiveness for yourself and forgive others.
7879**    May you share freely, never taking more than you give.
7880**
7881******************************************************************************
7882**
7883** This header file (together with is companion C source-code file
7884** "os.c") attempt to abstract the underlying operating system so that
7885** the SQLite library will work on both POSIX and windows systems.
7886**
7887** This header file is #include-ed by sqliteInt.h and thus ends up
7888** being included by every source file.
7889*/
7890#ifndef _SQLITE_OS_H_
7891#define _SQLITE_OS_H_
7892
7893/*
7894** Figure out if we are dealing with Unix, Windows, or some other
7895** operating system.  After the following block of preprocess macros,
7896** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
7897** will defined to either 1 or 0.  One of the four will be 1.  The other
7898** three will be 0.
7899*/
7900#if defined(SQLITE_OS_OTHER)
7901# if SQLITE_OS_OTHER==1
7902#   undef SQLITE_OS_UNIX
7903#   define SQLITE_OS_UNIX 0
7904#   undef SQLITE_OS_WIN
7905#   define SQLITE_OS_WIN 0
7906#   undef SQLITE_OS_OS2
7907#   define SQLITE_OS_OS2 0
7908# else
7909#   undef SQLITE_OS_OTHER
7910# endif
7911#endif
7912#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
7913# define SQLITE_OS_OTHER 0
7914# ifndef SQLITE_OS_WIN
7915#   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
7916#     define SQLITE_OS_WIN 1
7917#     define SQLITE_OS_UNIX 0
7918#     define SQLITE_OS_OS2 0
7919#   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
7920#     define SQLITE_OS_WIN 0
7921#     define SQLITE_OS_UNIX 0
7922#     define SQLITE_OS_OS2 1
7923#   else
7924#     define SQLITE_OS_WIN 0
7925#     define SQLITE_OS_UNIX 1
7926#     define SQLITE_OS_OS2 0
7927#  endif
7928# else
7929#  define SQLITE_OS_UNIX 0
7930#  define SQLITE_OS_OS2 0
7931# endif
7932#else
7933# ifndef SQLITE_OS_WIN
7934#  define SQLITE_OS_WIN 0
7935# endif
7936#endif
7937
7938/*
7939** Determine if we are dealing with WindowsCE - which has a much
7940** reduced API.
7941*/
7942#if defined(_WIN32_WCE)
7943# define SQLITE_OS_WINCE 1
7944#else
7945# define SQLITE_OS_WINCE 0
7946#endif
7947
7948
7949/*
7950** Define the maximum size of a temporary filename
7951*/
7952#if SQLITE_OS_WIN
7953# include <windows.h>
7954# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
7955#elif SQLITE_OS_OS2
7956# if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
7957#  include <os2safe.h> /* has to be included before os2.h for linking to work */
7958# endif
7959# define INCL_DOSDATETIME
7960# define INCL_DOSFILEMGR
7961# define INCL_DOSERRORS
7962# define INCL_DOSMISC
7963# define INCL_DOSPROCESS
7964# define INCL_DOSMODULEMGR
7965# define INCL_DOSSEMAPHORES
7966# include <os2.h>
7967# include <uconv.h>
7968# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
7969#else
7970# define SQLITE_TEMPNAME_SIZE 200
7971#endif
7972
7973/* If the SET_FULLSYNC macro is not defined above, then make it
7974** a no-op
7975*/
7976#ifndef SET_FULLSYNC
7977# define SET_FULLSYNC(x,y)
7978#endif
7979
7980/*
7981** The default size of a disk sector
7982*/
7983#ifndef SQLITE_DEFAULT_SECTOR_SIZE
7984# define SQLITE_DEFAULT_SECTOR_SIZE 512
7985#endif
7986
7987/*
7988** Temporary files are named starting with this prefix followed by 16 random
7989** alphanumeric characters, and no file extension. They are stored in the
7990** OS's standard temporary file directory, and are deleted prior to exit.
7991** If sqlite is being embedded in another program, you may wish to change the
7992** prefix to reflect your program's name, so that if your program exits
7993** prematurely, old temporary files can be easily identified. This can be done
7994** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
7995**
7996** 2006-10-31:  The default prefix used to be "sqlite_".  But then
7997** Mcafee started using SQLite in their anti-virus product and it
7998** started putting files with the "sqlite" name in the c:/temp folder.
7999** This annoyed many windows users.  Those users would then do a
8000** Google search for "sqlite", find the telephone numbers of the
8001** developers and call to wake them up at night and complain.
8002** For this reason, the default name prefix is changed to be "sqlite"
8003** spelled backwards.  So the temp files are still identified, but
8004** anybody smart enough to figure out the code is also likely smart
8005** enough to know that calling the developer will not help get rid
8006** of the file.
8007*/
8008#ifndef SQLITE_TEMP_FILE_PREFIX
8009# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8010#endif
8011
8012/*
8013** The following values may be passed as the second argument to
8014** sqlite3OsLock(). The various locks exhibit the following semantics:
8015**
8016** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
8017** RESERVED:  A single process may hold a RESERVED lock on a file at
8018**            any time. Other processes may hold and obtain new SHARED locks.
8019** PENDING:   A single process may hold a PENDING lock on a file at
8020**            any one time. Existing SHARED locks may persist, but no new
8021**            SHARED locks may be obtained by other processes.
8022** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8023**
8024** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8025** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8026** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8027** sqlite3OsLock().
8028*/
8029#define NO_LOCK         0
8030#define SHARED_LOCK     1
8031#define RESERVED_LOCK   2
8032#define PENDING_LOCK    3
8033#define EXCLUSIVE_LOCK  4
8034
8035/*
8036** File Locking Notes:  (Mostly about windows but also some info for Unix)
8037**
8038** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8039** those functions are not available.  So we use only LockFile() and
8040** UnlockFile().
8041**
8042** LockFile() prevents not just writing but also reading by other processes.
8043** A SHARED_LOCK is obtained by locking a single randomly-chosen
8044** byte out of a specific range of bytes. The lock byte is obtained at
8045** random so two separate readers can probably access the file at the
8046** same time, unless they are unlucky and choose the same lock byte.
8047** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8048** There can only be one writer.  A RESERVED_LOCK is obtained by locking
8049** a single byte of the file that is designated as the reserved lock byte.
8050** A PENDING_LOCK is obtained by locking a designated byte different from
8051** the RESERVED_LOCK byte.
8052**
8053** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8054** which means we can use reader/writer locks.  When reader/writer locks
8055** are used, the lock is placed on the same range of bytes that is used
8056** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8057** will support two or more Win95 readers or two or more WinNT readers.
8058** But a single Win95 reader will lock out all WinNT readers and a single
8059** WinNT reader will lock out all other Win95 readers.
8060**
8061** The following #defines specify the range of bytes used for locking.
8062** SHARED_SIZE is the number of bytes available in the pool from which
8063** a random byte is selected for a shared lock.  The pool of bytes for
8064** shared locks begins at SHARED_FIRST.
8065**
8066** The same locking strategy and
8067** byte ranges are used for Unix.  This leaves open the possiblity of having
8068** clients on win95, winNT, and unix all talking to the same shared file
8069** and all locking correctly.  To do so would require that samba (or whatever
8070** tool is being used for file sharing) implements locks correctly between
8071** windows and unix.  I'm guessing that isn't likely to happen, but by
8072** using the same locking range we are at least open to the possibility.
8073**
8074** Locking in windows is manditory.  For this reason, we cannot store
8075** actual data in the bytes used for locking.  The pager never allocates
8076** the pages involved in locking therefore.  SHARED_SIZE is selected so
8077** that all locks will fit on a single page even at the minimum page size.
8078** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8079** is set high so that we don't have to allocate an unused page except
8080** for very large databases.  But one should test the page skipping logic
8081** by setting PENDING_BYTE low and running the entire regression suite.
8082**
8083** Changing the value of PENDING_BYTE results in a subtly incompatible
8084** file format.  Depending on how it is changed, you might not notice
8085** the incompatibility right away, even running a full regression test.
8086** The default location of PENDING_BYTE is the first byte past the
8087** 1GB boundary.
8088**
8089*/
8090#define PENDING_BYTE      sqlite3PendingByte
8091#define RESERVED_BYTE     (PENDING_BYTE+1)
8092#define SHARED_FIRST      (PENDING_BYTE+2)
8093#define SHARED_SIZE       510
8094
8095/*
8096** Wrapper around OS specific sqlite3_os_init() function.
8097*/
8098SQLITE_PRIVATE int sqlite3OsInit(void);
8099
8100/*
8101** Functions for accessing sqlite3_file methods
8102*/
8103SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8104SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8105SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8106SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8107SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8108SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8109SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8110SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8111SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8112SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8113#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8114SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8115SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8116
8117/*
8118** Functions for accessing sqlite3_vfs methods
8119*/
8120SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8121SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8122SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8123SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8124#ifndef SQLITE_OMIT_LOAD_EXTENSION
8125SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8126SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8127SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8128SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8129#endif /* SQLITE_OMIT_LOAD_EXTENSION */
8130SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8131SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8132SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
8133
8134/*
8135** Convenience functions for opening and closing files using
8136** sqlite3_malloc() to obtain space for the file-handle structure.
8137*/
8138SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8139SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8140
8141#endif /* _SQLITE_OS_H_ */
8142
8143/************** End of os.h **************************************************/
8144/************** Continuing where we left off in sqliteInt.h ******************/
8145/************** Include mutex.h in the middle of sqliteInt.h *****************/
8146/************** Begin file mutex.h *******************************************/
8147/*
8148** 2007 August 28
8149**
8150** The author disclaims copyright to this source code.  In place of
8151** a legal notice, here is a blessing:
8152**
8153**    May you do good and not evil.
8154**    May you find forgiveness for yourself and forgive others.
8155**    May you share freely, never taking more than you give.
8156**
8157*************************************************************************
8158**
8159** This file contains the common header for all mutex implementations.
8160** The sqliteInt.h header #includes this file so that it is available
8161** to all source files.  We break it out in an effort to keep the code
8162** better organized.
8163**
8164** NOTE:  source files should *not* #include this header file directly.
8165** Source files should #include the sqliteInt.h file and let that file
8166** include this one indirectly.
8167*/
8168
8169
8170/*
8171** Figure out what version of the code to use.  The choices are
8172**
8173**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8174**                             mutexes implemention cannot be overridden
8175**                             at start-time.
8176**
8177**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8178**                             mutual exclusion is provided.  But this
8179**                             implementation can be overridden at
8180**                             start-time.
8181**
8182**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8183**
8184**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8185**
8186**   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8187*/
8188#if !SQLITE_THREADSAFE
8189# define SQLITE_MUTEX_OMIT
8190#endif
8191#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8192#  if SQLITE_OS_UNIX
8193#    define SQLITE_MUTEX_PTHREADS
8194#  elif SQLITE_OS_WIN
8195#    define SQLITE_MUTEX_W32
8196#  elif SQLITE_OS_OS2
8197#    define SQLITE_MUTEX_OS2
8198#  else
8199#    define SQLITE_MUTEX_NOOP
8200#  endif
8201#endif
8202
8203#ifdef SQLITE_MUTEX_OMIT
8204/*
8205** If this is a no-op implementation, implement everything as macros.
8206*/
8207#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8208#define sqlite3_mutex_free(X)
8209#define sqlite3_mutex_enter(X)
8210#define sqlite3_mutex_try(X)      SQLITE_OK
8211#define sqlite3_mutex_leave(X)
8212#define sqlite3_mutex_held(X)     1
8213#define sqlite3_mutex_notheld(X)  1
8214#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8215#define sqlite3MutexInit()        SQLITE_OK
8216#define sqlite3MutexEnd()
8217#endif /* defined(SQLITE_MUTEX_OMIT) */
8218
8219/************** End of mutex.h ***********************************************/
8220/************** Continuing where we left off in sqliteInt.h ******************/
8221
8222
8223/*
8224** Each database file to be accessed by the system is an instance
8225** of the following structure.  There are normally two of these structures
8226** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8227** aDb[1] is the database file used to hold temporary tables.  Additional
8228** databases may be attached.
8229*/
8230struct Db {
8231  char *zName;         /* Name of this database */
8232  Btree *pBt;          /* The B*Tree structure for this database file */
8233  u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8234  u8 safety_level;     /* How aggressive at syncing data to disk */
8235  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
8236};
8237
8238/*
8239** An instance of the following structure stores a database schema.
8240**
8241** If there are no virtual tables configured in this schema, the
8242** Schema.db variable is set to NULL. After the first virtual table
8243** has been added, it is set to point to the database connection
8244** used to create the connection. Once a virtual table has been
8245** added to the Schema structure and the Schema.db variable populated,
8246** only that database connection may use the Schema to prepare
8247** statements.
8248*/
8249struct Schema {
8250  int schema_cookie;   /* Database schema version number for this file */
8251  Hash tblHash;        /* All tables indexed by name */
8252  Hash idxHash;        /* All (named) indices indexed by name */
8253  Hash trigHash;       /* All triggers indexed by name */
8254  Hash fkeyHash;       /* All foreign keys by referenced table name */
8255  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
8256  u8 file_format;      /* Schema format version for this file */
8257  u8 enc;              /* Text encoding used by this database */
8258  u16 flags;           /* Flags associated with this schema */
8259  int cache_size;      /* Number of pages to use in the cache */
8260#ifndef SQLITE_OMIT_VIRTUALTABLE
8261  sqlite3 *db;         /* "Owner" connection. See comment above */
8262#endif
8263};
8264
8265/*
8266** These macros can be used to test, set, or clear bits in the
8267** Db.flags field.
8268*/
8269#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
8270#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
8271#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
8272#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
8273
8274/*
8275** Allowed values for the DB.flags field.
8276**
8277** The DB_SchemaLoaded flag is set after the database schema has been
8278** read into internal hash tables.
8279**
8280** DB_UnresetViews means that one or more views have column names that
8281** have been filled out.  If the schema changes, these column names might
8282** changes and so the view will need to be reset.
8283*/
8284#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
8285#define DB_UnresetViews    0x0002  /* Some views have defined column names */
8286#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
8287
8288/*
8289** The number of different kinds of things that can be limited
8290** using the sqlite3_limit() interface.
8291*/
8292#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
8293
8294/*
8295** Lookaside malloc is a set of fixed-size buffers that can be used
8296** to satisfy small transient memory allocation requests for objects
8297** associated with a particular database connection.  The use of
8298** lookaside malloc provides a significant performance enhancement
8299** (approx 10%) by avoiding numerous malloc/free requests while parsing
8300** SQL statements.
8301**
8302** The Lookaside structure holds configuration information about the
8303** lookaside malloc subsystem.  Each available memory allocation in
8304** the lookaside subsystem is stored on a linked list of LookasideSlot
8305** objects.
8306**
8307** Lookaside allocations are only allowed for objects that are associated
8308** with a particular database connection.  Hence, schema information cannot
8309** be stored in lookaside because in shared cache mode the schema information
8310** is shared by multiple database connections.  Therefore, while parsing
8311** schema information, the Lookaside.bEnabled flag is cleared so that
8312** lookaside allocations are not used to construct the schema objects.
8313*/
8314struct Lookaside {
8315  u16 sz;                 /* Size of each buffer in bytes */
8316  u8 bEnabled;            /* False to disable new lookaside allocations */
8317  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
8318  int nOut;               /* Number of buffers currently checked out */
8319  int mxOut;              /* Highwater mark for nOut */
8320  LookasideSlot *pFree;   /* List of available buffers */
8321  void *pStart;           /* First byte of available memory space */
8322  void *pEnd;             /* First byte past end of available space */
8323};
8324struct LookasideSlot {
8325  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
8326};
8327
8328/*
8329** A hash table for function definitions.
8330**
8331** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
8332** Collisions are on the FuncDef.pHash chain.
8333*/
8334struct FuncDefHash {
8335  FuncDef *a[23];       /* Hash table for functions */
8336};
8337
8338/*
8339** Each database is an instance of the following structure.
8340**
8341** The sqlite.lastRowid records the last insert rowid generated by an
8342** insert statement.  Inserts on views do not affect its value.  Each
8343** trigger has its own context, so that lastRowid can be updated inside
8344** triggers as usual.  The previous value will be restored once the trigger
8345** exits.  Upon entering a before or instead of trigger, lastRowid is no
8346** longer (since after version 2.8.12) reset to -1.
8347**
8348** The sqlite.nChange does not count changes within triggers and keeps no
8349** context.  It is reset at start of sqlite3_exec.
8350** The sqlite.lsChange represents the number of changes made by the last
8351** insert, update, or delete statement.  It remains constant throughout the
8352** length of a statement and is then updated by OP_SetCounts.  It keeps a
8353** context stack just like lastRowid so that the count of changes
8354** within a trigger is not seen outside the trigger.  Changes to views do not
8355** affect the value of lsChange.
8356** The sqlite.csChange keeps track of the number of current changes (since
8357** the last statement) and is used to update sqlite_lsChange.
8358**
8359** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
8360** store the most recent error code and, if applicable, string. The
8361** internal function sqlite3Error() is used to set these variables
8362** consistently.
8363*/
8364struct sqlite3 {
8365  sqlite3_vfs *pVfs;            /* OS Interface */
8366  int nDb;                      /* Number of backends currently in use */
8367  Db *aDb;                      /* All backends */
8368  int flags;                    /* Miscellaneous flags. See below */
8369  int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
8370  int errCode;                  /* Most recent error code (SQLITE_*) */
8371  int errMask;                  /* & result codes with this before returning */
8372  u8 autoCommit;                /* The auto-commit flag. */
8373  u8 temp_store;                /* 1: file 2: memory 0: default */
8374  u8 mallocFailed;              /* True if we have seen a malloc failure */
8375  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8376  u8 dfltJournalMode;           /* Default journal mode for attached dbs */
8377  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8378  int nextPagesize;             /* Pagesize after VACUUM if >0 */
8379  int nTable;                   /* Number of tables in the database */
8380  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
8381  i64 lastRowid;                /* ROWID of most recent insert (see above) */
8382  u32 magic;                    /* Magic number for detect library misuse */
8383  int nChange;                  /* Value returned by sqlite3_changes() */
8384  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
8385  sqlite3_mutex *mutex;         /* Connection mutex */
8386  int aLimit[SQLITE_N_LIMIT];   /* Limits */
8387  struct sqlite3InitInfo {      /* Information used during initialization */
8388    int iDb;                    /* When back is being initialized */
8389    int newTnum;                /* Rootpage of table being initialized */
8390    u8 busy;                    /* TRUE if currently initializing */
8391    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
8392  } init;
8393  int nExtension;               /* Number of loaded extensions */
8394  void **aExtension;            /* Array of shared library handles */
8395  struct Vdbe *pVdbe;           /* List of active virtual machines */
8396  int activeVdbeCnt;            /* Number of VDBEs currently executing */
8397  int writeVdbeCnt;             /* Number of active VDBEs that are writing */
8398  void (*xTrace)(void*,const char*);        /* Trace function */
8399  void *pTraceArg;                          /* Argument to the trace function */
8400  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
8401  void *pProfileArg;                        /* Argument to profile function */
8402  void *pCommitArg;                 /* Argument to xCommitCallback() */
8403  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
8404  void *pRollbackArg;               /* Argument to xRollbackCallback() */
8405  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
8406  void *pUpdateArg;
8407  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
8408  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
8409  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
8410  void *pCollNeededArg;
8411  sqlite3_value *pErr;          /* Most recent error message */
8412  char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
8413  char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
8414  union {
8415    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
8416    double notUsed1;            /* Spacer */
8417  } u1;
8418  Lookaside lookaside;          /* Lookaside malloc configuration */
8419#ifndef SQLITE_OMIT_AUTHORIZATION
8420  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
8421                                /* Access authorization function */
8422  void *pAuthArg;               /* 1st argument to the access auth function */
8423#endif
8424#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8425  int (*xProgress)(void *);     /* The progress callback */
8426  void *pProgressArg;           /* Argument to the progress callback */
8427  int nProgressOps;             /* Number of opcodes for progress callback */
8428#endif
8429#ifndef SQLITE_OMIT_VIRTUALTABLE
8430  Hash aModule;                 /* populated by sqlite3_create_module() */
8431  Table *pVTab;                 /* vtab with active Connect/Create method */
8432  VTable **aVTrans;             /* Virtual tables with open transactions */
8433  int nVTrans;                  /* Allocated size of aVTrans */
8434  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
8435#endif
8436  FuncDefHash aFunc;            /* Hash table of connection functions */
8437  Hash aCollSeq;                /* All collating sequences */
8438  BusyHandler busyHandler;      /* Busy callback */
8439  int busyTimeout;              /* Busy handler timeout, in msec */
8440  Db aDbStatic[2];              /* Static space for the 2 default backends */
8441  Savepoint *pSavepoint;        /* List of active savepoints */
8442  int nSavepoint;               /* Number of non-transaction savepoints */
8443  int nStatement;               /* Number of nested statement-transactions  */
8444  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
8445  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
8446
8447#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
8448  /* The following variables are all protected by the STATIC_MASTER
8449  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
8450  **
8451  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
8452  ** unlock so that it can proceed.
8453  **
8454  ** When X.pBlockingConnection==Y, that means that something that X tried
8455  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
8456  ** held by Y.
8457  */
8458  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
8459  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
8460  void *pUnlockArg;                     /* Argument to xUnlockNotify */
8461  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
8462  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
8463#endif
8464};
8465
8466/*
8467** A macro to discover the encoding of a database.
8468*/
8469#define ENC(db) ((db)->aDb[0].pSchema->enc)
8470
8471/*
8472** Possible values for the sqlite3.flags.
8473*/
8474#define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
8475#define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
8476#define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
8477#define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
8478#define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
8479                                          /*   DELETE, or UPDATE and return */
8480                                          /*   the count using a callback. */
8481#define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
8482                                          /*   result set is empty */
8483#define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
8484#define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
8485#define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
8486#define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when
8487                                          ** accessing read-only databases */
8488#define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
8489#define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
8490#define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
8491#define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
8492#define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
8493#define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
8494#define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
8495#define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
8496#define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
8497
8498/*
8499** Bits of the sqlite3.flags field that are used by the
8500** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
8501** These must be the low-order bits of the flags field.
8502*/
8503#define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
8504#define SQLITE_ColumnCache    0x02        /* Disable the column cache */
8505#define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
8506#define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
8507#define SQLITE_IndexCover     0x10        /* Disable index covering table */
8508#define SQLITE_OptMask        0x1f        /* Mask of all disablable opts */
8509
8510/*
8511** Possible values for the sqlite.magic field.
8512** The numbers are obtained at random and have no special meaning, other
8513** than being distinct from one another.
8514*/
8515#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
8516#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
8517#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
8518#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
8519#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
8520
8521/*
8522** Each SQL function is defined by an instance of the following
8523** structure.  A pointer to this structure is stored in the sqlite.aFunc
8524** hash table.  When multiple functions have the same name, the hash table
8525** points to a linked list of these structures.
8526*/
8527struct FuncDef {
8528  i16 nArg;            /* Number of arguments.  -1 means unlimited */
8529  u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
8530  u8 flags;            /* Some combination of SQLITE_FUNC_* */
8531  void *pUserData;     /* User data parameter */
8532  FuncDef *pNext;      /* Next function with same name */
8533  void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
8534  void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
8535  void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
8536  char *zName;         /* SQL name of the function. */
8537  FuncDef *pHash;      /* Next with a different name but the same hash */
8538};
8539
8540/*
8541** Possible values for FuncDef.flags
8542*/
8543#define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
8544#define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
8545#define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
8546#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
8547#define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
8548#define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
8549#define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
8550
8551/*
8552** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
8553** used to create the initializers for the FuncDef structures.
8554**
8555**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
8556**     Used to create a scalar function definition of a function zName
8557**     implemented by C function xFunc that accepts nArg arguments. The
8558**     value passed as iArg is cast to a (void*) and made available
8559**     as the user-data (sqlite3_user_data()) for the function. If
8560**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
8561**
8562**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
8563**     Used to create an aggregate function definition implemented by
8564**     the C functions xStep and xFinal. The first four parameters
8565**     are interpreted in the same way as the first 4 parameters to
8566**     FUNCTION().
8567**
8568**   LIKEFUNC(zName, nArg, pArg, flags)
8569**     Used to create a scalar function definition of a function zName
8570**     that accepts nArg arguments and is implemented by a call to C
8571**     function likeFunc. Argument pArg is cast to a (void *) and made
8572**     available as the function user-data (sqlite3_user_data()). The
8573**     FuncDef.flags variable is set to the value passed as the flags
8574**     parameter.
8575*/
8576#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
8577  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8578   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
8579#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
8580  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8581   pArg, 0, xFunc, 0, 0, #zName, 0}
8582#define LIKEFUNC(zName, nArg, arg, flags) \
8583  {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
8584#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
8585  {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
8586   SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
8587
8588/*
8589** All current savepoints are stored in a linked list starting at
8590** sqlite3.pSavepoint. The first element in the list is the most recently
8591** opened savepoint. Savepoints are added to the list by the vdbe
8592** OP_Savepoint instruction.
8593*/
8594struct Savepoint {
8595  char *zName;                        /* Savepoint name (nul-terminated) */
8596  i64 nDeferredCons;                  /* Number of deferred fk violations */
8597  Savepoint *pNext;                   /* Parent savepoint (if any) */
8598};
8599
8600/*
8601** The following are used as the second parameter to sqlite3Savepoint(),
8602** and as the P1 argument to the OP_Savepoint instruction.
8603*/
8604#define SAVEPOINT_BEGIN      0
8605#define SAVEPOINT_RELEASE    1
8606#define SAVEPOINT_ROLLBACK   2
8607
8608
8609/*
8610** Each SQLite module (virtual table definition) is defined by an
8611** instance of the following structure, stored in the sqlite3.aModule
8612** hash table.
8613*/
8614struct Module {
8615  const sqlite3_module *pModule;       /* Callback pointers */
8616  const char *zName;                   /* Name passed to create_module() */
8617  void *pAux;                          /* pAux passed to create_module() */
8618  void (*xDestroy)(void *);            /* Module destructor function */
8619};
8620
8621/*
8622** information about each column of an SQL table is held in an instance
8623** of this structure.
8624*/
8625struct Column {
8626  char *zName;     /* Name of this column */
8627  Expr *pDflt;     /* Default value of this column */
8628  char *zDflt;     /* Original text of the default value */
8629  char *zType;     /* Data type for this column */
8630  char *zColl;     /* Collating sequence.  If NULL, use the default */
8631  u8 notNull;      /* True if there is a NOT NULL constraint */
8632  u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
8633  char affinity;   /* One of the SQLITE_AFF_... values */
8634#ifndef SQLITE_OMIT_VIRTUALTABLE
8635  u8 isHidden;     /* True if this column is 'hidden' */
8636#endif
8637};
8638
8639/*
8640** A "Collating Sequence" is defined by an instance of the following
8641** structure. Conceptually, a collating sequence consists of a name and
8642** a comparison routine that defines the order of that sequence.
8643**
8644** There may two separate implementations of the collation function, one
8645** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
8646** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
8647** native byte order. When a collation sequence is invoked, SQLite selects
8648** the version that will require the least expensive encoding
8649** translations, if any.
8650**
8651** The CollSeq.pUser member variable is an extra parameter that passed in
8652** as the first argument to the UTF-8 comparison function, xCmp.
8653** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
8654** xCmp16.
8655**
8656** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
8657** collating sequence is undefined.  Indices built on an undefined
8658** collating sequence may not be read or written.
8659*/
8660struct CollSeq {
8661  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
8662  u8 enc;               /* Text encoding handled by xCmp() */
8663  u8 type;              /* One of the SQLITE_COLL_... values below */
8664  void *pUser;          /* First argument to xCmp() */
8665  int (*xCmp)(void*,int, const void*, int, const void*);
8666  void (*xDel)(void*);  /* Destructor for pUser */
8667};
8668
8669/*
8670** Allowed values of CollSeq.type:
8671*/
8672#define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
8673#define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
8674#define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
8675#define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
8676
8677/*
8678** A sort order can be either ASC or DESC.
8679*/
8680#define SQLITE_SO_ASC       0  /* Sort in ascending order */
8681#define SQLITE_SO_DESC      1  /* Sort in ascending order */
8682
8683/*
8684** Column affinity types.
8685**
8686** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
8687** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
8688** the speed a little by numbering the values consecutively.
8689**
8690** But rather than start with 0 or 1, we begin with 'a'.  That way,
8691** when multiple affinity types are concatenated into a string and
8692** used as the P4 operand, they will be more readable.
8693**
8694** Note also that the numeric types are grouped together so that testing
8695** for a numeric type is a single comparison.
8696*/
8697#define SQLITE_AFF_TEXT     'a'
8698#define SQLITE_AFF_NONE     'b'
8699#define SQLITE_AFF_NUMERIC  'c'
8700#define SQLITE_AFF_INTEGER  'd'
8701#define SQLITE_AFF_REAL     'e'
8702
8703#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
8704
8705/*
8706** The SQLITE_AFF_MASK values masks off the significant bits of an
8707** affinity value.
8708*/
8709#define SQLITE_AFF_MASK     0x67
8710
8711/*
8712** Additional bit values that can be ORed with an affinity without
8713** changing the affinity.
8714*/
8715#define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
8716#define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
8717#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
8718
8719/*
8720** An object of this type is created for each virtual table present in
8721** the database schema.
8722**
8723** If the database schema is shared, then there is one instance of this
8724** structure for each database connection (sqlite3*) that uses the shared
8725** schema. This is because each database connection requires its own unique
8726** instance of the sqlite3_vtab* handle used to access the virtual table
8727** implementation. sqlite3_vtab* handles can not be shared between
8728** database connections, even when the rest of the in-memory database
8729** schema is shared, as the implementation often stores the database
8730** connection handle passed to it via the xConnect() or xCreate() method
8731** during initialization internally. This database connection handle may
8732** then used by the virtual table implementation to access real tables
8733** within the database. So that they appear as part of the callers
8734** transaction, these accesses need to be made via the same database
8735** connection as that used to execute SQL operations on the virtual table.
8736**
8737** All VTable objects that correspond to a single table in a shared
8738** database schema are initially stored in a linked-list pointed to by
8739** the Table.pVTable member variable of the corresponding Table object.
8740** When an sqlite3_prepare() operation is required to access the virtual
8741** table, it searches the list for the VTable that corresponds to the
8742** database connection doing the preparing so as to use the correct
8743** sqlite3_vtab* handle in the compiled query.
8744**
8745** When an in-memory Table object is deleted (for example when the
8746** schema is being reloaded for some reason), the VTable objects are not
8747** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
8748** immediately. Instead, they are moved from the Table.pVTable list to
8749** another linked list headed by the sqlite3.pDisconnect member of the
8750** corresponding sqlite3 structure. They are then deleted/xDisconnected
8751** next time a statement is prepared using said sqlite3*. This is done
8752** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
8753** Refer to comments above function sqlite3VtabUnlockList() for an
8754** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
8755** list without holding the corresponding sqlite3.mutex mutex.
8756**
8757** The memory for objects of this type is always allocated by
8758** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
8759** the first argument.
8760*/
8761struct VTable {
8762  sqlite3 *db;              /* Database connection associated with this table */
8763  Module *pMod;             /* Pointer to module implementation */
8764  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
8765  int nRef;                 /* Number of pointers to this structure */
8766  VTable *pNext;            /* Next in linked list (see above) */
8767};
8768
8769/*
8770** Each SQL table is represented in memory by an instance of the
8771** following structure.
8772**
8773** Table.zName is the name of the table.  The case of the original
8774** CREATE TABLE statement is stored, but case is not significant for
8775** comparisons.
8776**
8777** Table.nCol is the number of columns in this table.  Table.aCol is a
8778** pointer to an array of Column structures, one for each column.
8779**
8780** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
8781** the column that is that key.   Otherwise Table.iPKey is negative.  Note
8782** that the datatype of the PRIMARY KEY must be INTEGER for this field to
8783** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
8784** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
8785** is generated for each row of the table.  TF_HasPrimaryKey is set if
8786** the table has any PRIMARY KEY, INTEGER or otherwise.
8787**
8788** Table.tnum is the page number for the root BTree page of the table in the
8789** database file.  If Table.iDb is the index of the database table backend
8790** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
8791** holds temporary tables and indices.  If TF_Ephemeral is set
8792** then the table is stored in a file that is automatically deleted
8793** when the VDBE cursor to the table is closed.  In this case Table.tnum
8794** refers VDBE cursor number that holds the table open, not to the root
8795** page number.  Transient tables are used to hold the results of a
8796** sub-query that appears instead of a real table name in the FROM clause
8797** of a SELECT statement.
8798*/
8799struct Table {
8800  sqlite3 *dbMem;      /* DB connection used for lookaside allocations. */
8801  char *zName;         /* Name of the table or view */
8802  int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
8803  int nCol;            /* Number of columns in this table */
8804  Column *aCol;        /* Information about each column */
8805  Index *pIndex;       /* List of SQL indexes on this table. */
8806  int tnum;            /* Root BTree node for this table (see note above) */
8807  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
8808  u16 nRef;            /* Number of pointers to this Table */
8809  u8 tabFlags;         /* Mask of TF_* values */
8810  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
8811  FKey *pFKey;         /* Linked list of all foreign keys in this table */
8812  char *zColAff;       /* String defining the affinity of each column */
8813#ifndef SQLITE_OMIT_CHECK
8814  Expr *pCheck;        /* The AND of all CHECK constraints */
8815#endif
8816#ifndef SQLITE_OMIT_ALTERTABLE
8817  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
8818#endif
8819#ifndef SQLITE_OMIT_VIRTUALTABLE
8820  VTable *pVTable;     /* List of VTable objects. */
8821  int nModuleArg;      /* Number of arguments to the module */
8822  char **azModuleArg;  /* Text of all module args. [0] is module name */
8823#endif
8824  Trigger *pTrigger;   /* List of triggers stored in pSchema */
8825  Schema *pSchema;     /* Schema that contains this table */
8826  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
8827};
8828
8829/*
8830** Allowed values for Tabe.tabFlags.
8831*/
8832#define TF_Readonly        0x01    /* Read-only system table */
8833#define TF_Ephemeral       0x02    /* An ephemeral table */
8834#define TF_HasPrimaryKey   0x04    /* Table has a primary key */
8835#define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
8836#define TF_Virtual         0x10    /* Is a virtual table */
8837#define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
8838
8839
8840
8841/*
8842** Test to see whether or not a table is a virtual table.  This is
8843** done as a macro so that it will be optimized out when virtual
8844** table support is omitted from the build.
8845*/
8846#ifndef SQLITE_OMIT_VIRTUALTABLE
8847#  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
8848#  define IsHiddenColumn(X) ((X)->isHidden)
8849#else
8850#  define IsVirtual(X)      0
8851#  define IsHiddenColumn(X) 0
8852#endif
8853
8854/*
8855** Each foreign key constraint is an instance of the following structure.
8856**
8857** A foreign key is associated with two tables.  The "from" table is
8858** the table that contains the REFERENCES clause that creates the foreign
8859** key.  The "to" table is the table that is named in the REFERENCES clause.
8860** Consider this example:
8861**
8862**     CREATE TABLE ex1(
8863**       a INTEGER PRIMARY KEY,
8864**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
8865**     );
8866**
8867** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
8868**
8869** Each REFERENCES clause generates an instance of the following structure
8870** which is attached to the from-table.  The to-table need not exist when
8871** the from-table is created.  The existence of the to-table is not checked.
8872*/
8873struct FKey {
8874  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
8875  FKey *pNextFrom;  /* Next foreign key in pFrom */
8876  char *zTo;        /* Name of table that the key points to (aka: Parent) */
8877  FKey *pNextTo;    /* Next foreign key on table named zTo */
8878  FKey *pPrevTo;    /* Previous foreign key on table named zTo */
8879  int nCol;         /* Number of columns in this key */
8880  /* EV: R-30323-21917 */
8881  u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
8882  u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
8883  Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
8884  struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
8885    int iFrom;         /* Index of column in pFrom */
8886    char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
8887  } aCol[1];        /* One entry for each of nCol column s */
8888};
8889
8890/*
8891** SQLite supports many different ways to resolve a constraint
8892** error.  ROLLBACK processing means that a constraint violation
8893** causes the operation in process to fail and for the current transaction
8894** to be rolled back.  ABORT processing means the operation in process
8895** fails and any prior changes from that one operation are backed out,
8896** but the transaction is not rolled back.  FAIL processing means that
8897** the operation in progress stops and returns an error code.  But prior
8898** changes due to the same operation are not backed out and no rollback
8899** occurs.  IGNORE means that the particular row that caused the constraint
8900** error is not inserted or updated.  Processing continues and no error
8901** is returned.  REPLACE means that preexisting database rows that caused
8902** a UNIQUE constraint violation are removed so that the new insert or
8903** update can proceed.  Processing continues and no error is reported.
8904**
8905** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
8906** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
8907** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
8908** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
8909** referenced table row is propagated into the row that holds the
8910** foreign key.
8911**
8912** The following symbolic values are used to record which type
8913** of action to take.
8914*/
8915#define OE_None     0   /* There is no constraint to check */
8916#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
8917#define OE_Abort    2   /* Back out changes but do no rollback transaction */
8918#define OE_Fail     3   /* Stop the operation but leave all prior changes */
8919#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
8920#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
8921
8922#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
8923#define OE_SetNull  7   /* Set the foreign key value to NULL */
8924#define OE_SetDflt  8   /* Set the foreign key value to its default */
8925#define OE_Cascade  9   /* Cascade the changes */
8926
8927#define OE_Default  99  /* Do whatever the default action is */
8928
8929
8930/*
8931** An instance of the following structure is passed as the first
8932** argument to sqlite3VdbeKeyCompare and is used to control the
8933** comparison of the two index keys.
8934*/
8935struct KeyInfo {
8936  sqlite3 *db;        /* The database connection */
8937  u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
8938  u16 nField;         /* Number of entries in aColl[] */
8939  u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
8940  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
8941};
8942
8943/*
8944** An instance of the following structure holds information about a
8945** single index record that has already been parsed out into individual
8946** values.
8947**
8948** A record is an object that contains one or more fields of data.
8949** Records are used to store the content of a table row and to store
8950** the key of an index.  A blob encoding of a record is created by
8951** the OP_MakeRecord opcode of the VDBE and is disassembled by the
8952** OP_Column opcode.
8953**
8954** This structure holds a record that has already been disassembled
8955** into its constituent fields.
8956*/
8957struct UnpackedRecord {
8958  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
8959  u16 nField;         /* Number of entries in apMem[] */
8960  u16 flags;          /* Boolean settings.  UNPACKED_... below */
8961  i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
8962  Mem *aMem;          /* Values */
8963};
8964
8965/*
8966** Allowed values of UnpackedRecord.flags
8967*/
8968#define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
8969#define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
8970#define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
8971#define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
8972#define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
8973#define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
8974
8975/*
8976** Each SQL index is represented in memory by an
8977** instance of the following structure.
8978**
8979** The columns of the table that are to be indexed are described
8980** by the aiColumn[] field of this structure.  For example, suppose
8981** we have the following table and index:
8982**
8983**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
8984**     CREATE INDEX Ex2 ON Ex1(c3,c1);
8985**
8986** In the Table structure describing Ex1, nCol==3 because there are
8987** three columns in the table.  In the Index structure describing
8988** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
8989** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
8990** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
8991** The second column to be indexed (c1) has an index of 0 in
8992** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
8993**
8994** The Index.onError field determines whether or not the indexed columns
8995** must be unique and what to do if they are not.  When Index.onError=OE_None,
8996** it means this is not a unique index.  Otherwise it is a unique index
8997** and the value of Index.onError indicate the which conflict resolution
8998** algorithm to employ whenever an attempt is made to insert a non-unique
8999** element.
9000*/
9001struct Index {
9002  char *zName;     /* Name of this index */
9003  int nColumn;     /* Number of columns in the table used by this index */
9004  int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
9005  unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
9006  Table *pTable;   /* The SQL table being indexed */
9007  int tnum;        /* Page containing root of this index in database file */
9008  u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
9009  u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
9010  char *zColAff;   /* String defining the affinity of each column */
9011  Index *pNext;    /* The next index associated with the same table */
9012  Schema *pSchema; /* Schema containing this index */
9013  u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
9014  char **azColl;   /* Array of collation sequence names for index */
9015  IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
9016};
9017
9018/*
9019** Each sample stored in the sqlite_stat2 table is represented in memory
9020** using a structure of this type.
9021*/
9022struct IndexSample {
9023  union {
9024    char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
9025    double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
9026  } u;
9027  u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
9028  u8 nByte;         /* Size in byte of text or blob. */
9029};
9030
9031/*
9032** Each token coming out of the lexer is an instance of
9033** this structure.  Tokens are also used as part of an expression.
9034**
9035** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9036** may contain random values.  Do not make any assumptions about Token.dyn
9037** and Token.n when Token.z==0.
9038*/
9039struct Token {
9040  const char *z;     /* Text of the token.  Not NULL-terminated! */
9041  unsigned int n;    /* Number of characters in this token */
9042};
9043
9044/*
9045** An instance of this structure contains information needed to generate
9046** code for a SELECT that contains aggregate functions.
9047**
9048** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9049** pointer to this structure.  The Expr.iColumn field is the index in
9050** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9051** code for that node.
9052**
9053** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9054** original Select structure that describes the SELECT statement.  These
9055** fields do not need to be freed when deallocating the AggInfo structure.
9056*/
9057struct AggInfo {
9058  u8 directMode;          /* Direct rendering mode means take data directly
9059                          ** from source tables rather than from accumulators */
9060  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9061                          ** than the source table */
9062  int sortingIdx;         /* Cursor number of the sorting index */
9063  ExprList *pGroupBy;     /* The group by clause */
9064  int nSortingColumn;     /* Number of columns in the sorting index */
9065  struct AggInfo_col {    /* For each column used in source tables */
9066    Table *pTab;             /* Source table */
9067    int iTable;              /* Cursor number of the source table */
9068    int iColumn;             /* Column number within the source table */
9069    int iSorterColumn;       /* Column number in the sorting index */
9070    int iMem;                /* Memory location that acts as accumulator */
9071    Expr *pExpr;             /* The original expression */
9072  } *aCol;
9073  int nColumn;            /* Number of used entries in aCol[] */
9074  int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9075  int nAccumulator;       /* Number of columns that show through to the output.
9076                          ** Additional columns are used only as parameters to
9077                          ** aggregate functions */
9078  struct AggInfo_func {   /* For each aggregate function */
9079    Expr *pExpr;             /* Expression encoding the function */
9080    FuncDef *pFunc;          /* The aggregate function implementation */
9081    int iMem;                /* Memory location that acts as accumulator */
9082    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
9083  } *aFunc;
9084  int nFunc;              /* Number of entries in aFunc[] */
9085  int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9086};
9087
9088/*
9089** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9090** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
9091** than 32767 we have to make it 32-bit.  16-bit is preferred because
9092** it uses less memory in the Expr object, which is a big memory user
9093** in systems with lots of prepared statements.  And few applications
9094** need more than about 10 or 20 variables.  But some extreme users want
9095** to have prepared statements with over 32767 variables, and for them
9096** the option is available (at compile-time).
9097*/
9098#if SQLITE_MAX_VARIABLE_NUMBER<=32767
9099typedef i16 ynVar;
9100#else
9101typedef int ynVar;
9102#endif
9103
9104/*
9105** Each node of an expression in the parse tree is an instance
9106** of this structure.
9107**
9108** Expr.op is the opcode. The integer parser token codes are reused
9109** as opcodes here. For example, the parser defines TK_GE to be an integer
9110** code representing the ">=" operator. This same integer code is reused
9111** to represent the greater-than-or-equal-to operator in the expression
9112** tree.
9113**
9114** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
9115** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9116** the expression is a variable (TK_VARIABLE), then Expr.token contains the
9117** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9118** then Expr.token contains the name of the function.
9119**
9120** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9121** binary operator. Either or both may be NULL.
9122**
9123** Expr.x.pList is a list of arguments if the expression is an SQL function,
9124** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9125** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9126** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9127** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
9128** valid.
9129**
9130** An expression of the form ID or ID.ID refers to a column in a table.
9131** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9132** the integer cursor number of a VDBE cursor pointing to that table and
9133** Expr.iColumn is the column number for the specific column.  If the
9134** expression is used as a result in an aggregate SELECT, then the
9135** value is also stored in the Expr.iAgg column in the aggregate so that
9136** it can be accessed after all aggregates are computed.
9137**
9138** If the expression is an unbound variable marker (a question mark
9139** character '?' in the original SQL) then the Expr.iTable holds the index
9140** number for that variable.
9141**
9142** If the expression is a subquery then Expr.iColumn holds an integer
9143** register number containing the result of the subquery.  If the
9144** subquery gives a constant result, then iTable is -1.  If the subquery
9145** gives a different answer at different times during statement processing
9146** then iTable is the address of a subroutine that computes the subquery.
9147**
9148** If the Expr is of type OP_Column, and the table it is selecting from
9149** is a disk table or the "old.*" pseudo-table, then pTab points to the
9150** corresponding table definition.
9151**
9152** ALLOCATION NOTES:
9153**
9154** Expr objects can use a lot of memory space in database schema.  To
9155** help reduce memory requirements, sometimes an Expr object will be
9156** truncated.  And to reduce the number of memory allocations, sometimes
9157** two or more Expr objects will be stored in a single memory allocation,
9158** together with Expr.zToken strings.
9159**
9160** If the EP_Reduced and EP_TokenOnly flags are set when
9161** an Expr object is truncated.  When EP_Reduced is set, then all
9162** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9163** are contained within the same memory allocation.  Note, however, that
9164** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9165** allocated, regardless of whether or not EP_Reduced is set.
9166*/
9167struct Expr {
9168  u8 op;                 /* Operation performed by this node */
9169  char affinity;         /* The affinity of the column or 0 if not a column */
9170  u16 flags;             /* Various flags.  EP_* See below */
9171  union {
9172    char *zToken;          /* Token value. Zero terminated and dequoted */
9173    int iValue;            /* Integer value if EP_IntValue */
9174  } u;
9175
9176  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9177  ** space is allocated for the fields below this point. An attempt to
9178  ** access them will result in a segfault or malfunction.
9179  *********************************************************************/
9180
9181  Expr *pLeft;           /* Left subnode */
9182  Expr *pRight;          /* Right subnode */
9183  union {
9184    ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
9185    Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
9186  } x;
9187  CollSeq *pColl;        /* The collation type of the column or 0 */
9188
9189  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
9190  ** space is allocated for the fields below this point. An attempt to
9191  ** access them will result in a segfault or malfunction.
9192  *********************************************************************/
9193
9194  int iTable;            /* TK_COLUMN: cursor number of table holding column
9195                         ** TK_REGISTER: register number
9196                         ** TK_TRIGGER: 1 -> new, 0 -> old */
9197  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
9198                         ** TK_VARIABLE: variable number (always >= 1). */
9199  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9200  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9201  u8 flags2;             /* Second set of flags.  EP2_... */
9202  u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
9203  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9204  Table *pTab;           /* Table for TK_COLUMN expressions. */
9205#if SQLITE_MAX_EXPR_DEPTH>0
9206  int nHeight;           /* Height of the tree headed by this node */
9207#endif
9208};
9209
9210/*
9211** The following are the meanings of bits in the Expr.flags field.
9212*/
9213#define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9214#define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9215#define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9216#define EP_Error      0x0008  /* Expression contains one or more errors */
9217#define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9218#define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9219#define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
9220#define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9221#define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9222#define EP_FixedDest  0x0200  /* Result needed in a specific register */
9223#define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
9224#define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
9225
9226#define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
9227#define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
9228#define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
9229
9230/*
9231** The following are the meanings of bits in the Expr.flags2 field.
9232*/
9233#define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
9234#define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
9235
9236/*
9237** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
9238** flag on an expression structure.  This flag is used for VV&A only.  The
9239** routine is implemented as a macro that only works when in debugging mode,
9240** so as not to burden production code.
9241*/
9242#ifdef SQLITE_DEBUG
9243# define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
9244#else
9245# define ExprSetIrreducible(X)
9246#endif
9247
9248/*
9249** These macros can be used to test, set, or clear bits in the
9250** Expr.flags field.
9251*/
9252#define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9253#define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9254#define ExprSetProperty(E,P)     (E)->flags|=(P)
9255#define ExprClearProperty(E,P)   (E)->flags&=~(P)
9256
9257/*
9258** Macros to determine the number of bytes required by a normal Expr
9259** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
9260** and an Expr struct with the EP_TokenOnly flag set.
9261*/
9262#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
9263#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
9264#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
9265
9266/*
9267** Flags passed to the sqlite3ExprDup() function. See the header comment
9268** above sqlite3ExprDup() for details.
9269*/
9270#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
9271
9272/*
9273** A list of expressions.  Each expression may optionally have a
9274** name.  An expr/name combination can be used in several ways, such
9275** as the list of "expr AS ID" fields following a "SELECT" or in the
9276** list of "ID = expr" items in an UPDATE.  A list of expressions can
9277** also be used as the argument to a function, in which case the a.zName
9278** field is not used.
9279*/
9280struct ExprList {
9281  int nExpr;             /* Number of expressions on the list */
9282  int nAlloc;            /* Number of entries allocated below */
9283  int iECursor;          /* VDBE Cursor associated with this ExprList */
9284  struct ExprList_item {
9285    Expr *pExpr;           /* The list of expressions */
9286    char *zName;           /* Token associated with this expression */
9287    char *zSpan;           /* Original text of the expression */
9288    u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9289    u8 done;               /* A flag to indicate when processing is finished */
9290    u16 iCol;              /* For ORDER BY, column number in result set */
9291    u16 iAlias;            /* Index into Parse.aAlias[] for zName */
9292  } *a;                  /* One entry for each expression */
9293};
9294
9295/*
9296** An instance of this structure is used by the parser to record both
9297** the parse tree for an expression and the span of input text for an
9298** expression.
9299*/
9300struct ExprSpan {
9301  Expr *pExpr;          /* The expression parse tree */
9302  const char *zStart;   /* First character of input text */
9303  const char *zEnd;     /* One character past the end of input text */
9304};
9305
9306/*
9307** An instance of this structure can hold a simple list of identifiers,
9308** such as the list "a,b,c" in the following statements:
9309**
9310**      INSERT INTO t(a,b,c) VALUES ...;
9311**      CREATE INDEX idx ON t(a,b,c);
9312**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9313**
9314** The IdList.a.idx field is used when the IdList represents the list of
9315** column names after a table name in an INSERT statement.  In the statement
9316**
9317**     INSERT INTO t(a,b,c) ...
9318**
9319** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9320*/
9321struct IdList {
9322  struct IdList_item {
9323    char *zName;      /* Name of the identifier */
9324    int idx;          /* Index in some Table.aCol[] of a column named zName */
9325  } *a;
9326  int nId;         /* Number of identifiers on the list */
9327  int nAlloc;      /* Number of entries allocated for a[] below */
9328};
9329
9330/*
9331** The bitmask datatype defined below is used for various optimizations.
9332**
9333** Changing this from a 64-bit to a 32-bit type limits the number of
9334** tables in a join to 32 instead of 64.  But it also reduces the size
9335** of the library by 738 bytes on ix86.
9336*/
9337typedef u64 Bitmask;
9338
9339/*
9340** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
9341*/
9342#define BMS  ((int)(sizeof(Bitmask)*8))
9343
9344/*
9345** The following structure describes the FROM clause of a SELECT statement.
9346** Each table or subquery in the FROM clause is a separate element of
9347** the SrcList.a[] array.
9348**
9349** With the addition of multiple database support, the following structure
9350** can also be used to describe a particular table such as the table that
9351** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
9352** such a table must be a simple name: ID.  But in SQLite, the table can
9353** now be identified by a database name, a dot, then the table name: ID.ID.
9354**
9355** The jointype starts out showing the join type between the current table
9356** and the next table on the list.  The parser builds the list this way.
9357** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9358** jointype expresses the join between the table and the previous table.
9359*/
9360struct SrcList {
9361  i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9362  i16 nAlloc;      /* Number of entries allocated in a[] below */
9363  struct SrcList_item {
9364    char *zDatabase;  /* Name of database holding this table */
9365    char *zName;      /* Name of the table */
9366    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
9367    Table *pTab;      /* An SQL table corresponding to zName */
9368    Select *pSelect;  /* A SELECT statement used in place of a table name */
9369    u8 isPopulated;   /* Temporary table associated with SELECT is populated */
9370    u8 jointype;      /* Type of join between this able and the previous */
9371    u8 notIndexed;    /* True if there is a NOT INDEXED clause */
9372    int iCursor;      /* The VDBE cursor number used to access this table */
9373    Expr *pOn;        /* The ON clause of a join */
9374    IdList *pUsing;   /* The USING clause of a join */
9375    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
9376    char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
9377    Index *pIndex;    /* Index structure corresponding to zIndex, if any */
9378  } a[1];             /* One entry for each identifier on the list */
9379};
9380
9381/*
9382** Permitted values of the SrcList.a.jointype field
9383*/
9384#define JT_INNER     0x0001    /* Any kind of inner or cross join */
9385#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
9386#define JT_NATURAL   0x0004    /* True for a "natural" join */
9387#define JT_LEFT      0x0008    /* Left outer join */
9388#define JT_RIGHT     0x0010    /* Right outer join */
9389#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
9390#define JT_ERROR     0x0040    /* unknown or unsupported join type */
9391
9392
9393/*
9394** A WherePlan object holds information that describes a lookup
9395** strategy.
9396**
9397** This object is intended to be opaque outside of the where.c module.
9398** It is included here only so that that compiler will know how big it
9399** is.  None of the fields in this object should be used outside of
9400** the where.c module.
9401**
9402** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
9403** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
9404** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
9405** case that more than one of these conditions is true.
9406*/
9407struct WherePlan {
9408  u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
9409  u32 nEq;                       /* Number of == constraints */
9410  union {
9411    Index *pIdx;                   /* Index when WHERE_INDEXED is true */
9412    struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
9413    sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
9414  } u;
9415};
9416
9417/*
9418** For each nested loop in a WHERE clause implementation, the WhereInfo
9419** structure contains a single instance of this structure.  This structure
9420** is intended to be private the the where.c module and should not be
9421** access or modified by other modules.
9422**
9423** The pIdxInfo field is used to help pick the best index on a
9424** virtual table.  The pIdxInfo pointer contains indexing
9425** information for the i-th table in the FROM clause before reordering.
9426** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
9427** All other information in the i-th WhereLevel object for the i-th table
9428** after FROM clause ordering.
9429*/
9430struct WhereLevel {
9431  WherePlan plan;       /* query plan for this element of the FROM clause */
9432  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
9433  int iTabCur;          /* The VDBE cursor used to access the table */
9434  int iIdxCur;          /* The VDBE cursor used to access pIdx */
9435  int addrBrk;          /* Jump here to break out of the loop */
9436  int addrNxt;          /* Jump here to start the next IN combination */
9437  int addrCont;         /* Jump here to continue with the next loop cycle */
9438  int addrFirst;        /* First instruction of interior of the loop */
9439  u8 iFrom;             /* Which entry in the FROM clause */
9440  u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
9441  int p1, p2;           /* Operands of the opcode used to ends the loop */
9442  union {               /* Information that depends on plan.wsFlags */
9443    struct {
9444      int nIn;              /* Number of entries in aInLoop[] */
9445      struct InLoop {
9446        int iCur;              /* The VDBE cursor used by this IN operator */
9447        int addrInTop;         /* Top of the IN loop */
9448      } *aInLoop;           /* Information about each nested IN operator */
9449    } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
9450  } u;
9451
9452  /* The following field is really not part of the current level.  But
9453  ** we need a place to cache virtual table index information for each
9454  ** virtual table in the FROM clause and the WhereLevel structure is
9455  ** a convenient place since there is one WhereLevel for each FROM clause
9456  ** element.
9457  */
9458  sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
9459};
9460
9461/*
9462** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
9463** and the WhereInfo.wctrlFlags member.
9464*/
9465#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
9466#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
9467#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
9468#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
9469#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
9470#define WHERE_OMIT_OPEN        0x0010 /* Table cursor are already open */
9471#define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
9472#define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
9473#define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
9474
9475/*
9476** The WHERE clause processing routine has two halves.  The
9477** first part does the start of the WHERE loop and the second
9478** half does the tail of the WHERE loop.  An instance of
9479** this structure is returned by the first half and passed
9480** into the second half to give some continuity.
9481*/
9482struct WhereInfo {
9483  Parse *pParse;       /* Parsing and code generating context */
9484  u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
9485  u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
9486  u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
9487  SrcList *pTabList;             /* List of tables in the join */
9488  int iTop;                      /* The very beginning of the WHERE loop */
9489  int iContinue;                 /* Jump here to continue with next record */
9490  int iBreak;                    /* Jump here to break out of the loop */
9491  int nLevel;                    /* Number of nested loop */
9492  struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
9493  WhereLevel a[1];               /* Information about each nest loop in WHERE */
9494};
9495
9496/*
9497** A NameContext defines a context in which to resolve table and column
9498** names.  The context consists of a list of tables (the pSrcList) field and
9499** a list of named expression (pEList).  The named expression list may
9500** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
9501** to the table being operated on by INSERT, UPDATE, or DELETE.  The
9502** pEList corresponds to the result set of a SELECT and is NULL for
9503** other statements.
9504**
9505** NameContexts can be nested.  When resolving names, the inner-most
9506** context is searched first.  If no match is found, the next outer
9507** context is checked.  If there is still no match, the next context
9508** is checked.  This process continues until either a match is found
9509** or all contexts are check.  When a match is found, the nRef member of
9510** the context containing the match is incremented.
9511**
9512** Each subquery gets a new NameContext.  The pNext field points to the
9513** NameContext in the parent query.  Thus the process of scanning the
9514** NameContext list corresponds to searching through successively outer
9515** subqueries looking for a match.
9516*/
9517struct NameContext {
9518  Parse *pParse;       /* The parser */
9519  SrcList *pSrcList;   /* One or more tables used to resolve names */
9520  ExprList *pEList;    /* Optional list of named expressions */
9521  int nRef;            /* Number of names resolved by this context */
9522  int nErr;            /* Number of errors encountered while resolving names */
9523  u8 allowAgg;         /* Aggregate functions allowed here */
9524  u8 hasAgg;           /* True if aggregates are seen */
9525  u8 isCheck;          /* True if resolving names in a CHECK constraint */
9526  int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
9527  AggInfo *pAggInfo;   /* Information about aggregates at this level */
9528  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
9529};
9530
9531/*
9532** An instance of the following structure contains all information
9533** needed to generate code for a single SELECT statement.
9534**
9535** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
9536** If there is a LIMIT clause, the parser sets nLimit to the value of the
9537** limit and nOffset to the value of the offset (or 0 if there is not
9538** offset).  But later on, nLimit and nOffset become the memory locations
9539** in the VDBE that record the limit and offset counters.
9540**
9541** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
9542** These addresses must be stored so that we can go back and fill in
9543** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
9544** the number of columns in P2 can be computed at the same time
9545** as the OP_OpenEphm instruction is coded because not
9546** enough information about the compound query is known at that point.
9547** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
9548** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
9549** sequences for the ORDER BY clause.
9550*/
9551struct Select {
9552  ExprList *pEList;      /* The fields of the result */
9553  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
9554  char affinity;         /* MakeRecord with this affinity for SRT_Set */
9555  u16 selFlags;          /* Various SF_* values */
9556  SrcList *pSrc;         /* The FROM clause */
9557  Expr *pWhere;          /* The WHERE clause */
9558  ExprList *pGroupBy;    /* The GROUP BY clause */
9559  Expr *pHaving;         /* The HAVING clause */
9560  ExprList *pOrderBy;    /* The ORDER BY clause */
9561  Select *pPrior;        /* Prior select in a compound select statement */
9562  Select *pNext;         /* Next select to the left in a compound */
9563  Select *pRightmost;    /* Right-most select in a compound select statement */
9564  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
9565  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
9566  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
9567  int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
9568};
9569
9570/*
9571** Allowed values for Select.selFlags.  The "SF" prefix stands for
9572** "Select Flag".
9573*/
9574#define SF_Distinct        0x0001  /* Output should be DISTINCT */
9575#define SF_Resolved        0x0002  /* Identifiers have been resolved */
9576#define SF_Aggregate       0x0004  /* Contains aggregate functions */
9577#define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
9578#define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
9579#define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
9580
9581
9582/*
9583** The results of a select can be distributed in several ways.  The
9584** "SRT" prefix means "SELECT Result Type".
9585*/
9586#define SRT_Union        1  /* Store result as keys in an index */
9587#define SRT_Except       2  /* Remove result from a UNION index */
9588#define SRT_Exists       3  /* Store 1 if the result is not empty */
9589#define SRT_Discard      4  /* Do not save the results anywhere */
9590
9591/* The ORDER BY clause is ignored for all of the above */
9592#define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
9593
9594#define SRT_Output       5  /* Output each row of result */
9595#define SRT_Mem          6  /* Store result in a memory cell */
9596#define SRT_Set          7  /* Store results as keys in an index */
9597#define SRT_Table        8  /* Store result as data with an automatic rowid */
9598#define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
9599#define SRT_Coroutine   10  /* Generate a single row of result */
9600
9601/*
9602** A structure used to customize the behavior of sqlite3Select(). See
9603** comments above sqlite3Select() for details.
9604*/
9605typedef struct SelectDest SelectDest;
9606struct SelectDest {
9607  u8 eDest;         /* How to dispose of the results */
9608  u8 affinity;      /* Affinity used when eDest==SRT_Set */
9609  int iParm;        /* A parameter used by the eDest disposal method */
9610  int iMem;         /* Base register where results are written */
9611  int nMem;         /* Number of registers allocated */
9612};
9613
9614/*
9615** During code generation of statements that do inserts into AUTOINCREMENT
9616** tables, the following information is attached to the Table.u.autoInc.p
9617** pointer of each autoincrement table to record some side information that
9618** the code generator needs.  We have to keep per-table autoincrement
9619** information in case inserts are down within triggers.  Triggers do not
9620** normally coordinate their activities, but we do need to coordinate the
9621** loading and saving of autoincrement information.
9622*/
9623struct AutoincInfo {
9624  AutoincInfo *pNext;   /* Next info block in a list of them all */
9625  Table *pTab;          /* Table this info block refers to */
9626  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
9627  int regCtr;           /* Memory register holding the rowid counter */
9628};
9629
9630/*
9631** Size of the column cache
9632*/
9633#ifndef SQLITE_N_COLCACHE
9634# define SQLITE_N_COLCACHE 10
9635#endif
9636
9637/*
9638** At least one instance of the following structure is created for each
9639** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
9640** statement. All such objects are stored in the linked list headed at
9641** Parse.pTriggerPrg and deleted once statement compilation has been
9642** completed.
9643**
9644** A Vdbe sub-program that implements the body and WHEN clause of trigger
9645** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
9646** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
9647** The Parse.pTriggerPrg list never contains two entries with the same
9648** values for both pTrigger and orconf.
9649**
9650** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
9651** accessed (or set to 0 for triggers fired as a result of INSERT
9652** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
9653** a mask of new.* columns used by the program.
9654*/
9655struct TriggerPrg {
9656  Trigger *pTrigger;      /* Trigger this program was coded from */
9657  int orconf;             /* Default ON CONFLICT policy */
9658  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
9659  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
9660  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
9661};
9662
9663/*
9664** An SQL parser context.  A copy of this structure is passed through
9665** the parser and down into all the parser action routine in order to
9666** carry around information that is global to the entire parse.
9667**
9668** The structure is divided into two parts.  When the parser and code
9669** generate call themselves recursively, the first part of the structure
9670** is constant but the second part is reset at the beginning and end of
9671** each recursion.
9672**
9673** The nTableLock and aTableLock variables are only used if the shared-cache
9674** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
9675** used to store the set of table-locks required by the statement being
9676** compiled. Function sqlite3TableLock() is used to add entries to the
9677** list.
9678*/
9679struct Parse {
9680  sqlite3 *db;         /* The main database structure */
9681  int rc;              /* Return code from execution */
9682  char *zErrMsg;       /* An error message */
9683  Vdbe *pVdbe;         /* An engine for executing database bytecode */
9684  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
9685  u8 nameClash;        /* A permanent table name clashes with temp table name */
9686  u8 checkSchema;      /* Causes schema cookie check after an error */
9687  u8 nested;           /* Number of nested calls to the parser/code generator */
9688  u8 parseError;       /* True after a parsing error.  Ticket #1794 */
9689  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
9690  u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
9691  int aTempReg[8];     /* Holding area for temporary registers */
9692  int nRangeReg;       /* Size of the temporary register block */
9693  int iRangeReg;       /* First register in temporary register block */
9694  int nErr;            /* Number of errors seen */
9695  int nTab;            /* Number of previously allocated VDBE cursors */
9696  int nMem;            /* Number of memory cells used so far */
9697  int nSet;            /* Number of sets used so far */
9698  int ckBase;          /* Base register of data during check constraints */
9699  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
9700  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
9701  u8 nColCache;        /* Number of entries in the column cache */
9702  u8 iColCache;        /* Next entry of the cache to replace */
9703  struct yColCache {
9704    int iTable;           /* Table cursor number */
9705    int iColumn;          /* Table column number */
9706    u8 tempReg;           /* iReg is a temp register that needs to be freed */
9707    int iLevel;           /* Nesting level */
9708    int iReg;             /* Reg with value of this column. 0 means none. */
9709    int lru;              /* Least recently used entry has the smallest value */
9710  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
9711  u32 writeMask;       /* Start a write transaction on these databases */
9712  u32 cookieMask;      /* Bitmask of schema verified databases */
9713  u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
9714  u8 mayAbort;         /* True if statement may throw an ABORT exception */
9715  int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
9716  int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
9717#ifndef SQLITE_OMIT_SHARED_CACHE
9718  int nTableLock;        /* Number of locks in aTableLock */
9719  TableLock *aTableLock; /* Required table locks for shared-cache mode */
9720#endif
9721  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
9722  int regRoot;         /* Register holding root page number for new objects */
9723  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
9724  int nMaxArg;         /* Max args passed to user function by sub-program */
9725
9726  /* Information used while coding trigger programs. */
9727  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
9728  Table *pTriggerTab;  /* Table triggers are being coded for */
9729  u32 oldmask;         /* Mask of old.* columns referenced */
9730  u32 newmask;         /* Mask of new.* columns referenced */
9731  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
9732  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
9733  u8 disableTriggers;  /* True to disable triggers */
9734
9735  /* Above is constant between recursions.  Below is reset before and after
9736  ** each recursion */
9737
9738  int nVar;            /* Number of '?' variables seen in the SQL so far */
9739  int nVarExpr;        /* Number of used slots in apVarExpr[] */
9740  int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
9741  Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
9742  Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
9743  int nAlias;          /* Number of aliased result set columns */
9744  int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
9745  int *aAlias;         /* Register used to hold aliased result */
9746  u8 explain;          /* True if the EXPLAIN flag is found on the query */
9747  Token sNameToken;    /* Token with unqualified schema object name */
9748  Token sLastToken;    /* The last token parsed */
9749  const char *zTail;   /* All SQL text past the last semicolon parsed */
9750  Table *pNewTable;    /* A table being constructed by CREATE TABLE */
9751  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
9752  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
9753#ifndef SQLITE_OMIT_VIRTUALTABLE
9754  Token sArg;                /* Complete text of a module argument */
9755  u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
9756  int nVtabLock;             /* Number of virtual tables to lock */
9757  Table **apVtabLock;        /* Pointer to virtual tables needing locking */
9758#endif
9759  int nHeight;            /* Expression tree height of current sub-select */
9760  Table *pZombieTab;      /* List of Table objects to delete after code gen */
9761  TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
9762};
9763
9764#ifdef SQLITE_OMIT_VIRTUALTABLE
9765  #define IN_DECLARE_VTAB 0
9766#else
9767  #define IN_DECLARE_VTAB (pParse->declareVtab)
9768#endif
9769
9770/*
9771** An instance of the following structure can be declared on a stack and used
9772** to save the Parse.zAuthContext value so that it can be restored later.
9773*/
9774struct AuthContext {
9775  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
9776  Parse *pParse;              /* The Parse structure */
9777};
9778
9779/*
9780** Bitfield flags for P5 value in OP_Insert and OP_Delete
9781*/
9782#define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
9783#define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
9784#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
9785#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
9786#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
9787#define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
9788
9789/*
9790 * Each trigger present in the database schema is stored as an instance of
9791 * struct Trigger.
9792 *
9793 * Pointers to instances of struct Trigger are stored in two ways.
9794 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
9795 *    database). This allows Trigger structures to be retrieved by name.
9796 * 2. All triggers associated with a single table form a linked list, using the
9797 *    pNext member of struct Trigger. A pointer to the first element of the
9798 *    linked list is stored as the "pTrigger" member of the associated
9799 *    struct Table.
9800 *
9801 * The "step_list" member points to the first element of a linked list
9802 * containing the SQL statements specified as the trigger program.
9803 */
9804struct Trigger {
9805  char *zName;            /* The name of the trigger                        */
9806  char *table;            /* The table or view to which the trigger applies */
9807  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
9808  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
9809  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
9810  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
9811                             the <column-list> is stored here */
9812  Schema *pSchema;        /* Schema containing the trigger */
9813  Schema *pTabSchema;     /* Schema containing the table */
9814  TriggerStep *step_list; /* Link list of trigger program steps             */
9815  Trigger *pNext;         /* Next trigger associated with the table */
9816};
9817
9818/*
9819** A trigger is either a BEFORE or an AFTER trigger.  The following constants
9820** determine which.
9821**
9822** If there are multiple triggers, you might of some BEFORE and some AFTER.
9823** In that cases, the constants below can be ORed together.
9824*/
9825#define TRIGGER_BEFORE  1
9826#define TRIGGER_AFTER   2
9827
9828/*
9829 * An instance of struct TriggerStep is used to store a single SQL statement
9830 * that is a part of a trigger-program.
9831 *
9832 * Instances of struct TriggerStep are stored in a singly linked list (linked
9833 * using the "pNext" member) referenced by the "step_list" member of the
9834 * associated struct Trigger instance. The first element of the linked list is
9835 * the first step of the trigger-program.
9836 *
9837 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
9838 * "SELECT" statement. The meanings of the other members is determined by the
9839 * value of "op" as follows:
9840 *
9841 * (op == TK_INSERT)
9842 * orconf    -> stores the ON CONFLICT algorithm
9843 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
9844 *              this stores a pointer to the SELECT statement. Otherwise NULL.
9845 * target    -> A token holding the quoted name of the table to insert into.
9846 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
9847 *              this stores values to be inserted. Otherwise NULL.
9848 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
9849 *              statement, then this stores the column-names to be
9850 *              inserted into.
9851 *
9852 * (op == TK_DELETE)
9853 * target    -> A token holding the quoted name of the table to delete from.
9854 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
9855 *              Otherwise NULL.
9856 *
9857 * (op == TK_UPDATE)
9858 * target    -> A token holding the quoted name of the table to update rows of.
9859 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
9860 *              Otherwise NULL.
9861 * pExprList -> A list of the columns to update and the expressions to update
9862 *              them to. See sqlite3Update() documentation of "pChanges"
9863 *              argument.
9864 *
9865 */
9866struct TriggerStep {
9867  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
9868  u8 orconf;           /* OE_Rollback etc. */
9869  Trigger *pTrig;      /* The trigger that this step is a part of */
9870  Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
9871  Token target;        /* Target table for DELETE, UPDATE, INSERT */
9872  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
9873  ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
9874  IdList *pIdList;     /* Column names for INSERT */
9875  TriggerStep *pNext;  /* Next in the link-list */
9876  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
9877};
9878
9879/*
9880** The following structure contains information used by the sqliteFix...
9881** routines as they walk the parse tree to make database references
9882** explicit.
9883*/
9884typedef struct DbFixer DbFixer;
9885struct DbFixer {
9886  Parse *pParse;      /* The parsing context.  Error messages written here */
9887  const char *zDb;    /* Make sure all objects are contained in this database */
9888  const char *zType;  /* Type of the container - used for error messages */
9889  const Token *pName; /* Name of the container - used for error messages */
9890};
9891
9892/*
9893** An objected used to accumulate the text of a string where we
9894** do not necessarily know how big the string will be in the end.
9895*/
9896struct StrAccum {
9897  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
9898  char *zBase;         /* A base allocation.  Not from malloc. */
9899  char *zText;         /* The string collected so far */
9900  int  nChar;          /* Length of the string so far */
9901  int  nAlloc;         /* Amount of space allocated in zText */
9902  int  mxAlloc;        /* Maximum allowed string length */
9903  u8   mallocFailed;   /* Becomes true if any memory allocation fails */
9904  u8   useMalloc;      /* True if zText is enlargeable using realloc */
9905  u8   tooBig;         /* Becomes true if string size exceeds limits */
9906};
9907
9908/*
9909** A pointer to this structure is used to communicate information
9910** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
9911*/
9912typedef struct {
9913  sqlite3 *db;        /* The database being initialized */
9914  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
9915  char **pzErrMsg;    /* Error message stored here */
9916  int rc;             /* Result code stored here */
9917} InitData;
9918
9919/*
9920** Structure containing global configuration data for the SQLite library.
9921**
9922** This structure also contains some state information.
9923*/
9924struct Sqlite3Config {
9925  int bMemstat;                     /* True to enable memory status */
9926  int bCoreMutex;                   /* True to enable core mutexing */
9927  int bFullMutex;                   /* True to enable full mutexing */
9928  int mxStrlen;                     /* Maximum string length */
9929  int szLookaside;                  /* Default lookaside buffer size */
9930  int nLookaside;                   /* Default lookaside buffer count */
9931  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
9932  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
9933  sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
9934  void *pHeap;                      /* Heap storage space */
9935  int nHeap;                        /* Size of pHeap[] */
9936  int mnReq, mxReq;                 /* Min and max heap requests sizes */
9937  void *pScratch;                   /* Scratch memory */
9938  int szScratch;                    /* Size of each scratch buffer */
9939  int nScratch;                     /* Number of scratch buffers */
9940  void *pPage;                      /* Page cache memory */
9941  int szPage;                       /* Size of each page in pPage[] */
9942  int nPage;                        /* Number of pages in pPage[] */
9943  int mxParserStack;                /* maximum depth of the parser stack */
9944  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
9945  /* The above might be initialized to non-zero.  The following need to always
9946  ** initially be zero, however. */
9947  int isInit;                       /* True after initialization has finished */
9948  int inProgress;                   /* True while initialization in progress */
9949  int isMutexInit;                  /* True after mutexes are initialized */
9950  int isMallocInit;                 /* True after malloc is initialized */
9951  int isPCacheInit;                 /* True after malloc is initialized */
9952  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
9953  int nRefInitMutex;                /* Number of users of pInitMutex */
9954};
9955
9956/*
9957** Context pointer passed down through the tree-walk.
9958*/
9959struct Walker {
9960  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
9961  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
9962  Parse *pParse;                            /* Parser context.  */
9963  union {                                   /* Extra data for callback */
9964    NameContext *pNC;                          /* Naming context */
9965    int i;                                     /* Integer value */
9966  } u;
9967};
9968
9969/* Forward declarations */
9970SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
9971SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
9972SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
9973SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
9974SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
9975
9976/*
9977** Return code from the parse-tree walking primitives and their
9978** callbacks.
9979*/
9980#define WRC_Continue    0   /* Continue down into children */
9981#define WRC_Prune       1   /* Omit children but continue walking siblings */
9982#define WRC_Abort       2   /* Abandon the tree walk */
9983
9984/*
9985** Assuming zIn points to the first byte of a UTF-8 character,
9986** advance zIn to point to the first byte of the next UTF-8 character.
9987*/
9988#define SQLITE_SKIP_UTF8(zIn) {                        \
9989  if( (*(zIn++))>=0xc0 ){                              \
9990    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
9991  }                                                    \
9992}
9993
9994/*
9995** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
9996** builds) or a function call (for debugging).  If it is a function call,
9997** it allows the operator to set a breakpoint at the spot where database
9998** corruption is first detected.
9999*/
10000/* Begin Android Delete
10001#ifdef SQLITE_DEBUG
10002SQLITE_PRIVATE   int sqlite3Corrupt(void);
10003# define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
10004#else
10005# define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
10006#endif
10007*/
10008
10009/*
10010** The ctype.h header is needed for non-ASCII systems.  It is also
10011** needed by FTS3 when FTS3 is included in the amalgamation.
10012*/
10013#if !defined(SQLITE_ASCII) || \
10014    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
10015# include <ctype.h>
10016#endif
10017
10018/*
10019** The following macros mimic the standard library functions toupper(),
10020** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
10021** sqlite versions only work for ASCII characters, regardless of locale.
10022*/
10023#ifdef SQLITE_ASCII
10024# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
10025# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
10026# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
10027# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
10028# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
10029# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
10030# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
10031#else
10032# define sqlite3Toupper(x)   toupper((unsigned char)(x))
10033# define sqlite3Isspace(x)   isspace((unsigned char)(x))
10034# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
10035# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
10036# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
10037# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
10038# define sqlite3Tolower(x)   tolower((unsigned char)(x))
10039#endif
10040
10041/*
10042** Internal function prototypes
10043*/
10044SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10045SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
10046SQLITE_PRIVATE int sqlite3Strlen30(const char*);
10047#define sqlite3StrNICmp sqlite3_strnicmp
10048
10049SQLITE_PRIVATE int sqlite3MallocInit(void);
10050SQLITE_PRIVATE void sqlite3MallocEnd(void);
10051SQLITE_PRIVATE void *sqlite3Malloc(int);
10052SQLITE_PRIVATE void *sqlite3MallocZero(int);
10053SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10054SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10055SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10056SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10057SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10058SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10059SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10060SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10061SQLITE_PRIVATE int sqlite3MallocSize(void*);
10062SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10063SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10064SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10065SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10066SQLITE_PRIVATE void sqlite3PageFree(void*);
10067SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10068SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10069SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
10070
10071/*
10072** On systems with ample stack space and that support alloca(), make
10073** use of alloca() to obtain space for large automatic objects.  By default,
10074** obtain space from malloc().
10075**
10076** The alloca() routine never returns NULL.  This will cause code paths
10077** that deal with sqlite3StackAlloc() failures to be unreachable.
10078*/
10079#ifdef SQLITE_USE_ALLOCA
10080# define sqlite3StackAllocRaw(D,N)   alloca(N)
10081# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
10082# define sqlite3StackFree(D,P)
10083#else
10084# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
10085# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
10086# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
10087#endif
10088
10089#ifdef SQLITE_ENABLE_MEMSYS3
10090SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10091#endif
10092#ifdef SQLITE_ENABLE_MEMSYS5
10093SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10094#endif
10095
10096
10097#ifndef SQLITE_MUTEX_OMIT
10098SQLITE_PRIVATE   sqlite3_mutex_methods *sqlite3DefaultMutex(void);
10099SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10100SQLITE_PRIVATE   int sqlite3MutexInit(void);
10101SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10102#endif
10103
10104SQLITE_PRIVATE int sqlite3StatusValue(int);
10105SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10106SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10107
10108SQLITE_PRIVATE int sqlite3IsNaN(double);
10109
10110SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10111#ifndef SQLITE_OMIT_TRACE
10112SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10113#endif
10114SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10115SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10116SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10117#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10118SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10119#endif
10120#if defined(SQLITE_TEST)
10121SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10122#endif
10123SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10124SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10125SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
10126SQLITE_PRIVATE int sqlite3Dequote(char*);
10127SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10128SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10129SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10130SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10131SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10132SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10133SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10134SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
10135SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
10136SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
10137SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10138SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10139SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10140SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10141SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10142SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
10143SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
10144SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
10145SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10146SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10147SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10148SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10149SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10150SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10151SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10152SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10153SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10154SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10155SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10156SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10157SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10158SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10159SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10160SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
10161SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10162SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10163
10164SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10165SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10166SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10167SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
10168SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10169SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
10170SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
10171
10172SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
10173SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
10174SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
10175SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
10176SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
10177
10178SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
10179
10180#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
10181SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
10182#else
10183# define sqlite3ViewGetColumnNames(A,B) 0
10184#endif
10185
10186SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10187SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
10188#ifndef SQLITE_OMIT_AUTOINCREMENT
10189SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
10190SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
10191#else
10192# define sqlite3AutoincrementBegin(X)
10193# define sqlite3AutoincrementEnd(X)
10194#endif
10195SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
10196SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
10197SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
10198SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
10199SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
10200SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
10201SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
10202                                      Token*, Select*, Expr*, IdList*);
10203SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
10204SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
10205SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
10206SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
10207SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
10208SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
10209SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
10210                        Token*, int, int);
10211SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
10212SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
10213SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
10214                         Expr*,ExprList*,int,Expr*,Expr*);
10215SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
10216SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
10217SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
10218SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
10219#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
10220SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
10221#endif
10222SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
10223SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
10224SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
10225SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10226SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
10227SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10228SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10229SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
10230SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
10231SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
10232SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
10233SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
10234SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10235SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
10236SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10237SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10238SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10239SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10240SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
10241SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
10242SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
10243SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
10244SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
10245SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
10246SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
10247SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
10248SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
10249SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
10250SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10251SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10252SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10253SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10254SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10255SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10256SQLITE_PRIVATE void sqlite3PrngSaveState(void);
10257SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
10258SQLITE_PRIVATE void sqlite3PrngResetState(void);
10259SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
10260SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
10261SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
10262SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
10263SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
10264SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
10265SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
10266SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
10267SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
10268SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
10269SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
10270SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
10271SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
10272SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
10273SQLITE_PRIVATE int sqlite3IsRowid(const char*);
10274SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
10275SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
10276SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
10277SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
10278                                     int*,int,int,int,int,int*);
10279SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
10280SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
10281SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
10282SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
10283SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
10284SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
10285SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
10286SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
10287SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
10288SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
10289SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
10290SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
10291SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
10292SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
10293SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
10294SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
10295#ifdef SQLITE_DEBUG
10296SQLITE_PRIVATE   int sqlite3SafetyOn(sqlite3*);
10297SQLITE_PRIVATE   int sqlite3SafetyOff(sqlite3*);
10298#else
10299# define sqlite3SafetyOn(A) 0
10300# define sqlite3SafetyOff(A) 0
10301#endif
10302SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
10303SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
10304SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
10305
10306#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
10307SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
10308#endif
10309
10310#ifndef SQLITE_OMIT_TRIGGER
10311SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
10312                           Expr*,int, int);
10313SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
10314SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
10315SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
10316SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
10317SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
10318SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
10319                            int, int, int);
10320SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
10321  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
10322SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
10323SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
10324SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
10325                                        ExprList*,Select*,u8);
10326SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
10327SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
10328SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
10329SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
10330SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
10331# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
10332#else
10333# define sqlite3TriggersExist(B,C,D,E,F) 0
10334# define sqlite3DeleteTrigger(A,B)
10335# define sqlite3DropTriggerPtr(A,B)
10336# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
10337# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
10338# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
10339# define sqlite3TriggerList(X, Y) 0
10340# define sqlite3ParseToplevel(p) p
10341# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
10342#endif
10343
10344SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
10345SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
10346SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
10347#ifndef SQLITE_OMIT_AUTHORIZATION
10348SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
10349SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
10350SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
10351SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
10352SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
10353#else
10354# define sqlite3AuthRead(a,b,c,d)
10355# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
10356# define sqlite3AuthContextPush(a,b,c)
10357# define sqlite3AuthContextPop(a)  ((void)(a))
10358#endif
10359SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10360SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10361SQLITE_PRIVATE int sqlite3BtreeFactory(sqlite3 *db, const char *zFilename,
10362                       int omitJournal, int nCache, int flags, Btree **ppBtree);
10363SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10364SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10365SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10366SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10367SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
10368SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
10369SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
10370SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
10371SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
10372SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
10373SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
10374SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
10375
10376/*
10377** Routines to read and write variable-length integers.  These used to
10378** be defined locally, but now we use the varint routines in the util.c
10379** file.  Code should use the MACRO forms below, as the Varint32 versions
10380** are coded to assume the single byte case is already handled (which
10381** the MACRO form does).
10382*/
10383SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
10384SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
10385SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
10386SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
10387SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
10388
10389/*
10390** The header of a record consists of a sequence variable-length integers.
10391** These integers are almost always small and are encoded as a single byte.
10392** The following macros take advantage this fact to provide a fast encode
10393** and decode of the integers in a record header.  It is faster for the common
10394** case where the integer is a single byte.  It is a little slower when the
10395** integer is two or more bytes.  But overall it is faster.
10396**
10397** The following expressions are equivalent:
10398**
10399**     x = sqlite3GetVarint32( A, &B );
10400**     x = sqlite3PutVarint32( A, B );
10401**
10402**     x = getVarint32( A, B );
10403**     x = putVarint32( A, B );
10404**
10405*/
10406#define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
10407#define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
10408#define getVarint    sqlite3GetVarint
10409#define putVarint    sqlite3PutVarint
10410
10411
10412SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
10413SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
10414SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
10415SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
10416SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
10417SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
10418SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
10419SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
10420SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
10421SQLITE_PRIVATE const char *sqlite3ErrStr(int);
10422SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
10423SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
10424SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
10425SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10426SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
10427SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10428SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10429SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
10430
10431SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
10432SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
10433SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
10434                        void(*)(void*));
10435SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
10436SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
10437SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
10438#ifdef SQLITE_ENABLE_STAT2
10439SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
10440#endif
10441SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
10442SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
10443#ifndef SQLITE_AMALGAMATION
10444SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
10445SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10446SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
10447SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
10448SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10449SQLITE_PRIVATE int sqlite3PendingByte;
10450#endif
10451SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10452SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10453SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
10454SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10455SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10456SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
10457SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
10458SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
10459SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
10460SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
10461SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
10462SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
10463SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
10464SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
10465SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
10466SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
10467SQLITE_PRIVATE char sqlite3AffinityType(const char*);
10468SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
10469SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
10470SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10471SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
10472SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
10473SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index*);
10474SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
10475SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
10476SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
10477SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
10478SQLITE_PRIVATE void sqlite3SchemaFree(void *);
10479SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
10480SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
10481SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
10482SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
10483  void (*)(sqlite3_context*,int,sqlite3_value **),
10484  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
10485SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
10486SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
10487
10488SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
10489SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
10490SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
10491SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
10492SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
10493SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
10494
10495SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
10496SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
10497
10498/*
10499** The interface to the LEMON-generated parser
10500*/
10501SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
10502SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
10503SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
10504#ifdef YYTRACKMAXSTACKDEPTH
10505SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
10506#endif
10507
10508SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
10509#ifndef SQLITE_OMIT_LOAD_EXTENSION
10510SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
10511#else
10512# define sqlite3CloseExtensions(X)
10513#endif
10514
10515#ifndef SQLITE_OMIT_SHARED_CACHE
10516SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
10517#else
10518  #define sqlite3TableLock(v,w,x,y,z)
10519#endif
10520
10521#ifdef SQLITE_TEST
10522SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
10523#endif
10524
10525#ifdef SQLITE_OMIT_VIRTUALTABLE
10526#  define sqlite3VtabClear(Y)
10527#  define sqlite3VtabSync(X,Y) SQLITE_OK
10528#  define sqlite3VtabRollback(X)
10529#  define sqlite3VtabCommit(X)
10530#  define sqlite3VtabInSync(db) 0
10531#  define sqlite3VtabLock(X)
10532#  define sqlite3VtabUnlock(X)
10533#  define sqlite3VtabUnlockList(X)
10534#else
10535SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
10536SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
10537SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
10538SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
10539SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
10540SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
10541SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
10542#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
10543#endif
10544SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
10545SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
10546SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
10547SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
10548SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
10549SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
10550SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
10551SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
10552SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
10553SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
10554SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
10555SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
10556SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
10557SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
10558SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
10559SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10560SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
10561SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
10562
10563/* Declarations for functions in fkey.c. All of these are replaced by
10564** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
10565** key functionality is available. If OMIT_TRIGGER is defined but
10566** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
10567** this case foreign keys are parsed, but no other functionality is
10568** provided (enforcement of FK constraints requires the triggers sub-system).
10569*/
10570#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
10571SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
10572SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
10573SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
10574SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
10575SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
10576SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
10577#else
10578  #define sqlite3FkActions(a,b,c,d)
10579  #define sqlite3FkCheck(a,b,c,d)
10580  #define sqlite3FkDropTable(a,b,c)
10581  #define sqlite3FkOldmask(a,b)      0
10582  #define sqlite3FkRequired(a,b,c,d) 0
10583#endif
10584#ifndef SQLITE_OMIT_FOREIGN_KEY
10585SQLITE_PRIVATE   void sqlite3FkDelete(Table*);
10586#else
10587  #define sqlite3FkDelete(a)
10588#endif
10589
10590
10591/*
10592** Available fault injectors.  Should be numbered beginning with 0.
10593*/
10594#define SQLITE_FAULTINJECTOR_MALLOC     0
10595#define SQLITE_FAULTINJECTOR_COUNT      1
10596
10597/*
10598** The interface to the code in fault.c used for identifying "benign"
10599** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
10600** is not defined.
10601*/
10602#ifndef SQLITE_OMIT_BUILTIN_TEST
10603SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
10604SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
10605#else
10606  #define sqlite3BeginBenignMalloc()
10607  #define sqlite3EndBenignMalloc()
10608#endif
10609
10610#define IN_INDEX_ROWID           1
10611#define IN_INDEX_EPH             2
10612#define IN_INDEX_INDEX           3
10613SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
10614
10615#ifdef SQLITE_ENABLE_ATOMIC_WRITE
10616SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
10617SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
10618SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
10619#else
10620  #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
10621#endif
10622
10623SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
10624SQLITE_PRIVATE int sqlite3MemJournalSize(void);
10625SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
10626
10627#if SQLITE_MAX_EXPR_DEPTH>0
10628SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
10629SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
10630SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
10631#else
10632  #define sqlite3ExprSetHeight(x,y)
10633  #define sqlite3SelectExprHeight(x) 0
10634  #define sqlite3ExprCheckHeight(x,y)
10635#endif
10636
10637SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
10638SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
10639
10640#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10641SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
10642SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
10643SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
10644#else
10645  #define sqlite3ConnectionBlocked(x,y)
10646  #define sqlite3ConnectionUnlocked(x)
10647  #define sqlite3ConnectionClosed(x)
10648#endif
10649
10650#ifdef SQLITE_DEBUG
10651SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
10652#endif
10653
10654/*
10655** If the SQLITE_ENABLE IOTRACE exists then the global variable
10656** sqlite3IoTrace is a pointer to a printf-like routine used to
10657** print I/O tracing messages.
10658*/
10659#ifdef SQLITE_ENABLE_IOTRACE
10660# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
10661SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
10662SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
10663#else
10664# define IOTRACE(A)
10665# define sqlite3VdbeIOTraceSql(X)
10666#endif
10667
10668#endif
10669
10670/************** End of sqliteInt.h *******************************************/
10671/************** Begin file global.c ******************************************/
10672/*
10673** 2008 June 13
10674**
10675** The author disclaims copyright to this source code.  In place of
10676** a legal notice, here is a blessing:
10677**
10678**    May you do good and not evil.
10679**    May you find forgiveness for yourself and forgive others.
10680**    May you share freely, never taking more than you give.
10681**
10682*************************************************************************
10683**
10684** This file contains definitions of global variables and contants.
10685*/
10686
10687/* An array to map all upper-case characters into their corresponding
10688** lower-case character.
10689**
10690** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
10691** handle case conversions for the UTF character set since the tables
10692** involved are nearly as big or bigger than SQLite itself.
10693*/
10694SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
10695#ifdef SQLITE_ASCII
10696      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
10697     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
10698     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
10699     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
10700    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
10701    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
10702    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
10703    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
10704    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
10705    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
10706    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
10707    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
10708    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
10709    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
10710    252,253,254,255
10711#endif
10712#ifdef SQLITE_EBCDIC
10713      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
10714     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
10715     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
10716     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
10717     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
10718     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
10719     96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
10720    112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
10721    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
10722    144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
10723    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
10724    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
10725    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
10726    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
10727    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
10728    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
10729#endif
10730};
10731
10732/*
10733** The following 256 byte lookup table is used to support SQLites built-in
10734** equivalents to the following standard library functions:
10735**
10736**   isspace()                        0x01
10737**   isalpha()                        0x02
10738**   isdigit()                        0x04
10739**   isalnum()                        0x06
10740**   isxdigit()                       0x08
10741**   toupper()                        0x20
10742**   SQLite identifier character      0x40
10743**
10744** Bit 0x20 is set if the mapped character requires translation to upper
10745** case. i.e. if the character is a lower-case ASCII character.
10746** If x is a lower-case ASCII character, then its upper-case equivalent
10747** is (x - 0x20). Therefore toupper() can be implemented as:
10748**
10749**   (x & ~(map[x]&0x20))
10750**
10751** Standard function tolower() is implemented using the sqlite3UpperToLower[]
10752** array. tolower() is used more often than toupper() by SQLite.
10753**
10754** Bit 0x40 is set if the character non-alphanumeric and can be used in an
10755** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
10756** non-ASCII UTF character. Hence the test for whether or not a character is
10757** part of an identifier is 0x46.
10758**
10759** SQLite's versions are identical to the standard versions assuming a
10760** locale of "C". They are implemented as macros in sqliteInt.h.
10761*/
10762#ifdef SQLITE_ASCII
10763SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
10764  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
10765  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
10766  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
10767  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
10768  0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
10769  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
10770  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
10771  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
10772
10773  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
10774  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
10775  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
10776  0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
10777  0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
10778  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
10779  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
10780  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
10781
10782  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
10783  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
10784  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
10785  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
10786  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
10787  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
10788  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
10789  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
10790
10791  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
10792  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
10793  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
10794  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
10795  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
10796  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
10797  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
10798  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
10799};
10800#endif
10801
10802
10803
10804/*
10805** The following singleton contains the global configuration for
10806** the SQLite library.
10807*/
10808SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
10809   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
10810   1,                         /* bCoreMutex */
10811   SQLITE_THREADSAFE==1,      /* bFullMutex */
10812   0x7ffffffe,                /* mxStrlen */
10813   100,                       /* szLookaside */
10814   500,                       /* nLookaside */
10815   {0,0,0,0,0,0,0,0},         /* m */
10816   {0,0,0,0,0,0,0,0,0},       /* mutex */
10817   {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
10818   (void*)0,                  /* pHeap */
10819   0,                         /* nHeap */
10820   0, 0,                      /* mnHeap, mxHeap */
10821   (void*)0,                  /* pScratch */
10822   0,                         /* szScratch */
10823   0,                         /* nScratch */
10824   (void*)0,                  /* pPage */
10825   0,                         /* szPage */
10826   0,                         /* nPage */
10827   0,                         /* mxParserStack */
10828   0,                         /* sharedCacheEnabled */
10829   /* All the rest should always be initialized to zero */
10830   0,                         /* isInit */
10831   0,                         /* inProgress */
10832   0,                         /* isMutexInit */
10833   0,                         /* isMallocInit */
10834   0,                         /* isPCacheInit */
10835   0,                         /* pInitMutex */
10836   0,                         /* nRefInitMutex */
10837};
10838
10839
10840/*
10841** Hash table for global functions - functions common to all
10842** database connections.  After initialization, this table is
10843** read-only.
10844*/
10845SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10846
10847/*
10848** The value of the "pending" byte must be 0x40000000 (1 byte past the
10849** 1-gibabyte boundary) in a compatible database.  SQLite never uses
10850** the database page that contains the pending byte.  It never attempts
10851** to read or write that page.  The pending byte page is set assign
10852** for use by the VFS layers as space for managing file locks.
10853**
10854** During testing, it is often desirable to move the pending byte to
10855** a different position in the file.  This allows code that has to
10856** deal with the pending byte to run on files that are much smaller
10857** than 1 GiB.  The sqlite3_test_control() interface can be used to
10858** move the pending byte.
10859**
10860** IMPORTANT:  Changing the pending byte to any value other than
10861** 0x40000000 results in an incompatible database file format!
10862** Changing the pending byte during operating results in undefined
10863** and dileterious behavior.
10864*/
10865SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
10866
10867/*
10868** Properties of opcodes.  The OPFLG_INITIALIZER macro is
10869** created by mkopcodeh.awk during compilation.  Data is obtained
10870** from the comments following the "case OP_xxxx:" statements in
10871** the vdbe.c file.
10872*/
10873SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
10874
10875/************** End of global.c **********************************************/
10876/************** Begin file status.c ******************************************/
10877/*
10878** 2008 June 18
10879**
10880** The author disclaims copyright to this source code.  In place of
10881** a legal notice, here is a blessing:
10882**
10883**    May you do good and not evil.
10884**    May you find forgiveness for yourself and forgive others.
10885**    May you share freely, never taking more than you give.
10886**
10887*************************************************************************
10888**
10889** This module implements the sqlite3_status() interface and related
10890** functionality.
10891*/
10892
10893/*
10894** Variables in which to record status information.
10895*/
10896typedef struct sqlite3StatType sqlite3StatType;
10897static SQLITE_WSD struct sqlite3StatType {
10898  int nowValue[9];         /* Current value */
10899  int mxValue[9];          /* Maximum value */
10900} sqlite3Stat = { {0,}, {0,} };
10901
10902
10903/* The "wsdStat" macro will resolve to the status information
10904** state vector.  If writable static data is unsupported on the target,
10905** we have to locate the state vector at run-time.  In the more common
10906** case where writable static data is supported, wsdStat can refer directly
10907** to the "sqlite3Stat" state vector declared above.
10908*/
10909#ifdef SQLITE_OMIT_WSD
10910# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
10911# define wsdStat x[0]
10912#else
10913# define wsdStatInit
10914# define wsdStat sqlite3Stat
10915#endif
10916
10917/*
10918** Return the current value of a status parameter.
10919*/
10920SQLITE_PRIVATE int sqlite3StatusValue(int op){
10921  wsdStatInit;
10922  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10923  return wsdStat.nowValue[op];
10924}
10925
10926/*
10927** Add N to the value of a status record.  It is assumed that the
10928** caller holds appropriate locks.
10929*/
10930SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
10931  wsdStatInit;
10932  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10933  wsdStat.nowValue[op] += N;
10934  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
10935    wsdStat.mxValue[op] = wsdStat.nowValue[op];
10936  }
10937}
10938
10939/*
10940** Set the value of a status to X.
10941*/
10942SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
10943  wsdStatInit;
10944  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10945  wsdStat.nowValue[op] = X;
10946  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
10947    wsdStat.mxValue[op] = wsdStat.nowValue[op];
10948  }
10949}
10950
10951/*
10952** Query status information.
10953**
10954** This implementation assumes that reading or writing an aligned
10955** 32-bit integer is an atomic operation.  If that assumption is not true,
10956** then this routine is not threadsafe.
10957*/
10958SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
10959  wsdStatInit;
10960  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
10961    return SQLITE_MISUSE;
10962  }
10963  *pCurrent = wsdStat.nowValue[op];
10964  *pHighwater = wsdStat.mxValue[op];
10965  if( resetFlag ){
10966    wsdStat.mxValue[op] = wsdStat.nowValue[op];
10967  }
10968  return SQLITE_OK;
10969}
10970
10971/*
10972** Query status information for a single database connection
10973*/
10974SQLITE_API int sqlite3_db_status(
10975  sqlite3 *db,          /* The database connection whose status is desired */
10976  int op,               /* Status verb */
10977  int *pCurrent,        /* Write current value here */
10978  int *pHighwater,      /* Write high-water mark here */
10979  int resetFlag         /* Reset high-water mark if true */
10980){
10981  switch( op ){
10982    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
10983      *pCurrent = db->lookaside.nOut;
10984      *pHighwater = db->lookaside.mxOut;
10985      if( resetFlag ){
10986        db->lookaside.mxOut = db->lookaside.nOut;
10987      }
10988      break;
10989    }
10990    default: {
10991      return SQLITE_ERROR;
10992    }
10993  }
10994  return SQLITE_OK;
10995}
10996
10997/************** End of status.c **********************************************/
10998/************** Begin file date.c ********************************************/
10999/*
11000** 2003 October 31
11001**
11002** The author disclaims copyright to this source code.  In place of
11003** a legal notice, here is a blessing:
11004**
11005**    May you do good and not evil.
11006**    May you find forgiveness for yourself and forgive others.
11007**    May you share freely, never taking more than you give.
11008**
11009*************************************************************************
11010** This file contains the C functions that implement date and time
11011** functions for SQLite.
11012**
11013** There is only one exported symbol in this file - the function
11014** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
11015** All other code has file scope.
11016**
11017** SQLite processes all times and dates as Julian Day numbers.  The
11018** dates and times are stored as the number of days since noon
11019** in Greenwich on November 24, 4714 B.C. according to the Gregorian
11020** calendar system.
11021**
11022** 1970-01-01 00:00:00 is JD 2440587.5
11023** 2000-01-01 00:00:00 is JD 2451544.5
11024**
11025** This implemention requires years to be expressed as a 4-digit number
11026** which means that only dates between 0000-01-01 and 9999-12-31 can
11027** be represented, even though julian day numbers allow a much wider
11028** range of dates.
11029**
11030** The Gregorian calendar system is used for all dates and times,
11031** even those that predate the Gregorian calendar.  Historians usually
11032** use the Julian calendar for dates prior to 1582-10-15 and for some
11033** dates afterwards, depending on locale.  Beware of this difference.
11034**
11035** The conversion algorithms are implemented based on descriptions
11036** in the following text:
11037**
11038**      Jean Meeus
11039**      Astronomical Algorithms, 2nd Edition, 1998
11040**      ISBM 0-943396-61-1
11041**      Willmann-Bell, Inc
11042**      Richmond, Virginia (USA)
11043*/
11044#include <time.h>
11045
11046#ifndef SQLITE_OMIT_DATETIME_FUNCS
11047
11048/*
11049** On recent Windows platforms, the localtime_s() function is available
11050** as part of the "Secure CRT". It is essentially equivalent to
11051** localtime_r() available under most POSIX platforms, except that the
11052** order of the parameters is reversed.
11053**
11054** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
11055**
11056** If the user has not indicated to use localtime_r() or localtime_s()
11057** already, check for an MSVC build environment that provides
11058** localtime_s().
11059*/
11060#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
11061     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
11062#define HAVE_LOCALTIME_S 1
11063#endif
11064
11065/*
11066** A structure for holding a single date and time.
11067*/
11068typedef struct DateTime DateTime;
11069struct DateTime {
11070  sqlite3_int64 iJD; /* The julian day number times 86400000 */
11071  int Y, M, D;       /* Year, month, and day */
11072  int h, m;          /* Hour and minutes */
11073  int tz;            /* Timezone offset in minutes */
11074  double s;          /* Seconds */
11075  char validYMD;     /* True (1) if Y,M,D are valid */
11076  char validHMS;     /* True (1) if h,m,s are valid */
11077  char validJD;      /* True (1) if iJD is valid */
11078  char validTZ;      /* True (1) if tz is valid */
11079};
11080
11081
11082/*
11083** Convert zDate into one or more integers.  Additional arguments
11084** come in groups of 5 as follows:
11085**
11086**       N       number of digits in the integer
11087**       min     minimum allowed value of the integer
11088**       max     maximum allowed value of the integer
11089**       nextC   first character after the integer
11090**       pVal    where to write the integers value.
11091**
11092** Conversions continue until one with nextC==0 is encountered.
11093** The function returns the number of successful conversions.
11094*/
11095static int getDigits(const char *zDate, ...){
11096  va_list ap;
11097  int val;
11098  int N;
11099  int min;
11100  int max;
11101  int nextC;
11102  int *pVal;
11103  int cnt = 0;
11104  va_start(ap, zDate);
11105  do{
11106    N = va_arg(ap, int);
11107    min = va_arg(ap, int);
11108    max = va_arg(ap, int);
11109    nextC = va_arg(ap, int);
11110    pVal = va_arg(ap, int*);
11111    val = 0;
11112    while( N-- ){
11113      if( !sqlite3Isdigit(*zDate) ){
11114        goto end_getDigits;
11115      }
11116      val = val*10 + *zDate - '0';
11117      zDate++;
11118    }
11119    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
11120      goto end_getDigits;
11121    }
11122    *pVal = val;
11123    zDate++;
11124    cnt++;
11125  }while( nextC );
11126end_getDigits:
11127  va_end(ap);
11128  return cnt;
11129}
11130
11131/*
11132** Read text from z[] and convert into a floating point number.  Return
11133** the number of digits converted.
11134*/
11135#define getValue sqlite3AtoF
11136
11137/*
11138** Parse a timezone extension on the end of a date-time.
11139** The extension is of the form:
11140**
11141**        (+/-)HH:MM
11142**
11143** Or the "zulu" notation:
11144**
11145**        Z
11146**
11147** If the parse is successful, write the number of minutes
11148** of change in p->tz and return 0.  If a parser error occurs,
11149** return non-zero.
11150**
11151** A missing specifier is not considered an error.
11152*/
11153static int parseTimezone(const char *zDate, DateTime *p){
11154  int sgn = 0;
11155  int nHr, nMn;
11156  int c;
11157  while( sqlite3Isspace(*zDate) ){ zDate++; }
11158  p->tz = 0;
11159  c = *zDate;
11160  if( c=='-' ){
11161    sgn = -1;
11162  }else if( c=='+' ){
11163    sgn = +1;
11164  }else if( c=='Z' || c=='z' ){
11165    zDate++;
11166    goto zulu_time;
11167  }else{
11168    return c!=0;
11169  }
11170  zDate++;
11171  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
11172    return 1;
11173  }
11174  zDate += 5;
11175  p->tz = sgn*(nMn + nHr*60);
11176zulu_time:
11177  while( sqlite3Isspace(*zDate) ){ zDate++; }
11178  return *zDate!=0;
11179}
11180
11181/*
11182** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
11183** The HH, MM, and SS must each be exactly 2 digits.  The
11184** fractional seconds FFFF can be one or more digits.
11185**
11186** Return 1 if there is a parsing error and 0 on success.
11187*/
11188static int parseHhMmSs(const char *zDate, DateTime *p){
11189  int h, m, s;
11190  double ms = 0.0;
11191  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
11192    return 1;
11193  }
11194  zDate += 5;
11195  if( *zDate==':' ){
11196    zDate++;
11197    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
11198      return 1;
11199    }
11200    zDate += 2;
11201    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
11202      double rScale = 1.0;
11203      zDate++;
11204      while( sqlite3Isdigit(*zDate) ){
11205        ms = ms*10.0 + *zDate - '0';
11206        rScale *= 10.0;
11207        zDate++;
11208      }
11209      ms /= rScale;
11210    }
11211  }else{
11212    s = 0;
11213  }
11214  p->validJD = 0;
11215  p->validHMS = 1;
11216  p->h = h;
11217  p->m = m;
11218  p->s = s + ms;
11219  if( parseTimezone(zDate, p) ) return 1;
11220  p->validTZ = (p->tz!=0)?1:0;
11221  return 0;
11222}
11223
11224/*
11225** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
11226** that the YYYY-MM-DD is according to the Gregorian calendar.
11227**
11228** Reference:  Meeus page 61
11229*/
11230static void computeJD(DateTime *p){
11231  int Y, M, D, A, B, X1, X2;
11232
11233  if( p->validJD ) return;
11234  if( p->validYMD ){
11235    Y = p->Y;
11236    M = p->M;
11237    D = p->D;
11238  }else{
11239    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
11240    M = 1;
11241    D = 1;
11242  }
11243  if( M<=2 ){
11244    Y--;
11245    M += 12;
11246  }
11247  A = Y/100;
11248  B = 2 - A + (A/4);
11249  X1 = 36525*(Y+4716)/100;
11250  X2 = 306001*(M+1)/10000;
11251  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
11252  p->validJD = 1;
11253  if( p->validHMS ){
11254    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
11255    if( p->validTZ ){
11256      p->iJD -= p->tz*60000;
11257      p->validYMD = 0;
11258      p->validHMS = 0;
11259      p->validTZ = 0;
11260    }
11261  }
11262}
11263
11264/*
11265** Parse dates of the form
11266**
11267**     YYYY-MM-DD HH:MM:SS.FFF
11268**     YYYY-MM-DD HH:MM:SS
11269**     YYYY-MM-DD HH:MM
11270**     YYYY-MM-DD
11271**
11272** Write the result into the DateTime structure and return 0
11273** on success and 1 if the input string is not a well-formed
11274** date.
11275*/
11276static int parseYyyyMmDd(const char *zDate, DateTime *p){
11277  int Y, M, D, neg;
11278
11279  if( zDate[0]=='-' ){
11280    zDate++;
11281    neg = 1;
11282  }else{
11283    neg = 0;
11284  }
11285  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
11286    return 1;
11287  }
11288  zDate += 10;
11289  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
11290  if( parseHhMmSs(zDate, p)==0 ){
11291    /* We got the time */
11292  }else if( *zDate==0 ){
11293    p->validHMS = 0;
11294  }else{
11295    return 1;
11296  }
11297  p->validJD = 0;
11298  p->validYMD = 1;
11299  p->Y = neg ? -Y : Y;
11300  p->M = M;
11301  p->D = D;
11302  if( p->validTZ ){
11303    computeJD(p);
11304  }
11305  return 0;
11306}
11307
11308/*
11309** Set the time to the current time reported by the VFS
11310*/
11311static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
11312  double r;
11313  sqlite3 *db = sqlite3_context_db_handle(context);
11314  sqlite3OsCurrentTime(db->pVfs, &r);
11315  p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11316  p->validJD = 1;
11317}
11318
11319/*
11320** Attempt to parse the given string into a Julian Day Number.  Return
11321** the number of errors.
11322**
11323** The following are acceptable forms for the input string:
11324**
11325**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
11326**      DDDD.DD
11327**      now
11328**
11329** In the first form, the +/-HH:MM is always optional.  The fractional
11330** seconds extension (the ".FFF") is optional.  The seconds portion
11331** (":SS.FFF") is option.  The year and date can be omitted as long
11332** as there is a time string.  The time string can be omitted as long
11333** as there is a year and date.
11334*/
11335static int parseDateOrTime(
11336  sqlite3_context *context,
11337  const char *zDate,
11338  DateTime *p
11339){
11340  int isRealNum;    /* Return from sqlite3IsNumber().  Not used */
11341  if( parseYyyyMmDd(zDate,p)==0 ){
11342    return 0;
11343  }else if( parseHhMmSs(zDate, p)==0 ){
11344    return 0;
11345  }else if( sqlite3StrICmp(zDate,"now")==0){
11346    setDateTimeToCurrent(context, p);
11347    return 0;
11348  }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
11349    double r;
11350    getValue(zDate, &r);
11351    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11352    p->validJD = 1;
11353    return 0;
11354  }
11355  return 1;
11356}
11357
11358/*
11359** Compute the Year, Month, and Day from the julian day number.
11360*/
11361static void computeYMD(DateTime *p){
11362  int Z, A, B, C, D, E, X1;
11363  if( p->validYMD ) return;
11364  if( !p->validJD ){
11365    p->Y = 2000;
11366    p->M = 1;
11367    p->D = 1;
11368  }else{
11369    Z = (int)((p->iJD + 43200000)/86400000);
11370    A = (int)((Z - 1867216.25)/36524.25);
11371    A = Z + 1 + A - (A/4);
11372    B = A + 1524;
11373    C = (int)((B - 122.1)/365.25);
11374    D = (36525*C)/100;
11375    E = (int)((B-D)/30.6001);
11376    X1 = (int)(30.6001*E);
11377    p->D = B - D - X1;
11378    p->M = E<14 ? E-1 : E-13;
11379    p->Y = p->M>2 ? C - 4716 : C - 4715;
11380  }
11381  p->validYMD = 1;
11382}
11383
11384/*
11385** Compute the Hour, Minute, and Seconds from the julian day number.
11386*/
11387static void computeHMS(DateTime *p){
11388  int s;
11389  if( p->validHMS ) return;
11390  computeJD(p);
11391  s = (int)((p->iJD + 43200000) % 86400000);
11392  p->s = s/1000.0;
11393  s = (int)p->s;
11394  p->s -= s;
11395  p->h = s/3600;
11396  s -= p->h*3600;
11397  p->m = s/60;
11398  p->s += s - p->m*60;
11399  p->validHMS = 1;
11400}
11401
11402/*
11403** Compute both YMD and HMS
11404*/
11405static void computeYMD_HMS(DateTime *p){
11406  computeYMD(p);
11407  computeHMS(p);
11408}
11409
11410/*
11411** Clear the YMD and HMS and the TZ
11412*/
11413static void clearYMD_HMS_TZ(DateTime *p){
11414  p->validYMD = 0;
11415  p->validHMS = 0;
11416  p->validTZ = 0;
11417}
11418
11419#ifndef SQLITE_OMIT_LOCALTIME
11420/*
11421** Compute the difference (in milliseconds)
11422** between localtime and UTC (a.k.a. GMT)
11423** for the time value p where p is in UTC.
11424*/
11425static sqlite3_int64 localtimeOffset(DateTime *p){
11426  DateTime x, y;
11427  time_t t;
11428  x = *p;
11429  computeYMD_HMS(&x);
11430  if( x.Y<1971 || x.Y>=2038 ){
11431    x.Y = 2000;
11432    x.M = 1;
11433    x.D = 1;
11434    x.h = 0;
11435    x.m = 0;
11436    x.s = 0.0;
11437  } else {
11438    int s = (int)(x.s + 0.5);
11439    x.s = s;
11440  }
11441  x.tz = 0;
11442  x.validJD = 0;
11443  computeJD(&x);
11444  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
11445#ifdef HAVE_LOCALTIME_R
11446  {
11447    struct tm sLocal;
11448    localtime_r(&t, &sLocal);
11449    y.Y = sLocal.tm_year + 1900;
11450    y.M = sLocal.tm_mon + 1;
11451    y.D = sLocal.tm_mday;
11452    y.h = sLocal.tm_hour;
11453    y.m = sLocal.tm_min;
11454    y.s = sLocal.tm_sec;
11455  }
11456#elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
11457  {
11458    struct tm sLocal;
11459    localtime_s(&sLocal, &t);
11460    y.Y = sLocal.tm_year + 1900;
11461    y.M = sLocal.tm_mon + 1;
11462    y.D = sLocal.tm_mday;
11463    y.h = sLocal.tm_hour;
11464    y.m = sLocal.tm_min;
11465    y.s = sLocal.tm_sec;
11466  }
11467#else
11468  {
11469    struct tm *pTm;
11470    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11471    pTm = localtime(&t);
11472    y.Y = pTm->tm_year + 1900;
11473    y.M = pTm->tm_mon + 1;
11474    y.D = pTm->tm_mday;
11475    y.h = pTm->tm_hour;
11476    y.m = pTm->tm_min;
11477    y.s = pTm->tm_sec;
11478    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11479  }
11480#endif
11481  y.validYMD = 1;
11482  y.validHMS = 1;
11483  y.validJD = 0;
11484  y.validTZ = 0;
11485  computeJD(&y);
11486  return y.iJD - x.iJD;
11487}
11488#endif /* SQLITE_OMIT_LOCALTIME */
11489
11490/*
11491** Process a modifier to a date-time stamp.  The modifiers are
11492** as follows:
11493**
11494**     NNN days
11495**     NNN hours
11496**     NNN minutes
11497**     NNN.NNNN seconds
11498**     NNN months
11499**     NNN years
11500**     start of month
11501**     start of year
11502**     start of week
11503**     start of day
11504**     weekday N
11505**     unixepoch
11506**     localtime
11507**     utc
11508**
11509** Return 0 on success and 1 if there is any kind of error.
11510*/
11511static int parseModifier(const char *zMod, DateTime *p){
11512  int rc = 1;
11513  int n;
11514  double r;
11515  char *z, zBuf[30];
11516  z = zBuf;
11517  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
11518    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
11519  }
11520  z[n] = 0;
11521  switch( z[0] ){
11522#ifndef SQLITE_OMIT_LOCALTIME
11523    case 'l': {
11524      /*    localtime
11525      **
11526      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
11527      ** show local time.
11528      */
11529      if( strcmp(z, "localtime")==0 ){
11530        computeJD(p);
11531        p->iJD += localtimeOffset(p);
11532        clearYMD_HMS_TZ(p);
11533        rc = 0;
11534      }
11535      break;
11536    }
11537#endif
11538    case 'u': {
11539      /*
11540      **    unixepoch
11541      **
11542      ** Treat the current value of p->iJD as the number of
11543      ** seconds since 1970.  Convert to a real julian day number.
11544      */
11545      if( strcmp(z, "unixepoch")==0 && p->validJD ){
11546        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
11547        clearYMD_HMS_TZ(p);
11548        rc = 0;
11549      }
11550#ifndef SQLITE_OMIT_LOCALTIME
11551      else if( strcmp(z, "utc")==0 ){
11552        sqlite3_int64 c1;
11553        computeJD(p);
11554        c1 = localtimeOffset(p);
11555        p->iJD -= c1;
11556        clearYMD_HMS_TZ(p);
11557        p->iJD += c1 - localtimeOffset(p);
11558        rc = 0;
11559      }
11560#endif
11561      break;
11562    }
11563    case 'w': {
11564      /*
11565      **    weekday N
11566      **
11567      ** Move the date to the same time on the next occurrence of
11568      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
11569      ** date is already on the appropriate weekday, this is a no-op.
11570      */
11571      if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
11572                 && (n=(int)r)==r && n>=0 && r<7 ){
11573        sqlite3_int64 Z;
11574        computeYMD_HMS(p);
11575        p->validTZ = 0;
11576        p->validJD = 0;
11577        computeJD(p);
11578        Z = ((p->iJD + 129600000)/86400000) % 7;
11579        if( Z>n ) Z -= 7;
11580        p->iJD += (n - Z)*86400000;
11581        clearYMD_HMS_TZ(p);
11582        rc = 0;
11583      }
11584      break;
11585    }
11586    case 's': {
11587      /*
11588      **    start of TTTTT
11589      **
11590      ** Move the date backwards to the beginning of the current day,
11591      ** or month or year.
11592      */
11593      if( strncmp(z, "start of ", 9)!=0 ) break;
11594      z += 9;
11595      computeYMD(p);
11596      p->validHMS = 1;
11597      p->h = p->m = 0;
11598      p->s = 0.0;
11599      p->validTZ = 0;
11600      p->validJD = 0;
11601      if( strcmp(z,"month")==0 ){
11602        p->D = 1;
11603        rc = 0;
11604      }else if( strcmp(z,"year")==0 ){
11605        computeYMD(p);
11606        p->M = 1;
11607        p->D = 1;
11608        rc = 0;
11609      }else if( strcmp(z,"day")==0 ){
11610        rc = 0;
11611      }
11612      break;
11613    }
11614    case '+':
11615    case '-':
11616    case '0':
11617    case '1':
11618    case '2':
11619    case '3':
11620    case '4':
11621    case '5':
11622    case '6':
11623    case '7':
11624    case '8':
11625    case '9': {
11626      double rRounder;
11627      n = getValue(z, &r);
11628      assert( n>=1 );
11629      if( z[n]==':' ){
11630        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
11631        ** specified number of hours, minutes, seconds, and fractional seconds
11632        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
11633        ** omitted.
11634        */
11635        const char *z2 = z;
11636        DateTime tx;
11637        sqlite3_int64 day;
11638        if( !sqlite3Isdigit(*z2) ) z2++;
11639        memset(&tx, 0, sizeof(tx));
11640        if( parseHhMmSs(z2, &tx) ) break;
11641        computeJD(&tx);
11642        tx.iJD -= 43200000;
11643        day = tx.iJD/86400000;
11644        tx.iJD -= day*86400000;
11645        if( z[0]=='-' ) tx.iJD = -tx.iJD;
11646        computeJD(p);
11647        clearYMD_HMS_TZ(p);
11648        p->iJD += tx.iJD;
11649        rc = 0;
11650        break;
11651      }
11652      z += n;
11653      while( sqlite3Isspace(*z) ) z++;
11654      n = sqlite3Strlen30(z);
11655      if( n>10 || n<3 ) break;
11656      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
11657      computeJD(p);
11658      rc = 0;
11659      rRounder = r<0 ? -0.5 : +0.5;
11660      if( n==3 && strcmp(z,"day")==0 ){
11661        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
11662      }else if( n==4 && strcmp(z,"hour")==0 ){
11663        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
11664      }else if( n==6 && strcmp(z,"minute")==0 ){
11665        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
11666      }else if( n==6 && strcmp(z,"second")==0 ){
11667        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
11668      }else if( n==5 && strcmp(z,"month")==0 ){
11669        int x, y;
11670        computeYMD_HMS(p);
11671        p->M += (int)r;
11672        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
11673        p->Y += x;
11674        p->M -= x*12;
11675        p->validJD = 0;
11676        computeJD(p);
11677        y = (int)r;
11678        if( y!=r ){
11679          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
11680        }
11681      }else if( n==4 && strcmp(z,"year")==0 ){
11682        int y = (int)r;
11683        computeYMD_HMS(p);
11684        p->Y += y;
11685        p->validJD = 0;
11686        computeJD(p);
11687        if( y!=r ){
11688          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
11689        }
11690      }else{
11691        rc = 1;
11692      }
11693      clearYMD_HMS_TZ(p);
11694      break;
11695    }
11696    default: {
11697      break;
11698    }
11699  }
11700  return rc;
11701}
11702
11703/*
11704** Process time function arguments.  argv[0] is a date-time stamp.
11705** argv[1] and following are modifiers.  Parse them all and write
11706** the resulting time into the DateTime structure p.  Return 0
11707** on success and 1 if there are any errors.
11708**
11709** If there are zero parameters (if even argv[0] is undefined)
11710** then assume a default value of "now" for argv[0].
11711*/
11712static int isDate(
11713  sqlite3_context *context,
11714  int argc,
11715  sqlite3_value **argv,
11716  DateTime *p
11717){
11718  int i;
11719  const unsigned char *z;
11720  int eType;
11721  memset(p, 0, sizeof(*p));
11722  if( argc==0 ){
11723    setDateTimeToCurrent(context, p);
11724  }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
11725                   || eType==SQLITE_INTEGER ){
11726    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
11727    p->validJD = 1;
11728  }else{
11729    z = sqlite3_value_text(argv[0]);
11730    if( !z || parseDateOrTime(context, (char*)z, p) ){
11731      return 1;
11732    }
11733  }
11734  for(i=1; i<argc; i++){
11735    if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
11736      return 1;
11737    }
11738  }
11739  return 0;
11740}
11741
11742
11743/*
11744** The following routines implement the various date and time functions
11745** of SQLite.
11746*/
11747
11748/*
11749**    julianday( TIMESTRING, MOD, MOD, ...)
11750**
11751** Return the julian day number of the date specified in the arguments
11752*/
11753static void juliandayFunc(
11754  sqlite3_context *context,
11755  int argc,
11756  sqlite3_value **argv
11757){
11758  DateTime x;
11759  if( isDate(context, argc, argv, &x)==0 ){
11760    computeJD(&x);
11761    sqlite3_result_double(context, x.iJD/86400000.0);
11762  }
11763}
11764
11765/*
11766**    datetime( TIMESTRING, MOD, MOD, ...)
11767**
11768** Return YYYY-MM-DD HH:MM:SS
11769*/
11770static void datetimeFunc(
11771  sqlite3_context *context,
11772  int argc,
11773  sqlite3_value **argv
11774){
11775  DateTime x;
11776  if( isDate(context, argc, argv, &x)==0 ){
11777    char zBuf[100];
11778    computeYMD_HMS(&x);
11779    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
11780                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
11781    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11782  }
11783}
11784
11785/*
11786**    time( TIMESTRING, MOD, MOD, ...)
11787**
11788** Return HH:MM:SS
11789*/
11790static void timeFunc(
11791  sqlite3_context *context,
11792  int argc,
11793  sqlite3_value **argv
11794){
11795  DateTime x;
11796  if( isDate(context, argc, argv, &x)==0 ){
11797    char zBuf[100];
11798    computeHMS(&x);
11799    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
11800    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11801  }
11802}
11803
11804/*
11805**    date( TIMESTRING, MOD, MOD, ...)
11806**
11807** Return YYYY-MM-DD
11808*/
11809static void dateFunc(
11810  sqlite3_context *context,
11811  int argc,
11812  sqlite3_value **argv
11813){
11814  DateTime x;
11815  if( isDate(context, argc, argv, &x)==0 ){
11816    char zBuf[100];
11817    computeYMD(&x);
11818    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
11819    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11820  }
11821}
11822
11823/*
11824**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
11825**
11826** Return a string described by FORMAT.  Conversions as follows:
11827**
11828**   %d  day of month
11829**   %f  ** fractional seconds  SS.SSS
11830**   %H  hour 00-24
11831**   %j  day of year 000-366
11832**   %J  ** Julian day number
11833**   %m  month 01-12
11834**   %M  minute 00-59
11835**   %s  seconds since 1970-01-01
11836**   %S  seconds 00-59
11837**   %w  day of week 0-6  sunday==0
11838**   %W  week of year 00-53
11839**   %Y  year 0000-9999
11840**   %%  %
11841*/
11842static void strftimeFunc(
11843  sqlite3_context *context,
11844  int argc,
11845  sqlite3_value **argv
11846){
11847  DateTime x;
11848  u64 n;
11849  size_t i,j;
11850  char *z;
11851  sqlite3 *db;
11852  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
11853  char zBuf[100];
11854  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
11855  db = sqlite3_context_db_handle(context);
11856  for(i=0, n=1; zFmt[i]; i++, n++){
11857    if( zFmt[i]=='%' ){
11858      switch( zFmt[i+1] ){
11859        case 'd':
11860        case 'H':
11861        case 'm':
11862        case 'M':
11863        case 'S':
11864        case 'W':
11865          n++;
11866          /* fall thru */
11867        case 'w':
11868        case '%':
11869          break;
11870        case 'f':
11871          n += 8;
11872          break;
11873        case 'j':
11874          n += 3;
11875          break;
11876        case 'Y':
11877          n += 8;
11878          break;
11879        case 's':
11880        case 'J':
11881          n += 50;
11882          break;
11883        default:
11884          return;  /* ERROR.  return a NULL */
11885      }
11886      i++;
11887    }
11888  }
11889  testcase( n==sizeof(zBuf)-1 );
11890  testcase( n==sizeof(zBuf) );
11891  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
11892  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
11893  if( n<sizeof(zBuf) ){
11894    z = zBuf;
11895  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
11896    sqlite3_result_error_toobig(context);
11897    return;
11898  }else{
11899    z = sqlite3DbMallocRaw(db, (int)n);
11900    if( z==0 ){
11901      sqlite3_result_error_nomem(context);
11902      return;
11903    }
11904  }
11905  computeJD(&x);
11906  computeYMD_HMS(&x);
11907  for(i=j=0; zFmt[i]; i++){
11908    if( zFmt[i]!='%' ){
11909      z[j++] = zFmt[i];
11910    }else{
11911      i++;
11912      switch( zFmt[i] ){
11913        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
11914        case 'f': {
11915          double s = x.s;
11916          if( s>59.999 ) s = 59.999;
11917          sqlite3_snprintf(7, &z[j],"%06.3f", s);
11918          j += sqlite3Strlen30(&z[j]);
11919          break;
11920        }
11921        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
11922        case 'W': /* Fall thru */
11923        case 'j': {
11924          int nDay;             /* Number of days since 1st day of year */
11925          DateTime y = x;
11926          y.validJD = 0;
11927          y.M = 1;
11928          y.D = 1;
11929          computeJD(&y);
11930          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
11931          if( zFmt[i]=='W' ){
11932            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
11933            wd = (int)(((x.iJD+43200000)/86400000)%7);
11934            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
11935            j += 2;
11936          }else{
11937            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
11938            j += 3;
11939          }
11940          break;
11941        }
11942        case 'J': {
11943          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
11944          j+=sqlite3Strlen30(&z[j]);
11945          break;
11946        }
11947        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
11948        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
11949        case 's': {
11950          sqlite3_snprintf(30,&z[j],"%lld",
11951                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
11952          j += sqlite3Strlen30(&z[j]);
11953          break;
11954        }
11955        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
11956        case 'w': {
11957          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
11958          break;
11959        }
11960        case 'Y': {
11961          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
11962          break;
11963        }
11964        default:   z[j++] = '%'; break;
11965      }
11966    }
11967  }
11968  z[j] = 0;
11969  sqlite3_result_text(context, z, -1,
11970                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
11971}
11972
11973/*
11974** current_time()
11975**
11976** This function returns the same value as time('now').
11977*/
11978static void ctimeFunc(
11979  sqlite3_context *context,
11980  int NotUsed,
11981  sqlite3_value **NotUsed2
11982){
11983  UNUSED_PARAMETER2(NotUsed, NotUsed2);
11984  timeFunc(context, 0, 0);
11985}
11986
11987/*
11988** current_date()
11989**
11990** This function returns the same value as date('now').
11991*/
11992static void cdateFunc(
11993  sqlite3_context *context,
11994  int NotUsed,
11995  sqlite3_value **NotUsed2
11996){
11997  UNUSED_PARAMETER2(NotUsed, NotUsed2);
11998  dateFunc(context, 0, 0);
11999}
12000
12001/*
12002** current_timestamp()
12003**
12004** This function returns the same value as datetime('now').
12005*/
12006static void ctimestampFunc(
12007  sqlite3_context *context,
12008  int NotUsed,
12009  sqlite3_value **NotUsed2
12010){
12011  UNUSED_PARAMETER2(NotUsed, NotUsed2);
12012  datetimeFunc(context, 0, 0);
12013}
12014#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
12015
12016#ifdef SQLITE_OMIT_DATETIME_FUNCS
12017/*
12018** If the library is compiled to omit the full-scale date and time
12019** handling (to get a smaller binary), the following minimal version
12020** of the functions current_time(), current_date() and current_timestamp()
12021** are included instead. This is to support column declarations that
12022** include "DEFAULT CURRENT_TIME" etc.
12023**
12024** This function uses the C-library functions time(), gmtime()
12025** and strftime(). The format string to pass to strftime() is supplied
12026** as the user-data for the function.
12027*/
12028static void currentTimeFunc(
12029  sqlite3_context *context,
12030  int argc,
12031  sqlite3_value **argv
12032){
12033  time_t t;
12034  char *zFormat = (char *)sqlite3_user_data(context);
12035  sqlite3 *db;
12036  double rT;
12037  char zBuf[20];
12038
12039  UNUSED_PARAMETER(argc);
12040  UNUSED_PARAMETER(argv);
12041
12042  db = sqlite3_context_db_handle(context);
12043  sqlite3OsCurrentTime(db->pVfs, &rT);
12044#ifndef SQLITE_OMIT_FLOATING_POINT
12045  t = 86400.0*(rT - 2440587.5) + 0.5;
12046#else
12047  /* without floating point support, rT will have
12048  ** already lost fractional day precision.
12049  */
12050  t = 86400 * (rT - 2440587) - 43200;
12051#endif
12052#ifdef HAVE_GMTIME_R
12053  {
12054    struct tm sNow;
12055    gmtime_r(&t, &sNow);
12056    strftime(zBuf, 20, zFormat, &sNow);
12057  }
12058#else
12059  {
12060    struct tm *pTm;
12061    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12062    pTm = gmtime(&t);
12063    strftime(zBuf, 20, zFormat, pTm);
12064    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12065  }
12066#endif
12067
12068  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12069}
12070#endif
12071
12072/*
12073** This function registered all of the above C functions as SQL
12074** functions.  This should be the only routine in this file with
12075** external linkage.
12076*/
12077SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
12078  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
12079#ifndef SQLITE_OMIT_DATETIME_FUNCS
12080    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
12081    FUNCTION(date,             -1, 0, 0, dateFunc      ),
12082    FUNCTION(time,             -1, 0, 0, timeFunc      ),
12083    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
12084    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
12085    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
12086    FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
12087    FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
12088#else
12089    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
12090    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d",          0, currentTimeFunc),
12091    STR_FUNCTION(current_date,      0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
12092#endif
12093  };
12094  int i;
12095  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
12096  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
12097
12098  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
12099    sqlite3FuncDefInsert(pHash, &aFunc[i]);
12100  }
12101}
12102
12103/************** End of date.c ************************************************/
12104/************** Begin file os.c **********************************************/
12105/*
12106** 2005 November 29
12107**
12108** The author disclaims copyright to this source code.  In place of
12109** a legal notice, here is a blessing:
12110**
12111**    May you do good and not evil.
12112**    May you find forgiveness for yourself and forgive others.
12113**    May you share freely, never taking more than you give.
12114**
12115******************************************************************************
12116**
12117** This file contains OS interface code that is common to all
12118** architectures.
12119*/
12120#define _SQLITE_OS_C_ 1
12121#undef _SQLITE_OS_C_
12122
12123/*
12124** The default SQLite sqlite3_vfs implementations do not allocate
12125** memory (actually, os_unix.c allocates a small amount of memory
12126** from within OsOpen()), but some third-party implementations may.
12127** So we test the effects of a malloc() failing and the sqlite3OsXXX()
12128** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
12129**
12130** The following functions are instrumented for malloc() failure
12131** testing:
12132**
12133**     sqlite3OsOpen()
12134**     sqlite3OsRead()
12135**     sqlite3OsWrite()
12136**     sqlite3OsSync()
12137**     sqlite3OsLock()
12138**
12139*/
12140#if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0)
12141  #define DO_OS_MALLOC_TEST(x) if (!x || !sqlite3IsMemJournal(x)) {     \
12142    void *pTstAlloc = sqlite3Malloc(10);                             \
12143    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
12144    sqlite3_free(pTstAlloc);                                         \
12145  }
12146#else
12147  #define DO_OS_MALLOC_TEST(x)
12148#endif
12149
12150/*
12151** The following routines are convenience wrappers around methods
12152** of the sqlite3_file object.  This is mostly just syntactic sugar. All
12153** of this would be completely automatic if SQLite were coded using
12154** C++ instead of plain old C.
12155*/
12156SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
12157  int rc = SQLITE_OK;
12158  if( pId->pMethods ){
12159    rc = pId->pMethods->xClose(pId);
12160    pId->pMethods = 0;
12161  }
12162  return rc;
12163}
12164SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
12165  DO_OS_MALLOC_TEST(id);
12166  return id->pMethods->xRead(id, pBuf, amt, offset);
12167}
12168SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
12169  DO_OS_MALLOC_TEST(id);
12170  return id->pMethods->xWrite(id, pBuf, amt, offset);
12171}
12172SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
12173  return id->pMethods->xTruncate(id, size);
12174}
12175SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
12176  DO_OS_MALLOC_TEST(id);
12177  return id->pMethods->xSync(id, flags);
12178}
12179SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
12180  DO_OS_MALLOC_TEST(id);
12181  return id->pMethods->xFileSize(id, pSize);
12182}
12183SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
12184  DO_OS_MALLOC_TEST(id);
12185  return id->pMethods->xLock(id, lockType);
12186}
12187SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
12188  return id->pMethods->xUnlock(id, lockType);
12189}
12190SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
12191  DO_OS_MALLOC_TEST(id);
12192  return id->pMethods->xCheckReservedLock(id, pResOut);
12193}
12194SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
12195  return id->pMethods->xFileControl(id, op, pArg);
12196}
12197SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
12198  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
12199  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
12200}
12201SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
12202  return id->pMethods->xDeviceCharacteristics(id);
12203}
12204
12205/*
12206** The next group of routines are convenience wrappers around the
12207** VFS methods.
12208*/
12209SQLITE_PRIVATE int sqlite3OsOpen(
12210  sqlite3_vfs *pVfs,
12211  const char *zPath,
12212  sqlite3_file *pFile,
12213  int flags,
12214  int *pFlagsOut
12215){
12216  int rc;
12217  DO_OS_MALLOC_TEST(0);
12218  /* 0x7f1f is a mask of SQLITE_OPEN_ flags that are valid to be passed
12219  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
12220  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
12221  ** reaching the VFS. */
12222  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x7f1f, pFlagsOut);
12223  assert( rc==SQLITE_OK || pFile->pMethods==0 );
12224  return rc;
12225}
12226SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
12227  return pVfs->xDelete(pVfs, zPath, dirSync);
12228}
12229SQLITE_PRIVATE int sqlite3OsAccess(
12230  sqlite3_vfs *pVfs,
12231  const char *zPath,
12232  int flags,
12233  int *pResOut
12234){
12235  DO_OS_MALLOC_TEST(0);
12236  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
12237}
12238SQLITE_PRIVATE int sqlite3OsFullPathname(
12239  sqlite3_vfs *pVfs,
12240  const char *zPath,
12241  int nPathOut,
12242  char *zPathOut
12243){
12244  zPathOut[0] = 0;
12245  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
12246}
12247#ifndef SQLITE_OMIT_LOAD_EXTENSION
12248SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
12249  return pVfs->xDlOpen(pVfs, zPath);
12250}
12251SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12252  pVfs->xDlError(pVfs, nByte, zBufOut);
12253}
12254SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
12255  return pVfs->xDlSym(pVfs, pHdle, zSym);
12256}
12257SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
12258  pVfs->xDlClose(pVfs, pHandle);
12259}
12260#endif /* SQLITE_OMIT_LOAD_EXTENSION */
12261SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12262  return pVfs->xRandomness(pVfs, nByte, zBufOut);
12263}
12264SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
12265  return pVfs->xSleep(pVfs, nMicro);
12266}
12267SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
12268  return pVfs->xCurrentTime(pVfs, pTimeOut);
12269}
12270
12271SQLITE_PRIVATE int sqlite3OsOpenMalloc(
12272  sqlite3_vfs *pVfs,
12273  const char *zFile,
12274  sqlite3_file **ppFile,
12275  int flags,
12276  int *pOutFlags
12277){
12278  int rc = SQLITE_NOMEM;
12279  sqlite3_file *pFile;
12280  pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
12281  if( pFile ){
12282    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
12283    if( rc!=SQLITE_OK ){
12284      sqlite3_free(pFile);
12285    }else{
12286      *ppFile = pFile;
12287    }
12288  }
12289  return rc;
12290}
12291SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
12292  int rc = SQLITE_OK;
12293  assert( pFile );
12294  rc = sqlite3OsClose(pFile);
12295  sqlite3_free(pFile);
12296  return rc;
12297}
12298
12299/*
12300** This function is a wrapper around the OS specific implementation of
12301** sqlite3_os_init(). The purpose of the wrapper is to provide the
12302** ability to simulate a malloc failure, so that the handling of an
12303** error in sqlite3_os_init() by the upper layers can be tested.
12304*/
12305SQLITE_PRIVATE int sqlite3OsInit(void){
12306  void *p = sqlite3_malloc(10);
12307  if( p==0 ) return SQLITE_NOMEM;
12308  sqlite3_free(p);
12309  return sqlite3_os_init();
12310}
12311
12312/*
12313** The list of all registered VFS implementations.
12314*/
12315static sqlite3_vfs * SQLITE_WSD vfsList = 0;
12316#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
12317
12318/*
12319** Locate a VFS by name.  If no name is given, simply return the
12320** first VFS on the list.
12321*/
12322SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
12323  sqlite3_vfs *pVfs = 0;
12324#if SQLITE_THREADSAFE
12325  sqlite3_mutex *mutex;
12326#endif
12327#ifndef SQLITE_OMIT_AUTOINIT
12328  int rc = sqlite3_initialize();
12329  if( rc ) return 0;
12330#endif
12331#if SQLITE_THREADSAFE
12332  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12333#endif
12334  sqlite3_mutex_enter(mutex);
12335  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
12336    if( zVfs==0 ) break;
12337    if( strcmp(zVfs, pVfs->zName)==0 ) break;
12338  }
12339  sqlite3_mutex_leave(mutex);
12340  return pVfs;
12341}
12342
12343/*
12344** Unlink a VFS from the linked list
12345*/
12346static void vfsUnlink(sqlite3_vfs *pVfs){
12347  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
12348  if( pVfs==0 ){
12349    /* No-op */
12350  }else if( vfsList==pVfs ){
12351    vfsList = pVfs->pNext;
12352  }else if( vfsList ){
12353    sqlite3_vfs *p = vfsList;
12354    while( p->pNext && p->pNext!=pVfs ){
12355      p = p->pNext;
12356    }
12357    if( p->pNext==pVfs ){
12358      p->pNext = pVfs->pNext;
12359    }
12360  }
12361}
12362
12363/*
12364** Register a VFS with the system.  It is harmless to register the same
12365** VFS multiple times.  The new VFS becomes the default if makeDflt is
12366** true.
12367*/
12368SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
12369  sqlite3_mutex *mutex = 0;
12370#ifndef SQLITE_OMIT_AUTOINIT
12371  int rc = sqlite3_initialize();
12372  if( rc ) return rc;
12373#endif
12374  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12375  sqlite3_mutex_enter(mutex);
12376  vfsUnlink(pVfs);
12377  if( makeDflt || vfsList==0 ){
12378    pVfs->pNext = vfsList;
12379    vfsList = pVfs;
12380  }else{
12381    pVfs->pNext = vfsList->pNext;
12382    vfsList->pNext = pVfs;
12383  }
12384  assert(vfsList);
12385  sqlite3_mutex_leave(mutex);
12386  return SQLITE_OK;
12387}
12388
12389/*
12390** Unregister a VFS so that it is no longer accessible.
12391*/
12392SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
12393#if SQLITE_THREADSAFE
12394  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12395#endif
12396  sqlite3_mutex_enter(mutex);
12397  vfsUnlink(pVfs);
12398  sqlite3_mutex_leave(mutex);
12399  return SQLITE_OK;
12400}
12401
12402/************** End of os.c **************************************************/
12403/************** Begin file fault.c *******************************************/
12404/*
12405** 2008 Jan 22
12406**
12407** The author disclaims copyright to this source code.  In place of
12408** a legal notice, here is a blessing:
12409**
12410**    May you do good and not evil.
12411**    May you find forgiveness for yourself and forgive others.
12412**    May you share freely, never taking more than you give.
12413**
12414*************************************************************************
12415**
12416** This file contains code to support the concept of "benign"
12417** malloc failures (when the xMalloc() or xRealloc() method of the
12418** sqlite3_mem_methods structure fails to allocate a block of memory
12419** and returns 0).
12420**
12421** Most malloc failures are non-benign. After they occur, SQLite
12422** abandons the current operation and returns an error code (usually
12423** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
12424** fatal. For example, if a malloc fails while resizing a hash table, this
12425** is completely recoverable simply by not carrying out the resize. The
12426** hash table will continue to function normally.  So a malloc failure
12427** during a hash table resize is a benign fault.
12428*/
12429
12430
12431#ifndef SQLITE_OMIT_BUILTIN_TEST
12432
12433/*
12434** Global variables.
12435*/
12436typedef struct BenignMallocHooks BenignMallocHooks;
12437static SQLITE_WSD struct BenignMallocHooks {
12438  void (*xBenignBegin)(void);
12439  void (*xBenignEnd)(void);
12440} sqlite3Hooks = { 0, 0 };
12441
12442/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
12443** structure.  If writable static data is unsupported on the target,
12444** we have to locate the state vector at run-time.  In the more common
12445** case where writable static data is supported, wsdHooks can refer directly
12446** to the "sqlite3Hooks" state vector declared above.
12447*/
12448#ifdef SQLITE_OMIT_WSD
12449# define wsdHooksInit \
12450  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
12451# define wsdHooks x[0]
12452#else
12453# define wsdHooksInit
12454# define wsdHooks sqlite3Hooks
12455#endif
12456
12457
12458/*
12459** Register hooks to call when sqlite3BeginBenignMalloc() and
12460** sqlite3EndBenignMalloc() are called, respectively.
12461*/
12462SQLITE_PRIVATE void sqlite3BenignMallocHooks(
12463  void (*xBenignBegin)(void),
12464  void (*xBenignEnd)(void)
12465){
12466  wsdHooksInit;
12467  wsdHooks.xBenignBegin = xBenignBegin;
12468  wsdHooks.xBenignEnd = xBenignEnd;
12469}
12470
12471/*
12472** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
12473** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
12474** indicates that subsequent malloc failures are non-benign.
12475*/
12476SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
12477  wsdHooksInit;
12478  if( wsdHooks.xBenignBegin ){
12479    wsdHooks.xBenignBegin();
12480  }
12481}
12482SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
12483  wsdHooksInit;
12484  if( wsdHooks.xBenignEnd ){
12485    wsdHooks.xBenignEnd();
12486  }
12487}
12488
12489#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
12490
12491/************** End of fault.c ***********************************************/
12492/************** Begin file mem0.c ********************************************/
12493/*
12494** 2008 October 28
12495**
12496** The author disclaims copyright to this source code.  In place of
12497** a legal notice, here is a blessing:
12498**
12499**    May you do good and not evil.
12500**    May you find forgiveness for yourself and forgive others.
12501**    May you share freely, never taking more than you give.
12502**
12503*************************************************************************
12504**
12505** This file contains a no-op memory allocation drivers for use when
12506** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
12507** here always fail.  SQLite will not operate with these drivers.  These
12508** are merely placeholders.  Real drivers must be substituted using
12509** sqlite3_config() before SQLite will operate.
12510*/
12511
12512/*
12513** This version of the memory allocator is the default.  It is
12514** used when no other memory allocator is specified using compile-time
12515** macros.
12516*/
12517#ifdef SQLITE_ZERO_MALLOC
12518
12519/*
12520** No-op versions of all memory allocation routines
12521*/
12522static void *sqlite3MemMalloc(int nByte){ return 0; }
12523static void sqlite3MemFree(void *pPrior){ return; }
12524static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
12525static int sqlite3MemSize(void *pPrior){ return 0; }
12526static int sqlite3MemRoundup(int n){ return n; }
12527static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
12528static void sqlite3MemShutdown(void *NotUsed){ return; }
12529
12530/*
12531** This routine is the only routine in this file with external linkage.
12532**
12533** Populate the low-level memory allocation function pointers in
12534** sqlite3GlobalConfig.m with pointers to the routines in this file.
12535*/
12536SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12537  static const sqlite3_mem_methods defaultMethods = {
12538     sqlite3MemMalloc,
12539     sqlite3MemFree,
12540     sqlite3MemRealloc,
12541     sqlite3MemSize,
12542     sqlite3MemRoundup,
12543     sqlite3MemInit,
12544     sqlite3MemShutdown,
12545     0
12546  };
12547  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
12548}
12549
12550#endif /* SQLITE_ZERO_MALLOC */
12551
12552/************** End of mem0.c ************************************************/
12553/************** Begin file mem1.c ********************************************/
12554/*
12555** 2007 August 14
12556**
12557** The author disclaims copyright to this source code.  In place of
12558** a legal notice, here is a blessing:
12559**
12560**    May you do good and not evil.
12561**    May you find forgiveness for yourself and forgive others.
12562**    May you share freely, never taking more than you give.
12563**
12564*************************************************************************
12565**
12566** This file contains low-level memory allocation drivers for when
12567** SQLite will use the standard C-library malloc/realloc/free interface
12568** to obtain the memory it needs.
12569**
12570** This file contains implementations of the low-level memory allocation
12571** routines specified in the sqlite3_mem_methods object.
12572*/
12573
12574/*
12575** This version of the memory allocator is the default.  It is
12576** used when no other memory allocator is specified using compile-time
12577** macros.
12578*/
12579#ifdef SQLITE_SYSTEM_MALLOC
12580
12581/*
12582** Like malloc(), but remember the size of the allocation
12583** so that we can find it later using sqlite3MemSize().
12584**
12585** For this low-level routine, we are guaranteed that nByte>0 because
12586** cases of nByte<=0 will be intercepted and dealt with by higher level
12587** routines.
12588*/
12589static void *sqlite3MemMalloc(int nByte){
12590  sqlite3_int64 *p;
12591  assert( nByte>0 );
12592  nByte = ROUND8(nByte);
12593  p = malloc( nByte+8 );
12594  if( p ){
12595    p[0] = nByte;
12596    p++;
12597  }
12598  return (void *)p;
12599}
12600
12601/*
12602** Like free() but works for allocations obtained from sqlite3MemMalloc()
12603** or sqlite3MemRealloc().
12604**
12605** For this low-level routine, we already know that pPrior!=0 since
12606** cases where pPrior==0 will have been intecepted and dealt with
12607** by higher-level routines.
12608*/
12609static void sqlite3MemFree(void *pPrior){
12610  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12611  assert( pPrior!=0 );
12612  p--;
12613  free(p);
12614}
12615
12616/*
12617** Like realloc().  Resize an allocation previously obtained from
12618** sqlite3MemMalloc().
12619**
12620** For this low-level interface, we know that pPrior!=0.  Cases where
12621** pPrior==0 while have been intercepted by higher-level routine and
12622** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
12623** cases where nByte<=0 will have been intercepted by higher-level
12624** routines and redirected to xFree.
12625*/
12626static void *sqlite3MemRealloc(void *pPrior, int nByte){
12627  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12628  assert( pPrior!=0 && nByte>0 );
12629  nByte = ROUND8(nByte);
12630  p = (sqlite3_int64*)pPrior;
12631  p--;
12632  p = realloc(p, nByte+8 );
12633  if( p ){
12634    p[0] = nByte;
12635    p++;
12636  }
12637  return (void*)p;
12638}
12639
12640/*
12641** Report the allocated size of a prior return from xMalloc()
12642** or xRealloc().
12643*/
12644static int sqlite3MemSize(void *pPrior){
12645  sqlite3_int64 *p;
12646  if( pPrior==0 ) return 0;
12647  p = (sqlite3_int64*)pPrior;
12648  p--;
12649  return (int)p[0];
12650}
12651
12652/*
12653** Round up a request size to the next valid allocation size.
12654*/
12655static int sqlite3MemRoundup(int n){
12656  return ROUND8(n);
12657}
12658
12659/*
12660** Initialize this module.
12661*/
12662static int sqlite3MemInit(void *NotUsed){
12663  UNUSED_PARAMETER(NotUsed);
12664  return SQLITE_OK;
12665}
12666
12667/*
12668** Deinitialize this module.
12669*/
12670static void sqlite3MemShutdown(void *NotUsed){
12671  UNUSED_PARAMETER(NotUsed);
12672  return;
12673}
12674
12675/*
12676** This routine is the only routine in this file with external linkage.
12677**
12678** Populate the low-level memory allocation function pointers in
12679** sqlite3GlobalConfig.m with pointers to the routines in this file.
12680*/
12681SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12682  static const sqlite3_mem_methods defaultMethods = {
12683     sqlite3MemMalloc,
12684     sqlite3MemFree,
12685     sqlite3MemRealloc,
12686     sqlite3MemSize,
12687     sqlite3MemRoundup,
12688     sqlite3MemInit,
12689     sqlite3MemShutdown,
12690     0
12691  };
12692  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
12693}
12694
12695#endif /* SQLITE_SYSTEM_MALLOC */
12696
12697/************** End of mem1.c ************************************************/
12698/************** Begin file mem2.c ********************************************/
12699/*
12700** 2007 August 15
12701**
12702** The author disclaims copyright to this source code.  In place of
12703** a legal notice, here is a blessing:
12704**
12705**    May you do good and not evil.
12706**    May you find forgiveness for yourself and forgive others.
12707**    May you share freely, never taking more than you give.
12708**
12709*************************************************************************
12710**
12711** This file contains low-level memory allocation drivers for when
12712** SQLite will use the standard C-library malloc/realloc/free interface
12713** to obtain the memory it needs while adding lots of additional debugging
12714** information to each allocation in order to help detect and fix memory
12715** leaks and memory usage errors.
12716**
12717** This file contains implementations of the low-level memory allocation
12718** routines specified in the sqlite3_mem_methods object.
12719*/
12720
12721/*
12722** This version of the memory allocator is used only if the
12723** SQLITE_MEMDEBUG macro is defined
12724*/
12725#ifdef SQLITE_MEMDEBUG
12726
12727/*
12728** The backtrace functionality is only available with GLIBC
12729*/
12730#ifdef __GLIBC__
12731  extern int backtrace(void**,int);
12732  extern void backtrace_symbols_fd(void*const*,int,int);
12733#else
12734# define backtrace(A,B) 1
12735# define backtrace_symbols_fd(A,B,C)
12736#endif
12737
12738/*
12739** Each memory allocation looks like this:
12740**
12741**  ------------------------------------------------------------------------
12742**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
12743**  ------------------------------------------------------------------------
12744**
12745** The application code sees only a pointer to the allocation.  We have
12746** to back up from the allocation pointer to find the MemBlockHdr.  The
12747** MemBlockHdr tells us the size of the allocation and the number of
12748** backtrace pointers.  There is also a guard word at the end of the
12749** MemBlockHdr.
12750*/
12751struct MemBlockHdr {
12752  i64 iSize;                          /* Size of this allocation */
12753  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
12754  char nBacktrace;                    /* Number of backtraces on this alloc */
12755  char nBacktraceSlots;               /* Available backtrace slots */
12756  short nTitle;                       /* Bytes of title; includes '\0' */
12757  int iForeGuard;                     /* Guard word for sanity */
12758};
12759
12760/*
12761** Guard words
12762*/
12763#define FOREGUARD 0x80F5E153
12764#define REARGUARD 0xE4676B53
12765
12766/*
12767** Number of malloc size increments to track.
12768*/
12769#define NCSIZE  1000
12770
12771/*
12772** All of the static variables used by this module are collected
12773** into a single structure named "mem".  This is to keep the
12774** static variables organized and to reduce namespace pollution
12775** when this module is combined with other in the amalgamation.
12776*/
12777static struct {
12778
12779  /*
12780  ** Mutex to control access to the memory allocation subsystem.
12781  */
12782  sqlite3_mutex *mutex;
12783
12784  /*
12785  ** Head and tail of a linked list of all outstanding allocations
12786  */
12787  struct MemBlockHdr *pFirst;
12788  struct MemBlockHdr *pLast;
12789
12790  /*
12791  ** The number of levels of backtrace to save in new allocations.
12792  */
12793  int nBacktrace;
12794  void (*xBacktrace)(int, int, void **);
12795
12796  /*
12797  ** Title text to insert in front of each block
12798  */
12799  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
12800  char zTitle[100];  /* The title text */
12801
12802  /*
12803  ** sqlite3MallocDisallow() increments the following counter.
12804  ** sqlite3MallocAllow() decrements it.
12805  */
12806  int disallow; /* Do not allow memory allocation */
12807
12808  /*
12809  ** Gather statistics on the sizes of memory allocations.
12810  ** nAlloc[i] is the number of allocation attempts of i*8
12811  ** bytes.  i==NCSIZE is the number of allocation attempts for
12812  ** sizes more than NCSIZE*8 bytes.
12813  */
12814  int nAlloc[NCSIZE];      /* Total number of allocations */
12815  int nCurrent[NCSIZE];    /* Current number of allocations */
12816  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
12817
12818} mem;
12819
12820
12821/*
12822** Adjust memory usage statistics
12823*/
12824static void adjustStats(int iSize, int increment){
12825  int i = ROUND8(iSize)/8;
12826  if( i>NCSIZE-1 ){
12827    i = NCSIZE - 1;
12828  }
12829  if( increment>0 ){
12830    mem.nAlloc[i]++;
12831    mem.nCurrent[i]++;
12832    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
12833      mem.mxCurrent[i] = mem.nCurrent[i];
12834    }
12835  }else{
12836    mem.nCurrent[i]--;
12837    assert( mem.nCurrent[i]>=0 );
12838  }
12839}
12840
12841/*
12842** Given an allocation, find the MemBlockHdr for that allocation.
12843**
12844** This routine checks the guards at either end of the allocation and
12845** if they are incorrect it asserts.
12846*/
12847static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
12848  struct MemBlockHdr *p;
12849  int *pInt;
12850  u8 *pU8;
12851  int nReserve;
12852
12853  p = (struct MemBlockHdr*)pAllocation;
12854  p--;
12855  assert( p->iForeGuard==(int)FOREGUARD );
12856  nReserve = ROUND8(p->iSize);
12857  pInt = (int*)pAllocation;
12858  pU8 = (u8*)pAllocation;
12859  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
12860  /* This checks any of the "extra" bytes allocated due
12861  ** to rounding up to an 8 byte boundary to ensure
12862  ** they haven't been overwritten.
12863  */
12864  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
12865  return p;
12866}
12867
12868/*
12869** Return the number of bytes currently allocated at address p.
12870*/
12871static int sqlite3MemSize(void *p){
12872  struct MemBlockHdr *pHdr;
12873  if( !p ){
12874    return 0;
12875  }
12876  pHdr = sqlite3MemsysGetHeader(p);
12877  return pHdr->iSize;
12878}
12879
12880/*
12881** Initialize the memory allocation subsystem.
12882*/
12883static int sqlite3MemInit(void *NotUsed){
12884  UNUSED_PARAMETER(NotUsed);
12885  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
12886  if( !sqlite3GlobalConfig.bMemstat ){
12887    /* If memory status is enabled, then the malloc.c wrapper will already
12888    ** hold the STATIC_MEM mutex when the routines here are invoked. */
12889    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
12890  }
12891  return SQLITE_OK;
12892}
12893
12894/*
12895** Deinitialize the memory allocation subsystem.
12896*/
12897static void sqlite3MemShutdown(void *NotUsed){
12898  UNUSED_PARAMETER(NotUsed);
12899  mem.mutex = 0;
12900}
12901
12902/*
12903** Round up a request size to the next valid allocation size.
12904*/
12905static int sqlite3MemRoundup(int n){
12906  return ROUND8(n);
12907}
12908
12909/*
12910** Fill a buffer with pseudo-random bytes.  This is used to preset
12911** the content of a new memory allocation to unpredictable values and
12912** to clear the content of a freed allocation to unpredictable values.
12913*/
12914static void randomFill(char *pBuf, int nByte){
12915  unsigned int x, y, r;
12916  x = SQLITE_PTR_TO_INT(pBuf);
12917  y = nByte | 1;
12918  while( nByte >= 4 ){
12919    x = (x>>1) ^ (-(x&1) & 0xd0000001);
12920    y = y*1103515245 + 12345;
12921    r = x ^ y;
12922    *(int*)pBuf = r;
12923    pBuf += 4;
12924    nByte -= 4;
12925  }
12926  while( nByte-- > 0 ){
12927    x = (x>>1) ^ (-(x&1) & 0xd0000001);
12928    y = y*1103515245 + 12345;
12929    r = x ^ y;
12930    *(pBuf++) = r & 0xff;
12931  }
12932}
12933
12934/*
12935** Allocate nByte bytes of memory.
12936*/
12937static void *sqlite3MemMalloc(int nByte){
12938  struct MemBlockHdr *pHdr;
12939  void **pBt;
12940  char *z;
12941  int *pInt;
12942  void *p = 0;
12943  int totalSize;
12944  int nReserve;
12945  sqlite3_mutex_enter(mem.mutex);
12946  assert( mem.disallow==0 );
12947  nReserve = ROUND8(nByte);
12948  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
12949               mem.nBacktrace*sizeof(void*) + mem.nTitle;
12950  p = malloc(totalSize);
12951  if( p ){
12952    z = p;
12953    pBt = (void**)&z[mem.nTitle];
12954    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
12955    pHdr->pNext = 0;
12956    pHdr->pPrev = mem.pLast;
12957    if( mem.pLast ){
12958      mem.pLast->pNext = pHdr;
12959    }else{
12960      mem.pFirst = pHdr;
12961    }
12962    mem.pLast = pHdr;
12963    pHdr->iForeGuard = FOREGUARD;
12964    pHdr->nBacktraceSlots = mem.nBacktrace;
12965    pHdr->nTitle = mem.nTitle;
12966    if( mem.nBacktrace ){
12967      void *aAddr[40];
12968      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
12969      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
12970      assert(pBt[0]);
12971      if( mem.xBacktrace ){
12972        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
12973      }
12974    }else{
12975      pHdr->nBacktrace = 0;
12976    }
12977    if( mem.nTitle ){
12978      memcpy(z, mem.zTitle, mem.nTitle);
12979    }
12980    pHdr->iSize = nByte;
12981    adjustStats(nByte, +1);
12982    pInt = (int*)&pHdr[1];
12983    pInt[nReserve/sizeof(int)] = REARGUARD;
12984    randomFill((char*)pInt, nByte);
12985    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
12986    p = (void*)pInt;
12987  }
12988  sqlite3_mutex_leave(mem.mutex);
12989  return p;
12990}
12991
12992/*
12993** Free memory.
12994*/
12995static void sqlite3MemFree(void *pPrior){
12996  struct MemBlockHdr *pHdr;
12997  void **pBt;
12998  char *z;
12999  assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 );
13000  pHdr = sqlite3MemsysGetHeader(pPrior);
13001  pBt = (void**)pHdr;
13002  pBt -= pHdr->nBacktraceSlots;
13003  sqlite3_mutex_enter(mem.mutex);
13004  if( pHdr->pPrev ){
13005    assert( pHdr->pPrev->pNext==pHdr );
13006    pHdr->pPrev->pNext = pHdr->pNext;
13007  }else{
13008    assert( mem.pFirst==pHdr );
13009    mem.pFirst = pHdr->pNext;
13010  }
13011  if( pHdr->pNext ){
13012    assert( pHdr->pNext->pPrev==pHdr );
13013    pHdr->pNext->pPrev = pHdr->pPrev;
13014  }else{
13015    assert( mem.pLast==pHdr );
13016    mem.pLast = pHdr->pPrev;
13017  }
13018  z = (char*)pBt;
13019  z -= pHdr->nTitle;
13020  adjustStats(pHdr->iSize, -1);
13021  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
13022                pHdr->iSize + sizeof(int) + pHdr->nTitle);
13023  free(z);
13024  sqlite3_mutex_leave(mem.mutex);
13025}
13026
13027/*
13028** Change the size of an existing memory allocation.
13029**
13030** For this debugging implementation, we *always* make a copy of the
13031** allocation into a new place in memory.  In this way, if the
13032** higher level code is using pointer to the old allocation, it is
13033** much more likely to break and we are much more liking to find
13034** the error.
13035*/
13036static void *sqlite3MemRealloc(void *pPrior, int nByte){
13037  struct MemBlockHdr *pOldHdr;
13038  void *pNew;
13039  assert( mem.disallow==0 );
13040  pOldHdr = sqlite3MemsysGetHeader(pPrior);
13041  pNew = sqlite3MemMalloc(nByte);
13042  if( pNew ){
13043    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
13044    if( nByte>pOldHdr->iSize ){
13045      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
13046    }
13047    sqlite3MemFree(pPrior);
13048  }
13049  return pNew;
13050}
13051
13052/*
13053** Populate the low-level memory allocation function pointers in
13054** sqlite3GlobalConfig.m with pointers to the routines in this file.
13055*/
13056SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13057  static const sqlite3_mem_methods defaultMethods = {
13058     sqlite3MemMalloc,
13059     sqlite3MemFree,
13060     sqlite3MemRealloc,
13061     sqlite3MemSize,
13062     sqlite3MemRoundup,
13063     sqlite3MemInit,
13064     sqlite3MemShutdown,
13065     0
13066  };
13067  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13068}
13069
13070/*
13071** Set the number of backtrace levels kept for each allocation.
13072** A value of zero turns off backtracing.  The number is always rounded
13073** up to a multiple of 2.
13074*/
13075SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
13076  if( depth<0 ){ depth = 0; }
13077  if( depth>20 ){ depth = 20; }
13078  depth = (depth+1)&0xfe;
13079  mem.nBacktrace = depth;
13080}
13081
13082SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
13083  mem.xBacktrace = xBacktrace;
13084}
13085
13086/*
13087** Set the title string for subsequent allocations.
13088*/
13089SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
13090  unsigned int n = sqlite3Strlen30(zTitle) + 1;
13091  sqlite3_mutex_enter(mem.mutex);
13092  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
13093  memcpy(mem.zTitle, zTitle, n);
13094  mem.zTitle[n] = 0;
13095  mem.nTitle = ROUND8(n);
13096  sqlite3_mutex_leave(mem.mutex);
13097}
13098
13099SQLITE_PRIVATE void sqlite3MemdebugSync(){
13100  struct MemBlockHdr *pHdr;
13101  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13102    void **pBt = (void**)pHdr;
13103    pBt -= pHdr->nBacktraceSlots;
13104    mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
13105  }
13106}
13107
13108/*
13109** Open the file indicated and write a log of all unfreed memory
13110** allocations into that log.
13111*/
13112SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
13113  FILE *out;
13114  struct MemBlockHdr *pHdr;
13115  void **pBt;
13116  int i;
13117  out = fopen(zFilename, "w");
13118  if( out==0 ){
13119    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13120                    zFilename);
13121    return;
13122  }
13123  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13124    char *z = (char*)pHdr;
13125    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
13126    fprintf(out, "**** %lld bytes at %p from %s ****\n",
13127            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
13128    if( pHdr->nBacktrace ){
13129      fflush(out);
13130      pBt = (void**)pHdr;
13131      pBt -= pHdr->nBacktraceSlots;
13132      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
13133      fprintf(out, "\n");
13134    }
13135  }
13136  fprintf(out, "COUNTS:\n");
13137  for(i=0; i<NCSIZE-1; i++){
13138    if( mem.nAlloc[i] ){
13139      fprintf(out, "   %5d: %10d %10d %10d\n",
13140            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
13141    }
13142  }
13143  if( mem.nAlloc[NCSIZE-1] ){
13144    fprintf(out, "   %5d: %10d %10d %10d\n",
13145             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
13146             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
13147  }
13148  fclose(out);
13149}
13150
13151/*
13152** Return the number of times sqlite3MemMalloc() has been called.
13153*/
13154SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
13155  int i;
13156  int nTotal = 0;
13157  for(i=0; i<NCSIZE; i++){
13158    nTotal += mem.nAlloc[i];
13159  }
13160  return nTotal;
13161}
13162
13163
13164#endif /* SQLITE_MEMDEBUG */
13165
13166/************** End of mem2.c ************************************************/
13167/************** Begin file mem3.c ********************************************/
13168/*
13169** 2007 October 14
13170**
13171** The author disclaims copyright to this source code.  In place of
13172** a legal notice, here is a blessing:
13173**
13174**    May you do good and not evil.
13175**    May you find forgiveness for yourself and forgive others.
13176**    May you share freely, never taking more than you give.
13177**
13178*************************************************************************
13179** This file contains the C functions that implement a memory
13180** allocation subsystem for use by SQLite.
13181**
13182** This version of the memory allocation subsystem omits all
13183** use of malloc(). The SQLite user supplies a block of memory
13184** before calling sqlite3_initialize() from which allocations
13185** are made and returned by the xMalloc() and xRealloc()
13186** implementations. Once sqlite3_initialize() has been called,
13187** the amount of memory available to SQLite is fixed and cannot
13188** be changed.
13189**
13190** This version of the memory allocation subsystem is included
13191** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
13192*/
13193
13194/*
13195** This version of the memory allocator is only built into the library
13196** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
13197** mean that the library will use a memory-pool by default, just that
13198** it is available. The mempool allocator is activated by calling
13199** sqlite3_config().
13200*/
13201#ifdef SQLITE_ENABLE_MEMSYS3
13202
13203/*
13204** Maximum size (in Mem3Blocks) of a "small" chunk.
13205*/
13206#define MX_SMALL 10
13207
13208
13209/*
13210** Number of freelist hash slots
13211*/
13212#define N_HASH  61
13213
13214/*
13215** A memory allocation (also called a "chunk") consists of two or
13216** more blocks where each block is 8 bytes.  The first 8 bytes are
13217** a header that is not returned to the user.
13218**
13219** A chunk is two or more blocks that is either checked out or
13220** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
13221** size of the allocation in blocks if the allocation is free.
13222** The u.hdr.size4x&1 bit is true if the chunk is checked out and
13223** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
13224** is true if the previous chunk is checked out and false if the
13225** previous chunk is free.  The u.hdr.prevSize field is the size of
13226** the previous chunk in blocks if the previous chunk is on the
13227** freelist. If the previous chunk is checked out, then
13228** u.hdr.prevSize can be part of the data for that chunk and should
13229** not be read or written.
13230**
13231** We often identify a chunk by its index in mem3.aPool[].  When
13232** this is done, the chunk index refers to the second block of
13233** the chunk.  In this way, the first chunk has an index of 1.
13234** A chunk index of 0 means "no such chunk" and is the equivalent
13235** of a NULL pointer.
13236**
13237** The second block of free chunks is of the form u.list.  The
13238** two fields form a double-linked list of chunks of related sizes.
13239** Pointers to the head of the list are stored in mem3.aiSmall[]
13240** for smaller chunks and mem3.aiHash[] for larger chunks.
13241**
13242** The second block of a chunk is user data if the chunk is checked
13243** out.  If a chunk is checked out, the user data may extend into
13244** the u.hdr.prevSize value of the following chunk.
13245*/
13246typedef struct Mem3Block Mem3Block;
13247struct Mem3Block {
13248  union {
13249    struct {
13250      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
13251      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
13252    } hdr;
13253    struct {
13254      u32 next;       /* Index in mem3.aPool[] of next free chunk */
13255      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
13256    } list;
13257  } u;
13258};
13259
13260/*
13261** All of the static variables used by this module are collected
13262** into a single structure named "mem3".  This is to keep the
13263** static variables organized and to reduce namespace pollution
13264** when this module is combined with other in the amalgamation.
13265*/
13266static SQLITE_WSD struct Mem3Global {
13267  /*
13268  ** Memory available for allocation. nPool is the size of the array
13269  ** (in Mem3Blocks) pointed to by aPool less 2.
13270  */
13271  u32 nPool;
13272  Mem3Block *aPool;
13273
13274  /*
13275  ** True if we are evaluating an out-of-memory callback.
13276  */
13277  int alarmBusy;
13278
13279  /*
13280  ** Mutex to control access to the memory allocation subsystem.
13281  */
13282  sqlite3_mutex *mutex;
13283
13284  /*
13285  ** The minimum amount of free space that we have seen.
13286  */
13287  u32 mnMaster;
13288
13289  /*
13290  ** iMaster is the index of the master chunk.  Most new allocations
13291  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
13292  ** of the current master.  iMaster is 0 if there is not master chunk.
13293  ** The master chunk is not in either the aiHash[] or aiSmall[].
13294  */
13295  u32 iMaster;
13296  u32 szMaster;
13297
13298  /*
13299  ** Array of lists of free blocks according to the block size
13300  ** for smaller chunks, or a hash on the block size for larger
13301  ** chunks.
13302  */
13303  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
13304  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
13305} mem3 = { 97535575 };
13306
13307#define mem3 GLOBAL(struct Mem3Global, mem3)
13308
13309/*
13310** Unlink the chunk at mem3.aPool[i] from list it is currently
13311** on.  *pRoot is the list that i is a member of.
13312*/
13313static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
13314  u32 next = mem3.aPool[i].u.list.next;
13315  u32 prev = mem3.aPool[i].u.list.prev;
13316  assert( sqlite3_mutex_held(mem3.mutex) );
13317  if( prev==0 ){
13318    *pRoot = next;
13319  }else{
13320    mem3.aPool[prev].u.list.next = next;
13321  }
13322  if( next ){
13323    mem3.aPool[next].u.list.prev = prev;
13324  }
13325  mem3.aPool[i].u.list.next = 0;
13326  mem3.aPool[i].u.list.prev = 0;
13327}
13328
13329/*
13330** Unlink the chunk at index i from
13331** whatever list is currently a member of.
13332*/
13333static void memsys3Unlink(u32 i){
13334  u32 size, hash;
13335  assert( sqlite3_mutex_held(mem3.mutex) );
13336  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13337  assert( i>=1 );
13338  size = mem3.aPool[i-1].u.hdr.size4x/4;
13339  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13340  assert( size>=2 );
13341  if( size <= MX_SMALL ){
13342    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
13343  }else{
13344    hash = size % N_HASH;
13345    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13346  }
13347}
13348
13349/*
13350** Link the chunk at mem3.aPool[i] so that is on the list rooted
13351** at *pRoot.
13352*/
13353static void memsys3LinkIntoList(u32 i, u32 *pRoot){
13354  assert( sqlite3_mutex_held(mem3.mutex) );
13355  mem3.aPool[i].u.list.next = *pRoot;
13356  mem3.aPool[i].u.list.prev = 0;
13357  if( *pRoot ){
13358    mem3.aPool[*pRoot].u.list.prev = i;
13359  }
13360  *pRoot = i;
13361}
13362
13363/*
13364** Link the chunk at index i into either the appropriate
13365** small chunk list, or into the large chunk hash table.
13366*/
13367static void memsys3Link(u32 i){
13368  u32 size, hash;
13369  assert( sqlite3_mutex_held(mem3.mutex) );
13370  assert( i>=1 );
13371  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13372  size = mem3.aPool[i-1].u.hdr.size4x/4;
13373  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13374  assert( size>=2 );
13375  if( size <= MX_SMALL ){
13376    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
13377  }else{
13378    hash = size % N_HASH;
13379    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
13380  }
13381}
13382
13383/*
13384** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13385** will already be held (obtained by code in malloc.c) if
13386** sqlite3GlobalConfig.bMemStat is true.
13387*/
13388static void memsys3Enter(void){
13389  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
13390    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13391  }
13392  sqlite3_mutex_enter(mem3.mutex);
13393}
13394static void memsys3Leave(void){
13395  sqlite3_mutex_leave(mem3.mutex);
13396}
13397
13398/*
13399** Called when we are unable to satisfy an allocation of nBytes.
13400*/
13401static void memsys3OutOfMemory(int nByte){
13402  if( !mem3.alarmBusy ){
13403    mem3.alarmBusy = 1;
13404    assert( sqlite3_mutex_held(mem3.mutex) );
13405    sqlite3_mutex_leave(mem3.mutex);
13406    sqlite3_release_memory(nByte);
13407    sqlite3_mutex_enter(mem3.mutex);
13408    mem3.alarmBusy = 0;
13409  }
13410}
13411
13412
13413/*
13414** Chunk i is a free chunk that has been unlinked.  Adjust its
13415** size parameters for check-out and return a pointer to the
13416** user portion of the chunk.
13417*/
13418static void *memsys3Checkout(u32 i, u32 nBlock){
13419  u32 x;
13420  assert( sqlite3_mutex_held(mem3.mutex) );
13421  assert( i>=1 );
13422  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
13423  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
13424  x = mem3.aPool[i-1].u.hdr.size4x;
13425  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
13426  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
13427  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
13428  return &mem3.aPool[i];
13429}
13430
13431/*
13432** Carve a piece off of the end of the mem3.iMaster free chunk.
13433** Return a pointer to the new allocation.  Or, if the master chunk
13434** is not large enough, return 0.
13435*/
13436static void *memsys3FromMaster(u32 nBlock){
13437  assert( sqlite3_mutex_held(mem3.mutex) );
13438  assert( mem3.szMaster>=nBlock );
13439  if( nBlock>=mem3.szMaster-1 ){
13440    /* Use the entire master */
13441    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
13442    mem3.iMaster = 0;
13443    mem3.szMaster = 0;
13444    mem3.mnMaster = 0;
13445    return p;
13446  }else{
13447    /* Split the master block.  Return the tail. */
13448    u32 newi, x;
13449    newi = mem3.iMaster + mem3.szMaster - nBlock;
13450    assert( newi > mem3.iMaster+1 );
13451    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
13452    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
13453    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
13454    mem3.szMaster -= nBlock;
13455    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
13456    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13457    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13458    if( mem3.szMaster < mem3.mnMaster ){
13459      mem3.mnMaster = mem3.szMaster;
13460    }
13461    return (void*)&mem3.aPool[newi];
13462  }
13463}
13464
13465/*
13466** *pRoot is the head of a list of free chunks of the same size
13467** or same size hash.  In other words, *pRoot is an entry in either
13468** mem3.aiSmall[] or mem3.aiHash[].
13469**
13470** This routine examines all entries on the given list and tries
13471** to coalesce each entries with adjacent free chunks.
13472**
13473** If it sees a chunk that is larger than mem3.iMaster, it replaces
13474** the current mem3.iMaster with the new larger chunk.  In order for
13475** this mem3.iMaster replacement to work, the master chunk must be
13476** linked into the hash tables.  That is not the normal state of
13477** affairs, of course.  The calling routine must link the master
13478** chunk before invoking this routine, then must unlink the (possibly
13479** changed) master chunk once this routine has finished.
13480*/
13481static void memsys3Merge(u32 *pRoot){
13482  u32 iNext, prev, size, i, x;
13483
13484  assert( sqlite3_mutex_held(mem3.mutex) );
13485  for(i=*pRoot; i>0; i=iNext){
13486    iNext = mem3.aPool[i].u.list.next;
13487    size = mem3.aPool[i-1].u.hdr.size4x;
13488    assert( (size&1)==0 );
13489    if( (size&2)==0 ){
13490      memsys3UnlinkFromList(i, pRoot);
13491      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
13492      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
13493      if( prev==iNext ){
13494        iNext = mem3.aPool[prev].u.list.next;
13495      }
13496      memsys3Unlink(prev);
13497      size = i + size/4 - prev;
13498      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
13499      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
13500      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
13501      memsys3Link(prev);
13502      i = prev;
13503    }else{
13504      size /= 4;
13505    }
13506    if( size>mem3.szMaster ){
13507      mem3.iMaster = i;
13508      mem3.szMaster = size;
13509    }
13510  }
13511}
13512
13513/*
13514** Return a block of memory of at least nBytes in size.
13515** Return NULL if unable.
13516**
13517** This function assumes that the necessary mutexes, if any, are
13518** already held by the caller. Hence "Unsafe".
13519*/
13520static void *memsys3MallocUnsafe(int nByte){
13521  u32 i;
13522  u32 nBlock;
13523  u32 toFree;
13524
13525  assert( sqlite3_mutex_held(mem3.mutex) );
13526  assert( sizeof(Mem3Block)==8 );
13527  if( nByte<=12 ){
13528    nBlock = 2;
13529  }else{
13530    nBlock = (nByte + 11)/8;
13531  }
13532  assert( nBlock>=2 );
13533
13534  /* STEP 1:
13535  ** Look for an entry of the correct size in either the small
13536  ** chunk table or in the large chunk hash table.  This is
13537  ** successful most of the time (about 9 times out of 10).
13538  */
13539  if( nBlock <= MX_SMALL ){
13540    i = mem3.aiSmall[nBlock-2];
13541    if( i>0 ){
13542      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
13543      return memsys3Checkout(i, nBlock);
13544    }
13545  }else{
13546    int hash = nBlock % N_HASH;
13547    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
13548      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
13549        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13550        return memsys3Checkout(i, nBlock);
13551      }
13552    }
13553  }
13554
13555  /* STEP 2:
13556  ** Try to satisfy the allocation by carving a piece off of the end
13557  ** of the master chunk.  This step usually works if step 1 fails.
13558  */
13559  if( mem3.szMaster>=nBlock ){
13560    return memsys3FromMaster(nBlock);
13561  }
13562
13563
13564  /* STEP 3:
13565  ** Loop through the entire memory pool.  Coalesce adjacent free
13566  ** chunks.  Recompute the master chunk as the largest free chunk.
13567  ** Then try again to satisfy the allocation by carving a piece off
13568  ** of the end of the master chunk.  This step happens very
13569  ** rarely (we hope!)
13570  */
13571  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
13572    memsys3OutOfMemory(toFree);
13573    if( mem3.iMaster ){
13574      memsys3Link(mem3.iMaster);
13575      mem3.iMaster = 0;
13576      mem3.szMaster = 0;
13577    }
13578    for(i=0; i<N_HASH; i++){
13579      memsys3Merge(&mem3.aiHash[i]);
13580    }
13581    for(i=0; i<MX_SMALL-1; i++){
13582      memsys3Merge(&mem3.aiSmall[i]);
13583    }
13584    if( mem3.szMaster ){
13585      memsys3Unlink(mem3.iMaster);
13586      if( mem3.szMaster>=nBlock ){
13587        return memsys3FromMaster(nBlock);
13588      }
13589    }
13590  }
13591
13592  /* If none of the above worked, then we fail. */
13593  return 0;
13594}
13595
13596/*
13597** Free an outstanding memory allocation.
13598**
13599** This function assumes that the necessary mutexes, if any, are
13600** already held by the caller. Hence "Unsafe".
13601*/
13602void memsys3FreeUnsafe(void *pOld){
13603  Mem3Block *p = (Mem3Block*)pOld;
13604  int i;
13605  u32 size, x;
13606  assert( sqlite3_mutex_held(mem3.mutex) );
13607  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
13608  i = p - mem3.aPool;
13609  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
13610  size = mem3.aPool[i-1].u.hdr.size4x/4;
13611  assert( i+size<=mem3.nPool+1 );
13612  mem3.aPool[i-1].u.hdr.size4x &= ~1;
13613  mem3.aPool[i+size-1].u.hdr.prevSize = size;
13614  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
13615  memsys3Link(i);
13616
13617  /* Try to expand the master using the newly freed chunk */
13618  if( mem3.iMaster ){
13619    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
13620      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
13621      mem3.iMaster -= size;
13622      mem3.szMaster += size;
13623      memsys3Unlink(mem3.iMaster);
13624      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13625      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13626      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
13627    }
13628    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13629    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
13630      memsys3Unlink(mem3.iMaster+mem3.szMaster);
13631      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
13632      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13633      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
13634    }
13635  }
13636}
13637
13638/*
13639** Return the size of an outstanding allocation, in bytes.  The
13640** size returned omits the 8-byte header overhead.  This only
13641** works for chunks that are currently checked out.
13642*/
13643static int memsys3Size(void *p){
13644  Mem3Block *pBlock;
13645  if( p==0 ) return 0;
13646  pBlock = (Mem3Block*)p;
13647  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
13648  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
13649}
13650
13651/*
13652** Round up a request size to the next valid allocation size.
13653*/
13654static int memsys3Roundup(int n){
13655  if( n<=12 ){
13656    return 12;
13657  }else{
13658    return ((n+11)&~7) - 4;
13659  }
13660}
13661
13662/*
13663** Allocate nBytes of memory.
13664*/
13665static void *memsys3Malloc(int nBytes){
13666  sqlite3_int64 *p;
13667  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
13668  memsys3Enter();
13669  p = memsys3MallocUnsafe(nBytes);
13670  memsys3Leave();
13671  return (void*)p;
13672}
13673
13674/*
13675** Free memory.
13676*/
13677void memsys3Free(void *pPrior){
13678  assert( pPrior );
13679  memsys3Enter();
13680  memsys3FreeUnsafe(pPrior);
13681  memsys3Leave();
13682}
13683
13684/*
13685** Change the size of an existing memory allocation
13686*/
13687void *memsys3Realloc(void *pPrior, int nBytes){
13688  int nOld;
13689  void *p;
13690  if( pPrior==0 ){
13691    return sqlite3_malloc(nBytes);
13692  }
13693  if( nBytes<=0 ){
13694    sqlite3_free(pPrior);
13695    return 0;
13696  }
13697  nOld = memsys3Size(pPrior);
13698  if( nBytes<=nOld && nBytes>=nOld-128 ){
13699    return pPrior;
13700  }
13701  memsys3Enter();
13702  p = memsys3MallocUnsafe(nBytes);
13703  if( p ){
13704    if( nOld<nBytes ){
13705      memcpy(p, pPrior, nOld);
13706    }else{
13707      memcpy(p, pPrior, nBytes);
13708    }
13709    memsys3FreeUnsafe(pPrior);
13710  }
13711  memsys3Leave();
13712  return p;
13713}
13714
13715/*
13716** Initialize this module.
13717*/
13718static int memsys3Init(void *NotUsed){
13719  UNUSED_PARAMETER(NotUsed);
13720  if( !sqlite3GlobalConfig.pHeap ){
13721    return SQLITE_ERROR;
13722  }
13723
13724  /* Store a pointer to the memory block in global structure mem3. */
13725  assert( sizeof(Mem3Block)==8 );
13726  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
13727  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
13728
13729  /* Initialize the master block. */
13730  mem3.szMaster = mem3.nPool;
13731  mem3.mnMaster = mem3.szMaster;
13732  mem3.iMaster = 1;
13733  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
13734  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
13735  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
13736
13737  return SQLITE_OK;
13738}
13739
13740/*
13741** Deinitialize this module.
13742*/
13743static void memsys3Shutdown(void *NotUsed){
13744  UNUSED_PARAMETER(NotUsed);
13745  mem3.mutex = 0;
13746  return;
13747}
13748
13749
13750
13751/*
13752** Open the file indicated and write a log of all unfreed memory
13753** allocations into that log.
13754*/
13755SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
13756#ifdef SQLITE_DEBUG
13757  FILE *out;
13758  u32 i, j;
13759  u32 size;
13760  if( zFilename==0 || zFilename[0]==0 ){
13761    out = stdout;
13762  }else{
13763    out = fopen(zFilename, "w");
13764    if( out==0 ){
13765      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13766                      zFilename);
13767      return;
13768    }
13769  }
13770  memsys3Enter();
13771  fprintf(out, "CHUNKS:\n");
13772  for(i=1; i<=mem3.nPool; i+=size/4){
13773    size = mem3.aPool[i-1].u.hdr.size4x;
13774    if( size/4<=1 ){
13775      fprintf(out, "%p size error\n", &mem3.aPool[i]);
13776      assert( 0 );
13777      break;
13778    }
13779    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
13780      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
13781      assert( 0 );
13782      break;
13783    }
13784    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
13785      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
13786      assert( 0 );
13787      break;
13788    }
13789    if( size&1 ){
13790      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
13791    }else{
13792      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
13793                  i==mem3.iMaster ? " **master**" : "");
13794    }
13795  }
13796  for(i=0; i<MX_SMALL-1; i++){
13797    if( mem3.aiSmall[i]==0 ) continue;
13798    fprintf(out, "small(%2d):", i);
13799    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
13800      fprintf(out, " %p(%d)", &mem3.aPool[j],
13801              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
13802    }
13803    fprintf(out, "\n");
13804  }
13805  for(i=0; i<N_HASH; i++){
13806    if( mem3.aiHash[i]==0 ) continue;
13807    fprintf(out, "hash(%2d):", i);
13808    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
13809      fprintf(out, " %p(%d)", &mem3.aPool[j],
13810              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
13811    }
13812    fprintf(out, "\n");
13813  }
13814  fprintf(out, "master=%d\n", mem3.iMaster);
13815  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
13816  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
13817  sqlite3_mutex_leave(mem3.mutex);
13818  if( out==stdout ){
13819    fflush(stdout);
13820  }else{
13821    fclose(out);
13822  }
13823#else
13824  UNUSED_PARAMETER(zFilename);
13825#endif
13826}
13827
13828/*
13829** This routine is the only routine in this file with external
13830** linkage.
13831**
13832** Populate the low-level memory allocation function pointers in
13833** sqlite3GlobalConfig.m with pointers to the routines in this file. The
13834** arguments specify the block of memory to manage.
13835**
13836** This routine is only called by sqlite3_config(), and therefore
13837** is not required to be threadsafe (it is not).
13838*/
13839SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
13840  static const sqlite3_mem_methods mempoolMethods = {
13841     memsys3Malloc,
13842     memsys3Free,
13843     memsys3Realloc,
13844     memsys3Size,
13845     memsys3Roundup,
13846     memsys3Init,
13847     memsys3Shutdown,
13848     0
13849  };
13850  return &mempoolMethods;
13851}
13852
13853#endif /* SQLITE_ENABLE_MEMSYS3 */
13854
13855/************** End of mem3.c ************************************************/
13856/************** Begin file mem5.c ********************************************/
13857/*
13858** 2007 October 14
13859**
13860** The author disclaims copyright to this source code.  In place of
13861** a legal notice, here is a blessing:
13862**
13863**    May you do good and not evil.
13864**    May you find forgiveness for yourself and forgive others.
13865**    May you share freely, never taking more than you give.
13866**
13867*************************************************************************
13868** This file contains the C functions that implement a memory
13869** allocation subsystem for use by SQLite.
13870**
13871** This version of the memory allocation subsystem omits all
13872** use of malloc(). The application gives SQLite a block of memory
13873** before calling sqlite3_initialize() from which allocations
13874** are made and returned by the xMalloc() and xRealloc()
13875** implementations. Once sqlite3_initialize() has been called,
13876** the amount of memory available to SQLite is fixed and cannot
13877** be changed.
13878**
13879** This version of the memory allocation subsystem is included
13880** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
13881**
13882** This memory allocator uses the following algorithm:
13883**
13884**   1.  All memory allocations sizes are rounded up to a power of 2.
13885**
13886**   2.  If two adjacent free blocks are the halves of a larger block,
13887**       then the two blocks are coalesed into the single larger block.
13888**
13889**   3.  New memory is allocated from the first available free block.
13890**
13891** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
13892** Concerning Dynamic Storage Allocation". Journal of the Association for
13893** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
13894**
13895** Let n be the size of the largest allocation divided by the minimum
13896** allocation size (after rounding all sizes up to a power of 2.)  Let M
13897** be the maximum amount of memory ever outstanding at one time.  Let
13898** N be the total amount of memory available for allocation.  Robson
13899** proved that this memory allocator will never breakdown due to
13900** fragmentation as long as the following constraint holds:
13901**
13902**      N >=  M*(1 + log2(n)/2) - n + 1
13903**
13904** The sqlite3_status() logic tracks the maximum values of n and M so
13905** that an application can, at any time, verify this constraint.
13906*/
13907
13908/*
13909** This version of the memory allocator is used only when
13910** SQLITE_ENABLE_MEMSYS5 is defined.
13911*/
13912#ifdef SQLITE_ENABLE_MEMSYS5
13913
13914/*
13915** A minimum allocation is an instance of the following structure.
13916** Larger allocations are an array of these structures where the
13917** size of the array is a power of 2.
13918**
13919** The size of this object must be a power of two.  That fact is
13920** verified in memsys5Init().
13921*/
13922typedef struct Mem5Link Mem5Link;
13923struct Mem5Link {
13924  int next;       /* Index of next free chunk */
13925  int prev;       /* Index of previous free chunk */
13926};
13927
13928/*
13929** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
13930** mem5.szAtom is always at least 8 and 32-bit integers are used,
13931** it is not actually possible to reach this limit.
13932*/
13933#define LOGMAX 30
13934
13935/*
13936** Masks used for mem5.aCtrl[] elements.
13937*/
13938#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
13939#define CTRL_FREE     0x20    /* True if not checked out */
13940
13941/*
13942** All of the static variables used by this module are collected
13943** into a single structure named "mem5".  This is to keep the
13944** static variables organized and to reduce namespace pollution
13945** when this module is combined with other in the amalgamation.
13946*/
13947static SQLITE_WSD struct Mem5Global {
13948  /*
13949  ** Memory available for allocation
13950  */
13951  int szAtom;      /* Smallest possible allocation in bytes */
13952  int nBlock;      /* Number of szAtom sized blocks in zPool */
13953  u8 *zPool;       /* Memory available to be allocated */
13954
13955  /*
13956  ** Mutex to control access to the memory allocation subsystem.
13957  */
13958  sqlite3_mutex *mutex;
13959
13960  /*
13961  ** Performance statistics
13962  */
13963  u64 nAlloc;         /* Total number of calls to malloc */
13964  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
13965  u64 totalExcess;    /* Total internal fragmentation */
13966  u32 currentOut;     /* Current checkout, including internal fragmentation */
13967  u32 currentCount;   /* Current number of distinct checkouts */
13968  u32 maxOut;         /* Maximum instantaneous currentOut */
13969  u32 maxCount;       /* Maximum instantaneous currentCount */
13970  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
13971
13972  /*
13973  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
13974  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
13975  ** and so forth.
13976  */
13977  int aiFreelist[LOGMAX+1];
13978
13979  /*
13980  ** Space for tracking which blocks are checked out and the size
13981  ** of each block.  One byte per block.
13982  */
13983  u8 *aCtrl;
13984
13985} mem5 = { 0 };
13986
13987/*
13988** Access the static variable through a macro for SQLITE_OMIT_WSD
13989*/
13990#define mem5 GLOBAL(struct Mem5Global, mem5)
13991
13992/*
13993** Assuming mem5.zPool is divided up into an array of Mem5Link
13994** structures, return a pointer to the idx-th such lik.
13995*/
13996#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
13997
13998/*
13999** Unlink the chunk at mem5.aPool[i] from list it is currently
14000** on.  It should be found on mem5.aiFreelist[iLogsize].
14001*/
14002static void memsys5Unlink(int i, int iLogsize){
14003  int next, prev;
14004  assert( i>=0 && i<mem5.nBlock );
14005  assert( iLogsize>=0 && iLogsize<=LOGMAX );
14006  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14007
14008  next = MEM5LINK(i)->next;
14009  prev = MEM5LINK(i)->prev;
14010  if( prev<0 ){
14011    mem5.aiFreelist[iLogsize] = next;
14012  }else{
14013    MEM5LINK(prev)->next = next;
14014  }
14015  if( next>=0 ){
14016    MEM5LINK(next)->prev = prev;
14017  }
14018}
14019
14020/*
14021** Link the chunk at mem5.aPool[i] so that is on the iLogsize
14022** free list.
14023*/
14024static void memsys5Link(int i, int iLogsize){
14025  int x;
14026  assert( sqlite3_mutex_held(mem5.mutex) );
14027  assert( i>=0 && i<mem5.nBlock );
14028  assert( iLogsize>=0 && iLogsize<=LOGMAX );
14029  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14030
14031  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
14032  MEM5LINK(i)->prev = -1;
14033  if( x>=0 ){
14034    assert( x<mem5.nBlock );
14035    MEM5LINK(x)->prev = i;
14036  }
14037  mem5.aiFreelist[iLogsize] = i;
14038}
14039
14040/*
14041** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
14042** will already be held (obtained by code in malloc.c) if
14043** sqlite3GlobalConfig.bMemStat is true.
14044*/
14045static void memsys5Enter(void){
14046  sqlite3_mutex_enter(mem5.mutex);
14047}
14048static void memsys5Leave(void){
14049  sqlite3_mutex_leave(mem5.mutex);
14050}
14051
14052/*
14053** Return the size of an outstanding allocation, in bytes.  The
14054** size returned omits the 8-byte header overhead.  This only
14055** works for chunks that are currently checked out.
14056*/
14057static int memsys5Size(void *p){
14058  int iSize = 0;
14059  if( p ){
14060    int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
14061    assert( i>=0 && i<mem5.nBlock );
14062    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
14063  }
14064  return iSize;
14065}
14066
14067/*
14068** Find the first entry on the freelist iLogsize.  Unlink that
14069** entry and return its index.
14070*/
14071static int memsys5UnlinkFirst(int iLogsize){
14072  int i;
14073  int iFirst;
14074
14075  assert( iLogsize>=0 && iLogsize<=LOGMAX );
14076  i = iFirst = mem5.aiFreelist[iLogsize];
14077  assert( iFirst>=0 );
14078  while( i>0 ){
14079    if( i<iFirst ) iFirst = i;
14080    i = MEM5LINK(i)->next;
14081  }
14082  memsys5Unlink(iFirst, iLogsize);
14083  return iFirst;
14084}
14085
14086/*
14087** Return a block of memory of at least nBytes in size.
14088** Return NULL if unable.  Return NULL if nBytes==0.
14089**
14090** The caller guarantees that nByte positive.
14091**
14092** The caller has obtained a mutex prior to invoking this
14093** routine so there is never any chance that two or more
14094** threads can be in this routine at the same time.
14095*/
14096static void *memsys5MallocUnsafe(int nByte){
14097  int i;           /* Index of a mem5.aPool[] slot */
14098  int iBin;        /* Index into mem5.aiFreelist[] */
14099  int iFullSz;     /* Size of allocation rounded up to power of 2 */
14100  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
14101
14102  /* nByte must be a positive */
14103  assert( nByte>0 );
14104
14105  /* Keep track of the maximum allocation request.  Even unfulfilled
14106  ** requests are counted */
14107  if( (u32)nByte>mem5.maxRequest ){
14108    mem5.maxRequest = nByte;
14109  }
14110
14111  /* Abort if the requested allocation size is larger than the largest
14112  ** power of two that we can represent using 32-bit signed integers.
14113  */
14114  if( nByte > 0x40000000 ){
14115    return 0;
14116  }
14117
14118  /* Round nByte up to the next valid power of two */
14119  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
14120
14121  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
14122  ** block.  If not, then split a block of the next larger power of
14123  ** two in order to create a new free block of size iLogsize.
14124  */
14125  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
14126  if( iBin>LOGMAX ) return 0;
14127  i = memsys5UnlinkFirst(iBin);
14128  while( iBin>iLogsize ){
14129    int newSize;
14130
14131    iBin--;
14132    newSize = 1 << iBin;
14133    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
14134    memsys5Link(i+newSize, iBin);
14135  }
14136  mem5.aCtrl[i] = iLogsize;
14137
14138  /* Update allocator performance statistics. */
14139  mem5.nAlloc++;
14140  mem5.totalAlloc += iFullSz;
14141  mem5.totalExcess += iFullSz - nByte;
14142  mem5.currentCount++;
14143  mem5.currentOut += iFullSz;
14144  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
14145  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
14146
14147  /* Return a pointer to the allocated memory. */
14148  return (void*)&mem5.zPool[i*mem5.szAtom];
14149}
14150
14151/*
14152** Free an outstanding memory allocation.
14153*/
14154static void memsys5FreeUnsafe(void *pOld){
14155  u32 size, iLogsize;
14156  int iBlock;
14157
14158  /* Set iBlock to the index of the block pointed to by pOld in
14159  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
14160  */
14161  iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
14162
14163  /* Check that the pointer pOld points to a valid, non-free block. */
14164  assert( iBlock>=0 && iBlock<mem5.nBlock );
14165  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
14166  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
14167
14168  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
14169  size = 1<<iLogsize;
14170  assert( iBlock+size-1<(u32)mem5.nBlock );
14171
14172  mem5.aCtrl[iBlock] |= CTRL_FREE;
14173  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
14174  assert( mem5.currentCount>0 );
14175  assert( mem5.currentOut>=(size*mem5.szAtom) );
14176  mem5.currentCount--;
14177  mem5.currentOut -= size*mem5.szAtom;
14178  assert( mem5.currentOut>0 || mem5.currentCount==0 );
14179  assert( mem5.currentCount>0 || mem5.currentOut==0 );
14180
14181  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14182  while( ALWAYS(iLogsize<LOGMAX) ){
14183    int iBuddy;
14184    if( (iBlock>>iLogsize) & 1 ){
14185      iBuddy = iBlock - size;
14186    }else{
14187      iBuddy = iBlock + size;
14188    }
14189    assert( iBuddy>=0 );
14190    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
14191    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
14192    memsys5Unlink(iBuddy, iLogsize);
14193    iLogsize++;
14194    if( iBuddy<iBlock ){
14195      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
14196      mem5.aCtrl[iBlock] = 0;
14197      iBlock = iBuddy;
14198    }else{
14199      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14200      mem5.aCtrl[iBuddy] = 0;
14201    }
14202    size *= 2;
14203  }
14204  memsys5Link(iBlock, iLogsize);
14205}
14206
14207/*
14208** Allocate nBytes of memory
14209*/
14210static void *memsys5Malloc(int nBytes){
14211  sqlite3_int64 *p = 0;
14212  if( nBytes>0 ){
14213    memsys5Enter();
14214    p = memsys5MallocUnsafe(nBytes);
14215    memsys5Leave();
14216  }
14217  return (void*)p;
14218}
14219
14220/*
14221** Free memory.
14222**
14223** The outer layer memory allocator prevents this routine from
14224** being called with pPrior==0.
14225*/
14226static void memsys5Free(void *pPrior){
14227  assert( pPrior!=0 );
14228  memsys5Enter();
14229  memsys5FreeUnsafe(pPrior);
14230  memsys5Leave();
14231}
14232
14233/*
14234** Change the size of an existing memory allocation.
14235**
14236** The outer layer memory allocator prevents this routine from
14237** being called with pPrior==0.
14238**
14239** nBytes is always a value obtained from a prior call to
14240** memsys5Round().  Hence nBytes is always a non-negative power
14241** of two.  If nBytes==0 that means that an oversize allocation
14242** (an allocation larger than 0x40000000) was requested and this
14243** routine should return 0 without freeing pPrior.
14244*/
14245static void *memsys5Realloc(void *pPrior, int nBytes){
14246  int nOld;
14247  void *p;
14248  assert( pPrior!=0 );
14249  assert( (nBytes&(nBytes-1))==0 );
14250  assert( nBytes>=0 );
14251  if( nBytes==0 ){
14252    return 0;
14253  }
14254  nOld = memsys5Size(pPrior);
14255  if( nBytes<=nOld ){
14256    return pPrior;
14257  }
14258  memsys5Enter();
14259  p = memsys5MallocUnsafe(nBytes);
14260  if( p ){
14261    memcpy(p, pPrior, nOld);
14262    memsys5FreeUnsafe(pPrior);
14263  }
14264  memsys5Leave();
14265  return p;
14266}
14267
14268/*
14269** Round up a request size to the next valid allocation size.  If
14270** the allocation is too large to be handled by this allocation system,
14271** return 0.
14272**
14273** All allocations must be a power of two and must be expressed by a
14274** 32-bit signed integer.  Hence the largest allocation is 0x40000000
14275** or 1073741824 bytes.
14276*/
14277static int memsys5Roundup(int n){
14278  int iFullSz;
14279  if( n > 0x40000000 ) return 0;
14280  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
14281  return iFullSz;
14282}
14283
14284/*
14285** Return the ceiling of the logarithm base 2 of iValue.
14286**
14287** Examples:   memsys5Log(1) -> 0
14288**             memsys5Log(2) -> 1
14289**             memsys5Log(4) -> 2
14290**             memsys5Log(5) -> 3
14291**             memsys5Log(8) -> 3
14292**             memsys5Log(9) -> 4
14293*/
14294static int memsys5Log(int iValue){
14295  int iLog;
14296  for(iLog=0; (1<<iLog)<iValue; iLog++);
14297  return iLog;
14298}
14299
14300/*
14301** Initialize the memory allocator.
14302**
14303** This routine is not threadsafe.  The caller must be holding a mutex
14304** to prevent multiple threads from entering at the same time.
14305*/
14306static int memsys5Init(void *NotUsed){
14307  int ii;            /* Loop counter */
14308  int nByte;         /* Number of bytes of memory available to this allocator */
14309  u8 *zByte;         /* Memory usable by this allocator */
14310  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
14311  int iOffset;       /* An offset into mem5.aCtrl[] */
14312
14313  UNUSED_PARAMETER(NotUsed);
14314
14315  /* For the purposes of this routine, disable the mutex */
14316  mem5.mutex = 0;
14317
14318  /* The size of a Mem5Link object must be a power of two.  Verify that
14319  ** this is case.
14320  */
14321  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
14322
14323  nByte = sqlite3GlobalConfig.nHeap;
14324  zByte = (u8*)sqlite3GlobalConfig.pHeap;
14325  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
14326
14327  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
14328  mem5.szAtom = (1<<nMinLog);
14329  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
14330    mem5.szAtom = mem5.szAtom << 1;
14331  }
14332
14333  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
14334  mem5.zPool = zByte;
14335  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
14336
14337  for(ii=0; ii<=LOGMAX; ii++){
14338    mem5.aiFreelist[ii] = -1;
14339  }
14340
14341  iOffset = 0;
14342  for(ii=LOGMAX; ii>=0; ii--){
14343    int nAlloc = (1<<ii);
14344    if( (iOffset+nAlloc)<=mem5.nBlock ){
14345      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
14346      memsys5Link(iOffset, ii);
14347      iOffset += nAlloc;
14348    }
14349    assert((iOffset+nAlloc)>mem5.nBlock);
14350  }
14351
14352  /* If a mutex is required for normal operation, allocate one */
14353  if( sqlite3GlobalConfig.bMemstat==0 ){
14354    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14355  }
14356
14357  return SQLITE_OK;
14358}
14359
14360/*
14361** Deinitialize this module.
14362*/
14363static void memsys5Shutdown(void *NotUsed){
14364  UNUSED_PARAMETER(NotUsed);
14365  mem5.mutex = 0;
14366  return;
14367}
14368
14369#ifdef SQLITE_TEST
14370/*
14371** Open the file indicated and write a log of all unfreed memory
14372** allocations into that log.
14373*/
14374SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
14375  FILE *out;
14376  int i, j, n;
14377  int nMinLog;
14378
14379  if( zFilename==0 || zFilename[0]==0 ){
14380    out = stdout;
14381  }else{
14382    out = fopen(zFilename, "w");
14383    if( out==0 ){
14384      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14385                      zFilename);
14386      return;
14387    }
14388  }
14389  memsys5Enter();
14390  nMinLog = memsys5Log(mem5.szAtom);
14391  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
14392    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
14393    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
14394  }
14395  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
14396  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
14397  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
14398  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
14399  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
14400  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
14401  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
14402  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
14403  memsys5Leave();
14404  if( out==stdout ){
14405    fflush(stdout);
14406  }else{
14407    fclose(out);
14408  }
14409}
14410#endif
14411
14412/*
14413** This routine is the only routine in this file with external
14414** linkage. It returns a pointer to a static sqlite3_mem_methods
14415** struct populated with the memsys5 methods.
14416*/
14417SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
14418  static const sqlite3_mem_methods memsys5Methods = {
14419     memsys5Malloc,
14420     memsys5Free,
14421     memsys5Realloc,
14422     memsys5Size,
14423     memsys5Roundup,
14424     memsys5Init,
14425     memsys5Shutdown,
14426     0
14427  };
14428  return &memsys5Methods;
14429}
14430
14431#endif /* SQLITE_ENABLE_MEMSYS5 */
14432
14433/************** End of mem5.c ************************************************/
14434/************** Begin file mutex.c *******************************************/
14435/*
14436** 2007 August 14
14437**
14438** The author disclaims copyright to this source code.  In place of
14439** a legal notice, here is a blessing:
14440**
14441**    May you do good and not evil.
14442**    May you find forgiveness for yourself and forgive others.
14443**    May you share freely, never taking more than you give.
14444**
14445*************************************************************************
14446** This file contains the C functions that implement mutexes.
14447**
14448** This file contains code that is common across all mutex implementations.
14449*/
14450
14451#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
14452/*
14453** For debugging purposes, record when the mutex subsystem is initialized
14454** and uninitialized so that we can assert() if there is an attempt to
14455** allocate a mutex while the system is uninitialized.
14456*/
14457static SQLITE_WSD int mutexIsInit = 0;
14458#endif /* SQLITE_DEBUG */
14459
14460
14461#ifndef SQLITE_MUTEX_OMIT
14462/*
14463** Initialize the mutex system.
14464*/
14465SQLITE_PRIVATE int sqlite3MutexInit(void){
14466  int rc = SQLITE_OK;
14467  if( sqlite3GlobalConfig.bCoreMutex ){
14468    if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
14469      /* If the xMutexAlloc method has not been set, then the user did not
14470      ** install a mutex implementation via sqlite3_config() prior to
14471      ** sqlite3_initialize() being called. This block copies pointers to
14472      ** the default implementation into the sqlite3GlobalConfig structure.
14473      */
14474      sqlite3_mutex_methods *pFrom = sqlite3DefaultMutex();
14475      sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
14476
14477      memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
14478      memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
14479             sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
14480      pTo->xMutexAlloc = pFrom->xMutexAlloc;
14481    }
14482    rc = sqlite3GlobalConfig.mutex.xMutexInit();
14483  }
14484
14485#ifdef SQLITE_DEBUG
14486  GLOBAL(int, mutexIsInit) = 1;
14487#endif
14488
14489  return rc;
14490}
14491
14492/*
14493** Shutdown the mutex system. This call frees resources allocated by
14494** sqlite3MutexInit().
14495*/
14496SQLITE_PRIVATE int sqlite3MutexEnd(void){
14497  int rc = SQLITE_OK;
14498  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
14499    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
14500  }
14501
14502#ifdef SQLITE_DEBUG
14503  GLOBAL(int, mutexIsInit) = 0;
14504#endif
14505
14506  return rc;
14507}
14508
14509/*
14510** Retrieve a pointer to a static mutex or allocate a new dynamic one.
14511*/
14512SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
14513#ifndef SQLITE_OMIT_AUTOINIT
14514  if( sqlite3_initialize() ) return 0;
14515#endif
14516  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14517}
14518
14519SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
14520  if( !sqlite3GlobalConfig.bCoreMutex ){
14521    return 0;
14522  }
14523  assert( GLOBAL(int, mutexIsInit) );
14524  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14525}
14526
14527/*
14528** Free a dynamic mutex.
14529*/
14530SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
14531  if( p ){
14532    sqlite3GlobalConfig.mutex.xMutexFree(p);
14533  }
14534}
14535
14536/*
14537** Obtain the mutex p. If some other thread already has the mutex, block
14538** until it can be obtained.
14539*/
14540SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
14541  if( p ){
14542    sqlite3GlobalConfig.mutex.xMutexEnter(p);
14543  }
14544}
14545
14546/*
14547** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
14548** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
14549*/
14550SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
14551  int rc = SQLITE_OK;
14552  if( p ){
14553    return sqlite3GlobalConfig.mutex.xMutexTry(p);
14554  }
14555  return rc;
14556}
14557
14558/*
14559** The sqlite3_mutex_leave() routine exits a mutex that was previously
14560** entered by the same thread.  The behavior is undefined if the mutex
14561** is not currently entered. If a NULL pointer is passed as an argument
14562** this function is a no-op.
14563*/
14564SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
14565  if( p ){
14566    sqlite3GlobalConfig.mutex.xMutexLeave(p);
14567  }
14568}
14569
14570#ifndef NDEBUG
14571/*
14572** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14573** intended for use inside assert() statements.
14574*/
14575SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
14576  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
14577}
14578SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
14579  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
14580}
14581#endif
14582
14583#endif /* SQLITE_MUTEX_OMIT */
14584
14585/************** End of mutex.c ***********************************************/
14586/************** Begin file mutex_noop.c **************************************/
14587/*
14588** 2008 October 07
14589**
14590** The author disclaims copyright to this source code.  In place of
14591** a legal notice, here is a blessing:
14592**
14593**    May you do good and not evil.
14594**    May you find forgiveness for yourself and forgive others.
14595**    May you share freely, never taking more than you give.
14596**
14597*************************************************************************
14598** This file contains the C functions that implement mutexes.
14599**
14600** This implementation in this file does not provide any mutual
14601** exclusion and is thus suitable for use only in applications
14602** that use SQLite in a single thread.  The routines defined
14603** here are place-holders.  Applications can substitute working
14604** mutex routines at start-time using the
14605**
14606**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
14607**
14608** interface.
14609**
14610** If compiled with SQLITE_DEBUG, then additional logic is inserted
14611** that does error checking on mutexes to make sure they are being
14612** called correctly.
14613*/
14614
14615
14616#if defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG)
14617/*
14618** Stub routines for all mutex methods.
14619**
14620** This routines provide no mutual exclusion or error checking.
14621*/
14622static int noopMutexHeld(sqlite3_mutex *p){ return 1; }
14623static int noopMutexNotheld(sqlite3_mutex *p){ return 1; }
14624static int noopMutexInit(void){ return SQLITE_OK; }
14625static int noopMutexEnd(void){ return SQLITE_OK; }
14626static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; }
14627static void noopMutexFree(sqlite3_mutex *p){ return; }
14628static void noopMutexEnter(sqlite3_mutex *p){ return; }
14629static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; }
14630static void noopMutexLeave(sqlite3_mutex *p){ return; }
14631
14632SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14633  static sqlite3_mutex_methods sMutex = {
14634    noopMutexInit,
14635    noopMutexEnd,
14636    noopMutexAlloc,
14637    noopMutexFree,
14638    noopMutexEnter,
14639    noopMutexTry,
14640    noopMutexLeave,
14641
14642    noopMutexHeld,
14643    noopMutexNotheld
14644  };
14645
14646  return &sMutex;
14647}
14648#endif /* defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG) */
14649
14650#if defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG)
14651/*
14652** In this implementation, error checking is provided for testing
14653** and debugging purposes.  The mutexes still do not provide any
14654** mutual exclusion.
14655*/
14656
14657/*
14658** The mutex object
14659*/
14660struct sqlite3_mutex {
14661  int id;     /* The mutex type */
14662  int cnt;    /* Number of entries without a matching leave */
14663};
14664
14665/*
14666** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14667** intended for use inside assert() statements.
14668*/
14669static int debugMutexHeld(sqlite3_mutex *p){
14670  return p==0 || p->cnt>0;
14671}
14672static int debugMutexNotheld(sqlite3_mutex *p){
14673  return p==0 || p->cnt==0;
14674}
14675
14676/*
14677** Initialize and deinitialize the mutex subsystem.
14678*/
14679static int debugMutexInit(void){ return SQLITE_OK; }
14680static int debugMutexEnd(void){ return SQLITE_OK; }
14681
14682/*
14683** The sqlite3_mutex_alloc() routine allocates a new
14684** mutex and returns a pointer to it.  If it returns NULL
14685** that means that a mutex could not be allocated.
14686*/
14687static sqlite3_mutex *debugMutexAlloc(int id){
14688  static sqlite3_mutex aStatic[6];
14689  sqlite3_mutex *pNew = 0;
14690  switch( id ){
14691    case SQLITE_MUTEX_FAST:
14692    case SQLITE_MUTEX_RECURSIVE: {
14693      pNew = sqlite3Malloc(sizeof(*pNew));
14694      if( pNew ){
14695        pNew->id = id;
14696        pNew->cnt = 0;
14697      }
14698      break;
14699    }
14700    default: {
14701      assert( id-2 >= 0 );
14702      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
14703      pNew = &aStatic[id-2];
14704      pNew->id = id;
14705      break;
14706    }
14707  }
14708  return pNew;
14709}
14710
14711/*
14712** This routine deallocates a previously allocated mutex.
14713*/
14714static void debugMutexFree(sqlite3_mutex *p){
14715  assert( p->cnt==0 );
14716  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
14717  sqlite3_free(p);
14718}
14719
14720/*
14721** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
14722** to enter a mutex.  If another thread is already within the mutex,
14723** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
14724** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
14725** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
14726** be entered multiple times by the same thread.  In such cases the,
14727** mutex must be exited an equal number of times before another thread
14728** can enter.  If the same thread tries to enter any other kind of mutex
14729** more than once, the behavior is undefined.
14730*/
14731static void debugMutexEnter(sqlite3_mutex *p){
14732  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14733  p->cnt++;
14734}
14735static int debugMutexTry(sqlite3_mutex *p){
14736  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14737  p->cnt++;
14738  return SQLITE_OK;
14739}
14740
14741/*
14742** The sqlite3_mutex_leave() routine exits a mutex that was
14743** previously entered by the same thread.  The behavior
14744** is undefined if the mutex is not currently entered or
14745** is not currently allocated.  SQLite will never do either.
14746*/
14747static void debugMutexLeave(sqlite3_mutex *p){
14748  assert( debugMutexHeld(p) );
14749  p->cnt--;
14750  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14751}
14752
14753SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14754  static sqlite3_mutex_methods sMutex = {
14755    debugMutexInit,
14756    debugMutexEnd,
14757    debugMutexAlloc,
14758    debugMutexFree,
14759    debugMutexEnter,
14760    debugMutexTry,
14761    debugMutexLeave,
14762
14763    debugMutexHeld,
14764    debugMutexNotheld
14765  };
14766
14767  return &sMutex;
14768}
14769#endif /* defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG) */
14770
14771/************** End of mutex_noop.c ******************************************/
14772/************** Begin file mutex_os2.c ***************************************/
14773/*
14774** 2007 August 28
14775**
14776** The author disclaims copyright to this source code.  In place of
14777** a legal notice, here is a blessing:
14778**
14779**    May you do good and not evil.
14780**    May you find forgiveness for yourself and forgive others.
14781**    May you share freely, never taking more than you give.
14782**
14783*************************************************************************
14784** This file contains the C functions that implement mutexes for OS/2
14785*/
14786
14787/*
14788** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
14789** See the mutex.h file for details.
14790*/
14791#ifdef SQLITE_MUTEX_OS2
14792
14793/********************** OS/2 Mutex Implementation **********************
14794**
14795** This implementation of mutexes is built using the OS/2 API.
14796*/
14797
14798/*
14799** The mutex object
14800** Each recursive mutex is an instance of the following structure.
14801*/
14802struct sqlite3_mutex {
14803  HMTX mutex;       /* Mutex controlling the lock */
14804  int  id;          /* Mutex type */
14805  int  nRef;        /* Number of references */
14806  TID  owner;       /* Thread holding this mutex */
14807};
14808
14809#define OS2_MUTEX_INITIALIZER   0,0,0,0
14810
14811/*
14812** Initialize and deinitialize the mutex subsystem.
14813*/
14814static int os2MutexInit(void){ return SQLITE_OK; }
14815static int os2MutexEnd(void){ return SQLITE_OK; }
14816
14817/*
14818** The sqlite3_mutex_alloc() routine allocates a new
14819** mutex and returns a pointer to it.  If it returns NULL
14820** that means that a mutex could not be allocated.
14821** SQLite will unwind its stack and return an error.  The argument
14822** to sqlite3_mutex_alloc() is one of these integer constants:
14823**
14824** <ul>
14825** <li>  SQLITE_MUTEX_FAST               0
14826** <li>  SQLITE_MUTEX_RECURSIVE          1
14827** <li>  SQLITE_MUTEX_STATIC_MASTER      2
14828** <li>  SQLITE_MUTEX_STATIC_MEM         3
14829** <li>  SQLITE_MUTEX_STATIC_PRNG        4
14830** </ul>
14831**
14832** The first two constants cause sqlite3_mutex_alloc() to create
14833** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
14834** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
14835** The mutex implementation does not need to make a distinction
14836** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
14837** not want to.  But SQLite will only request a recursive mutex in
14838** cases where it really needs one.  If a faster non-recursive mutex
14839** implementation is available on the host platform, the mutex subsystem
14840** might return such a mutex in response to SQLITE_MUTEX_FAST.
14841**
14842** The other allowed parameters to sqlite3_mutex_alloc() each return
14843** a pointer to a static preexisting mutex.  Three static mutexes are
14844** used by the current version of SQLite.  Future versions of SQLite
14845** may add additional static mutexes.  Static mutexes are for internal
14846** use by SQLite only.  Applications that use SQLite mutexes should
14847** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
14848** SQLITE_MUTEX_RECURSIVE.
14849**
14850** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
14851** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
14852** returns a different mutex on every call.  But for the static
14853** mutex types, the same mutex is returned on every call that has
14854** the same type number.
14855*/
14856static sqlite3_mutex *os2MutexAlloc(int iType){
14857  sqlite3_mutex *p = NULL;
14858  switch( iType ){
14859    case SQLITE_MUTEX_FAST:
14860    case SQLITE_MUTEX_RECURSIVE: {
14861      p = sqlite3MallocZero( sizeof(*p) );
14862      if( p ){
14863        p->id = iType;
14864        if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
14865          sqlite3_free( p );
14866          p = NULL;
14867        }
14868      }
14869      break;
14870    }
14871    default: {
14872      static volatile int isInit = 0;
14873      static sqlite3_mutex staticMutexes[] = {
14874        { OS2_MUTEX_INITIALIZER, },
14875        { OS2_MUTEX_INITIALIZER, },
14876        { OS2_MUTEX_INITIALIZER, },
14877        { OS2_MUTEX_INITIALIZER, },
14878        { OS2_MUTEX_INITIALIZER, },
14879        { OS2_MUTEX_INITIALIZER, },
14880      };
14881      if ( !isInit ){
14882        APIRET rc;
14883        PTIB ptib;
14884        PPIB ppib;
14885        HMTX mutex;
14886        char name[32];
14887        DosGetInfoBlocks( &ptib, &ppib );
14888        sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
14889                          ppib->pib_ulpid );
14890        while( !isInit ){
14891          mutex = 0;
14892          rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
14893          if( rc == NO_ERROR ){
14894            unsigned int i;
14895            if( !isInit ){
14896              for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
14897                DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
14898              }
14899              isInit = 1;
14900            }
14901            DosCloseMutexSem( mutex );
14902          }else if( rc == ERROR_DUPLICATE_NAME ){
14903            DosSleep( 1 );
14904          }else{
14905            return p;
14906          }
14907        }
14908      }
14909      assert( iType-2 >= 0 );
14910      assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
14911      p = &staticMutexes[iType-2];
14912      p->id = iType;
14913      break;
14914    }
14915  }
14916  return p;
14917}
14918
14919
14920/*
14921** This routine deallocates a previously allocated mutex.
14922** SQLite is careful to deallocate every mutex that it allocates.
14923*/
14924static void os2MutexFree(sqlite3_mutex *p){
14925  if( p==0 ) return;
14926  assert( p->nRef==0 );
14927  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
14928  DosCloseMutexSem( p->mutex );
14929  sqlite3_free( p );
14930}
14931
14932#ifdef SQLITE_DEBUG
14933/*
14934** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14935** intended for use inside assert() statements.
14936*/
14937static int os2MutexHeld(sqlite3_mutex *p){
14938  TID tid;
14939  PID pid;
14940  ULONG ulCount;
14941  PTIB ptib;
14942  if( p!=0 ) {
14943    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
14944  } else {
14945    DosGetInfoBlocks(&ptib, NULL);
14946    tid = ptib->tib_ptib2->tib2_ultid;
14947  }
14948  return p==0 || (p->nRef!=0 && p->owner==tid);
14949}
14950static int os2MutexNotheld(sqlite3_mutex *p){
14951  TID tid;
14952  PID pid;
14953  ULONG ulCount;
14954  PTIB ptib;
14955  if( p!= 0 ) {
14956    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
14957  } else {
14958    DosGetInfoBlocks(&ptib, NULL);
14959    tid = ptib->tib_ptib2->tib2_ultid;
14960  }
14961  return p==0 || p->nRef==0 || p->owner!=tid;
14962}
14963#endif
14964
14965/*
14966** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
14967** to enter a mutex.  If another thread is already within the mutex,
14968** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
14969** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
14970** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
14971** be entered multiple times by the same thread.  In such cases the,
14972** mutex must be exited an equal number of times before another thread
14973** can enter.  If the same thread tries to enter any other kind of mutex
14974** more than once, the behavior is undefined.
14975*/
14976static void os2MutexEnter(sqlite3_mutex *p){
14977  TID tid;
14978  PID holder1;
14979  ULONG holder2;
14980  if( p==0 ) return;
14981  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
14982  DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
14983  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14984  p->owner = tid;
14985  p->nRef++;
14986}
14987static int os2MutexTry(sqlite3_mutex *p){
14988  int rc;
14989  TID tid;
14990  PID holder1;
14991  ULONG holder2;
14992  if( p==0 ) return SQLITE_OK;
14993  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
14994  if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
14995    DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14996    p->owner = tid;
14997    p->nRef++;
14998    rc = SQLITE_OK;
14999  } else {
15000    rc = SQLITE_BUSY;
15001  }
15002
15003  return rc;
15004}
15005
15006/*
15007** The sqlite3_mutex_leave() routine exits a mutex that was
15008** previously entered by the same thread.  The behavior
15009** is undefined if the mutex is not currently entered or
15010** is not currently allocated.  SQLite will never do either.
15011*/
15012static void os2MutexLeave(sqlite3_mutex *p){
15013  TID tid;
15014  PID holder1;
15015  ULONG holder2;
15016  if( p==0 ) return;
15017  assert( p->nRef>0 );
15018  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15019  assert( p->owner==tid );
15020  p->nRef--;
15021  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15022  DosReleaseMutexSem(p->mutex);
15023}
15024
15025SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15026  static sqlite3_mutex_methods sMutex = {
15027    os2MutexInit,
15028    os2MutexEnd,
15029    os2MutexAlloc,
15030    os2MutexFree,
15031    os2MutexEnter,
15032    os2MutexTry,
15033    os2MutexLeave,
15034#ifdef SQLITE_DEBUG
15035    os2MutexHeld,
15036    os2MutexNotheld
15037#endif
15038  };
15039
15040  return &sMutex;
15041}
15042#endif /* SQLITE_MUTEX_OS2 */
15043
15044/************** End of mutex_os2.c *******************************************/
15045/************** Begin file mutex_unix.c **************************************/
15046/*
15047** 2007 August 28
15048**
15049** The author disclaims copyright to this source code.  In place of
15050** a legal notice, here is a blessing:
15051**
15052**    May you do good and not evil.
15053**    May you find forgiveness for yourself and forgive others.
15054**    May you share freely, never taking more than you give.
15055**
15056*************************************************************************
15057** This file contains the C functions that implement mutexes for pthreads
15058*/
15059
15060/*
15061** The code in this file is only used if we are compiling threadsafe
15062** under unix with pthreads.
15063**
15064** Note that this implementation requires a version of pthreads that
15065** supports recursive mutexes.
15066*/
15067#ifdef SQLITE_MUTEX_PTHREADS
15068
15069#include <pthread.h>
15070
15071
15072/*
15073** Each recursive mutex is an instance of the following structure.
15074*/
15075struct sqlite3_mutex {
15076  pthread_mutex_t mutex;     /* Mutex controlling the lock */
15077  int id;                    /* Mutex type */
15078  int nRef;                  /* Number of entrances */
15079  pthread_t owner;           /* Thread that is within this mutex */
15080#ifdef SQLITE_DEBUG
15081  int trace;                 /* True to trace changes */
15082#endif
15083};
15084#ifdef SQLITE_DEBUG
15085#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
15086#else
15087#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
15088#endif
15089
15090/*
15091** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15092** intended for use only inside assert() statements.  On some platforms,
15093** there might be race conditions that can cause these routines to
15094** deliver incorrect results.  In particular, if pthread_equal() is
15095** not an atomic operation, then these routines might delivery
15096** incorrect results.  On most platforms, pthread_equal() is a
15097** comparison of two integers and is therefore atomic.  But we are
15098** told that HPUX is not such a platform.  If so, then these routines
15099** will not always work correctly on HPUX.
15100**
15101** On those platforms where pthread_equal() is not atomic, SQLite
15102** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
15103** make sure no assert() statements are evaluated and hence these
15104** routines are never called.
15105*/
15106#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
15107static int pthreadMutexHeld(sqlite3_mutex *p){
15108  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
15109}
15110static int pthreadMutexNotheld(sqlite3_mutex *p){
15111  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
15112}
15113#endif
15114
15115/*
15116** Initialize and deinitialize the mutex subsystem.
15117*/
15118static int pthreadMutexInit(void){ return SQLITE_OK; }
15119static int pthreadMutexEnd(void){ return SQLITE_OK; }
15120
15121/*
15122** The sqlite3_mutex_alloc() routine allocates a new
15123** mutex and returns a pointer to it.  If it returns NULL
15124** that means that a mutex could not be allocated.  SQLite
15125** will unwind its stack and return an error.  The argument
15126** to sqlite3_mutex_alloc() is one of these integer constants:
15127**
15128** <ul>
15129** <li>  SQLITE_MUTEX_FAST
15130** <li>  SQLITE_MUTEX_RECURSIVE
15131** <li>  SQLITE_MUTEX_STATIC_MASTER
15132** <li>  SQLITE_MUTEX_STATIC_MEM
15133** <li>  SQLITE_MUTEX_STATIC_MEM2
15134** <li>  SQLITE_MUTEX_STATIC_PRNG
15135** <li>  SQLITE_MUTEX_STATIC_LRU
15136** <li>  SQLITE_MUTEX_STATIC_LRU2
15137** </ul>
15138**
15139** The first two constants cause sqlite3_mutex_alloc() to create
15140** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15141** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15142** The mutex implementation does not need to make a distinction
15143** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15144** not want to.  But SQLite will only request a recursive mutex in
15145** cases where it really needs one.  If a faster non-recursive mutex
15146** implementation is available on the host platform, the mutex subsystem
15147** might return such a mutex in response to SQLITE_MUTEX_FAST.
15148**
15149** The other allowed parameters to sqlite3_mutex_alloc() each return
15150** a pointer to a static preexisting mutex.  Six static mutexes are
15151** used by the current version of SQLite.  Future versions of SQLite
15152** may add additional static mutexes.  Static mutexes are for internal
15153** use by SQLite only.  Applications that use SQLite mutexes should
15154** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15155** SQLITE_MUTEX_RECURSIVE.
15156**
15157** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15158** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15159** returns a different mutex on every call.  But for the static
15160** mutex types, the same mutex is returned on every call that has
15161** the same type number.
15162*/
15163static sqlite3_mutex *pthreadMutexAlloc(int iType){
15164  static sqlite3_mutex staticMutexes[] = {
15165    SQLITE3_MUTEX_INITIALIZER,
15166    SQLITE3_MUTEX_INITIALIZER,
15167    SQLITE3_MUTEX_INITIALIZER,
15168    SQLITE3_MUTEX_INITIALIZER,
15169    SQLITE3_MUTEX_INITIALIZER,
15170    SQLITE3_MUTEX_INITIALIZER
15171  };
15172  sqlite3_mutex *p;
15173  switch( iType ){
15174    case SQLITE_MUTEX_RECURSIVE: {
15175      p = sqlite3MallocZero( sizeof(*p) );
15176      if( p ){
15177#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15178        /* If recursive mutexes are not available, we will have to
15179        ** build our own.  See below. */
15180        pthread_mutex_init(&p->mutex, 0);
15181#else
15182        /* Use a recursive mutex if it is available */
15183        pthread_mutexattr_t recursiveAttr;
15184        pthread_mutexattr_init(&recursiveAttr);
15185        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
15186        pthread_mutex_init(&p->mutex, &recursiveAttr);
15187        pthread_mutexattr_destroy(&recursiveAttr);
15188#endif
15189        p->id = iType;
15190      }
15191      break;
15192    }
15193    case SQLITE_MUTEX_FAST: {
15194      p = sqlite3MallocZero( sizeof(*p) );
15195      if( p ){
15196        p->id = iType;
15197        pthread_mutex_init(&p->mutex, 0);
15198      }
15199      break;
15200    }
15201    default: {
15202      assert( iType-2 >= 0 );
15203      assert( iType-2 < ArraySize(staticMutexes) );
15204      p = &staticMutexes[iType-2];
15205      p->id = iType;
15206      break;
15207    }
15208  }
15209  return p;
15210}
15211
15212
15213/*
15214** This routine deallocates a previously
15215** allocated mutex.  SQLite is careful to deallocate every
15216** mutex that it allocates.
15217*/
15218static void pthreadMutexFree(sqlite3_mutex *p){
15219  assert( p->nRef==0 );
15220  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15221  pthread_mutex_destroy(&p->mutex);
15222  sqlite3_free(p);
15223}
15224
15225/*
15226** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15227** to enter a mutex.  If another thread is already within the mutex,
15228** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15229** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15230** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15231** be entered multiple times by the same thread.  In such cases the,
15232** mutex must be exited an equal number of times before another thread
15233** can enter.  If the same thread tries to enter any other kind of mutex
15234** more than once, the behavior is undefined.
15235*/
15236static void pthreadMutexEnter(sqlite3_mutex *p){
15237  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15238
15239#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15240  /* If recursive mutexes are not available, then we have to grow
15241  ** our own.  This implementation assumes that pthread_equal()
15242  ** is atomic - that it cannot be deceived into thinking self
15243  ** and p->owner are equal if p->owner changes between two values
15244  ** that are not equal to self while the comparison is taking place.
15245  ** This implementation also assumes a coherent cache - that
15246  ** separate processes cannot read different values from the same
15247  ** address at the same time.  If either of these two conditions
15248  ** are not met, then the mutexes will fail and problems will result.
15249  */
15250  {
15251    pthread_t self = pthread_self();
15252    if( p->nRef>0 && pthread_equal(p->owner, self) ){
15253      p->nRef++;
15254    }else{
15255      pthread_mutex_lock(&p->mutex);
15256      assert( p->nRef==0 );
15257      p->owner = self;
15258      p->nRef = 1;
15259    }
15260  }
15261#else
15262  /* Use the built-in recursive mutexes if they are available.
15263  */
15264  pthread_mutex_lock(&p->mutex);
15265  p->owner = pthread_self();
15266  p->nRef++;
15267#endif
15268
15269#ifdef SQLITE_DEBUG
15270  if( p->trace ){
15271    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15272  }
15273#endif
15274}
15275static int pthreadMutexTry(sqlite3_mutex *p){
15276  int rc;
15277  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15278
15279#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15280  /* If recursive mutexes are not available, then we have to grow
15281  ** our own.  This implementation assumes that pthread_equal()
15282  ** is atomic - that it cannot be deceived into thinking self
15283  ** and p->owner are equal if p->owner changes between two values
15284  ** that are not equal to self while the comparison is taking place.
15285  ** This implementation also assumes a coherent cache - that
15286  ** separate processes cannot read different values from the same
15287  ** address at the same time.  If either of these two conditions
15288  ** are not met, then the mutexes will fail and problems will result.
15289  */
15290  {
15291    pthread_t self = pthread_self();
15292    if( p->nRef>0 && pthread_equal(p->owner, self) ){
15293      p->nRef++;
15294      rc = SQLITE_OK;
15295    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
15296      assert( p->nRef==0 );
15297      p->owner = self;
15298      p->nRef = 1;
15299      rc = SQLITE_OK;
15300    }else{
15301      rc = SQLITE_BUSY;
15302    }
15303  }
15304#else
15305  /* Use the built-in recursive mutexes if they are available.
15306  */
15307  if( pthread_mutex_trylock(&p->mutex)==0 ){
15308    p->owner = pthread_self();
15309    p->nRef++;
15310    rc = SQLITE_OK;
15311  }else{
15312    rc = SQLITE_BUSY;
15313  }
15314#endif
15315
15316#ifdef SQLITE_DEBUG
15317  if( rc==SQLITE_OK && p->trace ){
15318    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15319  }
15320#endif
15321  return rc;
15322}
15323
15324/*
15325** The sqlite3_mutex_leave() routine exits a mutex that was
15326** previously entered by the same thread.  The behavior
15327** is undefined if the mutex is not currently entered or
15328** is not currently allocated.  SQLite will never do either.
15329*/
15330static void pthreadMutexLeave(sqlite3_mutex *p){
15331  assert( pthreadMutexHeld(p) );
15332  p->nRef--;
15333  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15334
15335#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15336  if( p->nRef==0 ){
15337    pthread_mutex_unlock(&p->mutex);
15338  }
15339#else
15340  pthread_mutex_unlock(&p->mutex);
15341#endif
15342
15343#ifdef SQLITE_DEBUG
15344  if( p->trace ){
15345    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15346  }
15347#endif
15348}
15349
15350SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15351  static sqlite3_mutex_methods sMutex = {
15352    pthreadMutexInit,
15353    pthreadMutexEnd,
15354    pthreadMutexAlloc,
15355    pthreadMutexFree,
15356    pthreadMutexEnter,
15357    pthreadMutexTry,
15358    pthreadMutexLeave,
15359#ifdef SQLITE_DEBUG
15360    pthreadMutexHeld,
15361    pthreadMutexNotheld
15362#else
15363    0,
15364    0
15365#endif
15366  };
15367
15368  return &sMutex;
15369}
15370
15371#endif /* SQLITE_MUTEX_PTHREAD */
15372
15373/************** End of mutex_unix.c ******************************************/
15374/************** Begin file mutex_w32.c ***************************************/
15375/*
15376** 2007 August 14
15377**
15378** The author disclaims copyright to this source code.  In place of
15379** a legal notice, here is a blessing:
15380**
15381**    May you do good and not evil.
15382**    May you find forgiveness for yourself and forgive others.
15383**    May you share freely, never taking more than you give.
15384**
15385*************************************************************************
15386** This file contains the C functions that implement mutexes for win32
15387*/
15388
15389/*
15390** The code in this file is only used if we are compiling multithreaded
15391** on a win32 system.
15392*/
15393#ifdef SQLITE_MUTEX_W32
15394
15395/*
15396** Each recursive mutex is an instance of the following structure.
15397*/
15398struct sqlite3_mutex {
15399  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
15400  int id;                    /* Mutex type */
15401  int nRef;                  /* Number of enterances */
15402  DWORD owner;               /* Thread holding this mutex */
15403};
15404
15405/*
15406** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
15407** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
15408**
15409** Here is an interesting observation:  Win95, Win98, and WinME lack
15410** the LockFileEx() API.  But we can still statically link against that
15411** API as long as we don't call it win running Win95/98/ME.  A call to
15412** this routine is used to determine if the host is Win95/98/ME or
15413** WinNT/2K/XP so that we will know whether or not we can safely call
15414** the LockFileEx() API.
15415**
15416** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
15417** which is only available if your application was compiled with
15418** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
15419** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
15420** this out as well.
15421*/
15422#if 0
15423#if SQLITE_OS_WINCE
15424# define mutexIsNT()  (1)
15425#else
15426  static int mutexIsNT(void){
15427    static int osType = 0;
15428    if( osType==0 ){
15429      OSVERSIONINFO sInfo;
15430      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
15431      GetVersionEx(&sInfo);
15432      osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
15433    }
15434    return osType==2;
15435  }
15436#endif /* SQLITE_OS_WINCE */
15437#endif
15438
15439#ifdef SQLITE_DEBUG
15440/*
15441** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15442** intended for use only inside assert() statements.
15443*/
15444static int winMutexHeld(sqlite3_mutex *p){
15445  return p->nRef!=0 && p->owner==GetCurrentThreadId();
15446}
15447static int winMutexNotheld(sqlite3_mutex *p){
15448  return p->nRef==0 || p->owner!=GetCurrentThreadId();
15449}
15450#endif
15451
15452
15453/*
15454** Initialize and deinitialize the mutex subsystem.
15455*/
15456static sqlite3_mutex winMutex_staticMutexes[6];
15457static int winMutex_isInit = 0;
15458/* As winMutexInit() and winMutexEnd() are called as part
15459** of the sqlite3_initialize and sqlite3_shutdown()
15460** processing, the "interlocked" magic is probably not
15461** strictly necessary.
15462*/
15463static long winMutex_lock = 0;
15464
15465static int winMutexInit(void){
15466  /* The first to increment to 1 does actual initialization */
15467  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
15468    int i;
15469    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
15470      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
15471    }
15472    winMutex_isInit = 1;
15473  }else{
15474    /* Someone else is in the process of initing the static mutexes */
15475    while( !winMutex_isInit ){
15476      Sleep(1);
15477    }
15478  }
15479  return SQLITE_OK;
15480}
15481
15482static int winMutexEnd(void){
15483  /* The first to decrement to 0 does actual shutdown
15484  ** (which should be the last to shutdown.) */
15485  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
15486    if( winMutex_isInit==1 ){
15487      int i;
15488      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
15489        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
15490      }
15491      winMutex_isInit = 0;
15492    }
15493  }
15494  return SQLITE_OK;
15495}
15496
15497/*
15498** The sqlite3_mutex_alloc() routine allocates a new
15499** mutex and returns a pointer to it.  If it returns NULL
15500** that means that a mutex could not be allocated.  SQLite
15501** will unwind its stack and return an error.  The argument
15502** to sqlite3_mutex_alloc() is one of these integer constants:
15503**
15504** <ul>
15505** <li>  SQLITE_MUTEX_FAST
15506** <li>  SQLITE_MUTEX_RECURSIVE
15507** <li>  SQLITE_MUTEX_STATIC_MASTER
15508** <li>  SQLITE_MUTEX_STATIC_MEM
15509** <li>  SQLITE_MUTEX_STATIC_MEM2
15510** <li>  SQLITE_MUTEX_STATIC_PRNG
15511** <li>  SQLITE_MUTEX_STATIC_LRU
15512** <li>  SQLITE_MUTEX_STATIC_LRU2
15513** </ul>
15514**
15515** The first two constants cause sqlite3_mutex_alloc() to create
15516** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15517** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15518** The mutex implementation does not need to make a distinction
15519** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15520** not want to.  But SQLite will only request a recursive mutex in
15521** cases where it really needs one.  If a faster non-recursive mutex
15522** implementation is available on the host platform, the mutex subsystem
15523** might return such a mutex in response to SQLITE_MUTEX_FAST.
15524**
15525** The other allowed parameters to sqlite3_mutex_alloc() each return
15526** a pointer to a static preexisting mutex.  Six static mutexes are
15527** used by the current version of SQLite.  Future versions of SQLite
15528** may add additional static mutexes.  Static mutexes are for internal
15529** use by SQLite only.  Applications that use SQLite mutexes should
15530** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15531** SQLITE_MUTEX_RECURSIVE.
15532**
15533** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15534** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15535** returns a different mutex on every call.  But for the static
15536** mutex types, the same mutex is returned on every call that has
15537** the same type number.
15538*/
15539static sqlite3_mutex *winMutexAlloc(int iType){
15540  sqlite3_mutex *p;
15541
15542  switch( iType ){
15543    case SQLITE_MUTEX_FAST:
15544    case SQLITE_MUTEX_RECURSIVE: {
15545      p = sqlite3MallocZero( sizeof(*p) );
15546      if( p ){
15547        p->id = iType;
15548        InitializeCriticalSection(&p->mutex);
15549      }
15550      break;
15551    }
15552    default: {
15553      assert( winMutex_isInit==1 );
15554      assert( iType-2 >= 0 );
15555      assert( iType-2 < ArraySize(winMutex_staticMutexes) );
15556      p = &winMutex_staticMutexes[iType-2];
15557      p->id = iType;
15558      break;
15559    }
15560  }
15561  return p;
15562}
15563
15564
15565/*
15566** This routine deallocates a previously
15567** allocated mutex.  SQLite is careful to deallocate every
15568** mutex that it allocates.
15569*/
15570static void winMutexFree(sqlite3_mutex *p){
15571  assert( p );
15572  assert( p->nRef==0 );
15573  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15574  DeleteCriticalSection(&p->mutex);
15575  sqlite3_free(p);
15576}
15577
15578/*
15579** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15580** to enter a mutex.  If another thread is already within the mutex,
15581** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15582** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15583** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15584** be entered multiple times by the same thread.  In such cases the,
15585** mutex must be exited an equal number of times before another thread
15586** can enter.  If the same thread tries to enter any other kind of mutex
15587** more than once, the behavior is undefined.
15588*/
15589static void winMutexEnter(sqlite3_mutex *p){
15590  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15591  EnterCriticalSection(&p->mutex);
15592  p->owner = GetCurrentThreadId();
15593  p->nRef++;
15594}
15595static int winMutexTry(sqlite3_mutex *p){
15596  int rc = SQLITE_BUSY;
15597  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15598  /*
15599  ** The sqlite3_mutex_try() routine is very rarely used, and when it
15600  ** is used it is merely an optimization.  So it is OK for it to always
15601  ** fail.
15602  **
15603  ** The TryEnterCriticalSection() interface is only available on WinNT.
15604  ** And some windows compilers complain if you try to use it without
15605  ** first doing some #defines that prevent SQLite from building on Win98.
15606  ** For that reason, we will omit this optimization for now.  See
15607  ** ticket #2685.
15608  */
15609#if 0
15610  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
15611    p->owner = GetCurrentThreadId();
15612    p->nRef++;
15613    rc = SQLITE_OK;
15614  }
15615#else
15616  UNUSED_PARAMETER(p);
15617#endif
15618  return rc;
15619}
15620
15621/*
15622** The sqlite3_mutex_leave() routine exits a mutex that was
15623** previously entered by the same thread.  The behavior
15624** is undefined if the mutex is not currently entered or
15625** is not currently allocated.  SQLite will never do either.
15626*/
15627static void winMutexLeave(sqlite3_mutex *p){
15628  assert( p->nRef>0 );
15629  assert( p->owner==GetCurrentThreadId() );
15630  p->nRef--;
15631  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15632  LeaveCriticalSection(&p->mutex);
15633}
15634
15635SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15636  static sqlite3_mutex_methods sMutex = {
15637    winMutexInit,
15638    winMutexEnd,
15639    winMutexAlloc,
15640    winMutexFree,
15641    winMutexEnter,
15642    winMutexTry,
15643    winMutexLeave,
15644#ifdef SQLITE_DEBUG
15645    winMutexHeld,
15646    winMutexNotheld
15647#else
15648    0,
15649    0
15650#endif
15651  };
15652
15653  return &sMutex;
15654}
15655#endif /* SQLITE_MUTEX_W32 */
15656
15657/************** End of mutex_w32.c *******************************************/
15658/************** Begin file malloc.c ******************************************/
15659/*
15660** 2001 September 15
15661**
15662** The author disclaims copyright to this source code.  In place of
15663** a legal notice, here is a blessing:
15664**
15665**    May you do good and not evil.
15666**    May you find forgiveness for yourself and forgive others.
15667**    May you share freely, never taking more than you give.
15668**
15669*************************************************************************
15670**
15671** Memory allocation functions used throughout sqlite.
15672*/
15673
15674/*
15675** This routine runs when the memory allocator sees that the
15676** total memory allocation is about to exceed the soft heap
15677** limit.
15678*/
15679static void softHeapLimitEnforcer(
15680  void *NotUsed,
15681  sqlite3_int64 NotUsed2,
15682  int allocSize
15683){
15684  UNUSED_PARAMETER2(NotUsed, NotUsed2);
15685  sqlite3_release_memory(allocSize);
15686}
15687
15688/*
15689** Set the soft heap-size limit for the library. Passing a zero or
15690** negative value indicates no limit.
15691*/
15692SQLITE_API void sqlite3_soft_heap_limit(int n){
15693  sqlite3_uint64 iLimit;
15694  int overage;
15695  if( n<0 ){
15696    iLimit = 0;
15697  }else{
15698    iLimit = n;
15699  }
15700#ifndef SQLITE_OMIT_AUTOINIT
15701  sqlite3_initialize();
15702#endif
15703  if( iLimit>0 ){
15704    sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
15705  }else{
15706    sqlite3MemoryAlarm(0, 0, 0);
15707  }
15708  overage = (int)(sqlite3_memory_used() - (i64)n);
15709  if( overage>0 ){
15710    sqlite3_release_memory(overage);
15711  }
15712}
15713
15714/*
15715** Attempt to release up to n bytes of non-essential memory currently
15716** held by SQLite. An example of non-essential memory is memory used to
15717** cache database pages that are not currently in use.
15718*/
15719SQLITE_API int sqlite3_release_memory(int n){
15720#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
15721  int nRet = 0;
15722  nRet += sqlite3PcacheReleaseMemory(n-nRet);
15723  return nRet;
15724#else
15725  UNUSED_PARAMETER(n);
15726  return SQLITE_OK;
15727#endif
15728}
15729
15730/*
15731** State information local to the memory allocation subsystem.
15732*/
15733static SQLITE_WSD struct Mem0Global {
15734  /* Number of free pages for scratch and page-cache memory */
15735  u32 nScratchFree;
15736  u32 nPageFree;
15737
15738  sqlite3_mutex *mutex;         /* Mutex to serialize access */
15739
15740  /*
15741  ** The alarm callback and its arguments.  The mem0.mutex lock will
15742  ** be held while the callback is running.  Recursive calls into
15743  ** the memory subsystem are allowed, but no new callbacks will be
15744  ** issued.
15745  */
15746  sqlite3_int64 alarmThreshold;
15747  void (*alarmCallback)(void*, sqlite3_int64,int);
15748  void *alarmArg;
15749
15750  /*
15751  ** Pointers to the end of sqlite3GlobalConfig.pScratch and
15752  ** sqlite3GlobalConfig.pPage to a block of memory that records
15753  ** which pages are available.
15754  */
15755  u32 *aScratchFree;
15756  u32 *aPageFree;
15757} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
15758
15759#define mem0 GLOBAL(struct Mem0Global, mem0)
15760
15761/*
15762** Initialize the memory allocation subsystem.
15763*/
15764SQLITE_PRIVATE int sqlite3MallocInit(void){
15765  if( sqlite3GlobalConfig.m.xMalloc==0 ){
15766    sqlite3MemSetDefault();
15767  }
15768  memset(&mem0, 0, sizeof(mem0));
15769  if( sqlite3GlobalConfig.bCoreMutex ){
15770    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15771  }
15772  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
15773      && sqlite3GlobalConfig.nScratch>=0 ){
15774    int i;
15775    sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
15776    mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
15777                  [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
15778    for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
15779    mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
15780  }else{
15781    sqlite3GlobalConfig.pScratch = 0;
15782    sqlite3GlobalConfig.szScratch = 0;
15783  }
15784  if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
15785      && sqlite3GlobalConfig.nPage>=1 ){
15786    int i;
15787    int overhead;
15788    int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
15789    int n = sqlite3GlobalConfig.nPage;
15790    overhead = (4*n + sz - 1)/sz;
15791    sqlite3GlobalConfig.nPage -= overhead;
15792    mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
15793                  [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
15794    for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
15795    mem0.nPageFree = sqlite3GlobalConfig.nPage;
15796  }else{
15797    sqlite3GlobalConfig.pPage = 0;
15798    sqlite3GlobalConfig.szPage = 0;
15799  }
15800  return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
15801}
15802
15803/*
15804** Deinitialize the memory allocation subsystem.
15805*/
15806SQLITE_PRIVATE void sqlite3MallocEnd(void){
15807  if( sqlite3GlobalConfig.m.xShutdown ){
15808    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
15809  }
15810  memset(&mem0, 0, sizeof(mem0));
15811}
15812
15813/*
15814** Return the amount of memory currently checked out.
15815*/
15816SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
15817  int n, mx;
15818  sqlite3_int64 res;
15819  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
15820  res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
15821  return res;
15822}
15823
15824/*
15825** Return the maximum amount of memory that has ever been
15826** checked out since either the beginning of this process
15827** or since the most recent reset.
15828*/
15829SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
15830  int n, mx;
15831  sqlite3_int64 res;
15832  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
15833  res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
15834  return res;
15835}
15836
15837/*
15838** Change the alarm callback
15839*/
15840SQLITE_PRIVATE int sqlite3MemoryAlarm(
15841  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
15842  void *pArg,
15843  sqlite3_int64 iThreshold
15844){
15845  sqlite3_mutex_enter(mem0.mutex);
15846  mem0.alarmCallback = xCallback;
15847  mem0.alarmArg = pArg;
15848  mem0.alarmThreshold = iThreshold;
15849  sqlite3_mutex_leave(mem0.mutex);
15850  return SQLITE_OK;
15851}
15852
15853#ifndef SQLITE_OMIT_DEPRECATED
15854/*
15855** Deprecated external interface.  Internal/core SQLite code
15856** should call sqlite3MemoryAlarm.
15857*/
15858SQLITE_API int sqlite3_memory_alarm(
15859  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
15860  void *pArg,
15861  sqlite3_int64 iThreshold
15862){
15863  return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
15864}
15865#endif
15866
15867/*
15868** Trigger the alarm
15869*/
15870static void sqlite3MallocAlarm(int nByte){
15871  void (*xCallback)(void*,sqlite3_int64,int);
15872  sqlite3_int64 nowUsed;
15873  void *pArg;
15874  if( mem0.alarmCallback==0 ) return;
15875  xCallback = mem0.alarmCallback;
15876  nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
15877  pArg = mem0.alarmArg;
15878  mem0.alarmCallback = 0;
15879  sqlite3_mutex_leave(mem0.mutex);
15880  xCallback(pArg, nowUsed, nByte);
15881  sqlite3_mutex_enter(mem0.mutex);
15882  mem0.alarmCallback = xCallback;
15883  mem0.alarmArg = pArg;
15884}
15885
15886/*
15887** Do a memory allocation with statistics and alarms.  Assume the
15888** lock is already held.
15889*/
15890static int mallocWithAlarm(int n, void **pp){
15891  int nFull;
15892  void *p;
15893  assert( sqlite3_mutex_held(mem0.mutex) );
15894  nFull = sqlite3GlobalConfig.m.xRoundup(n);
15895  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
15896  if( mem0.alarmCallback!=0 ){
15897    int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
15898    if( nUsed+nFull >= mem0.alarmThreshold ){
15899      sqlite3MallocAlarm(nFull);
15900    }
15901  }
15902  p = sqlite3GlobalConfig.m.xMalloc(nFull);
15903  if( p==0 && mem0.alarmCallback ){
15904    sqlite3MallocAlarm(nFull);
15905    p = sqlite3GlobalConfig.m.xMalloc(nFull);
15906  }
15907  if( p ){
15908    nFull = sqlite3MallocSize(p);
15909    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
15910  }
15911  *pp = p;
15912  return nFull;
15913}
15914
15915/*
15916** Allocate memory.  This routine is like sqlite3_malloc() except that it
15917** assumes the memory subsystem has already been initialized.
15918*/
15919SQLITE_PRIVATE void *sqlite3Malloc(int n){
15920  void *p;
15921  if( n<=0 || n>=0x7fffff00 ){
15922    /* A memory allocation of a number of bytes which is near the maximum
15923    ** signed integer value might cause an integer overflow inside of the
15924    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
15925    ** 255 bytes of overhead.  SQLite itself will never use anything near
15926    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
15927    p = 0;
15928  }else if( sqlite3GlobalConfig.bMemstat ){
15929    sqlite3_mutex_enter(mem0.mutex);
15930    mallocWithAlarm(n, &p);
15931    sqlite3_mutex_leave(mem0.mutex);
15932  }else{
15933    p = sqlite3GlobalConfig.m.xMalloc(n);
15934  }
15935  return p;
15936}
15937
15938/*
15939** This version of the memory allocation is for use by the application.
15940** First make sure the memory subsystem is initialized, then do the
15941** allocation.
15942*/
15943SQLITE_API void *sqlite3_malloc(int n){
15944#ifndef SQLITE_OMIT_AUTOINIT
15945  if( sqlite3_initialize() ) return 0;
15946#endif
15947  return sqlite3Malloc(n);
15948}
15949
15950/*
15951** Each thread may only have a single outstanding allocation from
15952** xScratchMalloc().  We verify this constraint in the single-threaded
15953** case by setting scratchAllocOut to 1 when an allocation
15954** is outstanding clearing it when the allocation is freed.
15955*/
15956#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15957static int scratchAllocOut = 0;
15958#endif
15959
15960
15961/*
15962** Allocate memory that is to be used and released right away.
15963** This routine is similar to alloca() in that it is not intended
15964** for situations where the memory might be held long-term.  This
15965** routine is intended to get memory to old large transient data
15966** structures that would not normally fit on the stack of an
15967** embedded processor.
15968*/
15969SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
15970  void *p;
15971  assert( n>0 );
15972
15973#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15974  /* Verify that no more than one scratch allocation per thread
15975  ** is outstanding at one time.  (This is only checked in the
15976  ** single-threaded case since checking in the multi-threaded case
15977  ** would be much more complicated.) */
15978  assert( scratchAllocOut==0 );
15979#endif
15980
15981  if( sqlite3GlobalConfig.szScratch<n ){
15982    goto scratch_overflow;
15983  }else{
15984    sqlite3_mutex_enter(mem0.mutex);
15985    if( mem0.nScratchFree==0 ){
15986      sqlite3_mutex_leave(mem0.mutex);
15987      goto scratch_overflow;
15988    }else{
15989      int i;
15990      i = mem0.aScratchFree[--mem0.nScratchFree];
15991      i *= sqlite3GlobalConfig.szScratch;
15992      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
15993      sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
15994      sqlite3_mutex_leave(mem0.mutex);
15995      p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
15996      assert(  (((u8*)p - (u8*)0) & 7)==0 );
15997    }
15998  }
15999#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16000  scratchAllocOut = p!=0;
16001#endif
16002
16003  return p;
16004
16005scratch_overflow:
16006  if( sqlite3GlobalConfig.bMemstat ){
16007    sqlite3_mutex_enter(mem0.mutex);
16008    sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16009    n = mallocWithAlarm(n, &p);
16010    if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
16011    sqlite3_mutex_leave(mem0.mutex);
16012  }else{
16013    p = sqlite3GlobalConfig.m.xMalloc(n);
16014  }
16015#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16016  scratchAllocOut = p!=0;
16017#endif
16018  return p;
16019}
16020SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
16021  if( p ){
16022
16023#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16024    /* Verify that no more than one scratch allocation per thread
16025    ** is outstanding at one time.  (This is only checked in the
16026    ** single-threaded case since checking in the multi-threaded case
16027    ** would be much more complicated.) */
16028    assert( scratchAllocOut==1 );
16029    scratchAllocOut = 0;
16030#endif
16031
16032    if( sqlite3GlobalConfig.pScratch==0
16033           || p<sqlite3GlobalConfig.pScratch
16034           || p>=(void*)mem0.aScratchFree ){
16035      if( sqlite3GlobalConfig.bMemstat ){
16036        int iSize = sqlite3MallocSize(p);
16037        sqlite3_mutex_enter(mem0.mutex);
16038        sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
16039        sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
16040        sqlite3GlobalConfig.m.xFree(p);
16041        sqlite3_mutex_leave(mem0.mutex);
16042      }else{
16043        sqlite3GlobalConfig.m.xFree(p);
16044      }
16045    }else{
16046      int i;
16047      i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
16048      i /= sqlite3GlobalConfig.szScratch;
16049      assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
16050      sqlite3_mutex_enter(mem0.mutex);
16051      assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
16052      mem0.aScratchFree[mem0.nScratchFree++] = i;
16053      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
16054      sqlite3_mutex_leave(mem0.mutex);
16055    }
16056  }
16057}
16058
16059/*
16060** TRUE if p is a lookaside memory allocation from db
16061*/
16062#ifndef SQLITE_OMIT_LOOKASIDE
16063static int isLookaside(sqlite3 *db, void *p){
16064  return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
16065}
16066#else
16067#define isLookaside(A,B) 0
16068#endif
16069
16070/*
16071** Return the size of a memory allocation previously obtained from
16072** sqlite3Malloc() or sqlite3_malloc().
16073*/
16074SQLITE_PRIVATE int sqlite3MallocSize(void *p){
16075  return sqlite3GlobalConfig.m.xSize(p);
16076}
16077SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
16078  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16079  if( isLookaside(db, p) ){
16080    return db->lookaside.sz;
16081  }else{
16082    return sqlite3GlobalConfig.m.xSize(p);
16083  }
16084}
16085
16086/*
16087** Free memory previously obtained from sqlite3Malloc().
16088*/
16089SQLITE_API void sqlite3_free(void *p){
16090  if( p==0 ) return;
16091  if( sqlite3GlobalConfig.bMemstat ){
16092    sqlite3_mutex_enter(mem0.mutex);
16093    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
16094    sqlite3GlobalConfig.m.xFree(p);
16095    sqlite3_mutex_leave(mem0.mutex);
16096  }else{
16097    sqlite3GlobalConfig.m.xFree(p);
16098  }
16099}
16100
16101/*
16102** Free memory that might be associated with a particular database
16103** connection.
16104*/
16105SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
16106  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16107  if( isLookaside(db, p) ){
16108    LookasideSlot *pBuf = (LookasideSlot*)p;
16109    pBuf->pNext = db->lookaside.pFree;
16110    db->lookaside.pFree = pBuf;
16111    db->lookaside.nOut--;
16112  }else{
16113    sqlite3_free(p);
16114  }
16115}
16116
16117/*
16118** Change the size of an existing memory allocation
16119*/
16120SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
16121  int nOld, nNew;
16122  void *pNew;
16123  if( pOld==0 ){
16124    return sqlite3Malloc(nBytes);
16125  }
16126  if( nBytes<=0 ){
16127    sqlite3_free(pOld);
16128    return 0;
16129  }
16130  if( nBytes>=0x7fffff00 ){
16131    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
16132    return 0;
16133  }
16134  nOld = sqlite3MallocSize(pOld);
16135  nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
16136  if( nOld==nNew ){
16137    pNew = pOld;
16138  }else if( sqlite3GlobalConfig.bMemstat ){
16139    sqlite3_mutex_enter(mem0.mutex);
16140    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
16141    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
16142          mem0.alarmThreshold ){
16143      sqlite3MallocAlarm(nNew-nOld);
16144    }
16145    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16146    if( pNew==0 && mem0.alarmCallback ){
16147      sqlite3MallocAlarm(nBytes);
16148      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16149    }
16150    if( pNew ){
16151      nNew = sqlite3MallocSize(pNew);
16152      sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
16153    }
16154    sqlite3_mutex_leave(mem0.mutex);
16155  }else{
16156    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16157  }
16158  return pNew;
16159}
16160
16161/*
16162** The public interface to sqlite3Realloc.  Make sure that the memory
16163** subsystem is initialized prior to invoking sqliteRealloc.
16164*/
16165SQLITE_API void *sqlite3_realloc(void *pOld, int n){
16166#ifndef SQLITE_OMIT_AUTOINIT
16167  if( sqlite3_initialize() ) return 0;
16168#endif
16169  return sqlite3Realloc(pOld, n);
16170}
16171
16172
16173/*
16174** Allocate and zero memory.
16175*/
16176SQLITE_PRIVATE void *sqlite3MallocZero(int n){
16177  void *p = sqlite3Malloc(n);
16178  if( p ){
16179    memset(p, 0, n);
16180  }
16181  return p;
16182}
16183
16184/*
16185** Allocate and zero memory.  If the allocation fails, make
16186** the mallocFailed flag in the connection pointer.
16187*/
16188SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
16189  void *p = sqlite3DbMallocRaw(db, n);
16190  if( p ){
16191    memset(p, 0, n);
16192  }
16193  return p;
16194}
16195
16196/*
16197** Allocate and zero memory.  If the allocation fails, make
16198** the mallocFailed flag in the connection pointer.
16199**
16200** If db!=0 and db->mallocFailed is true (indicating a prior malloc
16201** failure on the same database connection) then always return 0.
16202** Hence for a particular database connection, once malloc starts
16203** failing, it fails consistently until mallocFailed is reset.
16204** This is an important assumption.  There are many places in the
16205** code that do things like this:
16206**
16207**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
16208**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
16209**         if( b ) a[10] = 9;
16210**
16211** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
16212** that all prior mallocs (ex: "a") worked too.
16213*/
16214SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
16215  void *p;
16216  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16217#ifndef SQLITE_OMIT_LOOKASIDE
16218  if( db ){
16219    LookasideSlot *pBuf;
16220    if( db->mallocFailed ){
16221      return 0;
16222    }
16223    if( db->lookaside.bEnabled && n<=db->lookaside.sz
16224         && (pBuf = db->lookaside.pFree)!=0 ){
16225      db->lookaside.pFree = pBuf->pNext;
16226      db->lookaside.nOut++;
16227      if( db->lookaside.nOut>db->lookaside.mxOut ){
16228        db->lookaside.mxOut = db->lookaside.nOut;
16229      }
16230      return (void*)pBuf;
16231    }
16232  }
16233#else
16234  if( db && db->mallocFailed ){
16235    return 0;
16236  }
16237#endif
16238  p = sqlite3Malloc(n);
16239  if( !p && db ){
16240    db->mallocFailed = 1;
16241  }
16242  return p;
16243}
16244
16245/*
16246** Resize the block of memory pointed to by p to n bytes. If the
16247** resize fails, set the mallocFailed flag in the connection object.
16248*/
16249SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
16250  void *pNew = 0;
16251  assert( db!=0 );
16252  assert( sqlite3_mutex_held(db->mutex) );
16253  if( db->mallocFailed==0 ){
16254    if( p==0 ){
16255      return sqlite3DbMallocRaw(db, n);
16256    }
16257    if( isLookaside(db, p) ){
16258      if( n<=db->lookaside.sz ){
16259        return p;
16260      }
16261      pNew = sqlite3DbMallocRaw(db, n);
16262      if( pNew ){
16263        memcpy(pNew, p, db->lookaside.sz);
16264        sqlite3DbFree(db, p);
16265      }
16266    }else{
16267      pNew = sqlite3_realloc(p, n);
16268      if( !pNew ){
16269        db->mallocFailed = 1;
16270      }
16271    }
16272  }
16273  return pNew;
16274}
16275
16276/*
16277** Attempt to reallocate p.  If the reallocation fails, then free p
16278** and set the mallocFailed flag in the database connection.
16279*/
16280SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
16281  void *pNew;
16282  pNew = sqlite3DbRealloc(db, p, n);
16283  if( !pNew ){
16284    sqlite3DbFree(db, p);
16285  }
16286  return pNew;
16287}
16288
16289/*
16290** Make a copy of a string in memory obtained from sqliteMalloc(). These
16291** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
16292** is because when memory debugging is turned on, these two functions are
16293** called via macros that record the current file and line number in the
16294** ThreadData structure.
16295*/
16296SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
16297  char *zNew;
16298  size_t n;
16299  if( z==0 ){
16300    return 0;
16301  }
16302  n = sqlite3Strlen30(z) + 1;
16303  assert( (n&0x7fffffff)==n );
16304  zNew = sqlite3DbMallocRaw(db, (int)n);
16305  if( zNew ){
16306    memcpy(zNew, z, n);
16307  }
16308  return zNew;
16309}
16310SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
16311  char *zNew;
16312  if( z==0 ){
16313    return 0;
16314  }
16315  assert( (n&0x7fffffff)==n );
16316  zNew = sqlite3DbMallocRaw(db, n+1);
16317  if( zNew ){
16318    memcpy(zNew, z, n);
16319    zNew[n] = 0;
16320  }
16321  return zNew;
16322}
16323
16324/*
16325** Create a string from the zFromat argument and the va_list that follows.
16326** Store the string in memory obtained from sqliteMalloc() and make *pz
16327** point to that string.
16328*/
16329SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
16330  va_list ap;
16331  char *z;
16332
16333  va_start(ap, zFormat);
16334  z = sqlite3VMPrintf(db, zFormat, ap);
16335  va_end(ap);
16336  sqlite3DbFree(db, *pz);
16337  *pz = z;
16338}
16339
16340
16341/*
16342** This function must be called before exiting any API function (i.e.
16343** returning control to the user) that has called sqlite3_malloc or
16344** sqlite3_realloc.
16345**
16346** The returned value is normally a copy of the second argument to this
16347** function. However, if a malloc() failure has occurred since the previous
16348** invocation SQLITE_NOMEM is returned instead.
16349**
16350** If the first argument, db, is not NULL and a malloc() error has occurred,
16351** then the connection error-code (the value returned by sqlite3_errcode())
16352** is set to SQLITE_NOMEM.
16353*/
16354SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
16355  /* If the db handle is not NULL, then we must hold the connection handle
16356  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
16357  ** is unsafe, as is the call to sqlite3Error().
16358  */
16359  assert( !db || sqlite3_mutex_held(db->mutex) );
16360  if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
16361    sqlite3Error(db, SQLITE_NOMEM, 0);
16362    db->mallocFailed = 0;
16363    rc = SQLITE_NOMEM;
16364  }
16365  return rc & (db ? db->errMask : 0xff);
16366}
16367
16368/************** End of malloc.c **********************************************/
16369/************** Begin file printf.c ******************************************/
16370/*
16371** The "printf" code that follows dates from the 1980's.  It is in
16372** the public domain.  The original comments are included here for
16373** completeness.  They are very out-of-date but might be useful as
16374** an historical reference.  Most of the "enhancements" have been backed
16375** out so that the functionality is now the same as standard printf().
16376**
16377**************************************************************************
16378**
16379** The following modules is an enhanced replacement for the "printf" subroutines
16380** found in the standard C library.  The following enhancements are
16381** supported:
16382**
16383**      +  Additional functions.  The standard set of "printf" functions
16384**         includes printf, fprintf, sprintf, vprintf, vfprintf, and
16385**         vsprintf.  This module adds the following:
16386**
16387**           *  snprintf -- Works like sprintf, but has an extra argument
16388**                          which is the size of the buffer written to.
16389**
16390**           *  mprintf --  Similar to sprintf.  Writes output to memory
16391**                          obtained from malloc.
16392**
16393**           *  xprintf --  Calls a function to dispose of output.
16394**
16395**           *  nprintf --  No output, but returns the number of characters
16396**                          that would have been output by printf.
16397**
16398**           *  A v- version (ex: vsnprintf) of every function is also
16399**              supplied.
16400**
16401**      +  A few extensions to the formatting notation are supported:
16402**
16403**           *  The "=" flag (similar to "-") causes the output to be
16404**              be centered in the appropriately sized field.
16405**
16406**           *  The %b field outputs an integer in binary notation.
16407**
16408**           *  The %c field now accepts a precision.  The character output
16409**              is repeated by the number of times the precision specifies.
16410**
16411**           *  The %' field works like %c, but takes as its character the
16412**              next character of the format string, instead of the next
16413**              argument.  For example,  printf("%.78'-")  prints 78 minus
16414**              signs, the same as  printf("%.78c",'-').
16415**
16416**      +  When compiled using GCC on a SPARC, this version of printf is
16417**         faster than the library printf for SUN OS 4.1.
16418**
16419**      +  All functions are fully reentrant.
16420**
16421*/
16422
16423/*
16424** Conversion types fall into various categories as defined by the
16425** following enumeration.
16426*/
16427#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
16428#define etFLOAT       2 /* Floating point.  %f */
16429#define etEXP         3 /* Exponentional notation. %e and %E */
16430#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
16431#define etSIZE        5 /* Return number of characters processed so far. %n */
16432#define etSTRING      6 /* Strings. %s */
16433#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
16434#define etPERCENT     8 /* Percent symbol. %% */
16435#define etCHARX       9 /* Characters. %c */
16436/* The rest are extensions, not normally found in printf() */
16437#define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
16438#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
16439                          NULL pointers replaced by SQL NULL.  %Q */
16440#define etTOKEN      12 /* a pointer to a Token structure */
16441#define etSRCLIST    13 /* a pointer to a SrcList */
16442#define etPOINTER    14 /* The %p conversion */
16443#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
16444#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
16445
16446#define etINVALID     0 /* Any unrecognized conversion type */
16447
16448
16449/*
16450** An "etByte" is an 8-bit unsigned value.
16451*/
16452typedef unsigned char etByte;
16453
16454/*
16455** Each builtin conversion character (ex: the 'd' in "%d") is described
16456** by an instance of the following structure
16457*/
16458typedef struct et_info {   /* Information about each format field */
16459  char fmttype;            /* The format field code letter */
16460  etByte base;             /* The base for radix conversion */
16461  etByte flags;            /* One or more of FLAG_ constants below */
16462  etByte type;             /* Conversion paradigm */
16463  etByte charset;          /* Offset into aDigits[] of the digits string */
16464  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
16465} et_info;
16466
16467/*
16468** Allowed values for et_info.flags
16469*/
16470#define FLAG_SIGNED  1     /* True if the value to convert is signed */
16471#define FLAG_INTERN  2     /* True if for internal use only */
16472#define FLAG_STRING  4     /* Allow infinity precision */
16473
16474
16475/*
16476** The following table is searched linearly, so it is good to put the
16477** most frequently used conversion types first.
16478*/
16479static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
16480static const char aPrefix[] = "-x0\000X0";
16481static const et_info fmtinfo[] = {
16482  {  'd', 10, 1, etRADIX,      0,  0 },
16483  {  's',  0, 4, etSTRING,     0,  0 },
16484  {  'g',  0, 1, etGENERIC,    30, 0 },
16485  {  'z',  0, 4, etDYNSTRING,  0,  0 },
16486  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
16487  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
16488  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
16489  {  'c',  0, 0, etCHARX,      0,  0 },
16490  {  'o',  8, 0, etRADIX,      0,  2 },
16491  {  'u', 10, 0, etRADIX,      0,  0 },
16492  {  'x', 16, 0, etRADIX,      16, 1 },
16493  {  'X', 16, 0, etRADIX,      0,  4 },
16494#ifndef SQLITE_OMIT_FLOATING_POINT
16495  {  'f',  0, 1, etFLOAT,      0,  0 },
16496  {  'e',  0, 1, etEXP,        30, 0 },
16497  {  'E',  0, 1, etEXP,        14, 0 },
16498  {  'G',  0, 1, etGENERIC,    14, 0 },
16499#endif
16500  {  'i', 10, 1, etRADIX,      0,  0 },
16501  {  'n',  0, 0, etSIZE,       0,  0 },
16502  {  '%',  0, 0, etPERCENT,    0,  0 },
16503  {  'p', 16, 0, etPOINTER,    0,  1 },
16504
16505/* All the rest have the FLAG_INTERN bit set and are thus for internal
16506** use only */
16507  {  'T',  0, 2, etTOKEN,      0,  0 },
16508  {  'S',  0, 2, etSRCLIST,    0,  0 },
16509  {  'r', 10, 3, etORDINAL,    0,  0 },
16510};
16511
16512/*
16513** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
16514** conversions will work.
16515*/
16516#ifndef SQLITE_OMIT_FLOATING_POINT
16517/*
16518** "*val" is a double such that 0.1 <= *val < 10.0
16519** Return the ascii code for the leading digit of *val, then
16520** multiply "*val" by 10.0 to renormalize.
16521**
16522** Example:
16523**     input:     *val = 3.14159
16524**     output:    *val = 1.4159    function return = '3'
16525**
16526** The counter *cnt is incremented each time.  After counter exceeds
16527** 16 (the number of significant digits in a 64-bit float) '0' is
16528** always returned.
16529*/
16530static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
16531  int digit;
16532  LONGDOUBLE_TYPE d;
16533  if( (*cnt)++ >= 16 ) return '0';
16534  digit = (int)*val;
16535  d = digit;
16536  digit += '0';
16537  *val = (*val - d)*10.0;
16538  return (char)digit;
16539}
16540#endif /* SQLITE_OMIT_FLOATING_POINT */
16541
16542/*
16543** Append N space characters to the given string buffer.
16544*/
16545static void appendSpace(StrAccum *pAccum, int N){
16546  static const char zSpaces[] = "                             ";
16547  while( N>=(int)sizeof(zSpaces)-1 ){
16548    sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
16549    N -= sizeof(zSpaces)-1;
16550  }
16551  if( N>0 ){
16552    sqlite3StrAccumAppend(pAccum, zSpaces, N);
16553  }
16554}
16555
16556/*
16557** On machines with a small stack size, you can redefine the
16558** SQLITE_PRINT_BUF_SIZE to be less than 350.
16559*/
16560#ifndef SQLITE_PRINT_BUF_SIZE
16561# if defined(SQLITE_SMALL_STACK)
16562#   define SQLITE_PRINT_BUF_SIZE 50
16563# else
16564#   define SQLITE_PRINT_BUF_SIZE 350
16565# endif
16566#endif
16567#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
16568
16569/*
16570** The root program.  All variations call this core.
16571**
16572** INPUTS:
16573**   func   This is a pointer to a function taking three arguments
16574**            1. A pointer to anything.  Same as the "arg" parameter.
16575**            2. A pointer to the list of characters to be output
16576**               (Note, this list is NOT null terminated.)
16577**            3. An integer number of characters to be output.
16578**               (Note: This number might be zero.)
16579**
16580**   arg    This is the pointer to anything which will be passed as the
16581**          first argument to "func".  Use it for whatever you like.
16582**
16583**   fmt    This is the format string, as in the usual print.
16584**
16585**   ap     This is a pointer to a list of arguments.  Same as in
16586**          vfprint.
16587**
16588** OUTPUTS:
16589**          The return value is the total number of characters sent to
16590**          the function "func".  Returns -1 on a error.
16591**
16592** Note that the order in which automatic variables are declared below
16593** seems to make a big difference in determining how fast this beast
16594** will run.
16595*/
16596SQLITE_PRIVATE void sqlite3VXPrintf(
16597  StrAccum *pAccum,                  /* Accumulate results here */
16598  int useExtended,                   /* Allow extended %-conversions */
16599  const char *fmt,                   /* Format string */
16600  va_list ap                         /* arguments */
16601){
16602  int c;                     /* Next character in the format string */
16603  char *bufpt;               /* Pointer to the conversion buffer */
16604  int precision;             /* Precision of the current field */
16605  int length;                /* Length of the field */
16606  int idx;                   /* A general purpose loop counter */
16607  int width;                 /* Width of the current field */
16608  etByte flag_leftjustify;   /* True if "-" flag is present */
16609  etByte flag_plussign;      /* True if "+" flag is present */
16610  etByte flag_blanksign;     /* True if " " flag is present */
16611  etByte flag_alternateform; /* True if "#" flag is present */
16612  etByte flag_altform2;      /* True if "!" flag is present */
16613  etByte flag_zeropad;       /* True if field width constant starts with zero */
16614  etByte flag_long;          /* True if "l" flag is present */
16615  etByte flag_longlong;      /* True if the "ll" flag is present */
16616  etByte done;               /* Loop termination flag */
16617  sqlite_uint64 longvalue;   /* Value for integer types */
16618  LONGDOUBLE_TYPE realvalue; /* Value for real types */
16619  const et_info *infop;      /* Pointer to the appropriate info structure */
16620  char buf[etBUFSIZE];       /* Conversion buffer */
16621  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
16622  etByte xtype = 0;          /* Conversion paradigm */
16623  char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
16624#ifndef SQLITE_OMIT_FLOATING_POINT
16625  int  exp, e2;              /* exponent of real numbers */
16626  double rounder;            /* Used for rounding floating point values */
16627  etByte flag_dp;            /* True if decimal point should be shown */
16628  etByte flag_rtz;           /* True if trailing zeros should be removed */
16629  etByte flag_exp;           /* True to force display of the exponent */
16630  int nsd;                   /* Number of significant digits returned */
16631#endif
16632
16633  length = 0;
16634  bufpt = 0;
16635  for(; (c=(*fmt))!=0; ++fmt){
16636    if( c!='%' ){
16637      int amt;
16638      bufpt = (char *)fmt;
16639      amt = 1;
16640      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
16641      sqlite3StrAccumAppend(pAccum, bufpt, amt);
16642      if( c==0 ) break;
16643    }
16644    if( (c=(*++fmt))==0 ){
16645      sqlite3StrAccumAppend(pAccum, "%", 1);
16646      break;
16647    }
16648    /* Find out what flags are present */
16649    flag_leftjustify = flag_plussign = flag_blanksign =
16650     flag_alternateform = flag_altform2 = flag_zeropad = 0;
16651    done = 0;
16652    do{
16653      switch( c ){
16654        case '-':   flag_leftjustify = 1;     break;
16655        case '+':   flag_plussign = 1;        break;
16656        case ' ':   flag_blanksign = 1;       break;
16657        case '#':   flag_alternateform = 1;   break;
16658        case '!':   flag_altform2 = 1;        break;
16659        case '0':   flag_zeropad = 1;         break;
16660        default:    done = 1;                 break;
16661      }
16662    }while( !done && (c=(*++fmt))!=0 );
16663    /* Get the field width */
16664    width = 0;
16665    if( c=='*' ){
16666      width = va_arg(ap,int);
16667      if( width<0 ){
16668        flag_leftjustify = 1;
16669        width = -width;
16670      }
16671      c = *++fmt;
16672    }else{
16673      while( c>='0' && c<='9' ){
16674        width = width*10 + c - '0';
16675        c = *++fmt;
16676      }
16677    }
16678    if( width > etBUFSIZE-10 ){
16679      width = etBUFSIZE-10;
16680    }
16681    /* Get the precision */
16682    if( c=='.' ){
16683      precision = 0;
16684      c = *++fmt;
16685      if( c=='*' ){
16686        precision = va_arg(ap,int);
16687        if( precision<0 ) precision = -precision;
16688        c = *++fmt;
16689      }else{
16690        while( c>='0' && c<='9' ){
16691          precision = precision*10 + c - '0';
16692          c = *++fmt;
16693        }
16694      }
16695    }else{
16696      precision = -1;
16697    }
16698    /* Get the conversion type modifier */
16699    if( c=='l' ){
16700      flag_long = 1;
16701      c = *++fmt;
16702      if( c=='l' ){
16703        flag_longlong = 1;
16704        c = *++fmt;
16705      }else{
16706        flag_longlong = 0;
16707      }
16708    }else{
16709      flag_long = flag_longlong = 0;
16710    }
16711    /* Fetch the info entry for the field */
16712    infop = &fmtinfo[0];
16713    xtype = etINVALID;
16714    for(idx=0; idx<ArraySize(fmtinfo); idx++){
16715      if( c==fmtinfo[idx].fmttype ){
16716        infop = &fmtinfo[idx];
16717        if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
16718          xtype = infop->type;
16719        }else{
16720          return;
16721        }
16722        break;
16723      }
16724    }
16725    zExtra = 0;
16726
16727
16728    /* Limit the precision to prevent overflowing buf[] during conversion */
16729    if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
16730      precision = etBUFSIZE-40;
16731    }
16732
16733    /*
16734    ** At this point, variables are initialized as follows:
16735    **
16736    **   flag_alternateform          TRUE if a '#' is present.
16737    **   flag_altform2               TRUE if a '!' is present.
16738    **   flag_plussign               TRUE if a '+' is present.
16739    **   flag_leftjustify            TRUE if a '-' is present or if the
16740    **                               field width was negative.
16741    **   flag_zeropad                TRUE if the width began with 0.
16742    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
16743    **                               the conversion character.
16744    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
16745    **                               the conversion character.
16746    **   flag_blanksign              TRUE if a ' ' is present.
16747    **   width                       The specified field width.  This is
16748    **                               always non-negative.  Zero is the default.
16749    **   precision                   The specified precision.  The default
16750    **                               is -1.
16751    **   xtype                       The class of the conversion.
16752    **   infop                       Pointer to the appropriate info struct.
16753    */
16754    switch( xtype ){
16755      case etPOINTER:
16756        flag_longlong = sizeof(char*)==sizeof(i64);
16757        flag_long = sizeof(char*)==sizeof(long int);
16758        /* Fall through into the next case */
16759      case etORDINAL:
16760      case etRADIX:
16761        if( infop->flags & FLAG_SIGNED ){
16762          i64 v;
16763          if( flag_longlong ){
16764            v = va_arg(ap,i64);
16765          }else if( flag_long ){
16766            v = va_arg(ap,long int);
16767          }else{
16768            v = va_arg(ap,int);
16769          }
16770          if( v<0 ){
16771            longvalue = -v;
16772            prefix = '-';
16773          }else{
16774            longvalue = v;
16775            if( flag_plussign )        prefix = '+';
16776            else if( flag_blanksign )  prefix = ' ';
16777            else                       prefix = 0;
16778          }
16779        }else{
16780          if( flag_longlong ){
16781            longvalue = va_arg(ap,u64);
16782          }else if( flag_long ){
16783            longvalue = va_arg(ap,unsigned long int);
16784          }else{
16785            longvalue = va_arg(ap,unsigned int);
16786          }
16787          prefix = 0;
16788        }
16789        if( longvalue==0 ) flag_alternateform = 0;
16790        if( flag_zeropad && precision<width-(prefix!=0) ){
16791          precision = width-(prefix!=0);
16792        }
16793        bufpt = &buf[etBUFSIZE-1];
16794        if( xtype==etORDINAL ){
16795          static const char zOrd[] = "thstndrd";
16796          int x = (int)(longvalue % 10);
16797          if( x>=4 || (longvalue/10)%10==1 ){
16798            x = 0;
16799          }
16800          buf[etBUFSIZE-3] = zOrd[x*2];
16801          buf[etBUFSIZE-2] = zOrd[x*2+1];
16802          bufpt -= 2;
16803        }
16804        {
16805          register const char *cset;      /* Use registers for speed */
16806          register int base;
16807          cset = &aDigits[infop->charset];
16808          base = infop->base;
16809          do{                                           /* Convert to ascii */
16810            *(--bufpt) = cset[longvalue%base];
16811            longvalue = longvalue/base;
16812          }while( longvalue>0 );
16813        }
16814        length = (int)(&buf[etBUFSIZE-1]-bufpt);
16815        for(idx=precision-length; idx>0; idx--){
16816          *(--bufpt) = '0';                             /* Zero pad */
16817        }
16818        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
16819        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
16820          const char *pre;
16821          char x;
16822          pre = &aPrefix[infop->prefix];
16823          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
16824        }
16825        length = (int)(&buf[etBUFSIZE-1]-bufpt);
16826        break;
16827      case etFLOAT:
16828      case etEXP:
16829      case etGENERIC:
16830        realvalue = va_arg(ap,double);
16831#ifndef SQLITE_OMIT_FLOATING_POINT
16832        if( precision<0 ) precision = 6;         /* Set default precision */
16833        if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
16834        if( realvalue<0.0 ){
16835          realvalue = -realvalue;
16836          prefix = '-';
16837        }else{
16838          if( flag_plussign )          prefix = '+';
16839          else if( flag_blanksign )    prefix = ' ';
16840          else                         prefix = 0;
16841        }
16842        if( xtype==etGENERIC && precision>0 ) precision--;
16843#if 0
16844        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
16845        for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
16846#else
16847        /* It makes more sense to use 0.5 */
16848        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
16849#endif
16850        if( xtype==etFLOAT ) realvalue += rounder;
16851        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
16852        exp = 0;
16853        if( sqlite3IsNaN((double)realvalue) ){
16854          bufpt = "NaN";
16855          length = 3;
16856          break;
16857        }
16858        if( realvalue>0.0 ){
16859          while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
16860          while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
16861          while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
16862          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
16863          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
16864          if( exp>350 ){
16865            if( prefix=='-' ){
16866              bufpt = "-Inf";
16867            }else if( prefix=='+' ){
16868              bufpt = "+Inf";
16869            }else{
16870              bufpt = "Inf";
16871            }
16872            length = sqlite3Strlen30(bufpt);
16873            break;
16874          }
16875        }
16876        bufpt = buf;
16877        /*
16878        ** If the field type is etGENERIC, then convert to either etEXP
16879        ** or etFLOAT, as appropriate.
16880        */
16881        flag_exp = xtype==etEXP;
16882        if( xtype!=etFLOAT ){
16883          realvalue += rounder;
16884          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
16885        }
16886        if( xtype==etGENERIC ){
16887          flag_rtz = !flag_alternateform;
16888          if( exp<-4 || exp>precision ){
16889            xtype = etEXP;
16890          }else{
16891            precision = precision - exp;
16892            xtype = etFLOAT;
16893          }
16894        }else{
16895          flag_rtz = 0;
16896        }
16897        if( xtype==etEXP ){
16898          e2 = 0;
16899        }else{
16900          e2 = exp;
16901        }
16902        nsd = 0;
16903        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
16904        /* The sign in front of the number */
16905        if( prefix ){
16906          *(bufpt++) = prefix;
16907        }
16908        /* Digits prior to the decimal point */
16909        if( e2<0 ){
16910          *(bufpt++) = '0';
16911        }else{
16912          for(; e2>=0; e2--){
16913            *(bufpt++) = et_getdigit(&realvalue,&nsd);
16914          }
16915        }
16916        /* The decimal point */
16917        if( flag_dp ){
16918          *(bufpt++) = '.';
16919        }
16920        /* "0" digits after the decimal point but before the first
16921        ** significant digit of the number */
16922        for(e2++; e2<0; precision--, e2++){
16923          assert( precision>0 );
16924          *(bufpt++) = '0';
16925        }
16926        /* Significant digits after the decimal point */
16927        while( (precision--)>0 ){
16928          *(bufpt++) = et_getdigit(&realvalue,&nsd);
16929        }
16930        /* Remove trailing zeros and the "." if no digits follow the "." */
16931        if( flag_rtz && flag_dp ){
16932          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
16933          assert( bufpt>buf );
16934          if( bufpt[-1]=='.' ){
16935            if( flag_altform2 ){
16936              *(bufpt++) = '0';
16937            }else{
16938              *(--bufpt) = 0;
16939            }
16940          }
16941        }
16942        /* Add the "eNNN" suffix */
16943        if( flag_exp || xtype==etEXP ){
16944          *(bufpt++) = aDigits[infop->charset];
16945          if( exp<0 ){
16946            *(bufpt++) = '-'; exp = -exp;
16947          }else{
16948            *(bufpt++) = '+';
16949          }
16950          if( exp>=100 ){
16951            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
16952            exp %= 100;
16953          }
16954          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
16955          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
16956        }
16957        *bufpt = 0;
16958
16959        /* The converted number is in buf[] and zero terminated. Output it.
16960        ** Note that the number is in the usual order, not reversed as with
16961        ** integer conversions. */
16962        length = (int)(bufpt-buf);
16963        bufpt = buf;
16964
16965        /* Special case:  Add leading zeros if the flag_zeropad flag is
16966        ** set and we are not left justified */
16967        if( flag_zeropad && !flag_leftjustify && length < width){
16968          int i;
16969          int nPad = width - length;
16970          for(i=width; i>=nPad; i--){
16971            bufpt[i] = bufpt[i-nPad];
16972          }
16973          i = prefix!=0;
16974          while( nPad-- ) bufpt[i++] = '0';
16975          length = width;
16976        }
16977#endif
16978        break;
16979      case etSIZE:
16980        *(va_arg(ap,int*)) = pAccum->nChar;
16981        length = width = 0;
16982        break;
16983      case etPERCENT:
16984        buf[0] = '%';
16985        bufpt = buf;
16986        length = 1;
16987        break;
16988      case etCHARX:
16989        c = va_arg(ap,int);
16990        buf[0] = (char)c;
16991        if( precision>=0 ){
16992          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
16993          length = precision;
16994        }else{
16995          length =1;
16996        }
16997        bufpt = buf;
16998        break;
16999      case etSTRING:
17000      case etDYNSTRING:
17001        bufpt = va_arg(ap,char*);
17002        if( bufpt==0 ){
17003          bufpt = "";
17004        }else if( xtype==etDYNSTRING ){
17005          zExtra = bufpt;
17006        }
17007        if( precision>=0 ){
17008          for(length=0; length<precision && bufpt[length]; length++){}
17009        }else{
17010          length = sqlite3Strlen30(bufpt);
17011        }
17012        break;
17013      case etSQLESCAPE:
17014      case etSQLESCAPE2:
17015      case etSQLESCAPE3: {
17016        int i, j, k, n, isnull;
17017        int needQuote;
17018        char ch;
17019        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
17020        char *escarg = va_arg(ap,char*);
17021        isnull = escarg==0;
17022        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
17023        k = precision;
17024        for(i=n=0; (ch=escarg[i])!=0 && k!=0; i++, k--){
17025          if( ch==q )  n++;
17026        }
17027        needQuote = !isnull && xtype==etSQLESCAPE2;
17028        n += i + 1 + needQuote*2;
17029        if( n>etBUFSIZE ){
17030          bufpt = zExtra = sqlite3Malloc( n );
17031          if( bufpt==0 ){
17032            pAccum->mallocFailed = 1;
17033            return;
17034          }
17035        }else{
17036          bufpt = buf;
17037        }
17038        j = 0;
17039        if( needQuote ) bufpt[j++] = q;
17040        k = i;
17041        for(i=0; i<k; i++){
17042          bufpt[j++] = ch = escarg[i];
17043          if( ch==q ) bufpt[j++] = ch;
17044        }
17045        if( needQuote ) bufpt[j++] = q;
17046        bufpt[j] = 0;
17047        length = j;
17048        /* The precision in %q and %Q means how many input characters to
17049        ** consume, not the length of the output...
17050        ** if( precision>=0 && precision<length ) length = precision; */
17051        break;
17052      }
17053      case etTOKEN: {
17054        Token *pToken = va_arg(ap, Token*);
17055        if( pToken ){
17056          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
17057        }
17058        length = width = 0;
17059        break;
17060      }
17061      case etSRCLIST: {
17062        SrcList *pSrc = va_arg(ap, SrcList*);
17063        int k = va_arg(ap, int);
17064        struct SrcList_item *pItem = &pSrc->a[k];
17065        assert( k>=0 && k<pSrc->nSrc );
17066        if( pItem->zDatabase ){
17067          sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
17068          sqlite3StrAccumAppend(pAccum, ".", 1);
17069        }
17070        sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
17071        length = width = 0;
17072        break;
17073      }
17074      default: {
17075        assert( xtype==etINVALID );
17076        return;
17077      }
17078    }/* End switch over the format type */
17079    /*
17080    ** The text of the conversion is pointed to by "bufpt" and is
17081    ** "length" characters long.  The field width is "width".  Do
17082    ** the output.
17083    */
17084    if( !flag_leftjustify ){
17085      register int nspace;
17086      nspace = width-length;
17087      if( nspace>0 ){
17088        appendSpace(pAccum, nspace);
17089      }
17090    }
17091    if( length>0 ){
17092      sqlite3StrAccumAppend(pAccum, bufpt, length);
17093    }
17094    if( flag_leftjustify ){
17095      register int nspace;
17096      nspace = width-length;
17097      if( nspace>0 ){
17098        appendSpace(pAccum, nspace);
17099      }
17100    }
17101    if( zExtra ){
17102      sqlite3_free(zExtra);
17103    }
17104  }/* End for loop over the format string */
17105} /* End of function */
17106
17107/*
17108** Append N bytes of text from z to the StrAccum object.
17109*/
17110SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
17111  assert( z!=0 || N==0 );
17112  if( p->tooBig | p->mallocFailed ){
17113    testcase(p->tooBig);
17114    testcase(p->mallocFailed);
17115    return;
17116  }
17117  if( N<0 ){
17118    N = sqlite3Strlen30(z);
17119  }
17120  if( N==0 || NEVER(z==0) ){
17121    return;
17122  }
17123  if( p->nChar+N >= p->nAlloc ){
17124    char *zNew;
17125    if( !p->useMalloc ){
17126      p->tooBig = 1;
17127      N = p->nAlloc - p->nChar - 1;
17128      if( N<=0 ){
17129        return;
17130      }
17131    }else{
17132      i64 szNew = p->nChar;
17133      szNew += N + 1;
17134      if( szNew > p->mxAlloc ){
17135        sqlite3StrAccumReset(p);
17136        p->tooBig = 1;
17137        return;
17138      }else{
17139        p->nAlloc = (int)szNew;
17140      }
17141      zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
17142      if( zNew ){
17143        memcpy(zNew, p->zText, p->nChar);
17144        sqlite3StrAccumReset(p);
17145        p->zText = zNew;
17146      }else{
17147        p->mallocFailed = 1;
17148        sqlite3StrAccumReset(p);
17149        return;
17150      }
17151    }
17152  }
17153  memcpy(&p->zText[p->nChar], z, N);
17154  p->nChar += N;
17155}
17156
17157/*
17158** Finish off a string by making sure it is zero-terminated.
17159** Return a pointer to the resulting string.  Return a NULL
17160** pointer if any kind of error was encountered.
17161*/
17162SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
17163  if( p->zText ){
17164    p->zText[p->nChar] = 0;
17165    if( p->useMalloc && p->zText==p->zBase ){
17166      p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
17167      if( p->zText ){
17168        memcpy(p->zText, p->zBase, p->nChar+1);
17169      }else{
17170        p->mallocFailed = 1;
17171      }
17172    }
17173  }
17174  return p->zText;
17175}
17176
17177/*
17178** Reset an StrAccum string.  Reclaim all malloced memory.
17179*/
17180SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
17181  if( p->zText!=p->zBase ){
17182    sqlite3DbFree(p->db, p->zText);
17183  }
17184  p->zText = 0;
17185}
17186
17187/*
17188** Initialize a string accumulator
17189*/
17190SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
17191  p->zText = p->zBase = zBase;
17192  p->db = 0;
17193  p->nChar = 0;
17194  p->nAlloc = n;
17195  p->mxAlloc = mx;
17196  p->useMalloc = 1;
17197  p->tooBig = 0;
17198  p->mallocFailed = 0;
17199}
17200
17201/*
17202** Print into memory obtained from sqliteMalloc().  Use the internal
17203** %-conversion extensions.
17204*/
17205SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
17206  char *z;
17207  char zBase[SQLITE_PRINT_BUF_SIZE];
17208  StrAccum acc;
17209  assert( db!=0 );
17210  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
17211                      db->aLimit[SQLITE_LIMIT_LENGTH]);
17212  acc.db = db;
17213  sqlite3VXPrintf(&acc, 1, zFormat, ap);
17214  z = sqlite3StrAccumFinish(&acc);
17215  if( acc.mallocFailed ){
17216    db->mallocFailed = 1;
17217  }
17218  return z;
17219}
17220
17221/*
17222** Print into memory obtained from sqliteMalloc().  Use the internal
17223** %-conversion extensions.
17224*/
17225SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
17226  va_list ap;
17227  char *z;
17228  va_start(ap, zFormat);
17229  z = sqlite3VMPrintf(db, zFormat, ap);
17230  va_end(ap);
17231  return z;
17232}
17233
17234/*
17235** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
17236** the string and before returnning.  This routine is intended to be used
17237** to modify an existing string.  For example:
17238**
17239**       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
17240**
17241*/
17242SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
17243  va_list ap;
17244  char *z;
17245  va_start(ap, zFormat);
17246  z = sqlite3VMPrintf(db, zFormat, ap);
17247  va_end(ap);
17248  sqlite3DbFree(db, zStr);
17249  return z;
17250}
17251
17252/*
17253** Print into memory obtained from sqlite3_malloc().  Omit the internal
17254** %-conversion extensions.
17255*/
17256SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
17257  char *z;
17258  char zBase[SQLITE_PRINT_BUF_SIZE];
17259  StrAccum acc;
17260#ifndef SQLITE_OMIT_AUTOINIT
17261  if( sqlite3_initialize() ) return 0;
17262#endif
17263  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
17264  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17265  z = sqlite3StrAccumFinish(&acc);
17266  return z;
17267}
17268
17269/*
17270** Print into memory obtained from sqlite3_malloc()().  Omit the internal
17271** %-conversion extensions.
17272*/
17273SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
17274  va_list ap;
17275  char *z;
17276#ifndef SQLITE_OMIT_AUTOINIT
17277  if( sqlite3_initialize() ) return 0;
17278#endif
17279  va_start(ap, zFormat);
17280  z = sqlite3_vmprintf(zFormat, ap);
17281  va_end(ap);
17282  return z;
17283}
17284
17285/*
17286** sqlite3_snprintf() works like snprintf() except that it ignores the
17287** current locale settings.  This is important for SQLite because we
17288** are not able to use a "," as the decimal point in place of "." as
17289** specified by some locales.
17290*/
17291SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
17292  char *z;
17293  va_list ap;
17294  StrAccum acc;
17295
17296  if( n<=0 ){
17297    return zBuf;
17298  }
17299  sqlite3StrAccumInit(&acc, zBuf, n, 0);
17300  acc.useMalloc = 0;
17301  va_start(ap,zFormat);
17302  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17303  va_end(ap);
17304  z = sqlite3StrAccumFinish(&acc);
17305  return z;
17306}
17307
17308#if defined(SQLITE_DEBUG)
17309/*
17310** A version of printf() that understands %lld.  Used for debugging.
17311** The printf() built into some versions of windows does not understand %lld
17312** and segfaults if you give it a long long int.
17313*/
17314SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
17315  va_list ap;
17316  StrAccum acc;
17317  char zBuf[500];
17318  sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
17319  acc.useMalloc = 0;
17320  va_start(ap,zFormat);
17321  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17322  va_end(ap);
17323  sqlite3StrAccumFinish(&acc);
17324  fprintf(stdout,"%s", zBuf);
17325  fflush(stdout);
17326}
17327#endif
17328
17329#ifndef SQLITE_OMIT_TRACE
17330/*
17331** variable-argument wrapper around sqlite3VXPrintf().
17332*/
17333SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
17334  va_list ap;
17335  va_start(ap,zFormat);
17336  sqlite3VXPrintf(p, 1, zFormat, ap);
17337  va_end(ap);
17338}
17339#endif
17340
17341/************** End of printf.c **********************************************/
17342/************** Begin file random.c ******************************************/
17343/*
17344** 2001 September 15
17345**
17346** The author disclaims copyright to this source code.  In place of
17347** a legal notice, here is a blessing:
17348**
17349**    May you do good and not evil.
17350**    May you find forgiveness for yourself and forgive others.
17351**    May you share freely, never taking more than you give.
17352**
17353*************************************************************************
17354** This file contains code to implement a pseudo-random number
17355** generator (PRNG) for SQLite.
17356**
17357** Random numbers are used by some of the database backends in order
17358** to generate random integer keys for tables or random filenames.
17359*/
17360
17361
17362/* All threads share a single random number generator.
17363** This structure is the current state of the generator.
17364*/
17365static SQLITE_WSD struct sqlite3PrngType {
17366  unsigned char isInit;          /* True if initialized */
17367  unsigned char i, j;            /* State variables */
17368  unsigned char s[256];          /* State variables */
17369} sqlite3Prng;
17370
17371/*
17372** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
17373** must be held while executing this routine.
17374**
17375** Why not just use a library random generator like lrand48() for this?
17376** Because the OP_NewRowid opcode in the VDBE depends on having a very
17377** good source of random numbers.  The lrand48() library function may
17378** well be good enough.  But maybe not.  Or maybe lrand48() has some
17379** subtle problems on some systems that could cause problems.  It is hard
17380** to know.  To minimize the risk of problems due to bad lrand48()
17381** implementations, SQLite uses this random number generator based
17382** on RC4, which we know works very well.
17383**
17384** (Later):  Actually, OP_NewRowid does not depend on a good source of
17385** randomness any more.  But we will leave this code in all the same.
17386*/
17387static u8 randomByte(void){
17388  unsigned char t;
17389
17390
17391  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
17392  ** state vector.  If writable static data is unsupported on the target,
17393  ** we have to locate the state vector at run-time.  In the more common
17394  ** case where writable static data is supported, wsdPrng can refer directly
17395  ** to the "sqlite3Prng" state vector declared above.
17396  */
17397#ifdef SQLITE_OMIT_WSD
17398  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
17399# define wsdPrng p[0]
17400#else
17401# define wsdPrng sqlite3Prng
17402#endif
17403
17404
17405  /* Initialize the state of the random number generator once,
17406  ** the first time this routine is called.  The seed value does
17407  ** not need to contain a lot of randomness since we are not
17408  ** trying to do secure encryption or anything like that...
17409  **
17410  ** Nothing in this file or anywhere else in SQLite does any kind of
17411  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
17412  ** number generator) not as an encryption device.
17413  */
17414  if( !wsdPrng.isInit ){
17415    int i;
17416    char k[256];
17417    wsdPrng.j = 0;
17418    wsdPrng.i = 0;
17419    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
17420    for(i=0; i<256; i++){
17421      wsdPrng.s[i] = (u8)i;
17422    }
17423    for(i=0; i<256; i++){
17424      wsdPrng.j += wsdPrng.s[i] + k[i];
17425      t = wsdPrng.s[wsdPrng.j];
17426      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
17427      wsdPrng.s[i] = t;
17428    }
17429    wsdPrng.isInit = 1;
17430  }
17431
17432  /* Generate and return single random byte
17433  */
17434  wsdPrng.i++;
17435  t = wsdPrng.s[wsdPrng.i];
17436  wsdPrng.j += t;
17437  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
17438  wsdPrng.s[wsdPrng.j] = t;
17439  t += wsdPrng.s[wsdPrng.i];
17440  return wsdPrng.s[t];
17441}
17442
17443/*
17444** Return N random bytes.
17445*/
17446SQLITE_API void sqlite3_randomness(int N, void *pBuf){
17447  unsigned char *zBuf = pBuf;
17448#if SQLITE_THREADSAFE
17449  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
17450#endif
17451  sqlite3_mutex_enter(mutex);
17452  while( N-- ){
17453    *(zBuf++) = randomByte();
17454  }
17455  sqlite3_mutex_leave(mutex);
17456}
17457
17458#ifndef SQLITE_OMIT_BUILTIN_TEST
17459/*
17460** For testing purposes, we sometimes want to preserve the state of
17461** PRNG and restore the PRNG to its saved state at a later time, or
17462** to reset the PRNG to its initial state.  These routines accomplish
17463** those tasks.
17464**
17465** The sqlite3_test_control() interface calls these routines to
17466** control the PRNG.
17467*/
17468static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
17469SQLITE_PRIVATE void sqlite3PrngSaveState(void){
17470  memcpy(
17471    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17472    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17473    sizeof(sqlite3Prng)
17474  );
17475}
17476SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
17477  memcpy(
17478    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17479    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17480    sizeof(sqlite3Prng)
17481  );
17482}
17483SQLITE_PRIVATE void sqlite3PrngResetState(void){
17484  GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
17485}
17486#endif /* SQLITE_OMIT_BUILTIN_TEST */
17487
17488/************** End of random.c **********************************************/
17489/************** Begin file utf.c *********************************************/
17490/*
17491** 2004 April 13
17492**
17493** The author disclaims copyright to this source code.  In place of
17494** a legal notice, here is a blessing:
17495**
17496**    May you do good and not evil.
17497**    May you find forgiveness for yourself and forgive others.
17498**    May you share freely, never taking more than you give.
17499**
17500*************************************************************************
17501** This file contains routines used to translate between UTF-8,
17502** UTF-16, UTF-16BE, and UTF-16LE.
17503**
17504** Notes on UTF-8:
17505**
17506**   Byte-0    Byte-1    Byte-2    Byte-3    Value
17507**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
17508**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
17509**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
17510**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
17511**
17512**
17513** Notes on UTF-16:  (with wwww+1==uuuuu)
17514**
17515**      Word-0               Word-1          Value
17516**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
17517**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
17518**
17519**
17520** BOM or Byte Order Mark:
17521**     0xff 0xfe   little-endian utf-16 follows
17522**     0xfe 0xff   big-endian utf-16 follows
17523**
17524*/
17525/************** Include vdbeInt.h in the middle of utf.c *********************/
17526/************** Begin file vdbeInt.h *****************************************/
17527/*
17528** 2003 September 6
17529**
17530** The author disclaims copyright to this source code.  In place of
17531** a legal notice, here is a blessing:
17532**
17533**    May you do good and not evil.
17534**    May you find forgiveness for yourself and forgive others.
17535**    May you share freely, never taking more than you give.
17536**
17537*************************************************************************
17538** This is the header file for information that is private to the
17539** VDBE.  This information used to all be at the top of the single
17540** source code file "vdbe.c".  When that file became too big (over
17541** 6000 lines long) it was split up into several smaller files and
17542** this header information was factored out.
17543*/
17544#ifndef _VDBEINT_H_
17545#define _VDBEINT_H_
17546
17547/*
17548** SQL is translated into a sequence of instructions to be
17549** executed by a virtual machine.  Each instruction is an instance
17550** of the following structure.
17551*/
17552typedef struct VdbeOp Op;
17553
17554/*
17555** Boolean values
17556*/
17557typedef unsigned char Bool;
17558
17559/*
17560** A cursor is a pointer into a single BTree within a database file.
17561** The cursor can seek to a BTree entry with a particular key, or
17562** loop over all entries of the Btree.  You can also insert new BTree
17563** entries or retrieve the key or data from the entry that the cursor
17564** is currently pointing to.
17565**
17566** Every cursor that the virtual machine has open is represented by an
17567** instance of the following structure.
17568**
17569** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
17570** really a single row that represents the NEW or OLD pseudo-table of
17571** a row trigger.  The data for the row is stored in VdbeCursor.pData and
17572** the rowid is in VdbeCursor.iKey.
17573*/
17574struct VdbeCursor {
17575  BtCursor *pCursor;    /* The cursor structure of the backend */
17576  int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
17577  i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
17578  Bool zeroed;          /* True if zeroed out and ready for reuse */
17579  Bool rowidIsValid;    /* True if lastRowid is valid */
17580  Bool atFirst;         /* True if pointing to first entry */
17581  Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
17582  Bool nullRow;         /* True if pointing to a row with no data */
17583  Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
17584  Bool isTable;         /* True if a table requiring integer keys */
17585  Bool isIndex;         /* True if an index containing keys only - no data */
17586  i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
17587  Btree *pBt;           /* Separate file holding temporary table */
17588  int pseudoTableReg;   /* Register holding pseudotable content. */
17589  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
17590  int nField;           /* Number of fields in the header */
17591  i64 seqCount;         /* Sequence counter */
17592  sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
17593  const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
17594
17595  /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
17596  ** OP_IsUnique opcode on this cursor. */
17597  int seekResult;
17598
17599  /* Cached information about the header for the data record that the
17600  ** cursor is currently pointing to.  Only valid if cacheStatus matches
17601  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
17602  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
17603  ** the cache is out of date.
17604  **
17605  ** aRow might point to (ephemeral) data for the current row, or it might
17606  ** be NULL.
17607  */
17608  u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
17609  int payloadSize;      /* Total number of bytes in the record */
17610  u32 *aType;           /* Type values for all entries in the record */
17611  u32 *aOffset;         /* Cached offsets to the start of each columns data */
17612  u8 *aRow;             /* Data for the current row, if all on one page */
17613};
17614typedef struct VdbeCursor VdbeCursor;
17615
17616/*
17617** When a sub-program is executed (OP_Program), a structure of this type
17618** is allocated to store the current value of the program counter, as
17619** well as the current memory cell array and various other frame specific
17620** values stored in the Vdbe struct. When the sub-program is finished,
17621** these values are copied back to the Vdbe from the VdbeFrame structure,
17622** restoring the state of the VM to as it was before the sub-program
17623** began executing.
17624**
17625** Frames are stored in a linked list headed at Vdbe.pParent. Vdbe.pParent
17626** is the parent of the current frame, or zero if the current frame
17627** is the main Vdbe program.
17628*/
17629typedef struct VdbeFrame VdbeFrame;
17630struct VdbeFrame {
17631  Vdbe *v;                /* VM this frame belongs to */
17632  int pc;                 /* Program Counter */
17633  Op *aOp;                /* Program instructions */
17634  int nOp;                /* Size of aOp array */
17635  Mem *aMem;              /* Array of memory cells */
17636  int nMem;               /* Number of entries in aMem */
17637  VdbeCursor **apCsr;     /* Element of Vdbe cursors */
17638  u16 nCursor;            /* Number of entries in apCsr */
17639  void *token;            /* Copy of SubProgram.token */
17640  int nChildMem;          /* Number of memory cells for child frame */
17641  int nChildCsr;          /* Number of cursors for child frame */
17642  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
17643  int nChange;            /* Statement changes (Vdbe.nChanges)     */
17644  VdbeFrame *pParent;     /* Parent of this frame */
17645};
17646
17647#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
17648
17649/*
17650** A value for VdbeCursor.cacheValid that means the cache is always invalid.
17651*/
17652#define CACHE_STALE 0
17653
17654/*
17655** Internally, the vdbe manipulates nearly all SQL values as Mem
17656** structures. Each Mem struct may cache multiple representations (string,
17657** integer etc.) of the same value.  A value (and therefore Mem structure)
17658** has the following properties:
17659**
17660** Each value has a manifest type. The manifest type of the value stored
17661** in a Mem struct is returned by the MemType(Mem*) macro. The type is
17662** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
17663** SQLITE_BLOB.
17664*/
17665struct Mem {
17666  union {
17667    i64 i;              /* Integer value. */
17668    int nZero;          /* Used when bit MEM_Zero is set in flags */
17669    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
17670    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
17671    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
17672  } u;
17673  double r;           /* Real value */
17674  sqlite3 *db;        /* The associated database connection */
17675  char *z;            /* String or BLOB value */
17676  int n;              /* Number of characters in string value, excluding '\0' */
17677  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
17678  u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
17679  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
17680  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
17681  char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
17682};
17683
17684/* One or more of the following flags are set to indicate the validOK
17685** representations of the value stored in the Mem struct.
17686**
17687** If the MEM_Null flag is set, then the value is an SQL NULL value.
17688** No other flags may be set in this case.
17689**
17690** If the MEM_Str flag is set then Mem.z points at a string representation.
17691** Usually this is encoded in the same unicode encoding as the main
17692** database (see below for exceptions). If the MEM_Term flag is also
17693** set, then the string is nul terminated. The MEM_Int and MEM_Real
17694** flags may coexist with the MEM_Str flag.
17695**
17696** Multiple of these values can appear in Mem.flags.  But only one
17697** at a time can appear in Mem.type.
17698*/
17699#define MEM_Null      0x0001   /* Value is NULL */
17700#define MEM_Str       0x0002   /* Value is a string */
17701#define MEM_Int       0x0004   /* Value is an integer */
17702#define MEM_Real      0x0008   /* Value is a real number */
17703#define MEM_Blob      0x0010   /* Value is a BLOB */
17704#define MEM_RowSet    0x0020   /* Value is a RowSet object */
17705#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
17706#define MEM_TypeMask  0x00ff   /* Mask of type bits */
17707
17708/* Whenever Mem contains a valid string or blob representation, one of
17709** the following flags must be set to determine the memory management
17710** policy for Mem.z.  The MEM_Term flag tells us whether or not the
17711** string is \000 or \u0000 terminated
17712*/
17713#define MEM_Term      0x0200   /* String rep is nul terminated */
17714#define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
17715#define MEM_Static    0x0800   /* Mem.z points to a static string */
17716#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
17717#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
17718#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
17719
17720#ifdef SQLITE_OMIT_INCRBLOB
17721  #undef MEM_Zero
17722  #define MEM_Zero 0x0000
17723#endif
17724
17725
17726/*
17727** Clear any existing type flags from a Mem and replace them with f
17728*/
17729#define MemSetTypeFlag(p, f) \
17730   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
17731
17732
17733/* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
17734** additional information about auxiliary information bound to arguments
17735** of the function.  This is used to implement the sqlite3_get_auxdata()
17736** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
17737** that can be associated with a constant argument to a function.  This
17738** allows functions such as "regexp" to compile their constant regular
17739** expression argument once and reused the compiled code for multiple
17740** invocations.
17741*/
17742struct VdbeFunc {
17743  FuncDef *pFunc;               /* The definition of the function */
17744  int nAux;                     /* Number of entries allocated for apAux[] */
17745  struct AuxData {
17746    void *pAux;                   /* Aux data for the i-th argument */
17747    void (*xDelete)(void *);      /* Destructor for the aux data */
17748  } apAux[1];                   /* One slot for each function argument */
17749};
17750
17751/*
17752** The "context" argument for a installable function.  A pointer to an
17753** instance of this structure is the first argument to the routines used
17754** implement the SQL functions.
17755**
17756** There is a typedef for this structure in sqlite.h.  So all routines,
17757** even the public interface to SQLite, can use a pointer to this structure.
17758** But this file is the only place where the internal details of this
17759** structure are known.
17760**
17761** This structure is defined inside of vdbeInt.h because it uses substructures
17762** (Mem) which are only defined there.
17763*/
17764struct sqlite3_context {
17765  FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
17766  VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
17767  Mem s;                /* The return value is stored here */
17768  Mem *pMem;            /* Memory cell used to store aggregate context */
17769  int isError;          /* Error code returned by the function. */
17770  CollSeq *pColl;       /* Collating sequence */
17771};
17772
17773/*
17774** A Set structure is used for quick testing to see if a value
17775** is part of a small set.  Sets are used to implement code like
17776** this:
17777**            x.y IN ('hi','hoo','hum')
17778*/
17779typedef struct Set Set;
17780struct Set {
17781  Hash hash;             /* A set is just a hash table */
17782  HashElem *prev;        /* Previously accessed hash elemen */
17783};
17784
17785/*
17786** An instance of the virtual machine.  This structure contains the complete
17787** state of the virtual machine.
17788**
17789** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
17790** is really a pointer to an instance of this structure.
17791**
17792** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
17793** any virtual table method invocations made by the vdbe program. It is
17794** set to 2 for xDestroy method calls and 1 for all other methods. This
17795** variable is used for two purposes: to allow xDestroy methods to execute
17796** "DROP TABLE" statements and to prevent some nasty side effects of
17797** malloc failure when SQLite is invoked recursively by a virtual table
17798** method function.
17799*/
17800struct Vdbe {
17801  sqlite3 *db;            /* The database connection that owns this statement */
17802  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
17803  int nOp;                /* Number of instructions in the program */
17804  int nOpAlloc;           /* Number of slots allocated for aOp[] */
17805  Op *aOp;                /* Space to hold the virtual machine's program */
17806  int nLabel;             /* Number of labels used */
17807  int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
17808  int *aLabel;            /* Space to hold the labels */
17809  Mem **apArg;            /* Arguments to currently executing user function */
17810  Mem *aColName;          /* Column names to return */
17811  Mem *pResultSet;        /* Pointer to an array of results */
17812  u16 nResColumn;         /* Number of columns in one row of the result set */
17813  u16 nCursor;            /* Number of slots in apCsr[] */
17814  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
17815  u8 errorAction;         /* Recovery action to do in case of an error */
17816  u8 okVar;               /* True if azVar[] has been initialized */
17817  ynVar nVar;             /* Number of entries in aVar[] */
17818  Mem *aVar;              /* Values for the OP_Variable opcode. */
17819  char **azVar;           /* Name of variables */
17820  u32 magic;              /* Magic number for sanity checking */
17821  int nMem;               /* Number of memory locations currently allocated */
17822  Mem *aMem;              /* The memory locations */
17823  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
17824  int pc;                 /* The program counter */
17825  int rc;                 /* Value to return */
17826  char *zErrMsg;          /* Error message written here */
17827  u8 explain;             /* True if EXPLAIN present on SQL command */
17828  u8 changeCntOn;         /* True to update the change-counter */
17829  u8 expired;             /* True if the VM needs to be recompiled */
17830  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
17831  u8 inVtabMethod;        /* See comments above */
17832  u8 usesStmtJournal;     /* True if uses a statement journal */
17833  u8 readOnly;            /* True for read-only statements */
17834  u8 isPrepareV2;         /* True if prepared with prepare_v2() */
17835  int nChange;            /* Number of db changes made since last reset */
17836  int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
17837  i64 startTime;          /* Time when query started - used for profiling */
17838  BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
17839  int aCounter[2];        /* Counters used by sqlite3_stmt_status() */
17840  char *zSql;             /* Text of the SQL statement that generated this */
17841  void *pFree;            /* Free this when deleting the vdbe */
17842  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
17843  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
17844  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
17845#ifdef SQLITE_DEBUG
17846  FILE *trace;            /* Write an execution trace here, if not NULL */
17847#endif
17848  VdbeFrame *pFrame;      /* Parent frame */
17849  int nFrame;             /* Number of frames in pFrame list */
17850  u32 expmask;            /* Binding to these vars invalidates VM */
17851};
17852
17853/*
17854** The following are allowed values for Vdbe.magic
17855*/
17856#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
17857#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
17858#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
17859#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
17860
17861/*
17862** Function prototypes
17863*/
17864SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
17865void sqliteVdbePopStack(Vdbe*,int);
17866SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
17867#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
17868SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
17869#endif
17870SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
17871SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
17872SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
17873SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
17874SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
17875
17876int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
17877SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
17878SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
17879SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
17880SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
17881SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
17882SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
17883SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
17884SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
17885SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
17886SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
17887SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
17888SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
17889SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
17890SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
17891SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
17892SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
17893SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
17894SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
17895SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
17896SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
17897SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
17898SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
17899SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
17900SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
17901SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
17902SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
17903SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
17904SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
17905SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
17906SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
17907SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
17908SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
17909SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
17910SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
17911SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
17912SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
17913
17914#ifndef SQLITE_OMIT_FOREIGN_KEY
17915SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
17916#else
17917# define sqlite3VdbeCheckFk(p,i) 0
17918#endif
17919
17920#ifndef SQLITE_OMIT_SHARED_CACHE
17921SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p);
17922#else
17923# define sqlite3VdbeMutexArrayEnter(p)
17924#endif
17925
17926SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
17927#ifdef SQLITE_DEBUG
17928SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
17929SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
17930#endif
17931SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
17932
17933#ifndef SQLITE_OMIT_INCRBLOB
17934SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
17935#else
17936  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
17937#endif
17938
17939#endif /* !defined(_VDBEINT_H_) */
17940
17941/************** End of vdbeInt.h *********************************************/
17942/************** Continuing where we left off in utf.c ************************/
17943
17944#ifndef SQLITE_AMALGAMATION
17945/*
17946** The following constant value is used by the SQLITE_BIGENDIAN and
17947** SQLITE_LITTLEENDIAN macros.
17948*/
17949SQLITE_PRIVATE const int sqlite3one = 1;
17950#endif /* SQLITE_AMALGAMATION */
17951
17952/*
17953** This lookup table is used to help decode the first byte of
17954** a multi-byte UTF8 character.
17955*/
17956static const unsigned char sqlite3Utf8Trans1[] = {
17957  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17958  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
17959  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
17960  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
17961  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17962  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
17963  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17964  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
17965};
17966
17967
17968#define WRITE_UTF8(zOut, c) {                          \
17969  if( c<0x00080 ){                                     \
17970    *zOut++ = (u8)(c&0xFF);                            \
17971  }                                                    \
17972  else if( c<0x00800 ){                                \
17973    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
17974    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
17975  }                                                    \
17976  else if( c<0x10000 ){                                \
17977    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
17978    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
17979    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
17980  }else{                                               \
17981    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
17982    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
17983    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
17984    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
17985  }                                                    \
17986}
17987
17988#define WRITE_UTF16LE(zOut, c) {                                    \
17989  if( c<=0xFFFF ){                                                  \
17990    *zOut++ = (u8)(c&0x00FF);                                       \
17991    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
17992  }else{                                                            \
17993    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
17994    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
17995    *zOut++ = (u8)(c&0x00FF);                                       \
17996    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
17997  }                                                                 \
17998}
17999
18000#define WRITE_UTF16BE(zOut, c) {                                    \
18001  if( c<=0xFFFF ){                                                  \
18002    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
18003    *zOut++ = (u8)(c&0x00FF);                                       \
18004  }else{                                                            \
18005    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
18006    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18007    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
18008    *zOut++ = (u8)(c&0x00FF);                                       \
18009  }                                                                 \
18010}
18011
18012#define READ_UTF16LE(zIn, TERM, c){                                   \
18013  c = (*zIn++);                                                       \
18014  c += ((*zIn++)<<8);                                                 \
18015  if( c>=0xD800 && c<0xE000 && TERM ){                                \
18016    int c2 = (*zIn++);                                                \
18017    c2 += ((*zIn++)<<8);                                              \
18018    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18019  }                                                                   \
18020}
18021
18022#define READ_UTF16BE(zIn, TERM, c){                                   \
18023  c = ((*zIn++)<<8);                                                  \
18024  c += (*zIn++);                                                      \
18025  if( c>=0xD800 && c<0xE000 && TERM ){                                \
18026    int c2 = ((*zIn++)<<8);                                           \
18027    c2 += (*zIn++);                                                   \
18028    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18029  }                                                                   \
18030}
18031
18032/*
18033** Translate a single UTF-8 character.  Return the unicode value.
18034**
18035** During translation, assume that the byte that zTerm points
18036** is a 0x00.
18037**
18038** Write a pointer to the next unread byte back into *pzNext.
18039**
18040** Notes On Invalid UTF-8:
18041**
18042**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
18043**     be encoded as a multi-byte character.  Any multi-byte character that
18044**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
18045**
18046**  *  This routine never allows a UTF16 surrogate value to be encoded.
18047**     If a multi-byte character attempts to encode a value between
18048**     0xd800 and 0xe000 then it is rendered as 0xfffd.
18049**
18050**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
18051**     byte of a character are interpreted as single-byte characters
18052**     and rendered as themselves even though they are technically
18053**     invalid characters.
18054**
18055**  *  This routine accepts an infinite number of different UTF8 encodings
18056**     for unicode values 0x80 and greater.  It do not change over-length
18057**     encodings to 0xfffd as some systems recommend.
18058*/
18059#define READ_UTF8(zIn, zTerm, c)                           \
18060  c = *(zIn++);                                            \
18061  if( c>=0xc0 ){                                           \
18062    c = sqlite3Utf8Trans1[c-0xc0];                         \
18063    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
18064      c = (c<<6) + (0x3f & *(zIn++));                      \
18065    }                                                      \
18066    if( c<0x80                                             \
18067        || (c&0xFFFFF800)==0xD800                          \
18068        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
18069  }
18070SQLITE_PRIVATE int sqlite3Utf8Read(
18071  const unsigned char *zIn,       /* First byte of UTF-8 character */
18072  const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
18073){
18074  int c;
18075
18076  /* Same as READ_UTF8() above but without the zTerm parameter.
18077  ** For this routine, we assume the UTF8 string is always zero-terminated.
18078  */
18079  c = *(zIn++);
18080  if( c>=0xc0 ){
18081    c = sqlite3Utf8Trans1[c-0xc0];
18082    while( (*zIn & 0xc0)==0x80 ){
18083      c = (c<<6) + (0x3f & *(zIn++));
18084    }
18085    if( c<0x80
18086        || (c&0xFFFFF800)==0xD800
18087        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
18088  }
18089  *pzNext = zIn;
18090  return c;
18091}
18092
18093
18094
18095
18096/*
18097** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
18098** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
18099*/
18100/* #define TRANSLATE_TRACE 1 */
18101
18102#ifndef SQLITE_OMIT_UTF16
18103/*
18104** This routine transforms the internal text encoding used by pMem to
18105** desiredEnc. It is an error if the string is already of the desired
18106** encoding, or if *pMem does not contain a string value.
18107*/
18108SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
18109  int len;                    /* Maximum length of output string in bytes */
18110  unsigned char *zOut;                  /* Output buffer */
18111  unsigned char *zIn;                   /* Input iterator */
18112  unsigned char *zTerm;                 /* End of input */
18113  unsigned char *z;                     /* Output iterator */
18114  unsigned int c;
18115
18116  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
18117  assert( pMem->flags&MEM_Str );
18118  assert( pMem->enc!=desiredEnc );
18119  assert( pMem->enc!=0 );
18120  assert( pMem->n>=0 );
18121
18122#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18123  {
18124    char zBuf[100];
18125    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18126    fprintf(stderr, "INPUT:  %s\n", zBuf);
18127  }
18128#endif
18129
18130  /* If the translation is between UTF-16 little and big endian, then
18131  ** all that is required is to swap the byte order. This case is handled
18132  ** differently from the others.
18133  */
18134  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
18135    u8 temp;
18136    int rc;
18137    rc = sqlite3VdbeMemMakeWriteable(pMem);
18138    if( rc!=SQLITE_OK ){
18139      assert( rc==SQLITE_NOMEM );
18140      return SQLITE_NOMEM;
18141    }
18142    zIn = (u8*)pMem->z;
18143    zTerm = &zIn[pMem->n&~1];
18144    while( zIn<zTerm ){
18145      temp = *zIn;
18146      *zIn = *(zIn+1);
18147      zIn++;
18148      *zIn++ = temp;
18149    }
18150    pMem->enc = desiredEnc;
18151    goto translate_out;
18152  }
18153
18154  /* Set len to the maximum number of bytes required in the output buffer. */
18155  if( desiredEnc==SQLITE_UTF8 ){
18156    /* When converting from UTF-16, the maximum growth results from
18157    ** translating a 2-byte character to a 4-byte UTF-8 character.
18158    ** A single byte is required for the output string
18159    ** nul-terminator.
18160    */
18161    pMem->n &= ~1;
18162    len = pMem->n * 2 + 1;
18163  }else{
18164    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
18165    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
18166    ** character. Two bytes are required in the output buffer for the
18167    ** nul-terminator.
18168    */
18169    len = pMem->n * 2 + 2;
18170  }
18171
18172  /* Set zIn to point at the start of the input buffer and zTerm to point 1
18173  ** byte past the end.
18174  **
18175  ** Variable zOut is set to point at the output buffer, space obtained
18176  ** from sqlite3_malloc().
18177  */
18178  zIn = (u8*)pMem->z;
18179  zTerm = &zIn[pMem->n];
18180  zOut = sqlite3DbMallocRaw(pMem->db, len);
18181  if( !zOut ){
18182    return SQLITE_NOMEM;
18183  }
18184  z = zOut;
18185
18186  if( pMem->enc==SQLITE_UTF8 ){
18187    if( desiredEnc==SQLITE_UTF16LE ){
18188      /* UTF-8 -> UTF-16 Little-endian */
18189      while( zIn<zTerm ){
18190        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18191        READ_UTF8(zIn, zTerm, c);
18192        WRITE_UTF16LE(z, c);
18193      }
18194    }else{
18195      assert( desiredEnc==SQLITE_UTF16BE );
18196      /* UTF-8 -> UTF-16 Big-endian */
18197      while( zIn<zTerm ){
18198        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18199        READ_UTF8(zIn, zTerm, c);
18200        WRITE_UTF16BE(z, c);
18201      }
18202    }
18203    pMem->n = (int)(z - zOut);
18204    *z++ = 0;
18205  }else{
18206    assert( desiredEnc==SQLITE_UTF8 );
18207    if( pMem->enc==SQLITE_UTF16LE ){
18208      /* UTF-16 Little-endian -> UTF-8 */
18209      while( zIn<zTerm ){
18210        READ_UTF16LE(zIn, zIn<zTerm, c);
18211        WRITE_UTF8(z, c);
18212      }
18213    }else{
18214      /* UTF-16 Big-endian -> UTF-8 */
18215      while( zIn<zTerm ){
18216        READ_UTF16BE(zIn, zIn<zTerm, c);
18217        WRITE_UTF8(z, c);
18218      }
18219    }
18220    pMem->n = (int)(z - zOut);
18221  }
18222  *z = 0;
18223  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
18224
18225  sqlite3VdbeMemRelease(pMem);
18226  pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
18227  pMem->enc = desiredEnc;
18228  pMem->flags |= (MEM_Term|MEM_Dyn);
18229  pMem->z = (char*)zOut;
18230  pMem->zMalloc = pMem->z;
18231
18232translate_out:
18233#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18234  {
18235    char zBuf[100];
18236    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18237    fprintf(stderr, "OUTPUT: %s\n", zBuf);
18238  }
18239#endif
18240  return SQLITE_OK;
18241}
18242
18243/*
18244** This routine checks for a byte-order mark at the beginning of the
18245** UTF-16 string stored in *pMem. If one is present, it is removed and
18246** the encoding of the Mem adjusted. This routine does not do any
18247** byte-swapping, it just sets Mem.enc appropriately.
18248**
18249** The allocation (static, dynamic etc.) and encoding of the Mem may be
18250** changed by this function.
18251*/
18252SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
18253  int rc = SQLITE_OK;
18254  u8 bom = 0;
18255
18256  assert( pMem->n>=0 );
18257  if( pMem->n>1 ){
18258    u8 b1 = *(u8 *)pMem->z;
18259    u8 b2 = *(((u8 *)pMem->z) + 1);
18260    if( b1==0xFE && b2==0xFF ){
18261      bom = SQLITE_UTF16BE;
18262    }
18263    if( b1==0xFF && b2==0xFE ){
18264      bom = SQLITE_UTF16LE;
18265    }
18266  }
18267
18268  if( bom ){
18269    rc = sqlite3VdbeMemMakeWriteable(pMem);
18270    if( rc==SQLITE_OK ){
18271      pMem->n -= 2;
18272      memmove(pMem->z, &pMem->z[2], pMem->n);
18273      pMem->z[pMem->n] = '\0';
18274      pMem->z[pMem->n+1] = '\0';
18275      pMem->flags |= MEM_Term;
18276      pMem->enc = bom;
18277    }
18278  }
18279  return rc;
18280}
18281#endif /* SQLITE_OMIT_UTF16 */
18282
18283/*
18284** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
18285** return the number of unicode characters in pZ up to (but not including)
18286** the first 0x00 byte. If nByte is not less than zero, return the
18287** number of unicode characters in the first nByte of pZ (or up to
18288** the first 0x00, whichever comes first).
18289*/
18290SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
18291  int r = 0;
18292  const u8 *z = (const u8*)zIn;
18293  const u8 *zTerm;
18294  if( nByte>=0 ){
18295    zTerm = &z[nByte];
18296  }else{
18297    zTerm = (const u8*)(-1);
18298  }
18299  assert( z<=zTerm );
18300  while( *z!=0 && z<zTerm ){
18301    SQLITE_SKIP_UTF8(z);
18302    r++;
18303  }
18304  return r;
18305}
18306
18307/* This test function is not currently used by the automated test-suite.
18308** Hence it is only available in debug builds.
18309*/
18310#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
18311/*
18312** Translate UTF-8 to UTF-8.
18313**
18314** This has the effect of making sure that the string is well-formed
18315** UTF-8.  Miscoded characters are removed.
18316**
18317** The translation is done in-place (since it is impossible for the
18318** correct UTF-8 encoding to be longer than a malformed encoding).
18319*/
18320SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
18321  unsigned char *zOut = zIn;
18322  unsigned char *zStart = zIn;
18323  u32 c;
18324
18325  while( zIn[0] ){
18326    c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
18327    if( c!=0xfffd ){
18328      WRITE_UTF8(zOut, c);
18329    }
18330  }
18331  *zOut = 0;
18332  return (int)(zOut - zStart);
18333}
18334#endif
18335
18336#ifndef SQLITE_OMIT_UTF16
18337/*
18338** Convert a UTF-16 string in the native encoding into a UTF-8 string.
18339** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
18340** be freed by the calling function.
18341**
18342** NULL is returned if there is an allocation error.
18343*/
18344SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
18345  Mem m;
18346  memset(&m, 0, sizeof(m));
18347  m.db = db;
18348  sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
18349  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
18350  if( db->mallocFailed ){
18351    sqlite3VdbeMemRelease(&m);
18352    m.z = 0;
18353  }
18354  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
18355  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
18356  return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
18357}
18358
18359/*
18360** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
18361** enc. A pointer to the new string is returned, and the value of *pnOut
18362** is set to the length of the returned string in bytes. The call should
18363** arrange to call sqlite3DbFree() on the returned pointer when it is
18364** no longer required.
18365**
18366** If a malloc failure occurs, NULL is returned and the db.mallocFailed
18367** flag set.
18368*/
18369#ifdef SQLITE_ENABLE_STAT2
18370SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
18371  Mem m;
18372  memset(&m, 0, sizeof(m));
18373  m.db = db;
18374  sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
18375  if( sqlite3VdbeMemTranslate(&m, enc) ){
18376    assert( db->mallocFailed );
18377    return 0;
18378  }
18379  assert( m.z==m.zMalloc );
18380  *pnOut = m.n;
18381  return m.z;
18382}
18383#endif
18384
18385/*
18386** zIn is a UTF-16 encoded unicode string at least nChar characters long.
18387** Return the number of bytes in the first nChar unicode characters
18388** in pZ.  nChar must be non-negative.
18389*/
18390SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
18391  int c;
18392  unsigned char const *z = zIn;
18393  int n = 0;
18394
18395  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
18396    while( n<nChar ){
18397      READ_UTF16BE(z, 1, c);
18398      n++;
18399    }
18400  }else{
18401    while( n<nChar ){
18402      READ_UTF16LE(z, 1, c);
18403      n++;
18404    }
18405  }
18406  return (int)(z-(unsigned char const *)zIn);
18407}
18408
18409#if defined(SQLITE_TEST)
18410/*
18411** This routine is called from the TCL test function "translate_selftest".
18412** It checks that the primitives for serializing and deserializing
18413** characters in each encoding are inverses of each other.
18414*/
18415SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
18416  unsigned int i, t;
18417  unsigned char zBuf[20];
18418  unsigned char *z;
18419  int n;
18420  unsigned int c;
18421
18422  for(i=0; i<0x00110000; i++){
18423    z = zBuf;
18424    WRITE_UTF8(z, i);
18425    n = (int)(z-zBuf);
18426    assert( n>0 && n<=4 );
18427    z[0] = 0;
18428    z = zBuf;
18429    c = sqlite3Utf8Read(z, (const u8**)&z);
18430    t = i;
18431    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
18432    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
18433    assert( c==t );
18434    assert( (z-zBuf)==n );
18435  }
18436  for(i=0; i<0x00110000; i++){
18437    if( i>=0xD800 && i<0xE000 ) continue;
18438    z = zBuf;
18439    WRITE_UTF16LE(z, i);
18440    n = (int)(z-zBuf);
18441    assert( n>0 && n<=4 );
18442    z[0] = 0;
18443    z = zBuf;
18444    READ_UTF16LE(z, 1, c);
18445    assert( c==i );
18446    assert( (z-zBuf)==n );
18447  }
18448  for(i=0; i<0x00110000; i++){
18449    if( i>=0xD800 && i<0xE000 ) continue;
18450    z = zBuf;
18451    WRITE_UTF16BE(z, i);
18452    n = (int)(z-zBuf);
18453    assert( n>0 && n<=4 );
18454    z[0] = 0;
18455    z = zBuf;
18456    READ_UTF16BE(z, 1, c);
18457    assert( c==i );
18458    assert( (z-zBuf)==n );
18459  }
18460}
18461#endif /* SQLITE_TEST */
18462#endif /* SQLITE_OMIT_UTF16 */
18463
18464/************** End of utf.c *************************************************/
18465/************** Begin file util.c ********************************************/
18466/*
18467** 2001 September 15
18468**
18469** The author disclaims copyright to this source code.  In place of
18470** a legal notice, here is a blessing:
18471**
18472**    May you do good and not evil.
18473**    May you find forgiveness for yourself and forgive others.
18474**    May you share freely, never taking more than you give.
18475**
18476*************************************************************************
18477** Utility functions used throughout sqlite.
18478**
18479** This file contains functions for allocating memory, comparing
18480** strings, and stuff like that.
18481**
18482*/
18483#ifdef SQLITE_HAVE_ISNAN
18484# include <math.h>
18485#endif
18486
18487/*
18488** Routine needed to support the testcase() macro.
18489*/
18490#ifdef SQLITE_COVERAGE_TEST
18491SQLITE_PRIVATE void sqlite3Coverage(int x){
18492  static int dummy = 0;
18493  dummy += x;
18494}
18495#endif
18496
18497/*
18498** Return true if the floating point value is Not a Number (NaN).
18499**
18500** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
18501** Otherwise, we have our own implementation that works on most systems.
18502*/
18503SQLITE_PRIVATE int sqlite3IsNaN(double x){
18504  int rc;   /* The value return */
18505#if !defined(SQLITE_HAVE_ISNAN)
18506  /*
18507  ** Systems that support the isnan() library function should probably
18508  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
18509  ** found that many systems do not have a working isnan() function so
18510  ** this implementation is provided as an alternative.
18511  **
18512  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
18513  ** On the other hand, the use of -ffast-math comes with the following
18514  ** warning:
18515  **
18516  **      This option [-ffast-math] should never be turned on by any
18517  **      -O option since it can result in incorrect output for programs
18518  **      which depend on an exact implementation of IEEE or ISO
18519  **      rules/specifications for math functions.
18520  **
18521  ** Under MSVC, this NaN test may fail if compiled with a floating-
18522  ** point precision mode other than /fp:precise.  From the MSDN
18523  ** documentation:
18524  **
18525  **      The compiler [with /fp:precise] will properly handle comparisons
18526  **      involving NaN. For example, x != x evaluates to true if x is NaN
18527  **      ...
18528  */
18529#ifdef __FAST_MATH__
18530# error SQLite will not work correctly with the -ffast-math option of GCC.
18531#endif
18532  volatile double y = x;
18533  volatile double z = y;
18534  rc = (y!=z);
18535#else  /* if defined(SQLITE_HAVE_ISNAN) */
18536  rc = isnan(x);
18537#endif /* SQLITE_HAVE_ISNAN */
18538  testcase( rc );
18539  return rc;
18540}
18541
18542/*
18543** Compute a string length that is limited to what can be stored in
18544** lower 30 bits of a 32-bit signed integer.
18545**
18546** The value returned will never be negative.  Nor will it ever be greater
18547** than the actual length of the string.  For very long strings (greater
18548** than 1GiB) the value returned might be less than the true string length.
18549*/
18550SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
18551  const char *z2 = z;
18552  if( z==0 ) return 0;
18553  while( *z2 ){ z2++; }
18554  return 0x3fffffff & (int)(z2 - z);
18555}
18556
18557/*
18558** Set the most recent error code and error string for the sqlite
18559** handle "db". The error code is set to "err_code".
18560**
18561** If it is not NULL, string zFormat specifies the format of the
18562** error string in the style of the printf functions: The following
18563** format characters are allowed:
18564**
18565**      %s      Insert a string
18566**      %z      A string that should be freed after use
18567**      %d      Insert an integer
18568**      %T      Insert a token
18569**      %S      Insert the first element of a SrcList
18570**
18571** zFormat and any string tokens that follow it are assumed to be
18572** encoded in UTF-8.
18573**
18574** To clear the most recent error for sqlite handle "db", sqlite3Error
18575** should be called with err_code set to SQLITE_OK and zFormat set
18576** to NULL.
18577*/
18578SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
18579  if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
18580    db->errCode = err_code;
18581    if( zFormat ){
18582      char *z;
18583      va_list ap;
18584      va_start(ap, zFormat);
18585      z = sqlite3VMPrintf(db, zFormat, ap);
18586      va_end(ap);
18587      sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
18588    }else{
18589      sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
18590    }
18591  }
18592}
18593
18594/*
18595** Add an error message to pParse->zErrMsg and increment pParse->nErr.
18596** The following formatting characters are allowed:
18597**
18598**      %s      Insert a string
18599**      %z      A string that should be freed after use
18600**      %d      Insert an integer
18601**      %T      Insert a token
18602**      %S      Insert the first element of a SrcList
18603**
18604** This function should be used to report any error that occurs whilst
18605** compiling an SQL statement (i.e. within sqlite3_prepare()). The
18606** last thing the sqlite3_prepare() function does is copy the error
18607** stored by this function into the database handle using sqlite3Error().
18608** Function sqlite3Error() should be used during statement execution
18609** (sqlite3_step() etc.).
18610*/
18611SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
18612  va_list ap;
18613  sqlite3 *db = pParse->db;
18614  pParse->nErr++;
18615  sqlite3DbFree(db, pParse->zErrMsg);
18616  va_start(ap, zFormat);
18617  pParse->zErrMsg = sqlite3VMPrintf(db, zFormat, ap);
18618  va_end(ap);
18619  pParse->rc = SQLITE_ERROR;
18620}
18621
18622/*
18623** Clear the error message in pParse, if any
18624*/
18625SQLITE_PRIVATE void sqlite3ErrorClear(Parse *pParse){
18626  sqlite3DbFree(pParse->db, pParse->zErrMsg);
18627  pParse->zErrMsg = 0;
18628  pParse->nErr = 0;
18629}
18630
18631/*
18632** Convert an SQL-style quoted string into a normal string by removing
18633** the quote characters.  The conversion is done in-place.  If the
18634** input does not begin with a quote character, then this routine
18635** is a no-op.
18636**
18637** The input string must be zero-terminated.  A new zero-terminator
18638** is added to the dequoted string.
18639**
18640** The return value is -1 if no dequoting occurs or the length of the
18641** dequoted string, exclusive of the zero terminator, if dequoting does
18642** occur.
18643**
18644** 2002-Feb-14: This routine is extended to remove MS-Access style
18645** brackets from around identifers.  For example:  "[a-b-c]" becomes
18646** "a-b-c".
18647*/
18648SQLITE_PRIVATE int sqlite3Dequote(char *z){
18649  char quote;
18650  int i, j;
18651  if( z==0 ) return -1;
18652  quote = z[0];
18653  switch( quote ){
18654    case '\'':  break;
18655    case '"':   break;
18656    case '`':   break;                /* For MySQL compatibility */
18657    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
18658    default:    return -1;
18659  }
18660  for(i=1, j=0; ALWAYS(z[i]); i++){
18661    if( z[i]==quote ){
18662      if( z[i+1]==quote ){
18663        z[j++] = quote;
18664        i++;
18665      }else{
18666        break;
18667      }
18668    }else{
18669      z[j++] = z[i];
18670    }
18671  }
18672  z[j] = 0;
18673  return j;
18674}
18675
18676/* Convenient short-hand */
18677#define UpperToLower sqlite3UpperToLower
18678
18679/*
18680** Some systems have stricmp().  Others have strcasecmp().  Because
18681** there is no consistency, we will define our own.
18682*/
18683SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
18684  register unsigned char *a, *b;
18685  a = (unsigned char *)zLeft;
18686  b = (unsigned char *)zRight;
18687  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18688  return UpperToLower[*a] - UpperToLower[*b];
18689}
18690SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
18691  register unsigned char *a, *b;
18692  a = (unsigned char *)zLeft;
18693  b = (unsigned char *)zRight;
18694  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18695  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
18696}
18697
18698/*
18699** Return TRUE if z is a pure numeric string.  Return FALSE and leave
18700** *realnum unchanged if the string contains any character which is not
18701** part of a number.
18702**
18703** If the string is pure numeric, set *realnum to TRUE if the string
18704** contains the '.' character or an "E+000" style exponentiation suffix.
18705** Otherwise set *realnum to FALSE.  Note that just becaue *realnum is
18706** false does not mean that the number can be successfully converted into
18707** an integer - it might be too big.
18708**
18709** An empty string is considered non-numeric.
18710*/
18711SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
18712  int incr = (enc==SQLITE_UTF8?1:2);
18713  if( enc==SQLITE_UTF16BE ) z++;
18714  if( *z=='-' || *z=='+' ) z += incr;
18715  if( !sqlite3Isdigit(*z) ){
18716    return 0;
18717  }
18718  z += incr;
18719  *realnum = 0;
18720  while( sqlite3Isdigit(*z) ){ z += incr; }
18721  if( *z=='.' ){
18722    z += incr;
18723    if( !sqlite3Isdigit(*z) ) return 0;
18724    while( sqlite3Isdigit(*z) ){ z += incr; }
18725    *realnum = 1;
18726  }
18727  if( *z=='e' || *z=='E' ){
18728    z += incr;
18729    if( *z=='+' || *z=='-' ) z += incr;
18730    if( !sqlite3Isdigit(*z) ) return 0;
18731    while( sqlite3Isdigit(*z) ){ z += incr; }
18732    *realnum = 1;
18733  }
18734  return *z==0;
18735}
18736
18737/*
18738** The string z[] is an ASCII representation of a real number.
18739** Convert this string to a double.
18740**
18741** This routine assumes that z[] really is a valid number.  If it
18742** is not, the result is undefined.
18743**
18744** This routine is used instead of the library atof() function because
18745** the library atof() might want to use "," as the decimal point instead
18746** of "." depending on how locale is set.  But that would cause problems
18747** for SQL.  So this routine always uses "." regardless of locale.
18748*/
18749SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
18750#ifndef SQLITE_OMIT_FLOATING_POINT
18751  const char *zBegin = z;
18752  /* sign * significand * (10 ^ (esign * exponent)) */
18753  int sign = 1;   /* sign of significand */
18754  i64 s = 0;      /* significand */
18755  int d = 0;      /* adjust exponent for shifting decimal point */
18756  int esign = 1;  /* sign of exponent */
18757  int e = 0;      /* exponent */
18758  double result;
18759  int nDigits = 0;
18760
18761  /* skip leading spaces */
18762  while( sqlite3Isspace(*z) ) z++;
18763  /* get sign of significand */
18764  if( *z=='-' ){
18765    sign = -1;
18766    z++;
18767  }else if( *z=='+' ){
18768    z++;
18769  }
18770  /* skip leading zeroes */
18771  while( z[0]=='0' ) z++, nDigits++;
18772
18773  /* copy max significant digits to significand */
18774  while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
18775    s = s*10 + (*z - '0');
18776    z++, nDigits++;
18777  }
18778  /* skip non-significant significand digits
18779  ** (increase exponent by d to shift decimal left) */
18780  while( sqlite3Isdigit(*z) ) z++, nDigits++, d++;
18781
18782  /* if decimal point is present */
18783  if( *z=='.' ){
18784    z++;
18785    /* copy digits from after decimal to significand
18786    ** (decrease exponent by d to shift decimal right) */
18787    while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
18788      s = s*10 + (*z - '0');
18789      z++, nDigits++, d--;
18790    }
18791    /* skip non-significant digits */
18792    while( sqlite3Isdigit(*z) ) z++, nDigits++;
18793  }
18794
18795  /* if exponent is present */
18796  if( *z=='e' || *z=='E' ){
18797    z++;
18798    /* get sign of exponent */
18799    if( *z=='-' ){
18800      esign = -1;
18801      z++;
18802    }else if( *z=='+' ){
18803      z++;
18804    }
18805    /* copy digits to exponent */
18806    while( sqlite3Isdigit(*z) ){
18807      e = e*10 + (*z - '0');
18808      z++;
18809    }
18810  }
18811
18812  /* adjust exponent by d, and update sign */
18813  e = (e*esign) + d;
18814  if( e<0 ) {
18815    esign = -1;
18816    e *= -1;
18817  } else {
18818    esign = 1;
18819  }
18820
18821  /* if 0 significand */
18822  if( !s ) {
18823    /* In the IEEE 754 standard, zero is signed.
18824    ** Add the sign if we've seen at least one digit */
18825    result = (sign<0 && nDigits) ? -(double)0 : (double)0;
18826  } else {
18827    /* attempt to reduce exponent */
18828    if( esign>0 ){
18829      while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
18830    }else{
18831      while( !(s%10) && e>0 ) e--,s/=10;
18832    }
18833
18834    /* adjust the sign of significand */
18835    s = sign<0 ? -s : s;
18836
18837    /* if exponent, scale significand as appropriate
18838    ** and store in result. */
18839    if( e ){
18840      double scale = 1.0;
18841      /* attempt to handle extremely small/large numbers better */
18842      if( e>307 && e<342 ){
18843        while( e%308 ) { scale *= 1.0e+1; e -= 1; }
18844        if( esign<0 ){
18845          result = s / scale;
18846          result /= 1.0e+308;
18847        }else{
18848          result = s * scale;
18849          result *= 1.0e+308;
18850        }
18851      }else{
18852        /* 1.0e+22 is the largest power of 10 than can be
18853        ** represented exactly. */
18854        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
18855        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
18856        if( esign<0 ){
18857          result = s / scale;
18858        }else{
18859          result = s * scale;
18860        }
18861      }
18862    } else {
18863      result = (double)s;
18864    }
18865  }
18866
18867  /* store the result */
18868  *pResult = result;
18869
18870  /* return number of characters used */
18871  return (int)(z - zBegin);
18872#else
18873  return sqlite3Atoi64(z, pResult);
18874#endif /* SQLITE_OMIT_FLOATING_POINT */
18875}
18876
18877/*
18878** Compare the 19-character string zNum against the text representation
18879** value 2^63:  9223372036854775808.  Return negative, zero, or positive
18880** if zNum is less than, equal to, or greater than the string.
18881**
18882** Unlike memcmp() this routine is guaranteed to return the difference
18883** in the values of the last digit if the only difference is in the
18884** last digit.  So, for example,
18885**
18886**      compare2pow63("9223372036854775800")
18887**
18888** will return -8.
18889*/
18890static int compare2pow63(const char *zNum){
18891  int c;
18892  c = memcmp(zNum,"922337203685477580",18)*10;
18893  if( c==0 ){
18894    c = zNum[18] - '8';
18895  }
18896  return c;
18897}
18898
18899
18900/*
18901** Return TRUE if zNum is a 64-bit signed integer and write
18902** the value of the integer into *pNum.  If zNum is not an integer
18903** or is an integer that is too large to be expressed with 64 bits,
18904** then return false.
18905**
18906** When this routine was originally written it dealt with only
18907** 32-bit numbers.  At that time, it was much faster than the
18908** atoi() library routine in RedHat 7.2.
18909*/
18910SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
18911  i64 v = 0;
18912  int neg;
18913  int i, c;
18914  const char *zStart;
18915  while( sqlite3Isspace(*zNum) ) zNum++;
18916  if( *zNum=='-' ){
18917    neg = 1;
18918    zNum++;
18919  }else if( *zNum=='+' ){
18920    neg = 0;
18921    zNum++;
18922  }else{
18923    neg = 0;
18924  }
18925  zStart = zNum;
18926  while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
18927  for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
18928    v = v*10 + c - '0';
18929  }
18930  *pNum = neg ? -v : v;
18931  if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
18932    /* zNum is empty or contains non-numeric text or is longer
18933    ** than 19 digits (thus guaranting that it is too large) */
18934    return 0;
18935  }else if( i<19 ){
18936    /* Less than 19 digits, so we know that it fits in 64 bits */
18937    return 1;
18938  }else{
18939    /* 19-digit numbers must be no larger than 9223372036854775807 if positive
18940    ** or 9223372036854775808 if negative.  Note that 9223372036854665808
18941    ** is 2^63. */
18942    return compare2pow63(zNum)<neg;
18943  }
18944}
18945
18946/*
18947** The string zNum represents an unsigned integer.  The zNum string
18948** consists of one or more digit characters and is terminated by
18949** a zero character.  Any stray characters in zNum result in undefined
18950** behavior.
18951**
18952** If the unsigned integer that zNum represents will fit in a
18953** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
18954**
18955** If the negFlag parameter is true, that means that zNum really represents
18956** a negative number.  (The leading "-" is omitted from zNum.)  This
18957** parameter is needed to determine a boundary case.  A string
18958** of "9223373036854775808" returns false if negFlag is false or true
18959** if negFlag is true.
18960**
18961** Leading zeros are ignored.
18962*/
18963SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
18964  int i;
18965  int neg = 0;
18966
18967  assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */
18968
18969  if( negFlag ) neg = 1-neg;
18970  while( *zNum=='0' ){
18971    zNum++;   /* Skip leading zeros.  Ticket #2454 */
18972  }
18973  for(i=0; zNum[i]; i++){ assert( zNum[i]>='0' && zNum[i]<='9' ); }
18974  if( i<19 ){
18975    /* Guaranteed to fit if less than 19 digits */
18976    return 1;
18977  }else if( i>19 ){
18978    /* Guaranteed to be too big if greater than 19 digits */
18979    return 0;
18980  }else{
18981    /* Compare against 2^63. */
18982    return compare2pow63(zNum)<neg;
18983  }
18984}
18985
18986/*
18987** If zNum represents an integer that will fit in 32-bits, then set
18988** *pValue to that integer and return true.  Otherwise return false.
18989**
18990** Any non-numeric characters that following zNum are ignored.
18991** This is different from sqlite3Atoi64() which requires the
18992** input number to be zero-terminated.
18993*/
18994SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
18995  sqlite_int64 v = 0;
18996  int i, c;
18997  int neg = 0;
18998  if( zNum[0]=='-' ){
18999    neg = 1;
19000    zNum++;
19001  }else if( zNum[0]=='+' ){
19002    zNum++;
19003  }
19004  while( zNum[0]=='0' ) zNum++;
19005  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
19006    v = v*10 + c;
19007  }
19008
19009  /* The longest decimal representation of a 32 bit integer is 10 digits:
19010  **
19011  **             1234567890
19012  **     2^31 -> 2147483648
19013  */
19014  if( i>10 ){
19015    return 0;
19016  }
19017  if( v-neg>2147483647 ){
19018    return 0;
19019  }
19020  if( neg ){
19021    v = -v;
19022  }
19023  *pValue = (int)v;
19024  return 1;
19025}
19026
19027/*
19028** The variable-length integer encoding is as follows:
19029**
19030** KEY:
19031**         A = 0xxxxxxx    7 bits of data and one flag bit
19032**         B = 1xxxxxxx    7 bits of data and one flag bit
19033**         C = xxxxxxxx    8 bits of data
19034**
19035**  7 bits - A
19036** 14 bits - BA
19037** 21 bits - BBA
19038** 28 bits - BBBA
19039** 35 bits - BBBBA
19040** 42 bits - BBBBBA
19041** 49 bits - BBBBBBA
19042** 56 bits - BBBBBBBA
19043** 64 bits - BBBBBBBBC
19044*/
19045
19046/*
19047** Write a 64-bit variable-length integer to memory starting at p[0].
19048** The length of data write will be between 1 and 9 bytes.  The number
19049** of bytes written is returned.
19050**
19051** A variable-length integer consists of the lower 7 bits of each byte
19052** for all bytes that have the 8th bit set and one byte with the 8th
19053** bit clear.  Except, if we get to the 9th byte, it stores the full
19054** 8 bits and is the last byte.
19055*/
19056SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
19057  int i, j, n;
19058  u8 buf[10];
19059  if( v & (((u64)0xff000000)<<32) ){
19060    p[8] = (u8)v;
19061    v >>= 8;
19062    for(i=7; i>=0; i--){
19063      p[i] = (u8)((v & 0x7f) | 0x80);
19064      v >>= 7;
19065    }
19066    return 9;
19067  }
19068  n = 0;
19069  do{
19070    buf[n++] = (u8)((v & 0x7f) | 0x80);
19071    v >>= 7;
19072  }while( v!=0 );
19073  buf[0] &= 0x7f;
19074  assert( n<=9 );
19075  for(i=0, j=n-1; j>=0; j--, i++){
19076    p[i] = buf[j];
19077  }
19078  return n;
19079}
19080
19081/*
19082** This routine is a faster version of sqlite3PutVarint() that only
19083** works for 32-bit positive integers and which is optimized for
19084** the common case of small integers.  A MACRO version, putVarint32,
19085** is provided which inlines the single-byte case.  All code should use
19086** the MACRO version as this function assumes the single-byte case has
19087** already been handled.
19088*/
19089SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
19090#ifndef putVarint32
19091  if( (v & ~0x7f)==0 ){
19092    p[0] = v;
19093    return 1;
19094  }
19095#endif
19096  if( (v & ~0x3fff)==0 ){
19097    p[0] = (u8)((v>>7) | 0x80);
19098    p[1] = (u8)(v & 0x7f);
19099    return 2;
19100  }
19101  return sqlite3PutVarint(p, v);
19102}
19103
19104/*
19105** Read a 64-bit variable-length integer from memory starting at p[0].
19106** Return the number of bytes read.  The value is stored in *v.
19107*/
19108SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
19109  u32 a,b,s;
19110
19111  a = *p;
19112  /* a: p0 (unmasked) */
19113  if (!(a&0x80))
19114  {
19115    *v = a;
19116    return 1;
19117  }
19118
19119  p++;
19120  b = *p;
19121  /* b: p1 (unmasked) */
19122  if (!(b&0x80))
19123  {
19124    a &= 0x7f;
19125    a = a<<7;
19126    a |= b;
19127    *v = a;
19128    return 2;
19129  }
19130
19131  p++;
19132  a = a<<14;
19133  a |= *p;
19134  /* a: p0<<14 | p2 (unmasked) */
19135  if (!(a&0x80))
19136  {
19137    a &= (0x7f<<14)|(0x7f);
19138    b &= 0x7f;
19139    b = b<<7;
19140    a |= b;
19141    *v = a;
19142    return 3;
19143  }
19144
19145  /* CSE1 from below */
19146  a &= (0x7f<<14)|(0x7f);
19147  p++;
19148  b = b<<14;
19149  b |= *p;
19150  /* b: p1<<14 | p3 (unmasked) */
19151  if (!(b&0x80))
19152  {
19153    b &= (0x7f<<14)|(0x7f);
19154    /* moved CSE1 up */
19155    /* a &= (0x7f<<14)|(0x7f); */
19156    a = a<<7;
19157    a |= b;
19158    *v = a;
19159    return 4;
19160  }
19161
19162  /* a: p0<<14 | p2 (masked) */
19163  /* b: p1<<14 | p3 (unmasked) */
19164  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19165  /* moved CSE1 up */
19166  /* a &= (0x7f<<14)|(0x7f); */
19167  b &= (0x7f<<14)|(0x7f);
19168  s = a;
19169  /* s: p0<<14 | p2 (masked) */
19170
19171  p++;
19172  a = a<<14;
19173  a |= *p;
19174  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19175  if (!(a&0x80))
19176  {
19177    /* we can skip these cause they were (effectively) done above in calc'ing s */
19178    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19179    /* b &= (0x7f<<14)|(0x7f); */
19180    b = b<<7;
19181    a |= b;
19182    s = s>>18;
19183    *v = ((u64)s)<<32 | a;
19184    return 5;
19185  }
19186
19187  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19188  s = s<<7;
19189  s |= b;
19190  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19191
19192  p++;
19193  b = b<<14;
19194  b |= *p;
19195  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
19196  if (!(b&0x80))
19197  {
19198    /* we can skip this cause it was (effectively) done above in calc'ing s */
19199    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19200    a &= (0x7f<<14)|(0x7f);
19201    a = a<<7;
19202    a |= b;
19203    s = s>>18;
19204    *v = ((u64)s)<<32 | a;
19205    return 6;
19206  }
19207
19208  p++;
19209  a = a<<14;
19210  a |= *p;
19211  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
19212  if (!(a&0x80))
19213  {
19214    a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19215    b &= (0x7f<<14)|(0x7f);
19216    b = b<<7;
19217    a |= b;
19218    s = s>>11;
19219    *v = ((u64)s)<<32 | a;
19220    return 7;
19221  }
19222
19223  /* CSE2 from below */
19224  a &= (0x7f<<14)|(0x7f);
19225  p++;
19226  b = b<<14;
19227  b |= *p;
19228  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
19229  if (!(b&0x80))
19230  {
19231    b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19232    /* moved CSE2 up */
19233    /* a &= (0x7f<<14)|(0x7f); */
19234    a = a<<7;
19235    a |= b;
19236    s = s>>4;
19237    *v = ((u64)s)<<32 | a;
19238    return 8;
19239  }
19240
19241  p++;
19242  a = a<<15;
19243  a |= *p;
19244  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
19245
19246  /* moved CSE2 up */
19247  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
19248  b &= (0x7f<<14)|(0x7f);
19249  b = b<<8;
19250  a |= b;
19251
19252  s = s<<4;
19253  b = p[-4];
19254  b &= 0x7f;
19255  b = b>>3;
19256  s |= b;
19257
19258  *v = ((u64)s)<<32 | a;
19259
19260  return 9;
19261}
19262
19263/*
19264** Read a 32-bit variable-length integer from memory starting at p[0].
19265** Return the number of bytes read.  The value is stored in *v.
19266**
19267** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
19268** integer, then set *v to 0xffffffff.
19269**
19270** A MACRO version, getVarint32, is provided which inlines the
19271** single-byte case.  All code should use the MACRO version as
19272** this function assumes the single-byte case has already been handled.
19273*/
19274SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
19275  u32 a,b;
19276
19277  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
19278  ** by the getVarin32() macro */
19279  a = *p;
19280  /* a: p0 (unmasked) */
19281#ifndef getVarint32
19282  if (!(a&0x80))
19283  {
19284    /* Values between 0 and 127 */
19285    *v = a;
19286    return 1;
19287  }
19288#endif
19289
19290  /* The 2-byte case */
19291  p++;
19292  b = *p;
19293  /* b: p1 (unmasked) */
19294  if (!(b&0x80))
19295  {
19296    /* Values between 128 and 16383 */
19297    a &= 0x7f;
19298    a = a<<7;
19299    *v = a | b;
19300    return 2;
19301  }
19302
19303  /* The 3-byte case */
19304  p++;
19305  a = a<<14;
19306  a |= *p;
19307  /* a: p0<<14 | p2 (unmasked) */
19308  if (!(a&0x80))
19309  {
19310    /* Values between 16384 and 2097151 */
19311    a &= (0x7f<<14)|(0x7f);
19312    b &= 0x7f;
19313    b = b<<7;
19314    *v = a | b;
19315    return 3;
19316  }
19317
19318  /* A 32-bit varint is used to store size information in btrees.
19319  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
19320  ** A 3-byte varint is sufficient, for example, to record the size
19321  ** of a 1048569-byte BLOB or string.
19322  **
19323  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
19324  ** rare larger cases can be handled by the slower 64-bit varint
19325  ** routine.
19326  */
19327#if 1
19328  {
19329    u64 v64;
19330    u8 n;
19331
19332    p -= 2;
19333    n = sqlite3GetVarint(p, &v64);
19334    assert( n>3 && n<=9 );
19335    if( (v64 & SQLITE_MAX_U32)!=v64 ){
19336      *v = 0xffffffff;
19337    }else{
19338      *v = (u32)v64;
19339    }
19340    return n;
19341  }
19342
19343#else
19344  /* For following code (kept for historical record only) shows an
19345  ** unrolling for the 3- and 4-byte varint cases.  This code is
19346  ** slightly faster, but it is also larger and much harder to test.
19347  */
19348  p++;
19349  b = b<<14;
19350  b |= *p;
19351  /* b: p1<<14 | p3 (unmasked) */
19352  if (!(b&0x80))
19353  {
19354    /* Values between 2097152 and 268435455 */
19355    b &= (0x7f<<14)|(0x7f);
19356    a &= (0x7f<<14)|(0x7f);
19357    a = a<<7;
19358    *v = a | b;
19359    return 4;
19360  }
19361
19362  p++;
19363  a = a<<14;
19364  a |= *p;
19365  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19366  if (!(a&0x80))
19367  {
19368    /* Walues  between 268435456 and 34359738367 */
19369    a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19370    b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19371    b = b<<7;
19372    *v = a | b;
19373    return 5;
19374  }
19375
19376  /* We can only reach this point when reading a corrupt database
19377  ** file.  In that case we are not in any hurry.  Use the (relatively
19378  ** slow) general-purpose sqlite3GetVarint() routine to extract the
19379  ** value. */
19380  {
19381    u64 v64;
19382    u8 n;
19383
19384    p -= 4;
19385    n = sqlite3GetVarint(p, &v64);
19386    assert( n>5 && n<=9 );
19387    *v = (u32)v64;
19388    return n;
19389  }
19390#endif
19391}
19392
19393/*
19394** Return the number of bytes that will be needed to store the given
19395** 64-bit integer.
19396*/
19397SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
19398  int i = 0;
19399  do{
19400    i++;
19401    v >>= 7;
19402  }while( v!=0 && ALWAYS(i<9) );
19403  return i;
19404}
19405
19406
19407/*
19408** Read or write a four-byte big-endian integer value.
19409*/
19410SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
19411  return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
19412}
19413SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
19414  p[0] = (u8)(v>>24);
19415  p[1] = (u8)(v>>16);
19416  p[2] = (u8)(v>>8);
19417  p[3] = (u8)v;
19418}
19419
19420
19421
19422#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19423/*
19424** Translate a single byte of Hex into an integer.
19425** This routine only works if h really is a valid hexadecimal
19426** character:  0..9a..fA..F
19427*/
19428static u8 hexToInt(int h){
19429  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
19430#ifdef SQLITE_ASCII
19431  h += 9*(1&(h>>6));
19432#endif
19433#ifdef SQLITE_EBCDIC
19434  h += 9*(1&~(h>>4));
19435#endif
19436  return (u8)(h & 0xf);
19437}
19438#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19439
19440#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19441/*
19442** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
19443** value.  Return a pointer to its binary value.  Space to hold the
19444** binary value has been obtained from malloc and must be freed by
19445** the calling routine.
19446*/
19447SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
19448  char *zBlob;
19449  int i;
19450
19451  zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
19452  n--;
19453  if( zBlob ){
19454    for(i=0; i<n; i+=2){
19455      zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
19456    }
19457    zBlob[i/2] = 0;
19458  }
19459  return zBlob;
19460}
19461#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19462
19463
19464/*
19465** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
19466** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
19467** when this routine is called.
19468**
19469** This routine is called when entering an SQLite API.  The SQLITE_MAGIC_OPEN
19470** value indicates that the database connection passed into the API is
19471** open and is not being used by another thread.  By changing the value
19472** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
19473** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
19474** when the API exits.
19475**
19476** This routine is a attempt to detect if two threads use the
19477** same sqlite* pointer at the same time.  There is a race
19478** condition so it is possible that the error is not detected.
19479** But usually the problem will be seen.  The result will be an
19480** error which can be used to debug the application that is
19481** using SQLite incorrectly.
19482**
19483** Ticket #202:  If db->magic is not a valid open value, take care not
19484** to modify the db structure at all.  It could be that db is a stale
19485** pointer.  In other words, it could be that there has been a prior
19486** call to sqlite3_close(db) and db has been deallocated.  And we do
19487** not want to write into deallocated memory.
19488*/
19489#ifdef SQLITE_DEBUG
19490SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3 *db){
19491  if( db->magic==SQLITE_MAGIC_OPEN ){
19492    db->magic = SQLITE_MAGIC_BUSY;
19493    assert( sqlite3_mutex_held(db->mutex) );
19494    return 0;
19495  }else if( db->magic==SQLITE_MAGIC_BUSY ){
19496    db->magic = SQLITE_MAGIC_ERROR;
19497    db->u1.isInterrupted = 1;
19498  }
19499  return 1;
19500}
19501#endif
19502
19503/*
19504** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
19505** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
19506** when this routine is called.
19507*/
19508#ifdef SQLITE_DEBUG
19509SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3 *db){
19510  if( db->magic==SQLITE_MAGIC_BUSY ){
19511    db->magic = SQLITE_MAGIC_OPEN;
19512    assert( sqlite3_mutex_held(db->mutex) );
19513    return 0;
19514  }else{
19515    db->magic = SQLITE_MAGIC_ERROR;
19516    db->u1.isInterrupted = 1;
19517    return 1;
19518  }
19519}
19520#endif
19521
19522/*
19523** Check to make sure we have a valid db pointer.  This test is not
19524** foolproof but it does provide some measure of protection against
19525** misuse of the interface such as passing in db pointers that are
19526** NULL or which have been previously closed.  If this routine returns
19527** 1 it means that the db pointer is valid and 0 if it should not be
19528** dereferenced for any reason.  The calling function should invoke
19529** SQLITE_MISUSE immediately.
19530**
19531** sqlite3SafetyCheckOk() requires that the db pointer be valid for
19532** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
19533** open properly and is not fit for general use but which can be
19534** used as an argument to sqlite3_errmsg() or sqlite3_close().
19535*/
19536SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
19537  u32 magic;
19538  if( db==0 ) return 0;
19539  magic = db->magic;
19540  if( magic!=SQLITE_MAGIC_OPEN
19541#ifdef SQLITE_DEBUG
19542     && magic!=SQLITE_MAGIC_BUSY
19543#endif
19544  ){
19545    return 0;
19546  }else{
19547    return 1;
19548  }
19549}
19550SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
19551  u32 magic;
19552  magic = db->magic;
19553  if( magic!=SQLITE_MAGIC_SICK &&
19554      magic!=SQLITE_MAGIC_OPEN &&
19555      magic!=SQLITE_MAGIC_BUSY ) return 0;
19556  return 1;
19557}
19558
19559/************** End of util.c ************************************************/
19560/************** Begin file hash.c ********************************************/
19561/*
19562** 2001 September 22
19563**
19564** The author disclaims copyright to this source code.  In place of
19565** a legal notice, here is a blessing:
19566**
19567**    May you do good and not evil.
19568**    May you find forgiveness for yourself and forgive others.
19569**    May you share freely, never taking more than you give.
19570**
19571*************************************************************************
19572** This is the implementation of generic hash-tables
19573** used in SQLite.
19574*/
19575
19576/* Turn bulk memory into a hash table object by initializing the
19577** fields of the Hash structure.
19578**
19579** "pNew" is a pointer to the hash table that is to be initialized.
19580*/
19581SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
19582  assert( pNew!=0 );
19583  pNew->first = 0;
19584  pNew->count = 0;
19585  pNew->htsize = 0;
19586  pNew->ht = 0;
19587}
19588
19589/* Remove all entries from a hash table.  Reclaim all memory.
19590** Call this routine to delete a hash table or to reset a hash table
19591** to the empty state.
19592*/
19593SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
19594  HashElem *elem;         /* For looping over all elements of the table */
19595
19596  assert( pH!=0 );
19597  elem = pH->first;
19598  pH->first = 0;
19599  sqlite3_free(pH->ht);
19600  pH->ht = 0;
19601  pH->htsize = 0;
19602  while( elem ){
19603    HashElem *next_elem = elem->next;
19604    sqlite3_free(elem);
19605    elem = next_elem;
19606  }
19607  pH->count = 0;
19608}
19609
19610/*
19611** The hashing function.
19612*/
19613static unsigned int strHash(const char *z, int nKey){
19614  int h = 0;
19615  assert( nKey>=0 );
19616  while( nKey > 0  ){
19617    h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
19618    nKey--;
19619  }
19620  return h;
19621}
19622
19623
19624/* Link pNew element into the hash table pH.  If pEntry!=0 then also
19625** insert pNew into the pEntry hash bucket.
19626*/
19627static void insertElement(
19628  Hash *pH,              /* The complete hash table */
19629  struct _ht *pEntry,    /* The entry into which pNew is inserted */
19630  HashElem *pNew         /* The element to be inserted */
19631){
19632  HashElem *pHead;       /* First element already in pEntry */
19633  if( pEntry ){
19634    pHead = pEntry->count ? pEntry->chain : 0;
19635    pEntry->count++;
19636    pEntry->chain = pNew;
19637  }else{
19638    pHead = 0;
19639  }
19640  if( pHead ){
19641    pNew->next = pHead;
19642    pNew->prev = pHead->prev;
19643    if( pHead->prev ){ pHead->prev->next = pNew; }
19644    else             { pH->first = pNew; }
19645    pHead->prev = pNew;
19646  }else{
19647    pNew->next = pH->first;
19648    if( pH->first ){ pH->first->prev = pNew; }
19649    pNew->prev = 0;
19650    pH->first = pNew;
19651  }
19652}
19653
19654
19655/* Resize the hash table so that it cantains "new_size" buckets.
19656**
19657** The hash table might fail to resize if sqlite3_malloc() fails or
19658** if the new size is the same as the prior size.
19659** Return TRUE if the resize occurs and false if not.
19660*/
19661static int rehash(Hash *pH, unsigned int new_size){
19662  struct _ht *new_ht;            /* The new hash table */
19663  HashElem *elem, *next_elem;    /* For looping over existing elements */
19664
19665#if SQLITE_MALLOC_SOFT_LIMIT>0
19666  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
19667    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
19668  }
19669  if( new_size==pH->htsize ) return 0;
19670#endif
19671
19672  /* The inability to allocates space for a larger hash table is
19673  ** a performance hit but it is not a fatal error.  So mark the
19674  ** allocation as a benign.
19675  */
19676  sqlite3BeginBenignMalloc();
19677  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
19678  sqlite3EndBenignMalloc();
19679
19680  if( new_ht==0 ) return 0;
19681  sqlite3_free(pH->ht);
19682  pH->ht = new_ht;
19683  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
19684  memset(new_ht, 0, new_size*sizeof(struct _ht));
19685  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
19686    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
19687    next_elem = elem->next;
19688    insertElement(pH, &new_ht[h], elem);
19689  }
19690  return 1;
19691}
19692
19693/* This function (for internal use only) locates an element in an
19694** hash table that matches the given key.  The hash for this key has
19695** already been computed and is passed as the 4th parameter.
19696*/
19697static HashElem *findElementGivenHash(
19698  const Hash *pH,     /* The pH to be searched */
19699  const char *pKey,   /* The key we are searching for */
19700  int nKey,           /* Bytes in key (not counting zero terminator) */
19701  unsigned int h      /* The hash for this key. */
19702){
19703  HashElem *elem;                /* Used to loop thru the element list */
19704  int count;                     /* Number of elements left to test */
19705
19706  if( pH->ht ){
19707    struct _ht *pEntry = &pH->ht[h];
19708    elem = pEntry->chain;
19709    count = pEntry->count;
19710  }else{
19711    elem = pH->first;
19712    count = pH->count;
19713  }
19714  while( count-- && ALWAYS(elem) ){
19715    if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
19716      return elem;
19717    }
19718    elem = elem->next;
19719  }
19720  return 0;
19721}
19722
19723/* Remove a single entry from the hash table given a pointer to that
19724** element and a hash on the element's key.
19725*/
19726static void removeElementGivenHash(
19727  Hash *pH,         /* The pH containing "elem" */
19728  HashElem* elem,   /* The element to be removed from the pH */
19729  unsigned int h    /* Hash value for the element */
19730){
19731  struct _ht *pEntry;
19732  if( elem->prev ){
19733    elem->prev->next = elem->next;
19734  }else{
19735    pH->first = elem->next;
19736  }
19737  if( elem->next ){
19738    elem->next->prev = elem->prev;
19739  }
19740  if( pH->ht ){
19741    pEntry = &pH->ht[h];
19742    if( pEntry->chain==elem ){
19743      pEntry->chain = elem->next;
19744    }
19745    pEntry->count--;
19746    assert( pEntry->count>=0 );
19747  }
19748  sqlite3_free( elem );
19749  pH->count--;
19750  if( pH->count<=0 ){
19751    assert( pH->first==0 );
19752    assert( pH->count==0 );
19753    sqlite3HashClear(pH);
19754  }
19755}
19756
19757/* Attempt to locate an element of the hash table pH with a key
19758** that matches pKey,nKey.  Return the data for this element if it is
19759** found, or NULL if there is no match.
19760*/
19761SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
19762  HashElem *elem;    /* The element that matches key */
19763  unsigned int h;    /* A hash on key */
19764
19765  assert( pH!=0 );
19766  assert( pKey!=0 );
19767  assert( nKey>=0 );
19768  if( pH->ht ){
19769    h = strHash(pKey, nKey) % pH->htsize;
19770  }else{
19771    h = 0;
19772  }
19773  elem = findElementGivenHash(pH, pKey, nKey, h);
19774  return elem ? elem->data : 0;
19775}
19776
19777/* Insert an element into the hash table pH.  The key is pKey,nKey
19778** and the data is "data".
19779**
19780** If no element exists with a matching key, then a new
19781** element is created and NULL is returned.
19782**
19783** If another element already exists with the same key, then the
19784** new data replaces the old data and the old data is returned.
19785** The key is not copied in this instance.  If a malloc fails, then
19786** the new data is returned and the hash table is unchanged.
19787**
19788** If the "data" parameter to this function is NULL, then the
19789** element corresponding to "key" is removed from the hash table.
19790*/
19791SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
19792  unsigned int h;       /* the hash of the key modulo hash table size */
19793  HashElem *elem;       /* Used to loop thru the element list */
19794  HashElem *new_elem;   /* New element added to the pH */
19795
19796  assert( pH!=0 );
19797  assert( pKey!=0 );
19798  assert( nKey>=0 );
19799  if( pH->htsize ){
19800    h = strHash(pKey, nKey) % pH->htsize;
19801  }else{
19802    h = 0;
19803  }
19804  elem = findElementGivenHash(pH,pKey,nKey,h);
19805  if( elem ){
19806    void *old_data = elem->data;
19807    if( data==0 ){
19808      removeElementGivenHash(pH,elem,h);
19809    }else{
19810      elem->data = data;
19811      elem->pKey = pKey;
19812      assert(nKey==elem->nKey);
19813    }
19814    return old_data;
19815  }
19816  if( data==0 ) return 0;
19817  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
19818  if( new_elem==0 ) return data;
19819  new_elem->pKey = pKey;
19820  new_elem->nKey = nKey;
19821  new_elem->data = data;
19822  pH->count++;
19823  if( pH->count>=10 && pH->count > 2*pH->htsize ){
19824    if( rehash(pH, pH->count*2) ){
19825      assert( pH->htsize>0 );
19826      h = strHash(pKey, nKey) % pH->htsize;
19827    }
19828  }
19829  if( pH->ht ){
19830    insertElement(pH, &pH->ht[h], new_elem);
19831  }else{
19832    insertElement(pH, 0, new_elem);
19833  }
19834  return 0;
19835}
19836
19837/************** End of hash.c ************************************************/
19838/************** Begin file opcodes.c *****************************************/
19839/* Automatically generated.  Do not edit */
19840/* See the mkopcodec.awk script for details. */
19841#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
19842SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
19843 static const char *const azName[] = { "?",
19844     /*   1 */ "Goto",
19845     /*   2 */ "Gosub",
19846     /*   3 */ "Return",
19847     /*   4 */ "Yield",
19848     /*   5 */ "HaltIfNull",
19849     /*   6 */ "Halt",
19850     /*   7 */ "Integer",
19851     /*   8 */ "Int64",
19852     /*   9 */ "String",
19853     /*  10 */ "Null",
19854     /*  11 */ "Blob",
19855     /*  12 */ "Variable",
19856     /*  13 */ "Move",
19857     /*  14 */ "Copy",
19858     /*  15 */ "SCopy",
19859     /*  16 */ "ResultRow",
19860     /*  17 */ "CollSeq",
19861     /*  18 */ "Function",
19862     /*  19 */ "Not",
19863     /*  20 */ "AddImm",
19864     /*  21 */ "MustBeInt",
19865     /*  22 */ "RealAffinity",
19866     /*  23 */ "Permutation",
19867     /*  24 */ "Compare",
19868     /*  25 */ "Jump",
19869     /*  26 */ "If",
19870     /*  27 */ "IfNot",
19871     /*  28 */ "Column",
19872     /*  29 */ "Affinity",
19873     /*  30 */ "MakeRecord",
19874     /*  31 */ "Count",
19875     /*  32 */ "Savepoint",
19876     /*  33 */ "AutoCommit",
19877     /*  34 */ "Transaction",
19878     /*  35 */ "ReadCookie",
19879     /*  36 */ "SetCookie",
19880     /*  37 */ "VerifyCookie",
19881     /*  38 */ "OpenRead",
19882     /*  39 */ "OpenWrite",
19883     /*  40 */ "OpenEphemeral",
19884     /*  41 */ "OpenPseudo",
19885     /*  42 */ "Close",
19886     /*  43 */ "SeekLt",
19887     /*  44 */ "SeekLe",
19888     /*  45 */ "SeekGe",
19889     /*  46 */ "SeekGt",
19890     /*  47 */ "Seek",
19891     /*  48 */ "NotFound",
19892     /*  49 */ "Found",
19893     /*  50 */ "IsUnique",
19894     /*  51 */ "NotExists",
19895     /*  52 */ "Sequence",
19896     /*  53 */ "NewRowid",
19897     /*  54 */ "Insert",
19898     /*  55 */ "InsertInt",
19899     /*  56 */ "Delete",
19900     /*  57 */ "ResetCount",
19901     /*  58 */ "RowKey",
19902     /*  59 */ "RowData",
19903     /*  60 */ "Rowid",
19904     /*  61 */ "NullRow",
19905     /*  62 */ "Last",
19906     /*  63 */ "Sort",
19907     /*  64 */ "Rewind",
19908     /*  65 */ "Prev",
19909     /*  66 */ "Next",
19910     /*  67 */ "IdxInsert",
19911     /*  68 */ "Or",
19912     /*  69 */ "And",
19913     /*  70 */ "IdxDelete",
19914     /*  71 */ "IdxRowid",
19915     /*  72 */ "IdxLT",
19916     /*  73 */ "IsNull",
19917     /*  74 */ "NotNull",
19918     /*  75 */ "Ne",
19919     /*  76 */ "Eq",
19920     /*  77 */ "Gt",
19921     /*  78 */ "Le",
19922     /*  79 */ "Lt",
19923     /*  80 */ "Ge",
19924     /*  81 */ "IdxGE",
19925     /*  82 */ "BitAnd",
19926     /*  83 */ "BitOr",
19927     /*  84 */ "ShiftLeft",
19928     /*  85 */ "ShiftRight",
19929     /*  86 */ "Add",
19930     /*  87 */ "Subtract",
19931     /*  88 */ "Multiply",
19932     /*  89 */ "Divide",
19933     /*  90 */ "Remainder",
19934     /*  91 */ "Concat",
19935     /*  92 */ "Destroy",
19936     /*  93 */ "BitNot",
19937     /*  94 */ "String8",
19938     /*  95 */ "Clear",
19939     /*  96 */ "CreateIndex",
19940     /*  97 */ "CreateTable",
19941     /*  98 */ "ParseSchema",
19942     /*  99 */ "LoadAnalysis",
19943     /* 100 */ "DropTable",
19944     /* 101 */ "DropIndex",
19945     /* 102 */ "DropTrigger",
19946     /* 103 */ "IntegrityCk",
19947     /* 104 */ "RowSetAdd",
19948     /* 105 */ "RowSetRead",
19949     /* 106 */ "RowSetTest",
19950     /* 107 */ "Program",
19951     /* 108 */ "Param",
19952     /* 109 */ "FkCounter",
19953     /* 110 */ "FkIfZero",
19954     /* 111 */ "MemMax",
19955     /* 112 */ "IfPos",
19956     /* 113 */ "IfNeg",
19957     /* 114 */ "IfZero",
19958     /* 115 */ "AggStep",
19959     /* 116 */ "AggFinal",
19960     /* 117 */ "Vacuum",
19961     /* 118 */ "IncrVacuum",
19962     /* 119 */ "Expire",
19963     /* 120 */ "TableLock",
19964     /* 121 */ "VBegin",
19965     /* 122 */ "VCreate",
19966     /* 123 */ "VDestroy",
19967     /* 124 */ "VOpen",
19968     /* 125 */ "VFilter",
19969     /* 126 */ "VColumn",
19970     /* 127 */ "VNext",
19971     /* 128 */ "VRename",
19972     /* 129 */ "VUpdate",
19973     /* 130 */ "Real",
19974     /* 131 */ "Pagecount",
19975     /* 132 */ "Trace",
19976     /* 133 */ "Noop",
19977     /* 134 */ "Explain",
19978     /* 135 */ "NotUsed_135",
19979     /* 136 */ "NotUsed_136",
19980     /* 137 */ "NotUsed_137",
19981     /* 138 */ "NotUsed_138",
19982     /* 139 */ "NotUsed_139",
19983     /* 140 */ "NotUsed_140",
19984     /* 141 */ "ToText",
19985     /* 142 */ "ToBlob",
19986     /* 143 */ "ToNumeric",
19987     /* 144 */ "ToInt",
19988     /* 145 */ "ToReal",
19989  };
19990  return azName[i];
19991}
19992#endif
19993
19994/************** End of opcodes.c *********************************************/
19995/************** Begin file os_os2.c ******************************************/
19996/*
19997** 2006 Feb 14
19998**
19999** The author disclaims copyright to this source code.  In place of
20000** a legal notice, here is a blessing:
20001**
20002**    May you do good and not evil.
20003**    May you find forgiveness for yourself and forgive others.
20004**    May you share freely, never taking more than you give.
20005**
20006******************************************************************************
20007**
20008** This file contains code that is specific to OS/2.
20009*/
20010
20011
20012#if SQLITE_OS_OS2
20013
20014/*
20015** A Note About Memory Allocation:
20016**
20017** This driver uses malloc()/free() directly rather than going through
20018** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
20019** are designed for use on embedded systems where memory is scarce and
20020** malloc failures happen frequently.  OS/2 does not typically run on
20021** embedded systems, and when it does the developers normally have bigger
20022** problems to worry about than running out of memory.  So there is not
20023** a compelling need to use the wrappers.
20024**
20025** But there is a good reason to not use the wrappers.  If we use the
20026** wrappers then we will get simulated malloc() failures within this
20027** driver.  And that causes all kinds of problems for our tests.  We
20028** could enhance SQLite to deal with simulated malloc failures within
20029** the OS driver, but the code to deal with those failure would not
20030** be exercised on Linux (which does not need to malloc() in the driver)
20031** and so we would have difficulty writing coverage tests for that
20032** code.  Better to leave the code out, we think.
20033**
20034** The point of this discussion is as follows:  When creating a new
20035** OS layer for an embedded system, if you use this file as an example,
20036** avoid the use of malloc()/free().  Those routines work ok on OS/2
20037** desktops but not so well in embedded systems.
20038*/
20039
20040/*
20041** Macros used to determine whether or not to use threads.
20042*/
20043#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
20044# define SQLITE_OS2_THREADS 1
20045#endif
20046
20047/*
20048** Include code that is common to all os_*.c files
20049*/
20050/************** Include os_common.h in the middle of os_os2.c ****************/
20051/************** Begin file os_common.h ***************************************/
20052/*
20053** 2004 May 22
20054**
20055** The author disclaims copyright to this source code.  In place of
20056** a legal notice, here is a blessing:
20057**
20058**    May you do good and not evil.
20059**    May you find forgiveness for yourself and forgive others.
20060**    May you share freely, never taking more than you give.
20061**
20062******************************************************************************
20063**
20064** This file contains macros and a little bit of code that is common to
20065** all of the platform-specific files (os_*.c) and is #included into those
20066** files.
20067**
20068** This file should be #included by the os_*.c files only.  It is not a
20069** general purpose header file.
20070*/
20071#ifndef _OS_COMMON_H_
20072#define _OS_COMMON_H_
20073
20074/*
20075** At least two bugs have slipped in because we changed the MEMORY_DEBUG
20076** macro to SQLITE_DEBUG and some older makefiles have not yet made the
20077** switch.  The following code should catch this problem at compile-time.
20078*/
20079#ifdef MEMORY_DEBUG
20080# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
20081#endif
20082
20083#ifdef SQLITE_DEBUG
20084SQLITE_PRIVATE int sqlite3OSTrace = 0;
20085#define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
20086#define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
20087#define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
20088#define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
20089#define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
20090#define OSTRACE6(X,Y,Z,A,B,C) \
20091    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
20092#define OSTRACE7(X,Y,Z,A,B,C,D) \
20093    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
20094#else
20095#define OSTRACE1(X)
20096#define OSTRACE2(X,Y)
20097#define OSTRACE3(X,Y,Z)
20098#define OSTRACE4(X,Y,Z,A)
20099#define OSTRACE5(X,Y,Z,A,B)
20100#define OSTRACE6(X,Y,Z,A,B,C)
20101#define OSTRACE7(X,Y,Z,A,B,C,D)
20102#endif
20103
20104/*
20105** Macros for performance tracing.  Normally turned off.  Only works
20106** on i486 hardware.
20107*/
20108#ifdef SQLITE_PERFORMANCE_TRACE
20109
20110/*
20111** hwtime.h contains inline assembler code for implementing
20112** high-performance timing routines.
20113*/
20114/************** Include hwtime.h in the middle of os_common.h ****************/
20115/************** Begin file hwtime.h ******************************************/
20116/*
20117** 2008 May 27
20118**
20119** The author disclaims copyright to this source code.  In place of
20120** a legal notice, here is a blessing:
20121**
20122**    May you do good and not evil.
20123**    May you find forgiveness for yourself and forgive others.
20124**    May you share freely, never taking more than you give.
20125**
20126******************************************************************************
20127**
20128** This file contains inline asm code for retrieving "high-performance"
20129** counters for x86 class CPUs.
20130*/
20131#ifndef _HWTIME_H_
20132#define _HWTIME_H_
20133
20134/*
20135** The following routine only works on pentium-class (or newer) processors.
20136** It uses the RDTSC opcode to read the cycle count value out of the
20137** processor and returns that value.  This can be used for high-res
20138** profiling.
20139*/
20140#if (defined(__GNUC__) || defined(_MSC_VER)) && \
20141      (defined(i386) || defined(__i386__) || defined(_M_IX86))
20142
20143  #if defined(__GNUC__)
20144
20145  __inline__ sqlite_uint64 sqlite3Hwtime(void){
20146     unsigned int lo, hi;
20147     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
20148     return (sqlite_uint64)hi << 32 | lo;
20149  }
20150
20151  #elif defined(_MSC_VER)
20152
20153  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
20154     __asm {
20155        rdtsc
20156        ret       ; return value at EDX:EAX
20157     }
20158  }
20159
20160  #endif
20161
20162#elif (defined(__GNUC__) && defined(__x86_64__))
20163
20164  __inline__ sqlite_uint64 sqlite3Hwtime(void){
20165      unsigned long val;
20166      __asm__ __volatile__ ("rdtsc" : "=A" (val));
20167      return val;
20168  }
20169
20170#elif (defined(__GNUC__) && defined(__ppc__))
20171
20172  __inline__ sqlite_uint64 sqlite3Hwtime(void){
20173      unsigned long long retval;
20174      unsigned long junk;
20175      __asm__ __volatile__ ("\n\
20176          1:      mftbu   %1\n\
20177                  mftb    %L0\n\
20178                  mftbu   %0\n\
20179                  cmpw    %0,%1\n\
20180                  bne     1b"
20181                  : "=r" (retval), "=r" (junk));
20182      return retval;
20183  }
20184
20185#else
20186
20187  #error Need implementation of sqlite3Hwtime() for your platform.
20188
20189  /*
20190  ** To compile without implementing sqlite3Hwtime() for your platform,
20191  ** you can remove the above #error and use the following
20192  ** stub function.  You will lose timing support for many
20193  ** of the debugging and testing utilities, but it should at
20194  ** least compile and run.
20195  */
20196SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
20197
20198#endif
20199
20200#endif /* !defined(_HWTIME_H_) */
20201
20202/************** End of hwtime.h **********************************************/
20203/************** Continuing where we left off in os_common.h ******************/
20204
20205static sqlite_uint64 g_start;
20206static sqlite_uint64 g_elapsed;
20207#define TIMER_START       g_start=sqlite3Hwtime()
20208#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
20209#define TIMER_ELAPSED     g_elapsed
20210#else
20211#define TIMER_START
20212#define TIMER_END
20213#define TIMER_ELAPSED     ((sqlite_uint64)0)
20214#endif
20215
20216/*
20217** If we compile with the SQLITE_TEST macro set, then the following block
20218** of code will give us the ability to simulate a disk I/O error.  This
20219** is used for testing the I/O recovery logic.
20220*/
20221#ifdef SQLITE_TEST
20222SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
20223SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
20224SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
20225SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
20226SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
20227SQLITE_API int sqlite3_diskfull_pending = 0;
20228SQLITE_API int sqlite3_diskfull = 0;
20229#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
20230#define SimulateIOError(CODE)  \
20231  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
20232       || sqlite3_io_error_pending-- == 1 )  \
20233              { local_ioerr(); CODE; }
20234static void local_ioerr(){
20235  IOTRACE(("IOERR\n"));
20236  sqlite3_io_error_hit++;
20237  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
20238}
20239#define SimulateDiskfullError(CODE) \
20240   if( sqlite3_diskfull_pending ){ \
20241     if( sqlite3_diskfull_pending == 1 ){ \
20242       local_ioerr(); \
20243       sqlite3_diskfull = 1; \
20244       sqlite3_io_error_hit = 1; \
20245       CODE; \
20246     }else{ \
20247       sqlite3_diskfull_pending--; \
20248     } \
20249   }
20250#else
20251#define SimulateIOErrorBenign(X)
20252#define SimulateIOError(A)
20253#define SimulateDiskfullError(A)
20254#endif
20255
20256/*
20257** When testing, keep a count of the number of open files.
20258*/
20259#ifdef SQLITE_TEST
20260SQLITE_API int sqlite3_open_file_count = 0;
20261#define OpenCounter(X)  sqlite3_open_file_count+=(X)
20262#else
20263#define OpenCounter(X)
20264#endif
20265
20266#endif /* !defined(_OS_COMMON_H_) */
20267
20268/************** End of os_common.h *******************************************/
20269/************** Continuing where we left off in os_os2.c *********************/
20270
20271/*
20272** The os2File structure is subclass of sqlite3_file specific for the OS/2
20273** protability layer.
20274*/
20275typedef struct os2File os2File;
20276struct os2File {
20277  const sqlite3_io_methods *pMethod;  /* Always the first entry */
20278  HFILE h;                  /* Handle for accessing the file */
20279  char* pathToDel;          /* Name of file to delete on close, NULL if not */
20280  unsigned char locktype;   /* Type of lock currently held on this file */
20281};
20282
20283#define LOCK_TIMEOUT 10L /* the default locking timeout */
20284
20285/*****************************************************************************
20286** The next group of routines implement the I/O methods specified
20287** by the sqlite3_io_methods object.
20288******************************************************************************/
20289
20290/*
20291** Close a file.
20292*/
20293static int os2Close( sqlite3_file *id ){
20294  APIRET rc = NO_ERROR;
20295  os2File *pFile;
20296  if( id && (pFile = (os2File*)id) != 0 ){
20297    OSTRACE2( "CLOSE %d\n", pFile->h );
20298    rc = DosClose( pFile->h );
20299    pFile->locktype = NO_LOCK;
20300    if( pFile->pathToDel != NULL ){
20301      rc = DosForceDelete( (PSZ)pFile->pathToDel );
20302      free( pFile->pathToDel );
20303      pFile->pathToDel = NULL;
20304    }
20305    id = 0;
20306    OpenCounter( -1 );
20307  }
20308
20309  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20310}
20311
20312/*
20313** Read data from a file into a buffer.  Return SQLITE_OK if all
20314** bytes were read successfully and SQLITE_IOERR if anything goes
20315** wrong.
20316*/
20317static int os2Read(
20318  sqlite3_file *id,               /* File to read from */
20319  void *pBuf,                     /* Write content into this buffer */
20320  int amt,                        /* Number of bytes to read */
20321  sqlite3_int64 offset            /* Begin reading at this offset */
20322){
20323  ULONG fileLocation = 0L;
20324  ULONG got;
20325  os2File *pFile = (os2File*)id;
20326  assert( id!=0 );
20327  SimulateIOError( return SQLITE_IOERR_READ );
20328  OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
20329  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20330    return SQLITE_IOERR;
20331  }
20332  if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
20333    return SQLITE_IOERR_READ;
20334  }
20335  if( got == (ULONG)amt )
20336    return SQLITE_OK;
20337  else {
20338    /* Unread portions of the input buffer must be zero-filled */
20339    memset(&((char*)pBuf)[got], 0, amt-got);
20340    return SQLITE_IOERR_SHORT_READ;
20341  }
20342}
20343
20344/*
20345** Write data from a buffer into a file.  Return SQLITE_OK on success
20346** or some other error code on failure.
20347*/
20348static int os2Write(
20349  sqlite3_file *id,               /* File to write into */
20350  const void *pBuf,               /* The bytes to be written */
20351  int amt,                        /* Number of bytes to write */
20352  sqlite3_int64 offset            /* Offset into the file to begin writing at */
20353){
20354  ULONG fileLocation = 0L;
20355  APIRET rc = NO_ERROR;
20356  ULONG wrote;
20357  os2File *pFile = (os2File*)id;
20358  assert( id!=0 );
20359  SimulateIOError( return SQLITE_IOERR_WRITE );
20360  SimulateDiskfullError( return SQLITE_FULL );
20361  OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
20362  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20363    return SQLITE_IOERR;
20364  }
20365  assert( amt>0 );
20366  while( amt > 0 &&
20367         ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
20368         wrote > 0
20369  ){
20370    amt -= wrote;
20371    pBuf = &((char*)pBuf)[wrote];
20372  }
20373
20374  return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
20375}
20376
20377/*
20378** Truncate an open file to a specified size
20379*/
20380static int os2Truncate( sqlite3_file *id, i64 nByte ){
20381  APIRET rc = NO_ERROR;
20382  os2File *pFile = (os2File*)id;
20383  OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
20384  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
20385  rc = DosSetFileSize( pFile->h, nByte );
20386  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
20387}
20388
20389#ifdef SQLITE_TEST
20390/*
20391** Count the number of fullsyncs and normal syncs.  This is used to test
20392** that syncs and fullsyncs are occuring at the right times.
20393*/
20394SQLITE_API int sqlite3_sync_count = 0;
20395SQLITE_API int sqlite3_fullsync_count = 0;
20396#endif
20397
20398/*
20399** Make sure all writes to a particular file are committed to disk.
20400*/
20401static int os2Sync( sqlite3_file *id, int flags ){
20402  os2File *pFile = (os2File*)id;
20403  OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
20404#ifdef SQLITE_TEST
20405  if( flags & SQLITE_SYNC_FULL){
20406    sqlite3_fullsync_count++;
20407  }
20408  sqlite3_sync_count++;
20409#endif
20410  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
20411  ** no-op
20412  */
20413#ifdef SQLITE_NO_SYNC
20414  UNUSED_PARAMETER(pFile);
20415  return SQLITE_OK;
20416#else
20417  return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20418#endif
20419}
20420
20421/*
20422** Determine the current size of a file in bytes
20423*/
20424static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
20425  APIRET rc = NO_ERROR;
20426  FILESTATUS3 fsts3FileInfo;
20427  memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
20428  assert( id!=0 );
20429  SimulateIOError( return SQLITE_IOERR_FSTAT );
20430  rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
20431  if( rc == NO_ERROR ){
20432    *pSize = fsts3FileInfo.cbFile;
20433    return SQLITE_OK;
20434  }else{
20435    return SQLITE_IOERR_FSTAT;
20436  }
20437}
20438
20439/*
20440** Acquire a reader lock.
20441*/
20442static int getReadLock( os2File *pFile ){
20443  FILELOCK  LockArea,
20444            UnlockArea;
20445  APIRET res;
20446  memset(&LockArea, 0, sizeof(LockArea));
20447  memset(&UnlockArea, 0, sizeof(UnlockArea));
20448  LockArea.lOffset = SHARED_FIRST;
20449  LockArea.lRange = SHARED_SIZE;
20450  UnlockArea.lOffset = 0L;
20451  UnlockArea.lRange = 0L;
20452  res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20453  OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
20454  return res;
20455}
20456
20457/*
20458** Undo a readlock
20459*/
20460static int unlockReadLock( os2File *id ){
20461  FILELOCK  LockArea,
20462            UnlockArea;
20463  APIRET res;
20464  memset(&LockArea, 0, sizeof(LockArea));
20465  memset(&UnlockArea, 0, sizeof(UnlockArea));
20466  LockArea.lOffset = 0L;
20467  LockArea.lRange = 0L;
20468  UnlockArea.lOffset = SHARED_FIRST;
20469  UnlockArea.lRange = SHARED_SIZE;
20470  res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20471  OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
20472  return res;
20473}
20474
20475/*
20476** Lock the file with the lock specified by parameter locktype - one
20477** of the following:
20478**
20479**     (1) SHARED_LOCK
20480**     (2) RESERVED_LOCK
20481**     (3) PENDING_LOCK
20482**     (4) EXCLUSIVE_LOCK
20483**
20484** Sometimes when requesting one lock state, additional lock states
20485** are inserted in between.  The locking might fail on one of the later
20486** transitions leaving the lock state different from what it started but
20487** still short of its goal.  The following chart shows the allowed
20488** transitions and the inserted intermediate states:
20489**
20490**    UNLOCKED -> SHARED
20491**    SHARED -> RESERVED
20492**    SHARED -> (PENDING) -> EXCLUSIVE
20493**    RESERVED -> (PENDING) -> EXCLUSIVE
20494**    PENDING -> EXCLUSIVE
20495**
20496** This routine will only increase a lock.  The os2Unlock() routine
20497** erases all locks at once and returns us immediately to locking level 0.
20498** It is not possible to lower the locking level one step at a time.  You
20499** must go straight to locking level 0.
20500*/
20501static int os2Lock( sqlite3_file *id, int locktype ){
20502  int rc = SQLITE_OK;       /* Return code from subroutines */
20503  APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
20504  int newLocktype;       /* Set pFile->locktype to this value before exiting */
20505  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
20506  FILELOCK  LockArea,
20507            UnlockArea;
20508  os2File *pFile = (os2File*)id;
20509  memset(&LockArea, 0, sizeof(LockArea));
20510  memset(&UnlockArea, 0, sizeof(UnlockArea));
20511  assert( pFile!=0 );
20512  OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
20513
20514  /* If there is already a lock of this type or more restrictive on the
20515  ** os2File, do nothing. Don't use the end_lock: exit path, as
20516  ** sqlite3_mutex_enter() hasn't been called yet.
20517  */
20518  if( pFile->locktype>=locktype ){
20519    OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
20520    return SQLITE_OK;
20521  }
20522
20523  /* Make sure the locking sequence is correct
20524  */
20525  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
20526  assert( locktype!=PENDING_LOCK );
20527  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
20528
20529  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
20530  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
20531  ** the PENDING_LOCK byte is temporary.
20532  */
20533  newLocktype = pFile->locktype;
20534  if( pFile->locktype==NO_LOCK
20535      || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
20536  ){
20537    LockArea.lOffset = PENDING_BYTE;
20538    LockArea.lRange = 1L;
20539    UnlockArea.lOffset = 0L;
20540    UnlockArea.lRange = 0L;
20541
20542    /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
20543    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
20544    if( res == NO_ERROR ){
20545      gotPendingLock = 1;
20546      OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
20547    }
20548  }
20549
20550  /* Acquire a shared lock
20551  */
20552  if( locktype==SHARED_LOCK && res == NO_ERROR ){
20553    assert( pFile->locktype==NO_LOCK );
20554    res = getReadLock(pFile);
20555    if( res == NO_ERROR ){
20556      newLocktype = SHARED_LOCK;
20557    }
20558    OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
20559  }
20560
20561  /* Acquire a RESERVED lock
20562  */
20563  if( locktype==RESERVED_LOCK && res == NO_ERROR ){
20564    assert( pFile->locktype==SHARED_LOCK );
20565    LockArea.lOffset = RESERVED_BYTE;
20566    LockArea.lRange = 1L;
20567    UnlockArea.lOffset = 0L;
20568    UnlockArea.lRange = 0L;
20569    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20570    if( res == NO_ERROR ){
20571      newLocktype = RESERVED_LOCK;
20572    }
20573    OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
20574  }
20575
20576  /* Acquire a PENDING lock
20577  */
20578  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20579    newLocktype = PENDING_LOCK;
20580    gotPendingLock = 0;
20581    OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
20582  }
20583
20584  /* Acquire an EXCLUSIVE lock
20585  */
20586  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20587    assert( pFile->locktype>=SHARED_LOCK );
20588    res = unlockReadLock(pFile);
20589    OSTRACE2( "unreadlock = %d\n", res );
20590    LockArea.lOffset = SHARED_FIRST;
20591    LockArea.lRange = SHARED_SIZE;
20592    UnlockArea.lOffset = 0L;
20593    UnlockArea.lRange = 0L;
20594    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20595    if( res == NO_ERROR ){
20596      newLocktype = EXCLUSIVE_LOCK;
20597    }else{
20598      OSTRACE2( "OS/2 error-code = %d\n", res );
20599      getReadLock(pFile);
20600    }
20601    OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
20602  }
20603
20604  /* If we are holding a PENDING lock that ought to be released, then
20605  ** release it now.
20606  */
20607  if( gotPendingLock && locktype==SHARED_LOCK ){
20608    int r;
20609    LockArea.lOffset = 0L;
20610    LockArea.lRange = 0L;
20611    UnlockArea.lOffset = PENDING_BYTE;
20612    UnlockArea.lRange = 1L;
20613    r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20614    OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
20615  }
20616
20617  /* Update the state of the lock has held in the file descriptor then
20618  ** return the appropriate result code.
20619  */
20620  if( res == NO_ERROR ){
20621    rc = SQLITE_OK;
20622  }else{
20623    OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
20624              locktype, newLocktype );
20625    rc = SQLITE_BUSY;
20626  }
20627  pFile->locktype = newLocktype;
20628  OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
20629  return rc;
20630}
20631
20632/*
20633** This routine checks if there is a RESERVED lock held on the specified
20634** file by this or any other process. If such a lock is held, return
20635** non-zero, otherwise zero.
20636*/
20637static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
20638  int r = 0;
20639  os2File *pFile = (os2File*)id;
20640  assert( pFile!=0 );
20641  if( pFile->locktype>=RESERVED_LOCK ){
20642    r = 1;
20643    OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
20644  }else{
20645    FILELOCK  LockArea,
20646              UnlockArea;
20647    APIRET rc = NO_ERROR;
20648    memset(&LockArea, 0, sizeof(LockArea));
20649    memset(&UnlockArea, 0, sizeof(UnlockArea));
20650    LockArea.lOffset = RESERVED_BYTE;
20651    LockArea.lRange = 1L;
20652    UnlockArea.lOffset = 0L;
20653    UnlockArea.lRange = 0L;
20654    rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20655    OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
20656    if( rc == NO_ERROR ){
20657      APIRET rcu = NO_ERROR; /* return code for unlocking */
20658      LockArea.lOffset = 0L;
20659      LockArea.lRange = 0L;
20660      UnlockArea.lOffset = RESERVED_BYTE;
20661      UnlockArea.lRange = 1L;
20662      rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20663      OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
20664    }
20665    r = !(rc == NO_ERROR);
20666    OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
20667  }
20668  *pOut = r;
20669  return SQLITE_OK;
20670}
20671
20672/*
20673** Lower the locking level on file descriptor id to locktype.  locktype
20674** must be either NO_LOCK or SHARED_LOCK.
20675**
20676** If the locking level of the file descriptor is already at or below
20677** the requested locking level, this routine is a no-op.
20678**
20679** It is not possible for this routine to fail if the second argument
20680** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
20681** might return SQLITE_IOERR;
20682*/
20683static int os2Unlock( sqlite3_file *id, int locktype ){
20684  int type;
20685  os2File *pFile = (os2File*)id;
20686  APIRET rc = SQLITE_OK;
20687  APIRET res = NO_ERROR;
20688  FILELOCK  LockArea,
20689            UnlockArea;
20690  memset(&LockArea, 0, sizeof(LockArea));
20691  memset(&UnlockArea, 0, sizeof(UnlockArea));
20692  assert( pFile!=0 );
20693  assert( locktype<=SHARED_LOCK );
20694  OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
20695  type = pFile->locktype;
20696  if( type>=EXCLUSIVE_LOCK ){
20697    LockArea.lOffset = 0L;
20698    LockArea.lRange = 0L;
20699    UnlockArea.lOffset = SHARED_FIRST;
20700    UnlockArea.lRange = SHARED_SIZE;
20701    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20702    OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
20703    if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
20704      /* This should never happen.  We should always be able to
20705      ** reacquire the read lock */
20706      OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
20707      rc = SQLITE_IOERR_UNLOCK;
20708    }
20709  }
20710  if( type>=RESERVED_LOCK ){
20711    LockArea.lOffset = 0L;
20712    LockArea.lRange = 0L;
20713    UnlockArea.lOffset = RESERVED_BYTE;
20714    UnlockArea.lRange = 1L;
20715    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20716    OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
20717  }
20718  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
20719    res = unlockReadLock(pFile);
20720    OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
20721  }
20722  if( type>=PENDING_LOCK ){
20723    LockArea.lOffset = 0L;
20724    LockArea.lRange = 0L;
20725    UnlockArea.lOffset = PENDING_BYTE;
20726    UnlockArea.lRange = 1L;
20727    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20728    OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
20729  }
20730  pFile->locktype = locktype;
20731  OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
20732  return rc;
20733}
20734
20735/*
20736** Control and query of the open file handle.
20737*/
20738static int os2FileControl(sqlite3_file *id, int op, void *pArg){
20739  switch( op ){
20740    case SQLITE_FCNTL_LOCKSTATE: {
20741      *(int*)pArg = ((os2File*)id)->locktype;
20742      OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
20743      return SQLITE_OK;
20744    }
20745  }
20746  return SQLITE_ERROR;
20747}
20748
20749/*
20750** Return the sector size in bytes of the underlying block device for
20751** the specified file. This is almost always 512 bytes, but may be
20752** larger for some devices.
20753**
20754** SQLite code assumes this function cannot fail. It also assumes that
20755** if two files are created in the same file-system directory (i.e.
20756** a database and its journal file) that the sector size will be the
20757** same for both.
20758*/
20759static int os2SectorSize(sqlite3_file *id){
20760  return SQLITE_DEFAULT_SECTOR_SIZE;
20761}
20762
20763/*
20764** Return a vector of device characteristics.
20765*/
20766static int os2DeviceCharacteristics(sqlite3_file *id){
20767  return 0;
20768}
20769
20770
20771/*
20772** Character set conversion objects used by conversion routines.
20773*/
20774static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
20775static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
20776
20777/*
20778** Helper function to initialize the conversion objects from and to UTF-8.
20779*/
20780static void initUconvObjects( void ){
20781  if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
20782    ucUtf8 = NULL;
20783  if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
20784    uclCp = NULL;
20785}
20786
20787/*
20788** Helper function to free the conversion objects from and to UTF-8.
20789*/
20790static void freeUconvObjects( void ){
20791  if ( ucUtf8 )
20792    UniFreeUconvObject( ucUtf8 );
20793  if ( uclCp )
20794    UniFreeUconvObject( uclCp );
20795  ucUtf8 = NULL;
20796  uclCp = NULL;
20797}
20798
20799/*
20800** Helper function to convert UTF-8 filenames to local OS/2 codepage.
20801** The two-step process: first convert the incoming UTF-8 string
20802** into UCS-2 and then from UCS-2 to the current codepage.
20803** The returned char pointer has to be freed.
20804*/
20805static char *convertUtf8PathToCp( const char *in ){
20806  UniChar tempPath[CCHMAXPATH];
20807  char *out = (char *)calloc( CCHMAXPATH, 1 );
20808
20809  if( !out )
20810    return NULL;
20811
20812  if( !ucUtf8 || !uclCp )
20813    initUconvObjects();
20814
20815  /* determine string for the conversion of UTF-8 which is CP1208 */
20816  if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
20817    return out; /* if conversion fails, return the empty string */
20818
20819  /* conversion for current codepage which can be used for paths */
20820  UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
20821
20822  return out;
20823}
20824
20825/*
20826** Helper function to convert filenames from local codepage to UTF-8.
20827** The two-step process: first convert the incoming codepage-specific
20828** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
20829** The returned char pointer has to be freed.
20830**
20831** This function is non-static to be able to use this in shell.c and
20832** similar applications that take command line arguments.
20833*/
20834char *convertCpPathToUtf8( const char *in ){
20835  UniChar tempPath[CCHMAXPATH];
20836  char *out = (char *)calloc( CCHMAXPATH, 1 );
20837
20838  if( !out )
20839    return NULL;
20840
20841  if( !ucUtf8 || !uclCp )
20842    initUconvObjects();
20843
20844  /* conversion for current codepage which can be used for paths */
20845  if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
20846    return out; /* if conversion fails, return the empty string */
20847
20848  /* determine string for the conversion of UTF-8 which is CP1208 */
20849  UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
20850
20851  return out;
20852}
20853
20854/*
20855** This vector defines all the methods that can operate on an
20856** sqlite3_file for os2.
20857*/
20858static const sqlite3_io_methods os2IoMethod = {
20859  1,                        /* iVersion */
20860  os2Close,
20861  os2Read,
20862  os2Write,
20863  os2Truncate,
20864  os2Sync,
20865  os2FileSize,
20866  os2Lock,
20867  os2Unlock,
20868  os2CheckReservedLock,
20869  os2FileControl,
20870  os2SectorSize,
20871  os2DeviceCharacteristics
20872};
20873
20874/***************************************************************************
20875** Here ends the I/O methods that form the sqlite3_io_methods object.
20876**
20877** The next block of code implements the VFS methods.
20878****************************************************************************/
20879
20880/*
20881** Create a temporary file name in zBuf.  zBuf must be big enough to
20882** hold at pVfs->mxPathname characters.
20883*/
20884static int getTempname(int nBuf, char *zBuf ){
20885  static const unsigned char zChars[] =
20886    "abcdefghijklmnopqrstuvwxyz"
20887    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
20888    "0123456789";
20889  int i, j;
20890  char zTempPathBuf[3];
20891  PSZ zTempPath = (PSZ)&zTempPathBuf;
20892  if( sqlite3_temp_directory ){
20893    zTempPath = sqlite3_temp_directory;
20894  }else{
20895    if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
20896      if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
20897        if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
20898           ULONG ulDriveNum = 0, ulDriveMap = 0;
20899           DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
20900           sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
20901        }
20902      }
20903    }
20904  }
20905  /* Strip off a trailing slashes or backslashes, otherwise we would get *
20906   * multiple (back)slashes which causes DosOpen() to fail.              *
20907   * Trailing spaces are not allowed, either.                            */
20908  j = sqlite3Strlen30(zTempPath);
20909  while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
20910                    || zTempPath[j-1] == ' ' ) ){
20911    j--;
20912  }
20913  zTempPath[j] = '\0';
20914  if( !sqlite3_temp_directory ){
20915    char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
20916    sqlite3_snprintf( nBuf-30, zBuf,
20917                      "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
20918    free( zTempPathUTF );
20919  }else{
20920    sqlite3_snprintf( nBuf-30, zBuf,
20921                      "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
20922  }
20923  j = sqlite3Strlen30( zBuf );
20924  sqlite3_randomness( 20, &zBuf[j] );
20925  for( i = 0; i < 20; i++, j++ ){
20926    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
20927  }
20928  zBuf[j] = 0;
20929  OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
20930  return SQLITE_OK;
20931}
20932
20933
20934/*
20935** Turn a relative pathname into a full pathname.  Write the full
20936** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
20937** bytes in size.
20938*/
20939static int os2FullPathname(
20940  sqlite3_vfs *pVfs,          /* Pointer to vfs object */
20941  const char *zRelative,      /* Possibly relative input path */
20942  int nFull,                  /* Size of output buffer in bytes */
20943  char *zFull                 /* Output buffer */
20944){
20945  char *zRelativeCp = convertUtf8PathToCp( zRelative );
20946  char zFullCp[CCHMAXPATH] = "\0";
20947  char *zFullUTF;
20948  APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
20949                                CCHMAXPATH );
20950  free( zRelativeCp );
20951  zFullUTF = convertCpPathToUtf8( zFullCp );
20952  sqlite3_snprintf( nFull, zFull, zFullUTF );
20953  free( zFullUTF );
20954  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20955}
20956
20957
20958/*
20959** Open a file.
20960*/
20961static int os2Open(
20962  sqlite3_vfs *pVfs,            /* Not used */
20963  const char *zName,            /* Name of the file */
20964  sqlite3_file *id,             /* Write the SQLite file handle here */
20965  int flags,                    /* Open mode flags */
20966  int *pOutFlags                /* Status return flags */
20967){
20968  HFILE h;
20969  ULONG ulFileAttribute = FILE_NORMAL;
20970  ULONG ulOpenFlags = 0;
20971  ULONG ulOpenMode = 0;
20972  os2File *pFile = (os2File*)id;
20973  APIRET rc = NO_ERROR;
20974  ULONG ulAction;
20975  char *zNameCp;
20976  char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
20977
20978  /* If the second argument to this function is NULL, generate a
20979  ** temporary file name to use
20980  */
20981  if( !zName ){
20982    int rc = getTempname(CCHMAXPATH+1, zTmpname);
20983    if( rc!=SQLITE_OK ){
20984      return rc;
20985    }
20986    zName = zTmpname;
20987  }
20988
20989
20990  memset( pFile, 0, sizeof(*pFile) );
20991
20992  OSTRACE2( "OPEN want %d\n", flags );
20993
20994  if( flags & SQLITE_OPEN_READWRITE ){
20995    ulOpenMode |= OPEN_ACCESS_READWRITE;
20996    OSTRACE1( "OPEN read/write\n" );
20997  }else{
20998    ulOpenMode |= OPEN_ACCESS_READONLY;
20999    OSTRACE1( "OPEN read only\n" );
21000  }
21001
21002  if( flags & SQLITE_OPEN_CREATE ){
21003    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
21004    OSTRACE1( "OPEN open new/create\n" );
21005  }else{
21006    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
21007    OSTRACE1( "OPEN open existing\n" );
21008  }
21009
21010  if( flags & SQLITE_OPEN_MAIN_DB ){
21011    ulOpenMode |= OPEN_SHARE_DENYNONE;
21012    OSTRACE1( "OPEN share read/write\n" );
21013  }else{
21014    ulOpenMode |= OPEN_SHARE_DENYWRITE;
21015    OSTRACE1( "OPEN share read only\n" );
21016  }
21017
21018  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
21019    char pathUtf8[CCHMAXPATH];
21020#ifdef NDEBUG /* when debugging we want to make sure it is deleted */
21021    ulFileAttribute = FILE_HIDDEN;
21022#endif
21023    os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
21024    pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
21025    OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
21026  }else{
21027    pFile->pathToDel = NULL;
21028    OSTRACE1( "OPEN normal file attribute\n" );
21029  }
21030
21031  /* always open in random access mode for possibly better speed */
21032  ulOpenMode |= OPEN_FLAGS_RANDOM;
21033  ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
21034  ulOpenMode |= OPEN_FLAGS_NOINHERIT;
21035
21036  zNameCp = convertUtf8PathToCp( zName );
21037  rc = DosOpen( (PSZ)zNameCp,
21038                &h,
21039                &ulAction,
21040                0L,
21041                ulFileAttribute,
21042                ulOpenFlags,
21043                ulOpenMode,
21044                (PEAOP2)NULL );
21045  free( zNameCp );
21046  if( rc != NO_ERROR ){
21047    OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
21048              rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
21049    if( pFile->pathToDel )
21050      free( pFile->pathToDel );
21051    pFile->pathToDel = NULL;
21052    if( flags & SQLITE_OPEN_READWRITE ){
21053      OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
21054      return os2Open( pVfs, zName, id,
21055                      ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
21056                      pOutFlags );
21057    }else{
21058      return SQLITE_CANTOPEN;
21059    }
21060  }
21061
21062  if( pOutFlags ){
21063    *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
21064  }
21065
21066  pFile->pMethod = &os2IoMethod;
21067  pFile->h = h;
21068  OpenCounter(+1);
21069  OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
21070  return SQLITE_OK;
21071}
21072
21073/*
21074** Delete the named file.
21075*/
21076static int os2Delete(
21077  sqlite3_vfs *pVfs,                     /* Not used on os2 */
21078  const char *zFilename,                 /* Name of file to delete */
21079  int syncDir                            /* Not used on os2 */
21080){
21081  APIRET rc = NO_ERROR;
21082  char *zFilenameCp = convertUtf8PathToCp( zFilename );
21083  SimulateIOError( return SQLITE_IOERR_DELETE );
21084  rc = DosDelete( (PSZ)zFilenameCp );
21085  free( zFilenameCp );
21086  OSTRACE2( "DELETE \"%s\"\n", zFilename );
21087  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
21088}
21089
21090/*
21091** Check the existance and status of a file.
21092*/
21093static int os2Access(
21094  sqlite3_vfs *pVfs,        /* Not used on os2 */
21095  const char *zFilename,    /* Name of file to check */
21096  int flags,                /* Type of test to make on this file */
21097  int *pOut                 /* Write results here */
21098){
21099  FILESTATUS3 fsts3ConfigInfo;
21100  APIRET rc = NO_ERROR;
21101  char *zFilenameCp = convertUtf8PathToCp( zFilename );
21102
21103  memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
21104  rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
21105                         &fsts3ConfigInfo, sizeof(FILESTATUS3) );
21106  free( zFilenameCp );
21107  OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
21108            fsts3ConfigInfo.attrFile, flags, rc );
21109  switch( flags ){
21110    case SQLITE_ACCESS_READ:
21111    case SQLITE_ACCESS_EXISTS:
21112      rc = (rc == NO_ERROR);
21113      OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
21114      break;
21115    case SQLITE_ACCESS_READWRITE:
21116      rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
21117      OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
21118      break;
21119    default:
21120      assert( !"Invalid flags argument" );
21121  }
21122  *pOut = rc;
21123  return SQLITE_OK;
21124}
21125
21126
21127#ifndef SQLITE_OMIT_LOAD_EXTENSION
21128/*
21129** Interfaces for opening a shared library, finding entry points
21130** within the shared library, and closing the shared library.
21131*/
21132/*
21133** Interfaces for opening a shared library, finding entry points
21134** within the shared library, and closing the shared library.
21135*/
21136static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
21137  UCHAR loadErr[256];
21138  HMODULE hmod;
21139  APIRET rc;
21140  char *zFilenameCp = convertUtf8PathToCp(zFilename);
21141  rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
21142  free(zFilenameCp);
21143  return rc != NO_ERROR ? 0 : (void*)hmod;
21144}
21145/*
21146** A no-op since the error code is returned on the DosLoadModule call.
21147** os2Dlopen returns zero if DosLoadModule is not successful.
21148*/
21149static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
21150/* no-op */
21151}
21152static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
21153  PFN pfn;
21154  APIRET rc;
21155  rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
21156  if( rc != NO_ERROR ){
21157    /* if the symbol itself was not found, search again for the same
21158     * symbol with an extra underscore, that might be needed depending
21159     * on the calling convention */
21160    char _zSymbol[256] = "_";
21161    strncat(_zSymbol, zSymbol, 255);
21162    rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
21163  }
21164  return rc != NO_ERROR ? 0 : (void*)pfn;
21165}
21166static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
21167  DosFreeModule((HMODULE)pHandle);
21168}
21169#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
21170  #define os2DlOpen 0
21171  #define os2DlError 0
21172  #define os2DlSym 0
21173  #define os2DlClose 0
21174#endif
21175
21176
21177/*
21178** Write up to nBuf bytes of randomness into zBuf.
21179*/
21180static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
21181  int n = 0;
21182#if defined(SQLITE_TEST)
21183  n = nBuf;
21184  memset(zBuf, 0, nBuf);
21185#else
21186  int sizeofULong = sizeof(ULONG);
21187  if( (int)sizeof(DATETIME) <= nBuf - n ){
21188    DATETIME x;
21189    DosGetDateTime(&x);
21190    memcpy(&zBuf[n], &x, sizeof(x));
21191    n += sizeof(x);
21192  }
21193
21194  if( sizeofULong <= nBuf - n ){
21195    PPIB ppib;
21196    DosGetInfoBlocks(NULL, &ppib);
21197    memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
21198    n += sizeofULong;
21199  }
21200
21201  if( sizeofULong <= nBuf - n ){
21202    PTIB ptib;
21203    DosGetInfoBlocks(&ptib, NULL);
21204    memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
21205    n += sizeofULong;
21206  }
21207
21208  /* if we still haven't filled the buffer yet the following will */
21209  /* grab everything once instead of making several calls for a single item */
21210  if( sizeofULong <= nBuf - n ){
21211    ULONG ulSysInfo[QSV_MAX];
21212    DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
21213
21214    memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
21215    n += sizeofULong;
21216
21217    if( sizeofULong <= nBuf - n ){
21218      memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
21219      n += sizeofULong;
21220    }
21221    if( sizeofULong <= nBuf - n ){
21222      memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
21223      n += sizeofULong;
21224    }
21225    if( sizeofULong <= nBuf - n ){
21226      memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
21227      n += sizeofULong;
21228    }
21229    if( sizeofULong <= nBuf - n ){
21230      memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
21231      n += sizeofULong;
21232    }
21233  }
21234#endif
21235
21236  return n;
21237}
21238
21239/*
21240** Sleep for a little while.  Return the amount of time slept.
21241** The argument is the number of microseconds we want to sleep.
21242** The return value is the number of microseconds of sleep actually
21243** requested from the underlying operating system, a number which
21244** might be greater than or equal to the argument, but not less
21245** than the argument.
21246*/
21247static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
21248  DosSleep( (microsec/1000) );
21249  return microsec;
21250}
21251
21252/*
21253** The following variable, if set to a non-zero value, becomes the result
21254** returned from sqlite3OsCurrentTime().  This is used for testing.
21255*/
21256#ifdef SQLITE_TEST
21257SQLITE_API int sqlite3_current_time = 0;
21258#endif
21259
21260/*
21261** Find the current time (in Universal Coordinated Time).  Write the
21262** current time and date as a Julian Day number into *prNow and
21263** return 0.  Return 1 if the time and date cannot be found.
21264*/
21265int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
21266  double now;
21267  SHORT minute; /* needs to be able to cope with negative timezone offset */
21268  USHORT second, hour,
21269         day, month, year;
21270  DATETIME dt;
21271  DosGetDateTime( &dt );
21272  second = (USHORT)dt.seconds;
21273  minute = (SHORT)dt.minutes + dt.timezone;
21274  hour = (USHORT)dt.hours;
21275  day = (USHORT)dt.day;
21276  month = (USHORT)dt.month;
21277  year = (USHORT)dt.year;
21278
21279  /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
21280     http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
21281  /* Calculate the Julian days */
21282  now = day - 32076 +
21283    1461*(year + 4800 + (month - 14)/12)/4 +
21284    367*(month - 2 - (month - 14)/12*12)/12 -
21285    3*((year + 4900 + (month - 14)/12)/100)/4;
21286
21287  /* Add the fractional hours, mins and seconds */
21288  now += (hour + 12.0)/24.0;
21289  now += minute/1440.0;
21290  now += second/86400.0;
21291  *prNow = now;
21292#ifdef SQLITE_TEST
21293  if( sqlite3_current_time ){
21294    *prNow = sqlite3_current_time/86400.0 + 2440587.5;
21295  }
21296#endif
21297  return 0;
21298}
21299
21300static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
21301  return 0;
21302}
21303
21304/*
21305** Initialize and deinitialize the operating system interface.
21306*/
21307SQLITE_API int sqlite3_os_init(void){
21308  static sqlite3_vfs os2Vfs = {
21309    1,                 /* iVersion */
21310    sizeof(os2File),   /* szOsFile */
21311    CCHMAXPATH,        /* mxPathname */
21312    0,                 /* pNext */
21313    "os2",             /* zName */
21314    0,                 /* pAppData */
21315
21316    os2Open,           /* xOpen */
21317    os2Delete,         /* xDelete */
21318    os2Access,         /* xAccess */
21319    os2FullPathname,   /* xFullPathname */
21320    os2DlOpen,         /* xDlOpen */
21321    os2DlError,        /* xDlError */
21322    os2DlSym,          /* xDlSym */
21323    os2DlClose,        /* xDlClose */
21324    os2Randomness,     /* xRandomness */
21325    os2Sleep,          /* xSleep */
21326    os2CurrentTime,    /* xCurrentTime */
21327    os2GetLastError    /* xGetLastError */
21328  };
21329  sqlite3_vfs_register(&os2Vfs, 1);
21330  initUconvObjects();
21331  return SQLITE_OK;
21332}
21333SQLITE_API int sqlite3_os_end(void){
21334  freeUconvObjects();
21335  return SQLITE_OK;
21336}
21337
21338#endif /* SQLITE_OS_OS2 */
21339
21340/************** End of os_os2.c **********************************************/
21341/************** Begin file os_unix.c *****************************************/
21342/*
21343** 2004 May 22
21344**
21345** The author disclaims copyright to this source code.  In place of
21346** a legal notice, here is a blessing:
21347**
21348**    May you do good and not evil.
21349**    May you find forgiveness for yourself and forgive others.
21350**    May you share freely, never taking more than you give.
21351**
21352******************************************************************************
21353**
21354** This file contains the VFS implementation for unix-like operating systems
21355** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
21356**
21357** There are actually several different VFS implementations in this file.
21358** The differences are in the way that file locking is done.  The default
21359** implementation uses Posix Advisory Locks.  Alternative implementations
21360** use flock(), dot-files, various proprietary locking schemas, or simply
21361** skip locking all together.
21362**
21363** This source file is organized into divisions where the logic for various
21364** subfunctions is contained within the appropriate division.  PLEASE
21365** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
21366** in the correct division and should be clearly labeled.
21367**
21368** The layout of divisions is as follows:
21369**
21370**   *  General-purpose declarations and utility functions.
21371**   *  Unique file ID logic used by VxWorks.
21372**   *  Various locking primitive implementations (all except proxy locking):
21373**      + for Posix Advisory Locks
21374**      + for no-op locks
21375**      + for dot-file locks
21376**      + for flock() locking
21377**      + for named semaphore locks (VxWorks only)
21378**      + for AFP filesystem locks (MacOSX only)
21379**   *  sqlite3_file methods not associated with locking.
21380**   *  Definitions of sqlite3_io_methods objects for all locking
21381**      methods plus "finder" functions for each locking method.
21382**   *  sqlite3_vfs method implementations.
21383**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
21384**   *  Definitions of sqlite3_vfs objects for all locking methods
21385**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
21386*/
21387#if SQLITE_OS_UNIX              /* This file is used on unix only */
21388
21389/*
21390** There are various methods for file locking used for concurrency
21391** control:
21392**
21393**   1. POSIX locking (the default),
21394**   2. No locking,
21395**   3. Dot-file locking,
21396**   4. flock() locking,
21397**   5. AFP locking (OSX only),
21398**   6. Named POSIX semaphores (VXWorks only),
21399**   7. proxy locking. (OSX only)
21400**
21401** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
21402** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
21403** selection of the appropriate locking style based on the filesystem
21404** where the database is located.
21405*/
21406#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
21407#  if defined(__APPLE__)
21408#    define SQLITE_ENABLE_LOCKING_STYLE 1
21409#  else
21410#    define SQLITE_ENABLE_LOCKING_STYLE 0
21411#  endif
21412#endif
21413
21414/*
21415** Define the OS_VXWORKS pre-processor macro to 1 if building on
21416** vxworks, or 0 otherwise.
21417*/
21418#ifndef OS_VXWORKS
21419#  if defined(__RTP__) || defined(_WRS_KERNEL)
21420#    define OS_VXWORKS 1
21421#  else
21422#    define OS_VXWORKS 0
21423#  endif
21424#endif
21425
21426/*
21427** These #defines should enable >2GB file support on Posix if the
21428** underlying operating system supports it.  If the OS lacks
21429** large file support, these should be no-ops.
21430**
21431** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
21432** on the compiler command line.  This is necessary if you are compiling
21433** on a recent machine (ex: RedHat 7.2) but you want your code to work
21434** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
21435** without this option, LFS is enable.  But LFS does not exist in the kernel
21436** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
21437** portability you should omit LFS.
21438**
21439** The previous paragraph was written in 2005.  (This paragraph is written
21440** on 2008-11-28.) These days, all Linux kernels support large files, so
21441** you should probably leave LFS enabled.  But some embedded platforms might
21442** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
21443*/
21444#ifndef SQLITE_DISABLE_LFS
21445# define _LARGE_FILE       1
21446# ifndef _FILE_OFFSET_BITS
21447#   define _FILE_OFFSET_BITS 64
21448# endif
21449# define _LARGEFILE_SOURCE 1
21450#endif
21451
21452/*
21453** standard include files.
21454*/
21455#include <sys/types.h>
21456#include <sys/stat.h>
21457#include <fcntl.h>
21458#include <unistd.h>
21459#include <sys/time.h>
21460#include <errno.h>
21461
21462#if SQLITE_ENABLE_LOCKING_STYLE
21463# include <sys/ioctl.h>
21464# if OS_VXWORKS
21465#  include <semaphore.h>
21466#  include <limits.h>
21467# else
21468#  include <sys/file.h>
21469#  include <sys/param.h>
21470#  include <sys/mount.h>
21471# endif
21472#endif /* SQLITE_ENABLE_LOCKING_STYLE */
21473
21474/*
21475** If we are to be thread-safe, include the pthreads header and define
21476** the SQLITE_UNIX_THREADS macro.
21477*/
21478#if SQLITE_THREADSAFE
21479# define SQLITE_UNIX_THREADS 1
21480#endif
21481
21482/*
21483** Default permissions when creating a new file
21484*/
21485#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
21486# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
21487#endif
21488
21489/*
21490 ** Default permissions when creating auto proxy dir
21491 */
21492#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
21493# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
21494#endif
21495
21496/*
21497** Maximum supported path-length.
21498*/
21499#define MAX_PATHNAME 512
21500
21501/*
21502** Only set the lastErrno if the error code is a real error and not
21503** a normal expected return code of SQLITE_BUSY or SQLITE_OK
21504*/
21505#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
21506
21507
21508/*
21509** Sometimes, after a file handle is closed by SQLite, the file descriptor
21510** cannot be closed immediately. In these cases, instances of the following
21511** structure are used to store the file descriptor while waiting for an
21512** opportunity to either close or reuse it.
21513*/
21514typedef struct UnixUnusedFd UnixUnusedFd;
21515struct UnixUnusedFd {
21516  int fd;                   /* File descriptor to close */
21517  int flags;                /* Flags this file descriptor was opened with */
21518  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
21519};
21520
21521/*
21522** The unixFile structure is subclass of sqlite3_file specific to the unix
21523** VFS implementations.
21524*/
21525typedef struct unixFile unixFile;
21526struct unixFile {
21527  sqlite3_io_methods const *pMethod;  /* Always the first entry */
21528  struct unixOpenCnt *pOpen;       /* Info about all open fd's on this inode */
21529  struct unixLockInfo *pLock;      /* Info about locks on this inode */
21530  int h;                           /* The file descriptor */
21531  int dirfd;                       /* File descriptor for the directory */
21532  unsigned char locktype;          /* The type of lock held on this fd */
21533  int lastErrno;                   /* The unix errno from the last I/O error */
21534  void *lockingContext;            /* Locking style specific state */
21535  UnixUnusedFd *pUnused;           /* Pre-allocated UnixUnusedFd */
21536  int fileFlags;                   /* Miscellanous flags */
21537#if SQLITE_ENABLE_LOCKING_STYLE
21538  int openFlags;                   /* The flags specified at open() */
21539#endif
21540#if SQLITE_THREADSAFE && defined(__linux__)
21541  pthread_t tid;                   /* The thread that "owns" this unixFile */
21542#endif
21543#if OS_VXWORKS
21544  int isDelete;                    /* Delete on close if true */
21545  struct vxworksFileId *pId;       /* Unique file ID */
21546#endif
21547#ifndef NDEBUG
21548  /* The next group of variables are used to track whether or not the
21549  ** transaction counter in bytes 24-27 of database files are updated
21550  ** whenever any part of the database changes.  An assertion fault will
21551  ** occur if a file is updated without also updating the transaction
21552  ** counter.  This test is made to avoid new problems similar to the
21553  ** one described by ticket #3584.
21554  */
21555  unsigned char transCntrChng;   /* True if the transaction counter changed */
21556  unsigned char dbUpdate;        /* True if any part of database file changed */
21557  unsigned char inNormalWrite;   /* True if in a normal write operation */
21558#endif
21559#ifdef SQLITE_TEST
21560  /* In test mode, increase the size of this structure a bit so that
21561  ** it is larger than the struct CrashFile defined in test6.c.
21562  */
21563  char aPadding[32];
21564#endif
21565};
21566
21567/*
21568** The following macros define bits in unixFile.fileFlags
21569*/
21570#define SQLITE_WHOLE_FILE_LOCKING  0x0001   /* Use whole-file locking */
21571
21572/*
21573** Include code that is common to all os_*.c files
21574*/
21575/************** Include os_common.h in the middle of os_unix.c ***************/
21576/************** Begin file os_common.h ***************************************/
21577/*
21578** 2004 May 22
21579**
21580** The author disclaims copyright to this source code.  In place of
21581** a legal notice, here is a blessing:
21582**
21583**    May you do good and not evil.
21584**    May you find forgiveness for yourself and forgive others.
21585**    May you share freely, never taking more than you give.
21586**
21587******************************************************************************
21588**
21589** This file contains macros and a little bit of code that is common to
21590** all of the platform-specific files (os_*.c) and is #included into those
21591** files.
21592**
21593** This file should be #included by the os_*.c files only.  It is not a
21594** general purpose header file.
21595*/
21596#ifndef _OS_COMMON_H_
21597#define _OS_COMMON_H_
21598
21599/*
21600** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21601** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21602** switch.  The following code should catch this problem at compile-time.
21603*/
21604#ifdef MEMORY_DEBUG
21605# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21606#endif
21607
21608#ifdef SQLITE_DEBUG
21609SQLITE_PRIVATE int sqlite3OSTrace = 0;
21610#define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
21611#define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
21612#define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
21613#define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
21614#define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
21615#define OSTRACE6(X,Y,Z,A,B,C) \
21616    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
21617#define OSTRACE7(X,Y,Z,A,B,C,D) \
21618    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
21619#else
21620#define OSTRACE1(X)
21621#define OSTRACE2(X,Y)
21622#define OSTRACE3(X,Y,Z)
21623#define OSTRACE4(X,Y,Z,A)
21624#define OSTRACE5(X,Y,Z,A,B)
21625#define OSTRACE6(X,Y,Z,A,B,C)
21626#define OSTRACE7(X,Y,Z,A,B,C,D)
21627#endif
21628
21629/*
21630** Macros for performance tracing.  Normally turned off.  Only works
21631** on i486 hardware.
21632*/
21633#ifdef SQLITE_PERFORMANCE_TRACE
21634
21635/*
21636** hwtime.h contains inline assembler code for implementing
21637** high-performance timing routines.
21638*/
21639/************** Include hwtime.h in the middle of os_common.h ****************/
21640/************** Begin file hwtime.h ******************************************/
21641/*
21642** 2008 May 27
21643**
21644** The author disclaims copyright to this source code.  In place of
21645** a legal notice, here is a blessing:
21646**
21647**    May you do good and not evil.
21648**    May you find forgiveness for yourself and forgive others.
21649**    May you share freely, never taking more than you give.
21650**
21651******************************************************************************
21652**
21653** This file contains inline asm code for retrieving "high-performance"
21654** counters for x86 class CPUs.
21655*/
21656#ifndef _HWTIME_H_
21657#define _HWTIME_H_
21658
21659/*
21660** The following routine only works on pentium-class (or newer) processors.
21661** It uses the RDTSC opcode to read the cycle count value out of the
21662** processor and returns that value.  This can be used for high-res
21663** profiling.
21664*/
21665#if (defined(__GNUC__) || defined(_MSC_VER)) && \
21666      (defined(i386) || defined(__i386__) || defined(_M_IX86))
21667
21668  #if defined(__GNUC__)
21669
21670  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21671     unsigned int lo, hi;
21672     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21673     return (sqlite_uint64)hi << 32 | lo;
21674  }
21675
21676  #elif defined(_MSC_VER)
21677
21678  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21679     __asm {
21680        rdtsc
21681        ret       ; return value at EDX:EAX
21682     }
21683  }
21684
21685  #endif
21686
21687#elif (defined(__GNUC__) && defined(__x86_64__))
21688
21689  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21690      unsigned long val;
21691      __asm__ __volatile__ ("rdtsc" : "=A" (val));
21692      return val;
21693  }
21694
21695#elif (defined(__GNUC__) && defined(__ppc__))
21696
21697  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21698      unsigned long long retval;
21699      unsigned long junk;
21700      __asm__ __volatile__ ("\n\
21701          1:      mftbu   %1\n\
21702                  mftb    %L0\n\
21703                  mftbu   %0\n\
21704                  cmpw    %0,%1\n\
21705                  bne     1b"
21706                  : "=r" (retval), "=r" (junk));
21707      return retval;
21708  }
21709
21710#else
21711
21712  #error Need implementation of sqlite3Hwtime() for your platform.
21713
21714  /*
21715  ** To compile without implementing sqlite3Hwtime() for your platform,
21716  ** you can remove the above #error and use the following
21717  ** stub function.  You will lose timing support for many
21718  ** of the debugging and testing utilities, but it should at
21719  ** least compile and run.
21720  */
21721SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21722
21723#endif
21724
21725#endif /* !defined(_HWTIME_H_) */
21726
21727/************** End of hwtime.h **********************************************/
21728/************** Continuing where we left off in os_common.h ******************/
21729
21730static sqlite_uint64 g_start;
21731static sqlite_uint64 g_elapsed;
21732#define TIMER_START       g_start=sqlite3Hwtime()
21733#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21734#define TIMER_ELAPSED     g_elapsed
21735#else
21736#define TIMER_START
21737#define TIMER_END
21738#define TIMER_ELAPSED     ((sqlite_uint64)0)
21739#endif
21740
21741/*
21742** If we compile with the SQLITE_TEST macro set, then the following block
21743** of code will give us the ability to simulate a disk I/O error.  This
21744** is used for testing the I/O recovery logic.
21745*/
21746#ifdef SQLITE_TEST
21747SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21748SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21749SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21750SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21751SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21752SQLITE_API int sqlite3_diskfull_pending = 0;
21753SQLITE_API int sqlite3_diskfull = 0;
21754#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21755#define SimulateIOError(CODE)  \
21756  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21757       || sqlite3_io_error_pending-- == 1 )  \
21758              { local_ioerr(); CODE; }
21759static void local_ioerr(){
21760  IOTRACE(("IOERR\n"));
21761  sqlite3_io_error_hit++;
21762  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21763}
21764#define SimulateDiskfullError(CODE) \
21765   if( sqlite3_diskfull_pending ){ \
21766     if( sqlite3_diskfull_pending == 1 ){ \
21767       local_ioerr(); \
21768       sqlite3_diskfull = 1; \
21769       sqlite3_io_error_hit = 1; \
21770       CODE; \
21771     }else{ \
21772       sqlite3_diskfull_pending--; \
21773     } \
21774   }
21775#else
21776#define SimulateIOErrorBenign(X)
21777#define SimulateIOError(A)
21778#define SimulateDiskfullError(A)
21779#endif
21780
21781/*
21782** When testing, keep a count of the number of open files.
21783*/
21784#ifdef SQLITE_TEST
21785SQLITE_API int sqlite3_open_file_count = 0;
21786#define OpenCounter(X)  sqlite3_open_file_count+=(X)
21787#else
21788#define OpenCounter(X)
21789#endif
21790
21791#endif /* !defined(_OS_COMMON_H_) */
21792
21793/************** End of os_common.h *******************************************/
21794/************** Continuing where we left off in os_unix.c ********************/
21795
21796/*
21797** Define various macros that are missing from some systems.
21798*/
21799#ifndef O_LARGEFILE
21800# define O_LARGEFILE 0
21801#endif
21802#ifdef SQLITE_DISABLE_LFS
21803# undef O_LARGEFILE
21804# define O_LARGEFILE 0
21805#endif
21806#ifndef O_NOFOLLOW
21807# define O_NOFOLLOW 0
21808#endif
21809#ifndef O_BINARY
21810# define O_BINARY 0
21811#endif
21812
21813/*
21814** The DJGPP compiler environment looks mostly like Unix, but it
21815** lacks the fcntl() system call.  So redefine fcntl() to be something
21816** that always succeeds.  This means that locking does not occur under
21817** DJGPP.  But it is DOS - what did you expect?
21818*/
21819#ifdef __DJGPP__
21820# define fcntl(A,B,C) 0
21821#endif
21822
21823/*
21824** The threadid macro resolves to the thread-id or to 0.  Used for
21825** testing and debugging only.
21826*/
21827#if SQLITE_THREADSAFE
21828#define threadid pthread_self()
21829#else
21830#define threadid 0
21831#endif
21832
21833
21834/*
21835** Helper functions to obtain and relinquish the global mutex. The
21836** global mutex is used to protect the unixOpenCnt, unixLockInfo and
21837** vxworksFileId objects used by this file, all of which may be
21838** shared by multiple threads.
21839**
21840** Function unixMutexHeld() is used to assert() that the global mutex
21841** is held when required. This function is only used as part of assert()
21842** statements. e.g.
21843**
21844**   unixEnterMutex()
21845**     assert( unixMutexHeld() );
21846**   unixEnterLeave()
21847*/
21848static void unixEnterMutex(void){
21849  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21850}
21851static void unixLeaveMutex(void){
21852  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21853}
21854#ifdef SQLITE_DEBUG
21855static int unixMutexHeld(void) {
21856  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21857}
21858#endif
21859
21860
21861#ifdef SQLITE_DEBUG
21862/*
21863** Helper function for printing out trace information from debugging
21864** binaries. This returns the string represetation of the supplied
21865** integer lock-type.
21866*/
21867static const char *locktypeName(int locktype){
21868  switch( locktype ){
21869    case NO_LOCK: return "NONE";
21870    case SHARED_LOCK: return "SHARED";
21871    case RESERVED_LOCK: return "RESERVED";
21872    case PENDING_LOCK: return "PENDING";
21873    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
21874  }
21875  return "ERROR";
21876}
21877#endif
21878
21879#ifdef SQLITE_LOCK_TRACE
21880/*
21881** Print out information about all locking operations.
21882**
21883** This routine is used for troubleshooting locks on multithreaded
21884** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
21885** command-line option on the compiler.  This code is normally
21886** turned off.
21887*/
21888static int lockTrace(int fd, int op, struct flock *p){
21889  char *zOpName, *zType;
21890  int s;
21891  int savedErrno;
21892  if( op==F_GETLK ){
21893    zOpName = "GETLK";
21894  }else if( op==F_SETLK ){
21895    zOpName = "SETLK";
21896  }else{
21897    s = fcntl(fd, op, p);
21898    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
21899    return s;
21900  }
21901  if( p->l_type==F_RDLCK ){
21902    zType = "RDLCK";
21903  }else if( p->l_type==F_WRLCK ){
21904    zType = "WRLCK";
21905  }else if( p->l_type==F_UNLCK ){
21906    zType = "UNLCK";
21907  }else{
21908    assert( 0 );
21909  }
21910  assert( p->l_whence==SEEK_SET );
21911  s = fcntl(fd, op, p);
21912  savedErrno = errno;
21913  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
21914     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
21915     (int)p->l_pid, s);
21916  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
21917    struct flock l2;
21918    l2 = *p;
21919    fcntl(fd, F_GETLK, &l2);
21920    if( l2.l_type==F_RDLCK ){
21921      zType = "RDLCK";
21922    }else if( l2.l_type==F_WRLCK ){
21923      zType = "WRLCK";
21924    }else if( l2.l_type==F_UNLCK ){
21925      zType = "UNLCK";
21926    }else{
21927      assert( 0 );
21928    }
21929    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
21930       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
21931  }
21932  errno = savedErrno;
21933  return s;
21934}
21935#define fcntl lockTrace
21936#endif /* SQLITE_LOCK_TRACE */
21937
21938
21939
21940/*
21941** This routine translates a standard POSIX errno code into something
21942** useful to the clients of the sqlite3 functions.  Specifically, it is
21943** intended to translate a variety of "try again" errors into SQLITE_BUSY
21944** and a variety of "please close the file descriptor NOW" errors into
21945** SQLITE_IOERR
21946**
21947** Errors during initialization of locks, or file system support for locks,
21948** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
21949*/
21950static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
21951  switch (posixError) {
21952  case 0:
21953    return SQLITE_OK;
21954
21955  case EAGAIN:
21956  case ETIMEDOUT:
21957  case EBUSY:
21958  case EINTR:
21959  case ENOLCK:
21960    /* random NFS retry error, unless during file system support
21961     * introspection, in which it actually means what it says */
21962    return SQLITE_BUSY;
21963
21964  case EACCES:
21965    /* EACCES is like EAGAIN during locking operations, but not any other time*/
21966    if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
21967	(sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
21968	(sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
21969	(sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
21970      return SQLITE_BUSY;
21971    }
21972    /* else fall through */
21973  case EPERM:
21974    return SQLITE_PERM;
21975
21976  case EDEADLK:
21977    return SQLITE_IOERR_BLOCKED;
21978
21979#if EOPNOTSUPP!=ENOTSUP
21980  case EOPNOTSUPP:
21981    /* something went terribly awry, unless during file system support
21982     * introspection, in which it actually means what it says */
21983#endif
21984#ifdef ENOTSUP
21985  case ENOTSUP:
21986    /* invalid fd, unless during file system support introspection, in which
21987     * it actually means what it says */
21988#endif
21989  case EIO:
21990  case EBADF:
21991  case EINVAL:
21992  case ENOTCONN:
21993  case ENODEV:
21994  case ENXIO:
21995  case ENOENT:
21996  case ESTALE:
21997  case ENOSYS:
21998    /* these should force the client to close the file and reconnect */
21999
22000  default:
22001    return sqliteIOErr;
22002  }
22003}
22004
22005
22006
22007/******************************************************************************
22008****************** Begin Unique File ID Utility Used By VxWorks ***************
22009**
22010** On most versions of unix, we can get a unique ID for a file by concatenating
22011** the device number and the inode number.  But this does not work on VxWorks.
22012** On VxWorks, a unique file id must be based on the canonical filename.
22013**
22014** A pointer to an instance of the following structure can be used as a
22015** unique file ID in VxWorks.  Each instance of this structure contains
22016** a copy of the canonical filename.  There is also a reference count.
22017** The structure is reclaimed when the number of pointers to it drops to
22018** zero.
22019**
22020** There are never very many files open at one time and lookups are not
22021** a performance-critical path, so it is sufficient to put these
22022** structures on a linked list.
22023*/
22024struct vxworksFileId {
22025  struct vxworksFileId *pNext;  /* Next in a list of them all */
22026  int nRef;                     /* Number of references to this one */
22027  int nName;                    /* Length of the zCanonicalName[] string */
22028  char *zCanonicalName;         /* Canonical filename */
22029};
22030
22031#if OS_VXWORKS
22032/*
22033** All unique filenames are held on a linked list headed by this
22034** variable:
22035*/
22036static struct vxworksFileId *vxworksFileList = 0;
22037
22038/*
22039** Simplify a filename into its canonical form
22040** by making the following changes:
22041**
22042**  * removing any trailing and duplicate /
22043**  * convert /./ into just /
22044**  * convert /A/../ where A is any simple name into just /
22045**
22046** Changes are made in-place.  Return the new name length.
22047**
22048** The original filename is in z[0..n-1].  Return the number of
22049** characters in the simplified name.
22050*/
22051static int vxworksSimplifyName(char *z, int n){
22052  int i, j;
22053  while( n>1 && z[n-1]=='/' ){ n--; }
22054  for(i=j=0; i<n; i++){
22055    if( z[i]=='/' ){
22056      if( z[i+1]=='/' ) continue;
22057      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
22058        i += 1;
22059        continue;
22060      }
22061      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
22062        while( j>0 && z[j-1]!='/' ){ j--; }
22063        if( j>0 ){ j--; }
22064        i += 2;
22065        continue;
22066      }
22067    }
22068    z[j++] = z[i];
22069  }
22070  z[j] = 0;
22071  return j;
22072}
22073
22074/*
22075** Find a unique file ID for the given absolute pathname.  Return
22076** a pointer to the vxworksFileId object.  This pointer is the unique
22077** file ID.
22078**
22079** The nRef field of the vxworksFileId object is incremented before
22080** the object is returned.  A new vxworksFileId object is created
22081** and added to the global list if necessary.
22082**
22083** If a memory allocation error occurs, return NULL.
22084*/
22085static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
22086  struct vxworksFileId *pNew;         /* search key and new file ID */
22087  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
22088  int n;                              /* Length of zAbsoluteName string */
22089
22090  assert( zAbsoluteName[0]=='/' );
22091  n = (int)strlen(zAbsoluteName);
22092  pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
22093  if( pNew==0 ) return 0;
22094  pNew->zCanonicalName = (char*)&pNew[1];
22095  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
22096  n = vxworksSimplifyName(pNew->zCanonicalName, n);
22097
22098  /* Search for an existing entry that matching the canonical name.
22099  ** If found, increment the reference count and return a pointer to
22100  ** the existing file ID.
22101  */
22102  unixEnterMutex();
22103  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
22104    if( pCandidate->nName==n
22105     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
22106    ){
22107       sqlite3_free(pNew);
22108       pCandidate->nRef++;
22109       unixLeaveMutex();
22110       return pCandidate;
22111    }
22112  }
22113
22114  /* No match was found.  We will make a new file ID */
22115  pNew->nRef = 1;
22116  pNew->nName = n;
22117  pNew->pNext = vxworksFileList;
22118  vxworksFileList = pNew;
22119  unixLeaveMutex();
22120  return pNew;
22121}
22122
22123/*
22124** Decrement the reference count on a vxworksFileId object.  Free
22125** the object when the reference count reaches zero.
22126*/
22127static void vxworksReleaseFileId(struct vxworksFileId *pId){
22128  unixEnterMutex();
22129  assert( pId->nRef>0 );
22130  pId->nRef--;
22131  if( pId->nRef==0 ){
22132    struct vxworksFileId **pp;
22133    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
22134    assert( *pp==pId );
22135    *pp = pId->pNext;
22136    sqlite3_free(pId);
22137  }
22138  unixLeaveMutex();
22139}
22140#endif /* OS_VXWORKS */
22141/*************** End of Unique File ID Utility Used By VxWorks ****************
22142******************************************************************************/
22143
22144
22145/******************************************************************************
22146*************************** Posix Advisory Locking ****************************
22147**
22148** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
22149** section 6.5.2.2 lines 483 through 490 specify that when a process
22150** sets or clears a lock, that operation overrides any prior locks set
22151** by the same process.  It does not explicitly say so, but this implies
22152** that it overrides locks set by the same process using a different
22153** file descriptor.  Consider this test case:
22154**
22155**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
22156**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
22157**
22158** Suppose ./file1 and ./file2 are really the same file (because
22159** one is a hard or symbolic link to the other) then if you set
22160** an exclusive lock on fd1, then try to get an exclusive lock
22161** on fd2, it works.  I would have expected the second lock to
22162** fail since there was already a lock on the file due to fd1.
22163** But not so.  Since both locks came from the same process, the
22164** second overrides the first, even though they were on different
22165** file descriptors opened on different file names.
22166**
22167** This means that we cannot use POSIX locks to synchronize file access
22168** among competing threads of the same process.  POSIX locks will work fine
22169** to synchronize access for threads in separate processes, but not
22170** threads within the same process.
22171**
22172** To work around the problem, SQLite has to manage file locks internally
22173** on its own.  Whenever a new database is opened, we have to find the
22174** specific inode of the database file (the inode is determined by the
22175** st_dev and st_ino fields of the stat structure that fstat() fills in)
22176** and check for locks already existing on that inode.  When locks are
22177** created or removed, we have to look at our own internal record of the
22178** locks to see if another thread has previously set a lock on that same
22179** inode.
22180**
22181** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
22182** For VxWorks, we have to use the alternative unique ID system based on
22183** canonical filename and implemented in the previous division.)
22184**
22185** The sqlite3_file structure for POSIX is no longer just an integer file
22186** descriptor.  It is now a structure that holds the integer file
22187** descriptor and a pointer to a structure that describes the internal
22188** locks on the corresponding inode.  There is one locking structure
22189** per inode, so if the same inode is opened twice, both unixFile structures
22190** point to the same locking structure.  The locking structure keeps
22191** a reference count (so we will know when to delete it) and a "cnt"
22192** field that tells us its internal lock status.  cnt==0 means the
22193** file is unlocked.  cnt==-1 means the file has an exclusive lock.
22194** cnt>0 means there are cnt shared locks on the file.
22195**
22196** Any attempt to lock or unlock a file first checks the locking
22197** structure.  The fcntl() system call is only invoked to set a
22198** POSIX lock if the internal lock structure transitions between
22199** a locked and an unlocked state.
22200**
22201** But wait:  there are yet more problems with POSIX advisory locks.
22202**
22203** If you close a file descriptor that points to a file that has locks,
22204** all locks on that file that are owned by the current process are
22205** released.  To work around this problem, each unixFile structure contains
22206** a pointer to an unixOpenCnt structure.  There is one unixOpenCnt structure
22207** per open inode, which means that multiple unixFile can point to a single
22208** unixOpenCnt.  When an attempt is made to close an unixFile, if there are
22209** other unixFile open on the same inode that are holding locks, the call
22210** to close() the file descriptor is deferred until all of the locks clear.
22211** The unixOpenCnt structure keeps a list of file descriptors that need to
22212** be closed and that list is walked (and cleared) when the last lock
22213** clears.
22214**
22215** Yet another problem:  LinuxThreads do not play well with posix locks.
22216**
22217** Many older versions of linux use the LinuxThreads library which is
22218** not posix compliant.  Under LinuxThreads, a lock created by thread
22219** A cannot be modified or overridden by a different thread B.
22220** Only thread A can modify the lock.  Locking behavior is correct
22221** if the appliation uses the newer Native Posix Thread Library (NPTL)
22222** on linux - with NPTL a lock created by thread A can override locks
22223** in thread B.  But there is no way to know at compile-time which
22224** threading library is being used.  So there is no way to know at
22225** compile-time whether or not thread A can override locks on thread B.
22226** We have to do a run-time check to discover the behavior of the
22227** current process.
22228**
22229** On systems where thread A is unable to modify locks created by
22230** thread B, we have to keep track of which thread created each
22231** lock.  Hence there is an extra field in the key to the unixLockInfo
22232** structure to record this information.  And on those systems it
22233** is illegal to begin a transaction in one thread and finish it
22234** in another.  For this latter restriction, there is no work-around.
22235** It is a limitation of LinuxThreads.
22236*/
22237
22238/*
22239** Set or check the unixFile.tid field.  This field is set when an unixFile
22240** is first opened.  All subsequent uses of the unixFile verify that the
22241** same thread is operating on the unixFile.  Some operating systems do
22242** not allow locks to be overridden by other threads and that restriction
22243** means that sqlite3* database handles cannot be moved from one thread
22244** to another while locks are held.
22245**
22246** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
22247** another as long as we are running on a system that supports threads
22248** overriding each others locks (which is now the most common behavior)
22249** or if no locks are held.  But the unixFile.pLock field needs to be
22250** recomputed because its key includes the thread-id.  See the
22251** transferOwnership() function below for additional information
22252*/
22253#if SQLITE_THREADSAFE && defined(__linux__)
22254# define SET_THREADID(X)   (X)->tid = pthread_self()
22255# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
22256                            !pthread_equal((X)->tid, pthread_self()))
22257#else
22258# define SET_THREADID(X)
22259# define CHECK_THREADID(X) 0
22260#endif
22261
22262/*
22263** An instance of the following structure serves as the key used
22264** to locate a particular unixOpenCnt structure given its inode.  This
22265** is the same as the unixLockKey except that the thread ID is omitted.
22266*/
22267struct unixFileId {
22268  dev_t dev;                  /* Device number */
22269#if OS_VXWORKS
22270  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
22271#else
22272  ino_t ino;                  /* Inode number */
22273#endif
22274};
22275
22276/*
22277** An instance of the following structure serves as the key used
22278** to locate a particular unixLockInfo structure given its inode.
22279**
22280** If threads cannot override each others locks (LinuxThreads), then we
22281** set the unixLockKey.tid field to the thread ID.  If threads can override
22282** each others locks (Posix and NPTL) then tid is always set to zero.
22283** tid is omitted if we compile without threading support or on an OS
22284** other than linux.
22285*/
22286struct unixLockKey {
22287  struct unixFileId fid;  /* Unique identifier for the file */
22288#if SQLITE_THREADSAFE && defined(__linux__)
22289  pthread_t tid;  /* Thread ID of lock owner. Zero if not using LinuxThreads */
22290#endif
22291};
22292
22293/*
22294** An instance of the following structure is allocated for each open
22295** inode.  Or, on LinuxThreads, there is one of these structures for
22296** each inode opened by each thread.
22297**
22298** A single inode can have multiple file descriptors, so each unixFile
22299** structure contains a pointer to an instance of this object and this
22300** object keeps a count of the number of unixFile pointing to it.
22301*/
22302struct unixLockInfo {
22303  struct unixLockKey lockKey;     /* The lookup key */
22304  int cnt;                        /* Number of SHARED locks held */
22305  int locktype;                   /* One of SHARED_LOCK, RESERVED_LOCK etc. */
22306  int nRef;                       /* Number of pointers to this structure */
22307  struct unixLockInfo *pNext;     /* List of all unixLockInfo objects */
22308  struct unixLockInfo *pPrev;     /*    .... doubly linked */
22309};
22310
22311/*
22312** An instance of the following structure is allocated for each open
22313** inode.  This structure keeps track of the number of locks on that
22314** inode.  If a close is attempted against an inode that is holding
22315** locks, the close is deferred until all locks clear by adding the
22316** file descriptor to be closed to the pending list.
22317**
22318** TODO:  Consider changing this so that there is only a single file
22319** descriptor for each open file, even when it is opened multiple times.
22320** The close() system call would only occur when the last database
22321** using the file closes.
22322*/
22323struct unixOpenCnt {
22324  struct unixFileId fileId;   /* The lookup key */
22325  int nRef;                   /* Number of pointers to this structure */
22326  int nLock;                  /* Number of outstanding locks */
22327  UnixUnusedFd *pUnused;      /* Unused file descriptors to close */
22328#if OS_VXWORKS
22329  sem_t *pSem;                     /* Named POSIX semaphore */
22330  char aSemName[MAX_PATHNAME+2];   /* Name of that semaphore */
22331#endif
22332  struct unixOpenCnt *pNext, *pPrev;   /* List of all unixOpenCnt objects */
22333};
22334
22335/*
22336** Lists of all unixLockInfo and unixOpenCnt objects.  These used to be hash
22337** tables.  But the number of objects is rarely more than a dozen and
22338** never exceeds a few thousand.  And lookup is not on a critical
22339** path so a simple linked list will suffice.
22340*/
22341static struct unixLockInfo *lockList = 0;
22342static struct unixOpenCnt *openList = 0;
22343
22344/*
22345** This variable remembers whether or not threads can override each others
22346** locks.
22347**
22348**    0:  No.  Threads cannot override each others locks.  (LinuxThreads)
22349**    1:  Yes.  Threads can override each others locks.  (Posix & NLPT)
22350**   -1:  We don't know yet.
22351**
22352** On some systems, we know at compile-time if threads can override each
22353** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
22354** will be set appropriately.  On other systems, we have to check at
22355** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
22356** undefined.
22357**
22358** This variable normally has file scope only.  But during testing, we make
22359** it a global so that the test code can change its value in order to verify
22360** that the right stuff happens in either case.
22361*/
22362#if SQLITE_THREADSAFE && defined(__linux__)
22363#  ifndef SQLITE_THREAD_OVERRIDE_LOCK
22364#    define SQLITE_THREAD_OVERRIDE_LOCK -1
22365#  endif
22366#  ifdef SQLITE_TEST
22367int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22368#  else
22369static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22370#  endif
22371#endif
22372
22373/*
22374** This structure holds information passed into individual test
22375** threads by the testThreadLockingBehavior() routine.
22376*/
22377struct threadTestData {
22378  int fd;                /* File to be locked */
22379  struct flock lock;     /* The locking operation */
22380  int result;            /* Result of the locking operation */
22381};
22382
22383#if SQLITE_THREADSAFE && defined(__linux__)
22384/*
22385** This function is used as the main routine for a thread launched by
22386** testThreadLockingBehavior(). It tests whether the shared-lock obtained
22387** by the main thread in testThreadLockingBehavior() conflicts with a
22388** hypothetical write-lock obtained by this thread on the same file.
22389**
22390** The write-lock is not actually acquired, as this is not possible if
22391** the file is open in read-only mode (see ticket #3472).
22392*/
22393static void *threadLockingTest(void *pArg){
22394  struct threadTestData *pData = (struct threadTestData*)pArg;
22395  pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
22396  return pArg;
22397}
22398#endif /* SQLITE_THREADSAFE && defined(__linux__) */
22399
22400
22401#if SQLITE_THREADSAFE && defined(__linux__)
22402/*
22403** This procedure attempts to determine whether or not threads
22404** can override each others locks then sets the
22405** threadsOverrideEachOthersLocks variable appropriately.
22406*/
22407static void testThreadLockingBehavior(int fd_orig){
22408  int fd;
22409  int rc;
22410  struct threadTestData d;
22411  struct flock l;
22412  pthread_t t;
22413
22414  fd = dup(fd_orig);
22415  if( fd<0 ) return;
22416  memset(&l, 0, sizeof(l));
22417  l.l_type = F_RDLCK;
22418  l.l_len = 1;
22419  l.l_start = 0;
22420  l.l_whence = SEEK_SET;
22421  rc = fcntl(fd_orig, F_SETLK, &l);
22422  if( rc!=0 ) return;
22423  memset(&d, 0, sizeof(d));
22424  d.fd = fd;
22425  d.lock = l;
22426  d.lock.l_type = F_WRLCK;
22427  if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
22428    pthread_join(t, 0);
22429  }
22430  close(fd);
22431  if( d.result!=0 ) return;
22432  threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
22433}
22434#endif /* SQLITE_THREADSAFE && defined(__linux__) */
22435
22436/*
22437** Release a unixLockInfo structure previously allocated by findLockInfo().
22438**
22439** The mutex entered using the unixEnterMutex() function must be held
22440** when this function is called.
22441*/
22442static void releaseLockInfo(struct unixLockInfo *pLock){
22443  assert( unixMutexHeld() );
22444  if( pLock ){
22445    pLock->nRef--;
22446    if( pLock->nRef==0 ){
22447      if( pLock->pPrev ){
22448        assert( pLock->pPrev->pNext==pLock );
22449        pLock->pPrev->pNext = pLock->pNext;
22450      }else{
22451        assert( lockList==pLock );
22452        lockList = pLock->pNext;
22453      }
22454      if( pLock->pNext ){
22455        assert( pLock->pNext->pPrev==pLock );
22456        pLock->pNext->pPrev = pLock->pPrev;
22457      }
22458      sqlite3_free(pLock);
22459    }
22460  }
22461}
22462
22463/*
22464** Release a unixOpenCnt structure previously allocated by findLockInfo().
22465**
22466** The mutex entered using the unixEnterMutex() function must be held
22467** when this function is called.
22468*/
22469static void releaseOpenCnt(struct unixOpenCnt *pOpen){
22470  assert( unixMutexHeld() );
22471  if( pOpen ){
22472    pOpen->nRef--;
22473    if( pOpen->nRef==0 ){
22474      if( pOpen->pPrev ){
22475        assert( pOpen->pPrev->pNext==pOpen );
22476        pOpen->pPrev->pNext = pOpen->pNext;
22477      }else{
22478        assert( openList==pOpen );
22479        openList = pOpen->pNext;
22480      }
22481      if( pOpen->pNext ){
22482        assert( pOpen->pNext->pPrev==pOpen );
22483        pOpen->pNext->pPrev = pOpen->pPrev;
22484      }
22485#if SQLITE_THREADSAFE && defined(__linux__)
22486      assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
22487#endif
22488
22489      /* If pOpen->pUnused is not null, then memory and file-descriptors
22490      ** are leaked.
22491      **
22492      ** This will only happen if, under Linuxthreads, the user has opened
22493      ** a transaction in one thread, then attempts to close the database
22494      ** handle from another thread (without first unlocking the db file).
22495      ** This is a misuse.  */
22496      sqlite3_free(pOpen);
22497    }
22498  }
22499}
22500
22501/*
22502** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
22503** describes that file descriptor.  Create new ones if necessary.  The
22504** return values might be uninitialized if an error occurs.
22505**
22506** The mutex entered using the unixEnterMutex() function must be held
22507** when this function is called.
22508**
22509** Return an appropriate error code.
22510*/
22511static int findLockInfo(
22512  unixFile *pFile,               /* Unix file with file desc used in the key */
22513  struct unixLockInfo **ppLock,  /* Return the unixLockInfo structure here */
22514  struct unixOpenCnt **ppOpen    /* Return the unixOpenCnt structure here */
22515){
22516  int rc;                        /* System call return code */
22517  int fd;                        /* The file descriptor for pFile */
22518  struct unixLockKey lockKey;    /* Lookup key for the unixLockInfo structure */
22519  struct unixFileId fileId;      /* Lookup key for the unixOpenCnt struct */
22520  struct stat statbuf;           /* Low-level file information */
22521  struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
22522  struct unixOpenCnt *pOpen;     /* Candidate unixOpenCnt object */
22523
22524  assert( unixMutexHeld() );
22525
22526  /* Get low-level information about the file that we can used to
22527  ** create a unique name for the file.
22528  */
22529  fd = pFile->h;
22530  rc = fstat(fd, &statbuf);
22531  if( rc!=0 ){
22532    pFile->lastErrno = errno;
22533#ifdef EOVERFLOW
22534    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
22535#endif
22536    return SQLITE_IOERR;
22537  }
22538
22539#ifdef __APPLE__
22540  /* On OS X on an msdos filesystem, the inode number is reported
22541  ** incorrectly for zero-size files.  See ticket #3260.  To work
22542  ** around this problem (we consider it a bug in OS X, not SQLite)
22543  ** we always increase the file size to 1 by writing a single byte
22544  ** prior to accessing the inode number.  The one byte written is
22545  ** an ASCII 'S' character which also happens to be the first byte
22546  ** in the header of every SQLite database.  In this way, if there
22547  ** is a race condition such that another thread has already populated
22548  ** the first page of the database, no damage is done.
22549  */
22550  if( statbuf.st_size==0 ){
22551    rc = write(fd, "S", 1);
22552    if( rc!=1 ){
22553      return SQLITE_IOERR;
22554    }
22555    rc = fstat(fd, &statbuf);
22556    if( rc!=0 ){
22557      pFile->lastErrno = errno;
22558      return SQLITE_IOERR;
22559    }
22560  }
22561#endif
22562
22563  memset(&lockKey, 0, sizeof(lockKey));
22564  lockKey.fid.dev = statbuf.st_dev;
22565#if OS_VXWORKS
22566  lockKey.fid.pId = pFile->pId;
22567#else
22568  lockKey.fid.ino = statbuf.st_ino;
22569#endif
22570#if SQLITE_THREADSAFE && defined(__linux__)
22571  if( threadsOverrideEachOthersLocks<0 ){
22572    testThreadLockingBehavior(fd);
22573  }
22574  lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
22575#endif
22576  fileId = lockKey.fid;
22577  if( ppLock!=0 ){
22578    pLock = lockList;
22579    while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
22580      pLock = pLock->pNext;
22581    }
22582    if( pLock==0 ){
22583      pLock = sqlite3_malloc( sizeof(*pLock) );
22584      if( pLock==0 ){
22585        rc = SQLITE_NOMEM;
22586        goto exit_findlockinfo;
22587      }
22588      memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey));
22589      pLock->nRef = 1;
22590      pLock->cnt = 0;
22591      pLock->locktype = 0;
22592      pLock->pNext = lockList;
22593      pLock->pPrev = 0;
22594      if( lockList ) lockList->pPrev = pLock;
22595      lockList = pLock;
22596    }else{
22597      pLock->nRef++;
22598    }
22599    *ppLock = pLock;
22600  }
22601  if( ppOpen!=0 ){
22602    pOpen = openList;
22603    while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
22604      pOpen = pOpen->pNext;
22605    }
22606    if( pOpen==0 ){
22607      pOpen = sqlite3_malloc( sizeof(*pOpen) );
22608      if( pOpen==0 ){
22609        releaseLockInfo(pLock);
22610        rc = SQLITE_NOMEM;
22611        goto exit_findlockinfo;
22612      }
22613      memset(pOpen, 0, sizeof(*pOpen));
22614      pOpen->fileId = fileId;
22615      pOpen->nRef = 1;
22616      pOpen->pNext = openList;
22617      if( openList ) openList->pPrev = pOpen;
22618      openList = pOpen;
22619    }else{
22620      pOpen->nRef++;
22621    }
22622    *ppOpen = pOpen;
22623  }
22624
22625exit_findlockinfo:
22626  return rc;
22627}
22628
22629/*
22630** If we are currently in a different thread than the thread that the
22631** unixFile argument belongs to, then transfer ownership of the unixFile
22632** over to the current thread.
22633**
22634** A unixFile is only owned by a thread on systems that use LinuxThreads.
22635**
22636** Ownership transfer is only allowed if the unixFile is currently unlocked.
22637** If the unixFile is locked and an ownership is wrong, then return
22638** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
22639*/
22640#if SQLITE_THREADSAFE && defined(__linux__)
22641static int transferOwnership(unixFile *pFile){
22642  int rc;
22643  pthread_t hSelf;
22644  if( threadsOverrideEachOthersLocks ){
22645    /* Ownership transfers not needed on this system */
22646    return SQLITE_OK;
22647  }
22648  hSelf = pthread_self();
22649  if( pthread_equal(pFile->tid, hSelf) ){
22650    /* We are still in the same thread */
22651    OSTRACE1("No-transfer, same thread\n");
22652    return SQLITE_OK;
22653  }
22654  if( pFile->locktype!=NO_LOCK ){
22655    /* We cannot change ownership while we are holding a lock! */
22656    return SQLITE_MISUSE;
22657  }
22658  OSTRACE4("Transfer ownership of %d from %d to %d\n",
22659            pFile->h, pFile->tid, hSelf);
22660  pFile->tid = hSelf;
22661  if (pFile->pLock != NULL) {
22662    releaseLockInfo(pFile->pLock);
22663    rc = findLockInfo(pFile, &pFile->pLock, 0);
22664    OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
22665           locktypeName(pFile->locktype),
22666           locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
22667    return rc;
22668  } else {
22669    return SQLITE_OK;
22670  }
22671}
22672#else  /* if not SQLITE_THREADSAFE */
22673  /* On single-threaded builds, ownership transfer is a no-op */
22674# define transferOwnership(X) SQLITE_OK
22675#endif /* SQLITE_THREADSAFE */
22676
22677
22678/*
22679** This routine checks if there is a RESERVED lock held on the specified
22680** file by this or any other process. If such a lock is held, set *pResOut
22681** to a non-zero value otherwise *pResOut is set to zero.  The return value
22682** is set to SQLITE_OK unless an I/O error occurs during lock checking.
22683*/
22684static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
22685  int rc = SQLITE_OK;
22686  int reserved = 0;
22687  unixFile *pFile = (unixFile*)id;
22688
22689  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
22690
22691  assert( pFile );
22692  unixEnterMutex(); /* Because pFile->pLock is shared across threads */
22693
22694  /* Check if a thread in this process holds such a lock */
22695  if( pFile->pLock->locktype>SHARED_LOCK ){
22696    reserved = 1;
22697  }
22698
22699  /* Otherwise see if some other process holds it.
22700  */
22701#ifndef __DJGPP__
22702  if( !reserved ){
22703    struct flock lock;
22704    lock.l_whence = SEEK_SET;
22705    lock.l_start = RESERVED_BYTE;
22706    lock.l_len = 1;
22707    lock.l_type = F_WRLCK;
22708    if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
22709      int tErrno = errno;
22710      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
22711      pFile->lastErrno = tErrno;
22712    } else if( lock.l_type!=F_UNLCK ){
22713      reserved = 1;
22714    }
22715  }
22716#endif
22717
22718  unixLeaveMutex();
22719  OSTRACE4("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved);
22720
22721  *pResOut = reserved;
22722  return rc;
22723}
22724
22725/*
22726** Perform a file locking operation on a range of bytes in a file.
22727** The "op" parameter should be one of F_RDLCK, F_WRLCK, or F_UNLCK.
22728** Return 0 on success or -1 for failure.  On failure, write the error
22729** code into *pErrcode.
22730**
22731** If the SQLITE_WHOLE_FILE_LOCKING bit is clear, then only lock
22732** the range of bytes on the locking page between SHARED_FIRST and
22733** SHARED_SIZE.  If SQLITE_WHOLE_FILE_LOCKING is set, then lock all
22734** bytes from 0 up to but not including PENDING_BYTE, and all bytes
22735** that follow SHARED_FIRST.
22736**
22737** In other words, of SQLITE_WHOLE_FILE_LOCKING if false (the historical
22738** default case) then only lock a small range of bytes from SHARED_FIRST
22739** through SHARED_FIRST+SHARED_SIZE-1.  But if SQLITE_WHOLE_FILE_LOCKING is
22740** true then lock every byte in the file except for PENDING_BYTE and
22741** RESERVED_BYTE.
22742**
22743** SQLITE_WHOLE_FILE_LOCKING=true overlaps SQLITE_WHOLE_FILE_LOCKING=false
22744** and so the locking schemes are compatible.  One type of lock will
22745** effectively exclude the other type.  The reason for using the
22746** SQLITE_WHOLE_FILE_LOCKING=true is that by indicating the full range
22747** of bytes to be read or written, we give hints to NFS to help it
22748** maintain cache coherency.  On the other hand, whole file locking
22749** is slower, so we don't want to use it except for NFS.
22750*/
22751static int rangeLock(unixFile *pFile, int op, int *pErrcode){
22752  struct flock lock;
22753  int rc;
22754  lock.l_type = op;
22755  lock.l_start = SHARED_FIRST;
22756  lock.l_whence = SEEK_SET;
22757  if( (pFile->fileFlags & SQLITE_WHOLE_FILE_LOCKING)==0 ){
22758    lock.l_len = SHARED_SIZE;
22759    rc = fcntl(pFile->h, F_SETLK, &lock);
22760    *pErrcode = errno;
22761  }else{
22762    lock.l_len = 0;
22763    rc = fcntl(pFile->h, F_SETLK, &lock);
22764    *pErrcode = errno;
22765    if( NEVER(op==F_UNLCK) || rc!=(-1) ){
22766      lock.l_start = 0;
22767      lock.l_len = PENDING_BYTE;
22768      rc = fcntl(pFile->h, F_SETLK, &lock);
22769      if( ALWAYS(op!=F_UNLCK) && rc==(-1) ){
22770        *pErrcode = errno;
22771        lock.l_type = F_UNLCK;
22772        lock.l_start = SHARED_FIRST;
22773        lock.l_len = 0;
22774        fcntl(pFile->h, F_SETLK, &lock);
22775      }
22776    }
22777  }
22778  return rc;
22779}
22780
22781/*
22782** Lock the file with the lock specified by parameter locktype - one
22783** of the following:
22784**
22785**     (1) SHARED_LOCK
22786**     (2) RESERVED_LOCK
22787**     (3) PENDING_LOCK
22788**     (4) EXCLUSIVE_LOCK
22789**
22790** Sometimes when requesting one lock state, additional lock states
22791** are inserted in between.  The locking might fail on one of the later
22792** transitions leaving the lock state different from what it started but
22793** still short of its goal.  The following chart shows the allowed
22794** transitions and the inserted intermediate states:
22795**
22796**    UNLOCKED -> SHARED
22797**    SHARED -> RESERVED
22798**    SHARED -> (PENDING) -> EXCLUSIVE
22799**    RESERVED -> (PENDING) -> EXCLUSIVE
22800**    PENDING -> EXCLUSIVE
22801**
22802** This routine will only increase a lock.  Use the sqlite3OsUnlock()
22803** routine to lower a locking level.
22804*/
22805static int unixLock(sqlite3_file *id, int locktype){
22806  /* The following describes the implementation of the various locks and
22807  ** lock transitions in terms of the POSIX advisory shared and exclusive
22808  ** lock primitives (called read-locks and write-locks below, to avoid
22809  ** confusion with SQLite lock names). The algorithms are complicated
22810  ** slightly in order to be compatible with windows systems simultaneously
22811  ** accessing the same database file, in case that is ever required.
22812  **
22813  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
22814  ** byte', each single bytes at well known offsets, and the 'shared byte
22815  ** range', a range of 510 bytes at a well known offset.
22816  **
22817  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
22818  ** byte'.  If this is successful, a random byte from the 'shared byte
22819  ** range' is read-locked and the lock on the 'pending byte' released.
22820  **
22821  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
22822  ** A RESERVED lock is implemented by grabbing a write-lock on the
22823  ** 'reserved byte'.
22824  **
22825  ** A process may only obtain a PENDING lock after it has obtained a
22826  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
22827  ** on the 'pending byte'. This ensures that no new SHARED locks can be
22828  ** obtained, but existing SHARED locks are allowed to persist. A process
22829  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
22830  ** This property is used by the algorithm for rolling back a journal file
22831  ** after a crash.
22832  **
22833  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
22834  ** implemented by obtaining a write-lock on the entire 'shared byte
22835  ** range'. Since all other locks require a read-lock on one of the bytes
22836  ** within this range, this ensures that no other locks are held on the
22837  ** database.
22838  **
22839  ** The reason a single byte cannot be used instead of the 'shared byte
22840  ** range' is that some versions of windows do not support read-locks. By
22841  ** locking a random byte from a range, concurrent SHARED locks may exist
22842  ** even if the locking primitive used is always a write-lock.
22843  */
22844  int rc = SQLITE_OK;
22845  unixFile *pFile = (unixFile*)id;
22846  struct unixLockInfo *pLock = pFile->pLock;
22847  struct flock lock;
22848  int s = 0;
22849  int tErrno;
22850
22851  assert( pFile );
22852  OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
22853      locktypeName(locktype), locktypeName(pFile->locktype),
22854      locktypeName(pLock->locktype), pLock->cnt , getpid());
22855
22856  /* If there is already a lock of this type or more restrictive on the
22857  ** unixFile, do nothing. Don't use the end_lock: exit path, as
22858  ** unixEnterMutex() hasn't been called yet.
22859  */
22860  if( pFile->locktype>=locktype ){
22861    OSTRACE3("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
22862            locktypeName(locktype));
22863    return SQLITE_OK;
22864  }
22865
22866  /* Make sure the locking sequence is correct.
22867  **  (1) We never move from unlocked to anything higher than shared lock.
22868  **  (2) SQLite never explicitly requests a pendig lock.
22869  **  (3) A shared lock is always held when a reserve lock is requested.
22870  */
22871  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22872  assert( locktype!=PENDING_LOCK );
22873  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22874
22875  /* This mutex is needed because pFile->pLock is shared across threads
22876  */
22877  unixEnterMutex();
22878
22879  /* Make sure the current thread owns the pFile.
22880  */
22881  rc = transferOwnership(pFile);
22882  if( rc!=SQLITE_OK ){
22883    unixLeaveMutex();
22884    return rc;
22885  }
22886  pLock = pFile->pLock;
22887
22888  /* If some thread using this PID has a lock via a different unixFile*
22889  ** handle that precludes the requested lock, return BUSY.
22890  */
22891  if( (pFile->locktype!=pLock->locktype &&
22892          (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
22893  ){
22894    rc = SQLITE_BUSY;
22895    goto end_lock;
22896  }
22897
22898  /* If a SHARED lock is requested, and some thread using this PID already
22899  ** has a SHARED or RESERVED lock, then increment reference counts and
22900  ** return SQLITE_OK.
22901  */
22902  if( locktype==SHARED_LOCK &&
22903      (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
22904    assert( locktype==SHARED_LOCK );
22905    assert( pFile->locktype==0 );
22906    assert( pLock->cnt>0 );
22907    pFile->locktype = SHARED_LOCK;
22908    pLock->cnt++;
22909    pFile->pOpen->nLock++;
22910    goto end_lock;
22911  }
22912
22913
22914  /* A PENDING lock is needed before acquiring a SHARED lock and before
22915  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
22916  ** be released.
22917  */
22918  lock.l_len = 1L;
22919  lock.l_whence = SEEK_SET;
22920  if( locktype==SHARED_LOCK
22921      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
22922  ){
22923    lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
22924    lock.l_start = PENDING_BYTE;
22925    s = fcntl(pFile->h, F_SETLK, &lock);
22926    if( s==(-1) ){
22927      tErrno = errno;
22928      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
22929      if( IS_LOCK_ERROR(rc) ){
22930        pFile->lastErrno = tErrno;
22931      }
22932      goto end_lock;
22933    }
22934  }
22935
22936
22937  /* If control gets to this point, then actually go ahead and make
22938  ** operating system calls for the specified lock.
22939  */
22940  if( locktype==SHARED_LOCK ){
22941    assert( pLock->cnt==0 );
22942    assert( pLock->locktype==0 );
22943
22944    /* Now get the read-lock */
22945    s = rangeLock(pFile, F_RDLCK, &tErrno);
22946
22947    /* Drop the temporary PENDING lock */
22948    lock.l_start = PENDING_BYTE;
22949    lock.l_len = 1L;
22950    lock.l_type = F_UNLCK;
22951    if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
22952      if( s != -1 ){
22953        /* This could happen with a network mount */
22954        tErrno = errno;
22955        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
22956        if( IS_LOCK_ERROR(rc) ){
22957          pFile->lastErrno = tErrno;
22958        }
22959        goto end_lock;
22960      }
22961    }
22962    if( s==(-1) ){
22963      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
22964      if( IS_LOCK_ERROR(rc) ){
22965        pFile->lastErrno = tErrno;
22966      }
22967    }else{
22968      pFile->locktype = SHARED_LOCK;
22969      pFile->pOpen->nLock++;
22970      pLock->cnt = 1;
22971    }
22972  }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
22973    /* We are trying for an exclusive lock but another thread in this
22974    ** same process is still holding a shared lock. */
22975    rc = SQLITE_BUSY;
22976  }else{
22977    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
22978    ** assumed that there is a SHARED or greater lock on the file
22979    ** already.
22980    */
22981    assert( 0!=pFile->locktype );
22982    lock.l_type = F_WRLCK;
22983    switch( locktype ){
22984      case RESERVED_LOCK:
22985        lock.l_start = RESERVED_BYTE;
22986        s = fcntl(pFile->h, F_SETLK, &lock);
22987        tErrno = errno;
22988        break;
22989      case EXCLUSIVE_LOCK:
22990        s = rangeLock(pFile, F_WRLCK, &tErrno);
22991        break;
22992      default:
22993        assert(0);
22994    }
22995    if( s==(-1) ){
22996      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
22997      if( IS_LOCK_ERROR(rc) ){
22998        pFile->lastErrno = tErrno;
22999      }
23000    }
23001  }
23002
23003
23004#ifndef NDEBUG
23005  /* Set up the transaction-counter change checking flags when
23006  ** transitioning from a SHARED to a RESERVED lock.  The change
23007  ** from SHARED to RESERVED marks the beginning of a normal
23008  ** write operation (not a hot journal rollback).
23009  */
23010  if( rc==SQLITE_OK
23011   && pFile->locktype<=SHARED_LOCK
23012   && locktype==RESERVED_LOCK
23013  ){
23014    pFile->transCntrChng = 0;
23015    pFile->dbUpdate = 0;
23016    pFile->inNormalWrite = 1;
23017  }
23018#endif
23019
23020
23021  if( rc==SQLITE_OK ){
23022    pFile->locktype = locktype;
23023    pLock->locktype = locktype;
23024  }else if( locktype==EXCLUSIVE_LOCK ){
23025    pFile->locktype = PENDING_LOCK;
23026    pLock->locktype = PENDING_LOCK;
23027  }
23028
23029end_lock:
23030  unixLeaveMutex();
23031  OSTRACE4("LOCK    %d %s %s (unix)\n", pFile->h, locktypeName(locktype),
23032      rc==SQLITE_OK ? "ok" : "failed");
23033  return rc;
23034}
23035
23036/*
23037** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
23038** If all such file descriptors are closed without error, the list is
23039** cleared and SQLITE_OK returned.
23040**
23041** Otherwise, if an error occurs, then successfully closed file descriptor
23042** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
23043** not deleted and SQLITE_IOERR_CLOSE returned.
23044*/
23045static int closePendingFds(unixFile *pFile){
23046  int rc = SQLITE_OK;
23047  struct unixOpenCnt *pOpen = pFile->pOpen;
23048  UnixUnusedFd *pError = 0;
23049  UnixUnusedFd *p;
23050  UnixUnusedFd *pNext;
23051  for(p=pOpen->pUnused; p; p=pNext){
23052    pNext = p->pNext;
23053    if( close(p->fd) ){
23054      pFile->lastErrno = errno;
23055      rc = SQLITE_IOERR_CLOSE;
23056      p->pNext = pError;
23057      pError = p;
23058    }else{
23059      sqlite3_free(p);
23060    }
23061  }
23062  pOpen->pUnused = pError;
23063  return rc;
23064}
23065
23066/*
23067** Add the file descriptor used by file handle pFile to the corresponding
23068** pUnused list.
23069*/
23070static void setPendingFd(unixFile *pFile){
23071  struct unixOpenCnt *pOpen = pFile->pOpen;
23072  UnixUnusedFd *p = pFile->pUnused;
23073  p->pNext = pOpen->pUnused;
23074  pOpen->pUnused = p;
23075  pFile->h = -1;
23076  pFile->pUnused = 0;
23077}
23078
23079/*
23080** Lower the locking level on file descriptor pFile to locktype.  locktype
23081** must be either NO_LOCK or SHARED_LOCK.
23082**
23083** If the locking level of the file descriptor is already at or below
23084** the requested locking level, this routine is a no-op.
23085*/
23086static int unixUnlock(sqlite3_file *id, int locktype){
23087  unixFile *pFile = (unixFile*)id; /* The open file */
23088  struct unixLockInfo *pLock;      /* Structure describing current lock state */
23089  struct flock lock;               /* Information passed into fcntl() */
23090  int rc = SQLITE_OK;              /* Return code from this interface */
23091  int h;                           /* The underlying file descriptor */
23092  int tErrno;                      /* Error code from system call errors */
23093
23094  assert( pFile );
23095  OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, locktype,
23096      pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
23097
23098  assert( locktype<=SHARED_LOCK );
23099  if( pFile->locktype<=locktype ){
23100    return SQLITE_OK;
23101  }
23102  if( CHECK_THREADID(pFile) ){
23103    return SQLITE_MISUSE;
23104  }
23105  unixEnterMutex();
23106  h = pFile->h;
23107  pLock = pFile->pLock;
23108  assert( pLock->cnt!=0 );
23109  if( pFile->locktype>SHARED_LOCK ){
23110    assert( pLock->locktype==pFile->locktype );
23111    SimulateIOErrorBenign(1);
23112    SimulateIOError( h=(-1) )
23113    SimulateIOErrorBenign(0);
23114
23115#ifndef NDEBUG
23116    /* When reducing a lock such that other processes can start
23117    ** reading the database file again, make sure that the
23118    ** transaction counter was updated if any part of the database
23119    ** file changed.  If the transaction counter is not updated,
23120    ** other connections to the same file might not realize that
23121    ** the file has changed and hence might not know to flush their
23122    ** cache.  The use of a stale cache can lead to database corruption.
23123    */
23124    assert( pFile->inNormalWrite==0
23125         || pFile->dbUpdate==0
23126         || pFile->transCntrChng==1 );
23127    pFile->inNormalWrite = 0;
23128#endif
23129
23130
23131    if( locktype==SHARED_LOCK ){
23132      if( rangeLock(pFile, F_RDLCK, &tErrno)==(-1) ){
23133        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23134        if( IS_LOCK_ERROR(rc) ){
23135          pFile->lastErrno = tErrno;
23136        }
23137        goto end_unlock;
23138      }
23139    }
23140    lock.l_type = F_UNLCK;
23141    lock.l_whence = SEEK_SET;
23142    lock.l_start = PENDING_BYTE;
23143    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
23144    if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23145      pLock->locktype = SHARED_LOCK;
23146    }else{
23147      tErrno = errno;
23148      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23149      if( IS_LOCK_ERROR(rc) ){
23150        pFile->lastErrno = tErrno;
23151      }
23152      goto end_unlock;
23153    }
23154  }
23155  if( locktype==NO_LOCK ){
23156    struct unixOpenCnt *pOpen;
23157
23158    /* Decrement the shared lock counter.  Release the lock using an
23159    ** OS call only when all threads in this same process have released
23160    ** the lock.
23161    */
23162    pLock->cnt--;
23163    if( pLock->cnt==0 ){
23164      lock.l_type = F_UNLCK;
23165      lock.l_whence = SEEK_SET;
23166      lock.l_start = lock.l_len = 0L;
23167      SimulateIOErrorBenign(1);
23168      SimulateIOError( h=(-1) )
23169      SimulateIOErrorBenign(0);
23170      if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23171        pLock->locktype = NO_LOCK;
23172      }else{
23173        tErrno = errno;
23174        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23175        if( IS_LOCK_ERROR(rc) ){
23176          pFile->lastErrno = tErrno;
23177        }
23178        pLock->locktype = NO_LOCK;
23179        pFile->locktype = NO_LOCK;
23180      }
23181    }
23182
23183    /* Decrement the count of locks against this same file.  When the
23184    ** count reaches zero, close any other file descriptors whose close
23185    ** was deferred because of outstanding locks.
23186    */
23187    pOpen = pFile->pOpen;
23188    pOpen->nLock--;
23189    assert( pOpen->nLock>=0 );
23190    if( pOpen->nLock==0 ){
23191      int rc2 = closePendingFds(pFile);
23192      if( rc==SQLITE_OK ){
23193        rc = rc2;
23194      }
23195    }
23196  }
23197
23198end_unlock:
23199  unixLeaveMutex();
23200  if( rc==SQLITE_OK ) pFile->locktype = locktype;
23201  return rc;
23202}
23203
23204/*
23205** This function performs the parts of the "close file" operation
23206** common to all locking schemes. It closes the directory and file
23207** handles, if they are valid, and sets all fields of the unixFile
23208** structure to 0.
23209**
23210** It is *not* necessary to hold the mutex when this routine is called,
23211** even on VxWorks.  A mutex will be acquired on VxWorks by the
23212** vxworksReleaseFileId() routine.
23213*/
23214static int closeUnixFile(sqlite3_file *id){
23215  unixFile *pFile = (unixFile*)id;
23216  if( pFile ){
23217    if( pFile->dirfd>=0 ){
23218      int err = close(pFile->dirfd);
23219      if( err ){
23220        pFile->lastErrno = errno;
23221        return SQLITE_IOERR_DIR_CLOSE;
23222      }else{
23223        pFile->dirfd=-1;
23224      }
23225    }
23226    if( pFile->h>=0 ){
23227      int err = close(pFile->h);
23228      if( err ){
23229        pFile->lastErrno = errno;
23230        return SQLITE_IOERR_CLOSE;
23231      }
23232    }
23233#if OS_VXWORKS
23234    if( pFile->pId ){
23235      if( pFile->isDelete ){
23236        unlink(pFile->pId->zCanonicalName);
23237      }
23238      vxworksReleaseFileId(pFile->pId);
23239      pFile->pId = 0;
23240    }
23241#endif
23242    OSTRACE2("CLOSE   %-3d\n", pFile->h);
23243    OpenCounter(-1);
23244    sqlite3_free(pFile->pUnused);
23245    memset(pFile, 0, sizeof(unixFile));
23246  }
23247  return SQLITE_OK;
23248}
23249
23250/*
23251** Close a file.
23252*/
23253static int unixClose(sqlite3_file *id){
23254  int rc = SQLITE_OK;
23255  if( id ){
23256    unixFile *pFile = (unixFile *)id;
23257    unixUnlock(id, NO_LOCK);
23258    unixEnterMutex();
23259    if( pFile->pOpen && pFile->pOpen->nLock ){
23260      /* If there are outstanding locks, do not actually close the file just
23261      ** yet because that would clear those locks.  Instead, add the file
23262      ** descriptor to pOpen->pUnused list.  It will be automatically closed
23263      ** when the last lock is cleared.
23264      */
23265      setPendingFd(pFile);
23266    }
23267    releaseLockInfo(pFile->pLock);
23268    releaseOpenCnt(pFile->pOpen);
23269    rc = closeUnixFile(id);
23270    unixLeaveMutex();
23271  }
23272  return rc;
23273}
23274
23275/************** End of the posix advisory lock implementation *****************
23276******************************************************************************/
23277
23278/******************************************************************************
23279****************************** No-op Locking **********************************
23280**
23281** Of the various locking implementations available, this is by far the
23282** simplest:  locking is ignored.  No attempt is made to lock the database
23283** file for reading or writing.
23284**
23285** This locking mode is appropriate for use on read-only databases
23286** (ex: databases that are burned into CD-ROM, for example.)  It can
23287** also be used if the application employs some external mechanism to
23288** prevent simultaneous access of the same database by two or more
23289** database connections.  But there is a serious risk of database
23290** corruption if this locking mode is used in situations where multiple
23291** database connections are accessing the same database file at the same
23292** time and one or more of those connections are writing.
23293*/
23294
23295static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
23296  UNUSED_PARAMETER(NotUsed);
23297  *pResOut = 0;
23298  return SQLITE_OK;
23299}
23300static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
23301  UNUSED_PARAMETER2(NotUsed, NotUsed2);
23302  return SQLITE_OK;
23303}
23304static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
23305  UNUSED_PARAMETER2(NotUsed, NotUsed2);
23306  return SQLITE_OK;
23307}
23308
23309/*
23310** Close the file.
23311*/
23312static int nolockClose(sqlite3_file *id) {
23313  return closeUnixFile(id);
23314}
23315
23316/******************* End of the no-op lock implementation *********************
23317******************************************************************************/
23318
23319/******************************************************************************
23320************************* Begin dot-file Locking ******************************
23321**
23322** The dotfile locking implementation uses the existance of separate lock
23323** files in order to control access to the database.  This works on just
23324** about every filesystem imaginable.  But there are serious downsides:
23325**
23326**    (1)  There is zero concurrency.  A single reader blocks all other
23327**         connections from reading or writing the database.
23328**
23329**    (2)  An application crash or power loss can leave stale lock files
23330**         sitting around that need to be cleared manually.
23331**
23332** Nevertheless, a dotlock is an appropriate locking mode for use if no
23333** other locking strategy is available.
23334**
23335** Dotfile locking works by creating a file in the same directory as the
23336** database and with the same name but with a ".lock" extension added.
23337** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
23338** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
23339*/
23340
23341/*
23342** The file suffix added to the data base filename in order to create the
23343** lock file.
23344*/
23345#define DOTLOCK_SUFFIX ".lock"
23346
23347/*
23348** This routine checks if there is a RESERVED lock held on the specified
23349** file by this or any other process. If such a lock is held, set *pResOut
23350** to a non-zero value otherwise *pResOut is set to zero.  The return value
23351** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23352**
23353** In dotfile locking, either a lock exists or it does not.  So in this
23354** variation of CheckReservedLock(), *pResOut is set to true if any lock
23355** is held on the file and false if the file is unlocked.
23356*/
23357static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
23358  int rc = SQLITE_OK;
23359  int reserved = 0;
23360  unixFile *pFile = (unixFile*)id;
23361
23362  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23363
23364  assert( pFile );
23365
23366  /* Check if a thread in this process holds such a lock */
23367  if( pFile->locktype>SHARED_LOCK ){
23368    /* Either this connection or some other connection in the same process
23369    ** holds a lock on the file.  No need to check further. */
23370    reserved = 1;
23371  }else{
23372    /* The lock is held if and only if the lockfile exists */
23373    const char *zLockFile = (const char*)pFile->lockingContext;
23374    reserved = access(zLockFile, 0)==0;
23375  }
23376  OSTRACE4("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved);
23377  *pResOut = reserved;
23378  return rc;
23379}
23380
23381/*
23382** Lock the file with the lock specified by parameter locktype - one
23383** of the following:
23384**
23385**     (1) SHARED_LOCK
23386**     (2) RESERVED_LOCK
23387**     (3) PENDING_LOCK
23388**     (4) EXCLUSIVE_LOCK
23389**
23390** Sometimes when requesting one lock state, additional lock states
23391** are inserted in between.  The locking might fail on one of the later
23392** transitions leaving the lock state different from what it started but
23393** still short of its goal.  The following chart shows the allowed
23394** transitions and the inserted intermediate states:
23395**
23396**    UNLOCKED -> SHARED
23397**    SHARED -> RESERVED
23398**    SHARED -> (PENDING) -> EXCLUSIVE
23399**    RESERVED -> (PENDING) -> EXCLUSIVE
23400**    PENDING -> EXCLUSIVE
23401**
23402** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23403** routine to lower a locking level.
23404**
23405** With dotfile locking, we really only support state (4): EXCLUSIVE.
23406** But we track the other locking levels internally.
23407*/
23408static int dotlockLock(sqlite3_file *id, int locktype) {
23409  unixFile *pFile = (unixFile*)id;
23410  int fd;
23411  char *zLockFile = (char *)pFile->lockingContext;
23412  int rc = SQLITE_OK;
23413
23414
23415  /* If we have any lock, then the lock file already exists.  All we have
23416  ** to do is adjust our internal record of the lock level.
23417  */
23418  if( pFile->locktype > NO_LOCK ){
23419    pFile->locktype = locktype;
23420#if !OS_VXWORKS
23421    /* Always update the timestamp on the old file */
23422    utimes(zLockFile, NULL);
23423#endif
23424    return SQLITE_OK;
23425  }
23426
23427  /* grab an exclusive lock */
23428  fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
23429  if( fd<0 ){
23430    /* failed to open/create the file, someone else may have stolen the lock */
23431    int tErrno = errno;
23432    if( EEXIST == tErrno ){
23433      rc = SQLITE_BUSY;
23434    } else {
23435      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23436      if( IS_LOCK_ERROR(rc) ){
23437        pFile->lastErrno = tErrno;
23438      }
23439    }
23440    return rc;
23441  }
23442  if( close(fd) ){
23443    pFile->lastErrno = errno;
23444    rc = SQLITE_IOERR_CLOSE;
23445  }
23446
23447  /* got it, set the type and return ok */
23448  pFile->locktype = locktype;
23449  return rc;
23450}
23451
23452/*
23453** Lower the locking level on file descriptor pFile to locktype.  locktype
23454** must be either NO_LOCK or SHARED_LOCK.
23455**
23456** If the locking level of the file descriptor is already at or below
23457** the requested locking level, this routine is a no-op.
23458**
23459** When the locking level reaches NO_LOCK, delete the lock file.
23460*/
23461static int dotlockUnlock(sqlite3_file *id, int locktype) {
23462  unixFile *pFile = (unixFile*)id;
23463  char *zLockFile = (char *)pFile->lockingContext;
23464
23465  assert( pFile );
23466  OSTRACE5("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, locktype,
23467	   pFile->locktype, getpid());
23468  assert( locktype<=SHARED_LOCK );
23469
23470  /* no-op if possible */
23471  if( pFile->locktype==locktype ){
23472    return SQLITE_OK;
23473  }
23474
23475  /* To downgrade to shared, simply update our internal notion of the
23476  ** lock state.  No need to mess with the file on disk.
23477  */
23478  if( locktype==SHARED_LOCK ){
23479    pFile->locktype = SHARED_LOCK;
23480    return SQLITE_OK;
23481  }
23482
23483  /* To fully unlock the database, delete the lock file */
23484  assert( locktype==NO_LOCK );
23485  if( unlink(zLockFile) ){
23486    int rc = 0;
23487    int tErrno = errno;
23488    if( ENOENT != tErrno ){
23489      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23490    }
23491    if( IS_LOCK_ERROR(rc) ){
23492      pFile->lastErrno = tErrno;
23493    }
23494    return rc;
23495  }
23496  pFile->locktype = NO_LOCK;
23497  return SQLITE_OK;
23498}
23499
23500/*
23501** Close a file.  Make sure the lock has been released before closing.
23502*/
23503static int dotlockClose(sqlite3_file *id) {
23504  int rc;
23505  if( id ){
23506    unixFile *pFile = (unixFile*)id;
23507    dotlockUnlock(id, NO_LOCK);
23508    sqlite3_free(pFile->lockingContext);
23509  }
23510  rc = closeUnixFile(id);
23511  return rc;
23512}
23513/****************** End of the dot-file lock implementation *******************
23514******************************************************************************/
23515
23516/******************************************************************************
23517************************** Begin flock Locking ********************************
23518**
23519** Use the flock() system call to do file locking.
23520**
23521** flock() locking is like dot-file locking in that the various
23522** fine-grain locking levels supported by SQLite are collapsed into
23523** a single exclusive lock.  In other words, SHARED, RESERVED, and
23524** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
23525** still works when you do this, but concurrency is reduced since
23526** only a single process can be reading the database at a time.
23527**
23528** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
23529** compiling for VXWORKS.
23530*/
23531#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
23532
23533/*
23534** This routine checks if there is a RESERVED lock held on the specified
23535** file by this or any other process. If such a lock is held, set *pResOut
23536** to a non-zero value otherwise *pResOut is set to zero.  The return value
23537** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23538*/
23539static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
23540  int rc = SQLITE_OK;
23541  int reserved = 0;
23542  unixFile *pFile = (unixFile*)id;
23543
23544  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23545
23546  assert( pFile );
23547
23548  /* Check if a thread in this process holds such a lock */
23549  if( pFile->locktype>SHARED_LOCK ){
23550    reserved = 1;
23551  }
23552
23553  /* Otherwise see if some other process holds it. */
23554  if( !reserved ){
23555    /* attempt to get the lock */
23556    int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
23557    if( !lrc ){
23558      /* got the lock, unlock it */
23559      lrc = flock(pFile->h, LOCK_UN);
23560      if ( lrc ) {
23561        int tErrno = errno;
23562        /* unlock failed with an error */
23563        lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23564        if( IS_LOCK_ERROR(lrc) ){
23565          pFile->lastErrno = tErrno;
23566          rc = lrc;
23567        }
23568      }
23569    } else {
23570      int tErrno = errno;
23571      reserved = 1;
23572      /* someone else might have it reserved */
23573      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23574      if( IS_LOCK_ERROR(lrc) ){
23575        pFile->lastErrno = tErrno;
23576        rc = lrc;
23577      }
23578    }
23579  }
23580  OSTRACE4("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved);
23581
23582#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
23583  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
23584    rc = SQLITE_OK;
23585    reserved=1;
23586  }
23587#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
23588  *pResOut = reserved;
23589  return rc;
23590}
23591
23592/*
23593** Lock the file with the lock specified by parameter locktype - one
23594** of the following:
23595**
23596**     (1) SHARED_LOCK
23597**     (2) RESERVED_LOCK
23598**     (3) PENDING_LOCK
23599**     (4) EXCLUSIVE_LOCK
23600**
23601** Sometimes when requesting one lock state, additional lock states
23602** are inserted in between.  The locking might fail on one of the later
23603** transitions leaving the lock state different from what it started but
23604** still short of its goal.  The following chart shows the allowed
23605** transitions and the inserted intermediate states:
23606**
23607**    UNLOCKED -> SHARED
23608**    SHARED -> RESERVED
23609**    SHARED -> (PENDING) -> EXCLUSIVE
23610**    RESERVED -> (PENDING) -> EXCLUSIVE
23611**    PENDING -> EXCLUSIVE
23612**
23613** flock() only really support EXCLUSIVE locks.  We track intermediate
23614** lock states in the sqlite3_file structure, but all locks SHARED or
23615** above are really EXCLUSIVE locks and exclude all other processes from
23616** access the file.
23617**
23618** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23619** routine to lower a locking level.
23620*/
23621static int flockLock(sqlite3_file *id, int locktype) {
23622  int rc = SQLITE_OK;
23623  unixFile *pFile = (unixFile*)id;
23624
23625  assert( pFile );
23626
23627  /* if we already have a lock, it is exclusive.
23628  ** Just adjust level and punt on outta here. */
23629  if (pFile->locktype > NO_LOCK) {
23630    pFile->locktype = locktype;
23631    return SQLITE_OK;
23632  }
23633
23634  /* grab an exclusive lock */
23635
23636  if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
23637    int tErrno = errno;
23638    /* didn't get, must be busy */
23639    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23640    if( IS_LOCK_ERROR(rc) ){
23641      pFile->lastErrno = tErrno;
23642    }
23643  } else {
23644    /* got it, set the type and return ok */
23645    pFile->locktype = locktype;
23646  }
23647  OSTRACE4("LOCK    %d %s %s (flock)\n", pFile->h, locktypeName(locktype),
23648           rc==SQLITE_OK ? "ok" : "failed");
23649#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
23650  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
23651    rc = SQLITE_BUSY;
23652  }
23653#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
23654  return rc;
23655}
23656
23657
23658/*
23659** Lower the locking level on file descriptor pFile to locktype.  locktype
23660** must be either NO_LOCK or SHARED_LOCK.
23661**
23662** If the locking level of the file descriptor is already at or below
23663** the requested locking level, this routine is a no-op.
23664*/
23665static int flockUnlock(sqlite3_file *id, int locktype) {
23666  unixFile *pFile = (unixFile*)id;
23667
23668  assert( pFile );
23669  OSTRACE5("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, locktype,
23670           pFile->locktype, getpid());
23671  assert( locktype<=SHARED_LOCK );
23672
23673  /* no-op if possible */
23674  if( pFile->locktype==locktype ){
23675    return SQLITE_OK;
23676  }
23677
23678  /* shared can just be set because we always have an exclusive */
23679  if (locktype==SHARED_LOCK) {
23680    pFile->locktype = locktype;
23681    return SQLITE_OK;
23682  }
23683
23684  /* no, really, unlock. */
23685  int rc = flock(pFile->h, LOCK_UN);
23686  if (rc) {
23687    int r, tErrno = errno;
23688    r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23689    if( IS_LOCK_ERROR(r) ){
23690      pFile->lastErrno = tErrno;
23691    }
23692#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
23693    if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
23694      r = SQLITE_BUSY;
23695    }
23696#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
23697
23698    return r;
23699  } else {
23700    pFile->locktype = NO_LOCK;
23701    return SQLITE_OK;
23702  }
23703}
23704
23705/*
23706** Close a file.
23707*/
23708static int flockClose(sqlite3_file *id) {
23709  if( id ){
23710    flockUnlock(id, NO_LOCK);
23711  }
23712  return closeUnixFile(id);
23713}
23714
23715#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
23716
23717/******************* End of the flock lock implementation *********************
23718******************************************************************************/
23719
23720/******************************************************************************
23721************************ Begin Named Semaphore Locking ************************
23722**
23723** Named semaphore locking is only supported on VxWorks.
23724**
23725** Semaphore locking is like dot-lock and flock in that it really only
23726** supports EXCLUSIVE locking.  Only a single process can read or write
23727** the database file at a time.  This reduces potential concurrency, but
23728** makes the lock implementation much easier.
23729*/
23730#if OS_VXWORKS
23731
23732/*
23733** This routine checks if there is a RESERVED lock held on the specified
23734** file by this or any other process. If such a lock is held, set *pResOut
23735** to a non-zero value otherwise *pResOut is set to zero.  The return value
23736** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23737*/
23738static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
23739  int rc = SQLITE_OK;
23740  int reserved = 0;
23741  unixFile *pFile = (unixFile*)id;
23742
23743  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23744
23745  assert( pFile );
23746
23747  /* Check if a thread in this process holds such a lock */
23748  if( pFile->locktype>SHARED_LOCK ){
23749    reserved = 1;
23750  }
23751
23752  /* Otherwise see if some other process holds it. */
23753  if( !reserved ){
23754    sem_t *pSem = pFile->pOpen->pSem;
23755    struct stat statBuf;
23756
23757    if( sem_trywait(pSem)==-1 ){
23758      int tErrno = errno;
23759      if( EAGAIN != tErrno ){
23760        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23761        pFile->lastErrno = tErrno;
23762      } else {
23763        /* someone else has the lock when we are in NO_LOCK */
23764        reserved = (pFile->locktype < SHARED_LOCK);
23765      }
23766    }else{
23767      /* we could have it if we want it */
23768      sem_post(pSem);
23769    }
23770  }
23771  OSTRACE4("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved);
23772
23773  *pResOut = reserved;
23774  return rc;
23775}
23776
23777/*
23778** Lock the file with the lock specified by parameter locktype - one
23779** of the following:
23780**
23781**     (1) SHARED_LOCK
23782**     (2) RESERVED_LOCK
23783**     (3) PENDING_LOCK
23784**     (4) EXCLUSIVE_LOCK
23785**
23786** Sometimes when requesting one lock state, additional lock states
23787** are inserted in between.  The locking might fail on one of the later
23788** transitions leaving the lock state different from what it started but
23789** still short of its goal.  The following chart shows the allowed
23790** transitions and the inserted intermediate states:
23791**
23792**    UNLOCKED -> SHARED
23793**    SHARED -> RESERVED
23794**    SHARED -> (PENDING) -> EXCLUSIVE
23795**    RESERVED -> (PENDING) -> EXCLUSIVE
23796**    PENDING -> EXCLUSIVE
23797**
23798** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
23799** lock states in the sqlite3_file structure, but all locks SHARED or
23800** above are really EXCLUSIVE locks and exclude all other processes from
23801** access the file.
23802**
23803** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23804** routine to lower a locking level.
23805*/
23806static int semLock(sqlite3_file *id, int locktype) {
23807  unixFile *pFile = (unixFile*)id;
23808  int fd;
23809  sem_t *pSem = pFile->pOpen->pSem;
23810  int rc = SQLITE_OK;
23811
23812  /* if we already have a lock, it is exclusive.
23813  ** Just adjust level and punt on outta here. */
23814  if (pFile->locktype > NO_LOCK) {
23815    pFile->locktype = locktype;
23816    rc = SQLITE_OK;
23817    goto sem_end_lock;
23818  }
23819
23820  /* lock semaphore now but bail out when already locked. */
23821  if( sem_trywait(pSem)==-1 ){
23822    rc = SQLITE_BUSY;
23823    goto sem_end_lock;
23824  }
23825
23826  /* got it, set the type and return ok */
23827  pFile->locktype = locktype;
23828
23829 sem_end_lock:
23830  return rc;
23831}
23832
23833/*
23834** Lower the locking level on file descriptor pFile to locktype.  locktype
23835** must be either NO_LOCK or SHARED_LOCK.
23836**
23837** If the locking level of the file descriptor is already at or below
23838** the requested locking level, this routine is a no-op.
23839*/
23840static int semUnlock(sqlite3_file *id, int locktype) {
23841  unixFile *pFile = (unixFile*)id;
23842  sem_t *pSem = pFile->pOpen->pSem;
23843
23844  assert( pFile );
23845  assert( pSem );
23846  OSTRACE5("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, locktype,
23847	   pFile->locktype, getpid());
23848  assert( locktype<=SHARED_LOCK );
23849
23850  /* no-op if possible */
23851  if( pFile->locktype==locktype ){
23852    return SQLITE_OK;
23853  }
23854
23855  /* shared can just be set because we always have an exclusive */
23856  if (locktype==SHARED_LOCK) {
23857    pFile->locktype = locktype;
23858    return SQLITE_OK;
23859  }
23860
23861  /* no, really unlock. */
23862  if ( sem_post(pSem)==-1 ) {
23863    int rc, tErrno = errno;
23864    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23865    if( IS_LOCK_ERROR(rc) ){
23866      pFile->lastErrno = tErrno;
23867    }
23868    return rc;
23869  }
23870  pFile->locktype = NO_LOCK;
23871  return SQLITE_OK;
23872}
23873
23874/*
23875 ** Close a file.
23876 */
23877static int semClose(sqlite3_file *id) {
23878  if( id ){
23879    unixFile *pFile = (unixFile*)id;
23880    semUnlock(id, NO_LOCK);
23881    assert( pFile );
23882    unixEnterMutex();
23883    releaseLockInfo(pFile->pLock);
23884    releaseOpenCnt(pFile->pOpen);
23885    unixLeaveMutex();
23886    closeUnixFile(id);
23887  }
23888  return SQLITE_OK;
23889}
23890
23891#endif /* OS_VXWORKS */
23892/*
23893** Named semaphore locking is only available on VxWorks.
23894**
23895*************** End of the named semaphore lock implementation ****************
23896******************************************************************************/
23897
23898
23899/******************************************************************************
23900*************************** Begin AFP Locking *********************************
23901**
23902** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
23903** on Apple Macintosh computers - both OS9 and OSX.
23904**
23905** Third-party implementations of AFP are available.  But this code here
23906** only works on OSX.
23907*/
23908
23909#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
23910/*
23911** The afpLockingContext structure contains all afp lock specific state
23912*/
23913typedef struct afpLockingContext afpLockingContext;
23914struct afpLockingContext {
23915  unsigned long long sharedByte;
23916  const char *dbPath;             /* Name of the open file */
23917};
23918
23919struct ByteRangeLockPB2
23920{
23921  unsigned long long offset;        /* offset to first byte to lock */
23922  unsigned long long length;        /* nbr of bytes to lock */
23923  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
23924  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
23925  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
23926  int fd;                           /* file desc to assoc this lock with */
23927};
23928
23929#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
23930
23931/*
23932** This is a utility for setting or clearing a bit-range lock on an
23933** AFP filesystem.
23934**
23935** Return SQLITE_OK on success, SQLITE_BUSY on failure.
23936*/
23937static int afpSetLock(
23938  const char *path,              /* Name of the file to be locked or unlocked */
23939  unixFile *pFile,               /* Open file descriptor on path */
23940  unsigned long long offset,     /* First byte to be locked */
23941  unsigned long long length,     /* Number of bytes to lock */
23942  int setLockFlag                /* True to set lock.  False to clear lock */
23943){
23944  struct ByteRangeLockPB2 pb;
23945  int err;
23946
23947  pb.unLockFlag = setLockFlag ? 0 : 1;
23948  pb.startEndFlag = 0;
23949  pb.offset = offset;
23950  pb.length = length;
23951  pb.fd = pFile->h;
23952
23953  OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
23954    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
23955    offset, length);
23956  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
23957  if ( err==-1 ) {
23958    int rc;
23959    int tErrno = errno;
23960    OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
23961             path, tErrno, strerror(tErrno));
23962#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
23963    rc = SQLITE_BUSY;
23964#else
23965    rc = sqliteErrorFromPosixError(tErrno,
23966                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
23967#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
23968    if( IS_LOCK_ERROR(rc) ){
23969      pFile->lastErrno = tErrno;
23970    }
23971    return rc;
23972  } else {
23973    return SQLITE_OK;
23974  }
23975}
23976
23977/*
23978** This routine checks if there is a RESERVED lock held on the specified
23979** file by this or any other process. If such a lock is held, set *pResOut
23980** to a non-zero value otherwise *pResOut is set to zero.  The return value
23981** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23982*/
23983static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
23984  int rc = SQLITE_OK;
23985  int reserved = 0;
23986  unixFile *pFile = (unixFile*)id;
23987
23988  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23989
23990  assert( pFile );
23991  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23992
23993  /* Check if a thread in this process holds such a lock */
23994  if( pFile->locktype>SHARED_LOCK ){
23995    reserved = 1;
23996  }
23997
23998  /* Otherwise see if some other process holds it.
23999   */
24000  if( !reserved ){
24001    /* lock the RESERVED byte */
24002    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
24003    if( SQLITE_OK==lrc ){
24004      /* if we succeeded in taking the reserved lock, unlock it to restore
24005      ** the original state */
24006      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
24007    } else {
24008      /* if we failed to get the lock then someone else must have it */
24009      reserved = 1;
24010    }
24011    if( IS_LOCK_ERROR(lrc) ){
24012      rc=lrc;
24013    }
24014  }
24015
24016  OSTRACE4("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved);
24017
24018  *pResOut = reserved;
24019  return rc;
24020}
24021
24022/*
24023** Lock the file with the lock specified by parameter locktype - one
24024** of the following:
24025**
24026**     (1) SHARED_LOCK
24027**     (2) RESERVED_LOCK
24028**     (3) PENDING_LOCK
24029**     (4) EXCLUSIVE_LOCK
24030**
24031** Sometimes when requesting one lock state, additional lock states
24032** are inserted in between.  The locking might fail on one of the later
24033** transitions leaving the lock state different from what it started but
24034** still short of its goal.  The following chart shows the allowed
24035** transitions and the inserted intermediate states:
24036**
24037**    UNLOCKED -> SHARED
24038**    SHARED -> RESERVED
24039**    SHARED -> (PENDING) -> EXCLUSIVE
24040**    RESERVED -> (PENDING) -> EXCLUSIVE
24041**    PENDING -> EXCLUSIVE
24042**
24043** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24044** routine to lower a locking level.
24045*/
24046static int afpLock(sqlite3_file *id, int locktype){
24047  int rc = SQLITE_OK;
24048  unixFile *pFile = (unixFile*)id;
24049  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24050
24051  assert( pFile );
24052  OSTRACE5("LOCK    %d %s was %s pid=%d (afp)\n", pFile->h,
24053         locktypeName(locktype), locktypeName(pFile->locktype), getpid());
24054
24055  /* If there is already a lock of this type or more restrictive on the
24056  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
24057  ** unixEnterMutex() hasn't been called yet.
24058  */
24059  if( pFile->locktype>=locktype ){
24060    OSTRACE3("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
24061           locktypeName(locktype));
24062    return SQLITE_OK;
24063  }
24064
24065  /* Make sure the locking sequence is correct
24066  */
24067  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
24068  assert( locktype!=PENDING_LOCK );
24069  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
24070
24071  /* This mutex is needed because pFile->pLock is shared across threads
24072  */
24073  unixEnterMutex();
24074
24075  /* Make sure the current thread owns the pFile.
24076  */
24077  rc = transferOwnership(pFile);
24078  if( rc!=SQLITE_OK ){
24079    unixLeaveMutex();
24080    return rc;
24081  }
24082
24083  /* A PENDING lock is needed before acquiring a SHARED lock and before
24084  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24085  ** be released.
24086  */
24087  if( locktype==SHARED_LOCK
24088      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
24089  ){
24090    int failed;
24091    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
24092    if (failed) {
24093      rc = failed;
24094      goto afp_end_lock;
24095    }
24096  }
24097
24098  /* If control gets to this point, then actually go ahead and make
24099  ** operating system calls for the specified lock.
24100  */
24101  if( locktype==SHARED_LOCK ){
24102    int lk, lrc1, lrc2;
24103    int lrc1Errno = 0;
24104
24105    /* Now get the read-lock SHARED_LOCK */
24106    /* note that the quality of the randomness doesn't matter that much */
24107    lk = random();
24108    context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
24109    lrc1 = afpSetLock(context->dbPath, pFile,
24110          SHARED_FIRST+context->sharedByte, 1, 1);
24111    if( IS_LOCK_ERROR(lrc1) ){
24112      lrc1Errno = pFile->lastErrno;
24113    }
24114    /* Drop the temporary PENDING lock */
24115    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
24116
24117    if( IS_LOCK_ERROR(lrc1) ) {
24118      pFile->lastErrno = lrc1Errno;
24119      rc = lrc1;
24120      goto afp_end_lock;
24121    } else if( IS_LOCK_ERROR(lrc2) ){
24122      rc = lrc2;
24123      goto afp_end_lock;
24124    } else if( lrc1 != SQLITE_OK ) {
24125      rc = lrc1;
24126    } else {
24127      pFile->locktype = SHARED_LOCK;
24128      pFile->pOpen->nLock++;
24129    }
24130  }else{
24131    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24132    ** assumed that there is a SHARED or greater lock on the file
24133    ** already.
24134    */
24135    int failed = 0;
24136    assert( 0!=pFile->locktype );
24137    if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
24138        /* Acquire a RESERVED lock */
24139        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
24140    }
24141    if (!failed && locktype == EXCLUSIVE_LOCK) {
24142      /* Acquire an EXCLUSIVE lock */
24143
24144      /* Remove the shared lock before trying the range.  we'll need to
24145      ** reestablish the shared lock if we can't get the  afpUnlock
24146      */
24147      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
24148                         context->sharedByte, 1, 0)) ){
24149        int failed2 = SQLITE_OK;
24150        /* now attemmpt to get the exclusive lock range */
24151        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
24152                               SHARED_SIZE, 1);
24153        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
24154                       SHARED_FIRST + context->sharedByte, 1, 1)) ){
24155          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
24156          ** a critical I/O error
24157          */
24158          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
24159               SQLITE_IOERR_LOCK;
24160          goto afp_end_lock;
24161        }
24162      }else{
24163        rc = failed;
24164      }
24165    }
24166    if( failed ){
24167      rc = failed;
24168    }
24169  }
24170
24171  if( rc==SQLITE_OK ){
24172    pFile->locktype = locktype;
24173  }else if( locktype==EXCLUSIVE_LOCK ){
24174    pFile->locktype = PENDING_LOCK;
24175  }
24176
24177afp_end_lock:
24178  unixLeaveMutex();
24179  OSTRACE4("LOCK    %d %s %s (afp)\n", pFile->h, locktypeName(locktype),
24180         rc==SQLITE_OK ? "ok" : "failed");
24181  return rc;
24182}
24183
24184/*
24185** Lower the locking level on file descriptor pFile to locktype.  locktype
24186** must be either NO_LOCK or SHARED_LOCK.
24187**
24188** If the locking level of the file descriptor is already at or below
24189** the requested locking level, this routine is a no-op.
24190*/
24191static int afpUnlock(sqlite3_file *id, int locktype) {
24192  int rc = SQLITE_OK;
24193  unixFile *pFile = (unixFile*)id;
24194  afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
24195
24196  assert( pFile );
24197  OSTRACE5("UNLOCK  %d %d was %d pid=%d (afp)\n", pFile->h, locktype,
24198         pFile->locktype, getpid());
24199
24200  assert( locktype<=SHARED_LOCK );
24201  if( pFile->locktype<=locktype ){
24202    return SQLITE_OK;
24203  }
24204  if( CHECK_THREADID(pFile) ){
24205    return SQLITE_MISUSE;
24206  }
24207  unixEnterMutex();
24208  if( pFile->locktype>SHARED_LOCK ){
24209
24210    if( pFile->locktype==EXCLUSIVE_LOCK ){
24211      rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
24212      if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
24213        /* only re-establish the shared lock if necessary */
24214        int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
24215        rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
24216      }
24217    }
24218    if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
24219      rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
24220    }
24221    if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
24222      rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
24223    }
24224  }else if( locktype==NO_LOCK ){
24225    /* clear the shared lock */
24226    int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
24227    rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
24228  }
24229
24230  if( rc==SQLITE_OK ){
24231    if( locktype==NO_LOCK ){
24232      struct unixOpenCnt *pOpen = pFile->pOpen;
24233      pOpen->nLock--;
24234      assert( pOpen->nLock>=0 );
24235      if( pOpen->nLock==0 ){
24236        rc = closePendingFds(pFile);
24237      }
24238    }
24239  }
24240  unixLeaveMutex();
24241  if( rc==SQLITE_OK ){
24242    pFile->locktype = locktype;
24243  }
24244  return rc;
24245}
24246
24247/*
24248** Close a file & cleanup AFP specific locking context
24249*/
24250static int afpClose(sqlite3_file *id) {
24251  if( id ){
24252    unixFile *pFile = (unixFile*)id;
24253    afpUnlock(id, NO_LOCK);
24254    unixEnterMutex();
24255    if( pFile->pOpen && pFile->pOpen->nLock ){
24256      /* If there are outstanding locks, do not actually close the file just
24257      ** yet because that would clear those locks.  Instead, add the file
24258      ** descriptor to pOpen->aPending.  It will be automatically closed when
24259      ** the last lock is cleared.
24260      */
24261      setPendingFd(pFile);
24262    }
24263    releaseOpenCnt(pFile->pOpen);
24264    sqlite3_free(pFile->lockingContext);
24265    closeUnixFile(id);
24266    unixLeaveMutex();
24267  }
24268  return SQLITE_OK;
24269}
24270
24271#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24272/*
24273** The code above is the AFP lock implementation.  The code is specific
24274** to MacOSX and does not work on other unix platforms.  No alternative
24275** is available.  If you don't compile for a mac, then the "unix-afp"
24276** VFS is not available.
24277**
24278********************* End of the AFP lock implementation **********************
24279******************************************************************************/
24280
24281
24282/******************************************************************************
24283**************** Non-locking sqlite3_file methods *****************************
24284**
24285** The next division contains implementations for all methods of the
24286** sqlite3_file object other than the locking methods.  The locking
24287** methods were defined in divisions above (one locking method per
24288** division).  Those methods that are common to all locking modes
24289** are gather together into this division.
24290*/
24291
24292/*
24293** Seek to the offset passed as the second argument, then read cnt
24294** bytes into pBuf. Return the number of bytes actually read.
24295**
24296** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
24297** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
24298** one system to another.  Since SQLite does not define USE_PREAD
24299** any any form by default, we will not attempt to define _XOPEN_SOURCE.
24300** See tickets #2741 and #2681.
24301**
24302** To avoid stomping the errno value on a failed read the lastErrno value
24303** is set before returning.
24304*/
24305static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
24306  int got;
24307  i64 newOffset;
24308  TIMER_START;
24309#if defined(USE_PREAD)
24310  got = pread(id->h, pBuf, cnt, offset);
24311  SimulateIOError( got = -1 );
24312#elif defined(USE_PREAD64)
24313  got = pread64(id->h, pBuf, cnt, offset);
24314  SimulateIOError( got = -1 );
24315#else
24316  newOffset = lseek(id->h, offset, SEEK_SET);
24317  SimulateIOError( newOffset-- );
24318  if( newOffset!=offset ){
24319    if( newOffset == -1 ){
24320      ((unixFile*)id)->lastErrno = errno;
24321    }else{
24322      ((unixFile*)id)->lastErrno = 0;
24323    }
24324    return -1;
24325  }
24326  got = read(id->h, pBuf, cnt);
24327#endif
24328  TIMER_END;
24329  if( got<0 ){
24330    ((unixFile*)id)->lastErrno = errno;
24331  }
24332  OSTRACE5("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
24333  return got;
24334}
24335
24336/*
24337** Read data from a file into a buffer.  Return SQLITE_OK if all
24338** bytes were read successfully and SQLITE_IOERR if anything goes
24339** wrong.
24340*/
24341static int unixRead(
24342  sqlite3_file *id,
24343  void *pBuf,
24344  int amt,
24345  sqlite3_int64 offset
24346){
24347  unixFile *pFile = (unixFile *)id;
24348  int got;
24349  assert( id );
24350
24351  /* If this is a database file (not a journal, master-journal or temp
24352  ** file), the bytes in the locking range should never be read or written. */
24353  assert( pFile->pUnused==0
24354       || offset>=PENDING_BYTE+512
24355       || offset+amt<=PENDING_BYTE
24356  );
24357
24358  got = seekAndRead(pFile, offset, pBuf, amt);
24359  if( got==amt ){
24360    return SQLITE_OK;
24361  }else if( got<0 ){
24362    /* lastErrno set by seekAndRead */
24363    return SQLITE_IOERR_READ;
24364  }else{
24365    pFile->lastErrno = 0; /* not a system error */
24366    /* Unread parts of the buffer must be zero-filled */
24367    memset(&((char*)pBuf)[got], 0, amt-got);
24368    return SQLITE_IOERR_SHORT_READ;
24369  }
24370}
24371
24372/*
24373** Seek to the offset in id->offset then read cnt bytes into pBuf.
24374** Return the number of bytes actually read.  Update the offset.
24375**
24376** To avoid stomping the errno value on a failed write the lastErrno value
24377** is set before returning.
24378*/
24379static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
24380  int got;
24381  i64 newOffset;
24382  TIMER_START;
24383#if defined(USE_PREAD)
24384  got = pwrite(id->h, pBuf, cnt, offset);
24385#elif defined(USE_PREAD64)
24386  got = pwrite64(id->h, pBuf, cnt, offset);
24387#else
24388  newOffset = lseek(id->h, offset, SEEK_SET);
24389  if( newOffset!=offset ){
24390    if( newOffset == -1 ){
24391      ((unixFile*)id)->lastErrno = errno;
24392    }else{
24393      ((unixFile*)id)->lastErrno = 0;
24394    }
24395    return -1;
24396  }
24397  got = write(id->h, pBuf, cnt);
24398#endif
24399  TIMER_END;
24400  if( got<0 ){
24401    ((unixFile*)id)->lastErrno = errno;
24402  }
24403
24404  OSTRACE5("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
24405  return got;
24406}
24407
24408
24409/*
24410** Write data from a buffer into a file.  Return SQLITE_OK on success
24411** or some other error code on failure.
24412*/
24413static int unixWrite(
24414  sqlite3_file *id,
24415  const void *pBuf,
24416  int amt,
24417  sqlite3_int64 offset
24418){
24419  unixFile *pFile = (unixFile*)id;
24420  int wrote = 0;
24421  assert( id );
24422  assert( amt>0 );
24423
24424  /* If this is a database file (not a journal, master-journal or temp
24425  ** file), the bytes in the locking range should never be read or written. */
24426  assert( pFile->pUnused==0
24427       || offset>=PENDING_BYTE+512
24428       || offset+amt<=PENDING_BYTE
24429  );
24430
24431#ifndef NDEBUG
24432  /* If we are doing a normal write to a database file (as opposed to
24433  ** doing a hot-journal rollback or a write to some file other than a
24434  ** normal database file) then record the fact that the database
24435  ** has changed.  If the transaction counter is modified, record that
24436  ** fact too.
24437  */
24438  if( pFile->inNormalWrite ){
24439    pFile->dbUpdate = 1;  /* The database has been modified */
24440    if( offset<=24 && offset+amt>=27 ){
24441      int rc;
24442      char oldCntr[4];
24443      SimulateIOErrorBenign(1);
24444      rc = seekAndRead(pFile, 24, oldCntr, 4);
24445      SimulateIOErrorBenign(0);
24446      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
24447        pFile->transCntrChng = 1;  /* The transaction counter has changed */
24448      }
24449    }
24450  }
24451#endif
24452
24453  while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
24454    amt -= wrote;
24455    offset += wrote;
24456    pBuf = &((char*)pBuf)[wrote];
24457  }
24458  SimulateIOError(( wrote=(-1), amt=1 ));
24459  SimulateDiskfullError(( wrote=0, amt=1 ));
24460  if( amt>0 ){
24461    if( wrote<0 ){
24462      /* lastErrno set by seekAndWrite */
24463      return SQLITE_IOERR_WRITE;
24464    }else{
24465      pFile->lastErrno = 0; /* not a system error */
24466      return SQLITE_FULL;
24467    }
24468  }
24469  return SQLITE_OK;
24470}
24471
24472#ifdef SQLITE_TEST
24473/*
24474** Count the number of fullsyncs and normal syncs.  This is used to test
24475** that syncs and fullsyncs are occurring at the right times.
24476*/
24477SQLITE_API int sqlite3_sync_count = 0;
24478SQLITE_API int sqlite3_fullsync_count = 0;
24479#endif
24480
24481/*
24482** We do not trust systems to provide a working fdatasync().  Some do.
24483** Others do no.  To be safe, we will stick with the (slower) fsync().
24484** If you know that your system does support fdatasync() correctly,
24485** then simply compile with -Dfdatasync=fdatasync
24486*/
24487#if !defined(fdatasync) && !defined(__linux__)
24488# define fdatasync fsync
24489#endif
24490
24491/*
24492** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
24493** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
24494** only available on Mac OS X.  But that could change.
24495*/
24496#ifdef F_FULLFSYNC
24497# define HAVE_FULLFSYNC 1
24498#else
24499# define HAVE_FULLFSYNC 0
24500#endif
24501
24502
24503/*
24504** The fsync() system call does not work as advertised on many
24505** unix systems.  The following procedure is an attempt to make
24506** it work better.
24507**
24508** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
24509** for testing when we want to run through the test suite quickly.
24510** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
24511** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
24512** or power failure will likely corrupt the database file.
24513**
24514** SQLite sets the dataOnly flag if the size of the file is unchanged.
24515** The idea behind dataOnly is that it should only write the file content
24516** to disk, not the inode.  We only set dataOnly if the file size is
24517** unchanged since the file size is part of the inode.  However,
24518** Ted Ts'o tells us that fdatasync() will also write the inode if the
24519** file size has changed.  The only real difference between fdatasync()
24520** and fsync(), Ted tells us, is that fdatasync() will not flush the
24521** inode if the mtime or owner or other inode attributes have changed.
24522** We only care about the file size, not the other file attributes, so
24523** as far as SQLite is concerned, an fdatasync() is always adequate.
24524** So, we always use fdatasync() if it is available, regardless of
24525** the value of the dataOnly flag.
24526*/
24527static int full_fsync(int fd, int fullSync, int dataOnly){
24528  int rc;
24529
24530  /* The following "ifdef/elif/else/" block has the same structure as
24531  ** the one below. It is replicated here solely to avoid cluttering
24532  ** up the real code with the UNUSED_PARAMETER() macros.
24533  */
24534#ifdef SQLITE_NO_SYNC
24535  UNUSED_PARAMETER(fd);
24536  UNUSED_PARAMETER(fullSync);
24537  UNUSED_PARAMETER(dataOnly);
24538#elif HAVE_FULLFSYNC
24539  UNUSED_PARAMETER(dataOnly);
24540#else
24541  UNUSED_PARAMETER(fullSync);
24542  UNUSED_PARAMETER(dataOnly);
24543#endif
24544
24545  /* Record the number of times that we do a normal fsync() and
24546  ** FULLSYNC.  This is used during testing to verify that this procedure
24547  ** gets called with the correct arguments.
24548  */
24549#ifdef SQLITE_TEST
24550  if( fullSync ) sqlite3_fullsync_count++;
24551  sqlite3_sync_count++;
24552#endif
24553
24554  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
24555  ** no-op
24556  */
24557#ifdef SQLITE_NO_SYNC
24558  rc = SQLITE_OK;
24559#elif HAVE_FULLFSYNC
24560  if( fullSync ){
24561    rc = fcntl(fd, F_FULLFSYNC, 0);
24562  }else{
24563    rc = 1;
24564  }
24565  /* If the FULLFSYNC failed, fall back to attempting an fsync().
24566  ** It shouldn't be possible for fullfsync to fail on the local
24567  ** file system (on OSX), so failure indicates that FULLFSYNC
24568  ** isn't supported for this file system. So, attempt an fsync
24569  ** and (for now) ignore the overhead of a superfluous fcntl call.
24570  ** It'd be better to detect fullfsync support once and avoid
24571  ** the fcntl call every time sync is called.
24572  */
24573  if( rc ) rc = fsync(fd);
24574
24575#else
24576  rc = fdatasync(fd);
24577#if OS_VXWORKS
24578  if( rc==-1 && errno==ENOTSUP ){
24579    rc = fsync(fd);
24580  }
24581#endif /* OS_VXWORKS */
24582#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
24583
24584  if( OS_VXWORKS && rc!= -1 ){
24585    rc = 0;
24586  }
24587  return rc;
24588}
24589
24590/*
24591** Make sure all writes to a particular file are committed to disk.
24592**
24593** If dataOnly==0 then both the file itself and its metadata (file
24594** size, access time, etc) are synced.  If dataOnly!=0 then only the
24595** file data is synced.
24596**
24597** Under Unix, also make sure that the directory entry for the file
24598** has been created by fsync-ing the directory that contains the file.
24599** If we do not do this and we encounter a power failure, the directory
24600** entry for the journal might not exist after we reboot.  The next
24601** SQLite to access the file will not know that the journal exists (because
24602** the directory entry for the journal was never created) and the transaction
24603** will not roll back - possibly leading to database corruption.
24604*/
24605static int unixSync(sqlite3_file *id, int flags){
24606  int rc;
24607  unixFile *pFile = (unixFile*)id;
24608
24609  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
24610  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
24611
24612  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
24613  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
24614      || (flags&0x0F)==SQLITE_SYNC_FULL
24615  );
24616
24617  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
24618  ** line is to test that doing so does not cause any problems.
24619  */
24620  SimulateDiskfullError( return SQLITE_FULL );
24621
24622  assert( pFile );
24623  OSTRACE2("SYNC    %-3d\n", pFile->h);
24624  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
24625  SimulateIOError( rc=1 );
24626  if( rc ){
24627    pFile->lastErrno = errno;
24628    return SQLITE_IOERR_FSYNC;
24629  }
24630  if( pFile->dirfd>=0 ){
24631    int err;
24632    OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
24633            HAVE_FULLFSYNC, isFullsync);
24634#ifndef SQLITE_DISABLE_DIRSYNC
24635    /* The directory sync is only attempted if full_fsync is
24636    ** turned off or unavailable.  If a full_fsync occurred above,
24637    ** then the directory sync is superfluous.
24638    */
24639    if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
24640       /*
24641       ** We have received multiple reports of fsync() returning
24642       ** errors when applied to directories on certain file systems.
24643       ** A failed directory sync is not a big deal.  So it seems
24644       ** better to ignore the error.  Ticket #1657
24645       */
24646       /* pFile->lastErrno = errno; */
24647       /* return SQLITE_IOERR; */
24648    }
24649#endif
24650    err = close(pFile->dirfd); /* Only need to sync once, so close the */
24651    if( err==0 ){              /* directory when we are done */
24652      pFile->dirfd = -1;
24653    }else{
24654      pFile->lastErrno = errno;
24655      rc = SQLITE_IOERR_DIR_CLOSE;
24656    }
24657  }
24658  return rc;
24659}
24660
24661/*
24662** Truncate an open file to a specified size
24663*/
24664static int unixTruncate(sqlite3_file *id, i64 nByte){
24665  int rc;
24666  assert( id );
24667  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
24668  rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
24669  if( rc ){
24670    ((unixFile*)id)->lastErrno = errno;
24671    return SQLITE_IOERR_TRUNCATE;
24672  }else{
24673#ifndef NDEBUG
24674    /* If we are doing a normal write to a database file (as opposed to
24675    ** doing a hot-journal rollback or a write to some file other than a
24676    ** normal database file) and we truncate the file to zero length,
24677    ** that effectively updates the change counter.  This might happen
24678    ** when restoring a database using the backup API from a zero-length
24679    ** source.
24680    */
24681    if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
24682      ((unixFile*)id)->transCntrChng = 1;
24683    }
24684#endif
24685
24686    return SQLITE_OK;
24687  }
24688}
24689
24690/*
24691** Determine the current size of a file in bytes
24692*/
24693static int unixFileSize(sqlite3_file *id, i64 *pSize){
24694  int rc;
24695  struct stat buf;
24696  assert( id );
24697  rc = fstat(((unixFile*)id)->h, &buf);
24698  SimulateIOError( rc=1 );
24699  if( rc!=0 ){
24700    ((unixFile*)id)->lastErrno = errno;
24701    return SQLITE_IOERR_FSTAT;
24702  }
24703  *pSize = buf.st_size;
24704
24705  /* When opening a zero-size database, the findLockInfo() procedure
24706  ** writes a single byte into that file in order to work around a bug
24707  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
24708  ** layers, we need to report this file size as zero even though it is
24709  ** really 1.   Ticket #3260.
24710  */
24711  if( *pSize==1 ) *pSize = 0;
24712
24713
24714  return SQLITE_OK;
24715}
24716
24717#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
24718/*
24719** Handler for proxy-locking file-control verbs.  Defined below in the
24720** proxying locking division.
24721*/
24722static int proxyFileControl(sqlite3_file*,int,void*);
24723#endif
24724
24725
24726/*
24727** Information and control of an open file handle.
24728*/
24729static int unixFileControl(sqlite3_file *id, int op, void *pArg){
24730  switch( op ){
24731    case SQLITE_FCNTL_LOCKSTATE: {
24732      *(int*)pArg = ((unixFile*)id)->locktype;
24733      return SQLITE_OK;
24734    }
24735    case SQLITE_LAST_ERRNO: {
24736      *(int*)pArg = ((unixFile*)id)->lastErrno;
24737      return SQLITE_OK;
24738    }
24739#ifndef NDEBUG
24740    /* The pager calls this method to signal that it has done
24741    ** a rollback and that the database is therefore unchanged and
24742    ** it hence it is OK for the transaction change counter to be
24743    ** unchanged.
24744    */
24745    case SQLITE_FCNTL_DB_UNCHANGED: {
24746      ((unixFile*)id)->dbUpdate = 0;
24747      return SQLITE_OK;
24748    }
24749#endif
24750#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
24751    case SQLITE_SET_LOCKPROXYFILE:
24752    case SQLITE_GET_LOCKPROXYFILE: {
24753      return proxyFileControl(id,op,pArg);
24754    }
24755#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
24756  }
24757  return SQLITE_ERROR;
24758}
24759
24760/*
24761** Return the sector size in bytes of the underlying block device for
24762** the specified file. This is almost always 512 bytes, but may be
24763** larger for some devices.
24764**
24765** SQLite code assumes this function cannot fail. It also assumes that
24766** if two files are created in the same file-system directory (i.e.
24767** a database and its journal file) that the sector size will be the
24768** same for both.
24769*/
24770static int unixSectorSize(sqlite3_file *NotUsed){
24771  UNUSED_PARAMETER(NotUsed);
24772  return SQLITE_DEFAULT_SECTOR_SIZE;
24773}
24774
24775/*
24776** Return the device characteristics for the file. This is always 0 for unix.
24777*/
24778static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
24779  UNUSED_PARAMETER(NotUsed);
24780  return 0;
24781}
24782
24783/*
24784** Here ends the implementation of all sqlite3_file methods.
24785**
24786********************** End sqlite3_file Methods *******************************
24787******************************************************************************/
24788
24789/*
24790** This division contains definitions of sqlite3_io_methods objects that
24791** implement various file locking strategies.  It also contains definitions
24792** of "finder" functions.  A finder-function is used to locate the appropriate
24793** sqlite3_io_methods object for a particular database file.  The pAppData
24794** field of the sqlite3_vfs VFS objects are initialized to be pointers to
24795** the correct finder-function for that VFS.
24796**
24797** Most finder functions return a pointer to a fixed sqlite3_io_methods
24798** object.  The only interesting finder-function is autolockIoFinder, which
24799** looks at the filesystem type and tries to guess the best locking
24800** strategy from that.
24801**
24802** For finder-funtion F, two objects are created:
24803**
24804**    (1) The real finder-function named "FImpt()".
24805**
24806**    (2) A constant pointer to this function named just "F".
24807**
24808**
24809** A pointer to the F pointer is used as the pAppData value for VFS
24810** objects.  We have to do this instead of letting pAppData point
24811** directly at the finder-function since C90 rules prevent a void*
24812** from be cast into a function pointer.
24813**
24814**
24815** Each instance of this macro generates two objects:
24816**
24817**   *  A constant sqlite3_io_methods object call METHOD that has locking
24818**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
24819**
24820**   *  An I/O method finder function called FINDER that returns a pointer
24821**      to the METHOD object in the previous bullet.
24822*/
24823#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK)               \
24824static const sqlite3_io_methods METHOD = {                                   \
24825   1,                          /* iVersion */                                \
24826   CLOSE,                      /* xClose */                                  \
24827   unixRead,                   /* xRead */                                   \
24828   unixWrite,                  /* xWrite */                                  \
24829   unixTruncate,               /* xTruncate */                               \
24830   unixSync,                   /* xSync */                                   \
24831   unixFileSize,               /* xFileSize */                               \
24832   LOCK,                       /* xLock */                                   \
24833   UNLOCK,                     /* xUnlock */                                 \
24834   CKLOCK,                     /* xCheckReservedLock */                      \
24835   unixFileControl,            /* xFileControl */                            \
24836   unixSectorSize,             /* xSectorSize */                             \
24837   unixDeviceCharacteristics   /* xDeviceCapabilities */                     \
24838};                                                                           \
24839static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
24840  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
24841  return &METHOD;                                                            \
24842}                                                                            \
24843static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
24844    = FINDER##Impl;
24845
24846/*
24847** Here are all of the sqlite3_io_methods objects for each of the
24848** locking strategies.  Functions that return pointers to these methods
24849** are also created.
24850*/
24851IOMETHODS(
24852  posixIoFinder,            /* Finder function name */
24853  posixIoMethods,           /* sqlite3_io_methods object name */
24854  unixClose,                /* xClose method */
24855  unixLock,                 /* xLock method */
24856  unixUnlock,               /* xUnlock method */
24857  unixCheckReservedLock     /* xCheckReservedLock method */
24858)
24859IOMETHODS(
24860  nolockIoFinder,           /* Finder function name */
24861  nolockIoMethods,          /* sqlite3_io_methods object name */
24862  nolockClose,              /* xClose method */
24863  nolockLock,               /* xLock method */
24864  nolockUnlock,             /* xUnlock method */
24865  nolockCheckReservedLock   /* xCheckReservedLock method */
24866)
24867IOMETHODS(
24868  dotlockIoFinder,          /* Finder function name */
24869  dotlockIoMethods,         /* sqlite3_io_methods object name */
24870  dotlockClose,             /* xClose method */
24871  dotlockLock,              /* xLock method */
24872  dotlockUnlock,            /* xUnlock method */
24873  dotlockCheckReservedLock  /* xCheckReservedLock method */
24874)
24875
24876#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
24877IOMETHODS(
24878  flockIoFinder,            /* Finder function name */
24879  flockIoMethods,           /* sqlite3_io_methods object name */
24880  flockClose,               /* xClose method */
24881  flockLock,                /* xLock method */
24882  flockUnlock,              /* xUnlock method */
24883  flockCheckReservedLock    /* xCheckReservedLock method */
24884)
24885#endif
24886
24887#if OS_VXWORKS
24888IOMETHODS(
24889  semIoFinder,              /* Finder function name */
24890  semIoMethods,             /* sqlite3_io_methods object name */
24891  semClose,                 /* xClose method */
24892  semLock,                  /* xLock method */
24893  semUnlock,                /* xUnlock method */
24894  semCheckReservedLock      /* xCheckReservedLock method */
24895)
24896#endif
24897
24898#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24899IOMETHODS(
24900  afpIoFinder,              /* Finder function name */
24901  afpIoMethods,             /* sqlite3_io_methods object name */
24902  afpClose,                 /* xClose method */
24903  afpLock,                  /* xLock method */
24904  afpUnlock,                /* xUnlock method */
24905  afpCheckReservedLock      /* xCheckReservedLock method */
24906)
24907#endif
24908
24909/*
24910** The "Whole File Locking" finder returns the same set of methods as
24911** the posix locking finder.  But it also sets the SQLITE_WHOLE_FILE_LOCKING
24912** flag to force the posix advisory locks to cover the whole file instead
24913** of just a small span of bytes near the 1GiB boundary.  Whole File Locking
24914** is useful on NFS-mounted files since it helps NFS to maintain cache
24915** coherency.  But it is a detriment to other filesystems since it runs
24916** slower.
24917*/
24918static const sqlite3_io_methods *posixWflIoFinderImpl(const char*z, unixFile*p){
24919  UNUSED_PARAMETER(z);
24920  p->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
24921  return &posixIoMethods;
24922}
24923static const sqlite3_io_methods
24924  *(*const posixWflIoFinder)(const char*,unixFile *p) = posixWflIoFinderImpl;
24925
24926/*
24927** The proxy locking method is a "super-method" in the sense that it
24928** opens secondary file descriptors for the conch and lock files and
24929** it uses proxy, dot-file, AFP, and flock() locking methods on those
24930** secondary files.  For this reason, the division that implements
24931** proxy locking is located much further down in the file.  But we need
24932** to go ahead and define the sqlite3_io_methods and finder function
24933** for proxy locking here.  So we forward declare the I/O methods.
24934*/
24935#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24936static int proxyClose(sqlite3_file*);
24937static int proxyLock(sqlite3_file*, int);
24938static int proxyUnlock(sqlite3_file*, int);
24939static int proxyCheckReservedLock(sqlite3_file*, int*);
24940IOMETHODS(
24941  proxyIoFinder,            /* Finder function name */
24942  proxyIoMethods,           /* sqlite3_io_methods object name */
24943  proxyClose,               /* xClose method */
24944  proxyLock,                /* xLock method */
24945  proxyUnlock,              /* xUnlock method */
24946  proxyCheckReservedLock    /* xCheckReservedLock method */
24947)
24948#endif
24949
24950
24951#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24952/*
24953** This "finder" function attempts to determine the best locking strategy
24954** for the database file "filePath".  It then returns the sqlite3_io_methods
24955** object that implements that strategy.
24956**
24957** This is for MacOSX only.
24958*/
24959static const sqlite3_io_methods *autolockIoFinderImpl(
24960  const char *filePath,    /* name of the database file */
24961  unixFile *pNew           /* open file object for the database file */
24962){
24963  static const struct Mapping {
24964    const char *zFilesystem;              /* Filesystem type name */
24965    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
24966  } aMap[] = {
24967    { "hfs",    &posixIoMethods },
24968    { "ufs",    &posixIoMethods },
24969    { "afpfs",  &afpIoMethods },
24970#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
24971    { "smbfs",  &afpIoMethods },
24972#else
24973    { "smbfs",  &flockIoMethods },
24974#endif
24975    { "webdav", &nolockIoMethods },
24976    { 0, 0 }
24977  };
24978  int i;
24979  struct statfs fsInfo;
24980  struct flock lockInfo;
24981
24982  if( !filePath ){
24983    /* If filePath==NULL that means we are dealing with a transient file
24984    ** that does not need to be locked. */
24985    return &nolockIoMethods;
24986  }
24987  if( statfs(filePath, &fsInfo) != -1 ){
24988    if( fsInfo.f_flags & MNT_RDONLY ){
24989      return &nolockIoMethods;
24990    }
24991    for(i=0; aMap[i].zFilesystem; i++){
24992      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
24993        return aMap[i].pMethods;
24994      }
24995    }
24996  }
24997
24998  /* Default case. Handles, amongst others, "nfs".
24999  ** Test byte-range lock using fcntl(). If the call succeeds,
25000  ** assume that the file-system supports POSIX style locks.
25001  */
25002  lockInfo.l_len = 1;
25003  lockInfo.l_start = 0;
25004  lockInfo.l_whence = SEEK_SET;
25005  lockInfo.l_type = F_RDLCK;
25006  if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
25007    pNew->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
25008    return &posixIoMethods;
25009  }else{
25010    return &dotlockIoMethods;
25011  }
25012}
25013static const sqlite3_io_methods
25014  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
25015
25016#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25017
25018#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
25019/*
25020** This "finder" function attempts to determine the best locking strategy
25021** for the database file "filePath".  It then returns the sqlite3_io_methods
25022** object that implements that strategy.
25023**
25024** This is for VXWorks only.
25025*/
25026static const sqlite3_io_methods *autolockIoFinderImpl(
25027  const char *filePath,    /* name of the database file */
25028  unixFile *pNew           /* the open file object */
25029){
25030  struct flock lockInfo;
25031
25032  if( !filePath ){
25033    /* If filePath==NULL that means we are dealing with a transient file
25034    ** that does not need to be locked. */
25035    return &nolockIoMethods;
25036  }
25037
25038  /* Test if fcntl() is supported and use POSIX style locks.
25039  ** Otherwise fall back to the named semaphore method.
25040  */
25041  lockInfo.l_len = 1;
25042  lockInfo.l_start = 0;
25043  lockInfo.l_whence = SEEK_SET;
25044  lockInfo.l_type = F_RDLCK;
25045  if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
25046    return &posixIoMethods;
25047  }else{
25048    return &semIoMethods;
25049  }
25050}
25051static const sqlite3_io_methods
25052  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
25053
25054#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
25055
25056/*
25057** An abstract type for a pointer to a IO method finder function:
25058*/
25059typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
25060
25061
25062/****************************************************************************
25063**************************** sqlite3_vfs methods ****************************
25064**
25065** This division contains the implementation of methods on the
25066** sqlite3_vfs object.
25067*/
25068
25069/*
25070** Initialize the contents of the unixFile structure pointed to by pId.
25071*/
25072static int fillInUnixFile(
25073  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
25074  int h,                  /* Open file descriptor of file being opened */
25075  int dirfd,              /* Directory file descriptor */
25076  sqlite3_file *pId,      /* Write to the unixFile structure here */
25077  const char *zFilename,  /* Name of the file being opened */
25078  int noLock,             /* Omit locking if true */
25079  int isDelete            /* Delete on close if true */
25080){
25081  const sqlite3_io_methods *pLockingStyle;
25082  unixFile *pNew = (unixFile *)pId;
25083  int rc = SQLITE_OK;
25084
25085  assert( pNew->pLock==NULL );
25086  assert( pNew->pOpen==NULL );
25087
25088  /* Parameter isDelete is only used on vxworks. Express this explicitly
25089  ** here to prevent compiler warnings about unused parameters.
25090  */
25091  UNUSED_PARAMETER(isDelete);
25092
25093  OSTRACE3("OPEN    %-3d %s\n", h, zFilename);
25094  pNew->h = h;
25095  pNew->dirfd = dirfd;
25096  SET_THREADID(pNew);
25097  pNew->fileFlags = 0;
25098
25099#if OS_VXWORKS
25100  pNew->pId = vxworksFindFileId(zFilename);
25101  if( pNew->pId==0 ){
25102    noLock = 1;
25103    rc = SQLITE_NOMEM;
25104  }
25105#endif
25106
25107  if( noLock ){
25108    pLockingStyle = &nolockIoMethods;
25109  }else{
25110    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
25111#if SQLITE_ENABLE_LOCKING_STYLE
25112    /* Cache zFilename in the locking context (AFP and dotlock override) for
25113    ** proxyLock activation is possible (remote proxy is based on db name)
25114    ** zFilename remains valid until file is closed, to support */
25115    pNew->lockingContext = (void*)zFilename;
25116#endif
25117  }
25118
25119  if( pLockingStyle == &posixIoMethods ){
25120    unixEnterMutex();
25121    rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
25122    if( rc!=SQLITE_OK ){
25123      /* If an error occured in findLockInfo(), close the file descriptor
25124      ** immediately, before releasing the mutex. findLockInfo() may fail
25125      ** in two scenarios:
25126      **
25127      **   (a) A call to fstat() failed.
25128      **   (b) A malloc failed.
25129      **
25130      ** Scenario (b) may only occur if the process is holding no other
25131      ** file descriptors open on the same file. If there were other file
25132      ** descriptors on this file, then no malloc would be required by
25133      ** findLockInfo(). If this is the case, it is quite safe to close
25134      ** handle h - as it is guaranteed that no posix locks will be released
25135      ** by doing so.
25136      **
25137      ** If scenario (a) caused the error then things are not so safe. The
25138      ** implicit assumption here is that if fstat() fails, things are in
25139      ** such bad shape that dropping a lock or two doesn't matter much.
25140      */
25141      close(h);
25142      h = -1;
25143    }
25144    unixLeaveMutex();
25145  }
25146
25147#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25148  else if( pLockingStyle == &afpIoMethods ){
25149    /* AFP locking uses the file path so it needs to be included in
25150    ** the afpLockingContext.
25151    */
25152    afpLockingContext *pCtx;
25153    pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
25154    if( pCtx==0 ){
25155      rc = SQLITE_NOMEM;
25156    }else{
25157      /* NB: zFilename exists and remains valid until the file is closed
25158      ** according to requirement F11141.  So we do not need to make a
25159      ** copy of the filename. */
25160      pCtx->dbPath = zFilename;
25161      srandomdev();
25162      unixEnterMutex();
25163      rc = findLockInfo(pNew, NULL, &pNew->pOpen);
25164      unixLeaveMutex();
25165    }
25166  }
25167#endif
25168
25169  else if( pLockingStyle == &dotlockIoMethods ){
25170    /* Dotfile locking uses the file path so it needs to be included in
25171    ** the dotlockLockingContext
25172    */
25173    char *zLockFile;
25174    int nFilename;
25175    nFilename = (int)strlen(zFilename) + 6;
25176    zLockFile = (char *)sqlite3_malloc(nFilename);
25177    if( zLockFile==0 ){
25178      rc = SQLITE_NOMEM;
25179    }else{
25180      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
25181    }
25182    pNew->lockingContext = zLockFile;
25183  }
25184
25185#if OS_VXWORKS
25186  else if( pLockingStyle == &semIoMethods ){
25187    /* Named semaphore locking uses the file path so it needs to be
25188    ** included in the semLockingContext
25189    */
25190    unixEnterMutex();
25191    rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
25192    if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
25193      char *zSemName = pNew->pOpen->aSemName;
25194      int n;
25195      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
25196                       pNew->pId->zCanonicalName);
25197      for( n=1; zSemName[n]; n++ )
25198        if( zSemName[n]=='/' ) zSemName[n] = '_';
25199      pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
25200      if( pNew->pOpen->pSem == SEM_FAILED ){
25201        rc = SQLITE_NOMEM;
25202        pNew->pOpen->aSemName[0] = '\0';
25203      }
25204    }
25205    unixLeaveMutex();
25206  }
25207#endif
25208
25209  pNew->lastErrno = 0;
25210#if OS_VXWORKS
25211  if( rc!=SQLITE_OK ){
25212    unlink(zFilename);
25213    isDelete = 0;
25214  }
25215  pNew->isDelete = isDelete;
25216#endif
25217  if( rc!=SQLITE_OK ){
25218    if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
25219    if( h>=0 ) close(h);
25220  }else{
25221    pNew->pMethod = pLockingStyle;
25222    OpenCounter(+1);
25223  }
25224  return rc;
25225}
25226
25227/*
25228** Open a file descriptor to the directory containing file zFilename.
25229** If successful, *pFd is set to the opened file descriptor and
25230** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
25231** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
25232** value.
25233**
25234** If SQLITE_OK is returned, the caller is responsible for closing
25235** the file descriptor *pFd using close().
25236*/
25237static int openDirectory(const char *zFilename, int *pFd){
25238  int ii;
25239  int fd = -1;
25240  char zDirname[MAX_PATHNAME+1];
25241
25242  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
25243  for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
25244  if( ii>0 ){
25245    zDirname[ii] = '\0';
25246    fd = open(zDirname, O_RDONLY|O_BINARY, 0);
25247    if( fd>=0 ){
25248#ifdef FD_CLOEXEC
25249      fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25250#endif
25251      OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
25252    }
25253  }
25254  *pFd = fd;
25255  return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
25256}
25257
25258/*
25259** Create a temporary file name in zBuf.  zBuf must be allocated
25260** by the calling process and must be big enough to hold at least
25261** pVfs->mxPathname bytes.
25262*/
25263static int getTempname(int nBuf, char *zBuf){
25264  static const char *azDirs[] = {
25265     0,
25266     0,
25267     "/var/tmp",
25268     "/usr/tmp",
25269     "/tmp",
25270     ".",
25271  };
25272  static const unsigned char zChars[] =
25273    "abcdefghijklmnopqrstuvwxyz"
25274    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
25275    "0123456789";
25276  unsigned int i, j;
25277  struct stat buf;
25278  const char *zDir = ".";
25279
25280  /* It's odd to simulate an io-error here, but really this is just
25281  ** using the io-error infrastructure to test that SQLite handles this
25282  ** function failing.
25283  */
25284  SimulateIOError( return SQLITE_IOERR );
25285
25286  azDirs[0] = sqlite3_temp_directory;
25287  if (NULL == azDirs[1]) {
25288    azDirs[1] = getenv("TMPDIR");
25289  }
25290
25291  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
25292    if( azDirs[i]==0 ) continue;
25293    if( stat(azDirs[i], &buf) ) continue;
25294    if( !S_ISDIR(buf.st_mode) ) continue;
25295    if( access(azDirs[i], 07) ) continue;
25296    zDir = azDirs[i];
25297    break;
25298  }
25299
25300  /* Check that the output buffer is large enough for the temporary file
25301  ** name. If it is not, return SQLITE_ERROR.
25302  */
25303  if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
25304    return SQLITE_ERROR;
25305  }
25306
25307  do{
25308    sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
25309    j = (int)strlen(zBuf);
25310    sqlite3_randomness(15, &zBuf[j]);
25311    for(i=0; i<15; i++, j++){
25312      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
25313    }
25314    zBuf[j] = 0;
25315  }while( access(zBuf,0)==0 );
25316  return SQLITE_OK;
25317}
25318
25319#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25320/*
25321** Routine to transform a unixFile into a proxy-locking unixFile.
25322** Implementation in the proxy-lock division, but used by unixOpen()
25323** if SQLITE_PREFER_PROXY_LOCKING is defined.
25324*/
25325static int proxyTransformUnixFile(unixFile*, const char*);
25326#endif
25327
25328/*
25329** Search for an unused file descriptor that was opened on the database
25330** file (not a journal or master-journal file) identified by pathname
25331** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
25332** argument to this function.
25333**
25334** Such a file descriptor may exist if a database connection was closed
25335** but the associated file descriptor could not be closed because some
25336** other file descriptor open on the same file is holding a file-lock.
25337** Refer to comments in the unixClose() function and the lengthy comment
25338** describing "Posix Advisory Locking" at the start of this file for
25339** further details. Also, ticket #4018.
25340**
25341** If a suitable file descriptor is found, then it is returned. If no
25342** such file descriptor is located, -1 is returned.
25343*/
25344static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
25345  UnixUnusedFd *pUnused = 0;
25346
25347  /* Do not search for an unused file descriptor on vxworks. Not because
25348  ** vxworks would not benefit from the change (it might, we're not sure),
25349  ** but because no way to test it is currently available. It is better
25350  ** not to risk breaking vxworks support for the sake of such an obscure
25351  ** feature.  */
25352#if !OS_VXWORKS
25353  struct stat sStat;                   /* Results of stat() call */
25354
25355  /* A stat() call may fail for various reasons. If this happens, it is
25356  ** almost certain that an open() call on the same path will also fail.
25357  ** For this reason, if an error occurs in the stat() call here, it is
25358  ** ignored and -1 is returned. The caller will try to open a new file
25359  ** descriptor on the same path, fail, and return an error to SQLite.
25360  **
25361  ** Even if a subsequent open() call does succeed, the consequences of
25362  ** not searching for a resusable file descriptor are not dire.  */
25363  if( 0==stat(zPath, &sStat) ){
25364    struct unixOpenCnt *pOpen;
25365
25366    unixEnterMutex();
25367    pOpen = openList;
25368    while( pOpen && (pOpen->fileId.dev!=sStat.st_dev
25369                     || pOpen->fileId.ino!=sStat.st_ino) ){
25370       pOpen = pOpen->pNext;
25371    }
25372    if( pOpen ){
25373      UnixUnusedFd **pp;
25374      for(pp=&pOpen->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
25375      pUnused = *pp;
25376      if( pUnused ){
25377        *pp = pUnused->pNext;
25378      }
25379    }
25380    unixLeaveMutex();
25381  }
25382#endif    /* if !OS_VXWORKS */
25383  return pUnused;
25384}
25385
25386/*
25387** Open the file zPath.
25388**
25389** Previously, the SQLite OS layer used three functions in place of this
25390** one:
25391**
25392**     sqlite3OsOpenReadWrite();
25393**     sqlite3OsOpenReadOnly();
25394**     sqlite3OsOpenExclusive();
25395**
25396** These calls correspond to the following combinations of flags:
25397**
25398**     ReadWrite() ->     (READWRITE | CREATE)
25399**     ReadOnly()  ->     (READONLY)
25400**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
25401**
25402** The old OpenExclusive() accepted a boolean argument - "delFlag". If
25403** true, the file was configured to be automatically deleted when the
25404** file handle closed. To achieve the same effect using this new
25405** interface, add the DELETEONCLOSE flag to those specified above for
25406** OpenExclusive().
25407*/
25408static int unixOpen(
25409  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
25410  const char *zPath,           /* Pathname of file to be opened */
25411  sqlite3_file *pFile,         /* The file descriptor to be filled in */
25412  int flags,                   /* Input flags to control the opening */
25413  int *pOutFlags               /* Output flags returned to SQLite core */
25414){
25415  unixFile *p = (unixFile *)pFile;
25416  int fd = -1;                   /* File descriptor returned by open() */
25417  int dirfd = -1;                /* Directory file descriptor */
25418  int openFlags = 0;             /* Flags to pass to open() */
25419  int eType = flags&0xFFFFFF00;  /* Type of file to open */
25420  int noLock;                    /* True to omit locking primitives */
25421  int rc = SQLITE_OK;            /* Function Return Code */
25422
25423  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
25424  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
25425  int isCreate     = (flags & SQLITE_OPEN_CREATE);
25426  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
25427  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
25428
25429  /* If creating a master or main-file journal, this function will open
25430  ** a file-descriptor on the directory too. The first time unixSync()
25431  ** is called the directory file descriptor will be fsync()ed and close()d.
25432  */
25433  int isOpenDirectory = (isCreate &&
25434      (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
25435  );
25436
25437  /* If argument zPath is a NULL pointer, this function is required to open
25438  ** a temporary file. Use this buffer to store the file name in.
25439  */
25440  char zTmpname[MAX_PATHNAME+1];
25441  const char *zName = zPath;
25442
25443  /* Check the following statements are true:
25444  **
25445  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
25446  **   (b) if CREATE is set, then READWRITE must also be set, and
25447  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
25448  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
25449  */
25450  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
25451  assert(isCreate==0 || isReadWrite);
25452  assert(isExclusive==0 || isCreate);
25453  assert(isDelete==0 || isCreate);
25454
25455  /* The main DB, main journal, and master journal are never automatically
25456  ** deleted. Nor are they ever temporary files.  */
25457  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
25458  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
25459  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
25460
25461  /* Assert that the upper layer has set one of the "file-type" flags. */
25462  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
25463       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
25464       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
25465       || eType==SQLITE_OPEN_TRANSIENT_DB
25466  );
25467
25468  memset(p, 0, sizeof(unixFile));
25469
25470  if( eType==SQLITE_OPEN_MAIN_DB ){
25471    UnixUnusedFd *pUnused;
25472    pUnused = findReusableFd(zName, flags);
25473    if( pUnused ){
25474      fd = pUnused->fd;
25475    }else{
25476      pUnused = sqlite3_malloc(sizeof(*pUnused));
25477      if( !pUnused ){
25478        return SQLITE_NOMEM;
25479      }
25480    }
25481    p->pUnused = pUnused;
25482  }else if( !zName ){
25483    /* If zName is NULL, the upper layer is requesting a temp file. */
25484    assert(isDelete && !isOpenDirectory);
25485    rc = getTempname(MAX_PATHNAME+1, zTmpname);
25486    if( rc!=SQLITE_OK ){
25487      return rc;
25488    }
25489    zName = zTmpname;
25490  }
25491
25492  /* Determine the value of the flags parameter passed to POSIX function
25493  ** open(). These must be calculated even if open() is not called, as
25494  ** they may be stored as part of the file handle and used by the
25495  ** 'conch file' locking functions later on.  */
25496  if( isReadonly )  openFlags |= O_RDONLY;
25497  if( isReadWrite ) openFlags |= O_RDWR;
25498  if( isCreate )    openFlags |= O_CREAT;
25499  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
25500  openFlags |= (O_LARGEFILE|O_BINARY);
25501
25502  if( fd<0 ){
25503    mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
25504    fd = open(zName, openFlags, openMode);
25505    OSTRACE4("OPENX   %-3d %s 0%o\n", fd, zName, openFlags);
25506    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
25507      /* Failed to open the file for read/write access. Try read-only. */
25508      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
25509      openFlags &= ~(O_RDWR|O_CREAT);
25510      flags |= SQLITE_OPEN_READONLY;
25511      openFlags |= O_RDONLY;
25512      fd = open(zName, openFlags, openMode);
25513    }
25514    if( fd<0 ){
25515      rc = SQLITE_CANTOPEN;
25516      goto open_finished;
25517    }
25518  }
25519  assert( fd>=0 );
25520  if( pOutFlags ){
25521    *pOutFlags = flags;
25522  }
25523
25524  if( p->pUnused ){
25525    p->pUnused->fd = fd;
25526    p->pUnused->flags = flags;
25527  }
25528
25529  if( isDelete ){
25530#if OS_VXWORKS
25531    zPath = zName;
25532#else
25533    unlink(zName);
25534#endif
25535  }
25536#if SQLITE_ENABLE_LOCKING_STYLE
25537  else{
25538    p->openFlags = openFlags;
25539  }
25540#endif
25541
25542  if( isOpenDirectory ){
25543    rc = openDirectory(zPath, &dirfd);
25544    if( rc!=SQLITE_OK ){
25545      /* It is safe to close fd at this point, because it is guaranteed not
25546      ** to be open on a database file. If it were open on a database file,
25547      ** it would not be safe to close as this would release any locks held
25548      ** on the file by this process.  */
25549      assert( eType!=SQLITE_OPEN_MAIN_DB );
25550      close(fd);             /* silently leak if fail, already in error */
25551      goto open_finished;
25552    }
25553  }
25554
25555#ifdef FD_CLOEXEC
25556  fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25557#endif
25558
25559  noLock = eType!=SQLITE_OPEN_MAIN_DB;
25560
25561#if SQLITE_PREFER_PROXY_LOCKING
25562  if( zPath!=NULL && !noLock && pVfs->xOpen ){
25563    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
25564    int useProxy = 0;
25565
25566    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
25567    ** never use proxy, NULL means use proxy for non-local files only.  */
25568    if( envforce!=NULL ){
25569      useProxy = atoi(envforce)>0;
25570    }else{
25571      struct statfs fsInfo;
25572      if( statfs(zPath, &fsInfo) == -1 ){
25573        /* In theory, the close(fd) call is sub-optimal. If the file opened
25574        ** with fd is a database file, and there are other connections open
25575        ** on that file that are currently holding advisory locks on it,
25576        ** then the call to close() will cancel those locks. In practice,
25577        ** we're assuming that statfs() doesn't fail very often. At least
25578        ** not while other file descriptors opened by the same process on
25579        ** the same file are working.  */
25580        p->lastErrno = errno;
25581        if( dirfd>=0 ){
25582          close(dirfd); /* silently leak if fail, in error */
25583        }
25584        close(fd); /* silently leak if fail, in error */
25585        rc = SQLITE_IOERR_ACCESS;
25586        goto open_finished;
25587      }
25588      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
25589    }
25590    if( useProxy ){
25591      rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
25592      if( rc==SQLITE_OK ){
25593        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
25594      }
25595      goto open_finished;
25596    }
25597  }
25598#endif
25599
25600  rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
25601open_finished:
25602  if( rc!=SQLITE_OK ){
25603    sqlite3_free(p->pUnused);
25604  }
25605  return rc;
25606}
25607
25608
25609/*
25610** Delete the file at zPath. If the dirSync argument is true, fsync()
25611** the directory after deleting the file.
25612*/
25613static int unixDelete(
25614  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
25615  const char *zPath,        /* Name of file to be deleted */
25616  int dirSync               /* If true, fsync() directory after deleting file */
25617){
25618  int rc = SQLITE_OK;
25619  UNUSED_PARAMETER(NotUsed);
25620  SimulateIOError(return SQLITE_IOERR_DELETE);
25621  unlink(zPath);
25622#ifndef SQLITE_DISABLE_DIRSYNC
25623  if( dirSync ){
25624    int fd;
25625    rc = openDirectory(zPath, &fd);
25626    if( rc==SQLITE_OK ){
25627#if OS_VXWORKS
25628      if( fsync(fd)==-1 )
25629#else
25630      if( fsync(fd) )
25631#endif
25632      {
25633        rc = SQLITE_IOERR_DIR_FSYNC;
25634      }
25635      if( close(fd)&&!rc ){
25636        rc = SQLITE_IOERR_DIR_CLOSE;
25637      }
25638    }
25639  }
25640#endif
25641  return rc;
25642}
25643
25644/*
25645** Test the existance of or access permissions of file zPath. The
25646** test performed depends on the value of flags:
25647**
25648**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
25649**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
25650**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
25651**
25652** Otherwise return 0.
25653*/
25654static int unixAccess(
25655  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
25656  const char *zPath,      /* Path of the file to examine */
25657  int flags,              /* What do we want to learn about the zPath file? */
25658  int *pResOut            /* Write result boolean here */
25659){
25660  int amode = 0;
25661  UNUSED_PARAMETER(NotUsed);
25662  SimulateIOError( return SQLITE_IOERR_ACCESS; );
25663  switch( flags ){
25664    case SQLITE_ACCESS_EXISTS:
25665      amode = F_OK;
25666      break;
25667    case SQLITE_ACCESS_READWRITE:
25668      amode = W_OK|R_OK;
25669      break;
25670    case SQLITE_ACCESS_READ:
25671      amode = R_OK;
25672      break;
25673
25674    default:
25675      assert(!"Invalid flags argument");
25676  }
25677  *pResOut = (access(zPath, amode)==0);
25678  return SQLITE_OK;
25679}
25680
25681
25682/*
25683** Turn a relative pathname into a full pathname. The relative path
25684** is stored as a nul-terminated string in the buffer pointed to by
25685** zPath.
25686**
25687** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
25688** (in this case, MAX_PATHNAME bytes). The full-path is written to
25689** this buffer before returning.
25690*/
25691static int unixFullPathname(
25692  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
25693  const char *zPath,            /* Possibly relative input path */
25694  int nOut,                     /* Size of output buffer in bytes */
25695  char *zOut                    /* Output buffer */
25696){
25697
25698  /* It's odd to simulate an io-error here, but really this is just
25699  ** using the io-error infrastructure to test that SQLite handles this
25700  ** function failing. This function could fail if, for example, the
25701  ** current working directory has been unlinked.
25702  */
25703  SimulateIOError( return SQLITE_ERROR );
25704
25705  assert( pVfs->mxPathname==MAX_PATHNAME );
25706  UNUSED_PARAMETER(pVfs);
25707
25708  zOut[nOut-1] = '\0';
25709  if( zPath[0]=='/' ){
25710    sqlite3_snprintf(nOut, zOut, "%s", zPath);
25711  }else{
25712    int nCwd;
25713    if( getcwd(zOut, nOut-1)==0 ){
25714      return SQLITE_CANTOPEN;
25715    }
25716    nCwd = (int)strlen(zOut);
25717    sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
25718  }
25719  return SQLITE_OK;
25720}
25721
25722
25723#ifndef SQLITE_OMIT_LOAD_EXTENSION
25724/*
25725** Interfaces for opening a shared library, finding entry points
25726** within the shared library, and closing the shared library.
25727*/
25728#include <dlfcn.h>
25729static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
25730  UNUSED_PARAMETER(NotUsed);
25731  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
25732}
25733
25734/*
25735** SQLite calls this function immediately after a call to unixDlSym() or
25736** unixDlOpen() fails (returns a null pointer). If a more detailed error
25737** message is available, it is written to zBufOut. If no error message
25738** is available, zBufOut is left unmodified and SQLite uses a default
25739** error message.
25740*/
25741static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
25742  char *zErr;
25743  UNUSED_PARAMETER(NotUsed);
25744  unixEnterMutex();
25745  zErr = dlerror();
25746  if( zErr ){
25747    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
25748  }
25749  unixLeaveMutex();
25750}
25751static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
25752  /*
25753  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
25754  ** cast into a pointer to a function.  And yet the library dlsym() routine
25755  ** returns a void* which is really a pointer to a function.  So how do we
25756  ** use dlsym() with -pedantic-errors?
25757  **
25758  ** Variable x below is defined to be a pointer to a function taking
25759  ** parameters void* and const char* and returning a pointer to a function.
25760  ** We initialize x by assigning it a pointer to the dlsym() function.
25761  ** (That assignment requires a cast.)  Then we call the function that
25762  ** x points to.
25763  **
25764  ** This work-around is unlikely to work correctly on any system where
25765  ** you really cannot cast a function pointer into void*.  But then, on the
25766  ** other hand, dlsym() will not work on such a system either, so we have
25767  ** not really lost anything.
25768  */
25769  void (*(*x)(void*,const char*))(void);
25770  UNUSED_PARAMETER(NotUsed);
25771  x = (void(*(*)(void*,const char*))(void))dlsym;
25772  return (*x)(p, zSym);
25773}
25774static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
25775  UNUSED_PARAMETER(NotUsed);
25776  dlclose(pHandle);
25777}
25778#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
25779  #define unixDlOpen  0
25780  #define unixDlError 0
25781  #define unixDlSym   0
25782  #define unixDlClose 0
25783#endif
25784
25785/*
25786** Write nBuf bytes of random data to the supplied buffer zBuf.
25787*/
25788static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
25789  UNUSED_PARAMETER(NotUsed);
25790  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
25791
25792  /* We have to initialize zBuf to prevent valgrind from reporting
25793  ** errors.  The reports issued by valgrind are incorrect - we would
25794  ** prefer that the randomness be increased by making use of the
25795  ** uninitialized space in zBuf - but valgrind errors tend to worry
25796  ** some users.  Rather than argue, it seems easier just to initialize
25797  ** the whole array and silence valgrind, even if that means less randomness
25798  ** in the random seed.
25799  **
25800  ** When testing, initializing zBuf[] to zero is all we do.  That means
25801  ** that we always use the same random number sequence.  This makes the
25802  ** tests repeatable.
25803  */
25804  memset(zBuf, 0, nBuf);
25805#if !defined(SQLITE_TEST)
25806  {
25807    int pid, fd;
25808    fd = open("/dev/urandom", O_RDONLY);
25809    if( fd<0 ){
25810      time_t t;
25811      time(&t);
25812      memcpy(zBuf, &t, sizeof(t));
25813      pid = getpid();
25814      memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
25815      assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
25816      nBuf = sizeof(t) + sizeof(pid);
25817    }else{
25818      nBuf = read(fd, zBuf, nBuf);
25819      close(fd);
25820    }
25821  }
25822#endif
25823  return nBuf;
25824}
25825
25826
25827/*
25828** Sleep for a little while.  Return the amount of time slept.
25829** The argument is the number of microseconds we want to sleep.
25830** The return value is the number of microseconds of sleep actually
25831** requested from the underlying operating system, a number which
25832** might be greater than or equal to the argument, but not less
25833** than the argument.
25834*/
25835static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
25836#if OS_VXWORKS
25837  struct timespec sp;
25838
25839  sp.tv_sec = microseconds / 1000000;
25840  sp.tv_nsec = (microseconds % 1000000) * 1000;
25841  nanosleep(&sp, NULL);
25842  UNUSED_PARAMETER(NotUsed);
25843  return microseconds;
25844#elif defined(HAVE_USLEEP) && HAVE_USLEEP
25845  usleep(microseconds);
25846  UNUSED_PARAMETER(NotUsed);
25847  return microseconds;
25848#else
25849  int seconds = (microseconds+999999)/1000000;
25850  sleep(seconds);
25851  UNUSED_PARAMETER(NotUsed);
25852  return seconds*1000000;
25853#endif
25854}
25855
25856/*
25857** The following variable, if set to a non-zero value, is interpreted as
25858** the number of seconds since 1970 and is used to set the result of
25859** sqlite3OsCurrentTime() during testing.
25860*/
25861#ifdef SQLITE_TEST
25862SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
25863#endif
25864
25865/*
25866** Find the current time (in Universal Coordinated Time).  Write the
25867** current time and date as a Julian Day number into *prNow and
25868** return 0.  Return 1 if the time and date cannot be found.
25869*/
25870static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
25871#if defined(SQLITE_OMIT_FLOATING_POINT)
25872  time_t t;
25873  time(&t);
25874  *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
25875#elif defined(NO_GETTOD)
25876  time_t t;
25877  time(&t);
25878  *prNow = t/86400.0 + 2440587.5;
25879#elif OS_VXWORKS
25880  struct timespec sNow;
25881  clock_gettime(CLOCK_REALTIME, &sNow);
25882  *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
25883#else
25884  struct timeval sNow;
25885  gettimeofday(&sNow, 0);
25886  *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
25887#endif
25888
25889#ifdef SQLITE_TEST
25890  if( sqlite3_current_time ){
25891    *prNow = sqlite3_current_time/86400.0 + 2440587.5;
25892  }
25893#endif
25894  UNUSED_PARAMETER(NotUsed);
25895  return 0;
25896}
25897
25898/*
25899** We added the xGetLastError() method with the intention of providing
25900** better low-level error messages when operating-system problems come up
25901** during SQLite operation.  But so far, none of that has been implemented
25902** in the core.  So this routine is never called.  For now, it is merely
25903** a place-holder.
25904*/
25905static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
25906  UNUSED_PARAMETER(NotUsed);
25907  UNUSED_PARAMETER(NotUsed2);
25908  UNUSED_PARAMETER(NotUsed3);
25909  return 0;
25910}
25911
25912/*
25913************************ End of sqlite3_vfs methods ***************************
25914******************************************************************************/
25915
25916/******************************************************************************
25917************************** Begin Proxy Locking ********************************
25918**
25919** Proxy locking is a "uber-locking-method" in this sense:  It uses the
25920** other locking methods on secondary lock files.  Proxy locking is a
25921** meta-layer over top of the primitive locking implemented above.  For
25922** this reason, the division that implements of proxy locking is deferred
25923** until late in the file (here) after all of the other I/O methods have
25924** been defined - so that the primitive locking methods are available
25925** as services to help with the implementation of proxy locking.
25926**
25927****
25928**
25929** The default locking schemes in SQLite use byte-range locks on the
25930** database file to coordinate safe, concurrent access by multiple readers
25931** and writers [http://sqlite.org/lockingv3.html].  The five file locking
25932** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
25933** as POSIX read & write locks over fixed set of locations (via fsctl),
25934** on AFP and SMB only exclusive byte-range locks are available via fsctl
25935** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
25936** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
25937** address in the shared range is taken for a SHARED lock, the entire
25938** shared range is taken for an EXCLUSIVE lock):
25939**
25940**      PENDING_BYTE        0x40000000
25941**      RESERVED_BYTE       0x40000001
25942**      SHARED_RANGE        0x40000002 -> 0x40000200
25943**
25944** This works well on the local file system, but shows a nearly 100x
25945** slowdown in read performance on AFP because the AFP client disables
25946** the read cache when byte-range locks are present.  Enabling the read
25947** cache exposes a cache coherency problem that is present on all OS X
25948** supported network file systems.  NFS and AFP both observe the
25949** close-to-open semantics for ensuring cache coherency
25950** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
25951** address the requirements for concurrent database access by multiple
25952** readers and writers
25953** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
25954**
25955** To address the performance and cache coherency issues, proxy file locking
25956** changes the way database access is controlled by limiting access to a
25957** single host at a time and moving file locks off of the database file
25958** and onto a proxy file on the local file system.
25959**
25960**
25961** Using proxy locks
25962** -----------------
25963**
25964** C APIs
25965**
25966**  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
25967**                       <proxy_path> | ":auto:");
25968**  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
25969**
25970**
25971** SQL pragmas
25972**
25973**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
25974**  PRAGMA [database.]lock_proxy_file
25975**
25976** Specifying ":auto:" means that if there is a conch file with a matching
25977** host ID in it, the proxy path in the conch file will be used, otherwise
25978** a proxy path based on the user's temp dir
25979** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
25980** actual proxy file name is generated from the name and path of the
25981** database file.  For example:
25982**
25983**       For database path "/Users/me/foo.db"
25984**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
25985**
25986** Once a lock proxy is configured for a database connection, it can not
25987** be removed, however it may be switched to a different proxy path via
25988** the above APIs (assuming the conch file is not being held by another
25989** connection or process).
25990**
25991**
25992** How proxy locking works
25993** -----------------------
25994**
25995** Proxy file locking relies primarily on two new supporting files:
25996**
25997**   *  conch file to limit access to the database file to a single host
25998**      at a time
25999**
26000**   *  proxy file to act as a proxy for the advisory locks normally
26001**      taken on the database
26002**
26003** The conch file - to use a proxy file, sqlite must first "hold the conch"
26004** by taking an sqlite-style shared lock on the conch file, reading the
26005** contents and comparing the host's unique host ID (see below) and lock
26006** proxy path against the values stored in the conch.  The conch file is
26007** stored in the same directory as the database file and the file name
26008** is patterned after the database file name as ".<databasename>-conch".
26009** If the conch file does not exist, or it's contents do not match the
26010** host ID and/or proxy path, then the lock is escalated to an exclusive
26011** lock and the conch file contents is updated with the host ID and proxy
26012** path and the lock is downgraded to a shared lock again.  If the conch
26013** is held by another process (with a shared lock), the exclusive lock
26014** will fail and SQLITE_BUSY is returned.
26015**
26016** The proxy file - a single-byte file used for all advisory file locks
26017** normally taken on the database file.   This allows for safe sharing
26018** of the database file for multiple readers and writers on the same
26019** host (the conch ensures that they all use the same local lock file).
26020**
26021** There is a third file - the host ID file - used as a persistent record
26022** of a unique identifier for the host, a 128-byte unique host id file
26023** in the path defined by the HOSTIDPATH macro (default value is
26024** /Library/Caches/.com.apple.sqliteConchHostId).
26025**
26026** Requesting the lock proxy does not immediately take the conch, it is
26027** only taken when the first request to lock database file is made.
26028** This matches the semantics of the traditional locking behavior, where
26029** opening a connection to a database file does not take a lock on it.
26030** The shared lock and an open file descriptor are maintained until
26031** the connection to the database is closed.
26032**
26033** The proxy file and the lock file are never deleted so they only need
26034** to be created the first time they are used.
26035**
26036** Configuration options
26037** ---------------------
26038**
26039**  SQLITE_PREFER_PROXY_LOCKING
26040**
26041**       Database files accessed on non-local file systems are
26042**       automatically configured for proxy locking, lock files are
26043**       named automatically using the same logic as
26044**       PRAGMA lock_proxy_file=":auto:"
26045**
26046**  SQLITE_PROXY_DEBUG
26047**
26048**       Enables the logging of error messages during host id file
26049**       retrieval and creation
26050**
26051**  HOSTIDPATH
26052**
26053**       Overrides the default host ID file path location
26054**
26055**  LOCKPROXYDIR
26056**
26057**       Overrides the default directory used for lock proxy files that
26058**       are named automatically via the ":auto:" setting
26059**
26060**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
26061**
26062**       Permissions to use when creating a directory for storing the
26063**       lock proxy files, only used when LOCKPROXYDIR is not set.
26064**
26065**
26066** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
26067** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
26068** force proxy locking to be used for every database file opened, and 0
26069** will force automatic proxy locking to be disabled for all database
26070** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
26071** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
26072*/
26073
26074/*
26075** Proxy locking is only available on MacOSX
26076*/
26077#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26078
26079#ifdef SQLITE_TEST
26080/* simulate multiple hosts by creating unique hostid file paths */
26081SQLITE_API int sqlite3_hostid_num = 0;
26082#endif
26083
26084/*
26085** The proxyLockingContext has the path and file structures for the remote
26086** and local proxy files in it
26087*/
26088typedef struct proxyLockingContext proxyLockingContext;
26089struct proxyLockingContext {
26090  unixFile *conchFile;         /* Open conch file */
26091  char *conchFilePath;         /* Name of the conch file */
26092  unixFile *lockProxy;         /* Open proxy lock file */
26093  char *lockProxyPath;         /* Name of the proxy lock file */
26094  char *dbPath;                /* Name of the open file */
26095  int conchHeld;               /* True if the conch is currently held */
26096  void *oldLockingContext;     /* Original lockingcontext to restore on close */
26097  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
26098};
26099
26100/* HOSTIDLEN and CONCHLEN both include space for the string
26101** terminating nul
26102*/
26103#define HOSTIDLEN         128
26104#define CONCHLEN          (MAXPATHLEN+HOSTIDLEN+1)
26105#ifndef HOSTIDPATH
26106# define HOSTIDPATH       "/Library/Caches/.com.apple.sqliteConchHostId"
26107#endif
26108
26109/* basically a copy of unixRandomness with different
26110** test behavior built in */
26111static int proxyGenerateHostID(char *pHostID){
26112  int pid, fd, len;
26113  unsigned char *key = (unsigned char *)pHostID;
26114
26115  memset(key, 0, HOSTIDLEN);
26116  len = 0;
26117  fd = open("/dev/urandom", O_RDONLY);
26118  if( fd>=0 ){
26119    len = read(fd, key, HOSTIDLEN);
26120    close(fd); /* silently leak the fd if it fails */
26121  }
26122  if( len < HOSTIDLEN ){
26123    time_t t;
26124    time(&t);
26125    memcpy(key, &t, sizeof(t));
26126    pid = getpid();
26127    memcpy(&key[sizeof(t)], &pid, sizeof(pid));
26128  }
26129
26130#ifdef MAKE_PRETTY_HOSTID
26131  {
26132    int i;
26133    /* filter the bytes into printable ascii characters and NUL terminate */
26134    key[(HOSTIDLEN-1)] = 0x00;
26135    for( i=0; i<(HOSTIDLEN-1); i++ ){
26136      unsigned char pa = key[i]&0x7F;
26137      if( pa<0x20 ){
26138        key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
26139      }else if( pa==0x7F ){
26140        key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
26141      }
26142    }
26143  }
26144#endif
26145  return SQLITE_OK;
26146}
26147
26148/* writes the host id path to path, path should be an pre-allocated buffer
26149** with enough space for a path
26150*/
26151static void proxyGetHostIDPath(char *path, size_t len){
26152  strlcpy(path, HOSTIDPATH, len);
26153#ifdef SQLITE_TEST
26154  if( sqlite3_hostid_num>0 ){
26155    char suffix[2] = "1";
26156    suffix[0] = suffix[0] + sqlite3_hostid_num;
26157    strlcat(path, suffix, len);
26158  }
26159#endif
26160  OSTRACE3("GETHOSTIDPATH  %s pid=%d\n", path, getpid());
26161}
26162
26163/* get the host ID from a sqlite hostid file stored in the
26164** user-specific tmp directory, create the ID if it's not there already
26165*/
26166static int proxyGetHostID(char *pHostID, int *pError){
26167  int fd;
26168  char path[MAXPATHLEN];
26169  size_t len;
26170  int rc=SQLITE_OK;
26171
26172  proxyGetHostIDPath(path, MAXPATHLEN);
26173  /* try to create the host ID file, if it already exists read the contents */
26174  fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
26175  if( fd<0 ){
26176    int err=errno;
26177
26178    if( err!=EEXIST ){
26179#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
26180      fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
26181              path, strerror(err));
26182#endif
26183      return SQLITE_PERM;
26184    }
26185    /* couldn't create the file, read it instead */
26186    fd = open(path, O_RDONLY|O_EXCL);
26187    if( fd<0 ){
26188#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
26189      int err = errno;
26190      fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
26191              path, strerror(err));
26192#endif
26193      return SQLITE_PERM;
26194    }
26195    len = pread(fd, pHostID, HOSTIDLEN, 0);
26196    if( len<0 ){
26197      *pError = errno;
26198      rc = SQLITE_IOERR_READ;
26199    }else if( len<HOSTIDLEN ){
26200      *pError = 0;
26201      rc = SQLITE_IOERR_SHORT_READ;
26202    }
26203    close(fd); /* silently leak the fd if it fails */
26204    OSTRACE3("GETHOSTID  read %s pid=%d\n", pHostID, getpid());
26205    return rc;
26206  }else{
26207    /* we're creating the host ID file (use a random string of bytes) */
26208    proxyGenerateHostID(pHostID);
26209    len = pwrite(fd, pHostID, HOSTIDLEN, 0);
26210    if( len<0 ){
26211      *pError = errno;
26212      rc = SQLITE_IOERR_WRITE;
26213    }else if( len<HOSTIDLEN ){
26214      *pError = 0;
26215      rc = SQLITE_IOERR_WRITE;
26216    }
26217    close(fd); /* silently leak the fd if it fails */
26218    OSTRACE3("GETHOSTID  wrote %s pid=%d\n", pHostID, getpid());
26219    return rc;
26220  }
26221}
26222
26223static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
26224  int len;
26225  int dbLen;
26226  int i;
26227
26228#ifdef LOCKPROXYDIR
26229  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
26230#else
26231# ifdef _CS_DARWIN_USER_TEMP_DIR
26232  {
26233    confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
26234    len = strlcat(lPath, "sqliteplocks", maxLen);
26235    if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
26236      /* if mkdir fails, handle as lock file creation failure */
26237#  ifdef SQLITE_DEBUG
26238      int err = errno;
26239      if( err!=EEXIST ){
26240        fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
26241                SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
26242      }
26243#  endif
26244    }else{
26245      OSTRACE3("GETLOCKPATH  mkdir %s pid=%d\n", lPath, getpid());
26246    }
26247
26248  }
26249# else
26250  len = strlcpy(lPath, "/tmp/", maxLen);
26251# endif
26252#endif
26253
26254  if( lPath[len-1]!='/' ){
26255    len = strlcat(lPath, "/", maxLen);
26256  }
26257
26258  /* transform the db path to a unique cache name */
26259  dbLen = (int)strlen(dbPath);
26260  for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
26261    char c = dbPath[i];
26262    lPath[i+len] = (c=='/')?'_':c;
26263  }
26264  lPath[i+len]='\0';
26265  strlcat(lPath, ":auto:", maxLen);
26266  return SQLITE_OK;
26267}
26268
26269/*
26270** Create a new VFS file descriptor (stored in memory obtained from
26271** sqlite3_malloc) and open the file named "path" in the file descriptor.
26272**
26273** The caller is responsible not only for closing the file descriptor
26274** but also for freeing the memory associated with the file descriptor.
26275*/
26276static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
26277  unixFile *pNew;
26278  int flags = SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
26279  int rc = SQLITE_OK;
26280  sqlite3_vfs dummyVfs;
26281
26282  pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
26283  if( !pNew ){
26284    return SQLITE_NOMEM;
26285  }
26286  memset(pNew, 0, sizeof(unixFile));
26287
26288  /* Call unixOpen() to open the proxy file. The flags passed to unixOpen()
26289  ** suggest that the file being opened is a "main database". This is
26290  ** necessary as other file types do not necessarily support locking. It
26291  ** is better to use unixOpen() instead of opening the file directly with
26292  ** open(), as unixOpen() sets up the various mechanisms required to
26293  ** make sure a call to close() does not cause the system to discard
26294  ** POSIX locks prematurely.
26295  **
26296  ** It is important that the xOpen member of the VFS object passed to
26297  ** unixOpen() is NULL. This tells unixOpen() may try to open a proxy-file
26298  ** for the proxy-file (creating a potential infinite loop).
26299  */
26300  dummyVfs.pAppData = (void*)&autolockIoFinder;
26301  dummyVfs.xOpen = 0;
26302  rc = unixOpen(&dummyVfs, path, (sqlite3_file *)pNew, flags, &flags);
26303  if( rc==SQLITE_OK && (flags&SQLITE_OPEN_READONLY) ){
26304    pNew->pMethod->xClose((sqlite3_file *)pNew);
26305    rc = SQLITE_CANTOPEN;
26306  }
26307
26308  if( rc!=SQLITE_OK ){
26309    sqlite3_free(pNew);
26310    pNew = 0;
26311  }
26312
26313  *ppFile = pNew;
26314  return rc;
26315}
26316
26317/* takes the conch by taking a shared lock and read the contents conch, if
26318** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
26319** lockPath means that the lockPath in the conch file will be used if the
26320** host IDs match, or a new lock path will be generated automatically
26321** and written to the conch file.
26322*/
26323static int proxyTakeConch(unixFile *pFile){
26324  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26325
26326  if( pCtx->conchHeld>0 ){
26327    return SQLITE_OK;
26328  }else{
26329    unixFile *conchFile = pCtx->conchFile;
26330    char testValue[CONCHLEN];
26331    char conchValue[CONCHLEN];
26332    char lockPath[MAXPATHLEN];
26333    char *tLockPath = NULL;
26334    int rc = SQLITE_OK;
26335    int readRc = SQLITE_OK;
26336    int syncPerms = 0;
26337
26338    OSTRACE4("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
26339             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
26340
26341    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
26342    if( rc==SQLITE_OK ){
26343      int pError = 0;
26344      memset(testValue, 0, CONCHLEN); /* conch is fixed size */
26345      rc = proxyGetHostID(testValue, &pError);
26346      if( (rc&0xff)==SQLITE_IOERR ){
26347        pFile->lastErrno = pError;
26348      }
26349      if( pCtx->lockProxyPath ){
26350        strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
26351      }
26352    }
26353    if( rc!=SQLITE_OK ){
26354      goto end_takeconch;
26355    }
26356
26357    readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
26358    if( readRc!=SQLITE_IOERR_SHORT_READ ){
26359      if( readRc!=SQLITE_OK ){
26360        if( (rc&0xff)==SQLITE_IOERR ){
26361          pFile->lastErrno = conchFile->lastErrno;
26362        }
26363        rc = readRc;
26364        goto end_takeconch;
26365      }
26366      /* if the conch has data compare the contents */
26367      if( !pCtx->lockProxyPath ){
26368        /* for auto-named local lock file, just check the host ID and we'll
26369         ** use the local lock file path that's already in there */
26370        if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
26371          tLockPath = (char *)&conchValue[HOSTIDLEN];
26372          goto end_takeconch;
26373        }
26374      }else{
26375        /* we've got the conch if conchValue matches our path and host ID */
26376        if( !memcmp(testValue, conchValue, CONCHLEN) ){
26377          goto end_takeconch;
26378        }
26379      }
26380    }else{
26381      /* a short read means we're "creating" the conch (even though it could
26382      ** have been user-intervention), if we acquire the exclusive lock,
26383      ** we'll try to match the current on-disk permissions of the database
26384      */
26385      syncPerms = 1;
26386    }
26387
26388    /* either conch was emtpy or didn't match */
26389    if( !pCtx->lockProxyPath ){
26390      proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
26391      tLockPath = lockPath;
26392      strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
26393    }
26394
26395    /* update conch with host and path (this will fail if other process
26396     ** has a shared lock already) */
26397    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
26398    if( rc==SQLITE_OK ){
26399      rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
26400      if( rc==SQLITE_OK && syncPerms ){
26401        struct stat buf;
26402        int err = fstat(pFile->h, &buf);
26403        if( err==0 ){
26404          /* try to match the database file permissions, ignore failure */
26405#ifndef SQLITE_PROXY_DEBUG
26406          fchmod(conchFile->h, buf.st_mode);
26407#else
26408          if( fchmod(conchFile->h, buf.st_mode)!=0 ){
26409            int code = errno;
26410            fprintf(stderr, "fchmod %o FAILED with %d %s\n",
26411                             buf.st_mode, code, strerror(code));
26412          } else {
26413            fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
26414          }
26415        }else{
26416          int code = errno;
26417          fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
26418                          err, code, strerror(code));
26419#endif
26420        }
26421      }
26422    }
26423    conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
26424
26425end_takeconch:
26426    OSTRACE2("TRANSPROXY: CLOSE  %d\n", pFile->h);
26427    if( rc==SQLITE_OK && pFile->openFlags ){
26428      if( pFile->h>=0 ){
26429#ifdef STRICT_CLOSE_ERROR
26430        if( close(pFile->h) ){
26431          pFile->lastErrno = errno;
26432          return SQLITE_IOERR_CLOSE;
26433        }
26434#else
26435        close(pFile->h); /* silently leak fd if fail */
26436#endif
26437      }
26438      pFile->h = -1;
26439      int fd = open(pCtx->dbPath, pFile->openFlags,
26440                    SQLITE_DEFAULT_FILE_PERMISSIONS);
26441      OSTRACE2("TRANSPROXY: OPEN  %d\n", fd);
26442      if( fd>=0 ){
26443        pFile->h = fd;
26444      }else{
26445        rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
26446                               during locking */
26447      }
26448    }
26449    if( rc==SQLITE_OK && !pCtx->lockProxy ){
26450      char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
26451      /* ACS: Need to make a copy of path sometimes */
26452      rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
26453    }
26454    if( rc==SQLITE_OK ){
26455      pCtx->conchHeld = 1;
26456
26457      if( tLockPath ){
26458        pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
26459        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
26460          ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
26461                     pCtx->lockProxyPath;
26462        }
26463      }
26464    } else {
26465      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
26466    }
26467    OSTRACE3("TAKECONCH  %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
26468    return rc;
26469  }
26470}
26471
26472/*
26473** If pFile holds a lock on a conch file, then release that lock.
26474*/
26475static int proxyReleaseConch(unixFile *pFile){
26476  int rc;                     /* Subroutine return code */
26477  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
26478  unixFile *conchFile;        /* Name of the conch file */
26479
26480  pCtx = (proxyLockingContext *)pFile->lockingContext;
26481  conchFile = pCtx->conchFile;
26482  OSTRACE4("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
26483           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
26484           getpid());
26485  pCtx->conchHeld = 0;
26486  rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
26487  OSTRACE3("RELEASECONCH  %d %s\n", conchFile->h,
26488           (rc==SQLITE_OK ? "ok" : "failed"));
26489  return rc;
26490}
26491
26492/*
26493** Given the name of a database file, compute the name of its conch file.
26494** Store the conch filename in memory obtained from sqlite3_malloc().
26495** Make *pConchPath point to the new name.  Return SQLITE_OK on success
26496** or SQLITE_NOMEM if unable to obtain memory.
26497**
26498** The caller is responsible for ensuring that the allocated memory
26499** space is eventually freed.
26500**
26501** *pConchPath is set to NULL if a memory allocation error occurs.
26502*/
26503static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
26504  int i;                        /* Loop counter */
26505  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
26506  char *conchPath;              /* buffer in which to construct conch name */
26507
26508  /* Allocate space for the conch filename and initialize the name to
26509  ** the name of the original database file. */
26510  *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
26511  if( conchPath==0 ){
26512    return SQLITE_NOMEM;
26513  }
26514  memcpy(conchPath, dbPath, len+1);
26515
26516  /* now insert a "." before the last / character */
26517  for( i=(len-1); i>=0; i-- ){
26518    if( conchPath[i]=='/' ){
26519      i++;
26520      break;
26521    }
26522  }
26523  conchPath[i]='.';
26524  while ( i<len ){
26525    conchPath[i+1]=dbPath[i];
26526    i++;
26527  }
26528
26529  /* append the "-conch" suffix to the file */
26530  memcpy(&conchPath[i+1], "-conch", 7);
26531  assert( (int)strlen(conchPath) == len+7 );
26532
26533  return SQLITE_OK;
26534}
26535
26536
26537/* Takes a fully configured proxy locking-style unix file and switches
26538** the local lock file path
26539*/
26540static int switchLockProxyPath(unixFile *pFile, const char *path) {
26541  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
26542  char *oldPath = pCtx->lockProxyPath;
26543  int rc = SQLITE_OK;
26544
26545  if( pFile->locktype!=NO_LOCK ){
26546    return SQLITE_BUSY;
26547  }
26548
26549  /* nothing to do if the path is NULL, :auto: or matches the existing path */
26550  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
26551    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
26552    return SQLITE_OK;
26553  }else{
26554    unixFile *lockProxy = pCtx->lockProxy;
26555    pCtx->lockProxy=NULL;
26556    pCtx->conchHeld = 0;
26557    if( lockProxy!=NULL ){
26558      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
26559      if( rc ) return rc;
26560      sqlite3_free(lockProxy);
26561    }
26562    sqlite3_free(oldPath);
26563    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
26564  }
26565
26566  return rc;
26567}
26568
26569/*
26570** pFile is a file that has been opened by a prior xOpen call.  dbPath
26571** is a string buffer at least MAXPATHLEN+1 characters in size.
26572**
26573** This routine find the filename associated with pFile and writes it
26574** int dbPath.
26575*/
26576static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
26577#if defined(__APPLE__)
26578  if( pFile->pMethod == &afpIoMethods ){
26579    /* afp style keeps a reference to the db path in the filePath field
26580    ** of the struct */
26581    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
26582    strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
26583  }else
26584#endif
26585  if( pFile->pMethod == &dotlockIoMethods ){
26586    /* dot lock style uses the locking context to store the dot lock
26587    ** file path */
26588    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
26589    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
26590  }else{
26591    /* all other styles use the locking context to store the db file path */
26592    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
26593    strcpy(dbPath, (char *)pFile->lockingContext);
26594  }
26595  return SQLITE_OK;
26596}
26597
26598/*
26599** Takes an already filled in unix file and alters it so all file locking
26600** will be performed on the local proxy lock file.  The following fields
26601** are preserved in the locking context so that they can be restored and
26602** the unix structure properly cleaned up at close time:
26603**  ->lockingContext
26604**  ->pMethod
26605*/
26606static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
26607  proxyLockingContext *pCtx;
26608  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
26609  char *lockPath=NULL;
26610  int rc = SQLITE_OK;
26611
26612  if( pFile->locktype!=NO_LOCK ){
26613    return SQLITE_BUSY;
26614  }
26615  proxyGetDbPathForUnixFile(pFile, dbPath);
26616  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
26617    lockPath=NULL;
26618  }else{
26619    lockPath=(char *)path;
26620  }
26621
26622  OSTRACE4("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
26623           (lockPath ? lockPath : ":auto:"), getpid());
26624
26625  pCtx = sqlite3_malloc( sizeof(*pCtx) );
26626  if( pCtx==0 ){
26627    return SQLITE_NOMEM;
26628  }
26629  memset(pCtx, 0, sizeof(*pCtx));
26630
26631  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
26632  if( rc==SQLITE_OK ){
26633    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
26634  }
26635  if( rc==SQLITE_OK && lockPath ){
26636    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
26637  }
26638
26639  if( rc==SQLITE_OK ){
26640    /* all memory is allocated, proxys are created and assigned,
26641    ** switch the locking context and pMethod then return.
26642    */
26643    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
26644    pCtx->oldLockingContext = pFile->lockingContext;
26645    pFile->lockingContext = pCtx;
26646    pCtx->pOldMethod = pFile->pMethod;
26647    pFile->pMethod = &proxyIoMethods;
26648  }else{
26649    if( pCtx->conchFile ){
26650      rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
26651      if( rc ) return rc;
26652      sqlite3_free(pCtx->conchFile);
26653    }
26654    sqlite3_free(pCtx->conchFilePath);
26655    sqlite3_free(pCtx);
26656  }
26657  OSTRACE3("TRANSPROXY  %d %s\n", pFile->h,
26658           (rc==SQLITE_OK ? "ok" : "failed"));
26659  return rc;
26660}
26661
26662
26663/*
26664** This routine handles sqlite3_file_control() calls that are specific
26665** to proxy locking.
26666*/
26667static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
26668  switch( op ){
26669    case SQLITE_GET_LOCKPROXYFILE: {
26670      unixFile *pFile = (unixFile*)id;
26671      if( pFile->pMethod == &proxyIoMethods ){
26672        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
26673        proxyTakeConch(pFile);
26674        if( pCtx->lockProxyPath ){
26675          *(const char **)pArg = pCtx->lockProxyPath;
26676        }else{
26677          *(const char **)pArg = ":auto: (not held)";
26678        }
26679      } else {
26680        *(const char **)pArg = NULL;
26681      }
26682      return SQLITE_OK;
26683    }
26684    case SQLITE_SET_LOCKPROXYFILE: {
26685      unixFile *pFile = (unixFile*)id;
26686      int rc = SQLITE_OK;
26687      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
26688      if( pArg==NULL || (const char *)pArg==0 ){
26689        if( isProxyStyle ){
26690          /* turn off proxy locking - not supported */
26691          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
26692        }else{
26693          /* turn off proxy locking - already off - NOOP */
26694          rc = SQLITE_OK;
26695        }
26696      }else{
26697        const char *proxyPath = (const char *)pArg;
26698        if( isProxyStyle ){
26699          proxyLockingContext *pCtx =
26700            (proxyLockingContext*)pFile->lockingContext;
26701          if( !strcmp(pArg, ":auto:")
26702           || (pCtx->lockProxyPath &&
26703               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
26704          ){
26705            rc = SQLITE_OK;
26706          }else{
26707            rc = switchLockProxyPath(pFile, proxyPath);
26708          }
26709        }else{
26710          /* turn on proxy file locking */
26711          rc = proxyTransformUnixFile(pFile, proxyPath);
26712        }
26713      }
26714      return rc;
26715    }
26716    default: {
26717      assert( 0 );  /* The call assures that only valid opcodes are sent */
26718    }
26719  }
26720  /*NOTREACHED*/
26721  return SQLITE_ERROR;
26722}
26723
26724/*
26725** Within this division (the proxying locking implementation) the procedures
26726** above this point are all utilities.  The lock-related methods of the
26727** proxy-locking sqlite3_io_method object follow.
26728*/
26729
26730
26731/*
26732** This routine checks if there is a RESERVED lock held on the specified
26733** file by this or any other process. If such a lock is held, set *pResOut
26734** to a non-zero value otherwise *pResOut is set to zero.  The return value
26735** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26736*/
26737static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
26738  unixFile *pFile = (unixFile*)id;
26739  int rc = proxyTakeConch(pFile);
26740  if( rc==SQLITE_OK ){
26741    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26742    unixFile *proxy = pCtx->lockProxy;
26743    return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
26744  }
26745  return rc;
26746}
26747
26748/*
26749** Lock the file with the lock specified by parameter locktype - one
26750** of the following:
26751**
26752**     (1) SHARED_LOCK
26753**     (2) RESERVED_LOCK
26754**     (3) PENDING_LOCK
26755**     (4) EXCLUSIVE_LOCK
26756**
26757** Sometimes when requesting one lock state, additional lock states
26758** are inserted in between.  The locking might fail on one of the later
26759** transitions leaving the lock state different from what it started but
26760** still short of its goal.  The following chart shows the allowed
26761** transitions and the inserted intermediate states:
26762**
26763**    UNLOCKED -> SHARED
26764**    SHARED -> RESERVED
26765**    SHARED -> (PENDING) -> EXCLUSIVE
26766**    RESERVED -> (PENDING) -> EXCLUSIVE
26767**    PENDING -> EXCLUSIVE
26768**
26769** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26770** routine to lower a locking level.
26771*/
26772static int proxyLock(sqlite3_file *id, int locktype) {
26773  unixFile *pFile = (unixFile*)id;
26774  int rc = proxyTakeConch(pFile);
26775  if( rc==SQLITE_OK ){
26776    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26777    unixFile *proxy = pCtx->lockProxy;
26778    rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
26779    pFile->locktype = proxy->locktype;
26780  }
26781  return rc;
26782}
26783
26784
26785/*
26786** Lower the locking level on file descriptor pFile to locktype.  locktype
26787** must be either NO_LOCK or SHARED_LOCK.
26788**
26789** If the locking level of the file descriptor is already at or below
26790** the requested locking level, this routine is a no-op.
26791*/
26792static int proxyUnlock(sqlite3_file *id, int locktype) {
26793  unixFile *pFile = (unixFile*)id;
26794  int rc = proxyTakeConch(pFile);
26795  if( rc==SQLITE_OK ){
26796    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26797    unixFile *proxy = pCtx->lockProxy;
26798    rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
26799    pFile->locktype = proxy->locktype;
26800  }
26801  return rc;
26802}
26803
26804/*
26805** Close a file that uses proxy locks.
26806*/
26807static int proxyClose(sqlite3_file *id) {
26808  if( id ){
26809    unixFile *pFile = (unixFile*)id;
26810    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26811    unixFile *lockProxy = pCtx->lockProxy;
26812    unixFile *conchFile = pCtx->conchFile;
26813    int rc = SQLITE_OK;
26814
26815    if( lockProxy ){
26816      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
26817      if( rc ) return rc;
26818      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
26819      if( rc ) return rc;
26820      sqlite3_free(lockProxy);
26821      pCtx->lockProxy = 0;
26822    }
26823    if( conchFile ){
26824      if( pCtx->conchHeld ){
26825        rc = proxyReleaseConch(pFile);
26826        if( rc ) return rc;
26827      }
26828      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
26829      if( rc ) return rc;
26830      sqlite3_free(conchFile);
26831    }
26832    sqlite3_free(pCtx->lockProxyPath);
26833    sqlite3_free(pCtx->conchFilePath);
26834    sqlite3_free(pCtx->dbPath);
26835    /* restore the original locking context and pMethod then close it */
26836    pFile->lockingContext = pCtx->oldLockingContext;
26837    pFile->pMethod = pCtx->pOldMethod;
26838    sqlite3_free(pCtx);
26839    return pFile->pMethod->xClose(id);
26840  }
26841  return SQLITE_OK;
26842}
26843
26844
26845
26846#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26847/*
26848** The proxy locking style is intended for use with AFP filesystems.
26849** And since AFP is only supported on MacOSX, the proxy locking is also
26850** restricted to MacOSX.
26851**
26852**
26853******************* End of the proxy lock implementation **********************
26854******************************************************************************/
26855
26856/*
26857** Initialize the operating system interface.
26858**
26859** This routine registers all VFS implementations for unix-like operating
26860** systems.  This routine, and the sqlite3_os_end() routine that follows,
26861** should be the only routines in this file that are visible from other
26862** files.
26863**
26864** This routine is called once during SQLite initialization and by a
26865** single thread.  The memory allocation and mutex subsystems have not
26866** necessarily been initialized when this routine is called, and so they
26867** should not be used.
26868*/
26869SQLITE_API int sqlite3_os_init(void){
26870  /*
26871  ** The following macro defines an initializer for an sqlite3_vfs object.
26872  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
26873  ** to the "finder" function.  (pAppData is a pointer to a pointer because
26874  ** silly C90 rules prohibit a void* from being cast to a function pointer
26875  ** and so we have to go through the intermediate pointer to avoid problems
26876  ** when compiling with -pedantic-errors on GCC.)
26877  **
26878  ** The FINDER parameter to this macro is the name of the pointer to the
26879  ** finder-function.  The finder-function returns a pointer to the
26880  ** sqlite_io_methods object that implements the desired locking
26881  ** behaviors.  See the division above that contains the IOMETHODS
26882  ** macro for addition information on finder-functions.
26883  **
26884  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
26885  ** object.  But the "autolockIoFinder" available on MacOSX does a little
26886  ** more than that; it looks at the filesystem type that hosts the
26887  ** database file and tries to choose an locking method appropriate for
26888  ** that filesystem time.
26889  */
26890  #define UNIXVFS(VFSNAME, FINDER) {                        \
26891    1,                    /* iVersion */                    \
26892    sizeof(unixFile),     /* szOsFile */                    \
26893    MAX_PATHNAME,         /* mxPathname */                  \
26894    0,                    /* pNext */                       \
26895    VFSNAME,              /* zName */                       \
26896    (void*)&FINDER,       /* pAppData */                    \
26897    unixOpen,             /* xOpen */                       \
26898    unixDelete,           /* xDelete */                     \
26899    unixAccess,           /* xAccess */                     \
26900    unixFullPathname,     /* xFullPathname */               \
26901    unixDlOpen,           /* xDlOpen */                     \
26902    unixDlError,          /* xDlError */                    \
26903    unixDlSym,            /* xDlSym */                      \
26904    unixDlClose,          /* xDlClose */                    \
26905    unixRandomness,       /* xRandomness */                 \
26906    unixSleep,            /* xSleep */                      \
26907    unixCurrentTime,      /* xCurrentTime */                \
26908    unixGetLastError      /* xGetLastError */               \
26909  }
26910
26911  /*
26912  ** All default VFSes for unix are contained in the following array.
26913  **
26914  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
26915  ** by the SQLite core when the VFS is registered.  So the following
26916  ** array cannot be const.
26917  */
26918  static sqlite3_vfs aVfs[] = {
26919#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
26920    UNIXVFS("unix",          autolockIoFinder ),
26921#else
26922    UNIXVFS("unix",          posixIoFinder ),
26923#endif
26924    UNIXVFS("unix-none",     nolockIoFinder ),
26925    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
26926    UNIXVFS("unix-wfl",      posixWflIoFinder ),
26927#if OS_VXWORKS
26928    UNIXVFS("unix-namedsem", semIoFinder ),
26929#endif
26930#if SQLITE_ENABLE_LOCKING_STYLE
26931    UNIXVFS("unix-posix",    posixIoFinder ),
26932#if !OS_VXWORKS
26933    UNIXVFS("unix-flock",    flockIoFinder ),
26934#endif
26935#endif
26936#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26937    UNIXVFS("unix-afp",      afpIoFinder ),
26938    UNIXVFS("unix-proxy",    proxyIoFinder ),
26939#endif
26940  };
26941  unsigned int i;          /* Loop counter */
26942
26943  /* Register all VFSes defined in the aVfs[] array */
26944  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
26945    sqlite3_vfs_register(&aVfs[i], i==0);
26946  }
26947  return SQLITE_OK;
26948}
26949
26950/*
26951** Shutdown the operating system interface.
26952**
26953** Some operating systems might need to do some cleanup in this routine,
26954** to release dynamically allocated objects.  But not on unix.
26955** This routine is a no-op for unix.
26956*/
26957SQLITE_API int sqlite3_os_end(void){
26958  return SQLITE_OK;
26959}
26960
26961#endif /* SQLITE_OS_UNIX */
26962
26963/************** End of os_unix.c *********************************************/
26964/************** Begin file os_win.c ******************************************/
26965/*
26966** 2004 May 22
26967**
26968** The author disclaims copyright to this source code.  In place of
26969** a legal notice, here is a blessing:
26970**
26971**    May you do good and not evil.
26972**    May you find forgiveness for yourself and forgive others.
26973**    May you share freely, never taking more than you give.
26974**
26975******************************************************************************
26976**
26977** This file contains code that is specific to windows.
26978*/
26979#if SQLITE_OS_WIN               /* This file is used for windows only */
26980
26981
26982/*
26983** A Note About Memory Allocation:
26984**
26985** This driver uses malloc()/free() directly rather than going through
26986** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
26987** are designed for use on embedded systems where memory is scarce and
26988** malloc failures happen frequently.  Win32 does not typically run on
26989** embedded systems, and when it does the developers normally have bigger
26990** problems to worry about than running out of memory.  So there is not
26991** a compelling need to use the wrappers.
26992**
26993** But there is a good reason to not use the wrappers.  If we use the
26994** wrappers then we will get simulated malloc() failures within this
26995** driver.  And that causes all kinds of problems for our tests.  We
26996** could enhance SQLite to deal with simulated malloc failures within
26997** the OS driver, but the code to deal with those failure would not
26998** be exercised on Linux (which does not need to malloc() in the driver)
26999** and so we would have difficulty writing coverage tests for that
27000** code.  Better to leave the code out, we think.
27001**
27002** The point of this discussion is as follows:  When creating a new
27003** OS layer for an embedded system, if you use this file as an example,
27004** avoid the use of malloc()/free().  Those routines work ok on windows
27005** desktops but not so well in embedded systems.
27006*/
27007
27008#include <winbase.h>
27009
27010#ifdef __CYGWIN__
27011# include <sys/cygwin.h>
27012#endif
27013
27014/*
27015** Macros used to determine whether or not to use threads.
27016*/
27017#if defined(THREADSAFE) && THREADSAFE
27018# define SQLITE_W32_THREADS 1
27019#endif
27020
27021/*
27022** Include code that is common to all os_*.c files
27023*/
27024/************** Include os_common.h in the middle of os_win.c ****************/
27025/************** Begin file os_common.h ***************************************/
27026/*
27027** 2004 May 22
27028**
27029** The author disclaims copyright to this source code.  In place of
27030** a legal notice, here is a blessing:
27031**
27032**    May you do good and not evil.
27033**    May you find forgiveness for yourself and forgive others.
27034**    May you share freely, never taking more than you give.
27035**
27036******************************************************************************
27037**
27038** This file contains macros and a little bit of code that is common to
27039** all of the platform-specific files (os_*.c) and is #included into those
27040** files.
27041**
27042** This file should be #included by the os_*.c files only.  It is not a
27043** general purpose header file.
27044*/
27045#ifndef _OS_COMMON_H_
27046#define _OS_COMMON_H_
27047
27048/*
27049** At least two bugs have slipped in because we changed the MEMORY_DEBUG
27050** macro to SQLITE_DEBUG and some older makefiles have not yet made the
27051** switch.  The following code should catch this problem at compile-time.
27052*/
27053#ifdef MEMORY_DEBUG
27054# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
27055#endif
27056
27057#ifdef SQLITE_DEBUG
27058SQLITE_PRIVATE int sqlite3OSTrace = 0;
27059#define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
27060#define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
27061#define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
27062#define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
27063#define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
27064#define OSTRACE6(X,Y,Z,A,B,C) \
27065    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
27066#define OSTRACE7(X,Y,Z,A,B,C,D) \
27067    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
27068#else
27069#define OSTRACE1(X)
27070#define OSTRACE2(X,Y)
27071#define OSTRACE3(X,Y,Z)
27072#define OSTRACE4(X,Y,Z,A)
27073#define OSTRACE5(X,Y,Z,A,B)
27074#define OSTRACE6(X,Y,Z,A,B,C)
27075#define OSTRACE7(X,Y,Z,A,B,C,D)
27076#endif
27077
27078/*
27079** Macros for performance tracing.  Normally turned off.  Only works
27080** on i486 hardware.
27081*/
27082#ifdef SQLITE_PERFORMANCE_TRACE
27083
27084/*
27085** hwtime.h contains inline assembler code for implementing
27086** high-performance timing routines.
27087*/
27088/************** Include hwtime.h in the middle of os_common.h ****************/
27089/************** Begin file hwtime.h ******************************************/
27090/*
27091** 2008 May 27
27092**
27093** The author disclaims copyright to this source code.  In place of
27094** a legal notice, here is a blessing:
27095**
27096**    May you do good and not evil.
27097**    May you find forgiveness for yourself and forgive others.
27098**    May you share freely, never taking more than you give.
27099**
27100******************************************************************************
27101**
27102** This file contains inline asm code for retrieving "high-performance"
27103** counters for x86 class CPUs.
27104*/
27105#ifndef _HWTIME_H_
27106#define _HWTIME_H_
27107
27108/*
27109** The following routine only works on pentium-class (or newer) processors.
27110** It uses the RDTSC opcode to read the cycle count value out of the
27111** processor and returns that value.  This can be used for high-res
27112** profiling.
27113*/
27114#if (defined(__GNUC__) || defined(_MSC_VER)) && \
27115      (defined(i386) || defined(__i386__) || defined(_M_IX86))
27116
27117  #if defined(__GNUC__)
27118
27119  __inline__ sqlite_uint64 sqlite3Hwtime(void){
27120     unsigned int lo, hi;
27121     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
27122     return (sqlite_uint64)hi << 32 | lo;
27123  }
27124
27125  #elif defined(_MSC_VER)
27126
27127  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
27128     __asm {
27129        rdtsc
27130        ret       ; return value at EDX:EAX
27131     }
27132  }
27133
27134  #endif
27135
27136#elif (defined(__GNUC__) && defined(__x86_64__))
27137
27138  __inline__ sqlite_uint64 sqlite3Hwtime(void){
27139      unsigned long val;
27140      __asm__ __volatile__ ("rdtsc" : "=A" (val));
27141      return val;
27142  }
27143
27144#elif (defined(__GNUC__) && defined(__ppc__))
27145
27146  __inline__ sqlite_uint64 sqlite3Hwtime(void){
27147      unsigned long long retval;
27148      unsigned long junk;
27149      __asm__ __volatile__ ("\n\
27150          1:      mftbu   %1\n\
27151                  mftb    %L0\n\
27152                  mftbu   %0\n\
27153                  cmpw    %0,%1\n\
27154                  bne     1b"
27155                  : "=r" (retval), "=r" (junk));
27156      return retval;
27157  }
27158
27159#else
27160
27161  #error Need implementation of sqlite3Hwtime() for your platform.
27162
27163  /*
27164  ** To compile without implementing sqlite3Hwtime() for your platform,
27165  ** you can remove the above #error and use the following
27166  ** stub function.  You will lose timing support for many
27167  ** of the debugging and testing utilities, but it should at
27168  ** least compile and run.
27169  */
27170SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
27171
27172#endif
27173
27174#endif /* !defined(_HWTIME_H_) */
27175
27176/************** End of hwtime.h **********************************************/
27177/************** Continuing where we left off in os_common.h ******************/
27178
27179static sqlite_uint64 g_start;
27180static sqlite_uint64 g_elapsed;
27181#define TIMER_START       g_start=sqlite3Hwtime()
27182#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
27183#define TIMER_ELAPSED     g_elapsed
27184#else
27185#define TIMER_START
27186#define TIMER_END
27187#define TIMER_ELAPSED     ((sqlite_uint64)0)
27188#endif
27189
27190/*
27191** If we compile with the SQLITE_TEST macro set, then the following block
27192** of code will give us the ability to simulate a disk I/O error.  This
27193** is used for testing the I/O recovery logic.
27194*/
27195#ifdef SQLITE_TEST
27196SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
27197SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
27198SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
27199SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
27200SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
27201SQLITE_API int sqlite3_diskfull_pending = 0;
27202SQLITE_API int sqlite3_diskfull = 0;
27203#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
27204#define SimulateIOError(CODE)  \
27205  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
27206       || sqlite3_io_error_pending-- == 1 )  \
27207              { local_ioerr(); CODE; }
27208static void local_ioerr(){
27209  IOTRACE(("IOERR\n"));
27210  sqlite3_io_error_hit++;
27211  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
27212}
27213#define SimulateDiskfullError(CODE) \
27214   if( sqlite3_diskfull_pending ){ \
27215     if( sqlite3_diskfull_pending == 1 ){ \
27216       local_ioerr(); \
27217       sqlite3_diskfull = 1; \
27218       sqlite3_io_error_hit = 1; \
27219       CODE; \
27220     }else{ \
27221       sqlite3_diskfull_pending--; \
27222     } \
27223   }
27224#else
27225#define SimulateIOErrorBenign(X)
27226#define SimulateIOError(A)
27227#define SimulateDiskfullError(A)
27228#endif
27229
27230/*
27231** When testing, keep a count of the number of open files.
27232*/
27233#ifdef SQLITE_TEST
27234SQLITE_API int sqlite3_open_file_count = 0;
27235#define OpenCounter(X)  sqlite3_open_file_count+=(X)
27236#else
27237#define OpenCounter(X)
27238#endif
27239
27240#endif /* !defined(_OS_COMMON_H_) */
27241
27242/************** End of os_common.h *******************************************/
27243/************** Continuing where we left off in os_win.c *********************/
27244
27245/*
27246** Some microsoft compilers lack this definition.
27247*/
27248#ifndef INVALID_FILE_ATTRIBUTES
27249# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
27250#endif
27251
27252/*
27253** Determine if we are dealing with WindowsCE - which has a much
27254** reduced API.
27255*/
27256#if SQLITE_OS_WINCE
27257# define AreFileApisANSI() 1
27258# define FormatMessageW(a,b,c,d,e,f,g) 0
27259#endif
27260
27261/*
27262** WinCE lacks native support for file locking so we have to fake it
27263** with some code of our own.
27264*/
27265#if SQLITE_OS_WINCE
27266typedef struct winceLock {
27267  int nReaders;       /* Number of reader locks obtained */
27268  BOOL bPending;      /* Indicates a pending lock has been obtained */
27269  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
27270  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
27271} winceLock;
27272#endif
27273
27274/*
27275** The winFile structure is a subclass of sqlite3_file* specific to the win32
27276** portability layer.
27277*/
27278typedef struct winFile winFile;
27279struct winFile {
27280  const sqlite3_io_methods *pMethod;/* Must be first */
27281  HANDLE h;               /* Handle for accessing the file */
27282  unsigned char locktype; /* Type of lock currently held on this file */
27283  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
27284  DWORD lastErrno;        /* The Windows errno from the last I/O error */
27285  DWORD sectorSize;       /* Sector size of the device file is on */
27286#if SQLITE_OS_WINCE
27287  WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
27288  HANDLE hMutex;          /* Mutex used to control access to shared lock */
27289  HANDLE hShared;         /* Shared memory segment used for locking */
27290  winceLock local;        /* Locks obtained by this instance of winFile */
27291  winceLock *shared;      /* Global shared lock memory for the file  */
27292#endif
27293};
27294
27295/*
27296** Forward prototypes.
27297*/
27298static int getSectorSize(
27299    sqlite3_vfs *pVfs,
27300    const char *zRelative     /* UTF-8 file name */
27301);
27302
27303/*
27304** The following variable is (normally) set once and never changes
27305** thereafter.  It records whether the operating system is Win95
27306** or WinNT.
27307**
27308** 0:   Operating system unknown.
27309** 1:   Operating system is Win95.
27310** 2:   Operating system is WinNT.
27311**
27312** In order to facilitate testing on a WinNT system, the test fixture
27313** can manually set this value to 1 to emulate Win98 behavior.
27314*/
27315#ifdef SQLITE_TEST
27316SQLITE_API int sqlite3_os_type = 0;
27317#else
27318static int sqlite3_os_type = 0;
27319#endif
27320
27321/*
27322** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
27323** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
27324**
27325** Here is an interesting observation:  Win95, Win98, and WinME lack
27326** the LockFileEx() API.  But we can still statically link against that
27327** API as long as we don't call it when running Win95/98/ME.  A call to
27328** this routine is used to determine if the host is Win95/98/ME or
27329** WinNT/2K/XP so that we will know whether or not we can safely call
27330** the LockFileEx() API.
27331*/
27332#if SQLITE_OS_WINCE
27333# define isNT()  (1)
27334#else
27335  static int isNT(void){
27336    if( sqlite3_os_type==0 ){
27337      OSVERSIONINFO sInfo;
27338      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
27339      GetVersionEx(&sInfo);
27340      sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
27341    }
27342    return sqlite3_os_type==2;
27343  }
27344#endif /* SQLITE_OS_WINCE */
27345
27346/*
27347** Convert a UTF-8 string to microsoft unicode (UTF-16?).
27348**
27349** Space to hold the returned string is obtained from malloc.
27350*/
27351static WCHAR *utf8ToUnicode(const char *zFilename){
27352  int nChar;
27353  WCHAR *zWideFilename;
27354
27355  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
27356  zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
27357  if( zWideFilename==0 ){
27358    return 0;
27359  }
27360  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
27361  if( nChar==0 ){
27362    free(zWideFilename);
27363    zWideFilename = 0;
27364  }
27365  return zWideFilename;
27366}
27367
27368/*
27369** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
27370** obtained from malloc().
27371*/
27372static char *unicodeToUtf8(const WCHAR *zWideFilename){
27373  int nByte;
27374  char *zFilename;
27375
27376  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
27377  zFilename = malloc( nByte );
27378  if( zFilename==0 ){
27379    return 0;
27380  }
27381  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
27382                              0, 0);
27383  if( nByte == 0 ){
27384    free(zFilename);
27385    zFilename = 0;
27386  }
27387  return zFilename;
27388}
27389
27390/*
27391** Convert an ansi string to microsoft unicode, based on the
27392** current codepage settings for file apis.
27393**
27394** Space to hold the returned string is obtained
27395** from malloc.
27396*/
27397static WCHAR *mbcsToUnicode(const char *zFilename){
27398  int nByte;
27399  WCHAR *zMbcsFilename;
27400  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
27401
27402  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
27403  zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
27404  if( zMbcsFilename==0 ){
27405    return 0;
27406  }
27407  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
27408  if( nByte==0 ){
27409    free(zMbcsFilename);
27410    zMbcsFilename = 0;
27411  }
27412  return zMbcsFilename;
27413}
27414
27415/*
27416** Convert microsoft unicode to multibyte character string, based on the
27417** user's Ansi codepage.
27418**
27419** Space to hold the returned string is obtained from
27420** malloc().
27421*/
27422static char *unicodeToMbcs(const WCHAR *zWideFilename){
27423  int nByte;
27424  char *zFilename;
27425  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
27426
27427  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
27428  zFilename = malloc( nByte );
27429  if( zFilename==0 ){
27430    return 0;
27431  }
27432  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
27433                              0, 0);
27434  if( nByte == 0 ){
27435    free(zFilename);
27436    zFilename = 0;
27437  }
27438  return zFilename;
27439}
27440
27441/*
27442** Convert multibyte character string to UTF-8.  Space to hold the
27443** returned string is obtained from malloc().
27444*/
27445SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
27446  char *zFilenameUtf8;
27447  WCHAR *zTmpWide;
27448
27449  zTmpWide = mbcsToUnicode(zFilename);
27450  if( zTmpWide==0 ){
27451    return 0;
27452  }
27453  zFilenameUtf8 = unicodeToUtf8(zTmpWide);
27454  free(zTmpWide);
27455  return zFilenameUtf8;
27456}
27457
27458/*
27459** Convert UTF-8 to multibyte character string.  Space to hold the
27460** returned string is obtained from malloc().
27461*/
27462static char *utf8ToMbcs(const char *zFilename){
27463  char *zFilenameMbcs;
27464  WCHAR *zTmpWide;
27465
27466  zTmpWide = utf8ToUnicode(zFilename);
27467  if( zTmpWide==0 ){
27468    return 0;
27469  }
27470  zFilenameMbcs = unicodeToMbcs(zTmpWide);
27471  free(zTmpWide);
27472  return zFilenameMbcs;
27473}
27474
27475#if SQLITE_OS_WINCE
27476/*************************************************************************
27477** This section contains code for WinCE only.
27478*/
27479/*
27480** WindowsCE does not have a localtime() function.  So create a
27481** substitute.
27482*/
27483struct tm *__cdecl localtime(const time_t *t)
27484{
27485  static struct tm y;
27486  FILETIME uTm, lTm;
27487  SYSTEMTIME pTm;
27488  sqlite3_int64 t64;
27489  t64 = *t;
27490  t64 = (t64 + 11644473600)*10000000;
27491  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
27492  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
27493  FileTimeToLocalFileTime(&uTm,&lTm);
27494  FileTimeToSystemTime(&lTm,&pTm);
27495  y.tm_year = pTm.wYear - 1900;
27496  y.tm_mon = pTm.wMonth - 1;
27497  y.tm_wday = pTm.wDayOfWeek;
27498  y.tm_mday = pTm.wDay;
27499  y.tm_hour = pTm.wHour;
27500  y.tm_min = pTm.wMinute;
27501  y.tm_sec = pTm.wSecond;
27502  return &y;
27503}
27504
27505/* This will never be called, but defined to make the code compile */
27506#define GetTempPathA(a,b)
27507
27508#define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
27509#define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
27510#define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
27511
27512#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
27513
27514/*
27515** Acquire a lock on the handle h
27516*/
27517static void winceMutexAcquire(HANDLE h){
27518   DWORD dwErr;
27519   do {
27520     dwErr = WaitForSingleObject(h, INFINITE);
27521   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
27522}
27523/*
27524** Release a lock acquired by winceMutexAcquire()
27525*/
27526#define winceMutexRelease(h) ReleaseMutex(h)
27527
27528/*
27529** Create the mutex and shared memory used for locking in the file
27530** descriptor pFile
27531*/
27532static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
27533  WCHAR *zTok;
27534  WCHAR *zName = utf8ToUnicode(zFilename);
27535  BOOL bInit = TRUE;
27536
27537  /* Initialize the local lockdata */
27538  ZeroMemory(&pFile->local, sizeof(pFile->local));
27539
27540  /* Replace the backslashes from the filename and lowercase it
27541  ** to derive a mutex name. */
27542  zTok = CharLowerW(zName);
27543  for (;*zTok;zTok++){
27544    if (*zTok == '\\') *zTok = '_';
27545  }
27546
27547  /* Create/open the named mutex */
27548  pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
27549  if (!pFile->hMutex){
27550    pFile->lastErrno = GetLastError();
27551    free(zName);
27552    return FALSE;
27553  }
27554
27555  /* Acquire the mutex before continuing */
27556  winceMutexAcquire(pFile->hMutex);
27557
27558  /* Since the names of named mutexes, semaphores, file mappings etc are
27559  ** case-sensitive, take advantage of that by uppercasing the mutex name
27560  ** and using that as the shared filemapping name.
27561  */
27562  CharUpperW(zName);
27563  pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
27564                                       PAGE_READWRITE, 0, sizeof(winceLock),
27565                                       zName);
27566
27567  /* Set a flag that indicates we're the first to create the memory so it
27568  ** must be zero-initialized */
27569  if (GetLastError() == ERROR_ALREADY_EXISTS){
27570    bInit = FALSE;
27571  }
27572
27573  free(zName);
27574
27575  /* If we succeeded in making the shared memory handle, map it. */
27576  if (pFile->hShared){
27577    pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
27578             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
27579    /* If mapping failed, close the shared memory handle and erase it */
27580    if (!pFile->shared){
27581      pFile->lastErrno = GetLastError();
27582      CloseHandle(pFile->hShared);
27583      pFile->hShared = NULL;
27584    }
27585  }
27586
27587  /* If shared memory could not be created, then close the mutex and fail */
27588  if (pFile->hShared == NULL){
27589    winceMutexRelease(pFile->hMutex);
27590    CloseHandle(pFile->hMutex);
27591    pFile->hMutex = NULL;
27592    return FALSE;
27593  }
27594
27595  /* Initialize the shared memory if we're supposed to */
27596  if (bInit) {
27597    ZeroMemory(pFile->shared, sizeof(winceLock));
27598  }
27599
27600  winceMutexRelease(pFile->hMutex);
27601  return TRUE;
27602}
27603
27604/*
27605** Destroy the part of winFile that deals with wince locks
27606*/
27607static void winceDestroyLock(winFile *pFile){
27608  if (pFile->hMutex){
27609    /* Acquire the mutex */
27610    winceMutexAcquire(pFile->hMutex);
27611
27612    /* The following blocks should probably assert in debug mode, but they
27613       are to cleanup in case any locks remained open */
27614    if (pFile->local.nReaders){
27615      pFile->shared->nReaders --;
27616    }
27617    if (pFile->local.bReserved){
27618      pFile->shared->bReserved = FALSE;
27619    }
27620    if (pFile->local.bPending){
27621      pFile->shared->bPending = FALSE;
27622    }
27623    if (pFile->local.bExclusive){
27624      pFile->shared->bExclusive = FALSE;
27625    }
27626
27627    /* De-reference and close our copy of the shared memory handle */
27628    UnmapViewOfFile(pFile->shared);
27629    CloseHandle(pFile->hShared);
27630
27631    /* Done with the mutex */
27632    winceMutexRelease(pFile->hMutex);
27633    CloseHandle(pFile->hMutex);
27634    pFile->hMutex = NULL;
27635  }
27636}
27637
27638/*
27639** An implementation of the LockFile() API of windows for wince
27640*/
27641static BOOL winceLockFile(
27642  HANDLE *phFile,
27643  DWORD dwFileOffsetLow,
27644  DWORD dwFileOffsetHigh,
27645  DWORD nNumberOfBytesToLockLow,
27646  DWORD nNumberOfBytesToLockHigh
27647){
27648  winFile *pFile = HANDLE_TO_WINFILE(phFile);
27649  BOOL bReturn = FALSE;
27650
27651  UNUSED_PARAMETER(dwFileOffsetHigh);
27652  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
27653
27654  if (!pFile->hMutex) return TRUE;
27655  winceMutexAcquire(pFile->hMutex);
27656
27657  /* Wanting an exclusive lock? */
27658  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
27659       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
27660    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
27661       pFile->shared->bExclusive = TRUE;
27662       pFile->local.bExclusive = TRUE;
27663       bReturn = TRUE;
27664    }
27665  }
27666
27667  /* Want a read-only lock? */
27668  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
27669           nNumberOfBytesToLockLow == 1){
27670    if (pFile->shared->bExclusive == 0){
27671      pFile->local.nReaders ++;
27672      if (pFile->local.nReaders == 1){
27673        pFile->shared->nReaders ++;
27674      }
27675      bReturn = TRUE;
27676    }
27677  }
27678
27679  /* Want a pending lock? */
27680  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
27681    /* If no pending lock has been acquired, then acquire it */
27682    if (pFile->shared->bPending == 0) {
27683      pFile->shared->bPending = TRUE;
27684      pFile->local.bPending = TRUE;
27685      bReturn = TRUE;
27686    }
27687  }
27688
27689  /* Want a reserved lock? */
27690  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
27691    if (pFile->shared->bReserved == 0) {
27692      pFile->shared->bReserved = TRUE;
27693      pFile->local.bReserved = TRUE;
27694      bReturn = TRUE;
27695    }
27696  }
27697
27698  winceMutexRelease(pFile->hMutex);
27699  return bReturn;
27700}
27701
27702/*
27703** An implementation of the UnlockFile API of windows for wince
27704*/
27705static BOOL winceUnlockFile(
27706  HANDLE *phFile,
27707  DWORD dwFileOffsetLow,
27708  DWORD dwFileOffsetHigh,
27709  DWORD nNumberOfBytesToUnlockLow,
27710  DWORD nNumberOfBytesToUnlockHigh
27711){
27712  winFile *pFile = HANDLE_TO_WINFILE(phFile);
27713  BOOL bReturn = FALSE;
27714
27715  UNUSED_PARAMETER(dwFileOffsetHigh);
27716  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
27717
27718  if (!pFile->hMutex) return TRUE;
27719  winceMutexAcquire(pFile->hMutex);
27720
27721  /* Releasing a reader lock or an exclusive lock */
27722  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
27723    /* Did we have an exclusive lock? */
27724    if (pFile->local.bExclusive){
27725      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
27726      pFile->local.bExclusive = FALSE;
27727      pFile->shared->bExclusive = FALSE;
27728      bReturn = TRUE;
27729    }
27730
27731    /* Did we just have a reader lock? */
27732    else if (pFile->local.nReaders){
27733      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
27734      pFile->local.nReaders --;
27735      if (pFile->local.nReaders == 0)
27736      {
27737        pFile->shared->nReaders --;
27738      }
27739      bReturn = TRUE;
27740    }
27741  }
27742
27743  /* Releasing a pending lock */
27744  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
27745    if (pFile->local.bPending){
27746      pFile->local.bPending = FALSE;
27747      pFile->shared->bPending = FALSE;
27748      bReturn = TRUE;
27749    }
27750  }
27751  /* Releasing a reserved lock */
27752  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
27753    if (pFile->local.bReserved) {
27754      pFile->local.bReserved = FALSE;
27755      pFile->shared->bReserved = FALSE;
27756      bReturn = TRUE;
27757    }
27758  }
27759
27760  winceMutexRelease(pFile->hMutex);
27761  return bReturn;
27762}
27763
27764/*
27765** An implementation of the LockFileEx() API of windows for wince
27766*/
27767static BOOL winceLockFileEx(
27768  HANDLE *phFile,
27769  DWORD dwFlags,
27770  DWORD dwReserved,
27771  DWORD nNumberOfBytesToLockLow,
27772  DWORD nNumberOfBytesToLockHigh,
27773  LPOVERLAPPED lpOverlapped
27774){
27775  UNUSED_PARAMETER(dwReserved);
27776  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
27777
27778  /* If the caller wants a shared read lock, forward this call
27779  ** to winceLockFile */
27780  if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
27781      dwFlags == 1 &&
27782      nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
27783    return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
27784  }
27785  return FALSE;
27786}
27787/*
27788** End of the special code for wince
27789*****************************************************************************/
27790#endif /* SQLITE_OS_WINCE */
27791
27792/*****************************************************************************
27793** The next group of routines implement the I/O methods specified
27794** by the sqlite3_io_methods object.
27795******************************************************************************/
27796
27797/*
27798** Close a file.
27799**
27800** It is reported that an attempt to close a handle might sometimes
27801** fail.  This is a very unreasonable result, but windows is notorious
27802** for being unreasonable so I do not doubt that it might happen.  If
27803** the close fails, we pause for 100 milliseconds and try again.  As
27804** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
27805** giving up and returning an error.
27806*/
27807#define MX_CLOSE_ATTEMPT 3
27808static int winClose(sqlite3_file *id){
27809  int rc, cnt = 0;
27810  winFile *pFile = (winFile*)id;
27811
27812  assert( id!=0 );
27813  OSTRACE2("CLOSE %d\n", pFile->h);
27814  do{
27815    rc = CloseHandle(pFile->h);
27816  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
27817#if SQLITE_OS_WINCE
27818#define WINCE_DELETION_ATTEMPTS 3
27819  winceDestroyLock(pFile);
27820  if( pFile->zDeleteOnClose ){
27821    int cnt = 0;
27822    while(
27823           DeleteFileW(pFile->zDeleteOnClose)==0
27824        && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
27825        && cnt++ < WINCE_DELETION_ATTEMPTS
27826    ){
27827       Sleep(100);  /* Wait a little before trying again */
27828    }
27829    free(pFile->zDeleteOnClose);
27830  }
27831#endif
27832  OpenCounter(-1);
27833  return rc ? SQLITE_OK : SQLITE_IOERR;
27834}
27835
27836/*
27837** Some microsoft compilers lack this definition.
27838*/
27839#ifndef INVALID_SET_FILE_POINTER
27840# define INVALID_SET_FILE_POINTER ((DWORD)-1)
27841#endif
27842
27843/*
27844** Read data from a file into a buffer.  Return SQLITE_OK if all
27845** bytes were read successfully and SQLITE_IOERR if anything goes
27846** wrong.
27847*/
27848static int winRead(
27849  sqlite3_file *id,          /* File to read from */
27850  void *pBuf,                /* Write content into this buffer */
27851  int amt,                   /* Number of bytes to read */
27852  sqlite3_int64 offset       /* Begin reading at this offset */
27853){
27854  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
27855  LONG lowerBits = (LONG)(offset & 0xffffffff);
27856  DWORD rc;
27857  winFile *pFile = (winFile*)id;
27858  DWORD error;
27859  DWORD got;
27860
27861  assert( id!=0 );
27862  SimulateIOError(return SQLITE_IOERR_READ);
27863  OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
27864  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
27865  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
27866    pFile->lastErrno = error;
27867    return SQLITE_FULL;
27868  }
27869  if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
27870    pFile->lastErrno = GetLastError();
27871    return SQLITE_IOERR_READ;
27872  }
27873  if( got==(DWORD)amt ){
27874    return SQLITE_OK;
27875  }else{
27876    /* Unread parts of the buffer must be zero-filled */
27877    memset(&((char*)pBuf)[got], 0, amt-got);
27878    return SQLITE_IOERR_SHORT_READ;
27879  }
27880}
27881
27882/*
27883** Write data from a buffer into a file.  Return SQLITE_OK on success
27884** or some other error code on failure.
27885*/
27886static int winWrite(
27887  sqlite3_file *id,         /* File to write into */
27888  const void *pBuf,         /* The bytes to be written */
27889  int amt,                  /* Number of bytes to write */
27890  sqlite3_int64 offset      /* Offset into the file to begin writing at */
27891){
27892  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
27893  LONG lowerBits = (LONG)(offset & 0xffffffff);
27894  DWORD rc;
27895  winFile *pFile = (winFile*)id;
27896  DWORD error;
27897  DWORD wrote = 0;
27898
27899  assert( id!=0 );
27900  SimulateIOError(return SQLITE_IOERR_WRITE);
27901  SimulateDiskfullError(return SQLITE_FULL);
27902  OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
27903  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
27904  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
27905    pFile->lastErrno = error;
27906    return SQLITE_FULL;
27907  }
27908  assert( amt>0 );
27909  while(
27910     amt>0
27911     && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
27912     && wrote>0
27913  ){
27914    amt -= wrote;
27915    pBuf = &((char*)pBuf)[wrote];
27916  }
27917  if( !rc || amt>(int)wrote ){
27918    pFile->lastErrno = GetLastError();
27919    return SQLITE_FULL;
27920  }
27921  return SQLITE_OK;
27922}
27923
27924/*
27925** Truncate an open file to a specified size
27926*/
27927static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
27928  LONG upperBits = (LONG)((nByte>>32) & 0x7fffffff);
27929  LONG lowerBits = (LONG)(nByte & 0xffffffff);
27930  DWORD rc;
27931  winFile *pFile = (winFile*)id;
27932  DWORD error;
27933
27934  assert( id!=0 );
27935  OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
27936  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
27937  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
27938  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
27939    pFile->lastErrno = error;
27940    return SQLITE_IOERR_TRUNCATE;
27941  }
27942  /* SetEndOfFile will fail if nByte is negative */
27943  if( !SetEndOfFile(pFile->h) ){
27944    pFile->lastErrno = GetLastError();
27945    return SQLITE_IOERR_TRUNCATE;
27946  }
27947  return SQLITE_OK;
27948}
27949
27950#ifdef SQLITE_TEST
27951/*
27952** Count the number of fullsyncs and normal syncs.  This is used to test
27953** that syncs and fullsyncs are occuring at the right times.
27954*/
27955SQLITE_API int sqlite3_sync_count = 0;
27956SQLITE_API int sqlite3_fullsync_count = 0;
27957#endif
27958
27959/*
27960** Make sure all writes to a particular file are committed to disk.
27961*/
27962static int winSync(sqlite3_file *id, int flags){
27963#ifndef SQLITE_NO_SYNC
27964  winFile *pFile = (winFile*)id;
27965
27966  assert( id!=0 );
27967  OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
27968#else
27969  UNUSED_PARAMETER(id);
27970#endif
27971#ifndef SQLITE_TEST
27972  UNUSED_PARAMETER(flags);
27973#else
27974  if( flags & SQLITE_SYNC_FULL ){
27975    sqlite3_fullsync_count++;
27976  }
27977  sqlite3_sync_count++;
27978#endif
27979  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
27980  ** no-op
27981  */
27982#ifdef SQLITE_NO_SYNC
27983    return SQLITE_OK;
27984#else
27985  if( FlushFileBuffers(pFile->h) ){
27986    return SQLITE_OK;
27987  }else{
27988    pFile->lastErrno = GetLastError();
27989    return SQLITE_IOERR;
27990  }
27991#endif
27992}
27993
27994/*
27995** Determine the current size of a file in bytes
27996*/
27997static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
27998  DWORD upperBits;
27999  DWORD lowerBits;
28000  winFile *pFile = (winFile*)id;
28001  DWORD error;
28002
28003  assert( id!=0 );
28004  SimulateIOError(return SQLITE_IOERR_FSTAT);
28005  lowerBits = GetFileSize(pFile->h, &upperBits);
28006  if(   (lowerBits == INVALID_FILE_SIZE)
28007     && ((error = GetLastError()) != NO_ERROR) )
28008  {
28009    pFile->lastErrno = error;
28010    return SQLITE_IOERR_FSTAT;
28011  }
28012  *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
28013  return SQLITE_OK;
28014}
28015
28016/*
28017** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
28018*/
28019#ifndef LOCKFILE_FAIL_IMMEDIATELY
28020# define LOCKFILE_FAIL_IMMEDIATELY 1
28021#endif
28022
28023/*
28024** Acquire a reader lock.
28025** Different API routines are called depending on whether or not this
28026** is Win95 or WinNT.
28027*/
28028static int getReadLock(winFile *pFile){
28029  int res;
28030  if( isNT() ){
28031    OVERLAPPED ovlp;
28032    ovlp.Offset = SHARED_FIRST;
28033    ovlp.OffsetHigh = 0;
28034    ovlp.hEvent = 0;
28035    res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
28036                     0, SHARED_SIZE, 0, &ovlp);
28037/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28038*/
28039#if SQLITE_OS_WINCE==0
28040  }else{
28041    int lk;
28042    sqlite3_randomness(sizeof(lk), &lk);
28043    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
28044    res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
28045#endif
28046  }
28047  if( res == 0 ){
28048    pFile->lastErrno = GetLastError();
28049  }
28050  return res;
28051}
28052
28053/*
28054** Undo a readlock
28055*/
28056static int unlockReadLock(winFile *pFile){
28057  int res;
28058  if( isNT() ){
28059    res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28060/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28061*/
28062#if SQLITE_OS_WINCE==0
28063  }else{
28064    res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
28065#endif
28066  }
28067  if( res == 0 ){
28068    pFile->lastErrno = GetLastError();
28069  }
28070  return res;
28071}
28072
28073/*
28074** Lock the file with the lock specified by parameter locktype - one
28075** of the following:
28076**
28077**     (1) SHARED_LOCK
28078**     (2) RESERVED_LOCK
28079**     (3) PENDING_LOCK
28080**     (4) EXCLUSIVE_LOCK
28081**
28082** Sometimes when requesting one lock state, additional lock states
28083** are inserted in between.  The locking might fail on one of the later
28084** transitions leaving the lock state different from what it started but
28085** still short of its goal.  The following chart shows the allowed
28086** transitions and the inserted intermediate states:
28087**
28088**    UNLOCKED -> SHARED
28089**    SHARED -> RESERVED
28090**    SHARED -> (PENDING) -> EXCLUSIVE
28091**    RESERVED -> (PENDING) -> EXCLUSIVE
28092**    PENDING -> EXCLUSIVE
28093**
28094** This routine will only increase a lock.  The winUnlock() routine
28095** erases all locks at once and returns us immediately to locking level 0.
28096** It is not possible to lower the locking level one step at a time.  You
28097** must go straight to locking level 0.
28098*/
28099static int winLock(sqlite3_file *id, int locktype){
28100  int rc = SQLITE_OK;    /* Return code from subroutines */
28101  int res = 1;           /* Result of a windows lock call */
28102  int newLocktype;       /* Set pFile->locktype to this value before exiting */
28103  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
28104  winFile *pFile = (winFile*)id;
28105  DWORD error = NO_ERROR;
28106
28107  assert( id!=0 );
28108  OSTRACE5("LOCK %d %d was %d(%d)\n",
28109          pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
28110
28111  /* If there is already a lock of this type or more restrictive on the
28112  ** OsFile, do nothing. Don't use the end_lock: exit path, as
28113  ** sqlite3OsEnterMutex() hasn't been called yet.
28114  */
28115  if( pFile->locktype>=locktype ){
28116    return SQLITE_OK;
28117  }
28118
28119  /* Make sure the locking sequence is correct
28120  */
28121  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
28122  assert( locktype!=PENDING_LOCK );
28123  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
28124
28125  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
28126  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
28127  ** the PENDING_LOCK byte is temporary.
28128  */
28129  newLocktype = pFile->locktype;
28130  if(   (pFile->locktype==NO_LOCK)
28131     || (   (locktype==EXCLUSIVE_LOCK)
28132         && (pFile->locktype==RESERVED_LOCK))
28133  ){
28134    int cnt = 3;
28135    while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
28136      /* Try 3 times to get the pending lock.  The pending lock might be
28137      ** held by another reader process who will release it momentarily.
28138      */
28139      OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
28140      Sleep(1);
28141    }
28142    gotPendingLock = res;
28143    if( !res ){
28144      error = GetLastError();
28145    }
28146  }
28147
28148  /* Acquire a shared lock
28149  */
28150  if( locktype==SHARED_LOCK && res ){
28151    assert( pFile->locktype==NO_LOCK );
28152    res = getReadLock(pFile);
28153    if( res ){
28154      newLocktype = SHARED_LOCK;
28155    }else{
28156      error = GetLastError();
28157    }
28158  }
28159
28160  /* Acquire a RESERVED lock
28161  */
28162  if( locktype==RESERVED_LOCK && res ){
28163    assert( pFile->locktype==SHARED_LOCK );
28164    res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28165    if( res ){
28166      newLocktype = RESERVED_LOCK;
28167    }else{
28168      error = GetLastError();
28169    }
28170  }
28171
28172  /* Acquire a PENDING lock
28173  */
28174  if( locktype==EXCLUSIVE_LOCK && res ){
28175    newLocktype = PENDING_LOCK;
28176    gotPendingLock = 0;
28177  }
28178
28179  /* Acquire an EXCLUSIVE lock
28180  */
28181  if( locktype==EXCLUSIVE_LOCK && res ){
28182    assert( pFile->locktype>=SHARED_LOCK );
28183    res = unlockReadLock(pFile);
28184    OSTRACE2("unreadlock = %d\n", res);
28185    res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28186    if( res ){
28187      newLocktype = EXCLUSIVE_LOCK;
28188    }else{
28189      error = GetLastError();
28190      OSTRACE2("error-code = %d\n", error);
28191      getReadLock(pFile);
28192    }
28193  }
28194
28195  /* If we are holding a PENDING lock that ought to be released, then
28196  ** release it now.
28197  */
28198  if( gotPendingLock && locktype==SHARED_LOCK ){
28199    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
28200  }
28201
28202  /* Update the state of the lock has held in the file descriptor then
28203  ** return the appropriate result code.
28204  */
28205  if( res ){
28206    rc = SQLITE_OK;
28207  }else{
28208    OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
28209           locktype, newLocktype);
28210    pFile->lastErrno = error;
28211    rc = SQLITE_BUSY;
28212  }
28213  pFile->locktype = (u8)newLocktype;
28214  return rc;
28215}
28216
28217/*
28218** This routine checks if there is a RESERVED lock held on the specified
28219** file by this or any other process. If such a lock is held, return
28220** non-zero, otherwise zero.
28221*/
28222static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
28223  int rc;
28224  winFile *pFile = (winFile*)id;
28225
28226  assert( id!=0 );
28227  if( pFile->locktype>=RESERVED_LOCK ){
28228    rc = 1;
28229    OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
28230  }else{
28231    rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28232    if( rc ){
28233      UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28234    }
28235    rc = !rc;
28236    OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
28237  }
28238  *pResOut = rc;
28239  return SQLITE_OK;
28240}
28241
28242/*
28243** Lower the locking level on file descriptor id to locktype.  locktype
28244** must be either NO_LOCK or SHARED_LOCK.
28245**
28246** If the locking level of the file descriptor is already at or below
28247** the requested locking level, this routine is a no-op.
28248**
28249** It is not possible for this routine to fail if the second argument
28250** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
28251** might return SQLITE_IOERR;
28252*/
28253static int winUnlock(sqlite3_file *id, int locktype){
28254  int type;
28255  winFile *pFile = (winFile*)id;
28256  int rc = SQLITE_OK;
28257  assert( pFile!=0 );
28258  assert( locktype<=SHARED_LOCK );
28259  OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
28260          pFile->locktype, pFile->sharedLockByte);
28261  type = pFile->locktype;
28262  if( type>=EXCLUSIVE_LOCK ){
28263    UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28264    if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
28265      /* This should never happen.  We should always be able to
28266      ** reacquire the read lock */
28267      rc = SQLITE_IOERR_UNLOCK;
28268    }
28269  }
28270  if( type>=RESERVED_LOCK ){
28271    UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28272  }
28273  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
28274    unlockReadLock(pFile);
28275  }
28276  if( type>=PENDING_LOCK ){
28277    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
28278  }
28279  pFile->locktype = (u8)locktype;
28280  return rc;
28281}
28282
28283/*
28284** Control and query of the open file handle.
28285*/
28286static int winFileControl(sqlite3_file *id, int op, void *pArg){
28287  switch( op ){
28288    case SQLITE_FCNTL_LOCKSTATE: {
28289      *(int*)pArg = ((winFile*)id)->locktype;
28290      return SQLITE_OK;
28291    }
28292    case SQLITE_LAST_ERRNO: {
28293      *(int*)pArg = (int)((winFile*)id)->lastErrno;
28294      return SQLITE_OK;
28295    }
28296  }
28297  return SQLITE_ERROR;
28298}
28299
28300/*
28301** Return the sector size in bytes of the underlying block device for
28302** the specified file. This is almost always 512 bytes, but may be
28303** larger for some devices.
28304**
28305** SQLite code assumes this function cannot fail. It also assumes that
28306** if two files are created in the same file-system directory (i.e.
28307** a database and its journal file) that the sector size will be the
28308** same for both.
28309*/
28310static int winSectorSize(sqlite3_file *id){
28311  assert( id!=0 );
28312  return (int)(((winFile*)id)->sectorSize);
28313}
28314
28315/*
28316** Return a vector of device characteristics.
28317*/
28318static int winDeviceCharacteristics(sqlite3_file *id){
28319  UNUSED_PARAMETER(id);
28320  return 0;
28321}
28322
28323/*
28324** This vector defines all the methods that can operate on an
28325** sqlite3_file for win32.
28326*/
28327static const sqlite3_io_methods winIoMethod = {
28328  1,                        /* iVersion */
28329  winClose,
28330  winRead,
28331  winWrite,
28332  winTruncate,
28333  winSync,
28334  winFileSize,
28335  winLock,
28336  winUnlock,
28337  winCheckReservedLock,
28338  winFileControl,
28339  winSectorSize,
28340  winDeviceCharacteristics
28341};
28342
28343/***************************************************************************
28344** Here ends the I/O methods that form the sqlite3_io_methods object.
28345**
28346** The next block of code implements the VFS methods.
28347****************************************************************************/
28348
28349/*
28350** Convert a UTF-8 filename into whatever form the underlying
28351** operating system wants filenames in.  Space to hold the result
28352** is obtained from malloc and must be freed by the calling
28353** function.
28354*/
28355static void *convertUtf8Filename(const char *zFilename){
28356  void *zConverted = 0;
28357  if( isNT() ){
28358    zConverted = utf8ToUnicode(zFilename);
28359/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28360*/
28361#if SQLITE_OS_WINCE==0
28362  }else{
28363    zConverted = utf8ToMbcs(zFilename);
28364#endif
28365  }
28366  /* caller will handle out of memory */
28367  return zConverted;
28368}
28369
28370/*
28371** Create a temporary file name in zBuf.  zBuf must be big enough to
28372** hold at pVfs->mxPathname characters.
28373*/
28374static int getTempname(int nBuf, char *zBuf){
28375  static char zChars[] =
28376    "abcdefghijklmnopqrstuvwxyz"
28377    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
28378    "0123456789";
28379  size_t i, j;
28380  char zTempPath[MAX_PATH+1];
28381  if( sqlite3_temp_directory ){
28382    sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
28383  }else if( isNT() ){
28384    char *zMulti;
28385    WCHAR zWidePath[MAX_PATH];
28386    GetTempPathW(MAX_PATH-30, zWidePath);
28387    zMulti = unicodeToUtf8(zWidePath);
28388    if( zMulti ){
28389      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
28390      free(zMulti);
28391    }else{
28392      return SQLITE_NOMEM;
28393    }
28394/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28395** Since the ASCII version of these Windows API do not exist for WINCE,
28396** it's important to not reference them for WINCE builds.
28397*/
28398#if SQLITE_OS_WINCE==0
28399  }else{
28400    char *zUtf8;
28401    char zMbcsPath[MAX_PATH];
28402    GetTempPathA(MAX_PATH-30, zMbcsPath);
28403    zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
28404    if( zUtf8 ){
28405      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
28406      free(zUtf8);
28407    }else{
28408      return SQLITE_NOMEM;
28409    }
28410#endif
28411  }
28412  for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
28413  zTempPath[i] = 0;
28414  sqlite3_snprintf(nBuf-30, zBuf,
28415                   "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
28416  j = sqlite3Strlen30(zBuf);
28417  sqlite3_randomness(20, &zBuf[j]);
28418  for(i=0; i<20; i++, j++){
28419    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
28420  }
28421  zBuf[j] = 0;
28422  OSTRACE2("TEMP FILENAME: %s\n", zBuf);
28423  return SQLITE_OK;
28424}
28425
28426/*
28427** The return value of getLastErrorMsg
28428** is zero if the error message fits in the buffer, or non-zero
28429** otherwise (if the message was truncated).
28430*/
28431static int getLastErrorMsg(int nBuf, char *zBuf){
28432  /* FormatMessage returns 0 on failure.  Otherwise it
28433  ** returns the number of TCHARs written to the output
28434  ** buffer, excluding the terminating null char.
28435  */
28436  DWORD error = GetLastError();
28437  DWORD dwLen = 0;
28438  char *zOut = 0;
28439
28440  if( isNT() ){
28441    WCHAR *zTempWide = NULL;
28442    dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
28443                           NULL,
28444                           error,
28445                           0,
28446                           (LPWSTR) &zTempWide,
28447                           0,
28448                           0);
28449    if( dwLen > 0 ){
28450      /* allocate a buffer and convert to UTF8 */
28451      zOut = unicodeToUtf8(zTempWide);
28452      /* free the system buffer allocated by FormatMessage */
28453      LocalFree(zTempWide);
28454    }
28455/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28456** Since the ASCII version of these Windows API do not exist for WINCE,
28457** it's important to not reference them for WINCE builds.
28458*/
28459#if SQLITE_OS_WINCE==0
28460  }else{
28461    char *zTemp = NULL;
28462    dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
28463                           NULL,
28464                           error,
28465                           0,
28466                           (LPSTR) &zTemp,
28467                           0,
28468                           0);
28469    if( dwLen > 0 ){
28470      /* allocate a buffer and convert to UTF8 */
28471      zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
28472      /* free the system buffer allocated by FormatMessage */
28473      LocalFree(zTemp);
28474    }
28475#endif
28476  }
28477  if( 0 == dwLen ){
28478    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
28479  }else{
28480    /* copy a maximum of nBuf chars to output buffer */
28481    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
28482    /* free the UTF8 buffer */
28483    free(zOut);
28484  }
28485  return 0;
28486}
28487
28488/*
28489** Open a file.
28490*/
28491static int winOpen(
28492  sqlite3_vfs *pVfs,        /* Not used */
28493  const char *zName,        /* Name of the file (UTF-8) */
28494  sqlite3_file *id,         /* Write the SQLite file handle here */
28495  int flags,                /* Open mode flags */
28496  int *pOutFlags            /* Status return flags */
28497){
28498  HANDLE h;
28499  DWORD dwDesiredAccess;
28500  DWORD dwShareMode;
28501  DWORD dwCreationDisposition;
28502  DWORD dwFlagsAndAttributes = 0;
28503#if SQLITE_OS_WINCE
28504  int isTemp = 0;
28505#endif
28506  winFile *pFile = (winFile*)id;
28507  void *zConverted;                 /* Filename in OS encoding */
28508  const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
28509  char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
28510
28511  assert( id!=0 );
28512  UNUSED_PARAMETER(pVfs);
28513
28514  /* If the second argument to this function is NULL, generate a
28515  ** temporary file name to use
28516  */
28517  if( !zUtf8Name ){
28518    int rc = getTempname(MAX_PATH+1, zTmpname);
28519    if( rc!=SQLITE_OK ){
28520      return rc;
28521    }
28522    zUtf8Name = zTmpname;
28523  }
28524
28525  /* Convert the filename to the system encoding. */
28526  zConverted = convertUtf8Filename(zUtf8Name);
28527  if( zConverted==0 ){
28528    return SQLITE_NOMEM;
28529  }
28530
28531  if( flags & SQLITE_OPEN_READWRITE ){
28532    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
28533  }else{
28534    dwDesiredAccess = GENERIC_READ;
28535  }
28536  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
28537  ** created. SQLite doesn't use it to indicate "exclusive access"
28538  ** as it is usually understood.
28539  */
28540  assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
28541  if( flags & SQLITE_OPEN_EXCLUSIVE ){
28542    /* Creates a new file, only if it does not already exist. */
28543    /* If the file exists, it fails. */
28544    dwCreationDisposition = CREATE_NEW;
28545  }else if( flags & SQLITE_OPEN_CREATE ){
28546    /* Open existing file, or create if it doesn't exist */
28547    dwCreationDisposition = OPEN_ALWAYS;
28548  }else{
28549    /* Opens a file, only if it exists. */
28550    dwCreationDisposition = OPEN_EXISTING;
28551  }
28552  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
28553  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
28554#if SQLITE_OS_WINCE
28555    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
28556    isTemp = 1;
28557#else
28558    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
28559                               | FILE_ATTRIBUTE_HIDDEN
28560                               | FILE_FLAG_DELETE_ON_CLOSE;
28561#endif
28562  }else{
28563    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
28564  }
28565  /* Reports from the internet are that performance is always
28566  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
28567#if SQLITE_OS_WINCE
28568  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
28569#endif
28570  if( isNT() ){
28571    h = CreateFileW((WCHAR*)zConverted,
28572       dwDesiredAccess,
28573       dwShareMode,
28574       NULL,
28575       dwCreationDisposition,
28576       dwFlagsAndAttributes,
28577       NULL
28578    );
28579/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28580** Since the ASCII version of these Windows API do not exist for WINCE,
28581** it's important to not reference them for WINCE builds.
28582*/
28583#if SQLITE_OS_WINCE==0
28584  }else{
28585    h = CreateFileA((char*)zConverted,
28586       dwDesiredAccess,
28587       dwShareMode,
28588       NULL,
28589       dwCreationDisposition,
28590       dwFlagsAndAttributes,
28591       NULL
28592    );
28593#endif
28594  }
28595  if( h==INVALID_HANDLE_VALUE ){
28596    free(zConverted);
28597    if( flags & SQLITE_OPEN_READWRITE ){
28598      return winOpen(pVfs, zName, id,
28599             ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
28600    }else{
28601      return SQLITE_CANTOPEN;
28602    }
28603  }
28604  if( pOutFlags ){
28605    if( flags & SQLITE_OPEN_READWRITE ){
28606      *pOutFlags = SQLITE_OPEN_READWRITE;
28607    }else{
28608      *pOutFlags = SQLITE_OPEN_READONLY;
28609    }
28610  }
28611  memset(pFile, 0, sizeof(*pFile));
28612  pFile->pMethod = &winIoMethod;
28613  pFile->h = h;
28614  pFile->lastErrno = NO_ERROR;
28615  pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
28616#if SQLITE_OS_WINCE
28617  if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
28618               (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
28619       && !winceCreateLock(zName, pFile)
28620  ){
28621    CloseHandle(h);
28622    free(zConverted);
28623    return SQLITE_CANTOPEN;
28624  }
28625  if( isTemp ){
28626    pFile->zDeleteOnClose = zConverted;
28627  }else
28628#endif
28629  {
28630    free(zConverted);
28631  }
28632  OpenCounter(+1);
28633  return SQLITE_OK;
28634}
28635
28636/*
28637** Delete the named file.
28638**
28639** Note that windows does not allow a file to be deleted if some other
28640** process has it open.  Sometimes a virus scanner or indexing program
28641** will open a journal file shortly after it is created in order to do
28642** whatever it does.  While this other process is holding the
28643** file open, we will be unable to delete it.  To work around this
28644** problem, we delay 100 milliseconds and try to delete again.  Up
28645** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
28646** up and returning an error.
28647*/
28648#define MX_DELETION_ATTEMPTS 5
28649static int winDelete(
28650  sqlite3_vfs *pVfs,          /* Not used on win32 */
28651  const char *zFilename,      /* Name of file to delete */
28652  int syncDir                 /* Not used on win32 */
28653){
28654  int cnt = 0;
28655  DWORD rc;
28656  DWORD error = 0;
28657  void *zConverted = convertUtf8Filename(zFilename);
28658  UNUSED_PARAMETER(pVfs);
28659  UNUSED_PARAMETER(syncDir);
28660  if( zConverted==0 ){
28661    return SQLITE_NOMEM;
28662  }
28663  SimulateIOError(return SQLITE_IOERR_DELETE);
28664  if( isNT() ){
28665    do{
28666      DeleteFileW(zConverted);
28667    }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
28668               || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
28669           && (++cnt < MX_DELETION_ATTEMPTS)
28670           && (Sleep(100), 1) );
28671/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28672** Since the ASCII version of these Windows API do not exist for WINCE,
28673** it's important to not reference them for WINCE builds.
28674*/
28675#if SQLITE_OS_WINCE==0
28676  }else{
28677    do{
28678      DeleteFileA(zConverted);
28679    }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
28680               || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
28681           && (++cnt < MX_DELETION_ATTEMPTS)
28682           && (Sleep(100), 1) );
28683#endif
28684  }
28685  free(zConverted);
28686  OSTRACE2("DELETE \"%s\"\n", zFilename);
28687  return (   (rc == INVALID_FILE_ATTRIBUTES)
28688          && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
28689}
28690
28691/*
28692** Check the existance and status of a file.
28693*/
28694static int winAccess(
28695  sqlite3_vfs *pVfs,         /* Not used on win32 */
28696  const char *zFilename,     /* Name of file to check */
28697  int flags,                 /* Type of test to make on this file */
28698  int *pResOut               /* OUT: Result */
28699){
28700  DWORD attr;
28701  int rc = 0;
28702  void *zConverted = convertUtf8Filename(zFilename);
28703  UNUSED_PARAMETER(pVfs);
28704  if( zConverted==0 ){
28705    return SQLITE_NOMEM;
28706  }
28707  if( isNT() ){
28708    attr = GetFileAttributesW((WCHAR*)zConverted);
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    attr = GetFileAttributesA((char*)zConverted);
28716#endif
28717  }
28718  free(zConverted);
28719  switch( flags ){
28720    case SQLITE_ACCESS_READ:
28721    case SQLITE_ACCESS_EXISTS:
28722      rc = attr!=INVALID_FILE_ATTRIBUTES;
28723      break;
28724    case SQLITE_ACCESS_READWRITE:
28725      rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
28726      break;
28727    default:
28728      assert(!"Invalid flags argument");
28729  }
28730  *pResOut = rc;
28731  return SQLITE_OK;
28732}
28733
28734
28735/*
28736** Turn a relative pathname into a full pathname.  Write the full
28737** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
28738** bytes in size.
28739*/
28740static int winFullPathname(
28741  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
28742  const char *zRelative,        /* Possibly relative input path */
28743  int nFull,                    /* Size of output buffer in bytes */
28744  char *zFull                   /* Output buffer */
28745){
28746
28747#if defined(__CYGWIN__)
28748  UNUSED_PARAMETER(nFull);
28749  cygwin_conv_to_full_win32_path(zRelative, zFull);
28750  return SQLITE_OK;
28751#endif
28752
28753#if SQLITE_OS_WINCE
28754  UNUSED_PARAMETER(nFull);
28755  /* WinCE has no concept of a relative pathname, or so I am told. */
28756  sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
28757  return SQLITE_OK;
28758#endif
28759
28760#if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
28761  int nByte;
28762  void *zConverted;
28763  char *zOut;
28764  UNUSED_PARAMETER(nFull);
28765  zConverted = convertUtf8Filename(zRelative);
28766  if( isNT() ){
28767    WCHAR *zTemp;
28768    nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
28769    zTemp = malloc( nByte*sizeof(zTemp[0]) );
28770    if( zTemp==0 ){
28771      free(zConverted);
28772      return SQLITE_NOMEM;
28773    }
28774    GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
28775    free(zConverted);
28776    zOut = unicodeToUtf8(zTemp);
28777    free(zTemp);
28778/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28779** Since the ASCII version of these Windows API do not exist for WINCE,
28780** it's important to not reference them for WINCE builds.
28781*/
28782#if SQLITE_OS_WINCE==0
28783  }else{
28784    char *zTemp;
28785    nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
28786    zTemp = malloc( nByte*sizeof(zTemp[0]) );
28787    if( zTemp==0 ){
28788      free(zConverted);
28789      return SQLITE_NOMEM;
28790    }
28791    GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
28792    free(zConverted);
28793    zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
28794    free(zTemp);
28795#endif
28796  }
28797  if( zOut ){
28798    sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
28799    free(zOut);
28800    return SQLITE_OK;
28801  }else{
28802    return SQLITE_NOMEM;
28803  }
28804#endif
28805}
28806
28807/*
28808** Get the sector size of the device used to store
28809** file.
28810*/
28811static int getSectorSize(
28812    sqlite3_vfs *pVfs,
28813    const char *zRelative     /* UTF-8 file name */
28814){
28815  DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
28816  /* GetDiskFreeSpace is not supported under WINCE */
28817#if SQLITE_OS_WINCE
28818  UNUSED_PARAMETER(pVfs);
28819  UNUSED_PARAMETER(zRelative);
28820#else
28821  char zFullpath[MAX_PATH+1];
28822  int rc;
28823  DWORD dwRet = 0;
28824  DWORD dwDummy;
28825
28826  /*
28827  ** We need to get the full path name of the file
28828  ** to get the drive letter to look up the sector
28829  ** size.
28830  */
28831  rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
28832  if( rc == SQLITE_OK )
28833  {
28834    void *zConverted = convertUtf8Filename(zFullpath);
28835    if( zConverted ){
28836      if( isNT() ){
28837        /* trim path to just drive reference */
28838        WCHAR *p = zConverted;
28839        for(;*p;p++){
28840          if( *p == '\\' ){
28841            *p = '\0';
28842            break;
28843          }
28844        }
28845        dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
28846                                  &dwDummy,
28847                                  &bytesPerSector,
28848                                  &dwDummy,
28849                                  &dwDummy);
28850      }else{
28851        /* trim path to just drive reference */
28852        char *p = (char *)zConverted;
28853        for(;*p;p++){
28854          if( *p == '\\' ){
28855            *p = '\0';
28856            break;
28857          }
28858        }
28859        dwRet = GetDiskFreeSpaceA((char*)zConverted,
28860                                  &dwDummy,
28861                                  &bytesPerSector,
28862                                  &dwDummy,
28863                                  &dwDummy);
28864      }
28865      free(zConverted);
28866    }
28867    if( !dwRet ){
28868      bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
28869    }
28870  }
28871#endif
28872  return (int) bytesPerSector;
28873}
28874
28875#ifndef SQLITE_OMIT_LOAD_EXTENSION
28876/*
28877** Interfaces for opening a shared library, finding entry points
28878** within the shared library, and closing the shared library.
28879*/
28880/*
28881** Interfaces for opening a shared library, finding entry points
28882** within the shared library, and closing the shared library.
28883*/
28884static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
28885  HANDLE h;
28886  void *zConverted = convertUtf8Filename(zFilename);
28887  UNUSED_PARAMETER(pVfs);
28888  if( zConverted==0 ){
28889    return 0;
28890  }
28891  if( isNT() ){
28892    h = LoadLibraryW((WCHAR*)zConverted);
28893/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28894** Since the ASCII version of these Windows API do not exist for WINCE,
28895** it's important to not reference them for WINCE builds.
28896*/
28897#if SQLITE_OS_WINCE==0
28898  }else{
28899    h = LoadLibraryA((char*)zConverted);
28900#endif
28901  }
28902  free(zConverted);
28903  return (void*)h;
28904}
28905static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
28906  UNUSED_PARAMETER(pVfs);
28907  getLastErrorMsg(nBuf, zBufOut);
28908}
28909void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
28910  UNUSED_PARAMETER(pVfs);
28911#if SQLITE_OS_WINCE
28912  /* The GetProcAddressA() routine is only available on wince. */
28913  return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
28914#else
28915  /* All other windows platforms expect GetProcAddress() to take
28916  ** an Ansi string regardless of the _UNICODE setting */
28917  return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
28918#endif
28919}
28920void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
28921  UNUSED_PARAMETER(pVfs);
28922  FreeLibrary((HANDLE)pHandle);
28923}
28924#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
28925  #define winDlOpen  0
28926  #define winDlError 0
28927  #define winDlSym   0
28928  #define winDlClose 0
28929#endif
28930
28931
28932/*
28933** Write up to nBuf bytes of randomness into zBuf.
28934*/
28935static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
28936  int n = 0;
28937  UNUSED_PARAMETER(pVfs);
28938#if defined(SQLITE_TEST)
28939  n = nBuf;
28940  memset(zBuf, 0, nBuf);
28941#else
28942  if( sizeof(SYSTEMTIME)<=nBuf-n ){
28943    SYSTEMTIME x;
28944    GetSystemTime(&x);
28945    memcpy(&zBuf[n], &x, sizeof(x));
28946    n += sizeof(x);
28947  }
28948  if( sizeof(DWORD)<=nBuf-n ){
28949    DWORD pid = GetCurrentProcessId();
28950    memcpy(&zBuf[n], &pid, sizeof(pid));
28951    n += sizeof(pid);
28952  }
28953  if( sizeof(DWORD)<=nBuf-n ){
28954    DWORD cnt = GetTickCount();
28955    memcpy(&zBuf[n], &cnt, sizeof(cnt));
28956    n += sizeof(cnt);
28957  }
28958  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
28959    LARGE_INTEGER i;
28960    QueryPerformanceCounter(&i);
28961    memcpy(&zBuf[n], &i, sizeof(i));
28962    n += sizeof(i);
28963  }
28964#endif
28965  return n;
28966}
28967
28968
28969/*
28970** Sleep for a little while.  Return the amount of time slept.
28971*/
28972static int winSleep(sqlite3_vfs *pVfs, int microsec){
28973  Sleep((microsec+999)/1000);
28974  UNUSED_PARAMETER(pVfs);
28975  return ((microsec+999)/1000)*1000;
28976}
28977
28978/*
28979** The following variable, if set to a non-zero value, becomes the result
28980** returned from sqlite3OsCurrentTime().  This is used for testing.
28981*/
28982#ifdef SQLITE_TEST
28983SQLITE_API int sqlite3_current_time = 0;
28984#endif
28985
28986/*
28987** Find the current time (in Universal Coordinated Time).  Write the
28988** current time and date as a Julian Day number into *prNow and
28989** return 0.  Return 1 if the time and date cannot be found.
28990*/
28991int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
28992  FILETIME ft;
28993  /* FILETIME structure is a 64-bit value representing the number of
28994     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
28995  */
28996  sqlite3_int64 timeW;   /* Whole days */
28997  sqlite3_int64 timeF;   /* Fractional Days */
28998
28999  /* Number of 100-nanosecond intervals in a single day */
29000  static const sqlite3_int64 ntuPerDay =
29001      10000000*(sqlite3_int64)86400;
29002
29003  /* Number of 100-nanosecond intervals in half of a day */
29004  static const sqlite3_int64 ntuPerHalfDay =
29005      10000000*(sqlite3_int64)43200;
29006
29007  /* 2^32 - to avoid use of LL and warnings in gcc */
29008  static const sqlite3_int64 max32BitValue =
29009      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
29010
29011#if SQLITE_OS_WINCE
29012  SYSTEMTIME time;
29013  GetSystemTime(&time);
29014  /* if SystemTimeToFileTime() fails, it returns zero. */
29015  if (!SystemTimeToFileTime(&time,&ft)){
29016    return 1;
29017  }
29018#else
29019  GetSystemTimeAsFileTime( &ft );
29020#endif
29021  UNUSED_PARAMETER(pVfs);
29022  timeW = (((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + (sqlite3_int64)ft.dwLowDateTime;
29023  timeF = timeW % ntuPerDay;          /* fractional days (100-nanoseconds) */
29024  timeW = timeW / ntuPerDay;          /* whole days */
29025  timeW = timeW + 2305813;            /* add whole days (from 2305813.5) */
29026  timeF = timeF + ntuPerHalfDay;      /* add half a day (from 2305813.5) */
29027  timeW = timeW + (timeF/ntuPerDay);  /* add whole day if half day made one */
29028  timeF = timeF % ntuPerDay;          /* compute new fractional days */
29029  *prNow = (double)timeW + ((double)timeF / (double)ntuPerDay);
29030#ifdef SQLITE_TEST
29031  if( sqlite3_current_time ){
29032    *prNow = ((double)sqlite3_current_time + (double)43200) / (double)86400 + (double)2440587;
29033  }
29034#endif
29035  return 0;
29036}
29037
29038/*
29039** The idea is that this function works like a combination of
29040** GetLastError() and FormatMessage() on windows (or errno and
29041** strerror_r() on unix). After an error is returned by an OS
29042** function, SQLite calls this function with zBuf pointing to
29043** a buffer of nBuf bytes. The OS layer should populate the
29044** buffer with a nul-terminated UTF-8 encoded error message
29045** describing the last IO error to have occurred within the calling
29046** thread.
29047**
29048** If the error message is too large for the supplied buffer,
29049** it should be truncated. The return value of xGetLastError
29050** is zero if the error message fits in the buffer, or non-zero
29051** otherwise (if the message was truncated). If non-zero is returned,
29052** then it is not necessary to include the nul-terminator character
29053** in the output buffer.
29054**
29055** Not supplying an error message will have no adverse effect
29056** on SQLite. It is fine to have an implementation that never
29057** returns an error message:
29058**
29059**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
29060**     assert(zBuf[0]=='\0');
29061**     return 0;
29062**   }
29063**
29064** However if an error message is supplied, it will be incorporated
29065** by sqlite into the error message available to the user using
29066** sqlite3_errmsg(), possibly making IO errors easier to debug.
29067*/
29068static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
29069  UNUSED_PARAMETER(pVfs);
29070  return getLastErrorMsg(nBuf, zBuf);
29071}
29072
29073/*
29074** Initialize and deinitialize the operating system interface.
29075*/
29076SQLITE_API int sqlite3_os_init(void){
29077  static sqlite3_vfs winVfs = {
29078    1,                 /* iVersion */
29079    sizeof(winFile),   /* szOsFile */
29080    MAX_PATH,          /* mxPathname */
29081    0,                 /* pNext */
29082    "win32",           /* zName */
29083    0,                 /* pAppData */
29084
29085    winOpen,           /* xOpen */
29086    winDelete,         /* xDelete */
29087    winAccess,         /* xAccess */
29088    winFullPathname,   /* xFullPathname */
29089    winDlOpen,         /* xDlOpen */
29090    winDlError,        /* xDlError */
29091    winDlSym,          /* xDlSym */
29092    winDlClose,        /* xDlClose */
29093    winRandomness,     /* xRandomness */
29094    winSleep,          /* xSleep */
29095    winCurrentTime,    /* xCurrentTime */
29096    winGetLastError    /* xGetLastError */
29097  };
29098
29099  sqlite3_vfs_register(&winVfs, 1);
29100  return SQLITE_OK;
29101}
29102SQLITE_API int sqlite3_os_end(void){
29103  return SQLITE_OK;
29104}
29105
29106#endif /* SQLITE_OS_WIN */
29107
29108/************** End of os_win.c **********************************************/
29109/************** Begin file bitvec.c ******************************************/
29110/*
29111** 2008 February 16
29112**
29113** The author disclaims copyright to this source code.  In place of
29114** a legal notice, here is a blessing:
29115**
29116**    May you do good and not evil.
29117**    May you find forgiveness for yourself and forgive others.
29118**    May you share freely, never taking more than you give.
29119**
29120*************************************************************************
29121** This file implements an object that represents a fixed-length
29122** bitmap.  Bits are numbered starting with 1.
29123**
29124** A bitmap is used to record which pages of a database file have been
29125** journalled during a transaction, or which pages have the "dont-write"
29126** property.  Usually only a few pages are meet either condition.
29127** So the bitmap is usually sparse and has low cardinality.
29128** But sometimes (for example when during a DROP of a large table) most
29129** or all of the pages in a database can get journalled.  In those cases,
29130** the bitmap becomes dense with high cardinality.  The algorithm needs
29131** to handle both cases well.
29132**
29133** The size of the bitmap is fixed when the object is created.
29134**
29135** All bits are clear when the bitmap is created.  Individual bits
29136** may be set or cleared one at a time.
29137**
29138** Test operations are about 100 times more common that set operations.
29139** Clear operations are exceedingly rare.  There are usually between
29140** 5 and 500 set operations per Bitvec object, though the number of sets can
29141** sometimes grow into tens of thousands or larger.  The size of the
29142** Bitvec object is the number of pages in the database file at the
29143** start of a transaction, and is thus usually less than a few thousand,
29144** but can be as large as 2 billion for a really big database.
29145*/
29146
29147/* Size of the Bitvec structure in bytes. */
29148#define BITVEC_SZ        (sizeof(void*)*128)  /* 512 on 32bit.  1024 on 64bit */
29149
29150/* Round the union size down to the nearest pointer boundary, since that's how
29151** it will be aligned within the Bitvec struct. */
29152#define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
29153
29154/* Type of the array "element" for the bitmap representation.
29155** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
29156** Setting this to the "natural word" size of your CPU may improve
29157** performance. */
29158#define BITVEC_TELEM     u8
29159/* Size, in bits, of the bitmap element. */
29160#define BITVEC_SZELEM    8
29161/* Number of elements in a bitmap array. */
29162#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
29163/* Number of bits in the bitmap array. */
29164#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
29165
29166/* Number of u32 values in hash table. */
29167#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
29168/* Maximum number of entries in hash table before
29169** sub-dividing and re-hashing. */
29170#define BITVEC_MXHASH    (BITVEC_NINT/2)
29171/* Hashing function for the aHash representation.
29172** Empirical testing showed that the *37 multiplier
29173** (an arbitrary prime)in the hash function provided
29174** no fewer collisions than the no-op *1. */
29175#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
29176
29177#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
29178
29179
29180/*
29181** A bitmap is an instance of the following structure.
29182**
29183** This bitmap records the existance of zero or more bits
29184** with values between 1 and iSize, inclusive.
29185**
29186** There are three possible representations of the bitmap.
29187** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
29188** bitmap.  The least significant bit is bit 1.
29189**
29190** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
29191** a hash table that will hold up to BITVEC_MXHASH distinct values.
29192**
29193** Otherwise, the value i is redirected into one of BITVEC_NPTR
29194** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
29195** handles up to iDivisor separate values of i.  apSub[0] holds
29196** values between 1 and iDivisor.  apSub[1] holds values between
29197** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
29198** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
29199** to hold deal with values between 1 and iDivisor.
29200*/
29201struct Bitvec {
29202  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
29203  u32 nSet;       /* Number of bits that are set - only valid for aHash
29204                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
29205                  ** this would be 125. */
29206  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
29207                  /* Should >=0 for apSub element. */
29208                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
29209                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
29210  union {
29211    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
29212    u32 aHash[BITVEC_NINT];      /* Hash table representation */
29213    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
29214  } u;
29215};
29216
29217/*
29218** Create a new bitmap object able to handle bits between 0 and iSize,
29219** inclusive.  Return a pointer to the new object.  Return NULL if
29220** malloc fails.
29221*/
29222SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
29223  Bitvec *p;
29224  assert( sizeof(*p)==BITVEC_SZ );
29225  p = sqlite3MallocZero( sizeof(*p) );
29226  if( p ){
29227    p->iSize = iSize;
29228  }
29229  return p;
29230}
29231
29232/*
29233** Check to see if the i-th bit is set.  Return true or false.
29234** If p is NULL (if the bitmap has not been created) or if
29235** i is out of range, then return false.
29236*/
29237SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
29238  if( p==0 ) return 0;
29239  if( i>p->iSize || i==0 ) return 0;
29240  i--;
29241  while( p->iDivisor ){
29242    u32 bin = i/p->iDivisor;
29243    i = i%p->iDivisor;
29244    p = p->u.apSub[bin];
29245    if (!p) {
29246      return 0;
29247    }
29248  }
29249  if( p->iSize<=BITVEC_NBIT ){
29250    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
29251  } else{
29252    u32 h = BITVEC_HASH(i++);
29253    while( p->u.aHash[h] ){
29254      if( p->u.aHash[h]==i ) return 1;
29255      h = (h+1) % BITVEC_NINT;
29256    }
29257    return 0;
29258  }
29259}
29260
29261/*
29262** Set the i-th bit.  Return 0 on success and an error code if
29263** anything goes wrong.
29264**
29265** This routine might cause sub-bitmaps to be allocated.  Failing
29266** to get the memory needed to hold the sub-bitmap is the only
29267** that can go wrong with an insert, assuming p and i are valid.
29268**
29269** The calling function must ensure that p is a valid Bitvec object
29270** and that the value for "i" is within range of the Bitvec object.
29271** Otherwise the behavior is undefined.
29272*/
29273SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
29274  u32 h;
29275  if( p==0 ) return SQLITE_OK;
29276  assert( i>0 );
29277  assert( i<=p->iSize );
29278  i--;
29279  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
29280    u32 bin = i/p->iDivisor;
29281    i = i%p->iDivisor;
29282    if( p->u.apSub[bin]==0 ){
29283      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
29284      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
29285    }
29286    p = p->u.apSub[bin];
29287  }
29288  if( p->iSize<=BITVEC_NBIT ){
29289    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
29290    return SQLITE_OK;
29291  }
29292  h = BITVEC_HASH(i++);
29293  /* if there wasn't a hash collision, and this doesn't */
29294  /* completely fill the hash, then just add it without */
29295  /* worring about sub-dividing and re-hashing. */
29296  if( !p->u.aHash[h] ){
29297    if (p->nSet<(BITVEC_NINT-1)) {
29298      goto bitvec_set_end;
29299    } else {
29300      goto bitvec_set_rehash;
29301    }
29302  }
29303  /* there was a collision, check to see if it's already */
29304  /* in hash, if not, try to find a spot for it */
29305  do {
29306    if( p->u.aHash[h]==i ) return SQLITE_OK;
29307    h++;
29308    if( h>=BITVEC_NINT ) h = 0;
29309  } while( p->u.aHash[h] );
29310  /* we didn't find it in the hash.  h points to the first */
29311  /* available free spot. check to see if this is going to */
29312  /* make our hash too "full".  */
29313bitvec_set_rehash:
29314  if( p->nSet>=BITVEC_MXHASH ){
29315    unsigned int j;
29316    int rc;
29317    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
29318    if( aiValues==0 ){
29319      return SQLITE_NOMEM;
29320    }else{
29321      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
29322      memset(p->u.apSub, 0, sizeof(p->u.apSub));
29323      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
29324      rc = sqlite3BitvecSet(p, i);
29325      for(j=0; j<BITVEC_NINT; j++){
29326        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
29327      }
29328      sqlite3StackFree(0, aiValues);
29329      return rc;
29330    }
29331  }
29332bitvec_set_end:
29333  p->nSet++;
29334  p->u.aHash[h] = i;
29335  return SQLITE_OK;
29336}
29337
29338/*
29339** Clear the i-th bit.
29340**
29341** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
29342** that BitvecClear can use to rebuilt its hash table.
29343*/
29344SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
29345  if( p==0 ) return;
29346  assert( i>0 );
29347  i--;
29348  while( p->iDivisor ){
29349    u32 bin = i/p->iDivisor;
29350    i = i%p->iDivisor;
29351    p = p->u.apSub[bin];
29352    if (!p) {
29353      return;
29354    }
29355  }
29356  if( p->iSize<=BITVEC_NBIT ){
29357    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
29358  }else{
29359    unsigned int j;
29360    u32 *aiValues = pBuf;
29361    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
29362    memset(p->u.aHash, 0, sizeof(p->u.aHash));
29363    p->nSet = 0;
29364    for(j=0; j<BITVEC_NINT; j++){
29365      if( aiValues[j] && aiValues[j]!=(i+1) ){
29366        u32 h = BITVEC_HASH(aiValues[j]-1);
29367        p->nSet++;
29368        while( p->u.aHash[h] ){
29369          h++;
29370          if( h>=BITVEC_NINT ) h = 0;
29371        }
29372        p->u.aHash[h] = aiValues[j];
29373      }
29374    }
29375  }
29376}
29377
29378/*
29379** Destroy a bitmap object.  Reclaim all memory used.
29380*/
29381SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
29382  if( p==0 ) return;
29383  if( p->iDivisor ){
29384    unsigned int i;
29385    for(i=0; i<BITVEC_NPTR; i++){
29386      sqlite3BitvecDestroy(p->u.apSub[i]);
29387    }
29388  }
29389  sqlite3_free(p);
29390}
29391
29392/*
29393** Return the value of the iSize parameter specified when Bitvec *p
29394** was created.
29395*/
29396SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
29397  return p->iSize;
29398}
29399
29400#ifndef SQLITE_OMIT_BUILTIN_TEST
29401/*
29402** Let V[] be an array of unsigned characters sufficient to hold
29403** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
29404** Then the following macros can be used to set, clear, or test
29405** individual bits within V.
29406*/
29407#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
29408#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
29409#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
29410
29411/*
29412** This routine runs an extensive test of the Bitvec code.
29413**
29414** The input is an array of integers that acts as a program
29415** to test the Bitvec.  The integers are opcodes followed
29416** by 0, 1, or 3 operands, depending on the opcode.  Another
29417** opcode follows immediately after the last operand.
29418**
29419** There are 6 opcodes numbered from 0 through 5.  0 is the
29420** "halt" opcode and causes the test to end.
29421**
29422**    0          Halt and return the number of errors
29423**    1 N S X    Set N bits beginning with S and incrementing by X
29424**    2 N S X    Clear N bits beginning with S and incrementing by X
29425**    3 N        Set N randomly chosen bits
29426**    4 N        Clear N randomly chosen bits
29427**    5 N S X    Set N bits from S increment X in array only, not in bitvec
29428**
29429** The opcodes 1 through 4 perform set and clear operations are performed
29430** on both a Bitvec object and on a linear array of bits obtained from malloc.
29431** Opcode 5 works on the linear array only, not on the Bitvec.
29432** Opcode 5 is used to deliberately induce a fault in order to
29433** confirm that error detection works.
29434**
29435** At the conclusion of the test the linear array is compared
29436** against the Bitvec object.  If there are any differences,
29437** an error is returned.  If they are the same, zero is returned.
29438**
29439** If a memory allocation error occurs, return -1.
29440*/
29441SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
29442  Bitvec *pBitvec = 0;
29443  unsigned char *pV = 0;
29444  int rc = -1;
29445  int i, nx, pc, op;
29446  void *pTmpSpace;
29447
29448  /* Allocate the Bitvec to be tested and a linear array of
29449  ** bits to act as the reference */
29450  pBitvec = sqlite3BitvecCreate( sz );
29451  pV = sqlite3_malloc( (sz+7)/8 + 1 );
29452  pTmpSpace = sqlite3_malloc(BITVEC_SZ);
29453  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
29454  memset(pV, 0, (sz+7)/8 + 1);
29455
29456  /* NULL pBitvec tests */
29457  sqlite3BitvecSet(0, 1);
29458  sqlite3BitvecClear(0, 1, pTmpSpace);
29459
29460  /* Run the program */
29461  pc = 0;
29462  while( (op = aOp[pc])!=0 ){
29463    switch( op ){
29464      case 1:
29465      case 2:
29466      case 5: {
29467        nx = 4;
29468        i = aOp[pc+2] - 1;
29469        aOp[pc+2] += aOp[pc+3];
29470        break;
29471      }
29472      case 3:
29473      case 4:
29474      default: {
29475        nx = 2;
29476        sqlite3_randomness(sizeof(i), &i);
29477        break;
29478      }
29479    }
29480    if( (--aOp[pc+1]) > 0 ) nx = 0;
29481    pc += nx;
29482    i = (i & 0x7fffffff)%sz;
29483    if( (op & 1)!=0 ){
29484      SETBIT(pV, (i+1));
29485      if( op!=5 ){
29486        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
29487      }
29488    }else{
29489      CLEARBIT(pV, (i+1));
29490      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
29491    }
29492  }
29493
29494  /* Test to make sure the linear array exactly matches the
29495  ** Bitvec object.  Start with the assumption that they do
29496  ** match (rc==0).  Change rc to non-zero if a discrepancy
29497  ** is found.
29498  */
29499  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
29500          + sqlite3BitvecTest(pBitvec, 0)
29501          + (sqlite3BitvecSize(pBitvec) - sz);
29502  for(i=1; i<=sz; i++){
29503    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
29504      rc = i;
29505      break;
29506    }
29507  }
29508
29509  /* Free allocated structure */
29510bitvec_end:
29511  sqlite3_free(pTmpSpace);
29512  sqlite3_free(pV);
29513  sqlite3BitvecDestroy(pBitvec);
29514  return rc;
29515}
29516#endif /* SQLITE_OMIT_BUILTIN_TEST */
29517
29518/************** End of bitvec.c **********************************************/
29519/************** Begin file pcache.c ******************************************/
29520/*
29521** 2008 August 05
29522**
29523** The author disclaims copyright to this source code.  In place of
29524** a legal notice, here is a blessing:
29525**
29526**    May you do good and not evil.
29527**    May you find forgiveness for yourself and forgive others.
29528**    May you share freely, never taking more than you give.
29529**
29530*************************************************************************
29531** This file implements that page cache.
29532*/
29533
29534/*
29535** A complete page cache is an instance of this structure.
29536*/
29537struct PCache {
29538  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
29539  PgHdr *pSynced;                     /* Last synced page in dirty page list */
29540  int nRef;                           /* Number of referenced pages */
29541  int nMax;                           /* Configured cache size */
29542  int szPage;                         /* Size of every page in this cache */
29543  int szExtra;                        /* Size of extra space for each page */
29544  int bPurgeable;                     /* True if pages are on backing store */
29545  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
29546  void *pStress;                      /* Argument to xStress */
29547  sqlite3_pcache *pCache;             /* Pluggable cache module */
29548  PgHdr *pPage1;                      /* Reference to page 1 */
29549};
29550
29551/*
29552** Some of the assert() macros in this code are too expensive to run
29553** even during normal debugging.  Use them only rarely on long-running
29554** tests.  Enable the expensive asserts using the
29555** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
29556*/
29557#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
29558# define expensive_assert(X)  assert(X)
29559#else
29560# define expensive_assert(X)
29561#endif
29562
29563/********************************** Linked List Management ********************/
29564
29565#if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
29566/*
29567** Check that the pCache->pSynced variable is set correctly. If it
29568** is not, either fail an assert or return zero. Otherwise, return
29569** non-zero. This is only used in debugging builds, as follows:
29570**
29571**   expensive_assert( pcacheCheckSynced(pCache) );
29572*/
29573static int pcacheCheckSynced(PCache *pCache){
29574  PgHdr *p;
29575  for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
29576    assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
29577  }
29578  return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
29579}
29580#endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
29581
29582/*
29583** Remove page pPage from the list of dirty pages.
29584*/
29585static void pcacheRemoveFromDirtyList(PgHdr *pPage){
29586  PCache *p = pPage->pCache;
29587
29588  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
29589  assert( pPage->pDirtyPrev || pPage==p->pDirty );
29590
29591  /* Update the PCache1.pSynced variable if necessary. */
29592  if( p->pSynced==pPage ){
29593    PgHdr *pSynced = pPage->pDirtyPrev;
29594    while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
29595      pSynced = pSynced->pDirtyPrev;
29596    }
29597    p->pSynced = pSynced;
29598  }
29599
29600  if( pPage->pDirtyNext ){
29601    pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
29602  }else{
29603    assert( pPage==p->pDirtyTail );
29604    p->pDirtyTail = pPage->pDirtyPrev;
29605  }
29606  if( pPage->pDirtyPrev ){
29607    pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
29608  }else{
29609    assert( pPage==p->pDirty );
29610    p->pDirty = pPage->pDirtyNext;
29611  }
29612  pPage->pDirtyNext = 0;
29613  pPage->pDirtyPrev = 0;
29614
29615  expensive_assert( pcacheCheckSynced(p) );
29616}
29617
29618/*
29619** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
29620** pPage).
29621*/
29622static void pcacheAddToDirtyList(PgHdr *pPage){
29623  PCache *p = pPage->pCache;
29624
29625  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
29626
29627  pPage->pDirtyNext = p->pDirty;
29628  if( pPage->pDirtyNext ){
29629    assert( pPage->pDirtyNext->pDirtyPrev==0 );
29630    pPage->pDirtyNext->pDirtyPrev = pPage;
29631  }
29632  p->pDirty = pPage;
29633  if( !p->pDirtyTail ){
29634    p->pDirtyTail = pPage;
29635  }
29636  if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
29637    p->pSynced = pPage;
29638  }
29639  expensive_assert( pcacheCheckSynced(p) );
29640}
29641
29642/*
29643** Wrapper around the pluggable caches xUnpin method. If the cache is
29644** being used for an in-memory database, this function is a no-op.
29645*/
29646static void pcacheUnpin(PgHdr *p){
29647  PCache *pCache = p->pCache;
29648  if( pCache->bPurgeable ){
29649    if( p->pgno==1 ){
29650      pCache->pPage1 = 0;
29651    }
29652    sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
29653  }
29654}
29655
29656/*************************************************** General Interfaces ******
29657**
29658** Initialize and shutdown the page cache subsystem. Neither of these
29659** functions are threadsafe.
29660*/
29661SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
29662  if( sqlite3GlobalConfig.pcache.xInit==0 ){
29663    sqlite3PCacheSetDefault();
29664  }
29665  return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
29666}
29667SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
29668  if( sqlite3GlobalConfig.pcache.xShutdown ){
29669    sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
29670  }
29671}
29672
29673/*
29674** Return the size in bytes of a PCache object.
29675*/
29676SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
29677
29678/*
29679** Create a new PCache object. Storage space to hold the object
29680** has already been allocated and is passed in as the p pointer.
29681** The caller discovers how much space needs to be allocated by
29682** calling sqlite3PcacheSize().
29683*/
29684SQLITE_PRIVATE void sqlite3PcacheOpen(
29685  int szPage,                  /* Size of every page */
29686  int szExtra,                 /* Extra space associated with each page */
29687  int bPurgeable,              /* True if pages are on backing store */
29688  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
29689  void *pStress,               /* Argument to xStress */
29690  PCache *p                    /* Preallocated space for the PCache */
29691){
29692  memset(p, 0, sizeof(PCache));
29693  p->szPage = szPage;
29694  p->szExtra = szExtra;
29695  p->bPurgeable = bPurgeable;
29696  p->xStress = xStress;
29697  p->pStress = pStress;
29698  p->nMax = 100;
29699}
29700
29701/*
29702** Change the page size for PCache object. The caller must ensure that there
29703** are no outstanding page references when this function is called.
29704*/
29705SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
29706  assert( pCache->nRef==0 && pCache->pDirty==0 );
29707  if( pCache->pCache ){
29708    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
29709    pCache->pCache = 0;
29710  }
29711  pCache->szPage = szPage;
29712}
29713
29714/*
29715** Try to obtain a page from the cache.
29716*/
29717SQLITE_PRIVATE int sqlite3PcacheFetch(
29718  PCache *pCache,       /* Obtain the page from this cache */
29719  Pgno pgno,            /* Page number to obtain */
29720  int createFlag,       /* If true, create page if it does not exist already */
29721  PgHdr **ppPage        /* Write the page here */
29722){
29723  PgHdr *pPage = 0;
29724  int eCreate;
29725
29726  assert( pCache!=0 );
29727  assert( createFlag==1 || createFlag==0 );
29728  assert( pgno>0 );
29729
29730  /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
29731  ** allocate it now.
29732  */
29733  if( !pCache->pCache && createFlag ){
29734    sqlite3_pcache *p;
29735    int nByte;
29736    nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
29737    p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
29738    if( !p ){
29739      return SQLITE_NOMEM;
29740    }
29741    sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
29742    pCache->pCache = p;
29743  }
29744
29745  eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
29746  if( pCache->pCache ){
29747    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
29748  }
29749
29750  if( !pPage && eCreate==1 ){
29751    PgHdr *pPg;
29752
29753    /* Find a dirty page to write-out and recycle. First try to find a
29754    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
29755    ** cleared), but if that is not possible settle for any other
29756    ** unreferenced dirty page.
29757    */
29758    expensive_assert( pcacheCheckSynced(pCache) );
29759    for(pPg=pCache->pSynced;
29760        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
29761        pPg=pPg->pDirtyPrev
29762    );
29763    pCache->pSynced = pPg;  // http://www.sqlite.org/src/ci/26cb1df735
29764    if( !pPg ){
29765      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
29766    }
29767    if( pPg ){
29768      int rc;
29769      rc = pCache->xStress(pCache->pStress, pPg);
29770      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
29771        return rc;
29772      }
29773    }
29774
29775    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
29776  }
29777
29778  if( pPage ){
29779    if( !pPage->pData ){
29780      memset(pPage, 0, sizeof(PgHdr) + pCache->szExtra);
29781      pPage->pExtra = (void*)&pPage[1];
29782      pPage->pData = (void *)&((char *)pPage)[sizeof(PgHdr) + pCache->szExtra];
29783      pPage->pCache = pCache;
29784      pPage->pgno = pgno;
29785    }
29786    assert( pPage->pCache==pCache );
29787    assert( pPage->pgno==pgno );
29788    assert( pPage->pExtra==(void *)&pPage[1] );
29789
29790    if( 0==pPage->nRef ){
29791      pCache->nRef++;
29792    }
29793    pPage->nRef++;
29794    if( pgno==1 ){
29795      pCache->pPage1 = pPage;
29796    }
29797  }
29798  *ppPage = pPage;
29799  return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
29800}
29801
29802/*
29803** Decrement the reference count on a page. If the page is clean and the
29804** reference count drops to 0, then it is made elible for recycling.
29805*/
29806SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
29807  assert( p->nRef>0 );
29808  p->nRef--;
29809  if( p->nRef==0 ){
29810    PCache *pCache = p->pCache;
29811    pCache->nRef--;
29812    if( (p->flags&PGHDR_DIRTY)==0 ){
29813      pcacheUnpin(p);
29814    }else{
29815      /* Move the page to the head of the dirty list. */
29816      pcacheRemoveFromDirtyList(p);
29817      pcacheAddToDirtyList(p);
29818    }
29819  }
29820}
29821
29822/*
29823** Increase the reference count of a supplied page by 1.
29824*/
29825SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
29826  assert(p->nRef>0);
29827  p->nRef++;
29828}
29829
29830/*
29831** Drop a page from the cache. There must be exactly one reference to the
29832** page. This function deletes that reference, so after it returns the
29833** page pointed to by p is invalid.
29834*/
29835SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
29836  PCache *pCache;
29837  assert( p->nRef==1 );
29838  if( p->flags&PGHDR_DIRTY ){
29839    pcacheRemoveFromDirtyList(p);
29840  }
29841  pCache = p->pCache;
29842  pCache->nRef--;
29843  if( p->pgno==1 ){
29844    pCache->pPage1 = 0;
29845  }
29846  sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
29847}
29848
29849/*
29850** Make sure the page is marked as dirty. If it isn't dirty already,
29851** make it so.
29852*/
29853SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
29854  p->flags &= ~PGHDR_DONT_WRITE;
29855  assert( p->nRef>0 );
29856  if( 0==(p->flags & PGHDR_DIRTY) ){
29857    p->flags |= PGHDR_DIRTY;
29858    pcacheAddToDirtyList( p);
29859  }
29860}
29861
29862/*
29863** Make sure the page is marked as clean. If it isn't clean already,
29864** make it so.
29865*/
29866SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
29867  if( (p->flags & PGHDR_DIRTY) ){
29868    pcacheRemoveFromDirtyList(p);
29869    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
29870    if( p->nRef==0 ){
29871      pcacheUnpin(p);
29872    }
29873  }
29874}
29875
29876/*
29877** Make every page in the cache clean.
29878*/
29879SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
29880  PgHdr *p;
29881  while( (p = pCache->pDirty)!=0 ){
29882    sqlite3PcacheMakeClean(p);
29883  }
29884}
29885
29886/*
29887** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
29888*/
29889SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
29890  PgHdr *p;
29891  for(p=pCache->pDirty; p; p=p->pDirtyNext){
29892    p->flags &= ~PGHDR_NEED_SYNC;
29893  }
29894  pCache->pSynced = pCache->pDirtyTail;
29895}
29896
29897/*
29898** Change the page number of page p to newPgno.
29899*/
29900SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
29901  PCache *pCache = p->pCache;
29902  assert( p->nRef>0 );
29903  assert( newPgno>0 );
29904  sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
29905  p->pgno = newPgno;
29906  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
29907    pcacheRemoveFromDirtyList(p);
29908    pcacheAddToDirtyList(p);
29909  }
29910}
29911
29912/*
29913** Drop every cache entry whose page number is greater than "pgno". The
29914** caller must ensure that there are no outstanding references to any pages
29915** other than page 1 with a page number greater than pgno.
29916**
29917** If there is a reference to page 1 and the pgno parameter passed to this
29918** function is 0, then the data area associated with page 1 is zeroed, but
29919** the page object is not dropped.
29920*/
29921SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
29922  if( pCache->pCache ){
29923    PgHdr *p;
29924    PgHdr *pNext;
29925    for(p=pCache->pDirty; p; p=pNext){
29926      pNext = p->pDirtyNext;
29927      if( p->pgno>pgno ){
29928        assert( p->flags&PGHDR_DIRTY );
29929        sqlite3PcacheMakeClean(p);
29930      }
29931    }
29932    if( pgno==0 && pCache->pPage1 ){
29933      memset(pCache->pPage1->pData, 0, pCache->szPage);
29934      pgno = 1;
29935    }
29936    sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
29937  }
29938}
29939
29940/*
29941** Close a cache.
29942*/
29943SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
29944  if( pCache->pCache ){
29945    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
29946  }
29947}
29948
29949/*
29950** Discard the contents of the cache.
29951*/
29952SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
29953  sqlite3PcacheTruncate(pCache, 0);
29954}
29955
29956/*
29957** Merge two lists of pages connected by pDirty and in pgno order.
29958** Do not both fixing the pDirtyPrev pointers.
29959*/
29960static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
29961  PgHdr result, *pTail;
29962  pTail = &result;
29963  while( pA && pB ){
29964    if( pA->pgno<pB->pgno ){
29965      pTail->pDirty = pA;
29966      pTail = pA;
29967      pA = pA->pDirty;
29968    }else{
29969      pTail->pDirty = pB;
29970      pTail = pB;
29971      pB = pB->pDirty;
29972    }
29973  }
29974  if( pA ){
29975    pTail->pDirty = pA;
29976  }else if( pB ){
29977    pTail->pDirty = pB;
29978  }else{
29979    pTail->pDirty = 0;
29980  }
29981  return result.pDirty;
29982}
29983
29984/*
29985** Sort the list of pages in accending order by pgno.  Pages are
29986** connected by pDirty pointers.  The pDirtyPrev pointers are
29987** corrupted by this sort.
29988**
29989** Since there cannot be more than 2^31 distinct pages in a database,
29990** there cannot be more than 31 buckets required by the merge sorter.
29991** One extra bucket is added to catch overflow in case something
29992** ever changes to make the previous sentence incorrect.
29993*/
29994#define N_SORT_BUCKET  32
29995static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
29996  PgHdr *a[N_SORT_BUCKET], *p;
29997  int i;
29998  memset(a, 0, sizeof(a));
29999  while( pIn ){
30000    p = pIn;
30001    pIn = p->pDirty;
30002    p->pDirty = 0;
30003    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
30004      if( a[i]==0 ){
30005        a[i] = p;
30006        break;
30007      }else{
30008        p = pcacheMergeDirtyList(a[i], p);
30009        a[i] = 0;
30010      }
30011    }
30012    if( NEVER(i==N_SORT_BUCKET-1) ){
30013      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
30014      ** the input list.  But that is impossible.
30015      */
30016      a[i] = pcacheMergeDirtyList(a[i], p);
30017    }
30018  }
30019  p = a[0];
30020  for(i=1; i<N_SORT_BUCKET; i++){
30021    p = pcacheMergeDirtyList(p, a[i]);
30022  }
30023  return p;
30024}
30025
30026/*
30027** Return a list of all dirty pages in the cache, sorted by page number.
30028*/
30029SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
30030  PgHdr *p;
30031  for(p=pCache->pDirty; p; p=p->pDirtyNext){
30032    p->pDirty = p->pDirtyNext;
30033  }
30034  return pcacheSortDirtyList(pCache->pDirty);
30035}
30036
30037/*
30038** Return the total number of referenced pages held by the cache.
30039*/
30040SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
30041  return pCache->nRef;
30042}
30043
30044/*
30045** Return the number of references to the page supplied as an argument.
30046*/
30047SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
30048  return p->nRef;
30049}
30050
30051/*
30052** Return the total number of pages in the cache.
30053*/
30054SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
30055  int nPage = 0;
30056  if( pCache->pCache ){
30057    nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
30058  }
30059  return nPage;
30060}
30061
30062#ifdef SQLITE_TEST
30063/*
30064** Get the suggested cache-size value.
30065*/
30066SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
30067  return pCache->nMax;
30068}
30069#endif
30070
30071/*
30072** Set the suggested cache-size value.
30073*/
30074SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
30075  pCache->nMax = mxPage;
30076  if( pCache->pCache ){
30077    sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
30078  }
30079}
30080
30081#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
30082/*
30083** For all dirty pages currently in the cache, invoke the specified
30084** callback. This is only used if the SQLITE_CHECK_PAGES macro is
30085** defined.
30086*/
30087SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
30088  PgHdr *pDirty;
30089  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
30090    xIter(pDirty);
30091  }
30092}
30093#endif
30094
30095/************** End of pcache.c **********************************************/
30096/************** Begin file pcache1.c *****************************************/
30097/*
30098** 2008 November 05
30099**
30100** The author disclaims copyright to this source code.  In place of
30101** a legal notice, here is a blessing:
30102**
30103**    May you do good and not evil.
30104**    May you find forgiveness for yourself and forgive others.
30105**    May you share freely, never taking more than you give.
30106**
30107*************************************************************************
30108**
30109** This file implements the default page cache implementation (the
30110** sqlite3_pcache interface). It also contains part of the implementation
30111** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
30112** If the default page cache implementation is overriden, then neither of
30113** these two features are available.
30114*/
30115
30116
30117typedef struct PCache1 PCache1;
30118typedef struct PgHdr1 PgHdr1;
30119typedef struct PgFreeslot PgFreeslot;
30120
30121/* Pointers to structures of this type are cast and returned as
30122** opaque sqlite3_pcache* handles
30123*/
30124struct PCache1 {
30125  /* Cache configuration parameters. Page size (szPage) and the purgeable
30126  ** flag (bPurgeable) are set when the cache is created. nMax may be
30127  ** modified at any time by a call to the pcache1CacheSize() method.
30128  ** The global mutex must be held when accessing nMax.
30129  */
30130  int szPage;                         /* Size of allocated pages in bytes */
30131  int bPurgeable;                     /* True if cache is purgeable */
30132  unsigned int nMin;                  /* Minimum number of pages reserved */
30133  unsigned int nMax;                  /* Configured "cache_size" value */
30134
30135  /* Hash table of all pages. The following variables may only be accessed
30136  ** when the accessor is holding the global mutex (see pcache1EnterMutex()
30137  ** and pcache1LeaveMutex()).
30138  */
30139  unsigned int nRecyclable;           /* Number of pages in the LRU list */
30140  unsigned int nPage;                 /* Total number of pages in apHash */
30141  unsigned int nHash;                 /* Number of slots in apHash[] */
30142  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
30143
30144  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
30145};
30146
30147/*
30148** Each cache entry is represented by an instance of the following
30149** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
30150** directly before this structure in memory (see the PGHDR1_TO_PAGE()
30151** macro below).
30152*/
30153struct PgHdr1 {
30154  unsigned int iKey;             /* Key value (page number) */
30155  PgHdr1 *pNext;                 /* Next in hash table chain */
30156  PCache1 *pCache;               /* Cache that currently owns this page */
30157  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
30158  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
30159};
30160
30161/*
30162** Free slots in the allocator used to divide up the buffer provided using
30163** the SQLITE_CONFIG_PAGECACHE mechanism.
30164*/
30165struct PgFreeslot {
30166  PgFreeslot *pNext;  /* Next free slot */
30167};
30168
30169/*
30170** Global data used by this cache.
30171*/
30172static SQLITE_WSD struct PCacheGlobal {
30173  sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
30174
30175  int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
30176  int nMinPage;                       /* Sum of nMinPage for purgeable caches */
30177  int nCurrentPage;                   /* Number of purgeable pages allocated */
30178  PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */
30179
30180  /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
30181  int szSlot;                         /* Size of each free slot */
30182  void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
30183  PgFreeslot *pFree;                  /* Free page blocks */
30184  int isInit;                         /* True if initialized */
30185} pcache1_g;
30186
30187/*
30188** All code in this file should access the global structure above via the
30189** alias "pcache1". This ensures that the WSD emulation is used when
30190** compiling for systems that do not support real WSD.
30191*/
30192#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
30193
30194/*
30195** When a PgHdr1 structure is allocated, the associated PCache1.szPage
30196** bytes of data are located directly before it in memory (i.e. the total
30197** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
30198** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
30199** an argument and returns a pointer to the associated block of szPage
30200** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
30201** a pointer to a block of szPage bytes of data and the return value is
30202** a pointer to the associated PgHdr1 structure.
30203**
30204**   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
30205*/
30206#define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
30207#define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
30208
30209/*
30210** Macros to enter and leave the global LRU mutex.
30211*/
30212#define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
30213#define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
30214
30215/******************************************************************************/
30216/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
30217
30218/*
30219** This function is called during initialization if a static buffer is
30220** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
30221** verb to sqlite3_config(). Parameter pBuf points to an allocation large
30222** enough to contain 'n' buffers of 'sz' bytes each.
30223*/
30224SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
30225  if( pcache1.isInit ){
30226    PgFreeslot *p;
30227    sz = ROUNDDOWN8(sz);
30228    pcache1.szSlot = sz;
30229    pcache1.pStart = pBuf;
30230    pcache1.pFree = 0;
30231    while( n-- ){
30232      p = (PgFreeslot*)pBuf;
30233      p->pNext = pcache1.pFree;
30234      pcache1.pFree = p;
30235      pBuf = (void*)&((char*)pBuf)[sz];
30236    }
30237    pcache1.pEnd = pBuf;
30238  }
30239}
30240
30241/*
30242** Malloc function used within this file to allocate space from the buffer
30243** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
30244** such buffer exists or there is no space left in it, this function falls
30245** back to sqlite3Malloc().
30246*/
30247static void *pcache1Alloc(int nByte){
30248  void *p;
30249  assert( sqlite3_mutex_held(pcache1.mutex) );
30250  if( nByte<=pcache1.szSlot && pcache1.pFree ){
30251    assert( pcache1.isInit );
30252    p = (PgHdr1 *)pcache1.pFree;
30253    pcache1.pFree = pcache1.pFree->pNext;
30254    sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
30255    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
30256  }else{
30257
30258    /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
30259    ** global pcache mutex and unlock the pager-cache object pCache. This is
30260    ** so that if the attempt to allocate a new buffer causes the the
30261    ** configured soft-heap-limit to be breached, it will be possible to
30262    ** reclaim memory from this pager-cache.
30263    */
30264    pcache1LeaveMutex();
30265    p = sqlite3Malloc(nByte);
30266    pcache1EnterMutex();
30267    if( p ){
30268      int sz = sqlite3MallocSize(p);
30269      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
30270    }
30271  }
30272  return p;
30273}
30274
30275/*
30276** Free an allocated buffer obtained from pcache1Alloc().
30277*/
30278static void pcache1Free(void *p){
30279  assert( sqlite3_mutex_held(pcache1.mutex) );
30280  if( p==0 ) return;
30281  if( p>=pcache1.pStart && p<pcache1.pEnd ){
30282    PgFreeslot *pSlot;
30283    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
30284    pSlot = (PgFreeslot*)p;
30285    pSlot->pNext = pcache1.pFree;
30286    pcache1.pFree = pSlot;
30287  }else{
30288    int iSize = sqlite3MallocSize(p);
30289    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
30290    sqlite3_free(p);
30291  }
30292}
30293
30294/*
30295** Allocate a new page object initially associated with cache pCache.
30296*/
30297static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
30298  int nByte = sizeof(PgHdr1) + pCache->szPage;
30299  void *pPg = pcache1Alloc(nByte);
30300  PgHdr1 *p;
30301  if( pPg ){
30302    p = PAGE_TO_PGHDR1(pCache, pPg);
30303    if( pCache->bPurgeable ){
30304      pcache1.nCurrentPage++;
30305    }
30306  }else{
30307    p = 0;
30308  }
30309  return p;
30310}
30311
30312/*
30313** Free a page object allocated by pcache1AllocPage().
30314**
30315** The pointer is allowed to be NULL, which is prudent.  But it turns out
30316** that the current implementation happens to never call this routine
30317** with a NULL pointer, so we mark the NULL test with ALWAYS().
30318*/
30319static void pcache1FreePage(PgHdr1 *p){
30320  if( ALWAYS(p) ){
30321    if( p->pCache->bPurgeable ){
30322      pcache1.nCurrentPage--;
30323    }
30324    pcache1Free(PGHDR1_TO_PAGE(p));
30325  }
30326}
30327
30328/*
30329** Malloc function used by SQLite to obtain space from the buffer configured
30330** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
30331** exists, this function falls back to sqlite3Malloc().
30332*/
30333SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
30334  void *p;
30335  pcache1EnterMutex();
30336  p = pcache1Alloc(sz);
30337  pcache1LeaveMutex();
30338  return p;
30339}
30340
30341/*
30342** Free an allocated buffer obtained from sqlite3PageMalloc().
30343*/
30344SQLITE_PRIVATE void sqlite3PageFree(void *p){
30345  pcache1EnterMutex();
30346  pcache1Free(p);
30347  pcache1LeaveMutex();
30348}
30349
30350/******************************************************************************/
30351/******** General Implementation Functions ************************************/
30352
30353/*
30354** This function is used to resize the hash table used by the cache passed
30355** as the first argument.
30356**
30357** The global mutex must be held when this function is called.
30358*/
30359static int pcache1ResizeHash(PCache1 *p){
30360  PgHdr1 **apNew;
30361  unsigned int nNew;
30362  unsigned int i;
30363
30364  assert( sqlite3_mutex_held(pcache1.mutex) );
30365
30366  nNew = p->nHash*2;
30367  if( nNew<256 ){
30368    nNew = 256;
30369  }
30370
30371  pcache1LeaveMutex();
30372  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
30373  apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
30374  if( p->nHash ){ sqlite3EndBenignMalloc(); }
30375  pcache1EnterMutex();
30376  if( apNew ){
30377    memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
30378    for(i=0; i<p->nHash; i++){
30379      PgHdr1 *pPage;
30380      PgHdr1 *pNext = p->apHash[i];
30381      while( (pPage = pNext)!=0 ){
30382        unsigned int h = pPage->iKey % nNew;
30383        pNext = pPage->pNext;
30384        pPage->pNext = apNew[h];
30385        apNew[h] = pPage;
30386      }
30387    }
30388    sqlite3_free(p->apHash);
30389    p->apHash = apNew;
30390    p->nHash = nNew;
30391  }
30392
30393  return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
30394}
30395
30396/*
30397** This function is used internally to remove the page pPage from the
30398** global LRU list, if is part of it. If pPage is not part of the global
30399** LRU list, then this function is a no-op.
30400**
30401** The global mutex must be held when this function is called.
30402*/
30403static void pcache1PinPage(PgHdr1 *pPage){
30404  assert( sqlite3_mutex_held(pcache1.mutex) );
30405  if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
30406    if( pPage->pLruPrev ){
30407      pPage->pLruPrev->pLruNext = pPage->pLruNext;
30408    }
30409    if( pPage->pLruNext ){
30410      pPage->pLruNext->pLruPrev = pPage->pLruPrev;
30411    }
30412    if( pcache1.pLruHead==pPage ){
30413      pcache1.pLruHead = pPage->pLruNext;
30414    }
30415    if( pcache1.pLruTail==pPage ){
30416      pcache1.pLruTail = pPage->pLruPrev;
30417    }
30418    pPage->pLruNext = 0;
30419    pPage->pLruPrev = 0;
30420    pPage->pCache->nRecyclable--;
30421  }
30422}
30423
30424
30425/*
30426** Remove the page supplied as an argument from the hash table
30427** (PCache1.apHash structure) that it is currently stored in.
30428**
30429** The global mutex must be held when this function is called.
30430*/
30431static void pcache1RemoveFromHash(PgHdr1 *pPage){
30432  unsigned int h;
30433  PCache1 *pCache = pPage->pCache;
30434  PgHdr1 **pp;
30435
30436  h = pPage->iKey % pCache->nHash;
30437  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
30438  *pp = (*pp)->pNext;
30439
30440  pCache->nPage--;
30441}
30442
30443/*
30444** If there are currently more than pcache.nMaxPage pages allocated, try
30445** to recycle pages to reduce the number allocated to pcache.nMaxPage.
30446*/
30447static void pcache1EnforceMaxPage(void){
30448  assert( sqlite3_mutex_held(pcache1.mutex) );
30449  while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
30450    PgHdr1 *p = pcache1.pLruTail;
30451    pcache1PinPage(p);
30452    pcache1RemoveFromHash(p);
30453    pcache1FreePage(p);
30454  }
30455}
30456
30457/*
30458** Discard all pages from cache pCache with a page number (key value)
30459** greater than or equal to iLimit. Any pinned pages that meet this
30460** criteria are unpinned before they are discarded.
30461**
30462** The global mutex must be held when this function is called.
30463*/
30464static void pcache1TruncateUnsafe(
30465  PCache1 *pCache,
30466  unsigned int iLimit
30467){
30468  TESTONLY( unsigned int nPage = 0; )      /* Used to assert pCache->nPage is correct */
30469  unsigned int h;
30470  assert( sqlite3_mutex_held(pcache1.mutex) );
30471  for(h=0; h<pCache->nHash; h++){
30472    PgHdr1 **pp = &pCache->apHash[h];
30473    PgHdr1 *pPage;
30474    while( (pPage = *pp)!=0 ){
30475      if( pPage->iKey>=iLimit ){
30476        pCache->nPage--;
30477        *pp = pPage->pNext;
30478        pcache1PinPage(pPage);
30479        pcache1FreePage(pPage);
30480      }else{
30481        pp = &pPage->pNext;
30482        TESTONLY( nPage++; )
30483      }
30484    }
30485  }
30486  assert( pCache->nPage==nPage );
30487}
30488
30489/******************************************************************************/
30490/******** sqlite3_pcache Methods **********************************************/
30491
30492/*
30493** Implementation of the sqlite3_pcache.xInit method.
30494*/
30495static int pcache1Init(void *NotUsed){
30496  UNUSED_PARAMETER(NotUsed);
30497  assert( pcache1.isInit==0 );
30498  memset(&pcache1, 0, sizeof(pcache1));
30499  if( sqlite3GlobalConfig.bCoreMutex ){
30500    pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
30501  }
30502  pcache1.isInit = 1;
30503  return SQLITE_OK;
30504}
30505
30506/*
30507** Implementation of the sqlite3_pcache.xShutdown method.
30508** Note that the static mutex allocated in xInit does
30509** not need to be freed.
30510*/
30511static void pcache1Shutdown(void *NotUsed){
30512  UNUSED_PARAMETER(NotUsed);
30513  assert( pcache1.isInit!=0 );
30514  memset(&pcache1, 0, sizeof(pcache1));
30515}
30516
30517/*
30518** Implementation of the sqlite3_pcache.xCreate method.
30519**
30520** Allocate a new cache.
30521*/
30522static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
30523  PCache1 *pCache;
30524
30525  pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
30526  if( pCache ){
30527    memset(pCache, 0, sizeof(PCache1));
30528    pCache->szPage = szPage;
30529    pCache->bPurgeable = (bPurgeable ? 1 : 0);
30530    if( bPurgeable ){
30531      pCache->nMin = 10;
30532      pcache1EnterMutex();
30533      pcache1.nMinPage += pCache->nMin;
30534      pcache1LeaveMutex();
30535    }
30536  }
30537  return (sqlite3_pcache *)pCache;
30538}
30539
30540/*
30541** Implementation of the sqlite3_pcache.xCachesize method.
30542**
30543** Configure the cache_size limit for a cache.
30544*/
30545static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
30546  PCache1 *pCache = (PCache1 *)p;
30547  if( pCache->bPurgeable ){
30548    pcache1EnterMutex();
30549    pcache1.nMaxPage += (nMax - pCache->nMax);
30550    pCache->nMax = nMax;
30551    pcache1EnforceMaxPage();
30552    pcache1LeaveMutex();
30553  }
30554}
30555
30556/*
30557** Implementation of the sqlite3_pcache.xPagecount method.
30558*/
30559static int pcache1Pagecount(sqlite3_pcache *p){
30560  int n;
30561  pcache1EnterMutex();
30562  n = ((PCache1 *)p)->nPage;
30563  pcache1LeaveMutex();
30564  return n;
30565}
30566
30567/*
30568** Implementation of the sqlite3_pcache.xFetch method.
30569**
30570** Fetch a page by key value.
30571**
30572** Whether or not a new page may be allocated by this function depends on
30573** the value of the createFlag argument.  0 means do not allocate a new
30574** page.  1 means allocate a new page if space is easily available.  2
30575** means to try really hard to allocate a new page.
30576**
30577** For a non-purgeable cache (a cache used as the storage for an in-memory
30578** database) there is really no difference between createFlag 1 and 2.  So
30579** the calling function (pcache.c) will never have a createFlag of 1 on
30580** a non-purgable cache.
30581**
30582** There are three different approaches to obtaining space for a page,
30583** depending on the value of parameter createFlag (which may be 0, 1 or 2).
30584**
30585**   1. Regardless of the value of createFlag, the cache is searched for a
30586**      copy of the requested page. If one is found, it is returned.
30587**
30588**   2. If createFlag==0 and the page is not already in the cache, NULL is
30589**      returned.
30590**
30591**   3. If createFlag is 1, and the page is not already in the cache,
30592**      and if either of the following are true, return NULL:
30593**
30594**       (a) the number of pages pinned by the cache is greater than
30595**           PCache1.nMax, or
30596**       (b) the number of pages pinned by the cache is greater than
30597**           the sum of nMax for all purgeable caches, less the sum of
30598**           nMin for all other purgeable caches.
30599**
30600**   4. If none of the first three conditions apply and the cache is marked
30601**      as purgeable, and if one of the following is true:
30602**
30603**       (a) The number of pages allocated for the cache is already
30604**           PCache1.nMax, or
30605**
30606**       (b) The number of pages allocated for all purgeable caches is
30607**           already equal to or greater than the sum of nMax for all
30608**           purgeable caches,
30609**
30610**      then attempt to recycle a page from the LRU list. If it is the right
30611**      size, return the recycled buffer. Otherwise, free the buffer and
30612**      proceed to step 5.
30613**
30614**   5. Otherwise, allocate and return a new page buffer.
30615*/
30616static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
30617  unsigned int nPinned;
30618  PCache1 *pCache = (PCache1 *)p;
30619  PgHdr1 *pPage = 0;
30620
30621  assert( pCache->bPurgeable || createFlag!=1 );
30622  pcache1EnterMutex();
30623  if( createFlag==1 ) sqlite3BeginBenignMalloc();
30624
30625  /* Search the hash table for an existing entry. */
30626  if( pCache->nHash>0 ){
30627    unsigned int h = iKey % pCache->nHash;
30628    for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
30629  }
30630
30631  if( pPage || createFlag==0 ){
30632    pcache1PinPage(pPage);
30633    goto fetch_out;
30634  }
30635
30636  /* Step 3 of header comment. */
30637  nPinned = pCache->nPage - pCache->nRecyclable;
30638  if( createFlag==1 && (
30639        nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
30640     || nPinned>=(pCache->nMax * 9 / 10)
30641  )){
30642    goto fetch_out;
30643  }
30644
30645  if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
30646    goto fetch_out;
30647  }
30648
30649  /* Step 4. Try to recycle a page buffer if appropriate. */
30650  if( pCache->bPurgeable && pcache1.pLruTail && (
30651     (pCache->nPage+1>=pCache->nMax) || pcache1.nCurrentPage>=pcache1.nMaxPage
30652  )){
30653    pPage = pcache1.pLruTail;
30654    pcache1RemoveFromHash(pPage);
30655    pcache1PinPage(pPage);
30656    if( pPage->pCache->szPage!=pCache->szPage ){
30657      pcache1FreePage(pPage);
30658      pPage = 0;
30659    }else{
30660      pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
30661    }
30662  }
30663
30664  /* Step 5. If a usable page buffer has still not been found,
30665  ** attempt to allocate a new one.
30666  */
30667  if( !pPage ){
30668    pPage = pcache1AllocPage(pCache);
30669  }
30670
30671  if( pPage ){
30672    unsigned int h = iKey % pCache->nHash;
30673    pCache->nPage++;
30674    pPage->iKey = iKey;
30675    pPage->pNext = pCache->apHash[h];
30676    pPage->pCache = pCache;
30677    pPage->pLruPrev = 0;
30678    pPage->pLruNext = 0;
30679    *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
30680    pCache->apHash[h] = pPage;
30681  }
30682
30683fetch_out:
30684  if( pPage && iKey>pCache->iMaxKey ){
30685    pCache->iMaxKey = iKey;
30686  }
30687  if( createFlag==1 ) sqlite3EndBenignMalloc();
30688  pcache1LeaveMutex();
30689  return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
30690}
30691
30692
30693/*
30694** Implementation of the sqlite3_pcache.xUnpin method.
30695**
30696** Mark a page as unpinned (eligible for asynchronous recycling).
30697*/
30698static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
30699  PCache1 *pCache = (PCache1 *)p;
30700  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
30701
30702  assert( pPage->pCache==pCache );
30703  pcache1EnterMutex();
30704
30705  /* It is an error to call this function if the page is already
30706  ** part of the global LRU list.
30707  */
30708  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
30709  assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
30710
30711  if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
30712    pcache1RemoveFromHash(pPage);
30713    pcache1FreePage(pPage);
30714  }else{
30715    /* Add the page to the global LRU list. Normally, the page is added to
30716    ** the head of the list (last page to be recycled). However, if the
30717    ** reuseUnlikely flag passed to this function is true, the page is added
30718    ** to the tail of the list (first page to be recycled).
30719    */
30720    if( pcache1.pLruHead ){
30721      pcache1.pLruHead->pLruPrev = pPage;
30722      pPage->pLruNext = pcache1.pLruHead;
30723      pcache1.pLruHead = pPage;
30724    }else{
30725      pcache1.pLruTail = pPage;
30726      pcache1.pLruHead = pPage;
30727    }
30728    pCache->nRecyclable++;
30729  }
30730
30731  pcache1LeaveMutex();
30732}
30733
30734/*
30735** Implementation of the sqlite3_pcache.xRekey method.
30736*/
30737static void pcache1Rekey(
30738  sqlite3_pcache *p,
30739  void *pPg,
30740  unsigned int iOld,
30741  unsigned int iNew
30742){
30743  PCache1 *pCache = (PCache1 *)p;
30744  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
30745  PgHdr1 **pp;
30746  unsigned int h;
30747  assert( pPage->iKey==iOld );
30748  assert( pPage->pCache==pCache );
30749
30750  pcache1EnterMutex();
30751
30752  h = iOld%pCache->nHash;
30753  pp = &pCache->apHash[h];
30754  while( (*pp)!=pPage ){
30755    pp = &(*pp)->pNext;
30756  }
30757  *pp = pPage->pNext;
30758
30759  h = iNew%pCache->nHash;
30760  pPage->iKey = iNew;
30761  pPage->pNext = pCache->apHash[h];
30762  pCache->apHash[h] = pPage;
30763  if( iNew>pCache->iMaxKey ){
30764    pCache->iMaxKey = iNew;
30765  }
30766
30767  pcache1LeaveMutex();
30768}
30769
30770/*
30771** Implementation of the sqlite3_pcache.xTruncate method.
30772**
30773** Discard all unpinned pages in the cache with a page number equal to
30774** or greater than parameter iLimit. Any pinned pages with a page number
30775** equal to or greater than iLimit are implicitly unpinned.
30776*/
30777static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
30778  PCache1 *pCache = (PCache1 *)p;
30779  pcache1EnterMutex();
30780  if( iLimit<=pCache->iMaxKey ){
30781    pcache1TruncateUnsafe(pCache, iLimit);
30782    pCache->iMaxKey = iLimit-1;
30783  }
30784  pcache1LeaveMutex();
30785}
30786
30787/*
30788** Implementation of the sqlite3_pcache.xDestroy method.
30789**
30790** Destroy a cache allocated using pcache1Create().
30791*/
30792static void pcache1Destroy(sqlite3_pcache *p){
30793  PCache1 *pCache = (PCache1 *)p;
30794  pcache1EnterMutex();
30795  pcache1TruncateUnsafe(pCache, 0);
30796  pcache1.nMaxPage -= pCache->nMax;
30797  pcache1.nMinPage -= pCache->nMin;
30798  pcache1EnforceMaxPage();
30799  pcache1LeaveMutex();
30800  sqlite3_free(pCache->apHash);
30801  sqlite3_free(pCache);
30802}
30803
30804/*
30805** This function is called during initialization (sqlite3_initialize()) to
30806** install the default pluggable cache module, assuming the user has not
30807** already provided an alternative.
30808*/
30809SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
30810  static sqlite3_pcache_methods defaultMethods = {
30811    0,                       /* pArg */
30812    pcache1Init,             /* xInit */
30813    pcache1Shutdown,         /* xShutdown */
30814    pcache1Create,           /* xCreate */
30815    pcache1Cachesize,        /* xCachesize */
30816    pcache1Pagecount,        /* xPagecount */
30817    pcache1Fetch,            /* xFetch */
30818    pcache1Unpin,            /* xUnpin */
30819    pcache1Rekey,            /* xRekey */
30820    pcache1Truncate,         /* xTruncate */
30821    pcache1Destroy           /* xDestroy */
30822  };
30823  sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
30824}
30825
30826#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
30827/*
30828** This function is called to free superfluous dynamically allocated memory
30829** held by the pager system. Memory in use by any SQLite pager allocated
30830** by the current thread may be sqlite3_free()ed.
30831**
30832** nReq is the number of bytes of memory required. Once this much has
30833** been released, the function returns. The return value is the total number
30834** of bytes of memory released.
30835*/
30836SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
30837  int nFree = 0;
30838  if( pcache1.pStart==0 ){
30839    PgHdr1 *p;
30840    pcache1EnterMutex();
30841    while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
30842      nFree += sqlite3MallocSize(PGHDR1_TO_PAGE(p));
30843      pcache1PinPage(p);
30844      pcache1RemoveFromHash(p);
30845      pcache1FreePage(p);
30846    }
30847    pcache1LeaveMutex();
30848  }
30849  return nFree;
30850}
30851#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
30852
30853#ifdef SQLITE_TEST
30854/*
30855** This function is used by test procedures to inspect the internal state
30856** of the global cache.
30857*/
30858SQLITE_PRIVATE void sqlite3PcacheStats(
30859  int *pnCurrent,      /* OUT: Total number of pages cached */
30860  int *pnMax,          /* OUT: Global maximum cache size */
30861  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
30862  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
30863){
30864  PgHdr1 *p;
30865  int nRecyclable = 0;
30866  for(p=pcache1.pLruHead; p; p=p->pLruNext){
30867    nRecyclable++;
30868  }
30869  *pnCurrent = pcache1.nCurrentPage;
30870  *pnMax = pcache1.nMaxPage;
30871  *pnMin = pcache1.nMinPage;
30872  *pnRecyclable = nRecyclable;
30873}
30874#endif
30875
30876/************** End of pcache1.c *********************************************/
30877/************** Begin file rowset.c ******************************************/
30878/*
30879** 2008 December 3
30880**
30881** The author disclaims copyright to this source code.  In place of
30882** a legal notice, here is a blessing:
30883**
30884**    May you do good and not evil.
30885**    May you find forgiveness for yourself and forgive others.
30886**    May you share freely, never taking more than you give.
30887**
30888*************************************************************************
30889**
30890** This module implements an object we call a "RowSet".
30891**
30892** The RowSet object is a collection of rowids.  Rowids
30893** are inserted into the RowSet in an arbitrary order.  Inserts
30894** can be intermixed with tests to see if a given rowid has been
30895** previously inserted into the RowSet.
30896**
30897** After all inserts are finished, it is possible to extract the
30898** elements of the RowSet in sorted order.  Once this extraction
30899** process has started, no new elements may be inserted.
30900**
30901** Hence, the primitive operations for a RowSet are:
30902**
30903**    CREATE
30904**    INSERT
30905**    TEST
30906**    SMALLEST
30907**    DESTROY
30908**
30909** The CREATE and DESTROY primitives are the constructor and destructor,
30910** obviously.  The INSERT primitive adds a new element to the RowSet.
30911** TEST checks to see if an element is already in the RowSet.  SMALLEST
30912** extracts the least value from the RowSet.
30913**
30914** The INSERT primitive might allocate additional memory.  Memory is
30915** allocated in chunks so most INSERTs do no allocation.  There is an
30916** upper bound on the size of allocated memory.  No memory is freed
30917** until DESTROY.
30918**
30919** The TEST primitive includes a "batch" number.  The TEST primitive
30920** will only see elements that were inserted before the last change
30921** in the batch number.  In other words, if an INSERT occurs between
30922** two TESTs where the TESTs have the same batch nubmer, then the
30923** value added by the INSERT will not be visible to the second TEST.
30924** The initial batch number is zero, so if the very first TEST contains
30925** a non-zero batch number, it will see all prior INSERTs.
30926**
30927** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
30928** that is attempted.
30929**
30930** The cost of an INSERT is roughly constant.  (Sometime new memory
30931** has to be allocated on an INSERT.)  The cost of a TEST with a new
30932** batch number is O(NlogN) where N is the number of elements in the RowSet.
30933** The cost of a TEST using the same batch number is O(logN).  The cost
30934** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
30935** primitives are constant time.  The cost of DESTROY is O(N).
30936**
30937** There is an added cost of O(N) when switching between TEST and
30938** SMALLEST primitives.
30939*/
30940
30941
30942/*
30943** Target size for allocation chunks.
30944*/
30945#define ROWSET_ALLOCATION_SIZE 1024
30946
30947/*
30948** The number of rowset entries per allocation chunk.
30949*/
30950#define ROWSET_ENTRY_PER_CHUNK  \
30951                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
30952
30953/*
30954** Each entry in a RowSet is an instance of the following object.
30955*/
30956struct RowSetEntry {
30957  i64 v;                        /* ROWID value for this entry */
30958  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
30959  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
30960};
30961
30962/*
30963** RowSetEntry objects are allocated in large chunks (instances of the
30964** following structure) to reduce memory allocation overhead.  The
30965** chunks are kept on a linked list so that they can be deallocated
30966** when the RowSet is destroyed.
30967*/
30968struct RowSetChunk {
30969  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
30970  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
30971};
30972
30973/*
30974** A RowSet in an instance of the following structure.
30975**
30976** A typedef of this structure if found in sqliteInt.h.
30977*/
30978struct RowSet {
30979  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
30980  sqlite3 *db;                   /* The database connection */
30981  struct RowSetEntry *pEntry;    /* List of entries using pRight */
30982  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
30983  struct RowSetEntry *pFresh;    /* Source of new entry objects */
30984  struct RowSetEntry *pTree;     /* Binary tree of entries */
30985  u16 nFresh;                    /* Number of objects on pFresh */
30986  u8 isSorted;                   /* True if pEntry is sorted */
30987  u8 iBatch;                     /* Current insert batch */
30988};
30989
30990/*
30991** Turn bulk memory into a RowSet object.  N bytes of memory
30992** are available at pSpace.  The db pointer is used as a memory context
30993** for any subsequent allocations that need to occur.
30994** Return a pointer to the new RowSet object.
30995**
30996** It must be the case that N is sufficient to make a Rowset.  If not
30997** an assertion fault occurs.
30998**
30999** If N is larger than the minimum, use the surplus as an initial
31000** allocation of entries available to be filled.
31001*/
31002SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
31003  RowSet *p;
31004  assert( N >= ROUND8(sizeof(*p)) );
31005  p = pSpace;
31006  p->pChunk = 0;
31007  p->db = db;
31008  p->pEntry = 0;
31009  p->pLast = 0;
31010  p->pTree = 0;
31011  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
31012  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
31013  p->isSorted = 1;
31014  p->iBatch = 0;
31015  return p;
31016}
31017
31018/*
31019** Deallocate all chunks from a RowSet.  This frees all memory that
31020** the RowSet has allocated over its lifetime.  This routine is
31021** the destructor for the RowSet.
31022*/
31023SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
31024  struct RowSetChunk *pChunk, *pNextChunk;
31025  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
31026    pNextChunk = pChunk->pNextChunk;
31027    sqlite3DbFree(p->db, pChunk);
31028  }
31029  p->pChunk = 0;
31030  p->nFresh = 0;
31031  p->pEntry = 0;
31032  p->pLast = 0;
31033  p->pTree = 0;
31034  p->isSorted = 1;
31035}
31036
31037/*
31038** Insert a new value into a RowSet.
31039**
31040** The mallocFailed flag of the database connection is set if a
31041** memory allocation fails.
31042*/
31043SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
31044  struct RowSetEntry *pEntry;  /* The new entry */
31045  struct RowSetEntry *pLast;   /* The last prior entry */
31046  assert( p!=0 );
31047  if( p->nFresh==0 ){
31048    struct RowSetChunk *pNew;
31049    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
31050    if( pNew==0 ){
31051      return;
31052    }
31053    pNew->pNextChunk = p->pChunk;
31054    p->pChunk = pNew;
31055    p->pFresh = pNew->aEntry;
31056    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
31057  }
31058  pEntry = p->pFresh++;
31059  p->nFresh--;
31060  pEntry->v = rowid;
31061  pEntry->pRight = 0;
31062  pLast = p->pLast;
31063  if( pLast ){
31064    if( p->isSorted && rowid<=pLast->v ){
31065      p->isSorted = 0;
31066    }
31067    pLast->pRight = pEntry;
31068  }else{
31069    assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
31070    p->pEntry = pEntry;
31071  }
31072  p->pLast = pEntry;
31073}
31074
31075/*
31076** Merge two lists of RowSetEntry objects.  Remove duplicates.
31077**
31078** The input lists are connected via pRight pointers and are
31079** assumed to each already be in sorted order.
31080*/
31081static struct RowSetEntry *rowSetMerge(
31082  struct RowSetEntry *pA,    /* First sorted list to be merged */
31083  struct RowSetEntry *pB     /* Second sorted list to be merged */
31084){
31085  struct RowSetEntry head;
31086  struct RowSetEntry *pTail;
31087
31088  pTail = &head;
31089  while( pA && pB ){
31090    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
31091    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
31092    if( pA->v<pB->v ){
31093      pTail->pRight = pA;
31094      pA = pA->pRight;
31095      pTail = pTail->pRight;
31096    }else if( pB->v<pA->v ){
31097      pTail->pRight = pB;
31098      pB = pB->pRight;
31099      pTail = pTail->pRight;
31100    }else{
31101      pA = pA->pRight;
31102    }
31103  }
31104  if( pA ){
31105    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
31106    pTail->pRight = pA;
31107  }else{
31108    assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
31109    pTail->pRight = pB;
31110  }
31111  return head.pRight;
31112}
31113
31114/*
31115** Sort all elements on the pEntry list of the RowSet into ascending order.
31116*/
31117static void rowSetSort(RowSet *p){
31118  unsigned int i;
31119  struct RowSetEntry *pEntry;
31120  struct RowSetEntry *aBucket[40];
31121
31122  assert( p->isSorted==0 );
31123  memset(aBucket, 0, sizeof(aBucket));
31124  while( p->pEntry ){
31125    pEntry = p->pEntry;
31126    p->pEntry = pEntry->pRight;
31127    pEntry->pRight = 0;
31128    for(i=0; aBucket[i]; i++){
31129      pEntry = rowSetMerge(aBucket[i], pEntry);
31130      aBucket[i] = 0;
31131    }
31132    aBucket[i] = pEntry;
31133  }
31134  pEntry = 0;
31135  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
31136    pEntry = rowSetMerge(pEntry, aBucket[i]);
31137  }
31138  p->pEntry = pEntry;
31139  p->pLast = 0;
31140  p->isSorted = 1;
31141}
31142
31143
31144/*
31145** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
31146** Convert this tree into a linked list connected by the pRight pointers
31147** and return pointers to the first and last elements of the new list.
31148*/
31149static void rowSetTreeToList(
31150  struct RowSetEntry *pIn,         /* Root of the input tree */
31151  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
31152  struct RowSetEntry **ppLast      /* Write tail of the output list here */
31153){
31154  assert( pIn!=0 );
31155  if( pIn->pLeft ){
31156    struct RowSetEntry *p;
31157    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
31158    p->pRight = pIn;
31159  }else{
31160    *ppFirst = pIn;
31161  }
31162  if( pIn->pRight ){
31163    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
31164  }else{
31165    *ppLast = pIn;
31166  }
31167  assert( (*ppLast)->pRight==0 );
31168}
31169
31170
31171/*
31172** Convert a sorted list of elements (connected by pRight) into a binary
31173** tree with depth of iDepth.  A depth of 1 means the tree contains a single
31174** node taken from the head of *ppList.  A depth of 2 means a tree with
31175** three nodes.  And so forth.
31176**
31177** Use as many entries from the input list as required and update the
31178** *ppList to point to the unused elements of the list.  If the input
31179** list contains too few elements, then construct an incomplete tree
31180** and leave *ppList set to NULL.
31181**
31182** Return a pointer to the root of the constructed binary tree.
31183*/
31184static struct RowSetEntry *rowSetNDeepTree(
31185  struct RowSetEntry **ppList,
31186  int iDepth
31187){
31188  struct RowSetEntry *p;         /* Root of the new tree */
31189  struct RowSetEntry *pLeft;     /* Left subtree */
31190  if( *ppList==0 ){
31191    return 0;
31192  }
31193  if( iDepth==1 ){
31194    p = *ppList;
31195    *ppList = p->pRight;
31196    p->pLeft = p->pRight = 0;
31197    return p;
31198  }
31199  pLeft = rowSetNDeepTree(ppList, iDepth-1);
31200  p = *ppList;
31201  if( p==0 ){
31202    return pLeft;
31203  }
31204  p->pLeft = pLeft;
31205  *ppList = p->pRight;
31206  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
31207  return p;
31208}
31209
31210/*
31211** Convert a sorted list of elements into a binary tree. Make the tree
31212** as deep as it needs to be in order to contain the entire list.
31213*/
31214static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
31215  int iDepth;           /* Depth of the tree so far */
31216  struct RowSetEntry *p;       /* Current tree root */
31217  struct RowSetEntry *pLeft;   /* Left subtree */
31218
31219  assert( pList!=0 );
31220  p = pList;
31221  pList = p->pRight;
31222  p->pLeft = p->pRight = 0;
31223  for(iDepth=1; pList; iDepth++){
31224    pLeft = p;
31225    p = pList;
31226    pList = p->pRight;
31227    p->pLeft = pLeft;
31228    p->pRight = rowSetNDeepTree(&pList, iDepth);
31229  }
31230  return p;
31231}
31232
31233/*
31234** Convert the list in p->pEntry into a sorted list if it is not
31235** sorted already.  If there is a binary tree on p->pTree, then
31236** convert it into a list too and merge it into the p->pEntry list.
31237*/
31238static void rowSetToList(RowSet *p){
31239  if( !p->isSorted ){
31240    rowSetSort(p);
31241  }
31242  if( p->pTree ){
31243    struct RowSetEntry *pHead, *pTail;
31244    rowSetTreeToList(p->pTree, &pHead, &pTail);
31245    p->pTree = 0;
31246    p->pEntry = rowSetMerge(p->pEntry, pHead);
31247  }
31248}
31249
31250/*
31251** Extract the smallest element from the RowSet.
31252** Write the element into *pRowid.  Return 1 on success.  Return
31253** 0 if the RowSet is already empty.
31254**
31255** After this routine has been called, the sqlite3RowSetInsert()
31256** routine may not be called again.
31257*/
31258SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
31259  rowSetToList(p);
31260  if( p->pEntry ){
31261    *pRowid = p->pEntry->v;
31262    p->pEntry = p->pEntry->pRight;
31263    if( p->pEntry==0 ){
31264      sqlite3RowSetClear(p);
31265    }
31266    return 1;
31267  }else{
31268    return 0;
31269  }
31270}
31271
31272/*
31273** Check to see if element iRowid was inserted into the the rowset as
31274** part of any insert batch prior to iBatch.  Return 1 or 0.
31275*/
31276SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
31277  struct RowSetEntry *p;
31278  if( iBatch!=pRowSet->iBatch ){
31279    if( pRowSet->pEntry ){
31280      rowSetToList(pRowSet);
31281      pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
31282      pRowSet->pEntry = 0;
31283      pRowSet->pLast = 0;
31284    }
31285    pRowSet->iBatch = iBatch;
31286  }
31287  p = pRowSet->pTree;
31288  while( p ){
31289    if( p->v<iRowid ){
31290      p = p->pRight;
31291    }else if( p->v>iRowid ){
31292      p = p->pLeft;
31293    }else{
31294      return 1;
31295    }
31296  }
31297  return 0;
31298}
31299
31300/************** End of rowset.c **********************************************/
31301/************** Begin file pager.c *******************************************/
31302/*
31303** 2001 September 15
31304**
31305** The author disclaims copyright to this source code.  In place of
31306** a legal notice, here is a blessing:
31307**
31308**    May you do good and not evil.
31309**    May you find forgiveness for yourself and forgive others.
31310**    May you share freely, never taking more than you give.
31311**
31312*************************************************************************
31313** This is the implementation of the page cache subsystem or "pager".
31314**
31315** The pager is used to access a database disk file.  It implements
31316** atomic commit and rollback through the use of a journal file that
31317** is separate from the database file.  The pager also implements file
31318** locking to prevent two processes from writing the same database
31319** file simultaneously, or one process from reading the database while
31320** another is writing.
31321*/
31322#ifndef SQLITE_OMIT_DISKIO
31323
31324/*
31325** Macros for troubleshooting.  Normally turned off
31326*/
31327#if 0
31328int sqlite3PagerTrace=1;  /* True to enable tracing */
31329#define sqlite3DebugPrintf printf
31330#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
31331#else
31332#define PAGERTRACE(X)
31333#endif
31334
31335/*
31336** The following two macros are used within the PAGERTRACE() macros above
31337** to print out file-descriptors.
31338**
31339** PAGERID() takes a pointer to a Pager struct as its argument. The
31340** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
31341** struct as its argument.
31342*/
31343#define PAGERID(p) ((int)(p->fd))
31344#define FILEHANDLEID(fd) ((int)fd)
31345
31346/*
31347** The page cache as a whole is always in one of the following
31348** states:
31349**
31350**   PAGER_UNLOCK        The page cache is not currently reading or
31351**                       writing the database file.  There is no
31352**                       data held in memory.  This is the initial
31353**                       state.
31354**
31355**   PAGER_SHARED        The page cache is reading the database.
31356**                       Writing is not permitted.  There can be
31357**                       multiple readers accessing the same database
31358**                       file at the same time.
31359**
31360**   PAGER_RESERVED      This process has reserved the database for writing
31361**                       but has not yet made any changes.  Only one process
31362**                       at a time can reserve the database.  The original
31363**                       database file has not been modified so other
31364**                       processes may still be reading the on-disk
31365**                       database file.
31366**
31367**   PAGER_EXCLUSIVE     The page cache is writing the database.
31368**                       Access is exclusive.  No other processes or
31369**                       threads can be reading or writing while one
31370**                       process is writing.
31371**
31372**   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
31373**                       after all dirty pages have been written to the
31374**                       database file and the file has been synced to
31375**                       disk. All that remains to do is to remove or
31376**                       truncate the journal file and the transaction
31377**                       will be committed.
31378**
31379** The page cache comes up in PAGER_UNLOCK.  The first time a
31380** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
31381** After all pages have been released using sqlite_page_unref(),
31382** the state transitions back to PAGER_UNLOCK.  The first time
31383** that sqlite3PagerWrite() is called, the state transitions to
31384** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
31385** called on an outstanding page which means that the pager must
31386** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
31387** PAGER_RESERVED means that there is an open rollback journal.
31388** The transition to PAGER_EXCLUSIVE occurs before any changes
31389** are made to the database file, though writes to the rollback
31390** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
31391** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
31392** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
31393*/
31394#define PAGER_UNLOCK      0
31395#define PAGER_SHARED      1   /* same as SHARED_LOCK */
31396#define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
31397#define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
31398#define PAGER_SYNCED      5
31399
31400/*
31401** A macro used for invoking the codec if there is one
31402*/
31403#ifdef SQLITE_HAS_CODEC
31404# define CODEC1(P,D,N,X,E) \
31405    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
31406# define CODEC2(P,D,N,X,E,O) \
31407    if( P->xCodec==0 ){ O=(char*)D; }else \
31408    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
31409#else
31410# define CODEC1(P,D,N,X,E)   /* NO-OP */
31411# define CODEC2(P,D,N,X,E,O) O=(char*)D
31412#endif
31413
31414/*
31415** The maximum allowed sector size. 64KiB. If the xSectorsize() method
31416** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
31417** This could conceivably cause corruption following a power failure on
31418** such a system. This is currently an undocumented limit.
31419*/
31420#define MAX_SECTOR_SIZE 0x10000
31421
31422/*
31423** An instance of the following structure is allocated for each active
31424** savepoint and statement transaction in the system. All such structures
31425** are stored in the Pager.aSavepoint[] array, which is allocated and
31426** resized using sqlite3Realloc().
31427**
31428** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
31429** set to 0. If a journal-header is written into the main journal while
31430** the savepoint is active, then iHdrOffset is set to the byte offset
31431** immediately following the last journal record written into the main
31432** journal before the journal-header. This is required during savepoint
31433** rollback (see pagerPlaybackSavepoint()).
31434*/
31435typedef struct PagerSavepoint PagerSavepoint;
31436struct PagerSavepoint {
31437  i64 iOffset;                 /* Starting offset in main journal */
31438  i64 iHdrOffset;              /* See above */
31439  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
31440  Pgno nOrig;                  /* Original number of pages in file */
31441  Pgno iSubRec;                /* Index of first record in sub-journal */
31442};
31443
31444/*
31445** A open page cache is an instance of the following structure.
31446**
31447** errCode
31448**
31449**   Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
31450**   or SQLITE_FULL. Once one of the first three errors occurs, it persists
31451**   and is returned as the result of every major pager API call.  The
31452**   SQLITE_FULL return code is slightly different. It persists only until the
31453**   next successful rollback is performed on the pager cache. Also,
31454**   SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
31455**   APIs, they may still be used successfully.
31456**
31457** dbSizeValid, dbSize, dbOrigSize, dbFileSize
31458**
31459**   Managing the size of the database file in pages is a little complicated.
31460**   The variable Pager.dbSize contains the number of pages that the database
31461**   image currently contains. As the database image grows or shrinks this
31462**   variable is updated. The variable Pager.dbFileSize contains the number
31463**   of pages in the database file. This may be different from Pager.dbSize
31464**   if some pages have been appended to the database image but not yet written
31465**   out from the cache to the actual file on disk. Or if the image has been
31466**   truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
31467**   contains the number of pages in the database image when the current
31468**   transaction was opened. The contents of all three of these variables is
31469**   only guaranteed to be correct if the boolean Pager.dbSizeValid is true.
31470**
31471**   TODO: Under what conditions is dbSizeValid set? Cleared?
31472**
31473** changeCountDone
31474**
31475**   This boolean variable is used to make sure that the change-counter
31476**   (the 4-byte header field at byte offset 24 of the database file) is
31477**   not updated more often than necessary.
31478**
31479**   It is set to true when the change-counter field is updated, which
31480**   can only happen if an exclusive lock is held on the database file.
31481**   It is cleared (set to false) whenever an exclusive lock is
31482**   relinquished on the database file. Each time a transaction is committed,
31483**   The changeCountDone flag is inspected. If it is true, the work of
31484**   updating the change-counter is omitted for the current transaction.
31485**
31486**   This mechanism means that when running in exclusive mode, a connection
31487**   need only update the change-counter once, for the first transaction
31488**   committed.
31489**
31490** dbModified
31491**
31492**   The dbModified flag is set whenever a database page is dirtied.
31493**   It is cleared at the end of each transaction.
31494**
31495**   It is used when committing or otherwise ending a transaction. If
31496**   the dbModified flag is clear then less work has to be done.
31497**
31498** journalStarted
31499**
31500**   This flag is set whenever the the main journal is synced.
31501**
31502**   The point of this flag is that it must be set after the
31503**   first journal header in a journal file has been synced to disk.
31504**   After this has happened, new pages appended to the database
31505**   do not need the PGHDR_NEED_SYNC flag set, as they do not need
31506**   to wait for a journal sync before they can be written out to
31507**   the database file (see function pager_write()).
31508**
31509** setMaster
31510**
31511**   This variable is used to ensure that the master journal file name
31512**   (if any) is only written into the journal file once.
31513**
31514**   When committing a transaction, the master journal file name (if any)
31515**   may be written into the journal file while the pager is still in
31516**   PAGER_RESERVED state (see CommitPhaseOne() for the action). It
31517**   then attempts to upgrade to an exclusive lock. If this attempt
31518**   fails, then SQLITE_BUSY may be returned to the user and the user
31519**   may attempt to commit the transaction again later (calling
31520**   CommitPhaseOne() again). This flag is used to ensure that the
31521**   master journal name is only written to the journal file the first
31522**   time CommitPhaseOne() is called.
31523**
31524** doNotSync
31525**
31526**   This variable is set and cleared by sqlite3PagerWrite().
31527**
31528** needSync
31529**
31530**   TODO: It might be easier to set this variable in writeJournalHdr()
31531**   and writeMasterJournal() only. Change its meaning to "unsynced data
31532**   has been written to the journal".
31533**
31534** subjInMemory
31535**
31536**   This is a boolean variable. If true, then any required sub-journal
31537**   is opened as an in-memory journal file. If false, then in-memory
31538**   sub-journals are only used for in-memory pager files.
31539*/
31540struct Pager {
31541  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
31542  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
31543  u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
31544  u8 useJournal;              /* Use a rollback journal on this file */
31545  u8 noReadlock;              /* Do not bother to obtain readlocks */
31546  u8 noSync;                  /* Do not sync the journal if true */
31547  u8 fullSync;                /* Do extra syncs of the journal for robustness */
31548  u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
31549  u8 tempFile;                /* zFilename is a temporary file */
31550  u8 readOnly;                /* True for a read-only database */
31551  u8 memDb;                   /* True to inhibit all file I/O */
31552
31553  /* The following block contains those class members that are dynamically
31554  ** modified during normal operations. The other variables in this structure
31555  ** are either constant throughout the lifetime of the pager, or else
31556  ** used to store configuration parameters that affect the way the pager
31557  ** operates.
31558  **
31559  ** The 'state' variable is described in more detail along with the
31560  ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the
31561  ** other variables in this block are described in the comment directly
31562  ** above this class definition.
31563  */
31564  u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
31565  u8 dbModified;              /* True if there are any changes to the Db */
31566  u8 needSync;                /* True if an fsync() is needed on the journal */
31567  u8 journalStarted;          /* True if header of journal is synced */
31568  u8 changeCountDone;         /* Set after incrementing the change-counter */
31569  u8 setMaster;               /* True if a m-j name has been written to jrnl */
31570  u8 doNotSync;               /* Boolean. While true, do not spill the cache */
31571  u8 dbSizeValid;             /* Set when dbSize is correct */
31572  u8 subjInMemory;            /* True to use in-memory sub-journals */
31573  Pgno dbSize;                /* Number of pages in the database */
31574  Pgno dbOrigSize;            /* dbSize before the current transaction */
31575  Pgno dbFileSize;            /* Number of pages in the database file */
31576  int errCode;                /* One of several kinds of errors */
31577  int nRec;                   /* Pages journalled since last j-header written */
31578  u32 cksumInit;              /* Quasi-random value added to every checksum */
31579  u32 nSubRec;                /* Number of records written to sub-journal */
31580  Bitvec *pInJournal;         /* One bit for each page in the database file */
31581  sqlite3_file *fd;           /* File descriptor for database */
31582  sqlite3_file *jfd;          /* File descriptor for main journal */
31583  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
31584  i64 journalOff;             /* Current write offset in the journal file */
31585  i64 journalHdr;             /* Byte offset to previous journal header */
31586  PagerSavepoint *aSavepoint; /* Array of active savepoints */
31587  int nSavepoint;             /* Number of elements in aSavepoint[] */
31588  char dbFileVers[16];        /* Changes whenever database file changes */
31589  u32 sectorSize;             /* Assumed sector size during rollback */
31590
31591  u16 nExtra;                 /* Add this many bytes to each in-memory page */
31592  i16 nReserve;               /* Number of unused bytes at end of each page */
31593  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
31594  int pageSize;               /* Number of bytes in a page */
31595  Pgno mxPgno;                /* Maximum allowed size of the database */
31596  char *zFilename;            /* Name of the database file */
31597  char *zJournal;             /* Name of the journal file */
31598  int (*xBusyHandler)(void*); /* Function to call when busy */
31599  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
31600#ifdef SQLITE_TEST
31601  int nHit, nMiss;            /* Cache hits and missing */
31602  int nRead, nWrite;          /* Database pages read/written */
31603#endif
31604  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
31605#ifdef SQLITE_HAS_CODEC
31606  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
31607  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
31608  void (*xCodecFree)(void*);             /* Destructor for the codec */
31609  void *pCodec;               /* First argument to xCodec... methods */
31610#endif
31611  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
31612  i64 journalSizeLimit;       /* Size limit for persistent journal files */
31613  PCache *pPCache;            /* Pointer to page cache object */
31614  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
31615};
31616
31617/*
31618** The following global variables hold counters used for
31619** testing purposes only.  These variables do not exist in
31620** a non-testing build.  These variables are not thread-safe.
31621*/
31622#ifdef SQLITE_TEST
31623SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
31624SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
31625SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
31626# define PAGER_INCR(v)  v++
31627#else
31628# define PAGER_INCR(v)
31629#endif
31630
31631
31632
31633/*
31634** Journal files begin with the following magic string.  The data
31635** was obtained from /dev/random.  It is used only as a sanity check.
31636**
31637** Since version 2.8.0, the journal format contains additional sanity
31638** checking information.  If the power fails while the journal is being
31639** written, semi-random garbage data might appear in the journal
31640** file after power is restored.  If an attempt is then made
31641** to roll the journal back, the database could be corrupted.  The additional
31642** sanity checking data is an attempt to discover the garbage in the
31643** journal and ignore it.
31644**
31645** The sanity checking information for the new journal format consists
31646** of a 32-bit checksum on each page of data.  The checksum covers both
31647** the page number and the pPager->pageSize bytes of data for the page.
31648** This cksum is initialized to a 32-bit random value that appears in the
31649** journal file right after the header.  The random initializer is important,
31650** because garbage data that appears at the end of a journal is likely
31651** data that was once in other files that have now been deleted.  If the
31652** garbage data came from an obsolete journal file, the checksums might
31653** be correct.  But by initializing the checksum to random value which
31654** is different for every journal, we minimize that risk.
31655*/
31656static const unsigned char aJournalMagic[] = {
31657  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
31658};
31659
31660/*
31661** The size of the of each page record in the journal is given by
31662** the following macro.
31663*/
31664#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
31665
31666/*
31667** The journal header size for this pager. This is usually the same
31668** size as a single disk sector. See also setSectorSize().
31669*/
31670#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
31671
31672/*
31673** The macro MEMDB is true if we are dealing with an in-memory database.
31674** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
31675** the value of MEMDB will be a constant and the compiler will optimize
31676** out code that would never execute.
31677*/
31678#ifdef SQLITE_OMIT_MEMORYDB
31679# define MEMDB 0
31680#else
31681# define MEMDB pPager->memDb
31682#endif
31683
31684/*
31685** The maximum legal page number is (2^31 - 1).
31686*/
31687#define PAGER_MAX_PGNO 2147483647
31688
31689#ifndef NDEBUG
31690/*
31691** Usage:
31692**
31693**   assert( assert_pager_state(pPager) );
31694*/
31695static int assert_pager_state(Pager *pPager){
31696
31697  /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */
31698  assert( pPager->tempFile==0 || pPager->state>=PAGER_EXCLUSIVE );
31699
31700  /* The changeCountDone flag is always set for temp-files */
31701  assert( pPager->tempFile==0 || pPager->changeCountDone );
31702
31703  return 1;
31704}
31705#endif
31706
31707/*
31708** Return true if it is necessary to write page *pPg into the sub-journal.
31709** A page needs to be written into the sub-journal if there exists one
31710** or more open savepoints for which:
31711**
31712**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
31713**   * The bit corresponding to the page-number is not set in
31714**     PagerSavepoint.pInSavepoint.
31715*/
31716static int subjRequiresPage(PgHdr *pPg){
31717  Pgno pgno = pPg->pgno;
31718  Pager *pPager = pPg->pPager;
31719  int i;
31720  for(i=0; i<pPager->nSavepoint; i++){
31721    PagerSavepoint *p = &pPager->aSavepoint[i];
31722    if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
31723      return 1;
31724    }
31725  }
31726  return 0;
31727}
31728
31729/*
31730** Return true if the page is already in the journal file.
31731*/
31732static int pageInJournal(PgHdr *pPg){
31733  return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
31734}
31735
31736/*
31737** Read a 32-bit integer from the given file descriptor.  Store the integer
31738** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
31739** error code is something goes wrong.
31740**
31741** All values are stored on disk as big-endian.
31742*/
31743static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
31744  unsigned char ac[4];
31745  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
31746  if( rc==SQLITE_OK ){
31747    *pRes = sqlite3Get4byte(ac);
31748  }
31749  return rc;
31750}
31751
31752/*
31753** Write a 32-bit integer into a string buffer in big-endian byte order.
31754*/
31755#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
31756
31757/*
31758** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
31759** on success or an error code is something goes wrong.
31760*/
31761static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
31762  char ac[4];
31763  put32bits(ac, val);
31764  return sqlite3OsWrite(fd, ac, 4, offset);
31765}
31766
31767/*
31768** The argument to this macro is a file descriptor (type sqlite3_file*).
31769** Return 0 if it is not open, or non-zero (but not 1) if it is.
31770**
31771** This is so that expressions can be written as:
31772**
31773**   if( isOpen(pPager->jfd) ){ ...
31774**
31775** instead of
31776**
31777**   if( pPager->jfd->pMethods ){ ...
31778*/
31779#define isOpen(pFd) ((pFd)->pMethods)
31780
31781/*
31782** If file pFd is open, call sqlite3OsUnlock() on it.
31783*/
31784static int osUnlock(sqlite3_file *pFd, int eLock){
31785  if( !isOpen(pFd) ){
31786    return SQLITE_OK;
31787  }
31788  return sqlite3OsUnlock(pFd, eLock);
31789}
31790
31791/*
31792** This function determines whether or not the atomic-write optimization
31793** can be used with this pager. The optimization can be used if:
31794**
31795**  (a) the value returned by OsDeviceCharacteristics() indicates that
31796**      a database page may be written atomically, and
31797**  (b) the value returned by OsSectorSize() is less than or equal
31798**      to the page size.
31799**
31800** The optimization is also always enabled for temporary files. It is
31801** an error to call this function if pPager is opened on an in-memory
31802** database.
31803**
31804** If the optimization cannot be used, 0 is returned. If it can be used,
31805** then the value returned is the size of the journal file when it
31806** contains rollback data for exactly one page.
31807*/
31808#ifdef SQLITE_ENABLE_ATOMIC_WRITE
31809static int jrnlBufferSize(Pager *pPager){
31810  assert( !MEMDB );
31811  if( !pPager->tempFile ){
31812    int dc;                           /* Device characteristics */
31813    int nSector;                      /* Sector size */
31814    int szPage;                       /* Page size */
31815
31816    assert( isOpen(pPager->fd) );
31817    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
31818    nSector = pPager->sectorSize;
31819    szPage = pPager->pageSize;
31820
31821    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
31822    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
31823    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
31824      return 0;
31825    }
31826  }
31827
31828  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
31829}
31830#endif
31831
31832/*
31833** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
31834** on the cache using a hash function.  This is used for testing
31835** and debugging only.
31836*/
31837#ifdef SQLITE_CHECK_PAGES
31838/*
31839** Return a 32-bit hash of the page data for pPage.
31840*/
31841static u32 pager_datahash(int nByte, unsigned char *pData){
31842  u32 hash = 0;
31843  int i;
31844  for(i=0; i<nByte; i++){
31845    hash = (hash*1039) + pData[i];
31846  }
31847  return hash;
31848}
31849static u32 pager_pagehash(PgHdr *pPage){
31850  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
31851}
31852static void pager_set_pagehash(PgHdr *pPage){
31853  pPage->pageHash = pager_pagehash(pPage);
31854}
31855
31856/*
31857** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
31858** is defined, and NDEBUG is not defined, an assert() statement checks
31859** that the page is either dirty or still matches the calculated page-hash.
31860*/
31861#define CHECK_PAGE(x) checkPage(x)
31862static void checkPage(PgHdr *pPg){
31863  Pager *pPager = pPg->pPager;
31864  assert( !pPg->pageHash || pPager->errCode
31865      || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
31866}
31867
31868#else
31869#define pager_datahash(X,Y)  0
31870#define pager_pagehash(X)  0
31871#define CHECK_PAGE(x)
31872#endif  /* SQLITE_CHECK_PAGES */
31873
31874/*
31875** When this is called the journal file for pager pPager must be open.
31876** This function attempts to read a master journal file name from the
31877** end of the file and, if successful, copies it into memory supplied
31878** by the caller. See comments above writeMasterJournal() for the format
31879** used to store a master journal file name at the end of a journal file.
31880**
31881** zMaster must point to a buffer of at least nMaster bytes allocated by
31882** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
31883** enough space to write the master journal name). If the master journal
31884** name in the journal is longer than nMaster bytes (including a
31885** nul-terminator), then this is handled as if no master journal name
31886** were present in the journal.
31887**
31888** If a master journal file name is present at the end of the journal
31889** file, then it is copied into the buffer pointed to by zMaster. A
31890** nul-terminator byte is appended to the buffer following the master
31891** journal file name.
31892**
31893** If it is determined that no master journal file name is present
31894** zMaster[0] is set to 0 and SQLITE_OK returned.
31895**
31896** If an error occurs while reading from the journal file, an SQLite
31897** error code is returned.
31898*/
31899static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
31900  int rc;                    /* Return code */
31901  u32 len;                   /* Length in bytes of master journal name */
31902  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
31903  u32 cksum;                 /* MJ checksum value read from journal */
31904  u32 u;                     /* Unsigned loop counter */
31905  unsigned char aMagic[8];   /* A buffer to hold the magic header */
31906  zMaster[0] = '\0';
31907
31908  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
31909   || szJ<16
31910   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
31911   || len>=nMaster
31912   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
31913   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
31914   || memcmp(aMagic, aJournalMagic, 8)
31915   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
31916  ){
31917    return rc;
31918  }
31919
31920  /* See if the checksum matches the master journal name */
31921  for(u=0; u<len; u++){
31922    cksum -= zMaster[u];
31923  }
31924  if( cksum ){
31925    /* If the checksum doesn't add up, then one or more of the disk sectors
31926    ** containing the master journal filename is corrupted. This means
31927    ** definitely roll back, so just return SQLITE_OK and report a (nul)
31928    ** master-journal filename.
31929    */
31930    len = 0;
31931  }
31932  zMaster[len] = '\0';
31933
31934  return SQLITE_OK;
31935}
31936
31937/*
31938** Return the offset of the sector boundary at or immediately
31939** following the value in pPager->journalOff, assuming a sector
31940** size of pPager->sectorSize bytes.
31941**
31942** i.e for a sector size of 512:
31943**
31944**   Pager.journalOff          Return value
31945**   ---------------------------------------
31946**   0                         0
31947**   512                       512
31948**   100                       512
31949**   2000                      2048
31950**
31951*/
31952static i64 journalHdrOffset(Pager *pPager){
31953  i64 offset = 0;
31954  i64 c = pPager->journalOff;
31955  if( c ){
31956    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
31957  }
31958  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
31959  assert( offset>=c );
31960  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
31961  return offset;
31962}
31963
31964/*
31965** The journal file must be open when this function is called.
31966**
31967** This function is a no-op if the journal file has not been written to
31968** within the current transaction (i.e. if Pager.journalOff==0).
31969**
31970** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
31971** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
31972** zero the 28-byte header at the start of the journal file. In either case,
31973** if the pager is not in no-sync mode, sync the journal file immediately
31974** after writing or truncating it.
31975**
31976** If Pager.journalSizeLimit is set to a positive, non-zero value, and
31977** following the truncation or zeroing described above the size of the
31978** journal file in bytes is larger than this value, then truncate the
31979** journal file to Pager.journalSizeLimit bytes. The journal file does
31980** not need to be synced following this operation.
31981**
31982** If an IO error occurs, abandon processing and return the IO error code.
31983** Otherwise, return SQLITE_OK.
31984*/
31985static int zeroJournalHdr(Pager *pPager, int doTruncate){
31986  int rc = SQLITE_OK;                               /* Return code */
31987  assert( isOpen(pPager->jfd) );
31988  if( pPager->journalOff ){
31989    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
31990
31991    IOTRACE(("JZEROHDR %p\n", pPager))
31992    if( doTruncate || iLimit==0 ){
31993      rc = sqlite3OsTruncate(pPager->jfd, 0);
31994    }else{
31995      static const char zeroHdr[28] = {0};
31996      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
31997    }
31998    if( rc==SQLITE_OK && !pPager->noSync ){
31999      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
32000    }
32001
32002    /* At this point the transaction is committed but the write lock
32003    ** is still held on the file. If there is a size limit configured for
32004    ** the persistent journal and the journal file currently consumes more
32005    ** space than that limit allows for, truncate it now. There is no need
32006    ** to sync the file following this operation.
32007    */
32008    if( rc==SQLITE_OK && iLimit>0 ){
32009      i64 sz;
32010      rc = sqlite3OsFileSize(pPager->jfd, &sz);
32011      if( rc==SQLITE_OK && sz>iLimit ){
32012        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
32013      }
32014    }
32015  }
32016  return rc;
32017}
32018
32019/*
32020** The journal file must be open when this routine is called. A journal
32021** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
32022** current location.
32023**
32024** The format for the journal header is as follows:
32025** - 8 bytes: Magic identifying journal format.
32026** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
32027** - 4 bytes: Random number used for page hash.
32028** - 4 bytes: Initial database page count.
32029** - 4 bytes: Sector size used by the process that wrote this journal.
32030** - 4 bytes: Database page size.
32031**
32032** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
32033*/
32034static int writeJournalHdr(Pager *pPager){
32035  int rc = SQLITE_OK;                 /* Return code */
32036  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
32037  u32 nHeader = pPager->pageSize;     /* Size of buffer pointed to by zHeader */
32038  u32 nWrite;                         /* Bytes of header sector written */
32039  int ii;                             /* Loop counter */
32040
32041  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
32042
32043  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
32044    nHeader = JOURNAL_HDR_SZ(pPager);
32045  }
32046
32047  /* If there are active savepoints and any of them were created
32048  ** since the most recent journal header was written, update the
32049  ** PagerSavepoint.iHdrOffset fields now.
32050  */
32051  for(ii=0; ii<pPager->nSavepoint; ii++){
32052    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
32053      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
32054    }
32055  }
32056
32057  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
32058
32059  /*
32060  ** Write the nRec Field - the number of page records that follow this
32061  ** journal header. Normally, zero is written to this value at this time.
32062  ** After the records are added to the journal (and the journal synced,
32063  ** if in full-sync mode), the zero is overwritten with the true number
32064  ** of records (see syncJournal()).
32065  **
32066  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
32067  ** reading the journal this value tells SQLite to assume that the
32068  ** rest of the journal file contains valid page records. This assumption
32069  ** is dangerous, as if a failure occurred whilst writing to the journal
32070  ** file it may contain some garbage data. There are two scenarios
32071  ** where this risk can be ignored:
32072  **
32073  **   * When the pager is in no-sync mode. Corruption can follow a
32074  **     power failure in this case anyway.
32075  **
32076  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
32077  **     that garbage data is never appended to the journal file.
32078  */
32079  assert( isOpen(pPager->fd) || pPager->noSync );
32080  if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
32081   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
32082  ){
32083    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
32084    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
32085  }else{
32086    memset(zHeader, 0, sizeof(aJournalMagic)+4);
32087  }
32088
32089  /* The random check-hash initialiser */
32090  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
32091  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
32092  /* The initial database size */
32093  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
32094  /* The assumed sector size for this process */
32095  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
32096
32097  /* The page size */
32098  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
32099
32100  /* Initializing the tail of the buffer is not necessary.  Everything
32101  ** works find if the following memset() is omitted.  But initializing
32102  ** the memory prevents valgrind from complaining, so we are willing to
32103  ** take the performance hit.
32104  */
32105  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
32106         nHeader-(sizeof(aJournalMagic)+20));
32107
32108  /* In theory, it is only necessary to write the 28 bytes that the
32109  ** journal header consumes to the journal file here. Then increment the
32110  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
32111  ** record is written to the following sector (leaving a gap in the file
32112  ** that will be implicitly filled in by the OS).
32113  **
32114  ** However it has been discovered that on some systems this pattern can
32115  ** be significantly slower than contiguously writing data to the file,
32116  ** even if that means explicitly writing data to the block of
32117  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
32118  ** is done.
32119  **
32120  ** The loop is required here in case the sector-size is larger than the
32121  ** database page size. Since the zHeader buffer is only Pager.pageSize
32122  ** bytes in size, more than one call to sqlite3OsWrite() may be required
32123  ** to populate the entire journal header sector.
32124  */
32125  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
32126    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
32127    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
32128    pPager->journalOff += nHeader;
32129  }
32130
32131  return rc;
32132}
32133
32134/*
32135** The journal file must be open when this is called. A journal header file
32136** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
32137** file. The current location in the journal file is given by
32138** pPager->journalOff. See comments above function writeJournalHdr() for
32139** a description of the journal header format.
32140**
32141** If the header is read successfully, *pNRec is set to the number of
32142** page records following this header and *pDbSize is set to the size of the
32143** database before the transaction began, in pages. Also, pPager->cksumInit
32144** is set to the value read from the journal header. SQLITE_OK is returned
32145** in this case.
32146**
32147** If the journal header file appears to be corrupted, SQLITE_DONE is
32148** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
32149** cannot be read from the journal file an error code is returned.
32150*/
32151static int readJournalHdr(
32152  Pager *pPager,               /* Pager object */
32153  int isHot,
32154  i64 journalSize,             /* Size of the open journal file in bytes */
32155  u32 *pNRec,                  /* OUT: Value read from the nRec field */
32156  u32 *pDbSize                 /* OUT: Value of original database size field */
32157){
32158  int rc;                      /* Return code */
32159  unsigned char aMagic[8];     /* A buffer to hold the magic header */
32160  i64 iHdrOff;                 /* Offset of journal header being read */
32161
32162  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
32163
32164  /* Advance Pager.journalOff to the start of the next sector. If the
32165  ** journal file is too small for there to be a header stored at this
32166  ** point, return SQLITE_DONE.
32167  */
32168  pPager->journalOff = journalHdrOffset(pPager);
32169  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
32170    return SQLITE_DONE;
32171  }
32172  iHdrOff = pPager->journalOff;
32173
32174  /* Read in the first 8 bytes of the journal header. If they do not match
32175  ** the  magic string found at the start of each journal header, return
32176  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
32177  ** proceed.
32178  */
32179  if( isHot || iHdrOff!=pPager->journalHdr ){
32180    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
32181    if( rc ){
32182      return rc;
32183    }
32184    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
32185      return SQLITE_DONE;
32186    }
32187  }
32188
32189  /* Read the first three 32-bit fields of the journal header: The nRec
32190  ** field, the checksum-initializer and the database size at the start
32191  ** of the transaction. Return an error code if anything goes wrong.
32192  */
32193  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
32194   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
32195   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
32196  ){
32197    return rc;
32198  }
32199
32200  if( pPager->journalOff==0 ){
32201    u32 iPageSize;               /* Page-size field of journal header */
32202    u32 iSectorSize;             /* Sector-size field of journal header */
32203    u16 iPageSize16;             /* Copy of iPageSize in 16-bit variable */
32204
32205    /* Read the page-size and sector-size journal header fields. */
32206    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
32207     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
32208    ){
32209      return rc;
32210    }
32211
32212    /* Check that the values read from the page-size and sector-size fields
32213    ** are within range. To be 'in range', both values need to be a power
32214    ** of two greater than or equal to 512 or 32, and not greater than their
32215    ** respective compile time maximum limits.
32216    */
32217    if( iPageSize<512                  || iSectorSize<32
32218     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
32219     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
32220    ){
32221      /* If the either the page-size or sector-size in the journal-header is
32222      ** invalid, then the process that wrote the journal-header must have
32223      ** crashed before the header was synced. In this case stop reading
32224      ** the journal file here.
32225      */
32226      return SQLITE_DONE;
32227    }
32228
32229    /* Update the page-size to match the value read from the journal.
32230    ** Use a testcase() macro to make sure that malloc failure within
32231    ** PagerSetPagesize() is tested.
32232    */
32233    iPageSize16 = (u16)iPageSize;
32234    rc = sqlite3PagerSetPagesize(pPager, &iPageSize16, -1);
32235    testcase( rc!=SQLITE_OK );
32236    assert( rc!=SQLITE_OK || iPageSize16==(u16)iPageSize );
32237
32238    /* Update the assumed sector-size to match the value used by
32239    ** the process that created this journal. If this journal was
32240    ** created by a process other than this one, then this routine
32241    ** is being called from within pager_playback(). The local value
32242    ** of Pager.sectorSize is restored at the end of that routine.
32243    */
32244    pPager->sectorSize = iSectorSize;
32245  }
32246
32247  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
32248  return rc;
32249}
32250
32251
32252/*
32253** Write the supplied master journal name into the journal file for pager
32254** pPager at the current location. The master journal name must be the last
32255** thing written to a journal file. If the pager is in full-sync mode, the
32256** journal file descriptor is advanced to the next sector boundary before
32257** anything is written. The format is:
32258**
32259**   + 4 bytes: PAGER_MJ_PGNO.
32260**   + N bytes: Master journal filename in utf-8.
32261**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
32262**   + 4 bytes: Master journal name checksum.
32263**   + 8 bytes: aJournalMagic[].
32264**
32265** The master journal page checksum is the sum of the bytes in the master
32266** journal name, where each byte is interpreted as a signed 8-bit integer.
32267**
32268** If zMaster is a NULL pointer (occurs for a single database transaction),
32269** this call is a no-op.
32270*/
32271static int writeMasterJournal(Pager *pPager, const char *zMaster){
32272  int rc;                          /* Return code */
32273  int nMaster;                     /* Length of string zMaster */
32274  i64 iHdrOff;                     /* Offset of header in journal file */
32275  i64 jrnlSize;                    /* Size of journal file on disk */
32276  u32 cksum = 0;                   /* Checksum of string zMaster */
32277
32278  if( !zMaster || pPager->setMaster
32279   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
32280   || pPager->journalMode==PAGER_JOURNALMODE_OFF
32281  ){
32282    return SQLITE_OK;
32283  }
32284  pPager->setMaster = 1;
32285  assert( isOpen(pPager->jfd) );
32286
32287  /* Calculate the length in bytes and the checksum of zMaster */
32288  for(nMaster=0; zMaster[nMaster]; nMaster++){
32289    cksum += zMaster[nMaster];
32290  }
32291
32292  /* If in full-sync mode, advance to the next disk sector before writing
32293  ** the master journal name. This is in case the previous page written to
32294  ** the journal has already been synced.
32295  */
32296  if( pPager->fullSync ){
32297    pPager->journalOff = journalHdrOffset(pPager);
32298  }
32299  iHdrOff = pPager->journalOff;
32300
32301  /* Write the master journal data to the end of the journal file. If
32302  ** an error occurs, return the error code to the caller.
32303  */
32304  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
32305   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
32306   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
32307   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
32308   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
32309  ){
32310    return rc;
32311  }
32312  pPager->journalOff += (nMaster+20);
32313  pPager->needSync = !pPager->noSync;
32314
32315  /* If the pager is in peristent-journal mode, then the physical
32316  ** journal-file may extend past the end of the master-journal name
32317  ** and 8 bytes of magic data just written to the file. This is
32318  ** dangerous because the code to rollback a hot-journal file
32319  ** will not be able to find the master-journal name to determine
32320  ** whether or not the journal is hot.
32321  **
32322  ** Easiest thing to do in this scenario is to truncate the journal
32323  ** file to the required size.
32324  */
32325  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
32326   && jrnlSize>pPager->journalOff
32327  ){
32328    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
32329  }
32330  return rc;
32331}
32332
32333/*
32334** Find a page in the hash table given its page number. Return
32335** a pointer to the page or NULL if the requested page is not
32336** already in memory.
32337*/
32338static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
32339  PgHdr *p;                         /* Return value */
32340
32341  /* It is not possible for a call to PcacheFetch() with createFlag==0 to
32342  ** fail, since no attempt to allocate dynamic memory will be made.
32343  */
32344  (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
32345  return p;
32346}
32347
32348/*
32349** Unless the pager is in error-state, discard all in-memory pages. If
32350** the pager is in error-state, then this call is a no-op.
32351**
32352** TODO: Why can we not reset the pager while in error state?
32353*/
32354static void pager_reset(Pager *pPager){
32355  if( SQLITE_OK==pPager->errCode ){
32356    sqlite3BackupRestart(pPager->pBackup);
32357    sqlite3PcacheClear(pPager->pPCache);
32358    pPager->dbSizeValid = 0;
32359  }
32360}
32361
32362/*
32363** Free all structures in the Pager.aSavepoint[] array and set both
32364** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
32365** if it is open and the pager is not in exclusive mode.
32366*/
32367static void releaseAllSavepoints(Pager *pPager){
32368  int ii;               /* Iterator for looping through Pager.aSavepoint */
32369  for(ii=0; ii<pPager->nSavepoint; ii++){
32370    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
32371  }
32372  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
32373    sqlite3OsClose(pPager->sjfd);
32374  }
32375  sqlite3_free(pPager->aSavepoint);
32376  pPager->aSavepoint = 0;
32377  pPager->nSavepoint = 0;
32378  pPager->nSubRec = 0;
32379}
32380
32381/*
32382** Set the bit number pgno in the PagerSavepoint.pInSavepoint
32383** bitvecs of all open savepoints. Return SQLITE_OK if successful
32384** or SQLITE_NOMEM if a malloc failure occurs.
32385*/
32386static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
32387  int ii;                   /* Loop counter */
32388  int rc = SQLITE_OK;       /* Result code */
32389
32390  for(ii=0; ii<pPager->nSavepoint; ii++){
32391    PagerSavepoint *p = &pPager->aSavepoint[ii];
32392    if( pgno<=p->nOrig ){
32393      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
32394      testcase( rc==SQLITE_NOMEM );
32395      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
32396    }
32397  }
32398  return rc;
32399}
32400
32401/*
32402** Unlock the database file. This function is a no-op if the pager
32403** is in exclusive mode.
32404**
32405** If the pager is currently in error state, discard the contents of
32406** the cache and reset the Pager structure internal state. If there is
32407** an open journal-file, then the next time a shared-lock is obtained
32408** on the pager file (by this or any other process), it will be
32409** treated as a hot-journal and rolled back.
32410*/
32411static void pager_unlock(Pager *pPager){
32412  if( !pPager->exclusiveMode ){
32413    int rc;                      /* Return code */
32414
32415    /* Always close the journal file when dropping the database lock.
32416    ** Otherwise, another connection with journal_mode=delete might
32417    ** delete the file out from under us.
32418    */
32419    sqlite3OsClose(pPager->jfd);
32420    sqlite3BitvecDestroy(pPager->pInJournal);
32421    pPager->pInJournal = 0;
32422    releaseAllSavepoints(pPager);
32423
32424    /* If the file is unlocked, somebody else might change it. The
32425    ** values stored in Pager.dbSize etc. might become invalid if
32426    ** this happens. TODO: Really, this doesn't need to be cleared
32427    ** until the change-counter check fails in PagerSharedLock().
32428    */
32429    pPager->dbSizeValid = 0;
32430
32431    rc = osUnlock(pPager->fd, NO_LOCK);
32432    if( rc ){
32433      pPager->errCode = rc;
32434    }
32435    IOTRACE(("UNLOCK %p\n", pPager))
32436
32437    /* If Pager.errCode is set, the contents of the pager cache cannot be
32438    ** trusted. Now that the pager file is unlocked, the contents of the
32439    ** cache can be discarded and the error code safely cleared.
32440    */
32441    if( pPager->errCode ){
32442      if( rc==SQLITE_OK ){
32443        pPager->errCode = SQLITE_OK;
32444      }
32445      pager_reset(pPager);
32446    }
32447
32448    pPager->changeCountDone = 0;
32449    pPager->state = PAGER_UNLOCK;
32450    pPager->dbModified = 0;
32451  }
32452}
32453
32454/*
32455** This function should be called when an IOERR, CORRUPT or FULL error
32456** may have occurred. The first argument is a pointer to the pager
32457** structure, the second the error-code about to be returned by a pager
32458** API function. The value returned is a copy of the second argument
32459** to this function.
32460**
32461** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
32462** the error becomes persistent. Until the persisten error is cleared,
32463** subsequent API calls on this Pager will immediately return the same
32464** error code.
32465**
32466** A persistent error indicates that the contents of the pager-cache
32467** cannot be trusted. This state can be cleared by completely discarding
32468** the contents of the pager-cache. If a transaction was active when
32469** the persistent error occurred, then the rollback journal may need
32470** to be replayed to restore the contents of the database file (as if
32471** it were a hot-journal).
32472*/
32473static int pager_error(Pager *pPager, int rc){
32474  int rc2 = rc & 0xff;
32475  assert( rc==SQLITE_OK || !MEMDB );
32476  assert(
32477       pPager->errCode==SQLITE_FULL ||
32478       pPager->errCode==SQLITE_OK ||
32479       (pPager->errCode & 0xff)==SQLITE_IOERR
32480  );
32481  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
32482    pPager->errCode = rc;
32483  }
32484  return rc;
32485}
32486
32487/*
32488** Execute a rollback if a transaction is active and unlock the
32489** database file.
32490**
32491** If the pager has already entered the error state, do not attempt
32492** the rollback at this time. Instead, pager_unlock() is called. The
32493** call to pager_unlock() will discard all in-memory pages, unlock
32494** the database file and clear the error state. If this means that
32495** there is a hot-journal left in the file-system, the next connection
32496** to obtain a shared lock on the pager (which may be this one) will
32497** roll it back.
32498**
32499** If the pager has not already entered the error state, but an IO or
32500** malloc error occurs during a rollback, then this will itself cause
32501** the pager to enter the error state. Which will be cleared by the
32502** call to pager_unlock(), as described above.
32503*/
32504static void pagerUnlockAndRollback(Pager *pPager){
32505  if( pPager->errCode==SQLITE_OK && pPager->state>=PAGER_RESERVED ){
32506    sqlite3BeginBenignMalloc();
32507    sqlite3PagerRollback(pPager);
32508    sqlite3EndBenignMalloc();
32509  }
32510  pager_unlock(pPager);
32511}
32512
32513/*
32514** This routine ends a transaction. A transaction is usually ended by
32515** either a COMMIT or a ROLLBACK operation. This routine may be called
32516** after rollback of a hot-journal, or if an error occurs while opening
32517** the journal file or writing the very first journal-header of a
32518** database transaction.
32519**
32520** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this
32521** routine is called, it is a no-op (returns SQLITE_OK).
32522**
32523** Otherwise, any active savepoints are released.
32524**
32525** If the journal file is open, then it is "finalized". Once a journal
32526** file has been finalized it is not possible to use it to roll back a
32527** transaction. Nor will it be considered to be a hot-journal by this
32528** or any other database connection. Exactly how a journal is finalized
32529** depends on whether or not the pager is running in exclusive mode and
32530** the current journal-mode (Pager.journalMode value), as follows:
32531**
32532**   journalMode==MEMORY
32533**     Journal file descriptor is simply closed. This destroys an
32534**     in-memory journal.
32535**
32536**   journalMode==TRUNCATE
32537**     Journal file is truncated to zero bytes in size.
32538**
32539**   journalMode==PERSIST
32540**     The first 28 bytes of the journal file are zeroed. This invalidates
32541**     the first journal header in the file, and hence the entire journal
32542**     file. An invalid journal file cannot be rolled back.
32543**
32544**   journalMode==DELETE
32545**     The journal file is closed and deleted using sqlite3OsDelete().
32546**
32547**     If the pager is running in exclusive mode, this method of finalizing
32548**     the journal file is never used. Instead, if the journalMode is
32549**     DELETE and the pager is in exclusive mode, the method described under
32550**     journalMode==PERSIST is used instead.
32551**
32552** After the journal is finalized, if running in non-exclusive mode, the
32553** pager moves to PAGER_SHARED state (and downgrades the lock on the
32554** database file accordingly).
32555**
32556** If the pager is running in exclusive mode and is in PAGER_SYNCED state,
32557** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in
32558** exclusive mode.
32559**
32560** SQLITE_OK is returned if no error occurs. If an error occurs during
32561** any of the IO operations to finalize the journal file or unlock the
32562** database then the IO error code is returned to the user. If the
32563** operation to finalize the journal file fails, then the code still
32564** tries to unlock the database file if not in exclusive mode. If the
32565** unlock operation fails as well, then the first error code related
32566** to the first error encountered (the journal finalization one) is
32567** returned.
32568*/
32569static int pager_end_transaction(Pager *pPager, int hasMaster){
32570  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
32571  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
32572
32573  if( pPager->state<PAGER_RESERVED ){
32574    return SQLITE_OK;
32575  }
32576  releaseAllSavepoints(pPager);
32577
32578  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
32579  if( isOpen(pPager->jfd) ){
32580
32581    /* Finalize the journal file. */
32582    if( sqlite3IsMemJournal(pPager->jfd) ){
32583      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
32584      sqlite3OsClose(pPager->jfd);
32585    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
32586      if( pPager->journalOff==0 ){
32587        rc = SQLITE_OK;
32588      }else{
32589        rc = sqlite3OsTruncate(pPager->jfd, 0);
32590      }
32591      pPager->journalOff = 0;
32592      pPager->journalStarted = 0;
32593    }else if( pPager->exclusiveMode
32594     || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
32595    ){
32596      rc = zeroJournalHdr(pPager, hasMaster);
32597      pager_error(pPager, rc);
32598      pPager->journalOff = 0;
32599      pPager->journalStarted = 0;
32600    }else{
32601      /* This branch may be executed with Pager.journalMode==MEMORY if
32602      ** a hot-journal was just rolled back. In this case the journal
32603      ** file should be closed and deleted. If this connection writes to
32604      ** the database file, it will do so using an in-memory journal.  */
32605      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
32606           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
32607      );
32608      sqlite3OsClose(pPager->jfd);
32609      if( !pPager->tempFile ){
32610        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
32611      }
32612    }
32613
32614#ifdef SQLITE_CHECK_PAGES
32615    sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
32616#endif
32617
32618    sqlite3PcacheCleanAll(pPager->pPCache);
32619    sqlite3BitvecDestroy(pPager->pInJournal);
32620    pPager->pInJournal = 0;
32621    pPager->nRec = 0;
32622  }
32623
32624  if( !pPager->exclusiveMode ){
32625    rc2 = osUnlock(pPager->fd, SHARED_LOCK);
32626    pPager->state = PAGER_SHARED;
32627    pPager->changeCountDone = 0;
32628  }else if( pPager->state==PAGER_SYNCED ){
32629    pPager->state = PAGER_EXCLUSIVE;
32630  }
32631  pPager->setMaster = 0;
32632  pPager->needSync = 0;
32633  pPager->dbModified = 0;
32634
32635  /* TODO: Is this optimal? Why is the db size invalidated here
32636  ** when the database file is not unlocked? */
32637  pPager->dbOrigSize = 0;
32638  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
32639  if( !MEMDB ){
32640    pPager->dbSizeValid = 0;
32641  }
32642
32643  return (rc==SQLITE_OK?rc2:rc);
32644}
32645
32646/*
32647** Parameter aData must point to a buffer of pPager->pageSize bytes
32648** of data. Compute and return a checksum based ont the contents of the
32649** page of data and the current value of pPager->cksumInit.
32650**
32651** This is not a real checksum. It is really just the sum of the
32652** random initial value (pPager->cksumInit) and every 200th byte
32653** of the page data, starting with byte offset (pPager->pageSize%200).
32654** Each byte is interpreted as an 8-bit unsigned integer.
32655**
32656** Changing the formula used to compute this checksum results in an
32657** incompatible journal file format.
32658**
32659** If journal corruption occurs due to a power failure, the most likely
32660** scenario is that one end or the other of the record will be changed.
32661** It is much less likely that the two ends of the journal record will be
32662** correct and the middle be corrupt.  Thus, this "checksum" scheme,
32663** though fast and simple, catches the mostly likely kind of corruption.
32664*/
32665static u32 pager_cksum(Pager *pPager, const u8 *aData){
32666  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
32667  int i = pPager->pageSize-200;          /* Loop counter */
32668  while( i>0 ){
32669    cksum += aData[i];
32670    i -= 200;
32671  }
32672  return cksum;
32673}
32674
32675/*
32676** Read a single page from either the journal file (if isMainJrnl==1) or
32677** from the sub-journal (if isMainJrnl==0) and playback that page.
32678** The page begins at offset *pOffset into the file. The *pOffset
32679** value is increased to the start of the next page in the journal.
32680**
32681** The isMainJrnl flag is true if this is the main rollback journal and
32682** false for the statement journal.  The main rollback journal uses
32683** checksums - the statement journal does not.
32684**
32685** If the page number of the page record read from the (sub-)journal file
32686** is greater than the current value of Pager.dbSize, then playback is
32687** skipped and SQLITE_OK is returned.
32688**
32689** If pDone is not NULL, then it is a record of pages that have already
32690** been played back.  If the page at *pOffset has already been played back
32691** (if the corresponding pDone bit is set) then skip the playback.
32692** Make sure the pDone bit corresponding to the *pOffset page is set
32693** prior to returning.
32694**
32695** If the page record is successfully read from the (sub-)journal file
32696** and played back, then SQLITE_OK is returned. If an IO error occurs
32697** while reading the record from the (sub-)journal file or while writing
32698** to the database file, then the IO error code is returned. If data
32699** is successfully read from the (sub-)journal file but appears to be
32700** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
32701** two circumstances:
32702**
32703**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
32704**   * If the record is being rolled back from the main journal file
32705**     and the checksum field does not match the record content.
32706**
32707** Neither of these two scenarios are possible during a savepoint rollback.
32708**
32709** If this is a savepoint rollback, then memory may have to be dynamically
32710** allocated by this function. If this is the case and an allocation fails,
32711** SQLITE_NOMEM is returned.
32712*/
32713static int pager_playback_one_page(
32714  Pager *pPager,                /* The pager being played back */
32715  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
32716  int isUnsync,                 /* True if reading from unsynced main journal */
32717  i64 *pOffset,                 /* Offset of record to playback */
32718  int isSavepnt,                /* True for a savepoint rollback */
32719  Bitvec *pDone                 /* Bitvec of pages already played back */
32720){
32721  int rc;
32722  PgHdr *pPg;                   /* An existing page in the cache */
32723  Pgno pgno;                    /* The page number of a page in journal */
32724  u32 cksum;                    /* Checksum used for sanity checking */
32725  char *aData;                  /* Temporary storage for the page */
32726  sqlite3_file *jfd;            /* The file descriptor for the journal file */
32727
32728  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
32729  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
32730  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
32731  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
32732
32733  aData = pPager->pTmpSpace;
32734  assert( aData );         /* Temp storage must have already been allocated */
32735
32736  /* Read the page number and page data from the journal or sub-journal
32737  ** file. Return an error code to the caller if an IO error occurs.
32738  */
32739  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
32740  rc = read32bits(jfd, *pOffset, &pgno);
32741  if( rc!=SQLITE_OK ) return rc;
32742  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
32743  if( rc!=SQLITE_OK ) return rc;
32744  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
32745
32746  /* Sanity checking on the page.  This is more important that I originally
32747  ** thought.  If a power failure occurs while the journal is being written,
32748  ** it could cause invalid data to be written into the journal.  We need to
32749  ** detect this invalid data (with high probability) and ignore it.
32750  */
32751  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
32752    assert( !isSavepnt );
32753    return SQLITE_DONE;
32754  }
32755  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
32756    return SQLITE_OK;
32757  }
32758  if( isMainJrnl ){
32759    rc = read32bits(jfd, (*pOffset)-4, &cksum);
32760    if( rc ) return rc;
32761    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
32762      return SQLITE_DONE;
32763    }
32764  }
32765
32766  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
32767    return rc;
32768  }
32769
32770  assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
32771
32772  /* If the pager is in RESERVED state, then there must be a copy of this
32773  ** page in the pager cache. In this case just update the pager cache,
32774  ** not the database file. The page is left marked dirty in this case.
32775  **
32776  ** An exception to the above rule: If the database is in no-sync mode
32777  ** and a page is moved during an incremental vacuum then the page may
32778  ** not be in the pager cache. Later: if a malloc() or IO error occurs
32779  ** during a Movepage() call, then the page may not be in the cache
32780  ** either. So the condition described in the above paragraph is not
32781  ** assert()able.
32782  **
32783  ** If in EXCLUSIVE state, then we update the pager cache if it exists
32784  ** and the main file. The page is then marked not dirty.
32785  **
32786  ** Ticket #1171:  The statement journal might contain page content that is
32787  ** different from the page content at the start of the transaction.
32788  ** This occurs when a page is changed prior to the start of a statement
32789  ** then changed again within the statement.  When rolling back such a
32790  ** statement we must not write to the original database unless we know
32791  ** for certain that original page contents are synced into the main rollback
32792  ** journal.  Otherwise, a power loss might leave modified data in the
32793  ** database file without an entry in the rollback journal that can
32794  ** restore the database to its original form.  Two conditions must be
32795  ** met before writing to the database files. (1) the database must be
32796  ** locked.  (2) we know that the original page content is fully synced
32797  ** in the main journal either because the page is not in cache or else
32798  ** the page is marked as needSync==0.
32799  **
32800  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
32801  ** is possible to fail a statement on a database that does not yet exist.
32802  ** Do not attempt to write if database file has never been opened.
32803  */
32804  pPg = pager_lookup(pPager, pgno);
32805  assert( pPg || !MEMDB );
32806  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
32807           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
32808           (isMainJrnl?"main-journal":"sub-journal")
32809  ));
32810  if( (pPager->state>=PAGER_EXCLUSIVE)
32811   && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
32812   && isOpen(pPager->fd)
32813   && !isUnsync
32814  ){
32815    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
32816    rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
32817    if( pgno>pPager->dbFileSize ){
32818      pPager->dbFileSize = pgno;
32819    }
32820    if( pPager->pBackup ){
32821      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
32822      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
32823      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
32824    }
32825  }else if( !isMainJrnl && pPg==0 ){
32826    /* If this is a rollback of a savepoint and data was not written to
32827    ** the database and the page is not in-memory, there is a potential
32828    ** problem. When the page is next fetched by the b-tree layer, it
32829    ** will be read from the database file, which may or may not be
32830    ** current.
32831    **
32832    ** There are a couple of different ways this can happen. All are quite
32833    ** obscure. When running in synchronous mode, this can only happen
32834    ** if the page is on the free-list at the start of the transaction, then
32835    ** populated, then moved using sqlite3PagerMovepage().
32836    **
32837    ** The solution is to add an in-memory page to the cache containing
32838    ** the data just read from the sub-journal. Mark the page as dirty
32839    ** and if the pager requires a journal-sync, then mark the page as
32840    ** requiring a journal-sync before it is written.
32841    */
32842    assert( isSavepnt );
32843    if( (rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1))!=SQLITE_OK ){
32844      return rc;
32845    }
32846    pPg->flags &= ~PGHDR_NEED_READ;
32847    sqlite3PcacheMakeDirty(pPg);
32848  }
32849  if( pPg ){
32850    /* No page should ever be explicitly rolled back that is in use, except
32851    ** for page 1 which is held in use in order to keep the lock on the
32852    ** database active. However such a page may be rolled back as a result
32853    ** of an internal error resulting in an automatic call to
32854    ** sqlite3PagerRollback().
32855    */
32856    void *pData;
32857    pData = pPg->pData;
32858    memcpy(pData, (u8*)aData, pPager->pageSize);
32859    pPager->xReiniter(pPg);
32860    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
32861      /* If the contents of this page were just restored from the main
32862      ** journal file, then its content must be as they were when the
32863      ** transaction was first opened. In this case we can mark the page
32864      ** as clean, since there will be no need to write it out to the.
32865      **
32866      ** There is one exception to this rule. If the page is being rolled
32867      ** back as part of a savepoint (or statement) rollback from an
32868      ** unsynced portion of the main journal file, then it is not safe
32869      ** to mark the page as clean. This is because marking the page as
32870      ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
32871      ** already in the journal file (recorded in Pager.pInJournal) and
32872      ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
32873      ** again within this transaction, it will be marked as dirty but
32874      ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
32875      ** be written out into the database file before its journal file
32876      ** segment is synced. If a crash occurs during or following this,
32877      ** database corruption may ensue.
32878      */
32879      sqlite3PcacheMakeClean(pPg);
32880    }
32881#ifdef SQLITE_CHECK_PAGES
32882    pPg->pageHash = pager_pagehash(pPg);
32883#endif
32884    /* If this was page 1, then restore the value of Pager.dbFileVers.
32885    ** Do this before any decoding. */
32886    if( pgno==1 ){
32887      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
32888    }
32889
32890    /* Decode the page just read from disk */
32891    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
32892    sqlite3PcacheRelease(pPg);
32893  }
32894  return rc;
32895}
32896
32897/*
32898** Parameter zMaster is the name of a master journal file. A single journal
32899** file that referred to the master journal file has just been rolled back.
32900** This routine checks if it is possible to delete the master journal file,
32901** and does so if it is.
32902**
32903** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
32904** available for use within this function.
32905**
32906** When a master journal file is created, it is populated with the names
32907** of all of its child journals, one after another, formatted as utf-8
32908** encoded text. The end of each child journal file is marked with a
32909** nul-terminator byte (0x00). i.e. the entire contents of a master journal
32910** file for a transaction involving two databases might be:
32911**
32912**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
32913**
32914** A master journal file may only be deleted once all of its child
32915** journals have been rolled back.
32916**
32917** This function reads the contents of the master-journal file into
32918** memory and loops through each of the child journal names. For
32919** each child journal, it checks if:
32920**
32921**   * if the child journal exists, and if so
32922**   * if the child journal contains a reference to master journal
32923**     file zMaster
32924**
32925** If a child journal can be found that matches both of the criteria
32926** above, this function returns without doing anything. Otherwise, if
32927** no such child journal can be found, file zMaster is deleted from
32928** the file-system using sqlite3OsDelete().
32929**
32930** If an IO error within this function, an error code is returned. This
32931** function allocates memory by calling sqlite3Malloc(). If an allocation
32932** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
32933** occur, SQLITE_OK is returned.
32934**
32935** TODO: This function allocates a single block of memory to load
32936** the entire contents of the master journal file. This could be
32937** a couple of kilobytes or so - potentially larger than the page
32938** size.
32939*/
32940static int pager_delmaster(Pager *pPager, const char *zMaster){
32941  sqlite3_vfs *pVfs = pPager->pVfs;
32942  int rc;                   /* Return code */
32943  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
32944  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
32945  char *zMasterJournal = 0; /* Contents of master journal file */
32946  i64 nMasterJournal;       /* Size of master journal file */
32947
32948  /* Allocate space for both the pJournal and pMaster file descriptors.
32949  ** If successful, open the master journal file for reading.
32950  */
32951  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
32952  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
32953  if( !pMaster ){
32954    rc = SQLITE_NOMEM;
32955  }else{
32956    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
32957    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
32958  }
32959  if( rc!=SQLITE_OK ) goto delmaster_out;
32960
32961  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
32962  if( rc!=SQLITE_OK ) goto delmaster_out;
32963
32964  if( nMasterJournal>0 ){
32965    char *zJournal;
32966    char *zMasterPtr = 0;
32967    int nMasterPtr = pVfs->mxPathname+1;
32968
32969    /* Load the entire master journal file into space obtained from
32970    ** sqlite3_malloc() and pointed to by zMasterJournal.
32971    */
32972    zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
32973    if( !zMasterJournal ){
32974      rc = SQLITE_NOMEM;
32975      goto delmaster_out;
32976    }
32977    zMasterPtr = &zMasterJournal[nMasterJournal+1];
32978    rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
32979    if( rc!=SQLITE_OK ) goto delmaster_out;
32980    zMasterJournal[nMasterJournal] = 0;
32981
32982    zJournal = zMasterJournal;
32983    while( (zJournal-zMasterJournal)<nMasterJournal ){
32984      int exists;
32985      rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
32986      if( rc!=SQLITE_OK ){
32987        goto delmaster_out;
32988      }
32989      if( exists ){
32990        /* One of the journals pointed to by the master journal exists.
32991        ** Open it and check if it points at the master journal. If
32992        ** so, return without deleting the master journal file.
32993        */
32994        int c;
32995        int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
32996        rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
32997        if( rc!=SQLITE_OK ){
32998          goto delmaster_out;
32999        }
33000
33001        rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
33002        sqlite3OsClose(pJournal);
33003        if( rc!=SQLITE_OK ){
33004          goto delmaster_out;
33005        }
33006
33007        c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
33008        if( c ){
33009          /* We have a match. Do not delete the master journal file. */
33010          goto delmaster_out;
33011        }
33012      }
33013      zJournal += (sqlite3Strlen30(zJournal)+1);
33014    }
33015  }
33016
33017  rc = sqlite3OsDelete(pVfs, zMaster, 0);
33018
33019delmaster_out:
33020  if( zMasterJournal ){
33021    sqlite3_free(zMasterJournal);
33022  }
33023  if( pMaster ){
33024    sqlite3OsClose(pMaster);
33025    assert( !isOpen(pJournal) );
33026  }
33027  sqlite3_free(pMaster);
33028  return rc;
33029}
33030
33031
33032/*
33033** This function is used to change the actual size of the database
33034** file in the file-system. This only happens when committing a transaction,
33035** or rolling back a transaction (including rolling back a hot-journal).
33036**
33037** If the main database file is not open, or an exclusive lock is not
33038** held, this function is a no-op. Otherwise, the size of the file is
33039** changed to nPage pages (nPage*pPager->pageSize bytes). If the file
33040** on disk is currently larger than nPage pages, then use the VFS
33041** xTruncate() method to truncate it.
33042**
33043** Or, it might might be the case that the file on disk is smaller than
33044** nPage pages. Some operating system implementations can get confused if
33045** you try to truncate a file to some size that is larger than it
33046** currently is, so detect this case and write a single zero byte to
33047** the end of the new file instead.
33048**
33049** If successful, return SQLITE_OK. If an IO error occurs while modifying
33050** the database file, return the error code to the caller.
33051*/
33052static int pager_truncate(Pager *pPager, Pgno nPage){
33053  int rc = SQLITE_OK;
33054  if( pPager->state>=PAGER_EXCLUSIVE && isOpen(pPager->fd) ){
33055    i64 currentSize, newSize;
33056    /* TODO: Is it safe to use Pager.dbFileSize here? */
33057    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
33058    newSize = pPager->pageSize*(i64)nPage;
33059    if( rc==SQLITE_OK && currentSize!=newSize ){
33060      if( currentSize>newSize ){
33061        rc = sqlite3OsTruncate(pPager->fd, newSize);
33062      }else{
33063        rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
33064      }
33065      if( rc==SQLITE_OK ){
33066        pPager->dbFileSize = nPage;
33067      }
33068    }
33069  }
33070  return rc;
33071}
33072
33073/*
33074** Set the value of the Pager.sectorSize variable for the given
33075** pager based on the value returned by the xSectorSize method
33076** of the open database file. The sector size will be used used
33077** to determine the size and alignment of journal header and
33078** master journal pointers within created journal files.
33079**
33080** For temporary files the effective sector size is always 512 bytes.
33081**
33082** Otherwise, for non-temporary files, the effective sector size is
33083** the value returned by the xSectorSize() method rounded up to 32 if
33084** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
33085** is greater than MAX_SECTOR_SIZE.
33086*/
33087static void setSectorSize(Pager *pPager){
33088  assert( isOpen(pPager->fd) || pPager->tempFile );
33089
33090  if( !pPager->tempFile ){
33091    /* Sector size doesn't matter for temporary files. Also, the file
33092    ** may not have been opened yet, in which case the OsSectorSize()
33093    ** call will segfault.
33094    */
33095    pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
33096  }
33097  if( pPager->sectorSize<32 ){
33098    pPager->sectorSize = 512;
33099  }
33100  if( pPager->sectorSize>MAX_SECTOR_SIZE ){
33101    assert( MAX_SECTOR_SIZE>=512 );
33102    pPager->sectorSize = MAX_SECTOR_SIZE;
33103  }
33104}
33105
33106/*
33107** Playback the journal and thus restore the database file to
33108** the state it was in before we started making changes.
33109**
33110** The journal file format is as follows:
33111**
33112**  (1)  8 byte prefix.  A copy of aJournalMagic[].
33113**  (2)  4 byte big-endian integer which is the number of valid page records
33114**       in the journal.  If this value is 0xffffffff, then compute the
33115**       number of page records from the journal size.
33116**  (3)  4 byte big-endian integer which is the initial value for the
33117**       sanity checksum.
33118**  (4)  4 byte integer which is the number of pages to truncate the
33119**       database to during a rollback.
33120**  (5)  4 byte big-endian integer which is the sector size.  The header
33121**       is this many bytes in size.
33122**  (6)  4 byte big-endian integer which is the page size.
33123**  (7)  zero padding out to the next sector size.
33124**  (8)  Zero or more pages instances, each as follows:
33125**        +  4 byte page number.
33126**        +  pPager->pageSize bytes of data.
33127**        +  4 byte checksum
33128**
33129** When we speak of the journal header, we mean the first 7 items above.
33130** Each entry in the journal is an instance of the 8th item.
33131**
33132** Call the value from the second bullet "nRec".  nRec is the number of
33133** valid page entries in the journal.  In most cases, you can compute the
33134** value of nRec from the size of the journal file.  But if a power
33135** failure occurred while the journal was being written, it could be the
33136** case that the size of the journal file had already been increased but
33137** the extra entries had not yet made it safely to disk.  In such a case,
33138** the value of nRec computed from the file size would be too large.  For
33139** that reason, we always use the nRec value in the header.
33140**
33141** If the nRec value is 0xffffffff it means that nRec should be computed
33142** from the file size.  This value is used when the user selects the
33143** no-sync option for the journal.  A power failure could lead to corruption
33144** in this case.  But for things like temporary table (which will be
33145** deleted when the power is restored) we don't care.
33146**
33147** If the file opened as the journal file is not a well-formed
33148** journal file then all pages up to the first corrupted page are rolled
33149** back (or no pages if the journal header is corrupted). The journal file
33150** is then deleted and SQLITE_OK returned, just as if no corruption had
33151** been encountered.
33152**
33153** If an I/O or malloc() error occurs, the journal-file is not deleted
33154** and an error code is returned.
33155**
33156** The isHot parameter indicates that we are trying to rollback a journal
33157** that might be a hot journal.  Or, it could be that the journal is
33158** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
33159** If the journal really is hot, reset the pager cache prior rolling
33160** back any content.  If the journal is merely persistent, no reset is
33161** needed.
33162*/
33163static int pager_playback(Pager *pPager, int isHot){
33164  sqlite3_vfs *pVfs = pPager->pVfs;
33165  i64 szJ;                 /* Size of the journal file in bytes */
33166  u32 nRec;                /* Number of Records in the journal */
33167  u32 u;                   /* Unsigned loop counter */
33168  Pgno mxPg = 0;           /* Size of the original file in pages */
33169  int rc;                  /* Result code of a subroutine */
33170  int res = 1;             /* Value returned by sqlite3OsAccess() */
33171  char *zMaster = 0;       /* Name of master journal file if any */
33172  int needPagerReset;      /* True to reset page prior to first page rollback */
33173
33174  /* Figure out how many records are in the journal.  Abort early if
33175  ** the journal is empty.
33176  */
33177  assert( isOpen(pPager->jfd) );
33178  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
33179  if( rc!=SQLITE_OK || szJ==0 ){
33180    goto end_playback;
33181  }
33182
33183  /* Read the master journal name from the journal, if it is present.
33184  ** If a master journal file name is specified, but the file is not
33185  ** present on disk, then the journal is not hot and does not need to be
33186  ** played back.
33187  **
33188  ** TODO: Technically the following is an error because it assumes that
33189  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
33190  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
33191  **  mxPathname is 512, which is the same as the minimum allowable value
33192  ** for pageSize.
33193  */
33194  zMaster = pPager->pTmpSpace;
33195  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
33196  if( rc==SQLITE_OK && zMaster[0] ){
33197    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
33198  }
33199  zMaster = 0;
33200  if( rc!=SQLITE_OK || !res ){
33201    goto end_playback;
33202  }
33203  pPager->journalOff = 0;
33204  needPagerReset = isHot;
33205
33206  /* This loop terminates either when a readJournalHdr() or
33207  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
33208  ** occurs.
33209  */
33210  while( 1 ){
33211    int isUnsync = 0;
33212
33213    /* Read the next journal header from the journal file.  If there are
33214    ** not enough bytes left in the journal file for a complete header, or
33215    ** it is corrupted, then a process must of failed while writing it.
33216    ** This indicates nothing more needs to be rolled back.
33217    */
33218    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
33219    if( rc!=SQLITE_OK ){
33220      if( rc==SQLITE_DONE ){
33221        rc = SQLITE_OK;
33222      }
33223      goto end_playback;
33224    }
33225
33226    /* If nRec is 0xffffffff, then this journal was created by a process
33227    ** working in no-sync mode. This means that the rest of the journal
33228    ** file consists of pages, there are no more journal headers. Compute
33229    ** the value of nRec based on this assumption.
33230    */
33231    if( nRec==0xffffffff ){
33232      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
33233      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
33234    }
33235
33236    /* If nRec is 0 and this rollback is of a transaction created by this
33237    ** process and if this is the final header in the journal, then it means
33238    ** that this part of the journal was being filled but has not yet been
33239    ** synced to disk.  Compute the number of pages based on the remaining
33240    ** size of the file.
33241    **
33242    ** The third term of the test was added to fix ticket #2565.
33243    ** When rolling back a hot journal, nRec==0 always means that the next
33244    ** chunk of the journal contains zero pages to be rolled back.  But
33245    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
33246    ** the journal, it means that the journal might contain additional
33247    ** pages that need to be rolled back and that the number of pages
33248    ** should be computed based on the journal file size.
33249    */
33250    if( nRec==0 && !isHot &&
33251        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
33252      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
33253      isUnsync = 1;
33254    }
33255
33256    /* If this is the first header read from the journal, truncate the
33257    ** database file back to its original size.
33258    */
33259    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
33260      rc = pager_truncate(pPager, mxPg);
33261      if( rc!=SQLITE_OK ){
33262        goto end_playback;
33263      }
33264      pPager->dbSize = mxPg;
33265    }
33266
33267    /* Copy original pages out of the journal and back into the
33268    ** database file and/or page cache.
33269    */
33270    for(u=0; u<nRec; u++){
33271      if( needPagerReset ){
33272        pager_reset(pPager);
33273        needPagerReset = 0;
33274      }
33275      rc = pager_playback_one_page(pPager,1,isUnsync,&pPager->journalOff,0,0);
33276      if( rc!=SQLITE_OK ){
33277        if( rc==SQLITE_DONE ){
33278          rc = SQLITE_OK;
33279          pPager->journalOff = szJ;
33280          break;
33281        }else{
33282          /* If we are unable to rollback, quit and return the error
33283          ** code.  This will cause the pager to enter the error state
33284          ** so that no further harm will be done.  Perhaps the next
33285          ** process to come along will be able to rollback the database.
33286          */
33287          goto end_playback;
33288        }
33289      }
33290    }
33291  }
33292  /*NOTREACHED*/
33293  assert( 0 );
33294
33295end_playback:
33296  /* Following a rollback, the database file should be back in its original
33297  ** state prior to the start of the transaction, so invoke the
33298  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
33299  ** assertion that the transaction counter was modified.
33300  */
33301  assert(
33302    pPager->fd->pMethods==0 ||
33303    sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
33304  );
33305
33306  /* If this playback is happening automatically as a result of an IO or
33307  ** malloc error that occurred after the change-counter was updated but
33308  ** before the transaction was committed, then the change-counter
33309  ** modification may just have been reverted. If this happens in exclusive
33310  ** mode, then subsequent transactions performed by the connection will not
33311  ** update the change-counter at all. This may lead to cache inconsistency
33312  ** problems for other processes at some point in the future. So, just
33313  ** in case this has happened, clear the changeCountDone flag now.
33314  */
33315  pPager->changeCountDone = pPager->tempFile;
33316
33317  if( rc==SQLITE_OK ){
33318    zMaster = pPager->pTmpSpace;
33319    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
33320    testcase( rc!=SQLITE_OK );
33321  }
33322  if( rc==SQLITE_OK ){
33323    rc = pager_end_transaction(pPager, zMaster[0]!='\0');
33324    testcase( rc!=SQLITE_OK );
33325  }
33326  if( rc==SQLITE_OK && zMaster[0] && res ){
33327    /* If there was a master journal and this routine will return success,
33328    ** see if it is possible to delete the master journal.
33329    */
33330    rc = pager_delmaster(pPager, zMaster);
33331    testcase( rc!=SQLITE_OK );
33332  }
33333
33334  /* The Pager.sectorSize variable may have been updated while rolling
33335  ** back a journal created by a process with a different sector size
33336  ** value. Reset it to the correct value for this process.
33337  */
33338  setSectorSize(pPager);
33339  return rc;
33340}
33341
33342/*
33343** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
33344** the entire master journal file. The case pSavepoint==NULL occurs when
33345** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
33346** savepoint.
33347**
33348** When pSavepoint is not NULL (meaning a non-transaction savepoint is
33349** being rolled back), then the rollback consists of up to three stages,
33350** performed in the order specified:
33351**
33352**   * Pages are played back from the main journal starting at byte
33353**     offset PagerSavepoint.iOffset and continuing to
33354**     PagerSavepoint.iHdrOffset, or to the end of the main journal
33355**     file if PagerSavepoint.iHdrOffset is zero.
33356**
33357**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
33358**     back starting from the journal header immediately following
33359**     PagerSavepoint.iHdrOffset to the end of the main journal file.
33360**
33361**   * Pages are then played back from the sub-journal file, starting
33362**     with the PagerSavepoint.iSubRec and continuing to the end of
33363**     the journal file.
33364**
33365** Throughout the rollback process, each time a page is rolled back, the
33366** corresponding bit is set in a bitvec structure (variable pDone in the
33367** implementation below). This is used to ensure that a page is only
33368** rolled back the first time it is encountered in either journal.
33369**
33370** If pSavepoint is NULL, then pages are only played back from the main
33371** journal file. There is no need for a bitvec in this case.
33372**
33373** In either case, before playback commences the Pager.dbSize variable
33374** is reset to the value that it held at the start of the savepoint
33375** (or transaction). No page with a page-number greater than this value
33376** is played back. If one is encountered it is simply skipped.
33377*/
33378static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
33379  i64 szJ;                 /* Effective size of the main journal */
33380  i64 iHdrOff;             /* End of first segment of main-journal records */
33381  int rc = SQLITE_OK;      /* Return code */
33382  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
33383
33384  assert( pPager->state>=PAGER_SHARED );
33385
33386  /* Allocate a bitvec to use to store the set of pages rolled back */
33387  if( pSavepoint ){
33388    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
33389    if( !pDone ){
33390      return SQLITE_NOMEM;
33391    }
33392  }
33393
33394  /* Set the database size back to the value it was before the savepoint
33395  ** being reverted was opened.
33396  */
33397  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
33398
33399  /* Use pPager->journalOff as the effective size of the main rollback
33400  ** journal.  The actual file might be larger than this in
33401  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
33402  ** past pPager->journalOff is off-limits to us.
33403  */
33404  szJ = pPager->journalOff;
33405
33406  /* Begin by rolling back records from the main journal starting at
33407  ** PagerSavepoint.iOffset and continuing to the next journal header.
33408  ** There might be records in the main journal that have a page number
33409  ** greater than the current database size (pPager->dbSize) but those
33410  ** will be skipped automatically.  Pages are added to pDone as they
33411  ** are played back.
33412  */
33413  if( pSavepoint ){
33414    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
33415    pPager->journalOff = pSavepoint->iOffset;
33416    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
33417      rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
33418    }
33419    assert( rc!=SQLITE_DONE );
33420  }else{
33421    pPager->journalOff = 0;
33422  }
33423
33424  /* Continue rolling back records out of the main journal starting at
33425  ** the first journal header seen and continuing until the effective end
33426  ** of the main journal file.  Continue to skip out-of-range pages and
33427  ** continue adding pages rolled back to pDone.
33428  */
33429  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
33430    u32 ii;            /* Loop counter */
33431    u32 nJRec = 0;     /* Number of Journal Records */
33432    u32 dummy;
33433    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
33434    assert( rc!=SQLITE_DONE );
33435
33436    /*
33437    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
33438    ** test is related to ticket #2565.  See the discussion in the
33439    ** pager_playback() function for additional information.
33440    */
33441    if( nJRec==0
33442     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
33443    ){
33444      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
33445    }
33446    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
33447      rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
33448    }
33449    assert( rc!=SQLITE_DONE );
33450  }
33451  assert( rc!=SQLITE_OK || pPager->journalOff==szJ );
33452
33453  /* Finally,  rollback pages from the sub-journal.  Page that were
33454  ** previously rolled back out of the main journal (and are hence in pDone)
33455  ** will be skipped.  Out-of-range pages are also skipped.
33456  */
33457  if( pSavepoint ){
33458    u32 ii;            /* Loop counter */
33459    i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
33460    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
33461      assert( offset==ii*(4+pPager->pageSize) );
33462      rc = pager_playback_one_page(pPager, 0, 0, &offset, 1, pDone);
33463    }
33464    assert( rc!=SQLITE_DONE );
33465  }
33466
33467  sqlite3BitvecDestroy(pDone);
33468  if( rc==SQLITE_OK ){
33469    pPager->journalOff = szJ;
33470  }
33471  return rc;
33472}
33473
33474/*
33475** Change the maximum number of in-memory pages that are allowed.
33476*/
33477SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
33478  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
33479}
33480
33481/*
33482** Adjust the robustness of the database to damage due to OS crashes
33483** or power failures by changing the number of syncs()s when writing
33484** the rollback journal.  There are three levels:
33485**
33486**    OFF       sqlite3OsSync() is never called.  This is the default
33487**              for temporary and transient files.
33488**
33489**    NORMAL    The journal is synced once before writes begin on the
33490**              database.  This is normally adequate protection, but
33491**              it is theoretically possible, though very unlikely,
33492**              that an inopertune power failure could leave the journal
33493**              in a state which would cause damage to the database
33494**              when it is rolled back.
33495**
33496**    FULL      The journal is synced twice before writes begin on the
33497**              database (with some additional information - the nRec field
33498**              of the journal header - being written in between the two
33499**              syncs).  If we assume that writing a
33500**              single disk sector is atomic, then this mode provides
33501**              assurance that the journal will not be corrupted to the
33502**              point of causing damage to the database during rollback.
33503**
33504** Numeric values associated with these states are OFF==1, NORMAL=2,
33505** and FULL=3.
33506*/
33507#ifndef SQLITE_OMIT_PAGER_PRAGMAS
33508SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
33509  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
33510  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
33511  pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
33512  if( pPager->noSync ) pPager->needSync = 0;
33513}
33514#endif
33515
33516/*
33517** The following global variable is incremented whenever the library
33518** attempts to open a temporary file.  This information is used for
33519** testing and analysis only.
33520*/
33521#ifdef SQLITE_TEST
33522SQLITE_API int sqlite3_opentemp_count = 0;
33523#endif
33524
33525/*
33526** Open a temporary file.
33527**
33528** Write the file descriptor into *pFile. Return SQLITE_OK on success
33529** or some other error code if we fail. The OS will automatically
33530** delete the temporary file when it is closed.
33531**
33532** The flags passed to the VFS layer xOpen() call are those specified
33533** by parameter vfsFlags ORed with the following:
33534**
33535**     SQLITE_OPEN_READWRITE
33536**     SQLITE_OPEN_CREATE
33537**     SQLITE_OPEN_EXCLUSIVE
33538**     SQLITE_OPEN_DELETEONCLOSE
33539*/
33540static int pagerOpentemp(
33541  Pager *pPager,        /* The pager object */
33542  sqlite3_file *pFile,  /* Write the file descriptor here */
33543  int vfsFlags          /* Flags passed through to the VFS */
33544){
33545  int rc;               /* Return code */
33546
33547#ifdef SQLITE_TEST
33548  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
33549#endif
33550
33551  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
33552            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
33553  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
33554  assert( rc!=SQLITE_OK || isOpen(pFile) );
33555  return rc;
33556}
33557
33558/*
33559** Set the busy handler function.
33560**
33561** The pager invokes the busy-handler if sqlite3OsLock() returns
33562** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
33563** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
33564** lock. It does *not* invoke the busy handler when upgrading from
33565** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
33566** (which occurs during hot-journal rollback). Summary:
33567**
33568**   Transition                        | Invokes xBusyHandler
33569**   --------------------------------------------------------
33570**   NO_LOCK       -> SHARED_LOCK      | Yes
33571**   SHARED_LOCK   -> RESERVED_LOCK    | No
33572**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
33573**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
33574**
33575** If the busy-handler callback returns non-zero, the lock is
33576** retried. If it returns zero, then the SQLITE_BUSY error is
33577** returned to the caller of the pager API function.
33578*/
33579SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
33580  Pager *pPager,                       /* Pager object */
33581  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
33582  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
33583){
33584  pPager->xBusyHandler = xBusyHandler;
33585  pPager->pBusyHandlerArg = pBusyHandlerArg;
33586}
33587
33588/*
33589** Report the current page size and number of reserved bytes back
33590** to the codec.
33591*/
33592#ifdef SQLITE_HAS_CODEC
33593static void pagerReportSize(Pager *pPager){
33594  if( pPager->xCodecSizeChng ){
33595    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
33596                           (int)pPager->nReserve);
33597  }
33598}
33599#else
33600# define pagerReportSize(X)     /* No-op if we do not support a codec */
33601#endif
33602
33603/*
33604** Change the page size used by the Pager object. The new page size
33605** is passed in *pPageSize.
33606**
33607** If the pager is in the error state when this function is called, it
33608** is a no-op. The value returned is the error state error code (i.e.
33609** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL).
33610**
33611** Otherwise, if all of the following are true:
33612**
33613**   * the new page size (value of *pPageSize) is valid (a power
33614**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
33615**
33616**   * there are no outstanding page references, and
33617**
33618**   * the database is either not an in-memory database or it is
33619**     an in-memory database that currently consists of zero pages.
33620**
33621** then the pager object page size is set to *pPageSize.
33622**
33623** If the page size is changed, then this function uses sqlite3PagerMalloc()
33624** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
33625** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
33626** In all other cases, SQLITE_OK is returned.
33627**
33628** If the page size is not changed, either because one of the enumerated
33629** conditions above is not true, the pager was in error state when this
33630** function was called, or because the memory allocation attempt failed,
33631** then *pPageSize is set to the old, retained page size before returning.
33632*/
33633SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize, int nReserve){
33634  int rc = pPager->errCode;
33635
33636  if( rc==SQLITE_OK ){
33637    u16 pageSize = *pPageSize;
33638    assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
33639    if( (pPager->memDb==0 || pPager->dbSize==0)
33640     && sqlite3PcacheRefCount(pPager->pPCache)==0
33641     && pageSize && pageSize!=pPager->pageSize
33642    ){
33643      char *pNew = (char *)sqlite3PageMalloc(pageSize);
33644      if( !pNew ){
33645        rc = SQLITE_NOMEM;
33646      }else{
33647        pager_reset(pPager);
33648        pPager->pageSize = pageSize;
33649        sqlite3PageFree(pPager->pTmpSpace);
33650        pPager->pTmpSpace = pNew;
33651        sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
33652      }
33653    }
33654    *pPageSize = (u16)pPager->pageSize;
33655    if( nReserve<0 ) nReserve = pPager->nReserve;
33656    assert( nReserve>=0 && nReserve<1000 );
33657    pPager->nReserve = (i16)nReserve;
33658    pagerReportSize(pPager);
33659  }
33660  return rc;
33661}
33662
33663/*
33664** Return a pointer to the "temporary page" buffer held internally
33665** by the pager.  This is a buffer that is big enough to hold the
33666** entire content of a database page.  This buffer is used internally
33667** during rollback and will be overwritten whenever a rollback
33668** occurs.  But other modules are free to use it too, as long as
33669** no rollbacks are happening.
33670*/
33671SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
33672  return pPager->pTmpSpace;
33673}
33674
33675/*
33676** Attempt to set the maximum database page count if mxPage is positive.
33677** Make no changes if mxPage is zero or negative.  And never reduce the
33678** maximum page count below the current size of the database.
33679**
33680** Regardless of mxPage, return the current maximum page count.
33681*/
33682SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
33683  if( mxPage>0 ){
33684    pPager->mxPgno = mxPage;
33685  }
33686  sqlite3PagerPagecount(pPager, 0);
33687  return pPager->mxPgno;
33688}
33689
33690/*
33691** The following set of routines are used to disable the simulated
33692** I/O error mechanism.  These routines are used to avoid simulated
33693** errors in places where we do not care about errors.
33694**
33695** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
33696** and generate no code.
33697*/
33698#ifdef SQLITE_TEST
33699SQLITE_API extern int sqlite3_io_error_pending;
33700SQLITE_API extern int sqlite3_io_error_hit;
33701static int saved_cnt;
33702void disable_simulated_io_errors(void){
33703  saved_cnt = sqlite3_io_error_pending;
33704  sqlite3_io_error_pending = -1;
33705}
33706void enable_simulated_io_errors(void){
33707  sqlite3_io_error_pending = saved_cnt;
33708}
33709#else
33710# define disable_simulated_io_errors()
33711# define enable_simulated_io_errors()
33712#endif
33713
33714/*
33715** Read the first N bytes from the beginning of the file into memory
33716** that pDest points to.
33717**
33718** If the pager was opened on a transient file (zFilename==""), or
33719** opened on a file less than N bytes in size, the output buffer is
33720** zeroed and SQLITE_OK returned. The rationale for this is that this
33721** function is used to read database headers, and a new transient or
33722** zero sized database has a header than consists entirely of zeroes.
33723**
33724** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
33725** the error code is returned to the caller and the contents of the
33726** output buffer undefined.
33727*/
33728SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
33729  int rc = SQLITE_OK;
33730  memset(pDest, 0, N);
33731  assert( isOpen(pPager->fd) || pPager->tempFile );
33732  if( isOpen(pPager->fd) ){
33733    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
33734    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
33735    if( rc==SQLITE_IOERR_SHORT_READ ){
33736      rc = SQLITE_OK;
33737    }
33738  }
33739  return rc;
33740}
33741
33742/*
33743** Return the total number of pages in the database file associated
33744** with pPager. Normally, this is calculated as (<db file size>/<page-size>).
33745** However, if the file is between 1 and <page-size> bytes in size, then
33746** this is considered a 1 page file.
33747**
33748** If the pager is in error state when this function is called, then the
33749** error state error code is returned and *pnPage left unchanged. Or,
33750** if the file system has to be queried for the size of the file and
33751** the query attempt returns an IO error, the IO error code is returned
33752** and *pnPage is left unchanged.
33753**
33754** Otherwise, if everything is successful, then SQLITE_OK is returned
33755** and *pnPage is set to the number of pages in the database.
33756*/
33757SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
33758  Pgno nPage;               /* Value to return via *pnPage */
33759
33760  /* If the pager is already in the error state, return the error code. */
33761  if( pPager->errCode ){
33762    return pPager->errCode;
33763  }
33764
33765  /* Determine the number of pages in the file. Store this in nPage. */
33766  if( pPager->dbSizeValid ){
33767    nPage = pPager->dbSize;
33768  }else{
33769    int rc;                 /* Error returned by OsFileSize() */
33770    i64 n = 0;              /* File size in bytes returned by OsFileSize() */
33771
33772    assert( isOpen(pPager->fd) || pPager->tempFile );
33773    if( isOpen(pPager->fd) && (0 != (rc = sqlite3OsFileSize(pPager->fd, &n))) ){
33774      pager_error(pPager, rc);
33775      return rc;
33776    }
33777    if( n>0 && n<pPager->pageSize ){
33778      nPage = 1;
33779    }else{
33780      nPage = (Pgno)(n / pPager->pageSize);
33781    }
33782    if( pPager->state!=PAGER_UNLOCK ){
33783      pPager->dbSize = nPage;
33784      pPager->dbFileSize = nPage;
33785      pPager->dbSizeValid = 1;
33786    }
33787  }
33788
33789  /* If the current number of pages in the file is greater than the
33790  ** configured maximum pager number, increase the allowed limit so
33791  ** that the file can be read.
33792  */
33793  if( nPage>pPager->mxPgno ){
33794    pPager->mxPgno = (Pgno)nPage;
33795  }
33796
33797  /* Set the output variable and return SQLITE_OK */
33798  if( pnPage ){
33799    *pnPage = nPage;
33800  }
33801  return SQLITE_OK;
33802}
33803
33804
33805/*
33806** Try to obtain a lock of type locktype on the database file. If
33807** a similar or greater lock is already held, this function is a no-op
33808** (returning SQLITE_OK immediately).
33809**
33810** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
33811** the busy callback if the lock is currently not available. Repeat
33812** until the busy callback returns false or until the attempt to
33813** obtain the lock succeeds.
33814**
33815** Return SQLITE_OK on success and an error code if we cannot obtain
33816** the lock. If the lock is obtained successfully, set the Pager.state
33817** variable to locktype before returning.
33818*/
33819static int pager_wait_on_lock(Pager *pPager, int locktype){
33820  int rc;                              /* Return code */
33821
33822  /* The OS lock values must be the same as the Pager lock values */
33823  assert( PAGER_SHARED==SHARED_LOCK );
33824  assert( PAGER_RESERVED==RESERVED_LOCK );
33825  assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
33826
33827  /* If the file is currently unlocked then the size must be unknown. It
33828  ** must not have been modified at this point.
33829  */
33830  assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );
33831  assert( pPager->state>=PAGER_SHARED || pPager->dbModified==0 );
33832
33833  /* Check that this is either a no-op (because the requested lock is
33834  ** already held, or one of the transistions that the busy-handler
33835  ** may be invoked during, according to the comment above
33836  ** sqlite3PagerSetBusyhandler().
33837  */
33838  assert( (pPager->state>=locktype)
33839       || (pPager->state==PAGER_UNLOCK && locktype==PAGER_SHARED)
33840       || (pPager->state==PAGER_RESERVED && locktype==PAGER_EXCLUSIVE)
33841  );
33842
33843  if( pPager->state>=locktype ){
33844    rc = SQLITE_OK;
33845  }else{
33846    do {
33847      rc = sqlite3OsLock(pPager->fd, locktype);
33848    }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
33849    if( rc==SQLITE_OK ){
33850      pPager->state = (u8)locktype;
33851      IOTRACE(("LOCK %p %d\n", pPager, locktype))
33852    }
33853  }
33854  return rc;
33855}
33856
33857/*
33858** Function assertTruncateConstraint(pPager) checks that one of the
33859** following is true for all dirty pages currently in the page-cache:
33860**
33861**   a) The page number is less than or equal to the size of the
33862**      current database image, in pages, OR
33863**
33864**   b) if the page content were written at this time, it would not
33865**      be necessary to write the current content out to the sub-journal
33866**      (as determined by function subjRequiresPage()).
33867**
33868** If the condition asserted by this function were not true, and the
33869** dirty page were to be discarded from the cache via the pagerStress()
33870** routine, pagerStress() would not write the current page content to
33871** the database file. If a savepoint transaction were rolled back after
33872** this happened, the correct behaviour would be to restore the current
33873** content of the page. However, since this content is not present in either
33874** the database file or the portion of the rollback journal and
33875** sub-journal rolled back the content could not be restored and the
33876** database image would become corrupt. It is therefore fortunate that
33877** this circumstance cannot arise.
33878*/
33879#if defined(SQLITE_DEBUG)
33880static void assertTruncateConstraintCb(PgHdr *pPg){
33881  assert( pPg->flags&PGHDR_DIRTY );
33882  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
33883}
33884static void assertTruncateConstraint(Pager *pPager){
33885  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
33886}
33887#else
33888# define assertTruncateConstraint(pPager)
33889#endif
33890
33891/*
33892** Truncate the in-memory database file image to nPage pages. This
33893** function does not actually modify the database file on disk. It
33894** just sets the internal state of the pager object so that the
33895** truncation will be done when the current transaction is committed.
33896*/
33897SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
33898  assert( pPager->dbSizeValid );
33899  assert( pPager->dbSize>=nPage );
33900  assert( pPager->state>=PAGER_RESERVED );
33901  pPager->dbSize = nPage;
33902  assertTruncateConstraint(pPager);
33903}
33904
33905/*
33906** Shutdown the page cache.  Free all memory and close all files.
33907**
33908** If a transaction was in progress when this routine is called, that
33909** transaction is rolled back.  All outstanding pages are invalidated
33910** and their memory is freed.  Any attempt to use a page associated
33911** with this page cache after this function returns will likely
33912** result in a coredump.
33913**
33914** This function always succeeds. If a transaction is active an attempt
33915** is made to roll it back. If an error occurs during the rollback
33916** a hot journal may be left in the filesystem but no error is returned
33917** to the caller.
33918*/
33919SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
33920  disable_simulated_io_errors();
33921  sqlite3BeginBenignMalloc();
33922  pPager->errCode = 0;
33923  pPager->exclusiveMode = 0;
33924  pager_reset(pPager);
33925  if( MEMDB ){
33926    pager_unlock(pPager);
33927  }else{
33928    /* Set Pager.journalHdr to -1 for the benefit of the pager_playback()
33929    ** call which may be made from within pagerUnlockAndRollback(). If it
33930    ** is not -1, then the unsynced portion of an open journal file may
33931    ** be played back into the database. If a power failure occurs while
33932    ** this is happening, the database may become corrupt.
33933    */
33934    pPager->journalHdr = -1;
33935    pagerUnlockAndRollback(pPager);
33936  }
33937  sqlite3EndBenignMalloc();
33938  enable_simulated_io_errors();
33939  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
33940  IOTRACE(("CLOSE %p\n", pPager))
33941  sqlite3OsClose(pPager->fd);
33942  sqlite3PageFree(pPager->pTmpSpace);
33943  sqlite3PcacheClose(pPager->pPCache);
33944
33945#ifdef SQLITE_HAS_CODEC
33946  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
33947#endif
33948
33949  assert( !pPager->aSavepoint && !pPager->pInJournal );
33950  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
33951
33952  sqlite3_free(pPager);
33953  return SQLITE_OK;
33954}
33955
33956#if !defined(NDEBUG) || defined(SQLITE_TEST)
33957/*
33958** Return the page number for page pPg.
33959*/
33960SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
33961  return pPg->pgno;
33962}
33963#endif
33964
33965/*
33966** Increment the reference count for page pPg.
33967*/
33968SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
33969  sqlite3PcacheRef(pPg);
33970}
33971
33972/*
33973** Sync the journal. In other words, make sure all the pages that have
33974** been written to the journal have actually reached the surface of the
33975** disk and can be restored in the event of a hot-journal rollback.
33976**
33977** If the Pager.needSync flag is not set, then this function is a
33978** no-op. Otherwise, the actions required depend on the journal-mode
33979** and the device characteristics of the the file-system, as follows:
33980**
33981**   * If the journal file is an in-memory journal file, no action need
33982**     be taken.
33983**
33984**   * Otherwise, if the device does not support the SAFE_APPEND property,
33985**     then the nRec field of the most recently written journal header
33986**     is updated to contain the number of journal records that have
33987**     been written following it. If the pager is operating in full-sync
33988**     mode, then the journal file is synced before this field is updated.
33989**
33990**   * If the device does not support the SEQUENTIAL property, then
33991**     journal file is synced.
33992**
33993** Or, in pseudo-code:
33994**
33995**   if( NOT <in-memory journal> ){
33996**     if( NOT SAFE_APPEND ){
33997**       if( <full-sync mode> ) xSync(<journal file>);
33998**       <update nRec field>
33999**     }
34000**     if( NOT SEQUENTIAL ) xSync(<journal file>);
34001**   }
34002**
34003** The Pager.needSync flag is never be set for temporary files, or any
34004** file operating in no-sync mode (Pager.noSync set to non-zero).
34005**
34006** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
34007** page currently held in memory before returning SQLITE_OK. If an IO
34008** error is encountered, then the IO error code is returned to the caller.
34009*/
34010static int syncJournal(Pager *pPager){
34011  if( pPager->needSync ){
34012    assert( !pPager->tempFile );
34013    if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
34014      int rc;                              /* Return code */
34015      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
34016      assert( isOpen(pPager->jfd) );
34017
34018      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
34019        /* This block deals with an obscure problem. If the last connection
34020        ** that wrote to this database was operating in persistent-journal
34021        ** mode, then the journal file may at this point actually be larger
34022        ** than Pager.journalOff bytes. If the next thing in the journal
34023        ** file happens to be a journal-header (written as part of the
34024        ** previous connections transaction), and a crash or power-failure
34025        ** occurs after nRec is updated but before this connection writes
34026        ** anything else to the journal file (or commits/rolls back its
34027        ** transaction), then SQLite may become confused when doing the
34028        ** hot-journal rollback following recovery. It may roll back all
34029        ** of this connections data, then proceed to rolling back the old,
34030        ** out-of-date data that follows it. Database corruption.
34031        **
34032        ** To work around this, if the journal file does appear to contain
34033        ** a valid header following Pager.journalOff, then write a 0x00
34034        ** byte to the start of it to prevent it from being recognized.
34035        **
34036        ** Variable iNextHdrOffset is set to the offset at which this
34037        ** problematic header will occur, if it exists. aMagic is used
34038        ** as a temporary buffer to inspect the first couple of bytes of
34039        ** the potential journal header.
34040        */
34041        i64 iNextHdrOffset;
34042        u8 aMagic[8];
34043	u8 zHeader[sizeof(aJournalMagic)+4];
34044
34045	memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
34046	put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
34047
34048        iNextHdrOffset = journalHdrOffset(pPager);
34049        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
34050        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
34051          static const u8 zerobyte = 0;
34052          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
34053        }
34054        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
34055          return rc;
34056        }
34057
34058        /* Write the nRec value into the journal file header. If in
34059        ** full-synchronous mode, sync the journal first. This ensures that
34060        ** all data has really hit the disk before nRec is updated to mark
34061        ** it as a candidate for rollback.
34062        **
34063        ** This is not required if the persistent media supports the
34064        ** SAFE_APPEND property. Because in this case it is not possible
34065        ** for garbage data to be appended to the file, the nRec field
34066        ** is populated with 0xFFFFFFFF when the journal header is written
34067        ** and never needs to be updated.
34068        */
34069        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
34070          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
34071          IOTRACE(("JSYNC %p\n", pPager))
34072          rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
34073          if( rc!=SQLITE_OK ) return rc;
34074        }
34075        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
34076        rc = sqlite3OsWrite(
34077            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
34078	);
34079        if( rc!=SQLITE_OK ) return rc;
34080      }
34081      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
34082        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
34083        IOTRACE(("JSYNC %p\n", pPager))
34084        rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags|
34085          (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
34086        );
34087        if( rc!=SQLITE_OK ) return rc;
34088      }
34089    }
34090
34091    /* The journal file was just successfully synced. Set Pager.needSync
34092    ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess.
34093    */
34094    pPager->needSync = 0;
34095    pPager->journalStarted = 1;
34096    sqlite3PcacheClearSyncFlags(pPager->pPCache);
34097  }
34098
34099  return SQLITE_OK;
34100}
34101
34102/*
34103** The argument is the first in a linked list of dirty pages connected
34104** by the PgHdr.pDirty pointer. This function writes each one of the
34105** in-memory pages in the list to the database file. The argument may
34106** be NULL, representing an empty list. In this case this function is
34107** a no-op.
34108**
34109** The pager must hold at least a RESERVED lock when this function
34110** is called. Before writing anything to the database file, this lock
34111** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
34112** SQLITE_BUSY is returned and no data is written to the database file.
34113**
34114** If the pager is a temp-file pager and the actual file-system file
34115** is not yet open, it is created and opened before any data is
34116** written out.
34117**
34118** Once the lock has been upgraded and, if necessary, the file opened,
34119** the pages are written out to the database file in list order. Writing
34120** a page is skipped if it meets either of the following criteria:
34121**
34122**   * The page number is greater than Pager.dbSize, or
34123**   * The PGHDR_DONT_WRITE flag is set on the page.
34124**
34125** If writing out a page causes the database file to grow, Pager.dbFileSize
34126** is updated accordingly. If page 1 is written out, then the value cached
34127** in Pager.dbFileVers[] is updated to match the new value stored in
34128** the database file.
34129**
34130** If everything is successful, SQLITE_OK is returned. If an IO error
34131** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
34132** be obtained, SQLITE_BUSY is returned.
34133*/
34134static int pager_write_pagelist(PgHdr *pList){
34135  Pager *pPager;                       /* Pager object */
34136  int rc;                              /* Return code */
34137
34138  if( NEVER(pList==0) ) return SQLITE_OK;
34139  pPager = pList->pPager;
34140
34141  /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
34142  ** database file. If there is already an EXCLUSIVE lock, the following
34143  ** call is a no-op.
34144  **
34145  ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
34146  ** through an intermediate state PENDING.   A PENDING lock prevents new
34147  ** readers from attaching to the database but is unsufficient for us to
34148  ** write.  The idea of a PENDING lock is to prevent new readers from
34149  ** coming in while we wait for existing readers to clear.
34150  **
34151  ** While the pager is in the RESERVED state, the original database file
34152  ** is unchanged and we can rollback without having to playback the
34153  ** journal into the original database file.  Once we transition to
34154  ** EXCLUSIVE, it means the database file has been changed and any rollback
34155  ** will require a journal playback.
34156  */
34157  assert( pPager->state>=PAGER_RESERVED );
34158  rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
34159
34160  /* If the file is a temp-file has not yet been opened, open it now. It
34161  ** is not possible for rc to be other than SQLITE_OK if this branch
34162  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
34163  */
34164  if( !isOpen(pPager->fd) ){
34165    assert( pPager->tempFile && rc==SQLITE_OK );
34166    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
34167  }
34168
34169  while( rc==SQLITE_OK && pList ){
34170    Pgno pgno = pList->pgno;
34171
34172    /* If there are dirty pages in the page cache with page numbers greater
34173    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
34174    ** make the file smaller (presumably by auto-vacuum code). Do not write
34175    ** any such pages to the file.
34176    **
34177    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
34178    ** set (set by sqlite3PagerDontWrite()).  Note that if compiled with
34179    ** SQLITE_SECURE_DELETE the PGHDR_DONT_WRITE bit is never set and so
34180    ** the second test is always true.
34181    */
34182    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
34183      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
34184      char *pData;                                   /* Data to write */
34185
34186      /* Encode the database */
34187      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
34188
34189      /* Write out the page data. */
34190      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
34191
34192      /* If page 1 was just written, update Pager.dbFileVers to match
34193      ** the value now stored in the database file. If writing this
34194      ** page caused the database file to grow, update dbFileSize.
34195      */
34196      if( pgno==1 ){
34197        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
34198      }
34199      if( pgno>pPager->dbFileSize ){
34200        pPager->dbFileSize = pgno;
34201      }
34202
34203      /* Update any backup objects copying the contents of this pager. */
34204      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
34205
34206      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
34207                   PAGERID(pPager), pgno, pager_pagehash(pList)));
34208      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
34209      PAGER_INCR(sqlite3_pager_writedb_count);
34210      PAGER_INCR(pPager->nWrite);
34211    }else{
34212      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
34213    }
34214#ifdef SQLITE_CHECK_PAGES
34215    pList->pageHash = pager_pagehash(pList);
34216#endif
34217    pList = pList->pDirty;
34218  }
34219
34220  return rc;
34221}
34222
34223/*
34224** Append a record of the current state of page pPg to the sub-journal.
34225** It is the callers responsibility to use subjRequiresPage() to check
34226** that it is really required before calling this function.
34227**
34228** If successful, set the bit corresponding to pPg->pgno in the bitvecs
34229** for all open savepoints before returning.
34230**
34231** This function returns SQLITE_OK if everything is successful, an IO
34232** error code if the attempt to write to the sub-journal fails, or
34233** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
34234** bitvec.
34235*/
34236static int subjournalPage(PgHdr *pPg){
34237  int rc = SQLITE_OK;
34238  Pager *pPager = pPg->pPager;
34239  if( isOpen(pPager->sjfd) ){
34240    void *pData = pPg->pData;
34241    i64 offset = pPager->nSubRec*(4+pPager->pageSize);
34242    char *pData2;
34243
34244    CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
34245    PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
34246
34247    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
34248    rc = write32bits(pPager->sjfd, offset, pPg->pgno);
34249    if( rc==SQLITE_OK ){
34250      rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
34251    }
34252  }
34253  if( rc==SQLITE_OK ){
34254    pPager->nSubRec++;
34255    assert( pPager->nSavepoint>0 );
34256    rc = addToSavepointBitvecs(pPager, pPg->pgno);
34257  }
34258  return rc;
34259}
34260
34261
34262/*
34263** This function is called by the pcache layer when it has reached some
34264** soft memory limit. The first argument is a pointer to a Pager object
34265** (cast as a void*). The pager is always 'purgeable' (not an in-memory
34266** database). The second argument is a reference to a page that is
34267** currently dirty but has no outstanding references. The page
34268** is always associated with the Pager object passed as the first
34269** argument.
34270**
34271** The job of this function is to make pPg clean by writing its contents
34272** out to the database file, if possible. This may involve syncing the
34273** journal file.
34274**
34275** If successful, sqlite3PcacheMakeClean() is called on the page and
34276** SQLITE_OK returned. If an IO error occurs while trying to make the
34277** page clean, the IO error code is returned. If the page cannot be
34278** made clean for some other reason, but no error occurs, then SQLITE_OK
34279** is returned by sqlite3PcacheMakeClean() is not called.
34280*/
34281static int pagerStress(void *p, PgHdr *pPg){
34282  Pager *pPager = (Pager *)p;
34283  int rc = SQLITE_OK;
34284
34285  assert( pPg->pPager==pPager );
34286  assert( pPg->flags&PGHDR_DIRTY );
34287
34288  /* The doNotSync flag is set by the sqlite3PagerWrite() function while it
34289  ** is journalling a set of two or more database pages that are stored
34290  ** on the same disk sector. Syncing the journal is not allowed while
34291  ** this is happening as it is important that all members of such a
34292  ** set of pages are synced to disk together. So, if the page this function
34293  ** is trying to make clean will require a journal sync and the doNotSync
34294  ** flag is set, return without doing anything. The pcache layer will
34295  ** just have to go ahead and allocate a new page buffer instead of
34296  ** reusing pPg.
34297  **
34298  ** Similarly, if the pager has already entered the error state, do not
34299  ** try to write the contents of pPg to disk.
34300  */
34301  if( NEVER(pPager->errCode)
34302   || (pPager->doNotSync && pPg->flags&PGHDR_NEED_SYNC)
34303  ){
34304    return SQLITE_OK;
34305  }
34306
34307  /* Sync the journal file if required. */
34308  if( pPg->flags&PGHDR_NEED_SYNC ){
34309    rc = syncJournal(pPager);
34310    if( rc==SQLITE_OK && pPager->fullSync &&
34311      !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
34312      !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
34313    ){
34314      pPager->nRec = 0;
34315      rc = writeJournalHdr(pPager);
34316    }
34317  }
34318
34319  /* If the page number of this page is larger than the current size of
34320  ** the database image, it may need to be written to the sub-journal.
34321  ** This is because the call to pager_write_pagelist() below will not
34322  ** actually write data to the file in this case.
34323  **
34324  ** Consider the following sequence of events:
34325  **
34326  **   BEGIN;
34327  **     <journal page X>
34328  **     <modify page X>
34329  **     SAVEPOINT sp;
34330  **       <shrink database file to Y pages>
34331  **       pagerStress(page X)
34332  **     ROLLBACK TO sp;
34333  **
34334  ** If (X>Y), then when pagerStress is called page X will not be written
34335  ** out to the database file, but will be dropped from the cache. Then,
34336  ** following the "ROLLBACK TO sp" statement, reading page X will read
34337  ** data from the database file. This will be the copy of page X as it
34338  ** was when the transaction started, not as it was when "SAVEPOINT sp"
34339  ** was executed.
34340  **
34341  ** The solution is to write the current data for page X into the
34342  ** sub-journal file now (if it is not already there), so that it will
34343  ** be restored to its current value when the "ROLLBACK TO sp" is
34344  ** executed.
34345  */
34346  if( NEVER(
34347      rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
34348  ) ){
34349    rc = subjournalPage(pPg);
34350  }
34351
34352  /* Write the contents of the page out to the database file. */
34353  if( rc==SQLITE_OK ){
34354    pPg->pDirty = 0;
34355    rc = pager_write_pagelist(pPg);
34356  }
34357
34358  /* Mark the page as clean. */
34359  if( rc==SQLITE_OK ){
34360    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
34361    sqlite3PcacheMakeClean(pPg);
34362  }
34363
34364  return pager_error(pPager, rc);
34365}
34366
34367
34368/*
34369** Allocate and initialize a new Pager object and put a pointer to it
34370** in *ppPager. The pager should eventually be freed by passing it
34371** to sqlite3PagerClose().
34372**
34373** The zFilename argument is the path to the database file to open.
34374** If zFilename is NULL then a randomly-named temporary file is created
34375** and used as the file to be cached. Temporary files are be deleted
34376** automatically when they are closed. If zFilename is ":memory:" then
34377** all information is held in cache. It is never written to disk.
34378** This can be used to implement an in-memory database.
34379**
34380** The nExtra parameter specifies the number of bytes of space allocated
34381** along with each page reference. This space is available to the user
34382** via the sqlite3PagerGetExtra() API.
34383**
34384** The flags argument is used to specify properties that affect the
34385** operation of the pager. It should be passed some bitwise combination
34386** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
34387**
34388** The vfsFlags parameter is a bitmask to pass to the flags parameter
34389** of the xOpen() method of the supplied VFS when opening files.
34390**
34391** If the pager object is allocated and the specified file opened
34392** successfully, SQLITE_OK is returned and *ppPager set to point to
34393** the new pager object. If an error occurs, *ppPager is set to NULL
34394** and error code returned. This function may return SQLITE_NOMEM
34395** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
34396** various SQLITE_IO_XXX errors.
34397*/
34398SQLITE_PRIVATE int sqlite3PagerOpen(
34399  sqlite3_vfs *pVfs,       /* The virtual file system to use */
34400  Pager **ppPager,         /* OUT: Return the Pager structure here */
34401  const char *zFilename,   /* Name of the database file to open */
34402  int nExtra,              /* Extra bytes append to each in-memory page */
34403  int flags,               /* flags controlling this file */
34404  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
34405  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
34406){
34407  u8 *pPtr;
34408  Pager *pPager = 0;       /* Pager object to allocate and return */
34409  int rc = SQLITE_OK;      /* Return code */
34410  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
34411  int memDb = 0;           /* True if this is an in-memory file */
34412  int readOnly = 0;        /* True if this is a read-only file */
34413  int journalFileSize;     /* Bytes to allocate for each journal fd */
34414  char *zPathname = 0;     /* Full path to database file */
34415  int nPathname = 0;       /* Number of bytes in zPathname */
34416  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
34417  int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
34418  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
34419  u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
34420
34421  /* Figure out how much space is required for each journal file-handle
34422  ** (there are two of them, the main journal and the sub-journal). This
34423  ** is the maximum space required for an in-memory journal file handle
34424  ** and a regular journal file-handle. Note that a "regular journal-handle"
34425  ** may be a wrapper capable of caching the first portion of the journal
34426  ** file in memory to implement the atomic-write optimization (see
34427  ** source file journal.c).
34428  */
34429  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
34430    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
34431  }else{
34432    journalFileSize = ROUND8(sqlite3MemJournalSize());
34433  }
34434
34435  /* Set the output variable to NULL in case an error occurs. */
34436  *ppPager = 0;
34437
34438  /* Compute and store the full pathname in an allocated buffer pointed
34439  ** to by zPathname, length nPathname. Or, if this is a temporary file,
34440  ** leave both nPathname and zPathname set to 0.
34441  */
34442  if( zFilename && zFilename[0] ){
34443    nPathname = pVfs->mxPathname+1;
34444    zPathname = sqlite3Malloc(nPathname*2);
34445    if( zPathname==0 ){
34446      return SQLITE_NOMEM;
34447    }
34448#ifndef SQLITE_OMIT_MEMORYDB
34449    if( strcmp(zFilename,":memory:")==0 ){
34450      memDb = 1;
34451      zPathname[0] = 0;
34452    }else
34453#endif
34454    {
34455      zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
34456      rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
34457    }
34458
34459    nPathname = sqlite3Strlen30(zPathname);
34460    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
34461      /* This branch is taken when the journal path required by
34462      ** the database being opened will be more than pVfs->mxPathname
34463      ** bytes in length. This means the database cannot be opened,
34464      ** as it will not be possible to open the journal file or even
34465      ** check for a hot-journal before reading.
34466      */
34467      rc = SQLITE_CANTOPEN;
34468    }
34469    if( rc!=SQLITE_OK ){
34470      sqlite3_free(zPathname);
34471      return rc;
34472    }
34473  }
34474
34475  /* Allocate memory for the Pager structure, PCache object, the
34476  ** three file descriptors, the database file name and the journal
34477  ** file name. The layout in memory is as follows:
34478  **
34479  **     Pager object                    (sizeof(Pager) bytes)
34480  **     PCache object                   (sqlite3PcacheSize() bytes)
34481  **     Database file handle            (pVfs->szOsFile bytes)
34482  **     Sub-journal file handle         (journalFileSize bytes)
34483  **     Main journal file handle        (journalFileSize bytes)
34484  **     Database file name              (nPathname+1 bytes)
34485  **     Journal file name               (nPathname+8+1 bytes)
34486  */
34487  pPtr = (u8 *)sqlite3MallocZero(
34488    ROUND8(sizeof(*pPager)) +      /* Pager structure */
34489    ROUND8(pcacheSize) +           /* PCache object */
34490    ROUND8(pVfs->szOsFile) +       /* The main db file */
34491    journalFileSize * 2 +          /* The two journal files */
34492    nPathname + 1 +                /* zFilename */
34493    nPathname + 8 + 1              /* zJournal */
34494  );
34495  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
34496  if( !pPtr ){
34497    sqlite3_free(zPathname);
34498    return SQLITE_NOMEM;
34499  }
34500  pPager =              (Pager*)(pPtr);
34501  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
34502  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
34503  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
34504  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
34505  pPager->zFilename =    (char*)(pPtr += journalFileSize);
34506  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
34507
34508  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
34509  if( zPathname ){
34510    pPager->zJournal =   (char*)(pPtr += nPathname + 1);
34511    memcpy(pPager->zFilename, zPathname, nPathname);
34512    memcpy(pPager->zJournal, zPathname, nPathname);
34513    memcpy(&pPager->zJournal[nPathname], "-journal", 8);
34514    if( pPager->zFilename[0]==0 ) pPager->zJournal[0] = 0;
34515    sqlite3_free(zPathname);
34516  }
34517  pPager->pVfs = pVfs;
34518  pPager->vfsFlags = vfsFlags;
34519
34520  /* Open the pager file.
34521  */
34522  if( zFilename && zFilename[0] && !memDb ){
34523    int fout = 0;                    /* VFS flags returned by xOpen() */
34524    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
34525    readOnly = (fout&SQLITE_OPEN_READONLY);
34526
34527    /* If the file was successfully opened for read/write access,
34528    ** choose a default page size in case we have to create the
34529    ** database file. The default page size is the maximum of:
34530    **
34531    **    + SQLITE_DEFAULT_PAGE_SIZE,
34532    **    + The value returned by sqlite3OsSectorSize()
34533    **    + The largest page size that can be written atomically.
34534    */
34535    if( rc==SQLITE_OK && !readOnly ){
34536      setSectorSize(pPager);
34537      assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
34538      if( szPageDflt<pPager->sectorSize ){
34539        if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
34540          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
34541        }else{
34542          szPageDflt = (u16)pPager->sectorSize;
34543        }
34544      }
34545#ifdef SQLITE_ENABLE_ATOMIC_WRITE
34546      {
34547        int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
34548        int ii;
34549        assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
34550        assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
34551        assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
34552        for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
34553          if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
34554            szPageDflt = ii;
34555          }
34556        }
34557      }
34558#endif
34559    }
34560  }else{
34561    /* If a temporary file is requested, it is not opened immediately.
34562    ** In this case we accept the default page size and delay actually
34563    ** opening the file until the first call to OsWrite().
34564    **
34565    ** This branch is also run for an in-memory database. An in-memory
34566    ** database is the same as a temp-file that is never written out to
34567    ** disk and uses an in-memory rollback journal.
34568    */
34569    tempFile = 1;
34570    pPager->state = PAGER_EXCLUSIVE;
34571    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
34572  }
34573
34574  /* The following call to PagerSetPagesize() serves to set the value of
34575  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
34576  */
34577  if( rc==SQLITE_OK ){
34578    assert( pPager->memDb==0 );
34579    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
34580    testcase( rc!=SQLITE_OK );
34581  }
34582
34583  /* If an error occurred in either of the blocks above, free the
34584  ** Pager structure and close the file.
34585  */
34586  if( rc!=SQLITE_OK ){
34587    assert( !pPager->pTmpSpace );
34588    sqlite3OsClose(pPager->fd);
34589    sqlite3_free(pPager);
34590    return rc;
34591  }
34592
34593  /* Initialize the PCache object. */
34594  assert( nExtra<1000 );
34595  nExtra = ROUND8(nExtra);
34596  sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
34597                    !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
34598
34599  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
34600  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
34601
34602  pPager->useJournal = (u8)useJournal;
34603  pPager->noReadlock = (noReadlock && readOnly) ?1:0;
34604  /* pPager->stmtOpen = 0; */
34605  /* pPager->stmtInUse = 0; */
34606  /* pPager->nRef = 0; */
34607  pPager->dbSizeValid = (u8)memDb;
34608  /* pPager->stmtSize = 0; */
34609  /* pPager->stmtJSize = 0; */
34610  /* pPager->nPage = 0; */
34611  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
34612  /* pPager->state = PAGER_UNLOCK; */
34613  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
34614  /* pPager->errMask = 0; */
34615  pPager->tempFile = (u8)tempFile;
34616  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
34617          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
34618  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
34619  pPager->exclusiveMode = (u8)tempFile;
34620  pPager->changeCountDone = pPager->tempFile;
34621  pPager->memDb = (u8)memDb;
34622  pPager->readOnly = (u8)readOnly;
34623  /* pPager->needSync = 0; */
34624  assert( useJournal || pPager->tempFile );
34625  pPager->noSync = pPager->tempFile;
34626  pPager->fullSync = pPager->noSync ?0:1;
34627  pPager->sync_flags = SQLITE_SYNC_NORMAL;
34628  /* pPager->pFirst = 0; */
34629  /* pPager->pFirstSynced = 0; */
34630  /* pPager->pLast = 0; */
34631  pPager->nExtra = (u16)nExtra;
34632  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
34633  assert( isOpen(pPager->fd) || tempFile );
34634  setSectorSize(pPager);
34635  if( !useJournal ){
34636    pPager->journalMode = PAGER_JOURNALMODE_OFF;
34637  }else if( memDb ){
34638    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
34639  }
34640  /* pPager->xBusyHandler = 0; */
34641  /* pPager->pBusyHandlerArg = 0; */
34642  pPager->xReiniter = xReinit;
34643  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
34644  *ppPager = pPager;
34645  return SQLITE_OK;
34646}
34647
34648
34649
34650/*
34651** This function is called after transitioning from PAGER_UNLOCK to
34652** PAGER_SHARED state. It tests if there is a hot journal present in
34653** the file-system for the given pager. A hot journal is one that
34654** needs to be played back. According to this function, a hot-journal
34655** file exists if the following criteria are met:
34656**
34657**   * The journal file exists in the file system, and
34658**   * No process holds a RESERVED or greater lock on the database file, and
34659**   * The database file itself is greater than 0 bytes in size, and
34660**   * The first byte of the journal file exists and is not 0x00.
34661**
34662** If the current size of the database file is 0 but a journal file
34663** exists, that is probably an old journal left over from a prior
34664** database with the same name. In this case the journal file is
34665** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
34666** is returned.
34667**
34668** This routine does not check if there is a master journal filename
34669** at the end of the file. If there is, and that master journal file
34670** does not exist, then the journal file is not really hot. In this
34671** case this routine will return a false-positive. The pager_playback()
34672** routine will discover that the journal file is not really hot and
34673** will not roll it back.
34674**
34675** If a hot-journal file is found to exist, *pExists is set to 1 and
34676** SQLITE_OK returned. If no hot-journal file is present, *pExists is
34677** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
34678** to determine whether or not a hot-journal file exists, the IO error
34679** code is returned and the value of *pExists is undefined.
34680*/
34681static int hasHotJournal(Pager *pPager, int *pExists){
34682  sqlite3_vfs * const pVfs = pPager->pVfs;
34683  int rc;                       /* Return code */
34684  int exists;                   /* True if a journal file is present */
34685
34686  assert( pPager!=0 );
34687  assert( pPager->useJournal );
34688  assert( isOpen(pPager->fd) );
34689  assert( !isOpen(pPager->jfd) );
34690  assert( pPager->state <= PAGER_SHARED );
34691
34692  *pExists = 0;
34693  rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
34694  if( rc==SQLITE_OK && exists ){
34695    int locked;                 /* True if some process holds a RESERVED lock */
34696
34697    /* Race condition here:  Another process might have been holding the
34698    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
34699    ** call above, but then delete the journal and drop the lock before
34700    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
34701    ** is the case, this routine might think there is a hot journal when
34702    ** in fact there is none.  This results in a false-positive which will
34703    ** be dealt with by the playback routine.  Ticket #3883.
34704    */
34705    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
34706    if( rc==SQLITE_OK && !locked ){
34707      int nPage;
34708
34709      /* Check the size of the database file. If it consists of 0 pages,
34710      ** then delete the journal file. See the header comment above for
34711      ** the reasoning here.  Delete the obsolete journal file under
34712      ** a RESERVED lock to avoid race conditions and to avoid violating
34713      ** [H33020].
34714      */
34715      rc = sqlite3PagerPagecount(pPager, &nPage);
34716      if( rc==SQLITE_OK ){
34717        if( nPage==0 ){
34718          sqlite3BeginBenignMalloc();
34719          if( sqlite3OsLock(pPager->fd, RESERVED_LOCK)==SQLITE_OK ){
34720            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
34721            sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
34722          }
34723          sqlite3EndBenignMalloc();
34724        }else{
34725          /* The journal file exists and no other connection has a reserved
34726          ** or greater lock on the database file. Now check that there is
34727          ** at least one non-zero bytes at the start of the journal file.
34728          ** If there is, then we consider this journal to be hot. If not,
34729          ** it can be ignored.
34730          */
34731          int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
34732          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
34733          if( rc==SQLITE_OK ){
34734            u8 first = 0;
34735            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
34736            if( rc==SQLITE_IOERR_SHORT_READ ){
34737              rc = SQLITE_OK;
34738            }
34739            sqlite3OsClose(pPager->jfd);
34740            *pExists = (first!=0);
34741          }else if( rc==SQLITE_CANTOPEN ){
34742            /* If we cannot open the rollback journal file in order to see if
34743            ** its has a zero header, that might be due to an I/O error, or
34744            ** it might be due to the race condition described above and in
34745            ** ticket #3883.  Either way, assume that the journal is hot.
34746            ** This might be a false positive.  But if it is, then the
34747            ** automatic journal playback and recovery mechanism will deal
34748            ** with it under an EXCLUSIVE lock where we do not need to
34749            ** worry so much with race conditions.
34750            */
34751            *pExists = 1;
34752            rc = SQLITE_OK;
34753          }
34754        }
34755      }
34756    }
34757  }
34758
34759  return rc;
34760}
34761
34762/*
34763** Read the content for page pPg out of the database file and into
34764** pPg->pData. A shared lock or greater must be held on the database
34765** file before this function is called.
34766**
34767** If page 1 is read, then the value of Pager.dbFileVers[] is set to
34768** the value read from the database file.
34769**
34770** If an IO error occurs, then the IO error is returned to the caller.
34771** Otherwise, SQLITE_OK is returned.
34772*/
34773static int readDbPage(PgHdr *pPg){
34774  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
34775  Pgno pgno = pPg->pgno;       /* Page number to read */
34776  int rc;                      /* Return code */
34777  i64 iOffset;                 /* Byte offset of file to read from */
34778
34779  assert( pPager->state>=PAGER_SHARED && !MEMDB );
34780  assert( isOpen(pPager->fd) );
34781
34782  if( NEVER(!isOpen(pPager->fd)) ){
34783    assert( pPager->tempFile );
34784    memset(pPg->pData, 0, pPager->pageSize);
34785    return SQLITE_OK;
34786  }
34787  iOffset = (pgno-1)*(i64)pPager->pageSize;
34788  rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
34789  if( rc==SQLITE_IOERR_SHORT_READ ){
34790    rc = SQLITE_OK;
34791  }
34792  if( pgno==1 ){
34793    u8 *dbFileVers = &((u8*)pPg->pData)[24];
34794    memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
34795  }
34796  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
34797
34798  PAGER_INCR(sqlite3_pager_readdb_count);
34799  PAGER_INCR(pPager->nRead);
34800  IOTRACE(("PGIN %p %d\n", pPager, pgno));
34801  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
34802               PAGERID(pPager), pgno, pager_pagehash(pPg)));
34803
34804  return rc;
34805}
34806
34807/*
34808** This function is called to obtain a shared lock on the database file.
34809** It is illegal to call sqlite3PagerAcquire() until after this function
34810** has been successfully called. If a shared-lock is already held when
34811** this function is called, it is a no-op.
34812**
34813** The following operations are also performed by this function.
34814**
34815**   1) If the pager is currently in PAGER_UNLOCK state (no lock held
34816**      on the database file), then an attempt is made to obtain a
34817**      SHARED lock on the database file. Immediately after obtaining
34818**      the SHARED lock, the file-system is checked for a hot-journal,
34819**      which is played back if present. Following any hot-journal
34820**      rollback, the contents of the cache are validated by checking
34821**      the 'change-counter' field of the database file header and
34822**      discarded if they are found to be invalid.
34823**
34824**   2) If the pager is running in exclusive-mode, and there are currently
34825**      no outstanding references to any pages, and is in the error state,
34826**      then an attempt is made to clear the error state by discarding
34827**      the contents of the page cache and rolling back any open journal
34828**      file.
34829**
34830** If the operation described by (2) above is not attempted, and if the
34831** pager is in an error state other than SQLITE_FULL when this is called,
34832** the error state error code is returned. It is permitted to read the
34833** database when in SQLITE_FULL error state.
34834**
34835** Otherwise, if everything is successful, SQLITE_OK is returned. If an
34836** IO error occurs while locking the database, checking for a hot-journal
34837** file or rolling back a journal file, the IO error code is returned.
34838*/
34839SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
34840  int rc = SQLITE_OK;                /* Return code */
34841  int isErrorReset = 0;              /* True if recovering from error state */
34842
34843  /* This routine is only called from b-tree and only when there are no
34844  ** outstanding pages */
34845  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
34846  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
34847
34848  /* If this database is in an error-state, now is a chance to clear
34849  ** the error. Discard the contents of the pager-cache and rollback
34850  ** any hot journal in the file-system.
34851  */
34852  if( pPager->errCode ){
34853    if( isOpen(pPager->jfd) || pPager->zJournal ){
34854      isErrorReset = 1;
34855    }
34856    pPager->errCode = SQLITE_OK;
34857    pager_reset(pPager);
34858  }
34859
34860  if( pPager->state==PAGER_UNLOCK || isErrorReset ){
34861    sqlite3_vfs * const pVfs = pPager->pVfs;
34862    int isHotJournal = 0;
34863    assert( !MEMDB );
34864    assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
34865    if( pPager->noReadlock ){
34866      assert( pPager->readOnly );
34867      pPager->state = PAGER_SHARED;
34868    }else{
34869      rc = pager_wait_on_lock(pPager, SHARED_LOCK);
34870      if( rc!=SQLITE_OK ){
34871        assert( pPager->state==PAGER_UNLOCK );
34872        return pager_error(pPager, rc);
34873      }
34874    }
34875    assert( pPager->state>=SHARED_LOCK );
34876
34877    /* If a journal file exists, and there is no RESERVED lock on the
34878    ** database file, then it either needs to be played back or deleted.
34879    */
34880    if( !isErrorReset ){
34881      assert( pPager->state <= PAGER_SHARED );
34882      rc = hasHotJournal(pPager, &isHotJournal);
34883      if( rc!=SQLITE_OK ){
34884        goto failed;
34885      }
34886    }
34887    if( isErrorReset || isHotJournal ){
34888      /* Get an EXCLUSIVE lock on the database file. At this point it is
34889      ** important that a RESERVED lock is not obtained on the way to the
34890      ** EXCLUSIVE lock. If it were, another process might open the
34891      ** database file, detect the RESERVED lock, and conclude that the
34892      ** database is safe to read while this process is still rolling the
34893      ** hot-journal back.
34894      **
34895      ** Because the intermediate RESERVED lock is not requested, any
34896      ** other process attempting to access the database file will get to
34897      ** this point in the code and fail to obtain its own EXCLUSIVE lock
34898      ** on the database file.
34899      */
34900      if( pPager->state<EXCLUSIVE_LOCK ){
34901        rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
34902        if( rc!=SQLITE_OK ){
34903          rc = pager_error(pPager, rc);
34904          goto failed;
34905        }
34906        pPager->state = PAGER_EXCLUSIVE;
34907      }
34908
34909      /* Open the journal for read/write access. This is because in
34910      ** exclusive-access mode the file descriptor will be kept open and
34911      ** possibly used for a transaction later on. On some systems, the
34912      ** OsTruncate() call used in exclusive-access mode also requires
34913      ** a read/write file handle.
34914      */
34915      if( !isOpen(pPager->jfd) ){
34916        int res;
34917        rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
34918        if( rc==SQLITE_OK ){
34919          if( res ){
34920            int fout = 0;
34921            int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
34922            assert( !pPager->tempFile );
34923            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
34924            assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
34925            if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
34926              rc = SQLITE_CANTOPEN;
34927              sqlite3OsClose(pPager->jfd);
34928            }
34929          }else{
34930            /* If the journal does not exist, it usually means that some
34931            ** other connection managed to get in and roll it back before
34932            ** this connection obtained the exclusive lock above. Or, it
34933            ** may mean that the pager was in the error-state when this
34934            ** function was called and the journal file does not exist.  */
34935            rc = pager_end_transaction(pPager, 0);
34936          }
34937        }
34938      }
34939      if( rc!=SQLITE_OK ){
34940        goto failed;
34941      }
34942
34943      /* TODO: Why are these cleared here? Is it necessary? */
34944      pPager->journalStarted = 0;
34945      pPager->journalOff = 0;
34946      pPager->setMaster = 0;
34947      pPager->journalHdr = 0;
34948
34949      /* Playback and delete the journal.  Drop the database write
34950      ** lock and reacquire the read lock. Purge the cache before
34951      ** playing back the hot-journal so that we don't end up with
34952      ** an inconsistent cache.
34953      */
34954      if( isOpen(pPager->jfd) ){
34955        rc = pager_playback(pPager, 1);
34956        if( rc!=SQLITE_OK ){
34957          rc = pager_error(pPager, rc);
34958          goto failed;
34959        }
34960      }
34961      assert( (pPager->state==PAGER_SHARED)
34962           || (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
34963      );
34964    }
34965
34966    if( pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0 ){
34967      /* The shared-lock has just been acquired on the database file
34968      ** and there are already pages in the cache (from a previous
34969      ** read or write transaction).  Check to see if the database
34970      ** has been modified.  If the database has changed, flush the
34971      ** cache.
34972      **
34973      ** Database changes is detected by looking at 15 bytes beginning
34974      ** at offset 24 into the file.  The first 4 of these 16 bytes are
34975      ** a 32-bit counter that is incremented with each change.  The
34976      ** other bytes change randomly with each file change when
34977      ** a codec is in use.
34978      **
34979      ** There is a vanishingly small chance that a change will not be
34980      ** detected.  The chance of an undetected change is so small that
34981      ** it can be neglected.
34982      */
34983      char dbFileVers[sizeof(pPager->dbFileVers)];
34984      sqlite3PagerPagecount(pPager, 0);
34985
34986      if( pPager->errCode ){
34987        rc = pPager->errCode;
34988        goto failed;
34989      }
34990
34991      assert( pPager->dbSizeValid );
34992      if( pPager->dbSize>0 ){
34993        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
34994        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
34995        if( rc!=SQLITE_OK ){
34996          goto failed;
34997        }
34998      }else{
34999        memset(dbFileVers, 0, sizeof(dbFileVers));
35000      }
35001
35002      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
35003        pager_reset(pPager);
35004      }
35005    }
35006    assert( pPager->exclusiveMode || pPager->state==PAGER_SHARED );
35007  }
35008
35009 failed:
35010  if( rc!=SQLITE_OK ){
35011    /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
35012    pager_unlock(pPager);
35013  }
35014  return rc;
35015}
35016
35017/*
35018** If the reference count has reached zero, rollback any active
35019** transaction and unlock the pager.
35020**
35021** Except, in locking_mode=EXCLUSIVE when there is nothing to in
35022** the rollback journal, the unlock is not performed and there is
35023** nothing to rollback, so this routine is a no-op.
35024*/
35025static void pagerUnlockIfUnused(Pager *pPager){
35026  if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
35027   && (!pPager->exclusiveMode || pPager->journalOff>0)
35028  ){
35029    pagerUnlockAndRollback(pPager);
35030  }
35031}
35032
35033/*
35034** Acquire a reference to page number pgno in pager pPager (a page
35035** reference has type DbPage*). If the requested reference is
35036** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
35037**
35038** If the requested page is already in the cache, it is returned.
35039** Otherwise, a new page object is allocated and populated with data
35040** read from the database file. In some cases, the pcache module may
35041** choose not to allocate a new page object and may reuse an existing
35042** object with no outstanding references.
35043**
35044** The extra data appended to a page is always initialized to zeros the
35045** first time a page is loaded into memory. If the page requested is
35046** already in the cache when this function is called, then the extra
35047** data is left as it was when the page object was last used.
35048**
35049** If the database image is smaller than the requested page or if a
35050** non-zero value is passed as the noContent parameter and the
35051** requested page is not already stored in the cache, then no
35052** actual disk read occurs. In this case the memory image of the
35053** page is initialized to all zeros.
35054**
35055** If noContent is true, it means that we do not care about the contents
35056** of the page. This occurs in two seperate scenarios:
35057**
35058**   a) When reading a free-list leaf page from the database, and
35059**
35060**   b) When a savepoint is being rolled back and we need to load
35061**      a new page into the cache to populate with the data read
35062**      from the savepoint journal.
35063**
35064** If noContent is true, then the data returned is zeroed instead of
35065** being read from the database. Additionally, the bits corresponding
35066** to pgno in Pager.pInJournal (bitvec of pages already written to the
35067** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
35068** savepoints are set. This means if the page is made writable at any
35069** point in the future, using a call to sqlite3PagerWrite(), its contents
35070** will not be journaled. This saves IO.
35071**
35072** The acquisition might fail for several reasons.  In all cases,
35073** an appropriate error code is returned and *ppPage is set to NULL.
35074**
35075** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
35076** to find a page in the in-memory cache first.  If the page is not already
35077** in memory, this routine goes to disk to read it in whereas Lookup()
35078** just returns 0.  This routine acquires a read-lock the first time it
35079** has to go to disk, and could also playback an old journal if necessary.
35080** Since Lookup() never goes to disk, it never has to deal with locks
35081** or journal files.
35082*/
35083SQLITE_PRIVATE int sqlite3PagerAcquire(
35084  Pager *pPager,      /* The pager open on the database file */
35085  Pgno pgno,          /* Page number to fetch */
35086  DbPage **ppPage,    /* Write a pointer to the page here */
35087  int noContent       /* Do not bother reading content from disk if true */
35088){
35089  int rc;
35090  PgHdr *pPg;
35091
35092  assert( assert_pager_state(pPager) );
35093  assert( pPager->state>PAGER_UNLOCK );
35094
35095  if( pgno==0 ){
35096    return SQLITE_CORRUPT_BKPT(PAGE_NUM_0_CORRUPTION); // Android Change
35097  }
35098
35099  /* If the pager is in the error state, return an error immediately.
35100  ** Otherwise, request the page from the PCache layer. */
35101  if( pPager->errCode!=SQLITE_OK && pPager->errCode!=SQLITE_FULL ){
35102    rc = pPager->errCode;
35103  }else{
35104    rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
35105  }
35106
35107  if( rc!=SQLITE_OK ){
35108    /* Either the call to sqlite3PcacheFetch() returned an error or the
35109    ** pager was already in the error-state when this function was called.
35110    ** Set pPg to 0 and jump to the exception handler.  */
35111    pPg = 0;
35112    goto pager_acquire_err;
35113  }
35114  assert( (*ppPage)->pgno==pgno );
35115  assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
35116
35117  if( (*ppPage)->pPager ){
35118    /* In this case the pcache already contains an initialized copy of
35119    ** the page. Return without further ado.  */
35120    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
35121    PAGER_INCR(pPager->nHit);
35122    return SQLITE_OK;
35123
35124  }else{
35125    /* The pager cache has created a new page. Its content needs to
35126    ** be initialized.  */
35127    int nMax;
35128
35129    PAGER_INCR(pPager->nMiss);
35130    pPg = *ppPage;
35131    pPg->pPager = pPager;
35132
35133    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
35134    ** number greater than this, or the unused locking-page, is requested. */
35135    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
35136      rc = SQLITE_CORRUPT_BKPT(PAGER_OUT_OF_RANGE_CORRUPTION); // Android Change
35137      goto pager_acquire_err;
35138    }
35139
35140    rc = sqlite3PagerPagecount(pPager, &nMax);
35141    if( rc!=SQLITE_OK ){
35142      goto pager_acquire_err;
35143    }
35144
35145    if( MEMDB || nMax<(int)pgno || noContent ){
35146      if( pgno>pPager->mxPgno ){
35147	rc = SQLITE_FULL;
35148	goto pager_acquire_err;
35149      }
35150      if( noContent ){
35151        /* Failure to set the bits in the InJournal bit-vectors is benign.
35152        ** It merely means that we might do some extra work to journal a
35153        ** page that does not need to be journaled.  Nevertheless, be sure
35154        ** to test the case where a malloc error occurs while trying to set
35155        ** a bit in a bit vector.
35156        */
35157        sqlite3BeginBenignMalloc();
35158        if( pgno<=pPager->dbOrigSize ){
35159          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
35160          testcase( rc==SQLITE_NOMEM );
35161        }
35162        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
35163        testcase( rc==SQLITE_NOMEM );
35164        sqlite3EndBenignMalloc();
35165      }
35166      memset(pPg->pData, 0, pPager->pageSize);
35167      IOTRACE(("ZERO %p %d\n", pPager, pgno));
35168    }else{
35169      assert( pPg->pPager==pPager );
35170      rc = readDbPage(pPg);
35171      if( rc!=SQLITE_OK ){
35172        goto pager_acquire_err;
35173      }
35174    }
35175#ifdef SQLITE_CHECK_PAGES
35176    pPg->pageHash = pager_pagehash(pPg);
35177#endif
35178  }
35179
35180  return SQLITE_OK;
35181
35182pager_acquire_err:
35183  assert( rc!=SQLITE_OK );
35184  if( pPg ){
35185    sqlite3PcacheDrop(pPg);
35186  }
35187  pagerUnlockIfUnused(pPager);
35188
35189  *ppPage = 0;
35190  return rc;
35191}
35192
35193/*
35194** Acquire a page if it is already in the in-memory cache.  Do
35195** not read the page from disk.  Return a pointer to the page,
35196** or 0 if the page is not in cache. Also, return 0 if the
35197** pager is in PAGER_UNLOCK state when this function is called,
35198** or if the pager is in an error state other than SQLITE_FULL.
35199**
35200** See also sqlite3PagerGet().  The difference between this routine
35201** and sqlite3PagerGet() is that _get() will go to the disk and read
35202** in the page if the page is not already in cache.  This routine
35203** returns NULL if the page is not in cache or if a disk I/O error
35204** has ever happened.
35205*/
35206SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
35207  PgHdr *pPg = 0;
35208  assert( pPager!=0 );
35209  assert( pgno!=0 );
35210  assert( pPager->pPCache!=0 );
35211  assert( pPager->state > PAGER_UNLOCK );
35212  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
35213  return pPg;
35214}
35215
35216/*
35217** Release a page reference.
35218**
35219** If the number of references to the page drop to zero, then the
35220** page is added to the LRU list.  When all references to all pages
35221** are released, a rollback occurs and the lock on the database is
35222** removed.
35223*/
35224SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
35225  if( pPg ){
35226    Pager *pPager = pPg->pPager;
35227    sqlite3PcacheRelease(pPg);
35228    pagerUnlockIfUnused(pPager);
35229  }
35230}
35231
35232/*
35233** If the main journal file has already been opened, ensure that the
35234** sub-journal file is open too. If the main journal is not open,
35235** this function is a no-op.
35236**
35237** SQLITE_OK is returned if everything goes according to plan.
35238** An SQLITE_IOERR_XXX error code is returned if a call to
35239** sqlite3OsOpen() fails.
35240*/
35241static int openSubJournal(Pager *pPager){
35242  int rc = SQLITE_OK;
35243  if( isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ){
35244    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
35245      sqlite3MemJournalOpen(pPager->sjfd);
35246    }else{
35247      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
35248    }
35249  }
35250  return rc;
35251}
35252
35253/*
35254** This function is called at the start of every write transaction.
35255** There must already be a RESERVED or EXCLUSIVE lock on the database
35256** file when this routine is called.
35257**
35258** Open the journal file for pager pPager and write a journal header
35259** to the start of it. If there are active savepoints, open the sub-journal
35260** as well. This function is only used when the journal file is being
35261** opened to write a rollback log for a transaction. It is not used
35262** when opening a hot journal file to roll it back.
35263**
35264** If the journal file is already open (as it may be in exclusive mode),
35265** then this function just writes a journal header to the start of the
35266** already open file.
35267**
35268** Whether or not the journal file is opened by this function, the
35269** Pager.pInJournal bitvec structure is allocated.
35270**
35271** Return SQLITE_OK if everything is successful. Otherwise, return
35272** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
35273** an IO error code if opening or writing the journal file fails.
35274*/
35275static int pager_open_journal(Pager *pPager){
35276  int rc = SQLITE_OK;                        /* Return code */
35277  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
35278
35279  assert( pPager->state>=PAGER_RESERVED );
35280  assert( pPager->useJournal );
35281  assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF );
35282  assert( pPager->pInJournal==0 );
35283
35284  /* If already in the error state, this function is a no-op.  But on
35285  ** the other hand, this routine is never called if we are already in
35286  ** an error state. */
35287  if( NEVER(pPager->errCode) ) return pPager->errCode;
35288
35289  /* TODO: Is it really possible to get here with dbSizeValid==0? If not,
35290  ** the call to PagerPagecount() can be removed.
35291  */
35292  testcase( pPager->dbSizeValid==0 );
35293  sqlite3PagerPagecount(pPager, 0);
35294
35295  pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
35296  if( pPager->pInJournal==0 ){
35297    return SQLITE_NOMEM;
35298  }
35299
35300  /* Open the journal file if it is not already open. */
35301  if( !isOpen(pPager->jfd) ){
35302    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
35303      sqlite3MemJournalOpen(pPager->jfd);
35304    }else{
35305      const int flags =                   /* VFS flags to open journal file */
35306        SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
35307        (pPager->tempFile ?
35308          (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
35309          (SQLITE_OPEN_MAIN_JOURNAL)
35310        );
35311#ifdef SQLITE_ENABLE_ATOMIC_WRITE
35312      rc = sqlite3JournalOpen(
35313          pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
35314      );
35315#else
35316      rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
35317#endif
35318    }
35319    assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
35320  }
35321
35322
35323  /* Write the first journal header to the journal file and open
35324  ** the sub-journal if necessary.
35325  */
35326  if( rc==SQLITE_OK ){
35327    /* TODO: Check if all of these are really required. */
35328    pPager->dbOrigSize = pPager->dbSize;
35329    pPager->journalStarted = 0;
35330    pPager->needSync = 0;
35331    pPager->nRec = 0;
35332    pPager->journalOff = 0;
35333    pPager->setMaster = 0;
35334    pPager->journalHdr = 0;
35335    rc = writeJournalHdr(pPager);
35336  }
35337  if( rc==SQLITE_OK && pPager->nSavepoint ){
35338    rc = openSubJournal(pPager);
35339  }
35340
35341  if( rc!=SQLITE_OK ){
35342    sqlite3BitvecDestroy(pPager->pInJournal);
35343    pPager->pInJournal = 0;
35344  }
35345  return rc;
35346}
35347
35348/*
35349** Begin a write-transaction on the specified pager object. If a
35350** write-transaction has already been opened, this function is a no-op.
35351**
35352** If the exFlag argument is false, then acquire at least a RESERVED
35353** lock on the database file. If exFlag is true, then acquire at least
35354** an EXCLUSIVE lock. If such a lock is already held, no locking
35355** functions need be called.
35356**
35357** If this is not a temporary or in-memory file and, the journal file is
35358** opened if it has not been already. For a temporary file, the opening
35359** of the journal file is deferred until there is an actual need to
35360** write to the journal. TODO: Why handle temporary files differently?
35361**
35362** If the journal file is opened (or if it is already open), then a
35363** journal-header is written to the start of it.
35364**
35365** If the subjInMemory argument is non-zero, then any sub-journal opened
35366** within this transaction will be opened as an in-memory file. This
35367** has no effect if the sub-journal is already opened (as it may be when
35368** running in exclusive mode) or if the transaction does not require a
35369** sub-journal. If the subjInMemory argument is zero, then any required
35370** sub-journal is implemented in-memory if pPager is an in-memory database,
35371** or using a temporary file otherwise.
35372*/
35373SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
35374  int rc = SQLITE_OK;
35375  assert( pPager->state!=PAGER_UNLOCK );
35376  pPager->subjInMemory = (u8)subjInMemory;
35377  if( pPager->state==PAGER_SHARED ){
35378    assert( pPager->pInJournal==0 );
35379    assert( !MEMDB && !pPager->tempFile );
35380
35381    /* Obtain a RESERVED lock on the database file. If the exFlag parameter
35382    ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
35383    ** busy-handler callback can be used when upgrading to the EXCLUSIVE
35384    ** lock, but not when obtaining the RESERVED lock.
35385    */
35386    rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
35387    if( rc==SQLITE_OK ){
35388      pPager->state = PAGER_RESERVED;
35389      if( exFlag ){
35390        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
35391      }
35392    }
35393
35394    /* If the required locks were successfully obtained, open the journal
35395    ** file and write the first journal-header to it.
35396    */
35397    if( rc==SQLITE_OK && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
35398      rc = pager_open_journal(pPager);
35399    }
35400  }else if( isOpen(pPager->jfd) && pPager->journalOff==0 ){
35401    /* This happens when the pager was in exclusive-access mode the last
35402    ** time a (read or write) transaction was successfully concluded
35403    ** by this connection. Instead of deleting the journal file it was
35404    ** kept open and either was truncated to 0 bytes or its header was
35405    ** overwritten with zeros.
35406    */
35407    assert( pPager->nRec==0 );
35408    assert( pPager->dbOrigSize==0 );
35409    assert( pPager->pInJournal==0 );
35410    rc = pager_open_journal(pPager);
35411  }
35412
35413  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
35414  assert( !isOpen(pPager->jfd) || pPager->journalOff>0 || rc!=SQLITE_OK );
35415  if( rc!=SQLITE_OK ){
35416    assert( !pPager->dbModified );
35417    /* Ignore any IO error that occurs within pager_end_transaction(). The
35418    ** purpose of this call is to reset the internal state of the pager
35419    ** sub-system. It doesn't matter if the journal-file is not properly
35420    ** finalized at this point (since it is not a valid journal file anyway).
35421    */
35422    pager_end_transaction(pPager, 0);
35423  }
35424  return rc;
35425}
35426
35427/*
35428** Mark a single data page as writeable. The page is written into the
35429** main journal or sub-journal as required. If the page is written into
35430** one of the journals, the corresponding bit is set in the
35431** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
35432** of any open savepoints as appropriate.
35433*/
35434static int pager_write(PgHdr *pPg){
35435  void *pData = pPg->pData;
35436  Pager *pPager = pPg->pPager;
35437  int rc = SQLITE_OK;
35438
35439  /* This routine is not called unless a transaction has already been
35440  ** started.
35441  */
35442  assert( pPager->state>=PAGER_RESERVED );
35443
35444  /* If an error has been previously detected, we should not be
35445  ** calling this routine.  Repeat the error for robustness.
35446  */
35447  if( NEVER(pPager->errCode) )  return pPager->errCode;
35448
35449  /* Higher-level routines never call this function if database is not
35450  ** writable.  But check anyway, just for robustness. */
35451  if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
35452
35453  assert( !pPager->setMaster );
35454
35455  CHECK_PAGE(pPg);
35456
35457  /* Mark the page as dirty.  If the page has already been written
35458  ** to the journal then we can return right away.
35459  */
35460  sqlite3PcacheMakeDirty(pPg);
35461  if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
35462    pPager->dbModified = 1;
35463  }else{
35464
35465    /* If we get this far, it means that the page needs to be
35466    ** written to the transaction journal or the ckeckpoint journal
35467    ** or both.
35468    **
35469    ** Higher level routines should have already started a transaction,
35470    ** which means they have acquired the necessary locks and opened
35471    ** a rollback journal.  Double-check to makes sure this is the case.
35472    */
35473    rc = sqlite3PagerBegin(pPager, 0, pPager->subjInMemory);
35474    if( NEVER(rc!=SQLITE_OK) ){
35475      return rc;
35476    }
35477    if( !isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
35478      assert( pPager->useJournal );
35479      rc = pager_open_journal(pPager);
35480      if( rc!=SQLITE_OK ) return rc;
35481    }
35482    pPager->dbModified = 1;
35483
35484    /* The transaction journal now exists and we have a RESERVED or an
35485    ** EXCLUSIVE lock on the main database file.  Write the current page to
35486    ** the transaction journal if it is not there already.
35487    */
35488    if( !pageInJournal(pPg) && isOpen(pPager->jfd) ){
35489      if( pPg->pgno<=pPager->dbOrigSize ){
35490        u32 cksum;
35491        char *pData2;
35492
35493        /* We should never write to the journal file the page that
35494        ** contains the database locks.  The following assert verifies
35495        ** that we do not. */
35496        assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
35497        CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
35498        cksum = pager_cksum(pPager, (u8*)pData2);
35499        rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
35500        if( rc==SQLITE_OK ){
35501          rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
35502                              pPager->journalOff + 4);
35503          pPager->journalOff += pPager->pageSize+4;
35504        }
35505        if( rc==SQLITE_OK ){
35506          rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
35507          pPager->journalOff += 4;
35508        }
35509        IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
35510                 pPager->journalOff, pPager->pageSize));
35511        PAGER_INCR(sqlite3_pager_writej_count);
35512        PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
35513             PAGERID(pPager), pPg->pgno,
35514             ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
35515
35516        /* Even if an IO or diskfull error occurred while journalling the
35517        ** page in the block above, set the need-sync flag for the page.
35518        ** Otherwise, when the transaction is rolled back, the logic in
35519        ** playback_one_page() will think that the page needs to be restored
35520        ** in the database file. And if an IO error occurs while doing so,
35521        ** then corruption may follow.
35522        */
35523        if( !pPager->noSync ){
35524          pPg->flags |= PGHDR_NEED_SYNC;
35525          pPager->needSync = 1;
35526        }
35527
35528        /* An error has occurred writing to the journal file. The
35529        ** transaction will be rolled back by the layer above.
35530        */
35531        if( rc!=SQLITE_OK ){
35532          return rc;
35533        }
35534
35535        pPager->nRec++;
35536        assert( pPager->pInJournal!=0 );
35537        rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
35538        testcase( rc==SQLITE_NOMEM );
35539        assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
35540        rc |= addToSavepointBitvecs(pPager, pPg->pgno);
35541        if( rc!=SQLITE_OK ){
35542          assert( rc==SQLITE_NOMEM );
35543          return rc;
35544        }
35545      }else{
35546        if( !pPager->journalStarted && !pPager->noSync ){
35547          pPg->flags |= PGHDR_NEED_SYNC;
35548          pPager->needSync = 1;
35549        }
35550        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
35551                PAGERID(pPager), pPg->pgno,
35552               ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
35553      }
35554    }
35555
35556    /* If the statement journal is open and the page is not in it,
35557    ** then write the current page to the statement journal.  Note that
35558    ** the statement journal format differs from the standard journal format
35559    ** in that it omits the checksums and the header.
35560    */
35561    if( subjRequiresPage(pPg) ){
35562      rc = subjournalPage(pPg);
35563    }
35564  }
35565
35566  /* Update the database size and return.
35567  */
35568  assert( pPager->state>=PAGER_SHARED );
35569  if( pPager->dbSize<pPg->pgno ){
35570    pPager->dbSize = pPg->pgno;
35571  }
35572  return rc;
35573}
35574
35575/*
35576** Mark a data page as writeable. This routine must be called before
35577** making changes to a page. The caller must check the return value
35578** of this function and be careful not to change any page data unless
35579** this routine returns SQLITE_OK.
35580**
35581** The difference between this function and pager_write() is that this
35582** function also deals with the special case where 2 or more pages
35583** fit on a single disk sector. In this case all co-resident pages
35584** must have been written to the journal file before returning.
35585**
35586** If an error occurs, SQLITE_NOMEM or an IO error code is returned
35587** as appropriate. Otherwise, SQLITE_OK.
35588*/
35589SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
35590  int rc = SQLITE_OK;
35591
35592  PgHdr *pPg = pDbPage;
35593  Pager *pPager = pPg->pPager;
35594  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
35595
35596  if( nPagePerSector>1 ){
35597    Pgno nPageCount;          /* Total number of pages in database file */
35598    Pgno pg1;                 /* First page of the sector pPg is located on. */
35599    int nPage;                /* Number of pages starting at pg1 to journal */
35600    int ii;                   /* Loop counter */
35601    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
35602
35603    /* Set the doNotSync flag to 1. This is because we cannot allow a journal
35604    ** header to be written between the pages journaled by this function.
35605    */
35606    assert( !MEMDB );
35607    assert( pPager->doNotSync==0 );
35608    pPager->doNotSync = 1;
35609
35610    /* This trick assumes that both the page-size and sector-size are
35611    ** an integer power of 2. It sets variable pg1 to the identifier
35612    ** of the first page of the sector pPg is located on.
35613    */
35614    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
35615
35616    sqlite3PagerPagecount(pPager, (int *)&nPageCount);
35617    if( pPg->pgno>nPageCount ){
35618      nPage = (pPg->pgno - pg1)+1;
35619    }else if( (pg1+nPagePerSector-1)>nPageCount ){
35620      nPage = nPageCount+1-pg1;
35621    }else{
35622      nPage = nPagePerSector;
35623    }
35624    assert(nPage>0);
35625    assert(pg1<=pPg->pgno);
35626    assert((pg1+nPage)>pPg->pgno);
35627
35628    for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
35629      Pgno pg = pg1+ii;
35630      PgHdr *pPage;
35631      if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
35632        if( pg!=PAGER_MJ_PGNO(pPager) ){
35633          rc = sqlite3PagerGet(pPager, pg, &pPage);
35634          if( rc==SQLITE_OK ){
35635            rc = pager_write(pPage);
35636            if( pPage->flags&PGHDR_NEED_SYNC ){
35637              needSync = 1;
35638              assert(pPager->needSync);
35639            }
35640            sqlite3PagerUnref(pPage);
35641          }
35642        }
35643      }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
35644        if( pPage->flags&PGHDR_NEED_SYNC ){
35645          needSync = 1;
35646        }
35647        sqlite3PagerUnref(pPage);
35648      }
35649    }
35650
35651    /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
35652    ** starting at pg1, then it needs to be set for all of them. Because
35653    ** writing to any of these nPage pages may damage the others, the
35654    ** journal file must contain sync()ed copies of all of them
35655    ** before any of them can be written out to the database file.
35656    */
35657    if( rc==SQLITE_OK && needSync ){
35658      assert( !MEMDB && pPager->noSync==0 );
35659      for(ii=0; ii<nPage; ii++){
35660        PgHdr *pPage = pager_lookup(pPager, pg1+ii);
35661        if( pPage ){
35662          pPage->flags |= PGHDR_NEED_SYNC;
35663          sqlite3PagerUnref(pPage);
35664        }
35665      }
35666      assert(pPager->needSync);
35667    }
35668
35669    assert( pPager->doNotSync==1 );
35670    pPager->doNotSync = 0;
35671  }else{
35672    rc = pager_write(pDbPage);
35673  }
35674  return rc;
35675}
35676
35677/*
35678** Return TRUE if the page given in the argument was previously passed
35679** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
35680** to change the content of the page.
35681*/
35682#ifndef NDEBUG
35683SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
35684  return pPg->flags&PGHDR_DIRTY;
35685}
35686#endif
35687
35688#ifndef SQLITE_SECURE_DELETE
35689/*
35690** A call to this routine tells the pager that it is not necessary to
35691** write the information on page pPg back to the disk, even though
35692** that page might be marked as dirty.  This happens, for example, when
35693** the page has been added as a leaf of the freelist and so its
35694** content no longer matters.
35695**
35696** The overlying software layer calls this routine when all of the data
35697** on the given page is unused. The pager marks the page as clean so
35698** that it does not get written to disk.
35699**
35700** Tests show that this optimization can quadruple the speed of large
35701** DELETE operations.
35702*/
35703SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
35704  Pager *pPager = pPg->pPager;
35705  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
35706    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
35707    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
35708    pPg->flags |= PGHDR_DONT_WRITE;
35709#ifdef SQLITE_CHECK_PAGES
35710    pPg->pageHash = pager_pagehash(pPg);
35711#endif
35712  }
35713}
35714#endif /* !defined(SQLITE_SECURE_DELETE) */
35715
35716/*
35717** This routine is called to increment the value of the database file
35718** change-counter, stored as a 4-byte big-endian integer starting at
35719** byte offset 24 of the pager file.
35720**
35721** If the isDirectMode flag is zero, then this is done by calling
35722** sqlite3PagerWrite() on page 1, then modifying the contents of the
35723** page data. In this case the file will be updated when the current
35724** transaction is committed.
35725**
35726** The isDirectMode flag may only be non-zero if the library was compiled
35727** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
35728** if isDirect is non-zero, then the database file is updated directly
35729** by writing an updated version of page 1 using a call to the
35730** sqlite3OsWrite() function.
35731*/
35732static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
35733  int rc = SQLITE_OK;
35734
35735  /* Declare and initialize constant integer 'isDirect'. If the
35736  ** atomic-write optimization is enabled in this build, then isDirect
35737  ** is initialized to the value passed as the isDirectMode parameter
35738  ** to this function. Otherwise, it is always set to zero.
35739  **
35740  ** The idea is that if the atomic-write optimization is not
35741  ** enabled at compile time, the compiler can omit the tests of
35742  ** 'isDirect' below, as well as the block enclosed in the
35743  ** "if( isDirect )" condition.
35744  */
35745#ifndef SQLITE_ENABLE_ATOMIC_WRITE
35746# define DIRECT_MODE 0
35747  assert( isDirectMode==0 );
35748  UNUSED_PARAMETER(isDirectMode);
35749#else
35750# define DIRECT_MODE isDirectMode
35751#endif
35752
35753  assert( pPager->state>=PAGER_RESERVED );
35754  if( !pPager->changeCountDone && pPager->dbSize>0 ){
35755    PgHdr *pPgHdr;                /* Reference to page 1 */
35756    u32 change_counter;           /* Initial value of change-counter field */
35757
35758    assert( !pPager->tempFile && isOpen(pPager->fd) );
35759
35760    /* Open page 1 of the file for writing. */
35761    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
35762    assert( pPgHdr==0 || rc==SQLITE_OK );
35763
35764    /* If page one was fetched successfully, and this function is not
35765    ** operating in direct-mode, make page 1 writable.  When not in
35766    ** direct mode, page 1 is always held in cache and hence the PagerGet()
35767    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
35768    */
35769    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
35770      rc = sqlite3PagerWrite(pPgHdr);
35771    }
35772
35773    if( rc==SQLITE_OK ){
35774      /* Increment the value just read and write it back to byte 24. */
35775      change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
35776      change_counter++;
35777      put32bits(((char*)pPgHdr->pData)+24, change_counter);
35778
35779      /* If running in direct mode, write the contents of page 1 to the file. */
35780      if( DIRECT_MODE ){
35781        const void *zBuf = pPgHdr->pData;
35782        assert( pPager->dbFileSize>0 );
35783        rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
35784        if( rc==SQLITE_OK ){
35785          pPager->changeCountDone = 1;
35786        }
35787      }else{
35788        pPager->changeCountDone = 1;
35789      }
35790    }
35791
35792    /* Release the page reference. */
35793    sqlite3PagerUnref(pPgHdr);
35794  }
35795  return rc;
35796}
35797
35798/*
35799** Sync the pager file to disk. This is a no-op for in-memory files
35800** or pages with the Pager.noSync flag set.
35801**
35802** If successful, or called on a pager for which it is a no-op, this
35803** function returns SQLITE_OK. Otherwise, an IO error code is returned.
35804*/
35805SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
35806  int rc;                              /* Return code */
35807  assert( !MEMDB );
35808  if( pPager->noSync ){
35809    rc = SQLITE_OK;
35810  }else{
35811    rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
35812  }
35813  return rc;
35814}
35815
35816/*
35817** Sync the database file for the pager pPager. zMaster points to the name
35818** of a master journal file that should be written into the individual
35819** journal file. zMaster may be NULL, which is interpreted as no master
35820** journal (a single database transaction).
35821**
35822** This routine ensures that:
35823**
35824**   * The database file change-counter is updated,
35825**   * the journal is synced (unless the atomic-write optimization is used),
35826**   * all dirty pages are written to the database file,
35827**   * the database file is truncated (if required), and
35828**   * the database file synced.
35829**
35830** The only thing that remains to commit the transaction is to finalize
35831** (delete, truncate or zero the first part of) the journal file (or
35832** delete the master journal file if specified).
35833**
35834** Note that if zMaster==NULL, this does not overwrite a previous value
35835** passed to an sqlite3PagerCommitPhaseOne() call.
35836**
35837** If the final parameter - noSync - is true, then the database file itself
35838** is not synced. The caller must call sqlite3PagerSync() directly to
35839** sync the database file before calling CommitPhaseTwo() to delete the
35840** journal file in this case.
35841*/
35842SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
35843  Pager *pPager,                  /* Pager object */
35844  const char *zMaster,            /* If not NULL, the master journal name */
35845  int noSync                      /* True to omit the xSync on the db file */
35846){
35847  int rc = SQLITE_OK;             /* Return code */
35848
35849  /* The dbOrigSize is never set if journal_mode=OFF */
35850  assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF || pPager->dbOrigSize==0 );
35851
35852  /* If a prior error occurred, this routine should not be called.  ROLLBACK
35853  ** is the appropriate response to an error, not COMMIT.  Guard against
35854  ** coding errors by repeating the prior error. */
35855  if( NEVER(pPager->errCode) ) return pPager->errCode;
35856
35857  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
35858      pPager->zFilename, zMaster, pPager->dbSize));
35859
35860  if( MEMDB && pPager->dbModified ){
35861    /* If this is an in-memory db, or no pages have been written to, or this
35862    ** function has already been called, it is mostly a no-op.  However, any
35863    ** backup in progress needs to be restarted.
35864    */
35865    sqlite3BackupRestart(pPager->pBackup);
35866  }else if( pPager->state!=PAGER_SYNCED && pPager->dbModified ){
35867
35868    /* The following block updates the change-counter. Exactly how it
35869    ** does this depends on whether or not the atomic-update optimization
35870    ** was enabled at compile time, and if this transaction meets the
35871    ** runtime criteria to use the operation:
35872    **
35873    **    * The file-system supports the atomic-write property for
35874    **      blocks of size page-size, and
35875    **    * This commit is not part of a multi-file transaction, and
35876    **    * Exactly one page has been modified and store in the journal file.
35877    **
35878    ** If the optimization was not enabled at compile time, then the
35879    ** pager_incr_changecounter() function is called to update the change
35880    ** counter in 'indirect-mode'. If the optimization is compiled in but
35881    ** is not applicable to this transaction, call sqlite3JournalCreate()
35882    ** to make sure the journal file has actually been created, then call
35883    ** pager_incr_changecounter() to update the change-counter in indirect
35884    ** mode.
35885    **
35886    ** Otherwise, if the optimization is both enabled and applicable,
35887    ** then call pager_incr_changecounter() to update the change-counter
35888    ** in 'direct' mode. In this case the journal file will never be
35889    ** created for this transaction.
35890    */
35891#ifdef SQLITE_ENABLE_ATOMIC_WRITE
35892    PgHdr *pPg;
35893    assert( isOpen(pPager->jfd) || pPager->journalMode==PAGER_JOURNALMODE_OFF );
35894    if( !zMaster && isOpen(pPager->jfd)
35895     && pPager->journalOff==jrnlBufferSize(pPager)
35896     && pPager->dbSize>=pPager->dbFileSize
35897     && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
35898    ){
35899      /* Update the db file change counter via the direct-write method. The
35900      ** following call will modify the in-memory representation of page 1
35901      ** to include the updated change counter and then write page 1
35902      ** directly to the database file. Because of the atomic-write
35903      ** property of the host file-system, this is safe.
35904      */
35905      rc = pager_incr_changecounter(pPager, 1);
35906    }else{
35907      rc = sqlite3JournalCreate(pPager->jfd);
35908      if( rc==SQLITE_OK ){
35909        rc = pager_incr_changecounter(pPager, 0);
35910      }
35911    }
35912#else
35913    rc = pager_incr_changecounter(pPager, 0);
35914#endif
35915    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35916
35917    /* If this transaction has made the database smaller, then all pages
35918    ** being discarded by the truncation must be written to the journal
35919    ** file. This can only happen in auto-vacuum mode.
35920    **
35921    ** Before reading the pages with page numbers larger than the
35922    ** current value of Pager.dbSize, set dbSize back to the value
35923    ** that it took at the start of the transaction. Otherwise, the
35924    ** calls to sqlite3PagerGet() return zeroed pages instead of
35925    ** reading data from the database file.
35926    **
35927    ** When journal_mode==OFF the dbOrigSize is always zero, so this
35928    ** block never runs if journal_mode=OFF.
35929    */
35930#ifndef SQLITE_OMIT_AUTOVACUUM
35931    if( pPager->dbSize<pPager->dbOrigSize
35932     && ALWAYS(pPager->journalMode!=PAGER_JOURNALMODE_OFF)
35933    ){
35934      Pgno i;                                   /* Iterator variable */
35935      const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
35936      const Pgno dbSize = pPager->dbSize;       /* Database image size */
35937      pPager->dbSize = pPager->dbOrigSize;
35938      for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
35939        if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
35940          PgHdr *pPage;             /* Page to journal */
35941          rc = sqlite3PagerGet(pPager, i, &pPage);
35942          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35943          rc = sqlite3PagerWrite(pPage);
35944          sqlite3PagerUnref(pPage);
35945          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35946        }
35947      }
35948      pPager->dbSize = dbSize;
35949    }
35950#endif
35951
35952    /* Write the master journal name into the journal file. If a master
35953    ** journal file name has already been written to the journal file,
35954    ** or if zMaster is NULL (no master journal), then this call is a no-op.
35955    */
35956    rc = writeMasterJournal(pPager, zMaster);
35957    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35958
35959    /* Sync the journal file. If the atomic-update optimization is being
35960    ** used, this call will not create the journal file or perform any
35961    ** real IO.
35962    */
35963    rc = syncJournal(pPager);
35964    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35965
35966    /* Write all dirty pages to the database file. */
35967    rc = pager_write_pagelist(sqlite3PcacheDirtyList(pPager->pPCache));
35968    if( rc!=SQLITE_OK ){
35969      assert( rc!=SQLITE_IOERR_BLOCKED );
35970      goto commit_phase_one_exit;
35971    }
35972    sqlite3PcacheCleanAll(pPager->pPCache);
35973
35974    /* If the file on disk is not the same size as the database image,
35975    ** then use pager_truncate to grow or shrink the file here.
35976    */
35977    if( pPager->dbSize!=pPager->dbFileSize ){
35978      Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
35979      assert( pPager->state>=PAGER_EXCLUSIVE );
35980      rc = pager_truncate(pPager, nNew);
35981      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35982    }
35983
35984    /* Finally, sync the database file. */
35985    if( !pPager->noSync && !noSync ){
35986      rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
35987    }
35988    IOTRACE(("DBSYNC %p\n", pPager))
35989
35990    pPager->state = PAGER_SYNCED;
35991  }
35992
35993commit_phase_one_exit:
35994  return rc;
35995}
35996
35997
35998/*
35999** When this function is called, the database file has been completely
36000** updated to reflect the changes made by the current transaction and
36001** synced to disk. The journal file still exists in the file-system
36002** though, and if a failure occurs at this point it will eventually
36003** be used as a hot-journal and the current transaction rolled back.
36004**
36005** This function finalizes the journal file, either by deleting,
36006** truncating or partially zeroing it, so that it cannot be used
36007** for hot-journal rollback. Once this is done the transaction is
36008** irrevocably committed.
36009**
36010** If an error occurs, an IO error code is returned and the pager
36011** moves into the error state. Otherwise, SQLITE_OK is returned.
36012*/
36013SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
36014  int rc = SQLITE_OK;                  /* Return code */
36015
36016  /* This routine should not be called if a prior error has occurred.
36017  ** But if (due to a coding error elsewhere in the system) it does get
36018  ** called, just return the same error code without doing anything. */
36019  if( NEVER(pPager->errCode) ) return pPager->errCode;
36020
36021  /* This function should not be called if the pager is not in at least
36022  ** PAGER_RESERVED state. And indeed SQLite never does this. But it is
36023  ** nice to have this defensive test here anyway.
36024  */
36025  if( NEVER(pPager->state<PAGER_RESERVED) ) return SQLITE_ERROR;
36026
36027  /* An optimization. If the database was not actually modified during
36028  ** this transaction, the pager is running in exclusive-mode and is
36029  ** using persistent journals, then this function is a no-op.
36030  **
36031  ** The start of the journal file currently contains a single journal
36032  ** header with the nRec field set to 0. If such a journal is used as
36033  ** a hot-journal during hot-journal rollback, 0 changes will be made
36034  ** to the database file. So there is no need to zero the journal
36035  ** header. Since the pager is in exclusive mode, there is no need
36036  ** to drop any locks either.
36037  */
36038  if( pPager->dbModified==0 && pPager->exclusiveMode
36039   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
36040  ){
36041    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
36042    return SQLITE_OK;
36043  }
36044
36045  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
36046  assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dbModified );
36047  rc = pager_end_transaction(pPager, pPager->setMaster);
36048  return pager_error(pPager, rc);
36049}
36050
36051/*
36052** Rollback all changes. The database falls back to PAGER_SHARED mode.
36053**
36054** This function performs two tasks:
36055**
36056**   1) It rolls back the journal file, restoring all database file and
36057**      in-memory cache pages to the state they were in when the transaction
36058**      was opened, and
36059**   2) It finalizes the journal file, so that it is not used for hot
36060**      rollback at any point in the future.
36061**
36062** subject to the following qualifications:
36063**
36064** * If the journal file is not yet open when this function is called,
36065**   then only (2) is performed. In this case there is no journal file
36066**   to roll back.
36067**
36068** * If in an error state other than SQLITE_FULL, then task (1) is
36069**   performed. If successful, task (2). Regardless of the outcome
36070**   of either, the error state error code is returned to the caller
36071**   (i.e. either SQLITE_IOERR or SQLITE_CORRUPT).
36072**
36073** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether
36074**   or not (1) is succussful, also attempt (2). If successful, return
36075**   SQLITE_OK. Otherwise, enter the error state and return the first
36076**   error code encountered.
36077**
36078**   In this case there is no chance that the database was written to.
36079**   So is safe to finalize the journal file even if the playback
36080**   (operation 1) failed. However the pager must enter the error state
36081**   as the contents of the in-memory cache are now suspect.
36082**
36083** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only
36084**   attempt (2) if (1) is successful. Return SQLITE_OK if successful,
36085**   otherwise enter the error state and return the error code from the
36086**   failing operation.
36087**
36088**   In this case the database file may have been written to. So if the
36089**   playback operation did not succeed it would not be safe to finalize
36090**   the journal file. It needs to be left in the file-system so that
36091**   some other process can use it to restore the database state (by
36092**   hot-journal rollback).
36093*/
36094SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
36095  int rc = SQLITE_OK;                  /* Return code */
36096  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
36097  if( !pPager->dbModified || !isOpen(pPager->jfd) ){
36098    rc = pager_end_transaction(pPager, pPager->setMaster);
36099  }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
36100    if( pPager->state>=PAGER_EXCLUSIVE ){
36101      pager_playback(pPager, 0);
36102    }
36103    rc = pPager->errCode;
36104  }else{
36105    if( pPager->state==PAGER_RESERVED ){
36106      int rc2;
36107      rc = pager_playback(pPager, 0);
36108      rc2 = pager_end_transaction(pPager, pPager->setMaster);
36109      if( rc==SQLITE_OK ){
36110        rc = rc2;
36111      }
36112    }else{
36113      rc = pager_playback(pPager, 0);
36114    }
36115
36116    if( !MEMDB ){
36117      pPager->dbSizeValid = 0;
36118    }
36119
36120    /* If an error occurs during a ROLLBACK, we can no longer trust the pager
36121    ** cache. So call pager_error() on the way out to make any error
36122    ** persistent.
36123    */
36124    rc = pager_error(pPager, rc);
36125  }
36126  return rc;
36127}
36128
36129/*
36130** Return TRUE if the database file is opened read-only.  Return FALSE
36131** if the database is (in theory) writable.
36132*/
36133SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
36134  return pPager->readOnly;
36135}
36136
36137/*
36138** Return the number of references to the pager.
36139*/
36140SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
36141  return sqlite3PcacheRefCount(pPager->pPCache);
36142}
36143
36144/*
36145** Return the number of references to the specified page.
36146*/
36147SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
36148  return sqlite3PcachePageRefcount(pPage);
36149}
36150
36151#ifdef SQLITE_TEST
36152/*
36153** This routine is used for testing and analysis only.
36154*/
36155SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
36156  static int a[11];
36157  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
36158  a[1] = sqlite3PcachePagecount(pPager->pPCache);
36159  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
36160  a[3] = pPager->dbSizeValid ? (int) pPager->dbSize : -1;
36161  a[4] = pPager->state;
36162  a[5] = pPager->errCode;
36163  a[6] = pPager->nHit;
36164  a[7] = pPager->nMiss;
36165  a[8] = 0;  /* Used to be pPager->nOvfl */
36166  a[9] = pPager->nRead;
36167  a[10] = pPager->nWrite;
36168  return a;
36169}
36170#endif
36171
36172/*
36173** Return true if this is an in-memory pager.
36174*/
36175SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
36176  return MEMDB;
36177}
36178
36179/*
36180** Check that there are at least nSavepoint savepoints open. If there are
36181** currently less than nSavepoints open, then open one or more savepoints
36182** to make up the difference. If the number of savepoints is already
36183** equal to nSavepoint, then this function is a no-op.
36184**
36185** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
36186** occurs while opening the sub-journal file, then an IO error code is
36187** returned. Otherwise, SQLITE_OK.
36188*/
36189SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
36190  int rc = SQLITE_OK;                       /* Return code */
36191  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
36192
36193  if( nSavepoint>nCurrent && pPager->useJournal ){
36194    int ii;                                 /* Iterator variable */
36195    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
36196
36197    /* Either there is no active journal or the sub-journal is open or
36198    ** the journal is always stored in memory */
36199    assert( pPager->nSavepoint==0 || isOpen(pPager->sjfd) ||
36200            pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
36201
36202    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
36203    ** if the allocation fails. Otherwise, zero the new portion in case a
36204    ** malloc failure occurs while populating it in the for(...) loop below.
36205    */
36206    aNew = (PagerSavepoint *)sqlite3Realloc(
36207        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
36208    );
36209    if( !aNew ){
36210      return SQLITE_NOMEM;
36211    }
36212    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
36213    pPager->aSavepoint = aNew;
36214    pPager->nSavepoint = nSavepoint;
36215
36216    /* Populate the PagerSavepoint structures just allocated. */
36217    for(ii=nCurrent; ii<nSavepoint; ii++){
36218      assert( pPager->dbSizeValid );
36219      aNew[ii].nOrig = pPager->dbSize;
36220      if( isOpen(pPager->jfd) && ALWAYS(pPager->journalOff>0) ){
36221        aNew[ii].iOffset = pPager->journalOff;
36222      }else{
36223        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
36224      }
36225      aNew[ii].iSubRec = pPager->nSubRec;
36226      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
36227      if( !aNew[ii].pInSavepoint ){
36228        return SQLITE_NOMEM;
36229      }
36230    }
36231
36232    /* Open the sub-journal, if it is not already opened. */
36233    rc = openSubJournal(pPager);
36234    assertTruncateConstraint(pPager);
36235  }
36236
36237  return rc;
36238}
36239
36240/*
36241** This function is called to rollback or release (commit) a savepoint.
36242** The savepoint to release or rollback need not be the most recently
36243** created savepoint.
36244**
36245** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
36246** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
36247** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
36248** that have occurred since the specified savepoint was created.
36249**
36250** The savepoint to rollback or release is identified by parameter
36251** iSavepoint. A value of 0 means to operate on the outermost savepoint
36252** (the first created). A value of (Pager.nSavepoint-1) means operate
36253** on the most recently created savepoint. If iSavepoint is greater than
36254** (Pager.nSavepoint-1), then this function is a no-op.
36255**
36256** If a negative value is passed to this function, then the current
36257** transaction is rolled back. This is different to calling
36258** sqlite3PagerRollback() because this function does not terminate
36259** the transaction or unlock the database, it just restores the
36260** contents of the database to its original state.
36261**
36262** In any case, all savepoints with an index greater than iSavepoint
36263** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
36264** then savepoint iSavepoint is also destroyed.
36265**
36266** This function may return SQLITE_NOMEM if a memory allocation fails,
36267** or an IO error code if an IO error occurs while rolling back a
36268** savepoint. If no errors occur, SQLITE_OK is returned.
36269*/
36270SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
36271  int rc = SQLITE_OK;
36272
36273  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
36274  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
36275
36276  if( iSavepoint<pPager->nSavepoint ){
36277    int ii;            /* Iterator variable */
36278    int nNew;          /* Number of remaining savepoints after this op. */
36279
36280    /* Figure out how many savepoints will still be active after this
36281    ** operation. Store this value in nNew. Then free resources associated
36282    ** with any savepoints that are destroyed by this operation.
36283    */
36284    nNew = iSavepoint + (op==SAVEPOINT_ROLLBACK);
36285    for(ii=nNew; ii<pPager->nSavepoint; ii++){
36286      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
36287    }
36288    pPager->nSavepoint = nNew;
36289
36290    /* If this is a rollback operation, playback the specified savepoint.
36291    ** If this is a temp-file, it is possible that the journal file has
36292    ** not yet been opened. In this case there have been no changes to
36293    ** the database file, so the playback operation can be skipped.
36294    */
36295    if( op==SAVEPOINT_ROLLBACK && isOpen(pPager->jfd) ){
36296      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
36297      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
36298      assert(rc!=SQLITE_DONE);
36299    }
36300
36301    /* If this is a release of the outermost savepoint, truncate
36302    ** the sub-journal to zero bytes in size. */
36303    if( nNew==0 && op==SAVEPOINT_RELEASE && isOpen(pPager->sjfd) ){
36304      assert( rc==SQLITE_OK );
36305      rc = sqlite3OsTruncate(pPager->sjfd, 0);
36306      pPager->nSubRec = 0;
36307    }
36308  }
36309  return rc;
36310}
36311
36312/*
36313** Return the full pathname of the database file.
36314*/
36315SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
36316  return pPager->zFilename;
36317}
36318
36319/*
36320** Return the VFS structure for the pager.
36321*/
36322SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
36323  return pPager->pVfs;
36324}
36325
36326/*
36327** Return the file handle for the database file associated
36328** with the pager.  This might return NULL if the file has
36329** not yet been opened.
36330*/
36331SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
36332  return pPager->fd;
36333}
36334
36335/*
36336** Return the full pathname of the journal file.
36337*/
36338SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
36339  return pPager->zJournal;
36340}
36341
36342/*
36343** Return true if fsync() calls are disabled for this pager.  Return FALSE
36344** if fsync()s are executed normally.
36345*/
36346SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
36347  return pPager->noSync;
36348}
36349
36350#ifdef SQLITE_HAS_CODEC
36351/*
36352** Set or retrieve the codec for this pager
36353*/
36354static void sqlite3PagerSetCodec(
36355  Pager *pPager,
36356  void *(*xCodec)(void*,void*,Pgno,int),
36357  void (*xCodecSizeChng)(void*,int,int),
36358  void (*xCodecFree)(void*),
36359  void *pCodec
36360){
36361  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
36362  pPager->xCodec = pPager->memDb ? 0 : xCodec;
36363  pPager->xCodecSizeChng = xCodecSizeChng;
36364  pPager->xCodecFree = xCodecFree;
36365  pPager->pCodec = pCodec;
36366  pagerReportSize(pPager);
36367}
36368static void *sqlite3PagerGetCodec(Pager *pPager){
36369  return pPager->pCodec;
36370}
36371#endif
36372
36373#ifndef SQLITE_OMIT_AUTOVACUUM
36374/*
36375** Move the page pPg to location pgno in the file.
36376**
36377** There must be no references to the page previously located at
36378** pgno (which we call pPgOld) though that page is allowed to be
36379** in cache.  If the page previously located at pgno is not already
36380** in the rollback journal, it is not put there by by this routine.
36381**
36382** References to the page pPg remain valid. Updating any
36383** meta-data associated with pPg (i.e. data stored in the nExtra bytes
36384** allocated along with the page) is the responsibility of the caller.
36385**
36386** A transaction must be active when this routine is called. It used to be
36387** required that a statement transaction was not active, but this restriction
36388** has been removed (CREATE INDEX needs to move a page when a statement
36389** transaction is active).
36390**
36391** If the fourth argument, isCommit, is non-zero, then this page is being
36392** moved as part of a database reorganization just before the transaction
36393** is being committed. In this case, it is guaranteed that the database page
36394** pPg refers to will not be written to again within this transaction.
36395**
36396** This function may return SQLITE_NOMEM or an IO error code if an error
36397** occurs. Otherwise, it returns SQLITE_OK.
36398*/
36399SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
36400  PgHdr *pPgOld;               /* The page being overwritten. */
36401  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
36402  int rc;                      /* Return code */
36403  Pgno origPgno;               /* The original page number */
36404
36405  assert( pPg->nRef>0 );
36406
36407  /* In order to be able to rollback, an in-memory database must journal
36408  ** the page we are moving from.
36409  */
36410  if( MEMDB ){
36411    rc = sqlite3PagerWrite(pPg);
36412    if( rc ) return rc;
36413  }
36414
36415  /* If the page being moved is dirty and has not been saved by the latest
36416  ** savepoint, then save the current contents of the page into the
36417  ** sub-journal now. This is required to handle the following scenario:
36418  **
36419  **   BEGIN;
36420  **     <journal page X, then modify it in memory>
36421  **     SAVEPOINT one;
36422  **       <Move page X to location Y>
36423  **     ROLLBACK TO one;
36424  **
36425  ** If page X were not written to the sub-journal here, it would not
36426  ** be possible to restore its contents when the "ROLLBACK TO one"
36427  ** statement were is processed.
36428  **
36429  ** subjournalPage() may need to allocate space to store pPg->pgno into
36430  ** one or more savepoint bitvecs. This is the reason this function
36431  ** may return SQLITE_NOMEM.
36432  */
36433  if( pPg->flags&PGHDR_DIRTY
36434   && subjRequiresPage(pPg)
36435   && SQLITE_OK!=(rc = subjournalPage(pPg))
36436  ){
36437    return rc;
36438  }
36439
36440  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
36441      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
36442  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
36443
36444  /* If the journal needs to be sync()ed before page pPg->pgno can
36445  ** be written to, store pPg->pgno in local variable needSyncPgno.
36446  **
36447  ** If the isCommit flag is set, there is no need to remember that
36448  ** the journal needs to be sync()ed before database page pPg->pgno
36449  ** can be written to. The caller has already promised not to write to it.
36450  */
36451  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
36452    needSyncPgno = pPg->pgno;
36453    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
36454    assert( pPg->flags&PGHDR_DIRTY );
36455    assert( pPager->needSync );
36456  }
36457
36458  /* If the cache contains a page with page-number pgno, remove it
36459  ** from its hash chain. Also, if the PgHdr.needSync was set for
36460  ** page pgno before the 'move' operation, it needs to be retained
36461  ** for the page moved there.
36462  */
36463  pPg->flags &= ~PGHDR_NEED_SYNC;
36464  pPgOld = pager_lookup(pPager, pgno);
36465  assert( !pPgOld || pPgOld->nRef==1 );
36466  if( pPgOld ){
36467    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
36468    if( MEMDB ){
36469      /* Do not discard pages from an in-memory database since we might
36470      ** need to rollback later.  Just move the page out of the way. */
36471      assert( pPager->dbSizeValid );
36472      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
36473    }else{
36474      sqlite3PcacheDrop(pPgOld);
36475    }
36476  }
36477
36478  origPgno = pPg->pgno;
36479  sqlite3PcacheMove(pPg, pgno);
36480  sqlite3PcacheMakeDirty(pPg);
36481  pPager->dbModified = 1;
36482
36483  if( needSyncPgno ){
36484    /* If needSyncPgno is non-zero, then the journal file needs to be
36485    ** sync()ed before any data is written to database file page needSyncPgno.
36486    ** Currently, no such page exists in the page-cache and the
36487    ** "is journaled" bitvec flag has been set. This needs to be remedied by
36488    ** loading the page into the pager-cache and setting the PgHdr.needSync
36489    ** flag.
36490    **
36491    ** If the attempt to load the page into the page-cache fails, (due
36492    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
36493    ** array. Otherwise, if the page is loaded and written again in
36494    ** this transaction, it may be written to the database file before
36495    ** it is synced into the journal file. This way, it may end up in
36496    ** the journal file twice, but that is not a problem.
36497    **
36498    ** The sqlite3PagerGet() call may cause the journal to sync. So make
36499    ** sure the Pager.needSync flag is set too.
36500    */
36501    PgHdr *pPgHdr;
36502    assert( pPager->needSync );
36503    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
36504    if( rc!=SQLITE_OK ){
36505      if( needSyncPgno<=pPager->dbOrigSize ){
36506        assert( pPager->pTmpSpace!=0 );
36507        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
36508      }
36509      return rc;
36510    }
36511    pPager->needSync = 1;
36512    assert( pPager->noSync==0 && !MEMDB );
36513    pPgHdr->flags |= PGHDR_NEED_SYNC;
36514    sqlite3PcacheMakeDirty(pPgHdr);
36515    sqlite3PagerUnref(pPgHdr);
36516  }
36517
36518  /*
36519  ** For an in-memory database, make sure the original page continues
36520  ** to exist, in case the transaction needs to roll back.  Use pPgOld
36521  ** as the original page since it has already been allocated.
36522  */
36523  if( MEMDB ){
36524    sqlite3PcacheMove(pPgOld, origPgno);
36525    sqlite3PagerUnref(pPgOld);
36526  }
36527
36528  return SQLITE_OK;
36529}
36530#endif
36531
36532/*
36533** Return a pointer to the data for the specified page.
36534*/
36535SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
36536  assert( pPg->nRef>0 || pPg->pPager->memDb );
36537  return pPg->pData;
36538}
36539
36540/*
36541** Return a pointer to the Pager.nExtra bytes of "extra" space
36542** allocated along with the specified page.
36543*/
36544SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
36545  return pPg->pExtra;
36546}
36547
36548/*
36549** Get/set the locking-mode for this pager. Parameter eMode must be one
36550** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
36551** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
36552** the locking-mode is set to the value specified.
36553**
36554** The returned value is either PAGER_LOCKINGMODE_NORMAL or
36555** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
36556** locking-mode.
36557*/
36558SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
36559  assert( eMode==PAGER_LOCKINGMODE_QUERY
36560            || eMode==PAGER_LOCKINGMODE_NORMAL
36561            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
36562  assert( PAGER_LOCKINGMODE_QUERY<0 );
36563  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
36564  if( eMode>=0 && !pPager->tempFile ){
36565    pPager->exclusiveMode = (u8)eMode;
36566  }
36567  return (int)pPager->exclusiveMode;
36568}
36569
36570/*
36571** Get/set the journal-mode for this pager. Parameter eMode must be one of:
36572**
36573**    PAGER_JOURNALMODE_QUERY
36574**    PAGER_JOURNALMODE_DELETE
36575**    PAGER_JOURNALMODE_TRUNCATE
36576**    PAGER_JOURNALMODE_PERSIST
36577**    PAGER_JOURNALMODE_OFF
36578**    PAGER_JOURNALMODE_MEMORY
36579**
36580** If the parameter is not _QUERY, then the journal_mode is set to the
36581** value specified if the change is allowed.  The change is disallowed
36582** for the following reasons:
36583**
36584**   *  An in-memory database can only have its journal_mode set to _OFF
36585**      or _MEMORY.
36586**
36587**   *  The journal mode may not be changed while a transaction is active.
36588**
36589** The returned indicate the current (possibly updated) journal-mode.
36590*/
36591SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
36592  assert( eMode==PAGER_JOURNALMODE_QUERY
36593            || eMode==PAGER_JOURNALMODE_DELETE
36594            || eMode==PAGER_JOURNALMODE_TRUNCATE
36595            || eMode==PAGER_JOURNALMODE_PERSIST
36596            || eMode==PAGER_JOURNALMODE_OFF
36597            || eMode==PAGER_JOURNALMODE_MEMORY );
36598  assert( PAGER_JOURNALMODE_QUERY<0 );
36599  if( eMode>=0
36600   && (!MEMDB || eMode==PAGER_JOURNALMODE_MEMORY
36601              || eMode==PAGER_JOURNALMODE_OFF)
36602   && !pPager->dbModified
36603   && (!isOpen(pPager->jfd) || 0==pPager->journalOff)
36604  ){
36605    if( isOpen(pPager->jfd) ){
36606      sqlite3OsClose(pPager->jfd);
36607    }
36608    pPager->journalMode = (u8)eMode;
36609  }
36610  return (int)pPager->journalMode;
36611}
36612
36613/*
36614** Get/set the size-limit used for persistent journal files.
36615**
36616** Setting the size limit to -1 means no limit is enforced.
36617** An attempt to set a limit smaller than -1 is a no-op.
36618*/
36619SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
36620  if( iLimit>=-1 ){
36621    pPager->journalSizeLimit = iLimit;
36622  }
36623  return pPager->journalSizeLimit;
36624}
36625
36626/*
36627** Return a pointer to the pPager->pBackup variable. The backup module
36628** in backup.c maintains the content of this variable. This module
36629** uses it opaquely as an argument to sqlite3BackupRestart() and
36630** sqlite3BackupUpdate() only.
36631*/
36632SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
36633  return &pPager->pBackup;
36634}
36635
36636#endif /* SQLITE_OMIT_DISKIO */
36637
36638/************** End of pager.c ***********************************************/
36639/************** Begin file btmutex.c *****************************************/
36640/*
36641** 2007 August 27
36642**
36643** The author disclaims copyright to this source code.  In place of
36644** a legal notice, here is a blessing:
36645**
36646**    May you do good and not evil.
36647**    May you find forgiveness for yourself and forgive others.
36648**    May you share freely, never taking more than you give.
36649**
36650*************************************************************************
36651**
36652** This file contains code used to implement mutexes on Btree objects.
36653** This code really belongs in btree.c.  But btree.c is getting too
36654** big and we want to break it down some.  This packaged seemed like
36655** a good breakout.
36656*/
36657/************** Include btreeInt.h in the middle of btmutex.c ****************/
36658/************** Begin file btreeInt.h ****************************************/
36659/*
36660** 2004 April 6
36661**
36662** The author disclaims copyright to this source code.  In place of
36663** a legal notice, here is a blessing:
36664**
36665**    May you do good and not evil.
36666**    May you find forgiveness for yourself and forgive others.
36667**    May you share freely, never taking more than you give.
36668**
36669*************************************************************************
36670** This file implements a external (disk-based) database using BTrees.
36671** For a detailed discussion of BTrees, refer to
36672**
36673**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
36674**     "Sorting And Searching", pages 473-480. Addison-Wesley
36675**     Publishing Company, Reading, Massachusetts.
36676**
36677** The basic idea is that each page of the file contains N database
36678** entries and N+1 pointers to subpages.
36679**
36680**   ----------------------------------------------------------------
36681**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
36682**   ----------------------------------------------------------------
36683**
36684** All of the keys on the page that Ptr(0) points to have values less
36685** than Key(0).  All of the keys on page Ptr(1) and its subpages have
36686** values greater than Key(0) and less than Key(1).  All of the keys
36687** on Ptr(N) and its subpages have values greater than Key(N-1).  And
36688** so forth.
36689**
36690** Finding a particular key requires reading O(log(M)) pages from the
36691** disk where M is the number of entries in the tree.
36692**
36693** In this implementation, a single file can hold one or more separate
36694** BTrees.  Each BTree is identified by the index of its root page.  The
36695** key and data for any entry are combined to form the "payload".  A
36696** fixed amount of payload can be carried directly on the database
36697** page.  If the payload is larger than the preset amount then surplus
36698** bytes are stored on overflow pages.  The payload for an entry
36699** and the preceding pointer are combined to form a "Cell".  Each
36700** page has a small header which contains the Ptr(N) pointer and other
36701** information such as the size of key and data.
36702**
36703** FORMAT DETAILS
36704**
36705** The file is divided into pages.  The first page is called page 1,
36706** the second is page 2, and so forth.  A page number of zero indicates
36707** "no such page".  The page size can be any power of 2 between 512 and 32768.
36708** Each page can be either a btree page, a freelist page, an overflow
36709** page, or a pointer-map page.
36710**
36711** The first page is always a btree page.  The first 100 bytes of the first
36712** page contain a special header (the "file header") that describes the file.
36713** The format of the file header is as follows:
36714**
36715**   OFFSET   SIZE    DESCRIPTION
36716**      0      16     Header string: "SQLite format 3\000"
36717**     16       2     Page size in bytes.
36718**     18       1     File format write version
36719**     19       1     File format read version
36720**     20       1     Bytes of unused space at the end of each page
36721**     21       1     Max embedded payload fraction
36722**     22       1     Min embedded payload fraction
36723**     23       1     Min leaf payload fraction
36724**     24       4     File change counter
36725**     28       4     Reserved for future use
36726**     32       4     First freelist page
36727**     36       4     Number of freelist pages in the file
36728**     40      60     15 4-byte meta values passed to higher layers
36729**
36730**     40       4     Schema cookie
36731**     44       4     File format of schema layer
36732**     48       4     Size of page cache
36733**     52       4     Largest root-page (auto/incr_vacuum)
36734**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
36735**     60       4     User version
36736**     64       4     Incremental vacuum mode
36737**     68       4     unused
36738**     72       4     unused
36739**     76       4     unused
36740**
36741** All of the integer values are big-endian (most significant byte first).
36742**
36743** The file change counter is incremented when the database is changed
36744** This counter allows other processes to know when the file has changed
36745** and thus when they need to flush their cache.
36746**
36747** The max embedded payload fraction is the amount of the total usable
36748** space in a page that can be consumed by a single cell for standard
36749** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
36750** is to limit the maximum cell size so that at least 4 cells will fit
36751** on one page.  Thus the default max embedded payload fraction is 64.
36752**
36753** If the payload for a cell is larger than the max payload, then extra
36754** payload is spilled to overflow pages.  Once an overflow page is allocated,
36755** as many bytes as possible are moved into the overflow pages without letting
36756** the cell size drop below the min embedded payload fraction.
36757**
36758** The min leaf payload fraction is like the min embedded payload fraction
36759** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
36760** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
36761** not specified in the header.
36762**
36763** Each btree pages is divided into three sections:  The header, the
36764** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
36765** file header that occurs before the page header.
36766**
36767**      |----------------|
36768**      | file header    |   100 bytes.  Page 1 only.
36769**      |----------------|
36770**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
36771**      |----------------|
36772**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
36773**      | array          |   |  Grows downward
36774**      |                |   v
36775**      |----------------|
36776**      | unallocated    |
36777**      | space          |
36778**      |----------------|   ^  Grows upwards
36779**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
36780**      | area           |   |  and free space fragments.
36781**      |----------------|
36782**
36783** The page headers looks like this:
36784**
36785**   OFFSET   SIZE     DESCRIPTION
36786**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
36787**      1       2      byte offset to the first freeblock
36788**      3       2      number of cells on this page
36789**      5       2      first byte of the cell content area
36790**      7       1      number of fragmented free bytes
36791**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
36792**
36793** The flags define the format of this btree page.  The leaf flag means that
36794** this page has no children.  The zerodata flag means that this page carries
36795** only keys and no data.  The intkey flag means that the key is a integer
36796** which is stored in the key size entry of the cell header rather than in
36797** the payload area.
36798**
36799** The cell pointer array begins on the first byte after the page header.
36800** The cell pointer array contains zero or more 2-byte numbers which are
36801** offsets from the beginning of the page to the cell content in the cell
36802** content area.  The cell pointers occur in sorted order.  The system strives
36803** to keep free space after the last cell pointer so that new cells can
36804** be easily added without having to defragment the page.
36805**
36806** Cell content is stored at the very end of the page and grows toward the
36807** beginning of the page.
36808**
36809** Unused space within the cell content area is collected into a linked list of
36810** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
36811** to the first freeblock is given in the header.  Freeblocks occur in
36812** increasing order.  Because a freeblock must be at least 4 bytes in size,
36813** any group of 3 or fewer unused bytes in the cell content area cannot
36814** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
36815** a fragment.  The total number of bytes in all fragments is recorded.
36816** in the page header at offset 7.
36817**
36818**    SIZE    DESCRIPTION
36819**      2     Byte offset of the next freeblock
36820**      2     Bytes in this freeblock
36821**
36822** Cells are of variable length.  Cells are stored in the cell content area at
36823** the end of the page.  Pointers to the cells are in the cell pointer array
36824** that immediately follows the page header.  Cells is not necessarily
36825** contiguous or in order, but cell pointers are contiguous and in order.
36826**
36827** Cell content makes use of variable length integers.  A variable
36828** length integer is 1 to 9 bytes where the lower 7 bits of each
36829** byte are used.  The integer consists of all bytes that have bit 8 set and
36830** the first byte with bit 8 clear.  The most significant byte of the integer
36831** appears first.  A variable-length integer may not be more than 9 bytes long.
36832** As a special case, all 8 bytes of the 9th byte are used as data.  This
36833** allows a 64-bit integer to be encoded in 9 bytes.
36834**
36835**    0x00                      becomes  0x00000000
36836**    0x7f                      becomes  0x0000007f
36837**    0x81 0x00                 becomes  0x00000080
36838**    0x82 0x00                 becomes  0x00000100
36839**    0x80 0x7f                 becomes  0x0000007f
36840**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
36841**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
36842**
36843** Variable length integers are used for rowids and to hold the number of
36844** bytes of key and data in a btree cell.
36845**
36846** The content of a cell looks like this:
36847**
36848**    SIZE    DESCRIPTION
36849**      4     Page number of the left child. Omitted if leaf flag is set.
36850**     var    Number of bytes of data. Omitted if the zerodata flag is set.
36851**     var    Number of bytes of key. Or the key itself if intkey flag is set.
36852**      *     Payload
36853**      4     First page of the overflow chain.  Omitted if no overflow
36854**
36855** Overflow pages form a linked list.  Each page except the last is completely
36856** filled with data (pagesize - 4 bytes).  The last page can have as little
36857** as 1 byte of data.
36858**
36859**    SIZE    DESCRIPTION
36860**      4     Page number of next overflow page
36861**      *     Data
36862**
36863** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
36864** file header points to the first in a linked list of trunk page.  Each trunk
36865** page points to multiple leaf pages.  The content of a leaf page is
36866** unspecified.  A trunk page looks like this:
36867**
36868**    SIZE    DESCRIPTION
36869**      4     Page number of next trunk page
36870**      4     Number of leaf pointers on this page
36871**      *     zero or more pages numbers of leaves
36872*/
36873
36874
36875/* The following value is the maximum cell size assuming a maximum page
36876** size give above.
36877*/
36878#define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
36879
36880/* The maximum number of cells on a single page of the database.  This
36881** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
36882** plus 2 bytes for the index to the cell in the page header).  Such
36883** small cells will be rare, but they are possible.
36884*/
36885#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
36886
36887/* Forward declarations */
36888typedef struct MemPage MemPage;
36889typedef struct BtLock BtLock;
36890
36891/*
36892** This is a magic string that appears at the beginning of every
36893** SQLite database in order to identify the file as a real database.
36894**
36895** You can change this value at compile-time by specifying a
36896** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
36897** header must be exactly 16 bytes including the zero-terminator so
36898** the string itself should be 15 characters long.  If you change
36899** the header, then your custom library will not be able to read
36900** databases generated by the standard tools and the standard tools
36901** will not be able to read databases created by your custom library.
36902*/
36903#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
36904#  define SQLITE_FILE_HEADER "SQLite format 3"
36905#endif
36906
36907/*
36908** Page type flags.  An ORed combination of these flags appear as the
36909** first byte of on-disk image of every BTree page.
36910*/
36911#define PTF_INTKEY    0x01
36912#define PTF_ZERODATA  0x02
36913#define PTF_LEAFDATA  0x04
36914#define PTF_LEAF      0x08
36915
36916/*
36917** As each page of the file is loaded into memory, an instance of the following
36918** structure is appended and initialized to zero.  This structure stores
36919** information about the page that is decoded from the raw file page.
36920**
36921** The pParent field points back to the parent page.  This allows us to
36922** walk up the BTree from any leaf to the root.  Care must be taken to
36923** unref() the parent page pointer when this page is no longer referenced.
36924** The pageDestructor() routine handles that chore.
36925**
36926** Access to all fields of this structure is controlled by the mutex
36927** stored in MemPage.pBt->mutex.
36928*/
36929struct MemPage {
36930  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
36931  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
36932  u8 intKey;           /* True if intkey flag is set */
36933  u8 leaf;             /* True if leaf flag is set */
36934  u8 hasData;          /* True if this page stores data */
36935  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
36936  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
36937  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
36938  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
36939  u16 cellOffset;      /* Index in aData of first cell pointer */
36940  u16 nFree;           /* Number of free bytes on the page */
36941  u16 nCell;           /* Number of cells on this page, local and ovfl */
36942  u16 maskPage;        /* Mask for page offset */
36943  struct _OvflCell {   /* Cells that will not fit on aData[] */
36944    u8 *pCell;          /* Pointers to the body of the overflow cell */
36945    u16 idx;            /* Insert this cell before idx-th non-overflow cell */
36946  } aOvfl[5];
36947  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
36948  u8 *aData;           /* Pointer to disk image of the page data */
36949  DbPage *pDbPage;     /* Pager page handle */
36950  Pgno pgno;           /* Page number for this page */
36951};
36952
36953/*
36954** The in-memory image of a disk page has the auxiliary information appended
36955** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
36956** that extra information.
36957*/
36958#define EXTRA_SIZE sizeof(MemPage)
36959
36960/*
36961** A linked list of the following structures is stored at BtShared.pLock.
36962** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
36963** is opened on the table with root page BtShared.iTable. Locks are removed
36964** from this list when a transaction is committed or rolled back, or when
36965** a btree handle is closed.
36966*/
36967struct BtLock {
36968  Btree *pBtree;        /* Btree handle holding this lock */
36969  Pgno iTable;          /* Root page of table */
36970  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
36971  BtLock *pNext;        /* Next in BtShared.pLock list */
36972};
36973
36974/* Candidate values for BtLock.eLock */
36975#define READ_LOCK     1
36976#define WRITE_LOCK    2
36977
36978/* A Btree handle
36979**
36980** A database connection contains a pointer to an instance of
36981** this object for every database file that it has open.  This structure
36982** is opaque to the database connection.  The database connection cannot
36983** see the internals of this structure and only deals with pointers to
36984** this structure.
36985**
36986** For some database files, the same underlying database cache might be
36987** shared between multiple connections.  In that case, each connection
36988** has it own instance of this object.  But each instance of this object
36989** points to the same BtShared object.  The database cache and the
36990** schema associated with the database file are all contained within
36991** the BtShared object.
36992**
36993** All fields in this structure are accessed under sqlite3.mutex.
36994** The pBt pointer itself may not be changed while there exists cursors
36995** in the referenced BtShared that point back to this Btree since those
36996** cursors have to do go through this Btree to find their BtShared and
36997** they often do so without holding sqlite3.mutex.
36998*/
36999struct Btree {
37000  sqlite3 *db;       /* The database connection holding this btree */
37001  BtShared *pBt;     /* Sharable content of this btree */
37002  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
37003  u8 sharable;       /* True if we can share pBt with another db */
37004  u8 locked;         /* True if db currently has pBt locked */
37005  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
37006  int nBackup;       /* Number of backup operations reading this btree */
37007  Btree *pNext;      /* List of other sharable Btrees from the same db */
37008  Btree *pPrev;      /* Back pointer of the same list */
37009#ifndef SQLITE_OMIT_SHARED_CACHE
37010  BtLock lock;       /* Object used to lock page 1 */
37011#endif
37012};
37013
37014/*
37015** Btree.inTrans may take one of the following values.
37016**
37017** If the shared-data extension is enabled, there may be multiple users
37018** of the Btree structure. At most one of these may open a write transaction,
37019** but any number may have active read transactions.
37020*/
37021#define TRANS_NONE  0
37022#define TRANS_READ  1
37023#define TRANS_WRITE 2
37024
37025/*
37026** An instance of this object represents a single database file.
37027**
37028** A single database file can be in use as the same time by two
37029** or more database connections.  When two or more connections are
37030** sharing the same database file, each connection has it own
37031** private Btree object for the file and each of those Btrees points
37032** to this one BtShared object.  BtShared.nRef is the number of
37033** connections currently sharing this database file.
37034**
37035** Fields in this structure are accessed under the BtShared.mutex
37036** mutex, except for nRef and pNext which are accessed under the
37037** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
37038** may not be modified once it is initially set as long as nRef>0.
37039** The pSchema field may be set once under BtShared.mutex and
37040** thereafter is unchanged as long as nRef>0.
37041**
37042** isPending:
37043**
37044**   If a BtShared client fails to obtain a write-lock on a database
37045**   table (because there exists one or more read-locks on the table),
37046**   the shared-cache enters 'pending-lock' state and isPending is
37047**   set to true.
37048**
37049**   The shared-cache leaves the 'pending lock' state when either of
37050**   the following occur:
37051**
37052**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
37053**     2) The number of locks held by other connections drops to zero.
37054**
37055**   while in the 'pending-lock' state, no connection may start a new
37056**   transaction.
37057**
37058**   This feature is included to help prevent writer-starvation.
37059*/
37060struct BtShared {
37061  Pager *pPager;        /* The page cache */
37062  sqlite3 *db;          /* Database connection currently using this Btree */
37063  BtCursor *pCursor;    /* A list of all open cursors */
37064  MemPage *pPage1;      /* First page of the database */
37065  u8 readOnly;          /* True if the underlying file is readonly */
37066  u8 pageSizeFixed;     /* True if the page size can no longer be changed */
37067#ifndef SQLITE_OMIT_AUTOVACUUM
37068  u8 autoVacuum;        /* True if auto-vacuum is enabled */
37069  u8 incrVacuum;        /* True if incr-vacuum is enabled */
37070#endif
37071  u16 pageSize;         /* Total number of bytes on a page */
37072  u16 usableSize;       /* Number of usable bytes on each page */
37073  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
37074  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
37075  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
37076  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
37077  u8 inTransaction;     /* Transaction state */
37078  int nTransaction;     /* Number of open transactions (read + write) */
37079  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
37080  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
37081  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
37082  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
37083#ifndef SQLITE_OMIT_SHARED_CACHE
37084  int nRef;             /* Number of references to this structure */
37085  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
37086  BtLock *pLock;        /* List of locks held on this shared-btree struct */
37087  Btree *pWriter;       /* Btree with currently open write transaction */
37088  u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
37089  u8 isPending;         /* If waiting for read-locks to clear */
37090#endif
37091  u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
37092};
37093
37094/*
37095** An instance of the following structure is used to hold information
37096** about a cell.  The parseCellPtr() function fills in this structure
37097** based on information extract from the raw disk page.
37098*/
37099typedef struct CellInfo CellInfo;
37100struct CellInfo {
37101  u8 *pCell;     /* Pointer to the start of cell content */
37102  i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
37103  u32 nData;     /* Number of bytes of data */
37104  u32 nPayload;  /* Total amount of payload */
37105  u16 nHeader;   /* Size of the cell content header in bytes */
37106  u16 nLocal;    /* Amount of payload held locally */
37107  u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
37108  u16 nSize;     /* Size of the cell content on the main b-tree page */
37109};
37110
37111/*
37112** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
37113** this will be declared corrupt. This value is calculated based on a
37114** maximum database size of 2^31 pages a minimum fanout of 2 for a
37115** root-node and 3 for all other internal nodes.
37116**
37117** If a tree that appears to be taller than this is encountered, it is
37118** assumed that the database is corrupt.
37119*/
37120#define BTCURSOR_MAX_DEPTH 20
37121
37122/*
37123** A cursor is a pointer to a particular entry within a particular
37124** b-tree within a database file.
37125**
37126** The entry is identified by its MemPage and the index in
37127** MemPage.aCell[] of the entry.
37128**
37129** A single database file can shared by two more database connections,
37130** but cursors cannot be shared.  Each cursor is associated with a
37131** particular database connection identified BtCursor.pBtree.db.
37132**
37133** Fields in this structure are accessed under the BtShared.mutex
37134** found at self->pBt->mutex.
37135*/
37136struct BtCursor {
37137  Btree *pBtree;            /* The Btree to which this cursor belongs */
37138  BtShared *pBt;            /* The BtShared this cursor points to */
37139  BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
37140  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
37141  Pgno pgnoRoot;            /* The root page of this tree */
37142  sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
37143  CellInfo info;            /* A parse of the cell we are pointing at */
37144  u8 wrFlag;                /* True if writable */
37145  u8 atLast;                /* Cursor pointing to the last entry */
37146  u8 validNKey;             /* True if info.nKey is valid */
37147  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
37148  void *pKey;      /* Saved key that was cursor's last known position */
37149  i64 nKey;        /* Size of pKey, or last integer key */
37150  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
37151#ifndef SQLITE_OMIT_INCRBLOB
37152  u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
37153  Pgno *aOverflow;          /* Cache of overflow page locations */
37154#endif
37155  i16 iPage;                            /* Index of current page in apPage */
37156  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
37157  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
37158};
37159
37160/*
37161** Potential values for BtCursor.eState.
37162**
37163** CURSOR_VALID:
37164**   Cursor points to a valid entry. getPayload() etc. may be called.
37165**
37166** CURSOR_INVALID:
37167**   Cursor does not point to a valid entry. This can happen (for example)
37168**   because the table is empty or because BtreeCursorFirst() has not been
37169**   called.
37170**
37171** CURSOR_REQUIRESEEK:
37172**   The table that this cursor was opened on still exists, but has been
37173**   modified since the cursor was last used. The cursor position is saved
37174**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
37175**   this state, restoreCursorPosition() can be called to attempt to
37176**   seek the cursor to the saved position.
37177**
37178** CURSOR_FAULT:
37179**   A unrecoverable error (an I/O error or a malloc failure) has occurred
37180**   on a different connection that shares the BtShared cache with this
37181**   cursor.  The error has left the cache in an inconsistent state.
37182**   Do nothing else with this cursor.  Any attempt to use the cursor
37183**   should return the error code stored in BtCursor.skip
37184*/
37185#define CURSOR_INVALID           0
37186#define CURSOR_VALID             1
37187#define CURSOR_REQUIRESEEK       2
37188#define CURSOR_FAULT             3
37189
37190/*
37191** The database page the PENDING_BYTE occupies. This page is never used.
37192*/
37193# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
37194
37195/*
37196** These macros define the location of the pointer-map entry for a
37197** database page. The first argument to each is the number of usable
37198** bytes on each page of the database (often 1024). The second is the
37199** page number to look up in the pointer map.
37200**
37201** PTRMAP_PAGENO returns the database page number of the pointer-map
37202** page that stores the required pointer. PTRMAP_PTROFFSET returns
37203** the offset of the requested map entry.
37204**
37205** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
37206** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
37207** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
37208** this test.
37209*/
37210#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
37211#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
37212#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
37213
37214/*
37215** The pointer map is a lookup table that identifies the parent page for
37216** each child page in the database file.  The parent page is the page that
37217** contains a pointer to the child.  Every page in the database contains
37218** 0 or 1 parent pages.  (In this context 'database page' refers
37219** to any page that is not part of the pointer map itself.)  Each pointer map
37220** entry consists of a single byte 'type' and a 4 byte parent page number.
37221** The PTRMAP_XXX identifiers below are the valid types.
37222**
37223** The purpose of the pointer map is to facility moving pages from one
37224** position in the file to another as part of autovacuum.  When a page
37225** is moved, the pointer in its parent must be updated to point to the
37226** new location.  The pointer map is used to locate the parent page quickly.
37227**
37228** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
37229**                  used in this case.
37230**
37231** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
37232**                  is not used in this case.
37233**
37234** PTRMAP_OVERFLOW1: The database page is the first page in a list of
37235**                   overflow pages. The page number identifies the page that
37236**                   contains the cell with a pointer to this overflow page.
37237**
37238** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
37239**                   overflow pages. The page-number identifies the previous
37240**                   page in the overflow page list.
37241**
37242** PTRMAP_BTREE: The database page is a non-root btree page. The page number
37243**               identifies the parent page in the btree.
37244*/
37245#define PTRMAP_ROOTPAGE 1
37246#define PTRMAP_FREEPAGE 2
37247#define PTRMAP_OVERFLOW1 3
37248#define PTRMAP_OVERFLOW2 4
37249#define PTRMAP_BTREE 5
37250
37251/* A bunch of assert() statements to check the transaction state variables
37252** of handle p (type Btree*) are internally consistent.
37253*/
37254#define btreeIntegrity(p) \
37255  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
37256  assert( p->pBt->inTransaction>=p->inTrans );
37257
37258
37259/*
37260** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
37261** if the database supports auto-vacuum or not. Because it is used
37262** within an expression that is an argument to another macro
37263** (sqliteMallocRaw), it is not possible to use conditional compilation.
37264** So, this macro is defined instead.
37265*/
37266#ifndef SQLITE_OMIT_AUTOVACUUM
37267#define ISAUTOVACUUM (pBt->autoVacuum)
37268#else
37269#define ISAUTOVACUUM 0
37270#endif
37271
37272
37273/*
37274** This structure is passed around through all the sanity checking routines
37275** in order to keep track of some global state information.
37276*/
37277typedef struct IntegrityCk IntegrityCk;
37278struct IntegrityCk {
37279  BtShared *pBt;    /* The tree being checked out */
37280  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
37281  Pgno nPage;       /* Number of pages in the database */
37282  int *anRef;       /* Number of times each page is referenced */
37283  int mxErr;        /* Stop accumulating errors when this reaches zero */
37284  int nErr;         /* Number of messages written to zErrMsg so far */
37285  int mallocFailed; /* A memory allocation error has occurred */
37286  StrAccum errMsg;  /* Accumulate the error message text here */
37287};
37288
37289/*
37290** Read or write a two- and four-byte big-endian integer values.
37291*/
37292#define get2byte(x)   ((x)[0]<<8 | (x)[1])
37293#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
37294#define get4byte sqlite3Get4byte
37295#define put4byte sqlite3Put4byte
37296
37297/************** End of btreeInt.h ********************************************/
37298/************** Continuing where we left off in btmutex.c ********************/
37299#ifndef SQLITE_OMIT_SHARED_CACHE
37300#if SQLITE_THREADSAFE
37301
37302/*
37303** Obtain the BtShared mutex associated with B-Tree handle p. Also,
37304** set BtShared.db to the database handle associated with p and the
37305** p->locked boolean to true.
37306*/
37307static void lockBtreeMutex(Btree *p){
37308  assert( p->locked==0 );
37309  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
37310  assert( sqlite3_mutex_held(p->db->mutex) );
37311
37312  sqlite3_mutex_enter(p->pBt->mutex);
37313  p->pBt->db = p->db;
37314  p->locked = 1;
37315}
37316
37317/*
37318** Release the BtShared mutex associated with B-Tree handle p and
37319** clear the p->locked boolean.
37320*/
37321static void unlockBtreeMutex(Btree *p){
37322  assert( p->locked==1 );
37323  assert( sqlite3_mutex_held(p->pBt->mutex) );
37324  assert( sqlite3_mutex_held(p->db->mutex) );
37325  assert( p->db==p->pBt->db );
37326
37327  sqlite3_mutex_leave(p->pBt->mutex);
37328  p->locked = 0;
37329}
37330
37331/*
37332** Enter a mutex on the given BTree object.
37333**
37334** If the object is not sharable, then no mutex is ever required
37335** and this routine is a no-op.  The underlying mutex is non-recursive.
37336** But we keep a reference count in Btree.wantToLock so the behavior
37337** of this interface is recursive.
37338**
37339** To avoid deadlocks, multiple Btrees are locked in the same order
37340** by all database connections.  The p->pNext is a list of other
37341** Btrees belonging to the same database connection as the p Btree
37342** which need to be locked after p.  If we cannot get a lock on
37343** p, then first unlock all of the others on p->pNext, then wait
37344** for the lock to become available on p, then relock all of the
37345** subsequent Btrees that desire a lock.
37346*/
37347SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
37348  Btree *pLater;
37349
37350  /* Some basic sanity checking on the Btree.  The list of Btrees
37351  ** connected by pNext and pPrev should be in sorted order by
37352  ** Btree.pBt value. All elements of the list should belong to
37353  ** the same connection. Only shared Btrees are on the list. */
37354  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
37355  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
37356  assert( p->pNext==0 || p->pNext->db==p->db );
37357  assert( p->pPrev==0 || p->pPrev->db==p->db );
37358  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
37359
37360  /* Check for locking consistency */
37361  assert( !p->locked || p->wantToLock>0 );
37362  assert( p->sharable || p->wantToLock==0 );
37363
37364  /* We should already hold a lock on the database connection */
37365  assert( sqlite3_mutex_held(p->db->mutex) );
37366
37367  /* Unless the database is sharable and unlocked, then BtShared.db
37368  ** should already be set correctly. */
37369  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
37370
37371  if( !p->sharable ) return;
37372  p->wantToLock++;
37373  if( p->locked ) return;
37374
37375  /* In most cases, we should be able to acquire the lock we
37376  ** want without having to go throught the ascending lock
37377  ** procedure that follows.  Just be sure not to block.
37378  */
37379  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
37380    p->pBt->db = p->db;
37381    p->locked = 1;
37382    return;
37383  }
37384
37385  /* To avoid deadlock, first release all locks with a larger
37386  ** BtShared address.  Then acquire our lock.  Then reacquire
37387  ** the other BtShared locks that we used to hold in ascending
37388  ** order.
37389  */
37390  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
37391    assert( pLater->sharable );
37392    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
37393    assert( !pLater->locked || pLater->wantToLock>0 );
37394    if( pLater->locked ){
37395      unlockBtreeMutex(pLater);
37396    }
37397  }
37398  lockBtreeMutex(p);
37399  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
37400    if( pLater->wantToLock ){
37401      lockBtreeMutex(pLater);
37402    }
37403  }
37404}
37405
37406/*
37407** Exit the recursive mutex on a Btree.
37408*/
37409SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
37410  if( p->sharable ){
37411    assert( p->wantToLock>0 );
37412    p->wantToLock--;
37413    if( p->wantToLock==0 ){
37414      unlockBtreeMutex(p);
37415    }
37416  }
37417}
37418
37419#ifndef NDEBUG
37420/*
37421** Return true if the BtShared mutex is held on the btree, or if the
37422** B-Tree is not marked as sharable.
37423**
37424** This routine is used only from within assert() statements.
37425*/
37426SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
37427  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
37428  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
37429  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
37430  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
37431
37432  return (p->sharable==0 || p->locked);
37433}
37434#endif
37435
37436
37437#ifndef SQLITE_OMIT_INCRBLOB
37438/*
37439** Enter and leave a mutex on a Btree given a cursor owned by that
37440** Btree.  These entry points are used by incremental I/O and can be
37441** omitted if that module is not used.
37442*/
37443SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
37444  sqlite3BtreeEnter(pCur->pBtree);
37445}
37446SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
37447  sqlite3BtreeLeave(pCur->pBtree);
37448}
37449#endif /* SQLITE_OMIT_INCRBLOB */
37450
37451
37452/*
37453** Enter the mutex on every Btree associated with a database
37454** connection.  This is needed (for example) prior to parsing
37455** a statement since we will be comparing table and column names
37456** against all schemas and we do not want those schemas being
37457** reset out from under us.
37458**
37459** There is a corresponding leave-all procedures.
37460**
37461** Enter the mutexes in accending order by BtShared pointer address
37462** to avoid the possibility of deadlock when two threads with
37463** two or more btrees in common both try to lock all their btrees
37464** at the same instant.
37465*/
37466SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
37467  int i;
37468  Btree *p, *pLater;
37469  assert( sqlite3_mutex_held(db->mutex) );
37470  for(i=0; i<db->nDb; i++){
37471    p = db->aDb[i].pBt;
37472    assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
37473    if( p && p->sharable ){
37474      p->wantToLock++;
37475      if( !p->locked ){
37476        assert( p->wantToLock==1 );
37477        while( p->pPrev ) p = p->pPrev;
37478        /* Reason for ALWAYS:  There must be at least on unlocked Btree in
37479        ** the chain.  Otherwise the !p->locked test above would have failed */
37480        while( p->locked && ALWAYS(p->pNext) ) p = p->pNext;
37481        for(pLater = p->pNext; pLater; pLater=pLater->pNext){
37482          if( pLater->locked ){
37483            unlockBtreeMutex(pLater);
37484          }
37485        }
37486        while( p ){
37487          lockBtreeMutex(p);
37488          p = p->pNext;
37489        }
37490      }
37491    }
37492  }
37493}
37494SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
37495  int i;
37496  Btree *p;
37497  assert( sqlite3_mutex_held(db->mutex) );
37498  for(i=0; i<db->nDb; i++){
37499    p = db->aDb[i].pBt;
37500    if( p && p->sharable ){
37501      assert( p->wantToLock>0 );
37502      p->wantToLock--;
37503      if( p->wantToLock==0 ){
37504        unlockBtreeMutex(p);
37505      }
37506    }
37507  }
37508}
37509
37510#ifndef NDEBUG
37511/*
37512** Return true if the current thread holds the database connection
37513** mutex and all required BtShared mutexes.
37514**
37515** This routine is used inside assert() statements only.
37516*/
37517SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
37518  int i;
37519  if( !sqlite3_mutex_held(db->mutex) ){
37520    return 0;
37521  }
37522  for(i=0; i<db->nDb; i++){
37523    Btree *p;
37524    p = db->aDb[i].pBt;
37525    if( p && p->sharable &&
37526         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
37527      return 0;
37528    }
37529  }
37530  return 1;
37531}
37532#endif /* NDEBUG */
37533
37534/*
37535** Add a new Btree pointer to a BtreeMutexArray.
37536** if the pointer can possibly be shared with
37537** another database connection.
37538**
37539** The pointers are kept in sorted order by pBtree->pBt.  That
37540** way when we go to enter all the mutexes, we can enter them
37541** in order without every having to backup and retry and without
37542** worrying about deadlock.
37543**
37544** The number of shared btrees will always be small (usually 0 or 1)
37545** so an insertion sort is an adequate algorithm here.
37546*/
37547SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
37548  int i, j;
37549  BtShared *pBt;
37550  if( pBtree==0 || pBtree->sharable==0 ) return;
37551#ifndef NDEBUG
37552  {
37553    for(i=0; i<pArray->nMutex; i++){
37554      assert( pArray->aBtree[i]!=pBtree );
37555    }
37556  }
37557#endif
37558  assert( pArray->nMutex>=0 );
37559  assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
37560  pBt = pBtree->pBt;
37561  for(i=0; i<pArray->nMutex; i++){
37562    assert( pArray->aBtree[i]!=pBtree );
37563    if( pArray->aBtree[i]->pBt>pBt ){
37564      for(j=pArray->nMutex; j>i; j--){
37565        pArray->aBtree[j] = pArray->aBtree[j-1];
37566      }
37567      pArray->aBtree[i] = pBtree;
37568      pArray->nMutex++;
37569      return;
37570    }
37571  }
37572  pArray->aBtree[pArray->nMutex++] = pBtree;
37573}
37574
37575/*
37576** Enter the mutex of every btree in the array.  This routine is
37577** called at the beginning of sqlite3VdbeExec().  The mutexes are
37578** exited at the end of the same function.
37579*/
37580SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
37581  int i;
37582  for(i=0; i<pArray->nMutex; i++){
37583    Btree *p = pArray->aBtree[i];
37584    /* Some basic sanity checking */
37585    assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
37586    assert( !p->locked || p->wantToLock>0 );
37587
37588    /* We should already hold a lock on the database connection */
37589    assert( sqlite3_mutex_held(p->db->mutex) );
37590
37591    /* The Btree is sharable because only sharable Btrees are entered
37592    ** into the array in the first place. */
37593    assert( p->sharable );
37594
37595    p->wantToLock++;
37596    if( !p->locked ){
37597      lockBtreeMutex(p);
37598    }
37599  }
37600}
37601
37602/*
37603** Leave the mutex of every btree in the group.
37604*/
37605SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
37606  int i;
37607  for(i=0; i<pArray->nMutex; i++){
37608    Btree *p = pArray->aBtree[i];
37609    /* Some basic sanity checking */
37610    assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
37611    assert( p->locked );
37612    assert( p->wantToLock>0 );
37613
37614    /* We should already hold a lock on the database connection */
37615    assert( sqlite3_mutex_held(p->db->mutex) );
37616
37617    p->wantToLock--;
37618    if( p->wantToLock==0 ){
37619      unlockBtreeMutex(p);
37620    }
37621  }
37622}
37623
37624#else
37625SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
37626  p->pBt->db = p->db;
37627}
37628SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
37629  int i;
37630  for(i=0; i<db->nDb; i++){
37631    Btree *p = db->aDb[i].pBt;
37632    if( p ){
37633      p->pBt->db = p->db;
37634    }
37635  }
37636}
37637#endif /* if SQLITE_THREADSAFE */
37638#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
37639
37640/************** End of btmutex.c *********************************************/
37641/************** Begin file btree.c *******************************************/
37642/*
37643** 2004 April 6
37644**
37645** The author disclaims copyright to this source code.  In place of
37646** a legal notice, here is a blessing:
37647**
37648**    May you do good and not evil.
37649**    May you find forgiveness for yourself and forgive others.
37650**    May you share freely, never taking more than you give.
37651**
37652*************************************************************************
37653** This file implements a external (disk-based) database using BTrees.
37654** See the header comment on "btreeInt.h" for additional information.
37655** Including a description of file format and an overview of operation.
37656*/
37657
37658/*
37659** The header string that appears at the beginning of every
37660** SQLite database.
37661*/
37662static const char zMagicHeader[] = SQLITE_FILE_HEADER;
37663
37664/*
37665** Set this global variable to 1 to enable tracing using the TRACE
37666** macro.
37667*/
37668#if 0
37669int sqlite3BtreeTrace=1;  /* True to enable tracing */
37670# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
37671#else
37672# define TRACE(X)
37673#endif
37674
37675
37676
37677#ifndef SQLITE_OMIT_SHARED_CACHE
37678/*
37679** A list of BtShared objects that are eligible for participation
37680** in shared cache.  This variable has file scope during normal builds,
37681** but the test harness needs to access it so we make it global for
37682** test builds.
37683**
37684** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
37685*/
37686#ifdef SQLITE_TEST
37687SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
37688#else
37689static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
37690#endif
37691#endif /* SQLITE_OMIT_SHARED_CACHE */
37692
37693#ifndef SQLITE_OMIT_SHARED_CACHE
37694/*
37695** Enable or disable the shared pager and schema features.
37696**
37697** This routine has no effect on existing database connections.
37698** The shared cache setting effects only future calls to
37699** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
37700*/
37701SQLITE_API int sqlite3_enable_shared_cache(int enable){
37702  sqlite3GlobalConfig.sharedCacheEnabled = enable;
37703  return SQLITE_OK;
37704}
37705#endif
37706
37707
37708
37709#ifdef SQLITE_OMIT_SHARED_CACHE
37710  /*
37711  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
37712  ** and clearAllSharedCacheTableLocks()
37713  ** manipulate entries in the BtShared.pLock linked list used to store
37714  ** shared-cache table level locks. If the library is compiled with the
37715  ** shared-cache feature disabled, then there is only ever one user
37716  ** of each BtShared structure and so this locking is not necessary.
37717  ** So define the lock related functions as no-ops.
37718  */
37719  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
37720  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
37721  #define clearAllSharedCacheTableLocks(a)
37722  #define downgradeAllSharedCacheTableLocks(a)
37723  #define hasSharedCacheTableLock(a,b,c,d) 1
37724  #define hasReadConflicts(a, b) 0
37725#endif
37726
37727#ifndef SQLITE_OMIT_SHARED_CACHE
37728
37729#ifdef SQLITE_DEBUG
37730/*
37731**** This function is only used as part of an assert() statement. ***
37732**
37733** Check to see if pBtree holds the required locks to read or write to the
37734** table with root page iRoot.   Return 1 if it does and 0 if not.
37735**
37736** For example, when writing to a table with root-page iRoot via
37737** Btree connection pBtree:
37738**
37739**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
37740**
37741** When writing to an index that resides in a sharable database, the
37742** caller should have first obtained a lock specifying the root page of
37743** the corresponding table. This makes things a bit more complicated,
37744** as this module treats each table as a separate structure. To determine
37745** the table corresponding to the index being written, this
37746** function has to search through the database schema.
37747**
37748** Instead of a lock on the table/index rooted at page iRoot, the caller may
37749** hold a write-lock on the schema table (root page 1). This is also
37750** acceptable.
37751*/
37752static int hasSharedCacheTableLock(
37753  Btree *pBtree,         /* Handle that must hold lock */
37754  Pgno iRoot,            /* Root page of b-tree */
37755  int isIndex,           /* True if iRoot is the root of an index b-tree */
37756  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
37757){
37758  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
37759  Pgno iTab = 0;
37760  BtLock *pLock;
37761
37762  /* If this database is not shareable, or if the client is reading
37763  ** and has the read-uncommitted flag set, then no lock is required.
37764  ** Return true immediately.
37765  */
37766  if( (pBtree->sharable==0)
37767   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
37768  ){
37769    return 1;
37770  }
37771
37772  /* If the client is reading  or writing an index and the schema is
37773  ** not loaded, then it is too difficult to actually check to see if
37774  ** the correct locks are held.  So do not bother - just return true.
37775  ** This case does not come up very often anyhow.
37776  */
37777  if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
37778    return 1;
37779  }
37780
37781  /* Figure out the root-page that the lock should be held on. For table
37782  ** b-trees, this is just the root page of the b-tree being read or
37783  ** written. For index b-trees, it is the root page of the associated
37784  ** table.  */
37785  if( isIndex ){
37786    HashElem *p;
37787    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
37788      Index *pIdx = (Index *)sqliteHashData(p);
37789      if( pIdx->tnum==(int)iRoot ){
37790        iTab = pIdx->pTable->tnum;
37791      }
37792    }
37793  }else{
37794    iTab = iRoot;
37795  }
37796
37797  /* Search for the required lock. Either a write-lock on root-page iTab, a
37798  ** write-lock on the schema table, or (if the client is reading) a
37799  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
37800  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
37801    if( pLock->pBtree==pBtree
37802     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
37803     && pLock->eLock>=eLockType
37804    ){
37805      return 1;
37806    }
37807  }
37808
37809  /* Failed to find the required lock. */
37810  return 0;
37811}
37812#endif /* SQLITE_DEBUG */
37813
37814#ifdef SQLITE_DEBUG
37815/*
37816**** This function may be used as part of assert() statements only. ****
37817**
37818** Return true if it would be illegal for pBtree to write into the
37819** table or index rooted at iRoot because other shared connections are
37820** simultaneously reading that same table or index.
37821**
37822** It is illegal for pBtree to write if some other Btree object that
37823** shares the same BtShared object is currently reading or writing
37824** the iRoot table.  Except, if the other Btree object has the
37825** read-uncommitted flag set, then it is OK for the other object to
37826** have a read cursor.
37827**
37828** For example, before writing to any part of the table or index
37829** rooted at page iRoot, one should call:
37830**
37831**    assert( !hasReadConflicts(pBtree, iRoot) );
37832*/
37833static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
37834  BtCursor *p;
37835  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
37836    if( p->pgnoRoot==iRoot
37837     && p->pBtree!=pBtree
37838     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
37839    ){
37840      return 1;
37841    }
37842  }
37843  return 0;
37844}
37845#endif    /* #ifdef SQLITE_DEBUG */
37846
37847/*
37848** Query to see if Btree handle p may obtain a lock of type eLock
37849** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
37850** SQLITE_OK if the lock may be obtained (by calling
37851** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
37852*/
37853static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
37854  BtShared *pBt = p->pBt;
37855  BtLock *pIter;
37856
37857  assert( sqlite3BtreeHoldsMutex(p) );
37858  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
37859  assert( p->db!=0 );
37860  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
37861
37862  /* If requesting a write-lock, then the Btree must have an open write
37863  ** transaction on this file. And, obviously, for this to be so there
37864  ** must be an open write transaction on the file itself.
37865  */
37866  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
37867  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
37868
37869  /* This routine is a no-op if the shared-cache is not enabled */
37870  if( !p->sharable ){
37871    return SQLITE_OK;
37872  }
37873
37874  /* If some other connection is holding an exclusive lock, the
37875  ** requested lock may not be obtained.
37876  */
37877  if( pBt->pWriter!=p && pBt->isExclusive ){
37878    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
37879    return SQLITE_LOCKED_SHAREDCACHE;
37880  }
37881
37882  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
37883    /* The condition (pIter->eLock!=eLock) in the following if(...)
37884    ** statement is a simplification of:
37885    **
37886    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
37887    **
37888    ** since we know that if eLock==WRITE_LOCK, then no other connection
37889    ** may hold a WRITE_LOCK on any table in this file (since there can
37890    ** only be a single writer).
37891    */
37892    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
37893    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
37894    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
37895      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
37896      if( eLock==WRITE_LOCK ){
37897        assert( p==pBt->pWriter );
37898        pBt->isPending = 1;
37899      }
37900      return SQLITE_LOCKED_SHAREDCACHE;
37901    }
37902  }
37903  return SQLITE_OK;
37904}
37905#endif /* !SQLITE_OMIT_SHARED_CACHE */
37906
37907#ifndef SQLITE_OMIT_SHARED_CACHE
37908/*
37909** Add a lock on the table with root-page iTable to the shared-btree used
37910** by Btree handle p. Parameter eLock must be either READ_LOCK or
37911** WRITE_LOCK.
37912**
37913** This function assumes the following:
37914**
37915**   (a) The specified Btree object p is connected to a sharable
37916**       database (one with the BtShared.sharable flag set), and
37917**
37918**   (b) No other Btree objects hold a lock that conflicts
37919**       with the requested lock (i.e. querySharedCacheTableLock() has
37920**       already been called and returned SQLITE_OK).
37921**
37922** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
37923** is returned if a malloc attempt fails.
37924*/
37925static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
37926  BtShared *pBt = p->pBt;
37927  BtLock *pLock = 0;
37928  BtLock *pIter;
37929
37930  assert( sqlite3BtreeHoldsMutex(p) );
37931  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
37932  assert( p->db!=0 );
37933
37934  /* A connection with the read-uncommitted flag set will never try to
37935  ** obtain a read-lock using this function. The only read-lock obtained
37936  ** by a connection in read-uncommitted mode is on the sqlite_master
37937  ** table, and that lock is obtained in BtreeBeginTrans().  */
37938  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
37939
37940  /* This function should only be called on a sharable b-tree after it
37941  ** has been determined that no other b-tree holds a conflicting lock.  */
37942  assert( p->sharable );
37943  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
37944
37945  /* First search the list for an existing lock on this table. */
37946  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
37947    if( pIter->iTable==iTable && pIter->pBtree==p ){
37948      pLock = pIter;
37949      break;
37950    }
37951  }
37952
37953  /* If the above search did not find a BtLock struct associating Btree p
37954  ** with table iTable, allocate one and link it into the list.
37955  */
37956  if( !pLock ){
37957    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
37958    if( !pLock ){
37959      return SQLITE_NOMEM;
37960    }
37961    pLock->iTable = iTable;
37962    pLock->pBtree = p;
37963    pLock->pNext = pBt->pLock;
37964    pBt->pLock = pLock;
37965  }
37966
37967  /* Set the BtLock.eLock variable to the maximum of the current lock
37968  ** and the requested lock. This means if a write-lock was already held
37969  ** and a read-lock requested, we don't incorrectly downgrade the lock.
37970  */
37971  assert( WRITE_LOCK>READ_LOCK );
37972  if( eLock>pLock->eLock ){
37973    pLock->eLock = eLock;
37974  }
37975
37976  return SQLITE_OK;
37977}
37978#endif /* !SQLITE_OMIT_SHARED_CACHE */
37979
37980#ifndef SQLITE_OMIT_SHARED_CACHE
37981/*
37982** Release all the table locks (locks obtained via calls to
37983** the setSharedCacheTableLock() procedure) held by Btree object p.
37984**
37985** This function assumes that Btree p has an open read or write
37986** transaction. If it does not, then the BtShared.isPending variable
37987** may be incorrectly cleared.
37988*/
37989static void clearAllSharedCacheTableLocks(Btree *p){
37990  BtShared *pBt = p->pBt;
37991  BtLock **ppIter = &pBt->pLock;
37992
37993  assert( sqlite3BtreeHoldsMutex(p) );
37994  assert( p->sharable || 0==*ppIter );
37995  assert( p->inTrans>0 );
37996
37997  while( *ppIter ){
37998    BtLock *pLock = *ppIter;
37999    assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
38000    assert( pLock->pBtree->inTrans>=pLock->eLock );
38001    if( pLock->pBtree==p ){
38002      *ppIter = pLock->pNext;
38003      assert( pLock->iTable!=1 || pLock==&p->lock );
38004      if( pLock->iTable!=1 ){
38005        sqlite3_free(pLock);
38006      }
38007    }else{
38008      ppIter = &pLock->pNext;
38009    }
38010  }
38011
38012  assert( pBt->isPending==0 || pBt->pWriter );
38013  if( pBt->pWriter==p ){
38014    pBt->pWriter = 0;
38015    pBt->isExclusive = 0;
38016    pBt->isPending = 0;
38017  }else if( pBt->nTransaction==2 ){
38018    /* This function is called when Btree p is concluding its
38019    ** transaction. If there currently exists a writer, and p is not
38020    ** that writer, then the number of locks held by connections other
38021    ** than the writer must be about to drop to zero. In this case
38022    ** set the isPending flag to 0.
38023    **
38024    ** If there is not currently a writer, then BtShared.isPending must
38025    ** be zero already. So this next line is harmless in that case.
38026    */
38027    pBt->isPending = 0;
38028  }
38029}
38030
38031/*
38032** This function changes all write-locks held by Btree p into read-locks.
38033*/
38034static void downgradeAllSharedCacheTableLocks(Btree *p){
38035  BtShared *pBt = p->pBt;
38036  if( pBt->pWriter==p ){
38037    BtLock *pLock;
38038    pBt->pWriter = 0;
38039    pBt->isExclusive = 0;
38040    pBt->isPending = 0;
38041    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
38042      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
38043      pLock->eLock = READ_LOCK;
38044    }
38045  }
38046}
38047
38048#endif /* SQLITE_OMIT_SHARED_CACHE */
38049
38050static void releasePage(MemPage *pPage);  /* Forward reference */
38051
38052/*
38053***** This routine is used inside of assert() only ****
38054**
38055** Verify that the cursor holds the mutex on its BtShared
38056*/
38057#ifdef SQLITE_DEBUG
38058static int cursorHoldsMutex(BtCursor *p){
38059  return sqlite3_mutex_held(p->pBt->mutex);
38060}
38061#endif
38062
38063
38064#ifndef SQLITE_OMIT_INCRBLOB
38065/*
38066** Invalidate the overflow page-list cache for cursor pCur, if any.
38067*/
38068static void invalidateOverflowCache(BtCursor *pCur){
38069  assert( cursorHoldsMutex(pCur) );
38070  sqlite3_free(pCur->aOverflow);
38071  pCur->aOverflow = 0;
38072}
38073
38074/*
38075** Invalidate the overflow page-list cache for all cursors opened
38076** on the shared btree structure pBt.
38077*/
38078static void invalidateAllOverflowCache(BtShared *pBt){
38079  BtCursor *p;
38080  assert( sqlite3_mutex_held(pBt->mutex) );
38081  for(p=pBt->pCursor; p; p=p->pNext){
38082    invalidateOverflowCache(p);
38083  }
38084}
38085
38086/*
38087** This function is called before modifying the contents of a table
38088** to invalidate any incrblob cursors that are open on the
38089** row or one of the rows being modified.
38090**
38091** If argument isClearTable is true, then the entire contents of the
38092** table is about to be deleted. In this case invalidate all incrblob
38093** cursors open on any row within the table with root-page pgnoRoot.
38094**
38095** Otherwise, if argument isClearTable is false, then the row with
38096** rowid iRow is being replaced or deleted. In this case invalidate
38097** only those incrblob cursors open on that specific row.
38098*/
38099static void invalidateIncrblobCursors(
38100  Btree *pBtree,          /* The database file to check */
38101  i64 iRow,               /* The rowid that might be changing */
38102  int isClearTable        /* True if all rows are being deleted */
38103){
38104  BtCursor *p;
38105  BtShared *pBt = pBtree->pBt;
38106  assert( sqlite3BtreeHoldsMutex(pBtree) );
38107  for(p=pBt->pCursor; p; p=p->pNext){
38108    if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
38109      p->eState = CURSOR_INVALID;
38110    }
38111  }
38112}
38113
38114#else
38115  /* Stub functions when INCRBLOB is omitted */
38116  #define invalidateOverflowCache(x)
38117  #define invalidateAllOverflowCache(x)
38118  #define invalidateIncrblobCursors(x,y,z)
38119#endif /* SQLITE_OMIT_INCRBLOB */
38120
38121/*
38122** Set bit pgno of the BtShared.pHasContent bitvec. This is called
38123** when a page that previously contained data becomes a free-list leaf
38124** page.
38125**
38126** The BtShared.pHasContent bitvec exists to work around an obscure
38127** bug caused by the interaction of two useful IO optimizations surrounding
38128** free-list leaf pages:
38129**
38130**   1) When all data is deleted from a page and the page becomes
38131**      a free-list leaf page, the page is not written to the database
38132**      (as free-list leaf pages contain no meaningful data). Sometimes
38133**      such a page is not even journalled (as it will not be modified,
38134**      why bother journalling it?).
38135**
38136**   2) When a free-list leaf page is reused, its content is not read
38137**      from the database or written to the journal file (why should it
38138**      be, if it is not at all meaningful?).
38139**
38140** By themselves, these optimizations work fine and provide a handy
38141** performance boost to bulk delete or insert operations. However, if
38142** a page is moved to the free-list and then reused within the same
38143** transaction, a problem comes up. If the page is not journalled when
38144** it is moved to the free-list and it is also not journalled when it
38145** is extracted from the free-list and reused, then the original data
38146** may be lost. In the event of a rollback, it may not be possible
38147** to restore the database to its original configuration.
38148**
38149** The solution is the BtShared.pHasContent bitvec. Whenever a page is
38150** moved to become a free-list leaf page, the corresponding bit is
38151** set in the bitvec. Whenever a leaf page is extracted from the free-list,
38152** optimization 2 above is omitted if the corresponding bit is already
38153** set in BtShared.pHasContent. The contents of the bitvec are cleared
38154** at the end of every transaction.
38155*/
38156static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
38157  int rc = SQLITE_OK;
38158  if( !pBt->pHasContent ){
38159    int nPage = 100;
38160    sqlite3PagerPagecount(pBt->pPager, &nPage);
38161    /* If sqlite3PagerPagecount() fails there is no harm because the
38162    ** nPage variable is unchanged from its default value of 100 */
38163    pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
38164    if( !pBt->pHasContent ){
38165      rc = SQLITE_NOMEM;
38166    }
38167  }
38168  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
38169    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
38170  }
38171  return rc;
38172}
38173
38174/*
38175** Query the BtShared.pHasContent vector.
38176**
38177** This function is called when a free-list leaf page is removed from the
38178** free-list for reuse. It returns false if it is safe to retrieve the
38179** page from the pager layer with the 'no-content' flag set. True otherwise.
38180*/
38181static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
38182  Bitvec *p = pBt->pHasContent;
38183  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
38184}
38185
38186/*
38187** Clear (destroy) the BtShared.pHasContent bitvec. This should be
38188** invoked at the conclusion of each write-transaction.
38189*/
38190static void btreeClearHasContent(BtShared *pBt){
38191  sqlite3BitvecDestroy(pBt->pHasContent);
38192  pBt->pHasContent = 0;
38193}
38194
38195/*
38196** Save the current cursor position in the variables BtCursor.nKey
38197** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
38198**
38199** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
38200** prior to calling this routine.
38201*/
38202static int saveCursorPosition(BtCursor *pCur){
38203  int rc;
38204
38205  assert( CURSOR_VALID==pCur->eState );
38206  assert( 0==pCur->pKey );
38207  assert( cursorHoldsMutex(pCur) );
38208
38209  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
38210  assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
38211
38212  /* If this is an intKey table, then the above call to BtreeKeySize()
38213  ** stores the integer key in pCur->nKey. In this case this value is
38214  ** all that is required. Otherwise, if pCur is not open on an intKey
38215  ** table, then malloc space for and store the pCur->nKey bytes of key
38216  ** data.
38217  */
38218  if( 0==pCur->apPage[0]->intKey ){
38219    void *pKey = sqlite3Malloc( (int)pCur->nKey );
38220    if( pKey ){
38221      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
38222      if( rc==SQLITE_OK ){
38223        pCur->pKey = pKey;
38224      }else{
38225        sqlite3_free(pKey);
38226      }
38227    }else{
38228      rc = SQLITE_NOMEM;
38229    }
38230  }
38231  assert( !pCur->apPage[0]->intKey || !pCur->pKey );
38232
38233  if( rc==SQLITE_OK ){
38234    int i;
38235    for(i=0; i<=pCur->iPage; i++){
38236      releasePage(pCur->apPage[i]);
38237      pCur->apPage[i] = 0;
38238    }
38239    pCur->iPage = -1;
38240    pCur->eState = CURSOR_REQUIRESEEK;
38241  }
38242
38243  invalidateOverflowCache(pCur);
38244  return rc;
38245}
38246
38247/*
38248** Save the positions of all cursors (except pExcept) that are open on
38249** the table  with root-page iRoot. Usually, this is called just before cursor
38250** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
38251*/
38252static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
38253  BtCursor *p;
38254  assert( sqlite3_mutex_held(pBt->mutex) );
38255  assert( pExcept==0 || pExcept->pBt==pBt );
38256  for(p=pBt->pCursor; p; p=p->pNext){
38257    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
38258        p->eState==CURSOR_VALID ){
38259      int rc = saveCursorPosition(p);
38260      if( SQLITE_OK!=rc ){
38261        return rc;
38262      }
38263    }
38264  }
38265  return SQLITE_OK;
38266}
38267
38268/*
38269** Clear the current cursor position.
38270*/
38271SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
38272  assert( cursorHoldsMutex(pCur) );
38273  sqlite3_free(pCur->pKey);
38274  pCur->pKey = 0;
38275  pCur->eState = CURSOR_INVALID;
38276}
38277
38278/*
38279** In this version of BtreeMoveto, pKey is a packed index record
38280** such as is generated by the OP_MakeRecord opcode.  Unpack the
38281** record and then call BtreeMovetoUnpacked() to do the work.
38282*/
38283static int btreeMoveto(
38284  BtCursor *pCur,     /* Cursor open on the btree to be searched */
38285  const void *pKey,   /* Packed key if the btree is an index */
38286  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
38287  int bias,           /* Bias search to the high end */
38288  int *pRes           /* Write search results here */
38289){
38290  int rc;                    /* Status code */
38291  UnpackedRecord *pIdxKey;   /* Unpacked index key */
38292  char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
38293
38294  if( pKey ){
38295    assert( nKey==(i64)(int)nKey );
38296    pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
38297                                      aSpace, sizeof(aSpace));
38298    if( pIdxKey==0 ) return SQLITE_NOMEM;
38299  }else{
38300    pIdxKey = 0;
38301  }
38302  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
38303  if( pKey ){
38304    sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
38305  }
38306  return rc;
38307}
38308
38309/*
38310** Restore the cursor to the position it was in (or as close to as possible)
38311** when saveCursorPosition() was called. Note that this call deletes the
38312** saved position info stored by saveCursorPosition(), so there can be
38313** at most one effective restoreCursorPosition() call after each
38314** saveCursorPosition().
38315*/
38316static int btreeRestoreCursorPosition(BtCursor *pCur){
38317  int rc;
38318  assert( cursorHoldsMutex(pCur) );
38319  assert( pCur->eState>=CURSOR_REQUIRESEEK );
38320  if( pCur->eState==CURSOR_FAULT ){
38321    return pCur->skipNext;
38322  }
38323  pCur->eState = CURSOR_INVALID;
38324  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
38325  if( rc==SQLITE_OK ){
38326    sqlite3_free(pCur->pKey);
38327    pCur->pKey = 0;
38328    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
38329  }
38330  return rc;
38331}
38332
38333#define restoreCursorPosition(p) \
38334  (p->eState>=CURSOR_REQUIRESEEK ? \
38335         btreeRestoreCursorPosition(p) : \
38336         SQLITE_OK)
38337
38338/*
38339** Determine whether or not a cursor has moved from the position it
38340** was last placed at.  Cursors can move when the row they are pointing
38341** at is deleted out from under them.
38342**
38343** This routine returns an error code if something goes wrong.  The
38344** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
38345*/
38346SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
38347  int rc;
38348
38349  rc = restoreCursorPosition(pCur);
38350  if( rc ){
38351    *pHasMoved = 1;
38352    return rc;
38353  }
38354  if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
38355    *pHasMoved = 1;
38356  }else{
38357    *pHasMoved = 0;
38358  }
38359  return SQLITE_OK;
38360}
38361
38362#ifndef SQLITE_OMIT_AUTOVACUUM
38363/*
38364** Given a page number of a regular database page, return the page
38365** number for the pointer-map page that contains the entry for the
38366** input page number.
38367*/
38368static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
38369  int nPagesPerMapPage;
38370  Pgno iPtrMap, ret;
38371  assert( sqlite3_mutex_held(pBt->mutex) );
38372  nPagesPerMapPage = (pBt->usableSize/5)+1;
38373  iPtrMap = (pgno-2)/nPagesPerMapPage;
38374  ret = (iPtrMap*nPagesPerMapPage) + 2;
38375  if( ret==PENDING_BYTE_PAGE(pBt) ){
38376    ret++;
38377  }
38378  return ret;
38379}
38380
38381/*
38382** Write an entry into the pointer map.
38383**
38384** This routine updates the pointer map entry for page number 'key'
38385** so that it maps to type 'eType' and parent page number 'pgno'.
38386**
38387** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
38388** a no-op.  If an error occurs, the appropriate error code is written
38389** into *pRC.
38390*/
38391static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
38392  DbPage *pDbPage;  /* The pointer map page */
38393  u8 *pPtrmap;      /* The pointer map data */
38394  Pgno iPtrmap;     /* The pointer map page number */
38395  int offset;       /* Offset in pointer map page */
38396  int rc;           /* Return code from subfunctions */
38397
38398  if( *pRC ) return;
38399
38400  assert( sqlite3_mutex_held(pBt->mutex) );
38401  /* The master-journal page number must never be used as a pointer map page */
38402  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
38403
38404  assert( pBt->autoVacuum );
38405  if( key==0 ){
38406    *pRC = SQLITE_CORRUPT_BKPT(INVALID_KEY_INTO_PTRMAP_CORRUPTION); // Android Change
38407    return;
38408  }
38409  iPtrmap = PTRMAP_PAGENO(pBt, key);
38410  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
38411  if( rc!=SQLITE_OK ){
38412    *pRC = rc;
38413    return;
38414  }
38415  offset = PTRMAP_PTROFFSET(iPtrmap, key);
38416  if( offset<0 ){
38417    *pRC = SQLITE_CORRUPT_BKPT(INVALID_OFFSET_IN_PTRMAP_CORRUPTION); // Android Change
38418    goto ptrmap_exit;
38419  }
38420  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
38421
38422  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
38423    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
38424    *pRC= rc = sqlite3PagerWrite(pDbPage);
38425    if( rc==SQLITE_OK ){
38426      pPtrmap[offset] = eType;
38427      put4byte(&pPtrmap[offset+1], parent);
38428    }
38429  }
38430
38431ptrmap_exit:
38432  sqlite3PagerUnref(pDbPage);
38433}
38434
38435/*
38436** Read an entry from the pointer map.
38437**
38438** This routine retrieves the pointer map entry for page 'key', writing
38439** the type and parent page number to *pEType and *pPgno respectively.
38440** An error code is returned if something goes wrong, otherwise SQLITE_OK.
38441*/
38442static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
38443  DbPage *pDbPage;   /* The pointer map page */
38444  int iPtrmap;       /* Pointer map page index */
38445  u8 *pPtrmap;       /* Pointer map page data */
38446  int offset;        /* Offset of entry in pointer map */
38447  int rc;
38448
38449  assert( sqlite3_mutex_held(pBt->mutex) );
38450
38451  iPtrmap = PTRMAP_PAGENO(pBt, key);
38452  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
38453  if( rc!=0 ){
38454    return rc;
38455  }
38456  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
38457
38458  offset = PTRMAP_PTROFFSET(iPtrmap, key);
38459  assert( pEType!=0 );
38460  *pEType = pPtrmap[offset];
38461  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
38462
38463  sqlite3PagerUnref(pDbPage);
38464  if( *pEType<1 || *pEType>5 )
38465    return SQLITE_CORRUPT_BKPT(INVALID_PETYPE_CORRUPTION); // Android Change
38466  return SQLITE_OK;
38467}
38468
38469#else /* if defined SQLITE_OMIT_AUTOVACUUM */
38470  #define ptrmapPut(w,x,y,z,rc)
38471  #define ptrmapGet(w,x,y,z) SQLITE_OK
38472  #define ptrmapPutOvflPtr(x, y, rc)
38473#endif
38474
38475/*
38476** Given a btree page and a cell index (0 means the first cell on
38477** the page, 1 means the second cell, and so forth) return a pointer
38478** to the cell content.
38479**
38480** This routine works only for pages that do not contain overflow cells.
38481*/
38482#define findCell(P,I) \
38483  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
38484
38485/*
38486** This a more complex version of findCell() that works for
38487** pages that do contain overflow cells.
38488*/
38489static u8 *findOverflowCell(MemPage *pPage, int iCell){
38490  int i;
38491  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38492  for(i=pPage->nOverflow-1; i>=0; i--){
38493    int k;
38494    struct _OvflCell *pOvfl;
38495    pOvfl = &pPage->aOvfl[i];
38496    k = pOvfl->idx;
38497    if( k<=iCell ){
38498      if( k==iCell ){
38499        return pOvfl->pCell;
38500      }
38501      iCell--;
38502    }
38503  }
38504  return findCell(pPage, iCell);
38505}
38506
38507/*
38508** Parse a cell content block and fill in the CellInfo structure.  There
38509** are two versions of this function.  btreeParseCell() takes a
38510** cell index as the second argument and btreeParseCellPtr()
38511** takes a pointer to the body of the cell as its second argument.
38512**
38513** Within this file, the parseCell() macro can be called instead of
38514** btreeParseCellPtr(). Using some compilers, this will be faster.
38515*/
38516static void btreeParseCellPtr(
38517  MemPage *pPage,         /* Page containing the cell */
38518  u8 *pCell,              /* Pointer to the cell text. */
38519  CellInfo *pInfo         /* Fill in this structure */
38520){
38521  u16 n;                  /* Number bytes in cell content header */
38522  u32 nPayload;           /* Number of bytes of cell payload */
38523
38524  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38525
38526  pInfo->pCell = pCell;
38527  assert( pPage->leaf==0 || pPage->leaf==1 );
38528  n = pPage->childPtrSize;
38529  assert( n==4-4*pPage->leaf );
38530  if( pPage->intKey ){
38531    if( pPage->hasData ){
38532      n += getVarint32(&pCell[n], nPayload);
38533    }else{
38534      nPayload = 0;
38535    }
38536    n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
38537    pInfo->nData = nPayload;
38538  }else{
38539    pInfo->nData = 0;
38540    n += getVarint32(&pCell[n], nPayload);
38541    pInfo->nKey = nPayload;
38542  }
38543  pInfo->nPayload = nPayload;
38544  pInfo->nHeader = n;
38545  testcase( nPayload==pPage->maxLocal );
38546  testcase( nPayload==pPage->maxLocal+1 );
38547  if( likely(nPayload<=pPage->maxLocal) ){
38548    /* This is the (easy) common case where the entire payload fits
38549    ** on the local page.  No overflow is required.
38550    */
38551    int nSize;          /* Total size of cell content in bytes */
38552    nSize = nPayload + n;
38553    pInfo->nLocal = (u16)nPayload;
38554    pInfo->iOverflow = 0;
38555    if( (nSize & ~3)==0 ){
38556      nSize = 4;        /* Minimum cell size is 4 */
38557    }
38558    pInfo->nSize = (u16)nSize;
38559  }else{
38560    /* If the payload will not fit completely on the local page, we have
38561    ** to decide how much to store locally and how much to spill onto
38562    ** overflow pages.  The strategy is to minimize the amount of unused
38563    ** space on overflow pages while keeping the amount of local storage
38564    ** in between minLocal and maxLocal.
38565    **
38566    ** Warning:  changing the way overflow payload is distributed in any
38567    ** way will result in an incompatible file format.
38568    */
38569    int minLocal;  /* Minimum amount of payload held locally */
38570    int maxLocal;  /* Maximum amount of payload held locally */
38571    int surplus;   /* Overflow payload available for local storage */
38572
38573    minLocal = pPage->minLocal;
38574    maxLocal = pPage->maxLocal;
38575    surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
38576    testcase( surplus==maxLocal );
38577    testcase( surplus==maxLocal+1 );
38578    if( surplus <= maxLocal ){
38579      pInfo->nLocal = (u16)surplus;
38580    }else{
38581      pInfo->nLocal = (u16)minLocal;
38582    }
38583    pInfo->iOverflow = (u16)(pInfo->nLocal + n);
38584    pInfo->nSize = pInfo->iOverflow + 4;
38585  }
38586}
38587#define parseCell(pPage, iCell, pInfo) \
38588  btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
38589static void btreeParseCell(
38590  MemPage *pPage,         /* Page containing the cell */
38591  int iCell,              /* The cell index.  First cell is 0 */
38592  CellInfo *pInfo         /* Fill in this structure */
38593){
38594  parseCell(pPage, iCell, pInfo);
38595}
38596
38597/*
38598** Compute the total number of bytes that a Cell needs in the cell
38599** data area of the btree-page.  The return number includes the cell
38600** data header and the local payload, but not any overflow page or
38601** the space used by the cell pointer.
38602*/
38603static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
38604  u8 *pIter = &pCell[pPage->childPtrSize];
38605  u32 nSize;
38606
38607#ifdef SQLITE_DEBUG
38608  /* The value returned by this function should always be the same as
38609  ** the (CellInfo.nSize) value found by doing a full parse of the
38610  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
38611  ** this function verifies that this invariant is not violated. */
38612  CellInfo debuginfo;
38613  btreeParseCellPtr(pPage, pCell, &debuginfo);
38614#endif
38615
38616  if( pPage->intKey ){
38617    u8 *pEnd;
38618    if( pPage->hasData ){
38619      pIter += getVarint32(pIter, nSize);
38620    }else{
38621      nSize = 0;
38622    }
38623
38624    /* pIter now points at the 64-bit integer key value, a variable length
38625    ** integer. The following block moves pIter to point at the first byte
38626    ** past the end of the key value. */
38627    pEnd = &pIter[9];
38628    while( (*pIter++)&0x80 && pIter<pEnd );
38629  }else{
38630    pIter += getVarint32(pIter, nSize);
38631  }
38632
38633  testcase( nSize==pPage->maxLocal );
38634  testcase( nSize==pPage->maxLocal+1 );
38635  if( nSize>pPage->maxLocal ){
38636    int minLocal = pPage->minLocal;
38637    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
38638    testcase( nSize==pPage->maxLocal );
38639    testcase( nSize==pPage->maxLocal+1 );
38640    if( nSize>pPage->maxLocal ){
38641      nSize = minLocal;
38642    }
38643    nSize += 4;
38644  }
38645  nSize += (u32)(pIter - pCell);
38646
38647  /* The minimum size of any cell is 4 bytes. */
38648  if( nSize<4 ){
38649    nSize = 4;
38650  }
38651
38652  assert( nSize==debuginfo.nSize );
38653  return (u16)nSize;
38654}
38655
38656#ifdef SQLITE_DEBUG
38657/* This variation on cellSizePtr() is used inside of assert() statements
38658** only. */
38659static u16 cellSize(MemPage *pPage, int iCell){
38660  return cellSizePtr(pPage, findCell(pPage, iCell));
38661}
38662#endif
38663
38664#ifndef SQLITE_OMIT_AUTOVACUUM
38665/*
38666** If the cell pCell, part of page pPage contains a pointer
38667** to an overflow page, insert an entry into the pointer-map
38668** for the overflow page.
38669*/
38670static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
38671  CellInfo info;
38672  if( *pRC ) return;
38673  assert( pCell!=0 );
38674  btreeParseCellPtr(pPage, pCell, &info);
38675  assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
38676  if( info.iOverflow ){
38677    Pgno ovfl = get4byte(&pCell[info.iOverflow]);
38678    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
38679  }
38680}
38681#endif
38682
38683
38684/*
38685** Defragment the page given.  All Cells are moved to the
38686** end of the page and all free space is collected into one
38687** big FreeBlk that occurs in between the header and cell
38688** pointer array and the cell content area.
38689*/
38690static int defragmentPage(MemPage *pPage){
38691  int i;                     /* Loop counter */
38692  int pc;                    /* Address of a i-th cell */
38693  int hdr;                   /* Offset to the page header */
38694  int size;                  /* Size of a cell */
38695  int usableSize;            /* Number of usable bytes on a page */
38696  int cellOffset;            /* Offset to the cell pointer array */
38697  int cbrk;                  /* Offset to the cell content area */
38698  int nCell;                 /* Number of cells on the page */
38699  unsigned char *data;       /* The page data */
38700  unsigned char *temp;       /* Temp area for cell content */
38701  int iCellFirst;            /* First allowable cell index */
38702  int iCellLast;             /* Last possible cell index */
38703
38704
38705  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38706  assert( pPage->pBt!=0 );
38707  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
38708  assert( pPage->nOverflow==0 );
38709  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38710  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
38711  data = pPage->aData;
38712  hdr = pPage->hdrOffset;
38713  cellOffset = pPage->cellOffset;
38714  nCell = pPage->nCell;
38715  assert( nCell==get2byte(&data[hdr+3]) );
38716  usableSize = pPage->pBt->usableSize;
38717  cbrk = get2byte(&data[hdr+5]);
38718  memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
38719  cbrk = usableSize;
38720  iCellFirst = cellOffset + 2*nCell;
38721  iCellLast = usableSize - 4;
38722  for(i=0; i<nCell; i++){
38723    u8 *pAddr;     /* The i-th cell pointer */
38724    pAddr = &data[cellOffset + i*2];
38725    pc = get2byte(pAddr);
38726    testcase( pc==iCellFirst );
38727    testcase( pc==iCellLast );
38728#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
38729    /* These conditions have already been verified in btreeInitPage()
38730    ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
38731    */
38732    if( pc<iCellFirst || pc>iCellLast ){
38733      return SQLITE_CORRUPT_BKPT(CELL_INDEX_CORRUPTION); // Android Change
38734    }
38735#endif
38736    assert( pc>=iCellFirst && pc<=iCellLast );
38737    size = cellSizePtr(pPage, &temp[pc]);
38738    cbrk -= size;
38739#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
38740    if( cbrk<iCellFirst ){
38741      return SQLITE_CORRUPT_BKPT(CELL_INDEX_TOO_LOW_CORRUPTION); // Android Change
38742    }
38743#else
38744    if( cbrk<iCellFirst || pc+size>usableSize ){
38745      return SQLITE_CORRUPT_BKPT(CELL_INDEX_INVALID_CORRUPTION); // Android Change
38746    }
38747#endif
38748    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
38749    testcase( cbrk+size==usableSize );
38750    testcase( pc+size==usableSize );
38751    memcpy(&data[cbrk], &temp[pc], size);
38752    put2byte(pAddr, cbrk);
38753  }
38754  assert( cbrk>=iCellFirst );
38755  put2byte(&data[hdr+5], cbrk);
38756  data[hdr+1] = 0;
38757  data[hdr+2] = 0;
38758  data[hdr+7] = 0;
38759  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
38760  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38761  if( cbrk-iCellFirst!=pPage->nFree ){
38762    return SQLITE_CORRUPT_BKPT(DEFRAG_PAGE_CORRUPTION); // Android Change
38763  }
38764  return SQLITE_OK;
38765}
38766
38767/*
38768** Allocate nByte bytes of space from within the B-Tree page passed
38769** as the first argument. Write into *pIdx the index into pPage->aData[]
38770** of the first byte of allocated space. Return either SQLITE_OK or
38771** an error code (usually SQLITE_CORRUPT).
38772**
38773** The caller guarantees that there is sufficient space to make the
38774** allocation.  This routine might need to defragment in order to bring
38775** all the space together, however.  This routine will avoid using
38776** the first two bytes past the cell pointer area since presumably this
38777** allocation is being made in order to insert a new cell, so we will
38778** also end up needing a new cell pointer.
38779*/
38780static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
38781  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
38782  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
38783  int nFrag;                           /* Number of fragmented bytes on pPage */
38784  int top;                             /* First byte of cell content area */
38785  int gap;        /* First byte of gap between cell pointers and cell content */
38786  int rc;         /* Integer return code */
38787  int usableSize; /* Usable size of the page */
38788
38789  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38790  assert( pPage->pBt );
38791  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38792  assert( nByte>=0 );  /* Minimum cell size is 4 */
38793  assert( pPage->nFree>=nByte );
38794  assert( pPage->nOverflow==0 );
38795  usableSize = pPage->pBt->usableSize;
38796  assert( nByte < usableSize-8 );
38797
38798  nFrag = data[hdr+7];
38799  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
38800  gap = pPage->cellOffset + 2*pPage->nCell;
38801  top = get2byte(&data[hdr+5]);
38802  if( gap>top ) return SQLITE_CORRUPT_BKPT(GAP_TOP_CORRUPTION); // Android Change
38803  testcase( gap+2==top );
38804  testcase( gap+1==top );
38805  testcase( gap==top );
38806
38807  if( nFrag>=60 ){
38808    /* Always defragment highly fragmented pages */
38809    rc = defragmentPage(pPage);
38810    if( rc ) return rc;
38811    top = get2byte(&data[hdr+5]);
38812  }else if( gap+2<=top ){
38813    /* Search the freelist looking for a free slot big enough to satisfy
38814    ** the request. The allocation is made from the first free slot in
38815    ** the list that is large enough to accomadate it.
38816    */
38817    int pc, addr;
38818    for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
38819      int size;            /* Size of the free slot */
38820      if( pc>usableSize-4 || pc<addr+4 ){
38821        return SQLITE_CORRUPT_BKPT(FREE_SLOT_AVAIL_CORRUPTION); // Android Change
38822      }
38823      size = get2byte(&data[pc+2]);
38824      if( size>=nByte ){
38825        int x = size - nByte;
38826        testcase( x==4 );
38827        testcase( x==3 );
38828        if( x<4 ){
38829          /* Remove the slot from the free-list. Update the number of
38830          ** fragmented bytes within the page. */
38831          memcpy(&data[addr], &data[pc], 2);
38832          data[hdr+7] = (u8)(nFrag + x);
38833        }else if( size+pc > usableSize ){
38834          return SQLITE_CORRUPT_BKPT(ALLOC_SPACE_CORRUPTION); // Android Change
38835        }else{
38836          /* The slot remains on the free-list. Reduce its size to account
38837          ** for the portion used by the new allocation. */
38838          put2byte(&data[pc+2], x);
38839        }
38840        *pIdx = pc + x;
38841        return SQLITE_OK;
38842      }
38843    }
38844  }
38845
38846  /* Check to make sure there is enough space in the gap to satisfy
38847  ** the allocation.  If not, defragment.
38848  */
38849  testcase( gap+2+nByte==top );
38850  if( gap+2+nByte>top ){
38851    rc = defragmentPage(pPage);
38852    if( rc ) return rc;
38853    top = get2byte(&data[hdr+5]);
38854    assert( gap+nByte<=top );
38855  }
38856
38857
38858  /* Allocate memory from the gap in between the cell pointer array
38859  ** and the cell content area.  The btreeInitPage() call has already
38860  ** validated the freelist.  Given that the freelist is valid, there
38861  ** is no way that the allocation can extend off the end of the page.
38862  ** The assert() below verifies the previous sentence.
38863  */
38864  top -= nByte;
38865  put2byte(&data[hdr+5], top);
38866  assert( top+nByte <= pPage->pBt->usableSize );
38867  *pIdx = top;
38868  return SQLITE_OK;
38869}
38870
38871/*
38872** Return a section of the pPage->aData to the freelist.
38873** The first byte of the new free block is pPage->aDisk[start]
38874** and the size of the block is "size" bytes.
38875**
38876** Most of the effort here is involved in coalesing adjacent
38877** free blocks into a single big free block.
38878*/
38879static int freeSpace(MemPage *pPage, int start, int size){
38880  int addr, pbegin, hdr;
38881  int iLast;                        /* Largest possible freeblock offset */
38882  unsigned char *data = pPage->aData;
38883
38884  assert( pPage->pBt!=0 );
38885  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38886  assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
38887  assert( (start + size)<=pPage->pBt->usableSize );
38888  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38889  assert( size>=0 );   /* Minimum cell size is 4 */
38890
38891#ifdef SQLITE_SECURE_DELETE
38892  /* Overwrite deleted information with zeros when the SECURE_DELETE
38893  ** option is enabled at compile-time */
38894  memset(&data[start], 0, size);
38895#endif
38896
38897  /* Add the space back into the linked list of freeblocks.  Note that
38898  ** even though the freeblock list was checked by btreeInitPage(),
38899  ** btreeInitPage() did not detect overlapping cells or
38900  ** freeblocks that overlapped cells.   Nor does it detect when the
38901  ** cell content area exceeds the value in the page header.  If these
38902  ** situations arise, then subsequent insert operations might corrupt
38903  ** the freelist.  So we do need to check for corruption while scanning
38904  ** the freelist.
38905  */
38906  hdr = pPage->hdrOffset;
38907  addr = hdr + 1;
38908  iLast = pPage->pBt->usableSize - 4;
38909  assert( start<=iLast );
38910  while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
38911    if( pbegin<addr+4 ){
38912      return SQLITE_CORRUPT_BKPT(FREE_SPACE_1_CORRUPTION); // Android Change
38913    }
38914    addr = pbegin;
38915  }
38916  if( pbegin>iLast ){
38917    return SQLITE_CORRUPT_BKPT(FREE_SPACE_2_CORRUPTION); // Android Change
38918  }
38919  assert( pbegin>addr || pbegin==0 );
38920  put2byte(&data[addr], start);
38921  put2byte(&data[start], pbegin);
38922  put2byte(&data[start+2], size);
38923  pPage->nFree = pPage->nFree + (u16)size;
38924
38925  /* Coalesce adjacent free blocks */
38926  addr = hdr + 1;
38927  while( (pbegin = get2byte(&data[addr]))>0 ){
38928    int pnext, psize, x;
38929    assert( pbegin>addr );
38930    assert( pbegin<=pPage->pBt->usableSize-4 );
38931    pnext = get2byte(&data[pbegin]);
38932    psize = get2byte(&data[pbegin+2]);
38933    if( pbegin + psize + 3 >= pnext && pnext>0 ){
38934      int frag = pnext - (pbegin+psize);
38935      if( (frag<0) || (frag>(int)data[hdr+7]) ){
38936        return SQLITE_CORRUPT_BKPT(FREE_SPACE_3_CORRUPTION); // Android Change
38937      }
38938      data[hdr+7] -= (u8)frag;
38939      x = get2byte(&data[pnext]);
38940      put2byte(&data[pbegin], x);
38941      x = pnext + get2byte(&data[pnext+2]) - pbegin;
38942      put2byte(&data[pbegin+2], x);
38943    }else{
38944      addr = pbegin;
38945    }
38946  }
38947
38948  /* If the cell content area begins with a freeblock, remove it. */
38949  if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
38950    int top;
38951    pbegin = get2byte(&data[hdr+1]);
38952    memcpy(&data[hdr+1], &data[pbegin], 2);
38953    top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
38954    put2byte(&data[hdr+5], top);
38955  }
38956  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38957  return SQLITE_OK;
38958}
38959
38960/*
38961** Decode the flags byte (the first byte of the header) for a page
38962** and initialize fields of the MemPage structure accordingly.
38963**
38964** Only the following combinations are supported.  Anything different
38965** indicates a corrupt database files:
38966**
38967**         PTF_ZERODATA
38968**         PTF_ZERODATA | PTF_LEAF
38969**         PTF_LEAFDATA | PTF_INTKEY
38970**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
38971*/
38972static int decodeFlags(MemPage *pPage, int flagByte){
38973  BtShared *pBt;     /* A copy of pPage->pBt */
38974
38975  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
38976  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38977  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
38978  flagByte &= ~PTF_LEAF;
38979  pPage->childPtrSize = 4-4*pPage->leaf;
38980  pBt = pPage->pBt;
38981  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
38982    pPage->intKey = 1;
38983    pPage->hasData = pPage->leaf;
38984    pPage->maxLocal = pBt->maxLeaf;
38985    pPage->minLocal = pBt->minLeaf;
38986  }else if( flagByte==PTF_ZERODATA ){
38987    pPage->intKey = 0;
38988    pPage->hasData = 0;
38989    pPage->maxLocal = pBt->maxLocal;
38990    pPage->minLocal = pBt->minLocal;
38991  }else{
38992    return SQLITE_CORRUPT_BKPT(DECODE_FLAGS_CORRUPTION); // Android Change
38993  }
38994  return SQLITE_OK;
38995}
38996
38997/*
38998** Initialize the auxiliary information for a disk block.
38999**
39000** Return SQLITE_OK on success.  If we see that the page does
39001** not contain a well-formed database page, then return
39002** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
39003** guarantee that the page is well-formed.  It only shows that
39004** we failed to detect any corruption.
39005*/
39006static int btreeInitPage(MemPage *pPage){
39007
39008  assert( pPage->pBt!=0 );
39009  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39010  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
39011  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
39012  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
39013
39014  if( !pPage->isInit ){
39015    u16 pc;            /* Address of a freeblock within pPage->aData[] */
39016    u8 hdr;            /* Offset to beginning of page header */
39017    u8 *data;          /* Equal to pPage->aData */
39018    BtShared *pBt;        /* The main btree structure */
39019    u16 usableSize;    /* Amount of usable space on each page */
39020    u16 cellOffset;    /* Offset from start of page to first cell pointer */
39021    u16 nFree;         /* Number of unused bytes on the page */
39022    u16 top;           /* First byte of the cell content area */
39023    int iCellFirst;    /* First allowable cell or freeblock offset */
39024    int iCellLast;     /* Last possible cell or freeblock offset */
39025
39026    pBt = pPage->pBt;
39027
39028    hdr = pPage->hdrOffset;
39029    data = pPage->aData;
39030    if( decodeFlags(pPage, data[hdr]) )
39031      return SQLITE_CORRUPT_BKPT(BTREE_INITPAGE_1_CORRUPTION); // Android Change
39032    assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
39033    pPage->maskPage = pBt->pageSize - 1;
39034    pPage->nOverflow = 0;
39035    usableSize = pBt->usableSize;
39036    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
39037    top = get2byte(&data[hdr+5]);
39038    pPage->nCell = get2byte(&data[hdr+3]);
39039    if( pPage->nCell>MX_CELL(pBt) ){
39040      /* To many cells for a single page.  The page must be corrupt */
39041      return SQLITE_CORRUPT_BKPT(TOO_MANY_CELLS_IN_PAGE_CORRUPTION); // Android Change
39042    }
39043    testcase( pPage->nCell==MX_CELL(pBt) );
39044
39045    /* A malformed database page might cause us to read past the end
39046    ** of page when parsing a cell.
39047    **
39048    ** The following block of code checks early to see if a cell extends
39049    ** past the end of a page boundary and causes SQLITE_CORRUPT to be
39050    ** returned if it does.
39051    */
39052    iCellFirst = cellOffset + 2*pPage->nCell;
39053    iCellLast = usableSize - 4;
39054#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
39055    {
39056      int i;            /* Index into the cell pointer array */
39057      int sz;           /* Size of a cell */
39058
39059      if( !pPage->leaf ) iCellLast--;
39060      for(i=0; i<pPage->nCell; i++){
39061        pc = get2byte(&data[cellOffset+i*2]);
39062        testcase( pc==iCellFirst );
39063        testcase( pc==iCellLast );
39064        if( pc<iCellFirst || pc>iCellLast ){
39065          return SQLITE_CORRUPT_BKPT(CELL_LOC_OUT_OF_RANGE_CORRUPTION); // Android Change
39066        }
39067        sz = cellSizePtr(pPage, &data[pc]);
39068        testcase( pc+sz==usableSize );
39069        if( pc+sz>usableSize ){
39070          return SQLITE_CORRUPT_BKPT(BTREE_INITPAGE_2_CORRUPTION); // Android Change
39071        }
39072      }
39073      if( !pPage->leaf ) iCellLast++;
39074    }
39075#endif
39076
39077    /* Compute the total free space on the page */
39078    pc = get2byte(&data[hdr+1]);
39079    nFree = data[hdr+7] + top;
39080    while( pc>0 ){
39081      u16 next, size;
39082      if( pc<iCellFirst || pc>iCellLast ){
39083        /* Start of free block is off the page */
39084        return SQLITE_CORRUPT_BKPT(FREE_BLOCK_ERR_CORRUPTION); // Android Change
39085      }
39086      next = get2byte(&data[pc]);
39087      size = get2byte(&data[pc+2]);
39088      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
39089        /* Free blocks must be in ascending order. And the last byte of
39090	** the free-block must lie on the database page.  */
39091        return SQLITE_CORRUPT_BKPT(FREE_BLOCK_NOT_IN_ORDER_CORRUPTION); // Android Change
39092      }
39093      nFree = nFree + size;
39094      pc = next;
39095    }
39096
39097    /* At this point, nFree contains the sum of the offset to the start
39098    ** of the cell-content area plus the number of free bytes within
39099    ** the cell-content area. If this is greater than the usable-size
39100    ** of the page, then the page must be corrupted. This check also
39101    ** serves to verify that the offset to the start of the cell-content
39102    ** area, according to the page header, lies within the page.
39103    */
39104    if( nFree>usableSize ){
39105      return SQLITE_CORRUPT_BKPT(FREE_SPACE_ERR_CORRUPTION); // Android Change
39106    }
39107    pPage->nFree = (u16)(nFree - iCellFirst);
39108    pPage->isInit = 1;
39109  }
39110  return SQLITE_OK;
39111}
39112
39113/*
39114** Set up a raw page so that it looks like a database page holding
39115** no entries.
39116*/
39117static void zeroPage(MemPage *pPage, int flags){
39118  unsigned char *data = pPage->aData;
39119  BtShared *pBt = pPage->pBt;
39120  u8 hdr = pPage->hdrOffset;
39121  u16 first;
39122
39123  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
39124  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
39125  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
39126  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
39127  assert( sqlite3_mutex_held(pBt->mutex) );
39128#ifdef SQLITE_SECURE_DELETE
39129  memset(&data[hdr], 0, pBt->usableSize - hdr);
39130#endif
39131  data[hdr] = (char)flags;
39132  first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
39133  memset(&data[hdr+1], 0, 4);
39134  data[hdr+7] = 0;
39135  put2byte(&data[hdr+5], pBt->usableSize);
39136  pPage->nFree = pBt->usableSize - first;
39137  decodeFlags(pPage, flags);
39138  pPage->hdrOffset = hdr;
39139  pPage->cellOffset = first;
39140  pPage->nOverflow = 0;
39141  assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
39142  pPage->maskPage = pBt->pageSize - 1;
39143  pPage->nCell = 0;
39144  pPage->isInit = 1;
39145}
39146
39147
39148/*
39149** Convert a DbPage obtained from the pager into a MemPage used by
39150** the btree layer.
39151*/
39152static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
39153  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
39154  pPage->aData = sqlite3PagerGetData(pDbPage);
39155  pPage->pDbPage = pDbPage;
39156  pPage->pBt = pBt;
39157  pPage->pgno = pgno;
39158  pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
39159  return pPage;
39160}
39161
39162/*
39163** Get a page from the pager.  Initialize the MemPage.pBt and
39164** MemPage.aData elements if needed.
39165**
39166** If the noContent flag is set, it means that we do not care about
39167** the content of the page at this time.  So do not go to the disk
39168** to fetch the content.  Just fill in the content with zeros for now.
39169** If in the future we call sqlite3PagerWrite() on this page, that
39170** means we have started to be concerned about content and the disk
39171** read should occur at that point.
39172*/
39173static int btreeGetPage(
39174  BtShared *pBt,       /* The btree */
39175  Pgno pgno,           /* Number of the page to fetch */
39176  MemPage **ppPage,    /* Return the page in this parameter */
39177  int noContent        /* Do not load page content if true */
39178){
39179  int rc;
39180  DbPage *pDbPage;
39181
39182  assert( sqlite3_mutex_held(pBt->mutex) );
39183  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
39184  if( rc ) return rc;
39185  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
39186  return SQLITE_OK;
39187}
39188
39189/*
39190** Retrieve a page from the pager cache. If the requested page is not
39191** already in the pager cache return NULL. Initialize the MemPage.pBt and
39192** MemPage.aData elements if needed.
39193*/
39194static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
39195  DbPage *pDbPage;
39196  assert( sqlite3_mutex_held(pBt->mutex) );
39197  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
39198  if( pDbPage ){
39199    return btreePageFromDbPage(pDbPage, pgno, pBt);
39200  }
39201  return 0;
39202}
39203
39204/*
39205** Return the size of the database file in pages. If there is any kind of
39206** error, return ((unsigned int)-1).
39207*/
39208static Pgno pagerPagecount(BtShared *pBt){
39209  int nPage = -1;
39210  int rc;
39211  assert( pBt->pPage1 );
39212  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
39213  assert( rc==SQLITE_OK || nPage==-1 );
39214  return (Pgno)nPage;
39215}
39216
39217/*
39218** Get a page from the pager and initialize it.  This routine is just a
39219** convenience wrapper around separate calls to btreeGetPage() and
39220** btreeInitPage().
39221**
39222** If an error occurs, then the value *ppPage is set to is undefined. It
39223** may remain unchanged, or it may be set to an invalid value.
39224*/
39225static int getAndInitPage(
39226  BtShared *pBt,          /* The database file */
39227  Pgno pgno,           /* Number of the page to get */
39228  MemPage **ppPage     /* Write the page pointer here */
39229){
39230  int rc;
39231  TESTONLY( Pgno iLastPg = pagerPagecount(pBt); )
39232  assert( sqlite3_mutex_held(pBt->mutex) );
39233
39234  rc = btreeGetPage(pBt, pgno, ppPage, 0);
39235  if( rc==SQLITE_OK ){
39236    rc = btreeInitPage(*ppPage);
39237    if( rc!=SQLITE_OK ){
39238      releasePage(*ppPage);
39239    }
39240  }
39241
39242  /* If the requested page number was either 0 or greater than the page
39243  ** number of the last page in the database, this function should return
39244  ** SQLITE_CORRUPT or some other error (i.e. SQLITE_FULL). Check that this
39245  ** is the case.  */
39246  assert( (pgno>0 && pgno<=iLastPg) || rc!=SQLITE_OK );
39247  testcase( pgno==0 );
39248  testcase( pgno==iLastPg );
39249
39250  return rc;
39251}
39252
39253/*
39254** Release a MemPage.  This should be called once for each prior
39255** call to btreeGetPage.
39256*/
39257static void releasePage(MemPage *pPage){
39258  if( pPage ){
39259    assert( pPage->aData );
39260    assert( pPage->pBt );
39261    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
39262    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
39263    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39264    sqlite3PagerUnref(pPage->pDbPage);
39265  }
39266}
39267
39268/*
39269** During a rollback, when the pager reloads information into the cache
39270** so that the cache is restored to its original state at the start of
39271** the transaction, for each page restored this routine is called.
39272**
39273** This routine needs to reset the extra data section at the end of the
39274** page to agree with the restored data.
39275*/
39276static void pageReinit(DbPage *pData){
39277  MemPage *pPage;
39278  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
39279  assert( sqlite3PagerPageRefcount(pData)>0 );
39280  if( pPage->isInit ){
39281    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39282    pPage->isInit = 0;
39283    if( sqlite3PagerPageRefcount(pData)>1 ){
39284      /* pPage might not be a btree page;  it might be an overflow page
39285      ** or ptrmap page or a free page.  In those cases, the following
39286      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
39287      ** But no harm is done by this.  And it is very important that
39288      ** btreeInitPage() be called on every btree page so we make
39289      ** the call for every page that comes in for re-initing. */
39290      btreeInitPage(pPage);
39291    }
39292  }
39293}
39294
39295/*
39296** Invoke the busy handler for a btree.
39297*/
39298static int btreeInvokeBusyHandler(void *pArg){
39299  BtShared *pBt = (BtShared*)pArg;
39300  assert( pBt->db );
39301  assert( sqlite3_mutex_held(pBt->db->mutex) );
39302  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
39303}
39304
39305/*
39306** Open a database file.
39307**
39308** zFilename is the name of the database file.  If zFilename is NULL
39309** a new database with a random name is created.  This randomly named
39310** database file will be deleted when sqlite3BtreeClose() is called.
39311** If zFilename is ":memory:" then an in-memory database is created
39312** that is automatically destroyed when it is closed.
39313**
39314** If the database is already opened in the same database connection
39315** and we are in shared cache mode, then the open will fail with an
39316** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
39317** objects in the same database connection since doing so will lead
39318** to problems with locking.
39319*/
39320SQLITE_PRIVATE int sqlite3BtreeOpen(
39321  const char *zFilename,  /* Name of the file containing the BTree database */
39322  sqlite3 *db,            /* Associated database handle */
39323  Btree **ppBtree,        /* Pointer to new Btree object written here */
39324  int flags,              /* Options */
39325  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
39326){
39327  sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
39328  BtShared *pBt = 0;             /* Shared part of btree structure */
39329  Btree *p;                      /* Handle to return */
39330  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
39331  int rc = SQLITE_OK;            /* Result code from this function */
39332  u8 nReserve;                   /* Byte of unused space on each page */
39333  unsigned char zDbHeader[100];  /* Database header content */
39334
39335  /* Set the variable isMemdb to true for an in-memory database, or
39336  ** false for a file-based database. This symbol is only required if
39337  ** either of the shared-data or autovacuum features are compiled
39338  ** into the library.
39339  */
39340#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
39341  #ifdef SQLITE_OMIT_MEMORYDB
39342    const int isMemdb = 0;
39343  #else
39344    const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
39345  #endif
39346#endif
39347
39348  assert( db!=0 );
39349  assert( sqlite3_mutex_held(db->mutex) );
39350
39351  pVfs = db->pVfs;
39352  p = sqlite3MallocZero(sizeof(Btree));
39353  if( !p ){
39354    return SQLITE_NOMEM;
39355  }
39356  p->inTrans = TRANS_NONE;
39357  p->db = db;
39358#ifndef SQLITE_OMIT_SHARED_CACHE
39359  p->lock.pBtree = p;
39360  p->lock.iTable = 1;
39361#endif
39362
39363#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
39364  /*
39365  ** If this Btree is a candidate for shared cache, try to find an
39366  ** existing BtShared object that we can share with
39367  */
39368  if( isMemdb==0 && zFilename && zFilename[0] ){
39369    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
39370      int nFullPathname = pVfs->mxPathname+1;
39371      char *zFullPathname = sqlite3Malloc(nFullPathname);
39372      sqlite3_mutex *mutexShared;
39373      p->sharable = 1;
39374      if( !zFullPathname ){
39375        sqlite3_free(p);
39376        return SQLITE_NOMEM;
39377      }
39378      sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
39379      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
39380      sqlite3_mutex_enter(mutexOpen);
39381      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
39382      sqlite3_mutex_enter(mutexShared);
39383      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
39384        assert( pBt->nRef>0 );
39385        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
39386                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
39387          int iDb;
39388          for(iDb=db->nDb-1; iDb>=0; iDb--){
39389            Btree *pExisting = db->aDb[iDb].pBt;
39390            if( pExisting && pExisting->pBt==pBt ){
39391              sqlite3_mutex_leave(mutexShared);
39392              sqlite3_mutex_leave(mutexOpen);
39393              sqlite3_free(zFullPathname);
39394              sqlite3_free(p);
39395              return SQLITE_CONSTRAINT;
39396            }
39397          }
39398          p->pBt = pBt;
39399          pBt->nRef++;
39400          break;
39401        }
39402      }
39403      sqlite3_mutex_leave(mutexShared);
39404      sqlite3_free(zFullPathname);
39405    }
39406#ifdef SQLITE_DEBUG
39407    else{
39408      /* In debug mode, we mark all persistent databases as sharable
39409      ** even when they are not.  This exercises the locking code and
39410      ** gives more opportunity for asserts(sqlite3_mutex_held())
39411      ** statements to find locking problems.
39412      */
39413      p->sharable = 1;
39414    }
39415#endif
39416  }
39417#endif
39418  if( pBt==0 ){
39419    /*
39420    ** The following asserts make sure that structures used by the btree are
39421    ** the right size.  This is to guard against size changes that result
39422    ** when compiling on a different architecture.
39423    */
39424    assert( sizeof(i64)==8 || sizeof(i64)==4 );
39425    assert( sizeof(u64)==8 || sizeof(u64)==4 );
39426    assert( sizeof(u32)==4 );
39427    assert( sizeof(u16)==2 );
39428    assert( sizeof(Pgno)==4 );
39429
39430    pBt = sqlite3MallocZero( sizeof(*pBt) );
39431    if( pBt==0 ){
39432      rc = SQLITE_NOMEM;
39433      goto btree_open_out;
39434    }
39435    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
39436                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
39437    if( rc==SQLITE_OK ){
39438      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
39439    }
39440    if( rc!=SQLITE_OK ){
39441      goto btree_open_out;
39442    }
39443    pBt->db = db;
39444    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
39445    p->pBt = pBt;
39446
39447    pBt->pCursor = 0;
39448    pBt->pPage1 = 0;
39449    pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
39450    pBt->pageSize = get2byte(&zDbHeader[16]);
39451    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
39452         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
39453      pBt->pageSize = 0;
39454#ifndef SQLITE_OMIT_AUTOVACUUM
39455      /* If the magic name ":memory:" will create an in-memory database, then
39456      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
39457      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
39458      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
39459      ** regular file-name. In this case the auto-vacuum applies as per normal.
39460      */
39461      if( zFilename && !isMemdb ){
39462        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
39463        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
39464      }
39465#endif
39466      nReserve = 0;
39467    }else{
39468      nReserve = zDbHeader[20];
39469      pBt->pageSizeFixed = 1;
39470#ifndef SQLITE_OMIT_AUTOVACUUM
39471      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
39472      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
39473#endif
39474    }
39475    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
39476    if( rc ) goto btree_open_out;
39477    pBt->usableSize = pBt->pageSize - nReserve;
39478    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
39479
39480#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
39481    /* Add the new BtShared object to the linked list sharable BtShareds.
39482    */
39483    if( p->sharable ){
39484      sqlite3_mutex *mutexShared;
39485      pBt->nRef = 1;
39486      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
39487      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
39488        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
39489        if( pBt->mutex==0 ){
39490          rc = SQLITE_NOMEM;
39491          db->mallocFailed = 0;
39492          goto btree_open_out;
39493        }
39494      }
39495      sqlite3_mutex_enter(mutexShared);
39496      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
39497      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
39498      sqlite3_mutex_leave(mutexShared);
39499    }
39500#endif
39501  }
39502
39503#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
39504  /* If the new Btree uses a sharable pBtShared, then link the new
39505  ** Btree into the list of all sharable Btrees for the same connection.
39506  ** The list is kept in ascending order by pBt address.
39507  */
39508  if( p->sharable ){
39509    int i;
39510    Btree *pSib;
39511    for(i=0; i<db->nDb; i++){
39512      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
39513        while( pSib->pPrev ){ pSib = pSib->pPrev; }
39514        if( p->pBt<pSib->pBt ){
39515          p->pNext = pSib;
39516          p->pPrev = 0;
39517          pSib->pPrev = p;
39518        }else{
39519          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
39520            pSib = pSib->pNext;
39521          }
39522          p->pNext = pSib->pNext;
39523          p->pPrev = pSib;
39524          if( p->pNext ){
39525            p->pNext->pPrev = p;
39526          }
39527          pSib->pNext = p;
39528        }
39529        break;
39530      }
39531    }
39532  }
39533#endif
39534  *ppBtree = p;
39535
39536btree_open_out:
39537  if( rc!=SQLITE_OK ){
39538    if( pBt && pBt->pPager ){
39539      sqlite3PagerClose(pBt->pPager);
39540    }
39541    sqlite3_free(pBt);
39542    sqlite3_free(p);
39543    *ppBtree = 0;
39544  }
39545  if( mutexOpen ){
39546    assert( sqlite3_mutex_held(mutexOpen) );
39547    sqlite3_mutex_leave(mutexOpen);
39548  }
39549  return rc;
39550}
39551
39552/*
39553** Decrement the BtShared.nRef counter.  When it reaches zero,
39554** remove the BtShared structure from the sharing list.  Return
39555** true if the BtShared.nRef counter reaches zero and return
39556** false if it is still positive.
39557*/
39558static int removeFromSharingList(BtShared *pBt){
39559#ifndef SQLITE_OMIT_SHARED_CACHE
39560  sqlite3_mutex *pMaster;
39561  BtShared *pList;
39562  int removed = 0;
39563
39564  assert( sqlite3_mutex_notheld(pBt->mutex) );
39565  pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
39566  sqlite3_mutex_enter(pMaster);
39567  pBt->nRef--;
39568  if( pBt->nRef<=0 ){
39569    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
39570      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
39571    }else{
39572      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
39573      while( ALWAYS(pList) && pList->pNext!=pBt ){
39574        pList=pList->pNext;
39575      }
39576      if( ALWAYS(pList) ){
39577        pList->pNext = pBt->pNext;
39578      }
39579    }
39580    if( SQLITE_THREADSAFE ){
39581      sqlite3_mutex_free(pBt->mutex);
39582    }
39583    removed = 1;
39584  }
39585  sqlite3_mutex_leave(pMaster);
39586  return removed;
39587#else
39588  return 1;
39589#endif
39590}
39591
39592/*
39593** Make sure pBt->pTmpSpace points to an allocation of
39594** MX_CELL_SIZE(pBt) bytes.
39595*/
39596static void allocateTempSpace(BtShared *pBt){
39597  if( !pBt->pTmpSpace ){
39598    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
39599  }
39600}
39601
39602/*
39603** Free the pBt->pTmpSpace allocation
39604*/
39605static void freeTempSpace(BtShared *pBt){
39606  sqlite3PageFree( pBt->pTmpSpace);
39607  pBt->pTmpSpace = 0;
39608}
39609
39610/*
39611** Close an open database and invalidate all cursors.
39612*/
39613SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
39614  BtShared *pBt = p->pBt;
39615  BtCursor *pCur;
39616
39617  /* Close all cursors opened via this handle.  */
39618  assert( sqlite3_mutex_held(p->db->mutex) );
39619  sqlite3BtreeEnter(p);
39620  pCur = pBt->pCursor;
39621  while( pCur ){
39622    BtCursor *pTmp = pCur;
39623    pCur = pCur->pNext;
39624    if( pTmp->pBtree==p ){
39625      sqlite3BtreeCloseCursor(pTmp);
39626    }
39627  }
39628
39629  /* Rollback any active transaction and free the handle structure.
39630  ** The call to sqlite3BtreeRollback() drops any table-locks held by
39631  ** this handle.
39632  */
39633  sqlite3BtreeRollback(p);
39634  sqlite3BtreeLeave(p);
39635
39636  /* If there are still other outstanding references to the shared-btree
39637  ** structure, return now. The remainder of this procedure cleans
39638  ** up the shared-btree.
39639  */
39640  assert( p->wantToLock==0 && p->locked==0 );
39641  if( !p->sharable || removeFromSharingList(pBt) ){
39642    /* The pBt is no longer on the sharing list, so we can access
39643    ** it without having to hold the mutex.
39644    **
39645    ** Clean out and delete the BtShared object.
39646    */
39647    assert( !pBt->pCursor );
39648    sqlite3PagerClose(pBt->pPager);
39649    if( pBt->xFreeSchema && pBt->pSchema ){
39650      pBt->xFreeSchema(pBt->pSchema);
39651    }
39652    sqlite3_free(pBt->pSchema);
39653    freeTempSpace(pBt);
39654    sqlite3_free(pBt);
39655  }
39656
39657#ifndef SQLITE_OMIT_SHARED_CACHE
39658  assert( p->wantToLock==0 );
39659  assert( p->locked==0 );
39660  if( p->pPrev ) p->pPrev->pNext = p->pNext;
39661  if( p->pNext ) p->pNext->pPrev = p->pPrev;
39662#endif
39663
39664  sqlite3_free(p);
39665  return SQLITE_OK;
39666}
39667
39668/*
39669** Change the limit on the number of pages allowed in the cache.
39670**
39671** The maximum number of cache pages is set to the absolute
39672** value of mxPage.  If mxPage is negative, the pager will
39673** operate asynchronously - it will not stop to do fsync()s
39674** to insure data is written to the disk surface before
39675** continuing.  Transactions still work if synchronous is off,
39676** and the database cannot be corrupted if this program
39677** crashes.  But if the operating system crashes or there is
39678** an abrupt power failure when synchronous is off, the database
39679** could be left in an inconsistent and unrecoverable state.
39680** Synchronous is on by default so database corruption is not
39681** normally a worry.
39682*/
39683SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
39684  BtShared *pBt = p->pBt;
39685  assert( sqlite3_mutex_held(p->db->mutex) );
39686  sqlite3BtreeEnter(p);
39687  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
39688  sqlite3BtreeLeave(p);
39689  return SQLITE_OK;
39690}
39691
39692/*
39693** Change the way data is synced to disk in order to increase or decrease
39694** how well the database resists damage due to OS crashes and power
39695** failures.  Level 1 is the same as asynchronous (no syncs() occur and
39696** there is a high probability of damage)  Level 2 is the default.  There
39697** is a very low but non-zero probability of damage.  Level 3 reduces the
39698** probability of damage to near zero but with a write performance reduction.
39699*/
39700#ifndef SQLITE_OMIT_PAGER_PRAGMAS
39701SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
39702  BtShared *pBt = p->pBt;
39703  assert( sqlite3_mutex_held(p->db->mutex) );
39704  sqlite3BtreeEnter(p);
39705  sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
39706  sqlite3BtreeLeave(p);
39707  return SQLITE_OK;
39708}
39709#endif
39710
39711/*
39712** Return TRUE if the given btree is set to safety level 1.  In other
39713** words, return TRUE if no sync() occurs on the disk files.
39714*/
39715SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
39716  BtShared *pBt = p->pBt;
39717  int rc;
39718  assert( sqlite3_mutex_held(p->db->mutex) );
39719  sqlite3BtreeEnter(p);
39720  assert( pBt && pBt->pPager );
39721  rc = sqlite3PagerNosync(pBt->pPager);
39722  sqlite3BtreeLeave(p);
39723  return rc;
39724}
39725
39726#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
39727/*
39728** Change the default pages size and the number of reserved bytes per page.
39729** Or, if the page size has already been fixed, return SQLITE_READONLY
39730** without changing anything.
39731**
39732** The page size must be a power of 2 between 512 and 65536.  If the page
39733** size supplied does not meet this constraint then the page size is not
39734** changed.
39735**
39736** Page sizes are constrained to be a power of two so that the region
39737** of the database file used for locking (beginning at PENDING_BYTE,
39738** the first byte past the 1GB boundary, 0x40000000) needs to occur
39739** at the beginning of a page.
39740**
39741** If parameter nReserve is less than zero, then the number of reserved
39742** bytes per page is left unchanged.
39743**
39744** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
39745** and autovacuum mode can no longer be changed.
39746*/
39747SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
39748  int rc = SQLITE_OK;
39749  BtShared *pBt = p->pBt;
39750  assert( nReserve>=-1 && nReserve<=255 );
39751  sqlite3BtreeEnter(p);
39752  if( pBt->pageSizeFixed ){
39753    sqlite3BtreeLeave(p);
39754    return SQLITE_READONLY;
39755  }
39756  if( nReserve<0 ){
39757    nReserve = pBt->pageSize - pBt->usableSize;
39758  }
39759  assert( nReserve>=0 && nReserve<=255 );
39760  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
39761        ((pageSize-1)&pageSize)==0 ){
39762    assert( (pageSize & 7)==0 );
39763    assert( !pBt->pPage1 && !pBt->pCursor );
39764    pBt->pageSize = (u16)pageSize;
39765    freeTempSpace(pBt);
39766  }
39767  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
39768  pBt->usableSize = pBt->pageSize - (u16)nReserve;
39769  if( iFix ) pBt->pageSizeFixed = 1;
39770  sqlite3BtreeLeave(p);
39771  return rc;
39772}
39773
39774/*
39775** Return the currently defined page size
39776*/
39777SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
39778  return p->pBt->pageSize;
39779}
39780
39781/*
39782** Return the number of bytes of space at the end of every page that
39783** are intentually left unused.  This is the "reserved" space that is
39784** sometimes used by extensions.
39785*/
39786SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
39787  int n;
39788  sqlite3BtreeEnter(p);
39789  n = p->pBt->pageSize - p->pBt->usableSize;
39790  sqlite3BtreeLeave(p);
39791  return n;
39792}
39793
39794/*
39795** Set the maximum page count for a database if mxPage is positive.
39796** No changes are made if mxPage is 0 or negative.
39797** Regardless of the value of mxPage, return the maximum page count.
39798*/
39799SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
39800  int n;
39801  sqlite3BtreeEnter(p);
39802  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
39803  sqlite3BtreeLeave(p);
39804  return n;
39805}
39806#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
39807
39808/*
39809** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
39810** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
39811** is disabled. The default value for the auto-vacuum property is
39812** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
39813*/
39814SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
39815#ifdef SQLITE_OMIT_AUTOVACUUM
39816  return SQLITE_READONLY;
39817#else
39818  BtShared *pBt = p->pBt;
39819  int rc = SQLITE_OK;
39820  u8 av = (u8)autoVacuum;
39821
39822  sqlite3BtreeEnter(p);
39823  if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
39824    rc = SQLITE_READONLY;
39825  }else{
39826    pBt->autoVacuum = av ?1:0;
39827    pBt->incrVacuum = av==2 ?1:0;
39828  }
39829  sqlite3BtreeLeave(p);
39830  return rc;
39831#endif
39832}
39833
39834/*
39835** Return the value of the 'auto-vacuum' property. If auto-vacuum is
39836** enabled 1 is returned. Otherwise 0.
39837*/
39838SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
39839#ifdef SQLITE_OMIT_AUTOVACUUM
39840  return BTREE_AUTOVACUUM_NONE;
39841#else
39842  int rc;
39843  sqlite3BtreeEnter(p);
39844  rc = (
39845    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
39846    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
39847    BTREE_AUTOVACUUM_INCR
39848  );
39849  sqlite3BtreeLeave(p);
39850  return rc;
39851#endif
39852}
39853
39854
39855/*
39856** Get a reference to pPage1 of the database file.  This will
39857** also acquire a readlock on that file.
39858**
39859** SQLITE_OK is returned on success.  If the file is not a
39860** well-formed database file, then SQLITE_CORRUPT is returned.
39861** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
39862** is returned if we run out of memory.
39863*/
39864static int lockBtree(BtShared *pBt){
39865  int rc;
39866  MemPage *pPage1;
39867  int nPage;
39868
39869  assert( sqlite3_mutex_held(pBt->mutex) );
39870  assert( pBt->pPage1==0 );
39871  rc = sqlite3PagerSharedLock(pBt->pPager);
39872  if( rc!=SQLITE_OK ) return rc;
39873  rc = btreeGetPage(pBt, 1, &pPage1, 0);
39874  if( rc!=SQLITE_OK ) return rc;
39875
39876  /* Do some checking to help insure the file we opened really is
39877  ** a valid database file.
39878  */
39879  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
39880  if( rc!=SQLITE_OK ){
39881    goto page1_init_failed;
39882  }else if( nPage>0 ){
39883    int pageSize;
39884    int usableSize;
39885    u8 *page1 = pPage1->aData;
39886    rc = SQLITE_NOTADB;
39887    if( memcmp(page1, zMagicHeader, 16)!=0 ){
39888      goto page1_init_failed;
39889    }
39890    if( page1[18]>1 ){
39891      pBt->readOnly = 1;
39892    }
39893    if( page1[19]>1 ){
39894      goto page1_init_failed;
39895    }
39896
39897    /* The maximum embedded fraction must be exactly 25%.  And the minimum
39898    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
39899    ** The original design allowed these amounts to vary, but as of
39900    ** version 3.6.0, we require them to be fixed.
39901    */
39902    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
39903      goto page1_init_failed;
39904    }
39905    pageSize = get2byte(&page1[16]);
39906    if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
39907        (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
39908    ){
39909      goto page1_init_failed;
39910    }
39911    assert( (pageSize & 7)==0 );
39912    usableSize = pageSize - page1[20];
39913    if( pageSize!=pBt->pageSize ){
39914      /* After reading the first page of the database assuming a page size
39915      ** of BtShared.pageSize, we have discovered that the page-size is
39916      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
39917      ** zero and return SQLITE_OK. The caller will call this function
39918      ** again with the correct page-size.
39919      */
39920      releasePage(pPage1);
39921      pBt->usableSize = (u16)usableSize;
39922      pBt->pageSize = (u16)pageSize;
39923      freeTempSpace(pBt);
39924      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
39925                                   pageSize-usableSize);
39926      return rc;
39927    }
39928    if( usableSize<480 ){
39929      goto page1_init_failed;
39930    }
39931    pBt->pageSize = (u16)pageSize;
39932    pBt->usableSize = (u16)usableSize;
39933#ifndef SQLITE_OMIT_AUTOVACUUM
39934    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
39935    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
39936#endif
39937  }
39938
39939  /* maxLocal is the maximum amount of payload to store locally for
39940  ** a cell.  Make sure it is small enough so that at least minFanout
39941  ** cells can will fit on one page.  We assume a 10-byte page header.
39942  ** Besides the payload, the cell must store:
39943  **     2-byte pointer to the cell
39944  **     4-byte child pointer
39945  **     9-byte nKey value
39946  **     4-byte nData value
39947  **     4-byte overflow page pointer
39948  ** So a cell consists of a 2-byte poiner, a header which is as much as
39949  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
39950  ** page pointer.
39951  */
39952  pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
39953  pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
39954  pBt->maxLeaf = pBt->usableSize - 35;
39955  pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
39956  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
39957  pBt->pPage1 = pPage1;
39958  return SQLITE_OK;
39959
39960page1_init_failed:
39961  releasePage(pPage1);
39962  pBt->pPage1 = 0;
39963  return rc;
39964}
39965
39966/*
39967** If there are no outstanding cursors and we are not in the middle
39968** of a transaction but there is a read lock on the database, then
39969** this routine unrefs the first page of the database file which
39970** has the effect of releasing the read lock.
39971**
39972** If there is a transaction in progress, this routine is a no-op.
39973*/
39974static void unlockBtreeIfUnused(BtShared *pBt){
39975  assert( sqlite3_mutex_held(pBt->mutex) );
39976  assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
39977  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
39978    assert( pBt->pPage1->aData );
39979    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
39980    assert( pBt->pPage1->aData );
39981    releasePage(pBt->pPage1);
39982    pBt->pPage1 = 0;
39983  }
39984}
39985
39986/*
39987** If pBt points to an empty file then convert that empty file
39988** into a new empty database by initializing the first page of
39989** the database.
39990*/
39991static int newDatabase(BtShared *pBt){
39992  MemPage *pP1;
39993  unsigned char *data;
39994  int rc;
39995  int nPage;
39996
39997  assert( sqlite3_mutex_held(pBt->mutex) );
39998  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
39999  if( rc!=SQLITE_OK || nPage>0 ){
40000    return rc;
40001  }
40002  pP1 = pBt->pPage1;
40003  assert( pP1!=0 );
40004  data = pP1->aData;
40005  rc = sqlite3PagerWrite(pP1->pDbPage);
40006  if( rc ) return rc;
40007  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
40008  assert( sizeof(zMagicHeader)==16 );
40009  put2byte(&data[16], pBt->pageSize);
40010  data[18] = 1;
40011  data[19] = 1;
40012  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
40013  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
40014  data[21] = 64;
40015  data[22] = 32;
40016  data[23] = 32;
40017  memset(&data[24], 0, 100-24);
40018  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
40019  pBt->pageSizeFixed = 1;
40020#ifndef SQLITE_OMIT_AUTOVACUUM
40021  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
40022  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
40023  put4byte(&data[36 + 4*4], pBt->autoVacuum);
40024  put4byte(&data[36 + 7*4], pBt->incrVacuum);
40025#endif
40026  return SQLITE_OK;
40027}
40028
40029/*
40030** Attempt to start a new transaction. A write-transaction
40031** is started if the second argument is nonzero, otherwise a read-
40032** transaction.  If the second argument is 2 or more and exclusive
40033** transaction is started, meaning that no other process is allowed
40034** to access the database.  A preexisting transaction may not be
40035** upgraded to exclusive by calling this routine a second time - the
40036** exclusivity flag only works for a new transaction.
40037**
40038** A write-transaction must be started before attempting any
40039** changes to the database.  None of the following routines
40040** will work unless a transaction is started first:
40041**
40042**      sqlite3BtreeCreateTable()
40043**      sqlite3BtreeCreateIndex()
40044**      sqlite3BtreeClearTable()
40045**      sqlite3BtreeDropTable()
40046**      sqlite3BtreeInsert()
40047**      sqlite3BtreeDelete()
40048**      sqlite3BtreeUpdateMeta()
40049**
40050** If an initial attempt to acquire the lock fails because of lock contention
40051** and the database was previously unlocked, then invoke the busy handler
40052** if there is one.  But if there was previously a read-lock, do not
40053** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
40054** returned when there is already a read-lock in order to avoid a deadlock.
40055**
40056** Suppose there are two processes A and B.  A has a read lock and B has
40057** a reserved lock.  B tries to promote to exclusive but is blocked because
40058** of A's read lock.  A tries to promote to reserved but is blocked by B.
40059** One or the other of the two processes must give way or there can be
40060** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
40061** when A already has a read lock, we encourage A to give up and let B
40062** proceed.
40063*/
40064SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
40065  sqlite3 *pBlock = 0;
40066  BtShared *pBt = p->pBt;
40067  int rc = SQLITE_OK;
40068
40069  sqlite3BtreeEnter(p);
40070  btreeIntegrity(p);
40071
40072  /* If the btree is already in a write-transaction, or it
40073  ** is already in a read-transaction and a read-transaction
40074  ** is requested, this is a no-op.
40075  */
40076  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
40077    goto trans_begun;
40078  }
40079
40080  /* Write transactions are not possible on a read-only database */
40081  if( pBt->readOnly && wrflag ){
40082    rc = SQLITE_READONLY;
40083    goto trans_begun;
40084  }
40085
40086#ifndef SQLITE_OMIT_SHARED_CACHE
40087  /* If another database handle has already opened a write transaction
40088  ** on this shared-btree structure and a second write transaction is
40089  ** requested, return SQLITE_LOCKED.
40090  */
40091  if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
40092    pBlock = pBt->pWriter->db;
40093  }else if( wrflag>1 ){
40094    BtLock *pIter;
40095    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
40096      if( pIter->pBtree!=p ){
40097        pBlock = pIter->pBtree->db;
40098        break;
40099      }
40100    }
40101  }
40102  if( pBlock ){
40103    sqlite3ConnectionBlocked(p->db, pBlock);
40104    rc = SQLITE_LOCKED_SHAREDCACHE;
40105    goto trans_begun;
40106  }
40107#endif
40108
40109  /* Any read-only or read-write transaction implies a read-lock on
40110  ** page 1. So if some other shared-cache client already has a write-lock
40111  ** on page 1, the transaction cannot be opened. */
40112  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
40113  if( SQLITE_OK!=rc ) goto trans_begun;
40114
40115  do {
40116    /* Call lockBtree() until either pBt->pPage1 is populated or
40117    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
40118    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
40119    ** reading page 1 it discovers that the page-size of the database
40120    ** file is not pBt->pageSize. In this case lockBtree() will update
40121    ** pBt->pageSize to the page-size of the file on disk.
40122    */
40123    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
40124
40125    if( rc==SQLITE_OK && wrflag ){
40126      if( pBt->readOnly ){
40127        rc = SQLITE_READONLY;
40128      }else{
40129        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
40130        if( rc==SQLITE_OK ){
40131          rc = newDatabase(pBt);
40132        }
40133      }
40134    }
40135
40136    if( rc!=SQLITE_OK ){
40137      unlockBtreeIfUnused(pBt);
40138    }
40139  }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
40140          btreeInvokeBusyHandler(pBt) );
40141
40142  if( rc==SQLITE_OK ){
40143    if( p->inTrans==TRANS_NONE ){
40144      pBt->nTransaction++;
40145#ifndef SQLITE_OMIT_SHARED_CACHE
40146      if( p->sharable ){
40147	assert( p->lock.pBtree==p && p->lock.iTable==1 );
40148        p->lock.eLock = READ_LOCK;
40149        p->lock.pNext = pBt->pLock;
40150        pBt->pLock = &p->lock;
40151      }
40152#endif
40153    }
40154    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
40155    if( p->inTrans>pBt->inTransaction ){
40156      pBt->inTransaction = p->inTrans;
40157    }
40158#ifndef SQLITE_OMIT_SHARED_CACHE
40159    if( wrflag ){
40160      assert( !pBt->pWriter );
40161      pBt->pWriter = p;
40162      pBt->isExclusive = (u8)(wrflag>1);
40163    }
40164#endif
40165  }
40166
40167
40168trans_begun:
40169  if( rc==SQLITE_OK && wrflag ){
40170    /* This call makes sure that the pager has the correct number of
40171    ** open savepoints. If the second parameter is greater than 0 and
40172    ** the sub-journal is not already open, then it will be opened here.
40173    */
40174    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
40175  }
40176
40177  btreeIntegrity(p);
40178  sqlite3BtreeLeave(p);
40179  return rc;
40180}
40181
40182#ifndef SQLITE_OMIT_AUTOVACUUM
40183
40184/*
40185** Set the pointer-map entries for all children of page pPage. Also, if
40186** pPage contains cells that point to overflow pages, set the pointer
40187** map entries for the overflow pages as well.
40188*/
40189static int setChildPtrmaps(MemPage *pPage){
40190  int i;                             /* Counter variable */
40191  int nCell;                         /* Number of cells in page pPage */
40192  int rc;                            /* Return code */
40193  BtShared *pBt = pPage->pBt;
40194  u8 isInitOrig = pPage->isInit;
40195  Pgno pgno = pPage->pgno;
40196
40197  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
40198  rc = btreeInitPage(pPage);
40199  if( rc!=SQLITE_OK ){
40200    goto set_child_ptrmaps_out;
40201  }
40202  nCell = pPage->nCell;
40203
40204  for(i=0; i<nCell; i++){
40205    u8 *pCell = findCell(pPage, i);
40206
40207    ptrmapPutOvflPtr(pPage, pCell, &rc);
40208
40209    if( !pPage->leaf ){
40210      Pgno childPgno = get4byte(pCell);
40211      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
40212    }
40213  }
40214
40215  if( !pPage->leaf ){
40216    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
40217    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
40218  }
40219
40220set_child_ptrmaps_out:
40221  pPage->isInit = isInitOrig;
40222  return rc;
40223}
40224
40225/*
40226** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
40227** that it points to iTo. Parameter eType describes the type of pointer to
40228** be modified, as  follows:
40229**
40230** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
40231**                   page of pPage.
40232**
40233** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
40234**                   page pointed to by one of the cells on pPage.
40235**
40236** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
40237**                   overflow page in the list.
40238*/
40239static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
40240  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
40241  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
40242  if( eType==PTRMAP_OVERFLOW2 ){
40243    /* The pointer is always the first 4 bytes of the page in this case.  */
40244    if( get4byte(pPage->aData)!=iFrom ){
40245      return SQLITE_CORRUPT_BKPT(MODIFY_PAGE_PTR_1_CORRUPTION); // Android Change
40246    }
40247    put4byte(pPage->aData, iTo);
40248  }else{
40249    u8 isInitOrig = pPage->isInit;
40250    int i;
40251    int nCell;
40252
40253    btreeInitPage(pPage);
40254    nCell = pPage->nCell;
40255
40256    for(i=0; i<nCell; i++){
40257      u8 *pCell = findCell(pPage, i);
40258      if( eType==PTRMAP_OVERFLOW1 ){
40259        CellInfo info;
40260        btreeParseCellPtr(pPage, pCell, &info);
40261        if( info.iOverflow ){
40262          if( iFrom==get4byte(&pCell[info.iOverflow]) ){
40263            put4byte(&pCell[info.iOverflow], iTo);
40264            break;
40265          }
40266        }
40267      }else{
40268        if( get4byte(pCell)==iFrom ){
40269          put4byte(pCell, iTo);
40270          break;
40271        }
40272      }
40273    }
40274
40275    if( i==nCell ){
40276      if( eType!=PTRMAP_BTREE ||
40277          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
40278        return SQLITE_CORRUPT_BKPT(MODIFY_PAGE_PTR_2_CORRUPTION); // Android Change
40279      }
40280      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
40281    }
40282
40283    pPage->isInit = isInitOrig;
40284  }
40285  return SQLITE_OK;
40286}
40287
40288
40289/*
40290** Move the open database page pDbPage to location iFreePage in the
40291** database. The pDbPage reference remains valid.
40292**
40293** The isCommit flag indicates that there is no need to remember that
40294** the journal needs to be sync()ed before database page pDbPage->pgno
40295** can be written to. The caller has already promised not to write to that
40296** page.
40297*/
40298static int relocatePage(
40299  BtShared *pBt,           /* Btree */
40300  MemPage *pDbPage,        /* Open page to move */
40301  u8 eType,                /* Pointer map 'type' entry for pDbPage */
40302  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
40303  Pgno iFreePage,          /* The location to move pDbPage to */
40304  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
40305){
40306  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
40307  Pgno iDbPage = pDbPage->pgno;
40308  Pager *pPager = pBt->pPager;
40309  int rc;
40310
40311  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
40312      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
40313  assert( sqlite3_mutex_held(pBt->mutex) );
40314  assert( pDbPage->pBt==pBt );
40315
40316  /* Move page iDbPage from its current location to page number iFreePage */
40317  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
40318      iDbPage, iFreePage, iPtrPage, eType));
40319  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
40320  if( rc!=SQLITE_OK ){
40321    return rc;
40322  }
40323  pDbPage->pgno = iFreePage;
40324
40325  /* If pDbPage was a btree-page, then it may have child pages and/or cells
40326  ** that point to overflow pages. The pointer map entries for all these
40327  ** pages need to be changed.
40328  **
40329  ** If pDbPage is an overflow page, then the first 4 bytes may store a
40330  ** pointer to a subsequent overflow page. If this is the case, then
40331  ** the pointer map needs to be updated for the subsequent overflow page.
40332  */
40333  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
40334    rc = setChildPtrmaps(pDbPage);
40335    if( rc!=SQLITE_OK ){
40336      return rc;
40337    }
40338  }else{
40339    Pgno nextOvfl = get4byte(pDbPage->aData);
40340    if( nextOvfl!=0 ){
40341      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
40342      if( rc!=SQLITE_OK ){
40343        return rc;
40344      }
40345    }
40346  }
40347
40348  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
40349  ** that it points at iFreePage. Also fix the pointer map entry for
40350  ** iPtrPage.
40351  */
40352  if( eType!=PTRMAP_ROOTPAGE ){
40353    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
40354    if( rc!=SQLITE_OK ){
40355      return rc;
40356    }
40357    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
40358    if( rc!=SQLITE_OK ){
40359      releasePage(pPtrPage);
40360      return rc;
40361    }
40362    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
40363    releasePage(pPtrPage);
40364    if( rc==SQLITE_OK ){
40365      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
40366    }
40367  }
40368  return rc;
40369}
40370
40371/* Forward declaration required by incrVacuumStep(). */
40372static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
40373
40374/*
40375** Perform a single step of an incremental-vacuum. If successful,
40376** return SQLITE_OK. If there is no work to do (and therefore no
40377** point in calling this function again), return SQLITE_DONE.
40378**
40379** More specificly, this function attempts to re-organize the
40380** database so that the last page of the file currently in use
40381** is no longer in use.
40382**
40383** If the nFin parameter is non-zero, this function assumes
40384** that the caller will keep calling incrVacuumStep() until
40385** it returns SQLITE_DONE or an error, and that nFin is the
40386** number of pages the database file will contain after this
40387** process is complete.  If nFin is zero, it is assumed that
40388** incrVacuumStep() will be called a finite amount of times
40389** which may or may not empty the freelist.  A full autovacuum
40390** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
40391*/
40392static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
40393  Pgno nFreeList;           /* Number of pages still on the free-list */
40394
40395  assert( sqlite3_mutex_held(pBt->mutex) );
40396  assert( iLastPg>nFin );
40397
40398  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
40399    int rc;
40400    u8 eType;
40401    Pgno iPtrPage;
40402
40403    nFreeList = get4byte(&pBt->pPage1->aData[36]);
40404    if( nFreeList==0 ){
40405      return SQLITE_DONE;
40406    }
40407
40408    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
40409    if( rc!=SQLITE_OK ){
40410      return rc;
40411    }
40412    if( eType==PTRMAP_ROOTPAGE ){
40413      return SQLITE_CORRUPT_BKPT(INCR_VAC_STEP_1_CORRUPTION); // Android Change
40414    }
40415
40416    if( eType==PTRMAP_FREEPAGE ){
40417      if( nFin==0 ){
40418        /* Remove the page from the files free-list. This is not required
40419        ** if nFin is non-zero. In that case, the free-list will be
40420        ** truncated to zero after this function returns, so it doesn't
40421        ** matter if it still contains some garbage entries.
40422        */
40423        Pgno iFreePg;
40424        MemPage *pFreePg;
40425        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
40426        if( rc!=SQLITE_OK ){
40427          return rc;
40428        }
40429        assert( iFreePg==iLastPg );
40430        releasePage(pFreePg);
40431      }
40432    } else {
40433      Pgno iFreePg;             /* Index of free page to move pLastPg to */
40434      MemPage *pLastPg;
40435
40436      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
40437      if( rc!=SQLITE_OK ){
40438        return rc;
40439      }
40440
40441      /* If nFin is zero, this loop runs exactly once and page pLastPg
40442      ** is swapped with the first free page pulled off the free list.
40443      **
40444      ** On the other hand, if nFin is greater than zero, then keep
40445      ** looping until a free-page located within the first nFin pages
40446      ** of the file is found.
40447      */
40448      do {
40449        MemPage *pFreePg;
40450        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
40451        if( rc!=SQLITE_OK ){
40452          releasePage(pLastPg);
40453          return rc;
40454        }
40455        releasePage(pFreePg);
40456      }while( nFin!=0 && iFreePg>nFin );
40457      assert( iFreePg<iLastPg );
40458
40459      rc = sqlite3PagerWrite(pLastPg->pDbPage);
40460      if( rc==SQLITE_OK ){
40461        rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
40462      }
40463      releasePage(pLastPg);
40464      if( rc!=SQLITE_OK ){
40465        return rc;
40466      }
40467    }
40468  }
40469
40470  if( nFin==0 ){
40471    iLastPg--;
40472    while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
40473      if( PTRMAP_ISPAGE(pBt, iLastPg) ){
40474        MemPage *pPg;
40475        int rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
40476        if( rc!=SQLITE_OK ){
40477          return rc;
40478        }
40479        rc = sqlite3PagerWrite(pPg->pDbPage);
40480        releasePage(pPg);
40481        if( rc!=SQLITE_OK ){
40482          return rc;
40483        }
40484      }
40485      iLastPg--;
40486    }
40487    sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
40488  }
40489  return SQLITE_OK;
40490}
40491
40492/*
40493** A write-transaction must be opened before calling this function.
40494** It performs a single unit of work towards an incremental vacuum.
40495**
40496** If the incremental vacuum is finished after this function has run,
40497** SQLITE_DONE is returned. If it is not finished, but no error occurred,
40498** SQLITE_OK is returned. Otherwise an SQLite error code.
40499*/
40500SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
40501  int rc;
40502  BtShared *pBt = p->pBt;
40503
40504  sqlite3BtreeEnter(p);
40505  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
40506  if( !pBt->autoVacuum ){
40507    rc = SQLITE_DONE;
40508  }else{
40509    invalidateAllOverflowCache(pBt);
40510    rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
40511  }
40512  sqlite3BtreeLeave(p);
40513  return rc;
40514}
40515
40516/*
40517** This routine is called prior to sqlite3PagerCommit when a transaction
40518** is commited for an auto-vacuum database.
40519**
40520** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
40521** the database file should be truncated to during the commit process.
40522** i.e. the database has been reorganized so that only the first *pnTrunc
40523** pages are in use.
40524*/
40525static int autoVacuumCommit(BtShared *pBt){
40526  int rc = SQLITE_OK;
40527  Pager *pPager = pBt->pPager;
40528  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
40529
40530  assert( sqlite3_mutex_held(pBt->mutex) );
40531  invalidateAllOverflowCache(pBt);
40532  assert(pBt->autoVacuum);
40533  if( !pBt->incrVacuum ){
40534    Pgno nFin;         /* Number of pages in database after autovacuuming */
40535    Pgno nFree;        /* Number of pages on the freelist initially */
40536    Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
40537    Pgno iFree;        /* The next page to be freed */
40538    int nEntry;        /* Number of entries on one ptrmap page */
40539    Pgno nOrig;        /* Database size before freeing */
40540
40541    nOrig = pagerPagecount(pBt);
40542    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
40543      /* It is not possible to create a database for which the final page
40544      ** is either a pointer-map page or the pending-byte page. If one
40545      ** is encountered, this indicates corruption.
40546      */
40547      return SQLITE_CORRUPT_BKPT(AUTO_VAC_COMMIT_1_CORRUPTION); // Android Change
40548    }
40549
40550    nFree = get4byte(&pBt->pPage1->aData[36]);
40551    nEntry = pBt->usableSize/5;
40552    nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
40553    nFin = nOrig - nFree - nPtrmap;
40554    if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
40555      nFin--;
40556    }
40557    while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
40558      nFin--;
40559    }
40560    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT(AUTO_VAC_COMMIT_2_CORRUPTION); // Android Change
40561
40562    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
40563      rc = incrVacuumStep(pBt, nFin, iFree);
40564    }
40565    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
40566      rc = SQLITE_OK;
40567      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
40568      put4byte(&pBt->pPage1->aData[32], 0);
40569      put4byte(&pBt->pPage1->aData[36], 0);
40570      sqlite3PagerTruncateImage(pBt->pPager, nFin);
40571    }
40572    if( rc!=SQLITE_OK ){
40573      sqlite3PagerRollback(pPager);
40574    }
40575  }
40576
40577  assert( nRef==sqlite3PagerRefcount(pPager) );
40578  return rc;
40579}
40580
40581#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
40582# define setChildPtrmaps(x) SQLITE_OK
40583#endif
40584
40585/*
40586** This routine does the first phase of a two-phase commit.  This routine
40587** causes a rollback journal to be created (if it does not already exist)
40588** and populated with enough information so that if a power loss occurs
40589** the database can be restored to its original state by playing back
40590** the journal.  Then the contents of the journal are flushed out to
40591** the disk.  After the journal is safely on oxide, the changes to the
40592** database are written into the database file and flushed to oxide.
40593** At the end of this call, the rollback journal still exists on the
40594** disk and we are still holding all locks, so the transaction has not
40595** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
40596** commit process.
40597**
40598** This call is a no-op if no write-transaction is currently active on pBt.
40599**
40600** Otherwise, sync the database file for the btree pBt. zMaster points to
40601** the name of a master journal file that should be written into the
40602** individual journal file, or is NULL, indicating no master journal file
40603** (single database transaction).
40604**
40605** When this is called, the master journal should already have been
40606** created, populated with this journal pointer and synced to disk.
40607**
40608** Once this is routine has returned, the only thing required to commit
40609** the write-transaction for this database file is to delete the journal.
40610*/
40611SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
40612  int rc = SQLITE_OK;
40613  if( p->inTrans==TRANS_WRITE ){
40614    BtShared *pBt = p->pBt;
40615    sqlite3BtreeEnter(p);
40616#ifndef SQLITE_OMIT_AUTOVACUUM
40617    if( pBt->autoVacuum ){
40618      rc = autoVacuumCommit(pBt);
40619      if( rc!=SQLITE_OK ){
40620        sqlite3BtreeLeave(p);
40621        return rc;
40622      }
40623    }
40624#endif
40625    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
40626    sqlite3BtreeLeave(p);
40627  }
40628  return rc;
40629}
40630
40631/*
40632** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
40633** at the conclusion of a transaction.
40634*/
40635static void btreeEndTransaction(Btree *p){
40636  BtShared *pBt = p->pBt;
40637  assert( sqlite3BtreeHoldsMutex(p) );
40638
40639  btreeClearHasContent(pBt);
40640  if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
40641    /* If there are other active statements that belong to this database
40642    ** handle, downgrade to a read-only transaction. The other statements
40643    ** may still be reading from the database.  */
40644    downgradeAllSharedCacheTableLocks(p);
40645    p->inTrans = TRANS_READ;
40646  }else{
40647    /* If the handle had any kind of transaction open, decrement the
40648    ** transaction count of the shared btree. If the transaction count
40649    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
40650    ** call below will unlock the pager.  */
40651    if( p->inTrans!=TRANS_NONE ){
40652      clearAllSharedCacheTableLocks(p);
40653      pBt->nTransaction--;
40654      if( 0==pBt->nTransaction ){
40655        pBt->inTransaction = TRANS_NONE;
40656      }
40657    }
40658
40659    /* Set the current transaction state to TRANS_NONE and unlock the
40660    ** pager if this call closed the only read or write transaction.  */
40661    p->inTrans = TRANS_NONE;
40662    unlockBtreeIfUnused(pBt);
40663  }
40664
40665  btreeIntegrity(p);
40666}
40667
40668/*
40669** Commit the transaction currently in progress.
40670**
40671** This routine implements the second phase of a 2-phase commit.  The
40672** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
40673** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
40674** routine did all the work of writing information out to disk and flushing the
40675** contents so that they are written onto the disk platter.  All this
40676** routine has to do is delete or truncate or zero the header in the
40677** the rollback journal (which causes the transaction to commit) and
40678** drop locks.
40679**
40680** This will release the write lock on the database file.  If there
40681** are no active cursors, it also releases the read lock.
40682*/
40683SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
40684  BtShared *pBt = p->pBt;
40685
40686  sqlite3BtreeEnter(p);
40687  btreeIntegrity(p);
40688
40689  /* If the handle has a write-transaction open, commit the shared-btrees
40690  ** transaction and set the shared state to TRANS_READ.
40691  */
40692  if( p->inTrans==TRANS_WRITE ){
40693    int rc;
40694    assert( pBt->inTransaction==TRANS_WRITE );
40695    assert( pBt->nTransaction>0 );
40696    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
40697    if( rc!=SQLITE_OK ){
40698      sqlite3BtreeLeave(p);
40699      return rc;
40700    }
40701    pBt->inTransaction = TRANS_READ;
40702  }
40703
40704  btreeEndTransaction(p);
40705  sqlite3BtreeLeave(p);
40706  return SQLITE_OK;
40707}
40708
40709/*
40710** Do both phases of a commit.
40711*/
40712SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
40713  int rc;
40714  sqlite3BtreeEnter(p);
40715  rc = sqlite3BtreeCommitPhaseOne(p, 0);
40716  if( rc==SQLITE_OK ){
40717    rc = sqlite3BtreeCommitPhaseTwo(p);
40718  }
40719  sqlite3BtreeLeave(p);
40720  return rc;
40721}
40722
40723#ifndef NDEBUG
40724/*
40725** Return the number of write-cursors open on this handle. This is for use
40726** in assert() expressions, so it is only compiled if NDEBUG is not
40727** defined.
40728**
40729** For the purposes of this routine, a write-cursor is any cursor that
40730** is capable of writing to the databse.  That means the cursor was
40731** originally opened for writing and the cursor has not be disabled
40732** by having its state changed to CURSOR_FAULT.
40733*/
40734static int countWriteCursors(BtShared *pBt){
40735  BtCursor *pCur;
40736  int r = 0;
40737  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
40738    if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
40739  }
40740  return r;
40741}
40742#endif
40743
40744/*
40745** This routine sets the state to CURSOR_FAULT and the error
40746** code to errCode for every cursor on BtShared that pBtree
40747** references.
40748**
40749** Every cursor is tripped, including cursors that belong
40750** to other database connections that happen to be sharing
40751** the cache with pBtree.
40752**
40753** This routine gets called when a rollback occurs.
40754** All cursors using the same cache must be tripped
40755** to prevent them from trying to use the btree after
40756** the rollback.  The rollback may have deleted tables
40757** or moved root pages, so it is not sufficient to
40758** save the state of the cursor.  The cursor must be
40759** invalidated.
40760*/
40761SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
40762  BtCursor *p;
40763  sqlite3BtreeEnter(pBtree);
40764  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
40765    int i;
40766    sqlite3BtreeClearCursor(p);
40767    p->eState = CURSOR_FAULT;
40768    p->skipNext = errCode;
40769    for(i=0; i<=p->iPage; i++){
40770      releasePage(p->apPage[i]);
40771      p->apPage[i] = 0;
40772    }
40773  }
40774  sqlite3BtreeLeave(pBtree);
40775}
40776
40777/*
40778** Rollback the transaction in progress.  All cursors will be
40779** invalided by this operation.  Any attempt to use a cursor
40780** that was open at the beginning of this operation will result
40781** in an error.
40782**
40783** This will release the write lock on the database file.  If there
40784** are no active cursors, it also releases the read lock.
40785*/
40786SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
40787  int rc;
40788  BtShared *pBt = p->pBt;
40789  MemPage *pPage1;
40790
40791  sqlite3BtreeEnter(p);
40792  rc = saveAllCursors(pBt, 0, 0);
40793#ifndef SQLITE_OMIT_SHARED_CACHE
40794  if( rc!=SQLITE_OK ){
40795    /* This is a horrible situation. An IO or malloc() error occurred whilst
40796    ** trying to save cursor positions. If this is an automatic rollback (as
40797    ** the result of a constraint, malloc() failure or IO error) then
40798    ** the cache may be internally inconsistent (not contain valid trees) so
40799    ** we cannot simply return the error to the caller. Instead, abort
40800    ** all queries that may be using any of the cursors that failed to save.
40801    */
40802    sqlite3BtreeTripAllCursors(p, rc);
40803  }
40804#endif
40805  btreeIntegrity(p);
40806
40807  if( p->inTrans==TRANS_WRITE ){
40808    int rc2;
40809
40810    assert( TRANS_WRITE==pBt->inTransaction );
40811    rc2 = sqlite3PagerRollback(pBt->pPager);
40812    if( rc2!=SQLITE_OK ){
40813      rc = rc2;
40814    }
40815
40816    /* The rollback may have destroyed the pPage1->aData value.  So
40817    ** call btreeGetPage() on page 1 again to make
40818    ** sure pPage1->aData is set correctly. */
40819    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
40820      releasePage(pPage1);
40821    }
40822    assert( countWriteCursors(pBt)==0 );
40823    pBt->inTransaction = TRANS_READ;
40824  }
40825
40826  btreeEndTransaction(p);
40827  sqlite3BtreeLeave(p);
40828  return rc;
40829}
40830
40831/*
40832** Start a statement subtransaction. The subtransaction can can be rolled
40833** back independently of the main transaction. You must start a transaction
40834** before starting a subtransaction. The subtransaction is ended automatically
40835** if the main transaction commits or rolls back.
40836**
40837** Statement subtransactions are used around individual SQL statements
40838** that are contained within a BEGIN...COMMIT block.  If a constraint
40839** error occurs within the statement, the effect of that one statement
40840** can be rolled back without having to rollback the entire transaction.
40841**
40842** A statement sub-transaction is implemented as an anonymous savepoint. The
40843** value passed as the second parameter is the total number of savepoints,
40844** including the new anonymous savepoint, open on the B-Tree. i.e. if there
40845** are no active savepoints and no other statement-transactions open,
40846** iStatement is 1. This anonymous savepoint can be released or rolled back
40847** using the sqlite3BtreeSavepoint() function.
40848*/
40849SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
40850  int rc;
40851  BtShared *pBt = p->pBt;
40852  sqlite3BtreeEnter(p);
40853  assert( p->inTrans==TRANS_WRITE );
40854  assert( pBt->readOnly==0 );
40855  assert( iStatement>0 );
40856  assert( iStatement>p->db->nSavepoint );
40857  if( NEVER(p->inTrans!=TRANS_WRITE || pBt->readOnly) ){
40858    rc = SQLITE_INTERNAL;
40859  }else{
40860    assert( pBt->inTransaction==TRANS_WRITE );
40861    /* At the pager level, a statement transaction is a savepoint with
40862    ** an index greater than all savepoints created explicitly using
40863    ** SQL statements. It is illegal to open, release or rollback any
40864    ** such savepoints while the statement transaction savepoint is active.
40865    */
40866    rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
40867  }
40868  sqlite3BtreeLeave(p);
40869  return rc;
40870}
40871
40872/*
40873** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
40874** or SAVEPOINT_RELEASE. This function either releases or rolls back the
40875** savepoint identified by parameter iSavepoint, depending on the value
40876** of op.
40877**
40878** Normally, iSavepoint is greater than or equal to zero. However, if op is
40879** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
40880** contents of the entire transaction are rolled back. This is different
40881** from a normal transaction rollback, as no locks are released and the
40882** transaction remains open.
40883*/
40884SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
40885  int rc = SQLITE_OK;
40886  if( p && p->inTrans==TRANS_WRITE ){
40887    BtShared *pBt = p->pBt;
40888    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
40889    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
40890    sqlite3BtreeEnter(p);
40891    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
40892    if( rc==SQLITE_OK ){
40893      rc = newDatabase(pBt);
40894    }
40895    sqlite3BtreeLeave(p);
40896  }
40897  return rc;
40898}
40899
40900/*
40901** Create a new cursor for the BTree whose root is on the page
40902** iTable. If a read-only cursor is requested, it is assumed that
40903** the caller already has at least a read-only transaction open
40904** on the database already. If a write-cursor is requested, then
40905** the caller is assumed to have an open write transaction.
40906**
40907** If wrFlag==0, then the cursor can only be used for reading.
40908** If wrFlag==1, then the cursor can be used for reading or for
40909** writing if other conditions for writing are also met.  These
40910** are the conditions that must be met in order for writing to
40911** be allowed:
40912**
40913** 1:  The cursor must have been opened with wrFlag==1
40914**
40915** 2:  Other database connections that share the same pager cache
40916**     but which are not in the READ_UNCOMMITTED state may not have
40917**     cursors open with wrFlag==0 on the same table.  Otherwise
40918**     the changes made by this write cursor would be visible to
40919**     the read cursors in the other database connection.
40920**
40921** 3:  The database must be writable (not on read-only media)
40922**
40923** 4:  There must be an active transaction.
40924**
40925** No checking is done to make sure that page iTable really is the
40926** root page of a b-tree.  If it is not, then the cursor acquired
40927** will not work correctly.
40928**
40929** It is assumed that the sqlite3BtreeCursorZero() has been called
40930** on pCur to initialize the memory space prior to invoking this routine.
40931*/
40932static int btreeCursor(
40933  Btree *p,                              /* The btree */
40934  int iTable,                            /* Root page of table to open */
40935  int wrFlag,                            /* 1 to write. 0 read-only */
40936  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
40937  BtCursor *pCur                         /* Space for new cursor */
40938){
40939  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
40940
40941  assert( sqlite3BtreeHoldsMutex(p) );
40942  assert( wrFlag==0 || wrFlag==1 );
40943
40944  /* The following assert statements verify that if this is a sharable
40945  ** b-tree database, the connection is holding the required table locks,
40946  ** and that no other connection has any open cursor that conflicts with
40947  ** this lock.  */
40948  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
40949  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
40950
40951  /* Assert that the caller has opened the required transaction. */
40952  assert( p->inTrans>TRANS_NONE );
40953  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
40954  assert( pBt->pPage1 && pBt->pPage1->aData );
40955
40956  if( NEVER(wrFlag && pBt->readOnly) ){
40957    return SQLITE_READONLY;
40958  }
40959  if( iTable==1 && pagerPagecount(pBt)==0 ){
40960    return SQLITE_EMPTY;
40961  }
40962
40963  /* Now that no other errors can occur, finish filling in the BtCursor
40964  ** variables and link the cursor into the BtShared list.  */
40965  pCur->pgnoRoot = (Pgno)iTable;
40966  pCur->iPage = -1;
40967  pCur->pKeyInfo = pKeyInfo;
40968  pCur->pBtree = p;
40969  pCur->pBt = pBt;
40970  pCur->wrFlag = (u8)wrFlag;
40971  pCur->pNext = pBt->pCursor;
40972  if( pCur->pNext ){
40973    pCur->pNext->pPrev = pCur;
40974  }
40975  pBt->pCursor = pCur;
40976  pCur->eState = CURSOR_INVALID;
40977  pCur->cachedRowid = 0;
40978  return SQLITE_OK;
40979}
40980SQLITE_PRIVATE int sqlite3BtreeCursor(
40981  Btree *p,                                   /* The btree */
40982  int iTable,                                 /* Root page of table to open */
40983  int wrFlag,                                 /* 1 to write. 0 read-only */
40984  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
40985  BtCursor *pCur                              /* Write new cursor here */
40986){
40987  int rc;
40988  sqlite3BtreeEnter(p);
40989  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
40990  sqlite3BtreeLeave(p);
40991  return rc;
40992}
40993
40994/*
40995** Return the size of a BtCursor object in bytes.
40996**
40997** This interfaces is needed so that users of cursors can preallocate
40998** sufficient storage to hold a cursor.  The BtCursor object is opaque
40999** to users so they cannot do the sizeof() themselves - they must call
41000** this routine.
41001*/
41002SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
41003  return ROUND8(sizeof(BtCursor));
41004}
41005
41006/*
41007** Initialize memory that will be converted into a BtCursor object.
41008**
41009** The simple approach here would be to memset() the entire object
41010** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
41011** do not need to be zeroed and they are large, so we can save a lot
41012** of run-time by skipping the initialization of those elements.
41013*/
41014SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
41015  memset(p, 0, offsetof(BtCursor, iPage));
41016}
41017
41018/*
41019** Set the cached rowid value of every cursor in the same database file
41020** as pCur and having the same root page number as pCur.  The value is
41021** set to iRowid.
41022**
41023** Only positive rowid values are considered valid for this cache.
41024** The cache is initialized to zero, indicating an invalid cache.
41025** A btree will work fine with zero or negative rowids.  We just cannot
41026** cache zero or negative rowids, which means tables that use zero or
41027** negative rowids might run a little slower.  But in practice, zero
41028** or negative rowids are very uncommon so this should not be a problem.
41029*/
41030SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
41031  BtCursor *p;
41032  for(p=pCur->pBt->pCursor; p; p=p->pNext){
41033    if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
41034  }
41035  assert( pCur->cachedRowid==iRowid );
41036}
41037
41038/*
41039** Return the cached rowid for the given cursor.  A negative or zero
41040** return value indicates that the rowid cache is invalid and should be
41041** ignored.  If the rowid cache has never before been set, then a
41042** zero is returned.
41043*/
41044SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
41045  return pCur->cachedRowid;
41046}
41047
41048/*
41049** Close a cursor.  The read lock on the database file is released
41050** when the last cursor is closed.
41051*/
41052SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
41053  Btree *pBtree = pCur->pBtree;
41054  if( pBtree ){
41055    int i;
41056    BtShared *pBt = pCur->pBt;
41057    sqlite3BtreeEnter(pBtree);
41058    sqlite3BtreeClearCursor(pCur);
41059    if( pCur->pPrev ){
41060      pCur->pPrev->pNext = pCur->pNext;
41061    }else{
41062      pBt->pCursor = pCur->pNext;
41063    }
41064    if( pCur->pNext ){
41065      pCur->pNext->pPrev = pCur->pPrev;
41066    }
41067    for(i=0; i<=pCur->iPage; i++){
41068      releasePage(pCur->apPage[i]);
41069    }
41070    unlockBtreeIfUnused(pBt);
41071    invalidateOverflowCache(pCur);
41072    /* sqlite3_free(pCur); */
41073    sqlite3BtreeLeave(pBtree);
41074  }
41075  return SQLITE_OK;
41076}
41077
41078/*
41079** Make sure the BtCursor* given in the argument has a valid
41080** BtCursor.info structure.  If it is not already valid, call
41081** btreeParseCell() to fill it in.
41082**
41083** BtCursor.info is a cache of the information in the current cell.
41084** Using this cache reduces the number of calls to btreeParseCell().
41085**
41086** 2007-06-25:  There is a bug in some versions of MSVC that cause the
41087** compiler to crash when getCellInfo() is implemented as a macro.
41088** But there is a measureable speed advantage to using the macro on gcc
41089** (when less compiler optimizations like -Os or -O0 are used and the
41090** compiler is not doing agressive inlining.)  So we use a real function
41091** for MSVC and a macro for everything else.  Ticket #2457.
41092*/
41093#ifndef NDEBUG
41094  static void assertCellInfo(BtCursor *pCur){
41095    CellInfo info;
41096    int iPage = pCur->iPage;
41097    memset(&info, 0, sizeof(info));
41098    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
41099    assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
41100  }
41101#else
41102  #define assertCellInfo(x)
41103#endif
41104#ifdef _MSC_VER
41105  /* Use a real function in MSVC to work around bugs in that compiler. */
41106  static void getCellInfo(BtCursor *pCur){
41107    if( pCur->info.nSize==0 ){
41108      int iPage = pCur->iPage;
41109      btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
41110      pCur->validNKey = 1;
41111    }else{
41112      assertCellInfo(pCur);
41113    }
41114  }
41115#else /* if not _MSC_VER */
41116  /* Use a macro in all other compilers so that the function is inlined */
41117#define getCellInfo(pCur)                                                      \
41118  if( pCur->info.nSize==0 ){                                                   \
41119    int iPage = pCur->iPage;                                                   \
41120    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
41121    pCur->validNKey = 1;                                                       \
41122  }else{                                                                       \
41123    assertCellInfo(pCur);                                                      \
41124  }
41125#endif /* _MSC_VER */
41126
41127#ifndef NDEBUG  /* The next routine used only within assert() statements */
41128/*
41129** Return true if the given BtCursor is valid.  A valid cursor is one
41130** that is currently pointing to a row in a (non-empty) table.
41131** This is a verification routine is used only within assert() statements.
41132*/
41133SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
41134  return pCur && pCur->eState==CURSOR_VALID;
41135}
41136#endif /* NDEBUG */
41137
41138/*
41139** Set *pSize to the size of the buffer needed to hold the value of
41140** the key for the current entry.  If the cursor is not pointing
41141** to a valid entry, *pSize is set to 0.
41142**
41143** For a table with the INTKEY flag set, this routine returns the key
41144** itself, not the number of bytes in the key.
41145**
41146** The caller must position the cursor prior to invoking this routine.
41147**
41148** This routine cannot fail.  It always returns SQLITE_OK.
41149*/
41150SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
41151  assert( cursorHoldsMutex(pCur) );
41152  assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
41153  if( pCur->eState!=CURSOR_VALID ){
41154    *pSize = 0;
41155  }else{
41156    getCellInfo(pCur);
41157    *pSize = pCur->info.nKey;
41158  }
41159  return SQLITE_OK;
41160}
41161
41162/*
41163** Set *pSize to the number of bytes of data in the entry the
41164** cursor currently points to.
41165**
41166** The caller must guarantee that the cursor is pointing to a non-NULL
41167** valid entry.  In other words, the calling procedure must guarantee
41168** that the cursor has Cursor.eState==CURSOR_VALID.
41169**
41170** Failure is not possible.  This function always returns SQLITE_OK.
41171** It might just as well be a procedure (returning void) but we continue
41172** to return an integer result code for historical reasons.
41173*/
41174SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
41175  assert( cursorHoldsMutex(pCur) );
41176  assert( pCur->eState==CURSOR_VALID );
41177  getCellInfo(pCur);
41178  *pSize = pCur->info.nData;
41179  return SQLITE_OK;
41180}
41181
41182/*
41183** Given the page number of an overflow page in the database (parameter
41184** ovfl), this function finds the page number of the next page in the
41185** linked list of overflow pages. If possible, it uses the auto-vacuum
41186** pointer-map data instead of reading the content of page ovfl to do so.
41187**
41188** If an error occurs an SQLite error code is returned. Otherwise:
41189**
41190** The page number of the next overflow page in the linked list is
41191** written to *pPgnoNext. If page ovfl is the last page in its linked
41192** list, *pPgnoNext is set to zero.
41193**
41194** If ppPage is not NULL, and a reference to the MemPage object corresponding
41195** to page number pOvfl was obtained, then *ppPage is set to point to that
41196** reference. It is the responsibility of the caller to call releasePage()
41197** on *ppPage to free the reference. In no reference was obtained (because
41198** the pointer-map was used to obtain the value for *pPgnoNext), then
41199** *ppPage is set to zero.
41200*/
41201static int getOverflowPage(
41202  BtShared *pBt,               /* The database file */
41203  Pgno ovfl,                   /* Current overflow page number */
41204  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
41205  Pgno *pPgnoNext              /* OUT: Next overflow page number */
41206){
41207  Pgno next = 0;
41208  MemPage *pPage = 0;
41209  int rc = SQLITE_OK;
41210
41211  assert( sqlite3_mutex_held(pBt->mutex) );
41212  assert(pPgnoNext);
41213
41214#ifndef SQLITE_OMIT_AUTOVACUUM
41215  /* Try to find the next page in the overflow list using the
41216  ** autovacuum pointer-map pages. Guess that the next page in
41217  ** the overflow list is page number (ovfl+1). If that guess turns
41218  ** out to be wrong, fall back to loading the data of page
41219  ** number ovfl to determine the next page number.
41220  */
41221  if( pBt->autoVacuum ){
41222    Pgno pgno;
41223    Pgno iGuess = ovfl+1;
41224    u8 eType;
41225
41226    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
41227      iGuess++;
41228    }
41229
41230    if( iGuess<=pagerPagecount(pBt) ){
41231      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
41232      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
41233        next = iGuess;
41234        rc = SQLITE_DONE;
41235      }
41236    }
41237  }
41238#endif
41239
41240  assert( next==0 || rc==SQLITE_DONE );
41241  if( rc==SQLITE_OK ){
41242    rc = btreeGetPage(pBt, ovfl, &pPage, 0);
41243    assert( rc==SQLITE_OK || pPage==0 );
41244    if( rc==SQLITE_OK ){
41245      next = get4byte(pPage->aData);
41246    }
41247  }
41248
41249  *pPgnoNext = next;
41250  if( ppPage ){
41251    *ppPage = pPage;
41252  }else{
41253    releasePage(pPage);
41254  }
41255  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
41256}
41257
41258/*
41259** Copy data from a buffer to a page, or from a page to a buffer.
41260**
41261** pPayload is a pointer to data stored on database page pDbPage.
41262** If argument eOp is false, then nByte bytes of data are copied
41263** from pPayload to the buffer pointed at by pBuf. If eOp is true,
41264** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
41265** of data are copied from the buffer pBuf to pPayload.
41266**
41267** SQLITE_OK is returned on success, otherwise an error code.
41268*/
41269static int copyPayload(
41270  void *pPayload,           /* Pointer to page data */
41271  void *pBuf,               /* Pointer to buffer */
41272  int nByte,                /* Number of bytes to copy */
41273  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
41274  DbPage *pDbPage           /* Page containing pPayload */
41275){
41276  if( eOp ){
41277    /* Copy data from buffer to page (a write operation) */
41278    int rc = sqlite3PagerWrite(pDbPage);
41279    if( rc!=SQLITE_OK ){
41280      return rc;
41281    }
41282    memcpy(pPayload, pBuf, nByte);
41283  }else{
41284    /* Copy data from page to buffer (a read operation) */
41285    memcpy(pBuf, pPayload, nByte);
41286  }
41287  return SQLITE_OK;
41288}
41289
41290/*
41291** This function is used to read or overwrite payload information
41292** for the entry that the pCur cursor is pointing to. If the eOp
41293** parameter is 0, this is a read operation (data copied into
41294** buffer pBuf). If it is non-zero, a write (data copied from
41295** buffer pBuf).
41296**
41297** A total of "amt" bytes are read or written beginning at "offset".
41298** Data is read to or from the buffer pBuf.
41299**
41300** The content being read or written might appear on the main page
41301** or be scattered out on multiple overflow pages.
41302**
41303** If the BtCursor.isIncrblobHandle flag is set, and the current
41304** cursor entry uses one or more overflow pages, this function
41305** allocates space for and lazily popluates the overflow page-list
41306** cache array (BtCursor.aOverflow). Subsequent calls use this
41307** cache to make seeking to the supplied offset more efficient.
41308**
41309** Once an overflow page-list cache has been allocated, it may be
41310** invalidated if some other cursor writes to the same table, or if
41311** the cursor is moved to a different row. Additionally, in auto-vacuum
41312** mode, the following events may invalidate an overflow page-list cache.
41313**
41314**   * An incremental vacuum,
41315**   * A commit in auto_vacuum="full" mode,
41316**   * Creating a table (may require moving an overflow page).
41317*/
41318static int accessPayload(
41319  BtCursor *pCur,      /* Cursor pointing to entry to read from */
41320  u32 offset,          /* Begin reading this far into payload */
41321  u32 amt,             /* Read this many bytes */
41322  unsigned char *pBuf, /* Write the bytes into this buffer */
41323  int eOp              /* zero to read. non-zero to write. */
41324){
41325  unsigned char *aPayload;
41326  int rc = SQLITE_OK;
41327  u32 nKey;
41328  int iIdx = 0;
41329  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
41330  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
41331
41332  assert( pPage );
41333  assert( pCur->eState==CURSOR_VALID );
41334  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
41335  assert( cursorHoldsMutex(pCur) );
41336
41337  getCellInfo(pCur);
41338  aPayload = pCur->info.pCell + pCur->info.nHeader;
41339  nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
41340
41341  if( NEVER(offset+amt > nKey+pCur->info.nData)
41342   || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
41343  ){
41344    /* Trying to read or write past the end of the data is an error */
41345    return SQLITE_CORRUPT_BKPT(ACCESS_PAYLOAD_1_CORRUPTION); // Android Change
41346  }
41347
41348  /* Check if data must be read/written to/from the btree page itself. */
41349  if( offset<pCur->info.nLocal ){
41350    int a = amt;
41351    if( a+offset>pCur->info.nLocal ){
41352      a = pCur->info.nLocal - offset;
41353    }
41354    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
41355    offset = 0;
41356    pBuf += a;
41357    amt -= a;
41358  }else{
41359    offset -= pCur->info.nLocal;
41360  }
41361
41362  if( rc==SQLITE_OK && amt>0 ){
41363    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
41364    Pgno nextPage;
41365
41366    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
41367
41368#ifndef SQLITE_OMIT_INCRBLOB
41369    /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
41370    ** has not been allocated, allocate it now. The array is sized at
41371    ** one entry for each overflow page in the overflow chain. The
41372    ** page number of the first overflow page is stored in aOverflow[0],
41373    ** etc. A value of 0 in the aOverflow[] array means "not yet known"
41374    ** (the cache is lazily populated).
41375    */
41376    if( pCur->isIncrblobHandle && !pCur->aOverflow ){
41377      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
41378      pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
41379      /* nOvfl is always positive.  If it were zero, fetchPayload would have
41380      ** been used instead of this routine. */
41381      if( ALWAYS(nOvfl) && !pCur->aOverflow ){
41382        rc = SQLITE_NOMEM;
41383      }
41384    }
41385
41386    /* If the overflow page-list cache has been allocated and the
41387    ** entry for the first required overflow page is valid, skip
41388    ** directly to it.
41389    */
41390    if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
41391      iIdx = (offset/ovflSize);
41392      nextPage = pCur->aOverflow[iIdx];
41393      offset = (offset%ovflSize);
41394    }
41395#endif
41396
41397    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
41398
41399#ifndef SQLITE_OMIT_INCRBLOB
41400      /* If required, populate the overflow page-list cache. */
41401      if( pCur->aOverflow ){
41402        assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
41403        pCur->aOverflow[iIdx] = nextPage;
41404      }
41405#endif
41406
41407      if( offset>=ovflSize ){
41408        /* The only reason to read this page is to obtain the page
41409        ** number for the next page in the overflow chain. The page
41410        ** data is not required. So first try to lookup the overflow
41411        ** page-list cache, if any, then fall back to the getOverflowPage()
41412        ** function.
41413        */
41414#ifndef SQLITE_OMIT_INCRBLOB
41415        if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
41416          nextPage = pCur->aOverflow[iIdx+1];
41417        } else
41418#endif
41419          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
41420        offset -= ovflSize;
41421      }else{
41422        /* Need to read this page properly. It contains some of the
41423        ** range of data that is being read (eOp==0) or written (eOp!=0).
41424        */
41425        DbPage *pDbPage;
41426        int a = amt;
41427        rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
41428        if( rc==SQLITE_OK ){
41429          aPayload = sqlite3PagerGetData(pDbPage);
41430          nextPage = get4byte(aPayload);
41431          if( a + offset > ovflSize ){
41432            a = ovflSize - offset;
41433          }
41434          rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
41435          sqlite3PagerUnref(pDbPage);
41436          offset = 0;
41437          amt -= a;
41438          pBuf += a;
41439        }
41440      }
41441    }
41442  }
41443
41444  if( rc==SQLITE_OK && amt>0 ){
41445    return SQLITE_CORRUPT_BKPT(AUTO_VAC_COMMIT_2_CORRUPTION); // Android Change
41446  }
41447  return rc;
41448}
41449
41450/*
41451** Read part of the key associated with cursor pCur.  Exactly
41452** "amt" bytes will be transfered into pBuf[].  The transfer
41453** begins at "offset".
41454**
41455** The caller must ensure that pCur is pointing to a valid row
41456** in the table.
41457**
41458** Return SQLITE_OK on success or an error code if anything goes
41459** wrong.  An error is returned if "offset+amt" is larger than
41460** the available payload.
41461*/
41462SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
41463  assert( cursorHoldsMutex(pCur) );
41464  assert( pCur->eState==CURSOR_VALID );
41465  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
41466  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
41467  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
41468}
41469
41470/*
41471** Read part of the data associated with cursor pCur.  Exactly
41472** "amt" bytes will be transfered into pBuf[].  The transfer
41473** begins at "offset".
41474**
41475** Return SQLITE_OK on success or an error code if anything goes
41476** wrong.  An error is returned if "offset+amt" is larger than
41477** the available payload.
41478*/
41479SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
41480  int rc;
41481
41482#ifndef SQLITE_OMIT_INCRBLOB
41483  if ( pCur->eState==CURSOR_INVALID ){
41484    return SQLITE_ABORT;
41485  }
41486#endif
41487
41488  assert( cursorHoldsMutex(pCur) );
41489  rc = restoreCursorPosition(pCur);
41490  if( rc==SQLITE_OK ){
41491    assert( pCur->eState==CURSOR_VALID );
41492    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
41493    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
41494    rc = accessPayload(pCur, offset, amt, pBuf, 0);
41495  }
41496  return rc;
41497}
41498
41499/*
41500** Return a pointer to payload information from the entry that the
41501** pCur cursor is pointing to.  The pointer is to the beginning of
41502** the key if skipKey==0 and it points to the beginning of data if
41503** skipKey==1.  The number of bytes of available key/data is written
41504** into *pAmt.  If *pAmt==0, then the value returned will not be
41505** a valid pointer.
41506**
41507** This routine is an optimization.  It is common for the entire key
41508** and data to fit on the local page and for there to be no overflow
41509** pages.  When that is so, this routine can be used to access the
41510** key and data without making a copy.  If the key and/or data spills
41511** onto overflow pages, then accessPayload() must be used to reassemble
41512** the key/data and copy it into a preallocated buffer.
41513**
41514** The pointer returned by this routine looks directly into the cached
41515** page of the database.  The data might change or move the next time
41516** any btree routine is called.
41517*/
41518static const unsigned char *fetchPayload(
41519  BtCursor *pCur,      /* Cursor pointing to entry to read from */
41520  int *pAmt,           /* Write the number of available bytes here */
41521  int skipKey          /* read beginning at data if this is true */
41522){
41523  unsigned char *aPayload;
41524  MemPage *pPage;
41525  u32 nKey;
41526  u32 nLocal;
41527
41528  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
41529  assert( pCur->eState==CURSOR_VALID );
41530  assert( cursorHoldsMutex(pCur) );
41531  pPage = pCur->apPage[pCur->iPage];
41532  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
41533  if( NEVER(pCur->info.nSize==0) ){
41534    btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
41535                   &pCur->info);
41536  }
41537  aPayload = pCur->info.pCell;
41538  aPayload += pCur->info.nHeader;
41539  if( pPage->intKey ){
41540    nKey = 0;
41541  }else{
41542    nKey = (int)pCur->info.nKey;
41543  }
41544  if( skipKey ){
41545    aPayload += nKey;
41546    nLocal = pCur->info.nLocal - nKey;
41547  }else{
41548    nLocal = pCur->info.nLocal;
41549    assert( nLocal<=nKey );
41550  }
41551  *pAmt = nLocal;
41552  return aPayload;
41553}
41554
41555
41556/*
41557** For the entry that cursor pCur is point to, return as
41558** many bytes of the key or data as are available on the local
41559** b-tree page.  Write the number of available bytes into *pAmt.
41560**
41561** The pointer returned is ephemeral.  The key/data may move
41562** or be destroyed on the next call to any Btree routine,
41563** including calls from other threads against the same cache.
41564** Hence, a mutex on the BtShared should be held prior to calling
41565** this routine.
41566**
41567** These routines is used to get quick access to key and data
41568** in the common case where no overflow pages are used.
41569*/
41570SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
41571  const void *p = 0;
41572  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41573  assert( cursorHoldsMutex(pCur) );
41574  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
41575    p = (const void*)fetchPayload(pCur, pAmt, 0);
41576  }
41577  return p;
41578}
41579SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
41580  const void *p = 0;
41581  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41582  assert( cursorHoldsMutex(pCur) );
41583  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
41584    p = (const void*)fetchPayload(pCur, pAmt, 1);
41585  }
41586  return p;
41587}
41588
41589
41590/*
41591** Move the cursor down to a new child page.  The newPgno argument is the
41592** page number of the child page to move to.
41593**
41594** This function returns SQLITE_CORRUPT if the page-header flags field of
41595** the new child page does not match the flags field of the parent (i.e.
41596** if an intkey page appears to be the parent of a non-intkey page, or
41597** vice-versa).
41598*/
41599static int moveToChild(BtCursor *pCur, u32 newPgno){
41600  int rc;
41601  int i = pCur->iPage;
41602  MemPage *pNewPage;
41603  BtShared *pBt = pCur->pBt;
41604
41605  assert( cursorHoldsMutex(pCur) );
41606  assert( pCur->eState==CURSOR_VALID );
41607  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
41608  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
41609    return SQLITE_CORRUPT_BKPT(MOVE_TO_CHILD_1_CORRUPTION); // Android Change
41610  }
41611  rc = getAndInitPage(pBt, newPgno, &pNewPage);
41612  if( rc ) return rc;
41613  pCur->apPage[i+1] = pNewPage;
41614  pCur->aiIdx[i+1] = 0;
41615  pCur->iPage++;
41616
41617  pCur->info.nSize = 0;
41618  pCur->validNKey = 0;
41619  if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
41620    return SQLITE_CORRUPT_BKPT(MOVE_TO_CHILD_2_CORRUPTION); // Android Change
41621  }
41622  return SQLITE_OK;
41623}
41624
41625#ifndef NDEBUG
41626/*
41627** Page pParent is an internal (non-leaf) tree page. This function
41628** asserts that page number iChild is the left-child if the iIdx'th
41629** cell in page pParent. Or, if iIdx is equal to the total number of
41630** cells in pParent, that page number iChild is the right-child of
41631** the page.
41632*/
41633static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
41634  assert( iIdx<=pParent->nCell );
41635  if( iIdx==pParent->nCell ){
41636    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
41637  }else{
41638    assert( get4byte(findCell(pParent, iIdx))==iChild );
41639  }
41640}
41641#else
41642#  define assertParentIndex(x,y,z)
41643#endif
41644
41645/*
41646** Move the cursor up to the parent page.
41647**
41648** pCur->idx is set to the cell index that contains the pointer
41649** to the page we are coming from.  If we are coming from the
41650** right-most child page then pCur->idx is set to one more than
41651** the largest cell index.
41652*/
41653static void moveToParent(BtCursor *pCur){
41654  assert( cursorHoldsMutex(pCur) );
41655  assert( pCur->eState==CURSOR_VALID );
41656  assert( pCur->iPage>0 );
41657  assert( pCur->apPage[pCur->iPage] );
41658  assertParentIndex(
41659    pCur->apPage[pCur->iPage-1],
41660    pCur->aiIdx[pCur->iPage-1],
41661    pCur->apPage[pCur->iPage]->pgno
41662  );
41663  releasePage(pCur->apPage[pCur->iPage]);
41664  pCur->iPage--;
41665  pCur->info.nSize = 0;
41666  pCur->validNKey = 0;
41667}
41668
41669/*
41670** Move the cursor to point to the root page of its b-tree structure.
41671**
41672** If the table has a virtual root page, then the cursor is moved to point
41673** to the virtual root page instead of the actual root page. A table has a
41674** virtual root page when the actual root page contains no cells and a
41675** single child page. This can only happen with the table rooted at page 1.
41676**
41677** If the b-tree structure is empty, the cursor state is set to
41678** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
41679** cell located on the root (or virtual root) page and the cursor state
41680** is set to CURSOR_VALID.
41681**
41682** If this function returns successfully, it may be assumed that the
41683** page-header flags indicate that the [virtual] root-page is the expected
41684** kind of b-tree page (i.e. if when opening the cursor the caller did not
41685** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
41686** indicating a table b-tree, or if the caller did specify a KeyInfo
41687** structure the flags byte is set to 0x02 or 0x0A, indicating an index
41688** b-tree).
41689*/
41690static int moveToRoot(BtCursor *pCur){
41691  MemPage *pRoot;
41692  int rc = SQLITE_OK;
41693  Btree *p = pCur->pBtree;
41694  BtShared *pBt = p->pBt;
41695
41696  assert( cursorHoldsMutex(pCur) );
41697  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
41698  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
41699  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
41700  if( pCur->eState>=CURSOR_REQUIRESEEK ){
41701    if( pCur->eState==CURSOR_FAULT ){
41702      assert( pCur->skipNext!=SQLITE_OK );
41703      return pCur->skipNext;
41704    }
41705    sqlite3BtreeClearCursor(pCur);
41706  }
41707
41708  if( pCur->iPage>=0 ){
41709    int i;
41710    for(i=1; i<=pCur->iPage; i++){
41711      releasePage(pCur->apPage[i]);
41712    }
41713    pCur->iPage = 0;
41714  }else{
41715    rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
41716    if( rc!=SQLITE_OK ){
41717      pCur->eState = CURSOR_INVALID;
41718      return rc;
41719    }
41720    pCur->iPage = 0;
41721
41722    /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
41723    ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
41724    ** NULL, the caller expects a table b-tree. If this is not the case,
41725    ** return an SQLITE_CORRUPT error.  */
41726    assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
41727    if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
41728      return SQLITE_CORRUPT_BKPT(MOVE_TO_ROOT_1_CORRUPTION); // Android Change
41729    }
41730  }
41731
41732  /* Assert that the root page is of the correct type. This must be the
41733  ** case as the call to this function that loaded the root-page (either
41734  ** this call or a previous invocation) would have detected corruption
41735  ** if the assumption were not true, and it is not possible for the flags
41736  ** byte to have been modified while this cursor is holding a reference
41737  ** to the page.  */
41738  pRoot = pCur->apPage[0];
41739  assert( pRoot->pgno==pCur->pgnoRoot );
41740  assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
41741
41742  pCur->aiIdx[0] = 0;
41743  pCur->info.nSize = 0;
41744  pCur->atLast = 0;
41745  pCur->validNKey = 0;
41746
41747  if( pRoot->nCell==0 && !pRoot->leaf ){
41748    Pgno subpage;
41749    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT(MOVE_TO_ROOT_2_CORRUPTION); // Android Change
41750    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
41751    pCur->eState = CURSOR_VALID;
41752    rc = moveToChild(pCur, subpage);
41753  }else{
41754    pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
41755  }
41756  return rc;
41757}
41758
41759/*
41760** Move the cursor down to the left-most leaf entry beneath the
41761** entry to which it is currently pointing.
41762**
41763** The left-most leaf is the one with the smallest key - the first
41764** in ascending order.
41765*/
41766static int moveToLeftmost(BtCursor *pCur){
41767  Pgno pgno;
41768  int rc = SQLITE_OK;
41769  MemPage *pPage;
41770
41771  assert( cursorHoldsMutex(pCur) );
41772  assert( pCur->eState==CURSOR_VALID );
41773  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
41774    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
41775    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
41776    rc = moveToChild(pCur, pgno);
41777  }
41778  return rc;
41779}
41780
41781/*
41782** Move the cursor down to the right-most leaf entry beneath the
41783** page to which it is currently pointing.  Notice the difference
41784** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
41785** finds the left-most entry beneath the *entry* whereas moveToRightmost()
41786** finds the right-most entry beneath the *page*.
41787**
41788** The right-most entry is the one with the largest key - the last
41789** key in ascending order.
41790*/
41791static int moveToRightmost(BtCursor *pCur){
41792  Pgno pgno;
41793  int rc = SQLITE_OK;
41794  MemPage *pPage = 0;
41795
41796  assert( cursorHoldsMutex(pCur) );
41797  assert( pCur->eState==CURSOR_VALID );
41798  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
41799    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
41800    pCur->aiIdx[pCur->iPage] = pPage->nCell;
41801    rc = moveToChild(pCur, pgno);
41802  }
41803  if( rc==SQLITE_OK ){
41804    pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
41805    pCur->info.nSize = 0;
41806    pCur->validNKey = 0;
41807  }
41808  return rc;
41809}
41810
41811/* Move the cursor to the first entry in the table.  Return SQLITE_OK
41812** on success.  Set *pRes to 0 if the cursor actually points to something
41813** or set *pRes to 1 if the table is empty.
41814*/
41815SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
41816  int rc;
41817
41818  assert( cursorHoldsMutex(pCur) );
41819  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41820  rc = moveToRoot(pCur);
41821  if( rc==SQLITE_OK ){
41822    if( pCur->eState==CURSOR_INVALID ){
41823      assert( pCur->apPage[pCur->iPage]->nCell==0 );
41824      *pRes = 1;
41825      rc = SQLITE_OK;
41826    }else{
41827      assert( pCur->apPage[pCur->iPage]->nCell>0 );
41828      *pRes = 0;
41829      rc = moveToLeftmost(pCur);
41830    }
41831  }
41832  return rc;
41833}
41834
41835/* Move the cursor to the last entry in the table.  Return SQLITE_OK
41836** on success.  Set *pRes to 0 if the cursor actually points to something
41837** or set *pRes to 1 if the table is empty.
41838*/
41839SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
41840  int rc;
41841
41842  assert( cursorHoldsMutex(pCur) );
41843  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41844
41845  /* If the cursor already points to the last entry, this is a no-op. */
41846  if( CURSOR_VALID==pCur->eState && pCur->atLast ){
41847#ifdef SQLITE_DEBUG
41848    /* This block serves to assert() that the cursor really does point
41849    ** to the last entry in the b-tree. */
41850    int ii;
41851    for(ii=0; ii<pCur->iPage; ii++){
41852      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
41853    }
41854    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
41855    assert( pCur->apPage[pCur->iPage]->leaf );
41856#endif
41857    return SQLITE_OK;
41858  }
41859
41860  rc = moveToRoot(pCur);
41861  if( rc==SQLITE_OK ){
41862    if( CURSOR_INVALID==pCur->eState ){
41863      assert( pCur->apPage[pCur->iPage]->nCell==0 );
41864      *pRes = 1;
41865    }else{
41866      assert( pCur->eState==CURSOR_VALID );
41867      *pRes = 0;
41868      rc = moveToRightmost(pCur);
41869      pCur->atLast = rc==SQLITE_OK ?1:0;
41870    }
41871  }
41872  return rc;
41873}
41874
41875/* Move the cursor so that it points to an entry near the key
41876** specified by pIdxKey or intKey.   Return a success code.
41877**
41878** For INTKEY tables, the intKey parameter is used.  pIdxKey
41879** must be NULL.  For index tables, pIdxKey is used and intKey
41880** is ignored.
41881**
41882** If an exact match is not found, then the cursor is always
41883** left pointing at a leaf page which would hold the entry if it
41884** were present.  The cursor might point to an entry that comes
41885** before or after the key.
41886**
41887** An integer is written into *pRes which is the result of
41888** comparing the key with the entry to which the cursor is
41889** pointing.  The meaning of the integer written into
41890** *pRes is as follows:
41891**
41892**     *pRes<0      The cursor is left pointing at an entry that
41893**                  is smaller than intKey/pIdxKey or if the table is empty
41894**                  and the cursor is therefore left point to nothing.
41895**
41896**     *pRes==0     The cursor is left pointing at an entry that
41897**                  exactly matches intKey/pIdxKey.
41898**
41899**     *pRes>0      The cursor is left pointing at an entry that
41900**                  is larger than intKey/pIdxKey.
41901**
41902*/
41903SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
41904  BtCursor *pCur,          /* The cursor to be moved */
41905  UnpackedRecord *pIdxKey, /* Unpacked index key */
41906  i64 intKey,              /* The table key */
41907  int biasRight,           /* If true, bias the search to the high end */
41908  int *pRes                /* Write search results here */
41909){
41910  int rc;
41911
41912  assert( cursorHoldsMutex(pCur) );
41913  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41914  assert( pRes );
41915  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
41916
41917  /* If the cursor is already positioned at the point we are trying
41918  ** to move to, then just return without doing any work */
41919  if( pCur->eState==CURSOR_VALID && pCur->validNKey
41920   && pCur->apPage[0]->intKey
41921  ){
41922    if( pCur->info.nKey==intKey ){
41923      *pRes = 0;
41924      return SQLITE_OK;
41925    }
41926    if( pCur->atLast && pCur->info.nKey<intKey ){
41927      *pRes = -1;
41928      return SQLITE_OK;
41929    }
41930  }
41931
41932  rc = moveToRoot(pCur);
41933  if( rc ){
41934    return rc;
41935  }
41936  assert( pCur->apPage[pCur->iPage] );
41937  assert( pCur->apPage[pCur->iPage]->isInit );
41938  assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
41939  if( pCur->eState==CURSOR_INVALID ){
41940    *pRes = -1;
41941    assert( pCur->apPage[pCur->iPage]->nCell==0 );
41942    return SQLITE_OK;
41943  }
41944  assert( pCur->apPage[0]->intKey || pIdxKey );
41945  for(;;){
41946    int lwr, upr;
41947    Pgno chldPg;
41948    MemPage *pPage = pCur->apPage[pCur->iPage];
41949    int c;
41950
41951    /* pPage->nCell must be greater than zero. If this is the root-page
41952    ** the cursor would have been INVALID above and this for(;;) loop
41953    ** not run. If this is not the root-page, then the moveToChild() routine
41954    ** would have already detected db corruption. Similarly, pPage must
41955    ** be the right kind (index or table) of b-tree page. Otherwise
41956    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
41957    assert( pPage->nCell>0 );
41958    assert( pPage->intKey==(pIdxKey==0) );
41959    lwr = 0;
41960    upr = pPage->nCell-1;
41961    if( biasRight ){
41962      pCur->aiIdx[pCur->iPage] = (u16)upr;
41963    }else{
41964      pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
41965    }
41966    for(;;){
41967      int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
41968      u8 *pCell;                          /* Pointer to current cell in pPage */
41969
41970      pCur->info.nSize = 0;
41971      pCell = findCell(pPage, idx) + pPage->childPtrSize;
41972      if( pPage->intKey ){
41973        i64 nCellKey;
41974        if( pPage->hasData ){
41975          u32 dummy;
41976          pCell += getVarint32(pCell, dummy);
41977        }
41978        getVarint(pCell, (u64*)&nCellKey);
41979        if( nCellKey==intKey ){
41980          c = 0;
41981        }else if( nCellKey<intKey ){
41982          c = -1;
41983        }else{
41984          assert( nCellKey>intKey );
41985          c = +1;
41986        }
41987        pCur->validNKey = 1;
41988        pCur->info.nKey = nCellKey;
41989      }else{
41990        /* The maximum supported page-size is 32768 bytes. This means that
41991        ** the maximum number of record bytes stored on an index B-Tree
41992        ** page is at most 8198 bytes, which may be stored as a 2-byte
41993        ** varint. This information is used to attempt to avoid parsing
41994        ** the entire cell by checking for the cases where the record is
41995        ** stored entirely within the b-tree page by inspecting the first
41996        ** 2 bytes of the cell.
41997        */
41998        int nCell = pCell[0];
41999        if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
42000          /* This branch runs if the record-size field of the cell is a
42001          ** single byte varint and the record fits entirely on the main
42002          ** b-tree page.  */
42003          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
42004        }else if( !(pCell[1] & 0x80)
42005          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
42006        ){
42007          /* The record-size field is a 2 byte varint and the record
42008          ** fits entirely on the main b-tree page.  */
42009          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
42010        }else{
42011          /* The record flows over onto one or more overflow pages. In
42012          ** this case the whole cell needs to be parsed, a buffer allocated
42013          ** and accessPayload() used to retrieve the record into the
42014          ** buffer before VdbeRecordCompare() can be called. */
42015          void *pCellKey;
42016          u8 * const pCellBody = pCell - pPage->childPtrSize;
42017          btreeParseCellPtr(pPage, pCellBody, &pCur->info);
42018          nCell = (int)pCur->info.nKey;
42019          pCellKey = sqlite3Malloc( nCell );
42020          if( pCellKey==0 ){
42021            rc = SQLITE_NOMEM;
42022            goto moveto_finish;
42023          }
42024          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
42025          if( rc ){
42026            sqlite3_free(pCellKey);
42027            goto moveto_finish;
42028          }
42029          c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
42030          sqlite3_free(pCellKey);
42031        }
42032      }
42033      if( c==0 ){
42034        if( pPage->intKey && !pPage->leaf ){
42035          lwr = idx;
42036          upr = lwr - 1;
42037          break;
42038        }else{
42039          *pRes = 0;
42040          rc = SQLITE_OK;
42041          goto moveto_finish;
42042        }
42043      }
42044      if( c<0 ){
42045        lwr = idx+1;
42046      }else{
42047        upr = idx-1;
42048      }
42049      if( lwr>upr ){
42050        break;
42051      }
42052      pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
42053    }
42054    assert( lwr==upr+1 );
42055    assert( pPage->isInit );
42056    if( pPage->leaf ){
42057      chldPg = 0;
42058    }else if( lwr>=pPage->nCell ){
42059      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
42060    }else{
42061      chldPg = get4byte(findCell(pPage, lwr));
42062    }
42063    if( chldPg==0 ){
42064      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
42065      *pRes = c;
42066      rc = SQLITE_OK;
42067      goto moveto_finish;
42068    }
42069    pCur->aiIdx[pCur->iPage] = (u16)lwr;
42070    pCur->info.nSize = 0;
42071    pCur->validNKey = 0;
42072    rc = moveToChild(pCur, chldPg);
42073    if( rc ) goto moveto_finish;
42074  }
42075moveto_finish:
42076  return rc;
42077}
42078
42079
42080/*
42081** Return TRUE if the cursor is not pointing at an entry of the table.
42082**
42083** TRUE will be returned after a call to sqlite3BtreeNext() moves
42084** past the last entry in the table or sqlite3BtreePrev() moves past
42085** the first entry.  TRUE is also returned if the table is empty.
42086*/
42087SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
42088  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
42089  ** have been deleted? This API will need to change to return an error code
42090  ** as well as the boolean result value.
42091  */
42092  return (CURSOR_VALID!=pCur->eState);
42093}
42094
42095/*
42096** Advance the cursor to the next entry in the database.  If
42097** successful then set *pRes=0.  If the cursor
42098** was already pointing to the last entry in the database before
42099** this routine was called, then set *pRes=1.
42100*/
42101SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
42102  int rc;
42103  int idx;
42104  MemPage *pPage;
42105
42106  assert( cursorHoldsMutex(pCur) );
42107  rc = restoreCursorPosition(pCur);
42108  if( rc!=SQLITE_OK ){
42109    return rc;
42110  }
42111  assert( pRes!=0 );
42112  if( CURSOR_INVALID==pCur->eState ){
42113    *pRes = 1;
42114    return SQLITE_OK;
42115  }
42116  if( pCur->skipNext>0 ){
42117    pCur->skipNext = 0;
42118    *pRes = 0;
42119    return SQLITE_OK;
42120  }
42121  pCur->skipNext = 0;
42122
42123  pPage = pCur->apPage[pCur->iPage];
42124  idx = ++pCur->aiIdx[pCur->iPage];
42125  assert( pPage->isInit );
42126  assert( idx<=pPage->nCell );
42127
42128  pCur->info.nSize = 0;
42129  pCur->validNKey = 0;
42130  if( idx>=pPage->nCell ){
42131    if( !pPage->leaf ){
42132      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
42133      if( rc ) return rc;
42134      rc = moveToLeftmost(pCur);
42135      *pRes = 0;
42136      return rc;
42137    }
42138    do{
42139      if( pCur->iPage==0 ){
42140        *pRes = 1;
42141        pCur->eState = CURSOR_INVALID;
42142        return SQLITE_OK;
42143      }
42144      moveToParent(pCur);
42145      pPage = pCur->apPage[pCur->iPage];
42146    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
42147    *pRes = 0;
42148    if( pPage->intKey ){
42149      rc = sqlite3BtreeNext(pCur, pRes);
42150    }else{
42151      rc = SQLITE_OK;
42152    }
42153    return rc;
42154  }
42155  *pRes = 0;
42156  if( pPage->leaf ){
42157    return SQLITE_OK;
42158  }
42159  rc = moveToLeftmost(pCur);
42160  return rc;
42161}
42162
42163
42164/*
42165** Step the cursor to the back to the previous entry in the database.  If
42166** successful then set *pRes=0.  If the cursor
42167** was already pointing to the first entry in the database before
42168** this routine was called, then set *pRes=1.
42169*/
42170SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
42171  int rc;
42172  MemPage *pPage;
42173
42174  assert( cursorHoldsMutex(pCur) );
42175  rc = restoreCursorPosition(pCur);
42176  if( rc!=SQLITE_OK ){
42177    return rc;
42178  }
42179  pCur->atLast = 0;
42180  if( CURSOR_INVALID==pCur->eState ){
42181    *pRes = 1;
42182    return SQLITE_OK;
42183  }
42184  if( pCur->skipNext<0 ){
42185    pCur->skipNext = 0;
42186    *pRes = 0;
42187    return SQLITE_OK;
42188  }
42189  pCur->skipNext = 0;
42190
42191  pPage = pCur->apPage[pCur->iPage];
42192  assert( pPage->isInit );
42193  if( !pPage->leaf ){
42194    int idx = pCur->aiIdx[pCur->iPage];
42195    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
42196    if( rc ){
42197      return rc;
42198    }
42199    rc = moveToRightmost(pCur);
42200  }else{
42201    while( pCur->aiIdx[pCur->iPage]==0 ){
42202      if( pCur->iPage==0 ){
42203        pCur->eState = CURSOR_INVALID;
42204        *pRes = 1;
42205        return SQLITE_OK;
42206      }
42207      moveToParent(pCur);
42208    }
42209    pCur->info.nSize = 0;
42210    pCur->validNKey = 0;
42211
42212    pCur->aiIdx[pCur->iPage]--;
42213    pPage = pCur->apPage[pCur->iPage];
42214    if( pPage->intKey && !pPage->leaf ){
42215      rc = sqlite3BtreePrevious(pCur, pRes);
42216    }else{
42217      rc = SQLITE_OK;
42218    }
42219  }
42220  *pRes = 0;
42221  return rc;
42222}
42223
42224/*
42225** Allocate a new page from the database file.
42226**
42227** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
42228** has already been called on the new page.)  The new page has also
42229** been referenced and the calling routine is responsible for calling
42230** sqlite3PagerUnref() on the new page when it is done.
42231**
42232** SQLITE_OK is returned on success.  Any other return value indicates
42233** an error.  *ppPage and *pPgno are undefined in the event of an error.
42234** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
42235**
42236** If the "nearby" parameter is not 0, then a (feeble) effort is made to
42237** locate a page close to the page number "nearby".  This can be used in an
42238** attempt to keep related pages close to each other in the database file,
42239** which in turn can make database access faster.
42240**
42241** If the "exact" parameter is not 0, and the page-number nearby exists
42242** anywhere on the free-list, then it is guarenteed to be returned. This
42243** is only used by auto-vacuum databases when allocating a new table.
42244*/
42245static int allocateBtreePage(
42246  BtShared *pBt,
42247  MemPage **ppPage,
42248  Pgno *pPgno,
42249  Pgno nearby,
42250  u8 exact
42251){
42252  MemPage *pPage1;
42253  int rc;
42254  u32 n;     /* Number of pages on the freelist */
42255  u32 k;     /* Number of leaves on the trunk of the freelist */
42256  MemPage *pTrunk = 0;
42257  MemPage *pPrevTrunk = 0;
42258  Pgno mxPage;     /* Total size of the database file */
42259
42260  assert( sqlite3_mutex_held(pBt->mutex) );
42261  pPage1 = pBt->pPage1;
42262  mxPage = pagerPagecount(pBt);
42263  n = get4byte(&pPage1->aData[36]);
42264  testcase( n==mxPage-1 );
42265  if( n>=mxPage ){
42266    return SQLITE_CORRUPT_BKPT(BTREE_PAGE_1_CORRUPTION); // Android Change
42267  }
42268  if( n>0 ){
42269    /* There are pages on the freelist.  Reuse one of those pages. */
42270    Pgno iTrunk;
42271    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
42272
42273    /* If the 'exact' parameter was true and a query of the pointer-map
42274    ** shows that the page 'nearby' is somewhere on the free-list, then
42275    ** the entire-list will be searched for that page.
42276    */
42277#ifndef SQLITE_OMIT_AUTOVACUUM
42278    if( exact && nearby<=mxPage ){
42279      u8 eType;
42280      assert( nearby>0 );
42281      assert( pBt->autoVacuum );
42282      rc = ptrmapGet(pBt, nearby, &eType, 0);
42283      if( rc ) return rc;
42284      if( eType==PTRMAP_FREEPAGE ){
42285        searchList = 1;
42286      }
42287      *pPgno = nearby;
42288    }
42289#endif
42290
42291    /* Decrement the free-list count by 1. Set iTrunk to the index of the
42292    ** first free-list trunk page. iPrevTrunk is initially 1.
42293    */
42294    rc = sqlite3PagerWrite(pPage1->pDbPage);
42295    if( rc ) return rc;
42296    put4byte(&pPage1->aData[36], n-1);
42297
42298    /* The code within this loop is run only once if the 'searchList' variable
42299    ** is not true. Otherwise, it runs once for each trunk-page on the
42300    ** free-list until the page 'nearby' is located.
42301    */
42302    do {
42303      pPrevTrunk = pTrunk;
42304      if( pPrevTrunk ){
42305        iTrunk = get4byte(&pPrevTrunk->aData[0]);
42306      }else{
42307        iTrunk = get4byte(&pPage1->aData[32]);
42308      }
42309      testcase( iTrunk==mxPage );
42310      if( iTrunk>mxPage ){
42311        rc = SQLITE_CORRUPT_BKPT(BTREE_PAGE_2_CORRUPTION); // Android Change
42312      }else{
42313        rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
42314      }
42315      if( rc ){
42316        pTrunk = 0;
42317        goto end_allocate_page;
42318      }
42319
42320      k = get4byte(&pTrunk->aData[4]);
42321      if( k==0 && !searchList ){
42322        /* The trunk has no leaves and the list is not being searched.
42323        ** So extract the trunk page itself and use it as the newly
42324        ** allocated page */
42325        assert( pPrevTrunk==0 );
42326        rc = sqlite3PagerWrite(pTrunk->pDbPage);
42327        if( rc ){
42328          goto end_allocate_page;
42329        }
42330        *pPgno = iTrunk;
42331        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
42332        *ppPage = pTrunk;
42333        pTrunk = 0;
42334        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
42335      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
42336        /* Value of k is out of range.  Database corruption */
42337        rc = SQLITE_CORRUPT_BKPT(BTREE_PAGE_3_CORRUPTION); // Android Change
42338        goto end_allocate_page;
42339#ifndef SQLITE_OMIT_AUTOVACUUM
42340      }else if( searchList && nearby==iTrunk ){
42341        /* The list is being searched and this trunk page is the page
42342        ** to allocate, regardless of whether it has leaves.
42343        */
42344        assert( *pPgno==iTrunk );
42345        *ppPage = pTrunk;
42346        searchList = 0;
42347        rc = sqlite3PagerWrite(pTrunk->pDbPage);
42348        if( rc ){
42349          goto end_allocate_page;
42350        }
42351        if( k==0 ){
42352          if( !pPrevTrunk ){
42353            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
42354          }else{
42355            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
42356          }
42357        }else{
42358          /* The trunk page is required by the caller but it contains
42359          ** pointers to free-list leaves. The first leaf becomes a trunk
42360          ** page in this case.
42361          */
42362          MemPage *pNewTrunk;
42363          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
42364          if( iNewTrunk>mxPage ){
42365            rc = SQLITE_CORRUPT_BKPT(BTREE_PAGE_4_CORRUPTION); // Android Change
42366            goto end_allocate_page;
42367          }
42368          testcase( iNewTrunk==mxPage );
42369          rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
42370          if( rc!=SQLITE_OK ){
42371            goto end_allocate_page;
42372          }
42373          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
42374          if( rc!=SQLITE_OK ){
42375            releasePage(pNewTrunk);
42376            goto end_allocate_page;
42377          }
42378          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
42379          put4byte(&pNewTrunk->aData[4], k-1);
42380          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
42381          releasePage(pNewTrunk);
42382          if( !pPrevTrunk ){
42383            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
42384            put4byte(&pPage1->aData[32], iNewTrunk);
42385          }else{
42386            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
42387            if( rc ){
42388              goto end_allocate_page;
42389            }
42390            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
42391          }
42392        }
42393        pTrunk = 0;
42394        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
42395#endif
42396      }else if( k>0 ){
42397        /* Extract a leaf from the trunk */
42398        u32 closest;
42399        Pgno iPage;
42400        unsigned char *aData = pTrunk->aData;
42401        rc = sqlite3PagerWrite(pTrunk->pDbPage);
42402        if( rc ){
42403          goto end_allocate_page;
42404        }
42405        if( nearby>0 ){
42406          u32 i;
42407          int dist;
42408          closest = 0;
42409          dist = get4byte(&aData[8]) - nearby;
42410          if( dist<0 ) dist = -dist;
42411          for(i=1; i<k; i++){
42412            int d2 = get4byte(&aData[8+i*4]) - nearby;
42413            if( d2<0 ) d2 = -d2;
42414            if( d2<dist ){
42415              closest = i;
42416              dist = d2;
42417            }
42418          }
42419        }else{
42420          closest = 0;
42421        }
42422
42423        iPage = get4byte(&aData[8+closest*4]);
42424        testcase( iPage==mxPage );
42425        if( iPage>mxPage ){
42426          rc = SQLITE_CORRUPT_BKPT(BTREE_PAGE_5_CORRUPTION); // Android Change
42427          goto end_allocate_page;
42428        }
42429        testcase( iPage==mxPage );
42430        if( !searchList || iPage==nearby ){
42431          int noContent;
42432          *pPgno = iPage;
42433          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
42434                 ": %d more free pages\n",
42435                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
42436          if( closest<k-1 ){
42437            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
42438          }
42439          put4byte(&aData[4], k-1);
42440          assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
42441          noContent = !btreeGetHasContent(pBt, *pPgno);
42442          rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
42443          if( rc==SQLITE_OK ){
42444            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
42445            if( rc!=SQLITE_OK ){
42446              releasePage(*ppPage);
42447            }
42448          }
42449          searchList = 0;
42450        }
42451      }
42452      releasePage(pPrevTrunk);
42453      pPrevTrunk = 0;
42454    }while( searchList );
42455  }else{
42456    /* There are no pages on the freelist, so create a new page at the
42457    ** end of the file */
42458    int nPage = pagerPagecount(pBt);
42459    *pPgno = nPage + 1;
42460
42461    if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
42462      (*pPgno)++;
42463    }
42464
42465#ifndef SQLITE_OMIT_AUTOVACUUM
42466    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
42467      /* If *pPgno refers to a pointer-map page, allocate two new pages
42468      ** at the end of the file instead of one. The first allocated page
42469      ** becomes a new pointer-map page, the second is used by the caller.
42470      */
42471      MemPage *pPg = 0;
42472      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
42473      assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
42474      rc = btreeGetPage(pBt, *pPgno, &pPg, 0);
42475      if( rc==SQLITE_OK ){
42476        rc = sqlite3PagerWrite(pPg->pDbPage);
42477        releasePage(pPg);
42478      }
42479      if( rc ) return rc;
42480      (*pPgno)++;
42481      if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
42482    }
42483#endif
42484
42485    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
42486    rc = btreeGetPage(pBt, *pPgno, ppPage, 0);
42487    if( rc ) return rc;
42488    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
42489    if( rc!=SQLITE_OK ){
42490      releasePage(*ppPage);
42491    }
42492    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
42493  }
42494
42495  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
42496
42497end_allocate_page:
42498  releasePage(pTrunk);
42499  releasePage(pPrevTrunk);
42500  if( rc==SQLITE_OK ){
42501    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
42502      releasePage(*ppPage);
42503      return SQLITE_CORRUPT_BKPT(BTREE_PAGE_6_CORRUPTION); // Android Change
42504    }
42505    (*ppPage)->isInit = 0;
42506  }else{
42507    *ppPage = 0;
42508  }
42509  return rc;
42510}
42511
42512/*
42513** This function is used to add page iPage to the database file free-list.
42514** It is assumed that the page is not already a part of the free-list.
42515**
42516** The value passed as the second argument to this function is optional.
42517** If the caller happens to have a pointer to the MemPage object
42518** corresponding to page iPage handy, it may pass it as the second value.
42519** Otherwise, it may pass NULL.
42520**
42521** If a pointer to a MemPage object is passed as the second argument,
42522** its reference count is not altered by this function.
42523*/
42524static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
42525  MemPage *pTrunk = 0;                /* Free-list trunk page */
42526  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
42527  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
42528  MemPage *pPage;                     /* Page being freed. May be NULL. */
42529  int rc;                             /* Return Code */
42530  int nFree;                          /* Initial number of pages on free-list */
42531
42532  assert( sqlite3_mutex_held(pBt->mutex) );
42533  assert( iPage>1 );
42534  assert( !pMemPage || pMemPage->pgno==iPage );
42535
42536  if( pMemPage ){
42537    pPage = pMemPage;
42538    sqlite3PagerRef(pPage->pDbPage);
42539  }else{
42540    pPage = btreePageLookup(pBt, iPage);
42541  }
42542
42543  /* Increment the free page count on pPage1 */
42544  rc = sqlite3PagerWrite(pPage1->pDbPage);
42545  if( rc ) goto freepage_out;
42546  nFree = get4byte(&pPage1->aData[36]);
42547  put4byte(&pPage1->aData[36], nFree+1);
42548
42549#ifdef SQLITE_SECURE_DELETE
42550  /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
42551  ** always fully overwrite deleted information with zeros.
42552  */
42553  if( (!pPage && (rc = btreeGetPage(pBt, iPage, &pPage, 0)))
42554   ||            (rc = sqlite3PagerWrite(pPage->pDbPage))
42555  ){
42556    goto freepage_out;
42557  }
42558  memset(pPage->aData, 0, pPage->pBt->pageSize);
42559#endif
42560
42561  /* If the database supports auto-vacuum, write an entry in the pointer-map
42562  ** to indicate that the page is free.
42563  */
42564  if( ISAUTOVACUUM ){
42565    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
42566    if( rc ) goto freepage_out;
42567  }
42568
42569  /* Now manipulate the actual database free-list structure. There are two
42570  ** possibilities. If the free-list is currently empty, or if the first
42571  ** trunk page in the free-list is full, then this page will become a
42572  ** new free-list trunk page. Otherwise, it will become a leaf of the
42573  ** first trunk page in the current free-list. This block tests if it
42574  ** is possible to add the page as a new free-list leaf.
42575  */
42576  if( nFree!=0 ){
42577    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
42578
42579    iTrunk = get4byte(&pPage1->aData[32]);
42580    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
42581    if( rc!=SQLITE_OK ){
42582      goto freepage_out;
42583    }
42584
42585    nLeaf = get4byte(&pTrunk->aData[4]);
42586    assert( pBt->usableSize>32 );
42587    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
42588      rc = SQLITE_CORRUPT_BKPT(FREEPAGE2_1_CORRUPTION); // Android Change
42589      goto freepage_out;
42590    }
42591    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
42592      /* In this case there is room on the trunk page to insert the page
42593      ** being freed as a new leaf.
42594      **
42595      ** Note that the trunk page is not really full until it contains
42596      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
42597      ** coded.  But due to a coding error in versions of SQLite prior to
42598      ** 3.6.0, databases with freelist trunk pages holding more than
42599      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
42600      ** to maintain backwards compatibility with older versions of SQLite,
42601      ** we will continue to restrict the number of entries to usableSize/4 - 8
42602      ** for now.  At some point in the future (once everyone has upgraded
42603      ** to 3.6.0 or later) we should consider fixing the conditional above
42604      ** to read "usableSize/4-2" instead of "usableSize/4-8".
42605      */
42606      rc = sqlite3PagerWrite(pTrunk->pDbPage);
42607      if( rc==SQLITE_OK ){
42608        put4byte(&pTrunk->aData[4], nLeaf+1);
42609        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
42610#ifndef SQLITE_SECURE_DELETE
42611        if( pPage ){
42612          sqlite3PagerDontWrite(pPage->pDbPage);
42613        }
42614#endif
42615        rc = btreeSetHasContent(pBt, iPage);
42616      }
42617      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
42618      goto freepage_out;
42619    }
42620  }
42621
42622  /* If control flows to this point, then it was not possible to add the
42623  ** the page being freed as a leaf page of the first trunk in the free-list.
42624  ** Possibly because the free-list is empty, or possibly because the
42625  ** first trunk in the free-list is full. Either way, the page being freed
42626  ** will become the new first trunk page in the free-list.
42627  */
42628  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
42629    goto freepage_out;
42630  }
42631  rc = sqlite3PagerWrite(pPage->pDbPage);
42632  if( rc!=SQLITE_OK ){
42633    goto freepage_out;
42634  }
42635  put4byte(pPage->aData, iTrunk);
42636  put4byte(&pPage->aData[4], 0);
42637  put4byte(&pPage1->aData[32], iPage);
42638  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
42639
42640freepage_out:
42641  if( pPage ){
42642    pPage->isInit = 0;
42643  }
42644  releasePage(pPage);
42645  releasePage(pTrunk);
42646  return rc;
42647}
42648static void freePage(MemPage *pPage, int *pRC){
42649  if( (*pRC)==SQLITE_OK ){
42650    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
42651  }
42652}
42653
42654/*
42655** Free any overflow pages associated with the given Cell.
42656*/
42657static int clearCell(MemPage *pPage, unsigned char *pCell){
42658  BtShared *pBt = pPage->pBt;
42659  CellInfo info;
42660  Pgno ovflPgno;
42661  int rc;
42662  int nOvfl;
42663  u16 ovflPageSize;
42664
42665  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42666  btreeParseCellPtr(pPage, pCell, &info);
42667  if( info.iOverflow==0 ){
42668    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
42669  }
42670  ovflPgno = get4byte(&pCell[info.iOverflow]);
42671  assert( pBt->usableSize > 4 );
42672  ovflPageSize = pBt->usableSize - 4;
42673  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
42674  assert( ovflPgno==0 || nOvfl>0 );
42675  while( nOvfl-- ){
42676    Pgno iNext = 0;
42677    MemPage *pOvfl = 0;
42678    if( ovflPgno<2 || ovflPgno>pagerPagecount(pBt) ){
42679      /* 0 is not a legal page number and page 1 cannot be an
42680      ** overflow page. Therefore if ovflPgno<2 or past the end of the
42681      ** file the database must be corrupt. */
42682      return SQLITE_CORRUPT_BKPT(CLEARCELL_CORRUPTION); // Android Change
42683    }
42684    if( nOvfl ){
42685      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
42686      if( rc ) return rc;
42687    }
42688    rc = freePage2(pBt, pOvfl, ovflPgno);
42689    if( pOvfl ){
42690      sqlite3PagerUnref(pOvfl->pDbPage);
42691    }
42692    if( rc ) return rc;
42693    ovflPgno = iNext;
42694  }
42695  return SQLITE_OK;
42696}
42697
42698/*
42699** Create the byte sequence used to represent a cell on page pPage
42700** and write that byte sequence into pCell[].  Overflow pages are
42701** allocated and filled in as necessary.  The calling procedure
42702** is responsible for making sure sufficient space has been allocated
42703** for pCell[].
42704**
42705** Note that pCell does not necessary need to point to the pPage->aData
42706** area.  pCell might point to some temporary storage.  The cell will
42707** be constructed in this temporary area then copied into pPage->aData
42708** later.
42709*/
42710static int fillInCell(
42711  MemPage *pPage,                /* The page that contains the cell */
42712  unsigned char *pCell,          /* Complete text of the cell */
42713  const void *pKey, i64 nKey,    /* The key */
42714  const void *pData,int nData,   /* The data */
42715  int nZero,                     /* Extra zero bytes to append to pData */
42716  int *pnSize                    /* Write cell size here */
42717){
42718  int nPayload;
42719  const u8 *pSrc;
42720  int nSrc, n, rc;
42721  int spaceLeft;
42722  MemPage *pOvfl = 0;
42723  MemPage *pToRelease = 0;
42724  unsigned char *pPrior;
42725  unsigned char *pPayload;
42726  BtShared *pBt = pPage->pBt;
42727  Pgno pgnoOvfl = 0;
42728  int nHeader;
42729  CellInfo info;
42730
42731  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42732
42733  /* pPage is not necessarily writeable since pCell might be auxiliary
42734  ** buffer space that is separate from the pPage buffer area */
42735  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
42736            || sqlite3PagerIswriteable(pPage->pDbPage) );
42737
42738  /* Fill in the header. */
42739  nHeader = 0;
42740  if( !pPage->leaf ){
42741    nHeader += 4;
42742  }
42743  if( pPage->hasData ){
42744    nHeader += putVarint(&pCell[nHeader], nData+nZero);
42745  }else{
42746    nData = nZero = 0;
42747  }
42748  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
42749  btreeParseCellPtr(pPage, pCell, &info);
42750  assert( info.nHeader==nHeader );
42751  assert( info.nKey==nKey );
42752  assert( info.nData==(u32)(nData+nZero) );
42753
42754  /* Fill in the payload */
42755  nPayload = nData + nZero;
42756  if( pPage->intKey ){
42757    pSrc = pData;
42758    nSrc = nData;
42759    nData = 0;
42760  }else{
42761    if( NEVER(nKey>0x7fffffff || pKey==0) ){
42762      return SQLITE_CORRUPT_BKPT(FILL_IN_CELL_1_CORRUPTION); // Android Change
42763    }
42764    nPayload += (int)nKey;
42765    pSrc = pKey;
42766    nSrc = (int)nKey;
42767  }
42768  *pnSize = info.nSize;
42769  spaceLeft = info.nLocal;
42770  pPayload = &pCell[nHeader];
42771  pPrior = &pCell[info.iOverflow];
42772
42773  while( nPayload>0 ){
42774    if( spaceLeft==0 ){
42775#ifndef SQLITE_OMIT_AUTOVACUUM
42776      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
42777      if( pBt->autoVacuum ){
42778        do{
42779          pgnoOvfl++;
42780        } while(
42781          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
42782        );
42783      }
42784#endif
42785      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
42786#ifndef SQLITE_OMIT_AUTOVACUUM
42787      /* If the database supports auto-vacuum, and the second or subsequent
42788      ** overflow page is being allocated, add an entry to the pointer-map
42789      ** for that page now.
42790      **
42791      ** If this is the first overflow page, then write a partial entry
42792      ** to the pointer-map. If we write nothing to this pointer-map slot,
42793      ** then the optimistic overflow chain processing in clearCell()
42794      ** may misinterpret the uninitialised values and delete the
42795      ** wrong pages from the database.
42796      */
42797      if( pBt->autoVacuum && rc==SQLITE_OK ){
42798        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
42799        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
42800        if( rc ){
42801          releasePage(pOvfl);
42802        }
42803      }
42804#endif
42805      if( rc ){
42806        releasePage(pToRelease);
42807        return rc;
42808      }
42809
42810      /* If pToRelease is not zero than pPrior points into the data area
42811      ** of pToRelease.  Make sure pToRelease is still writeable. */
42812      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
42813
42814      /* If pPrior is part of the data area of pPage, then make sure pPage
42815      ** is still writeable */
42816      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
42817            || sqlite3PagerIswriteable(pPage->pDbPage) );
42818
42819      put4byte(pPrior, pgnoOvfl);
42820      releasePage(pToRelease);
42821      pToRelease = pOvfl;
42822      pPrior = pOvfl->aData;
42823      put4byte(pPrior, 0);
42824      pPayload = &pOvfl->aData[4];
42825      spaceLeft = pBt->usableSize - 4;
42826    }
42827    n = nPayload;
42828    if( n>spaceLeft ) n = spaceLeft;
42829
42830    /* If pToRelease is not zero than pPayload points into the data area
42831    ** of pToRelease.  Make sure pToRelease is still writeable. */
42832    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
42833
42834    /* If pPayload is part of the data area of pPage, then make sure pPage
42835    ** is still writeable */
42836    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
42837            || sqlite3PagerIswriteable(pPage->pDbPage) );
42838
42839    if( nSrc>0 ){
42840      if( n>nSrc ) n = nSrc;
42841      assert( pSrc );
42842      memcpy(pPayload, pSrc, n);
42843    }else{
42844      memset(pPayload, 0, n);
42845    }
42846    nPayload -= n;
42847    pPayload += n;
42848    pSrc += n;
42849    nSrc -= n;
42850    spaceLeft -= n;
42851    if( nSrc==0 ){
42852      nSrc = nData;
42853      pSrc = pData;
42854    }
42855  }
42856  releasePage(pToRelease);
42857  return SQLITE_OK;
42858}
42859
42860/*
42861** Remove the i-th cell from pPage.  This routine effects pPage only.
42862** The cell content is not freed or deallocated.  It is assumed that
42863** the cell content has been copied someplace else.  This routine just
42864** removes the reference to the cell from pPage.
42865**
42866** "sz" must be the number of bytes in the cell.
42867*/
42868static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
42869  int i;          /* Loop counter */
42870  int pc;         /* Offset to cell content of cell being deleted */
42871  u8 *data;       /* pPage->aData */
42872  u8 *ptr;        /* Used to move bytes around within data[] */
42873  int rc;         /* The return code */
42874  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
42875
42876  if( *pRC ) return;
42877
42878  assert( idx>=0 && idx<pPage->nCell );
42879  assert( sz==cellSize(pPage, idx) );
42880  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
42881  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42882  data = pPage->aData;
42883  ptr = &data[pPage->cellOffset + 2*idx];
42884  pc = get2byte(ptr);
42885  hdr = pPage->hdrOffset;
42886  testcase( pc==get2byte(&data[hdr+5]) );
42887  testcase( pc+sz==pPage->pBt->usableSize );
42888  if( pc < get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
42889    *pRC = SQLITE_CORRUPT_BKPT(DROP_CELL_CORRUPTION); // Android Change
42890    return;
42891  }
42892  rc = freeSpace(pPage, pc, sz);
42893  if( rc ){
42894    *pRC = rc;
42895    return;
42896  }
42897  for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
42898    ptr[0] = ptr[2];
42899    ptr[1] = ptr[3];
42900  }
42901  pPage->nCell--;
42902  put2byte(&data[hdr+3], pPage->nCell);
42903  pPage->nFree += 2;
42904}
42905
42906/*
42907** Insert a new cell on pPage at cell index "i".  pCell points to the
42908** content of the cell.
42909**
42910** If the cell content will fit on the page, then put it there.  If it
42911** will not fit, then make a copy of the cell content into pTemp if
42912** pTemp is not null.  Regardless of pTemp, allocate a new entry
42913** in pPage->aOvfl[] and make it point to the cell content (either
42914** in pTemp or the original pCell) and also record its index.
42915** Allocating a new entry in pPage->aCell[] implies that
42916** pPage->nOverflow is incremented.
42917**
42918** If nSkip is non-zero, then do not copy the first nSkip bytes of the
42919** cell. The caller will overwrite them after this function returns. If
42920** nSkip is non-zero, then pCell may not point to an invalid memory location
42921** (but pCell+nSkip is always valid).
42922*/
42923static void insertCell(
42924  MemPage *pPage,   /* Page into which we are copying */
42925  int i,            /* New cell becomes the i-th cell of the page */
42926  u8 *pCell,        /* Content of the new cell */
42927  int sz,           /* Bytes of content in pCell */
42928  u8 *pTemp,        /* Temp storage space for pCell, if needed */
42929  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
42930  int *pRC          /* Read and write return code from here */
42931){
42932  int idx;          /* Where to write new cell content in data[] */
42933  int j;            /* Loop counter */
42934  int end;          /* First byte past the last cell pointer in data[] */
42935  int ins;          /* Index in data[] where new cell pointer is inserted */
42936  int cellOffset;   /* Address of first cell pointer in data[] */
42937  u8 *data;         /* The content of the whole page */
42938  u8 *ptr;          /* Used for moving information around in data[] */
42939
42940  int nSkip = (iChild ? 4 : 0);
42941
42942  if( *pRC ) return;
42943
42944  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
42945  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
42946  assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
42947  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42948  /* The cell should normally be sized correctly.  However, when moving a
42949  ** malformed cell from a leaf page to an interior page, if the cell size
42950  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
42951  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
42952  ** the term after the || in the following assert(). */
42953  assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
42954  if( pPage->nOverflow || sz+2>pPage->nFree ){
42955    if( pTemp ){
42956      memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
42957      pCell = pTemp;
42958    }
42959    if( iChild ){
42960      put4byte(pCell, iChild);
42961    }
42962    j = pPage->nOverflow++;
42963    assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
42964    pPage->aOvfl[j].pCell = pCell;
42965    pPage->aOvfl[j].idx = (u16)i;
42966  }else{
42967    int rc = sqlite3PagerWrite(pPage->pDbPage);
42968    if( rc!=SQLITE_OK ){
42969      *pRC = rc;
42970      return;
42971    }
42972    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
42973    data = pPage->aData;
42974    cellOffset = pPage->cellOffset;
42975    end = cellOffset + 2*pPage->nCell;
42976    ins = cellOffset + 2*i;
42977    rc = allocateSpace(pPage, sz, &idx);
42978    if( rc ){ *pRC = rc; return; }
42979    /* The allocateSpace() routine guarantees the following two properties
42980    ** if it returns success */
42981    assert( idx >= end+2 );
42982    assert( idx+sz <= pPage->pBt->usableSize );
42983    pPage->nCell++;
42984    pPage->nFree -= (u16)(2 + sz);
42985    memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
42986    if( iChild ){
42987      put4byte(&data[idx], iChild);
42988    }
42989    for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
42990      ptr[0] = ptr[-2];
42991      ptr[1] = ptr[-1];
42992    }
42993    put2byte(&data[ins], idx);
42994    put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
42995#ifndef SQLITE_OMIT_AUTOVACUUM
42996    if( pPage->pBt->autoVacuum ){
42997      /* The cell may contain a pointer to an overflow page. If so, write
42998      ** the entry for the overflow page into the pointer map.
42999      */
43000      ptrmapPutOvflPtr(pPage, pCell, pRC);
43001    }
43002#endif
43003  }
43004}
43005
43006/*
43007** Add a list of cells to a page.  The page should be initially empty.
43008** The cells are guaranteed to fit on the page.
43009*/
43010static void assemblePage(
43011  MemPage *pPage,   /* The page to be assemblied */
43012  int nCell,        /* The number of cells to add to this page */
43013  u8 **apCell,      /* Pointers to cell bodies */
43014  u16 *aSize        /* Sizes of the cells */
43015){
43016  int i;            /* Loop counter */
43017  u8 *pCellptr;     /* Address of next cell pointer */
43018  int cellbody;     /* Address of next cell body */
43019  u8 * const data = pPage->aData;             /* Pointer to data for pPage */
43020  const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
43021  const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
43022
43023  assert( pPage->nOverflow==0 );
43024  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43025  assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
43026  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
43027
43028  /* Check that the page has just been zeroed by zeroPage() */
43029  assert( pPage->nCell==0 );
43030  assert( get2byte(&data[hdr+5])==nUsable );
43031
43032  pCellptr = &data[pPage->cellOffset + nCell*2];
43033  cellbody = nUsable;
43034  for(i=nCell-1; i>=0; i--){
43035    pCellptr -= 2;
43036    cellbody -= aSize[i];
43037    put2byte(pCellptr, cellbody);
43038    memcpy(&data[cellbody], apCell[i], aSize[i]);
43039  }
43040  put2byte(&data[hdr+3], nCell);
43041  put2byte(&data[hdr+5], cellbody);
43042  pPage->nFree -= (nCell*2 + nUsable - cellbody);
43043  pPage->nCell = (u16)nCell;
43044}
43045
43046/*
43047** The following parameters determine how many adjacent pages get involved
43048** in a balancing operation.  NN is the number of neighbors on either side
43049** of the page that participate in the balancing operation.  NB is the
43050** total number of pages that participate, including the target page and
43051** NN neighbors on either side.
43052**
43053** The minimum value of NN is 1 (of course).  Increasing NN above 1
43054** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
43055** in exchange for a larger degradation in INSERT and UPDATE performance.
43056** The value of NN appears to give the best results overall.
43057*/
43058#define NN 1             /* Number of neighbors on either side of pPage */
43059#define NB (NN*2+1)      /* Total pages involved in the balance */
43060
43061
43062#ifndef SQLITE_OMIT_QUICKBALANCE
43063/*
43064** This version of balance() handles the common special case where
43065** a new entry is being inserted on the extreme right-end of the
43066** tree, in other words, when the new entry will become the largest
43067** entry in the tree.
43068**
43069** Instead of trying to balance the 3 right-most leaf pages, just add
43070** a new page to the right-hand side and put the one new entry in
43071** that page.  This leaves the right side of the tree somewhat
43072** unbalanced.  But odds are that we will be inserting new entries
43073** at the end soon afterwards so the nearly empty page will quickly
43074** fill up.  On average.
43075**
43076** pPage is the leaf page which is the right-most page in the tree.
43077** pParent is its parent.  pPage must have a single overflow entry
43078** which is also the right-most entry on the page.
43079**
43080** The pSpace buffer is used to store a temporary copy of the divider
43081** cell that will be inserted into pParent. Such a cell consists of a 4
43082** byte page number followed by a variable length integer. In other
43083** words, at most 13 bytes. Hence the pSpace buffer must be at
43084** least 13 bytes in size.
43085*/
43086static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
43087  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
43088  MemPage *pNew;                       /* Newly allocated page */
43089  int rc;                              /* Return Code */
43090  Pgno pgnoNew;                        /* Page number of pNew */
43091
43092  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43093  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43094  assert( pPage->nOverflow==1 );
43095
43096  if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT(BALANCE_QUICK_CORRUPTION); // Android Change
43097
43098  /* Allocate a new page. This page will become the right-sibling of
43099  ** pPage. Make the parent page writable, so that the new divider cell
43100  ** may be inserted. If both these operations are successful, proceed.
43101  */
43102  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
43103
43104  if( rc==SQLITE_OK ){
43105
43106    u8 *pOut = &pSpace[4];
43107    u8 *pCell = pPage->aOvfl[0].pCell;
43108    u16 szCell = cellSizePtr(pPage, pCell);
43109    u8 *pStop;
43110
43111    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
43112    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
43113    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
43114    assemblePage(pNew, 1, &pCell, &szCell);
43115
43116    /* If this is an auto-vacuum database, update the pointer map
43117    ** with entries for the new page, and any pointer from the
43118    ** cell on the page to an overflow page. If either of these
43119    ** operations fails, the return code is set, but the contents
43120    ** of the parent page are still manipulated by thh code below.
43121    ** That is Ok, at this point the parent page is guaranteed to
43122    ** be marked as dirty. Returning an error code will cause a
43123    ** rollback, undoing any changes made to the parent page.
43124    */
43125    if( ISAUTOVACUUM ){
43126      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
43127      if( szCell>pNew->minLocal ){
43128        ptrmapPutOvflPtr(pNew, pCell, &rc);
43129      }
43130    }
43131
43132    /* Create a divider cell to insert into pParent. The divider cell
43133    ** consists of a 4-byte page number (the page number of pPage) and
43134    ** a variable length key value (which must be the same value as the
43135    ** largest key on pPage).
43136    **
43137    ** To find the largest key value on pPage, first find the right-most
43138    ** cell on pPage. The first two fields of this cell are the
43139    ** record-length (a variable length integer at most 32-bits in size)
43140    ** and the key value (a variable length integer, may have any value).
43141    ** The first of the while(...) loops below skips over the record-length
43142    ** field. The second while(...) loop copies the key value from the
43143    ** cell on pPage into the pSpace buffer.
43144    */
43145    pCell = findCell(pPage, pPage->nCell-1);
43146    pStop = &pCell[9];
43147    while( (*(pCell++)&0x80) && pCell<pStop );
43148    pStop = &pCell[9];
43149    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
43150
43151    /* Insert the new divider cell into pParent. */
43152    insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
43153               0, pPage->pgno, &rc);
43154
43155    /* Set the right-child pointer of pParent to point to the new page. */
43156    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
43157
43158    /* Release the reference to the new page. */
43159    releasePage(pNew);
43160  }
43161
43162  return rc;
43163}
43164#endif /* SQLITE_OMIT_QUICKBALANCE */
43165
43166#if 0
43167/*
43168** This function does not contribute anything to the operation of SQLite.
43169** it is sometimes activated temporarily while debugging code responsible
43170** for setting pointer-map entries.
43171*/
43172static int ptrmapCheckPages(MemPage **apPage, int nPage){
43173  int i, j;
43174  for(i=0; i<nPage; i++){
43175    Pgno n;
43176    u8 e;
43177    MemPage *pPage = apPage[i];
43178    BtShared *pBt = pPage->pBt;
43179    assert( pPage->isInit );
43180
43181    for(j=0; j<pPage->nCell; j++){
43182      CellInfo info;
43183      u8 *z;
43184
43185      z = findCell(pPage, j);
43186      btreeParseCellPtr(pPage, z, &info);
43187      if( info.iOverflow ){
43188        Pgno ovfl = get4byte(&z[info.iOverflow]);
43189        ptrmapGet(pBt, ovfl, &e, &n);
43190        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
43191      }
43192      if( !pPage->leaf ){
43193        Pgno child = get4byte(z);
43194        ptrmapGet(pBt, child, &e, &n);
43195        assert( n==pPage->pgno && e==PTRMAP_BTREE );
43196      }
43197    }
43198    if( !pPage->leaf ){
43199      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
43200      ptrmapGet(pBt, child, &e, &n);
43201      assert( n==pPage->pgno && e==PTRMAP_BTREE );
43202    }
43203  }
43204  return 1;
43205}
43206#endif
43207
43208/*
43209** This function is used to copy the contents of the b-tree node stored
43210** on page pFrom to page pTo. If page pFrom was not a leaf page, then
43211** the pointer-map entries for each child page are updated so that the
43212** parent page stored in the pointer map is page pTo. If pFrom contained
43213** any cells with overflow page pointers, then the corresponding pointer
43214** map entries are also updated so that the parent page is page pTo.
43215**
43216** If pFrom is currently carrying any overflow cells (entries in the
43217** MemPage.aOvfl[] array), they are not copied to pTo.
43218**
43219** Before returning, page pTo is reinitialized using btreeInitPage().
43220**
43221** The performance of this function is not critical. It is only used by
43222** the balance_shallower() and balance_deeper() procedures, neither of
43223** which are called often under normal circumstances.
43224*/
43225static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
43226  if( (*pRC)==SQLITE_OK ){
43227    BtShared * const pBt = pFrom->pBt;
43228    u8 * const aFrom = pFrom->aData;
43229    u8 * const aTo = pTo->aData;
43230    int const iFromHdr = pFrom->hdrOffset;
43231    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
43232    int rc;
43233    int iData;
43234
43235
43236    assert( pFrom->isInit );
43237    assert( pFrom->nFree>=iToHdr );
43238    assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
43239
43240    /* Copy the b-tree node content from page pFrom to page pTo. */
43241    iData = get2byte(&aFrom[iFromHdr+5]);
43242    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
43243    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
43244
43245    /* Reinitialize page pTo so that the contents of the MemPage structure
43246    ** match the new data. The initialization of pTo can actually fail under
43247    ** fairly obscure circumstances, even though it is a copy of initialized
43248    ** page pFrom.
43249    */
43250    pTo->isInit = 0;
43251    rc = btreeInitPage(pTo);
43252    if( rc!=SQLITE_OK ){
43253      *pRC = rc;
43254      return;
43255    }
43256
43257    /* If this is an auto-vacuum database, update the pointer-map entries
43258    ** for any b-tree or overflow pages that pTo now contains the pointers to.
43259    */
43260    if( ISAUTOVACUUM ){
43261      *pRC = setChildPtrmaps(pTo);
43262    }
43263  }
43264}
43265
43266/*
43267** This routine redistributes cells on the iParentIdx'th child of pParent
43268** (hereafter "the page") and up to 2 siblings so that all pages have about the
43269** same amount of free space. Usually a single sibling on either side of the
43270** page are used in the balancing, though both siblings might come from one
43271** side if the page is the first or last child of its parent. If the page
43272** has fewer than 2 siblings (something which can only happen if the page
43273** is a root page or a child of a root page) then all available siblings
43274** participate in the balancing.
43275**
43276** The number of siblings of the page might be increased or decreased by
43277** one or two in an effort to keep pages nearly full but not over full.
43278**
43279** Note that when this routine is called, some of the cells on the page
43280** might not actually be stored in MemPage.aData[]. This can happen
43281** if the page is overfull. This routine ensures that all cells allocated
43282** to the page and its siblings fit into MemPage.aData[] before returning.
43283**
43284** In the course of balancing the page and its siblings, cells may be
43285** inserted into or removed from the parent page (pParent). Doing so
43286** may cause the parent page to become overfull or underfull. If this
43287** happens, it is the responsibility of the caller to invoke the correct
43288** balancing routine to fix this problem (see the balance() routine).
43289**
43290** If this routine fails for any reason, it might leave the database
43291** in a corrupted state. So if this routine fails, the database should
43292** be rolled back.
43293**
43294** The third argument to this function, aOvflSpace, is a pointer to a
43295** buffer big enough to hold one page. If while inserting cells into the parent
43296** page (pParent) the parent page becomes overfull, this buffer is
43297** used to store the parent's overflow cells. Because this function inserts
43298** a maximum of four divider cells into the parent page, and the maximum
43299** size of a cell stored within an internal node is always less than 1/4
43300** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
43301** enough for all overflow cells.
43302**
43303** If aOvflSpace is set to a null pointer, this function returns
43304** SQLITE_NOMEM.
43305*/
43306static int balance_nonroot(
43307  MemPage *pParent,               /* Parent page of siblings being balanced */
43308  int iParentIdx,                 /* Index of "the page" in pParent */
43309  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
43310  int isRoot                      /* True if pParent is a root-page */
43311){
43312  BtShared *pBt;               /* The whole database */
43313  int nCell = 0;               /* Number of cells in apCell[] */
43314  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
43315  int nNew = 0;                /* Number of pages in apNew[] */
43316  int nOld;                    /* Number of pages in apOld[] */
43317  int i, j, k;                 /* Loop counters */
43318  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
43319  int rc = SQLITE_OK;          /* The return code */
43320  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
43321  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
43322  int usableSpace;             /* Bytes in pPage beyond the header */
43323  int pageFlags;               /* Value of pPage->aData[0] */
43324  int subtotal;                /* Subtotal of bytes in cells on one page */
43325  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
43326  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
43327  int szScratch;               /* Size of scratch memory requested */
43328  MemPage *apOld[NB];          /* pPage and up to two siblings */
43329  MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
43330  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
43331  u8 *pRight;                  /* Location in parent of right-sibling pointer */
43332  u8 *apDiv[NB-1];             /* Divider cells in pParent */
43333  int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
43334  int szNew[NB+2];             /* Combined size of cells place on i-th page */
43335  u8 **apCell = 0;             /* All cells begin balanced */
43336  u16 *szCell;                 /* Local size of all cells in apCell[] */
43337  u8 *aSpace1;                 /* Space for copies of dividers cells */
43338  Pgno pgno;                   /* Temp var to store a page number in */
43339
43340  pBt = pParent->pBt;
43341  assert( sqlite3_mutex_held(pBt->mutex) );
43342  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43343
43344#if 0
43345  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
43346#endif
43347
43348  /* At this point pParent may have at most one overflow cell. And if
43349  ** this overflow cell is present, it must be the cell with
43350  ** index iParentIdx. This scenario comes about when this function
43351  ** is called (indirectly) from sqlite3BtreeDelete().
43352  */
43353  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
43354  assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
43355
43356  if( !aOvflSpace ){
43357    return SQLITE_NOMEM;
43358  }
43359
43360  /* Find the sibling pages to balance. Also locate the cells in pParent
43361  ** that divide the siblings. An attempt is made to find NN siblings on
43362  ** either side of pPage. More siblings are taken from one side, however,
43363  ** if there are fewer than NN siblings on the other side. If pParent
43364  ** has NB or fewer children then all children of pParent are taken.
43365  **
43366  ** This loop also drops the divider cells from the parent page. This
43367  ** way, the remainder of the function does not have to deal with any
43368  ** overflow cells in the parent page, since if any existed they will
43369  ** have already been removed.
43370  */
43371  i = pParent->nOverflow + pParent->nCell;
43372  if( i<2 ){
43373    nxDiv = 0;
43374    nOld = i+1;
43375  }else{
43376    nOld = 3;
43377    if( iParentIdx==0 ){
43378      nxDiv = 0;
43379    }else if( iParentIdx==i ){
43380      nxDiv = i-2;
43381    }else{
43382      nxDiv = iParentIdx-1;
43383    }
43384    i = 2;
43385  }
43386  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
43387    pRight = &pParent->aData[pParent->hdrOffset+8];
43388  }else{
43389    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
43390  }
43391  pgno = get4byte(pRight);
43392  while( 1 ){
43393    rc = getAndInitPage(pBt, pgno, &apOld[i]);
43394    if( rc ){
43395      memset(apOld, 0, (i+1)*sizeof(MemPage*));
43396      goto balance_cleanup;
43397    }
43398    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
43399    if( (i--)==0 ) break;
43400
43401    if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
43402      apDiv[i] = pParent->aOvfl[0].pCell;
43403      pgno = get4byte(apDiv[i]);
43404      szNew[i] = cellSizePtr(pParent, apDiv[i]);
43405      pParent->nOverflow = 0;
43406    }else{
43407      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
43408      pgno = get4byte(apDiv[i]);
43409      szNew[i] = cellSizePtr(pParent, apDiv[i]);
43410
43411      /* Drop the cell from the parent page. apDiv[i] still points to
43412      ** the cell within the parent, even though it has been dropped.
43413      ** This is safe because dropping a cell only overwrites the first
43414      ** four bytes of it, and this function does not need the first
43415      ** four bytes of the divider cell. So the pointer is safe to use
43416      ** later on.
43417      **
43418      ** Unless SQLite is compiled in secure-delete mode. In this case,
43419      ** the dropCell() routine will overwrite the entire cell with zeroes.
43420      ** In this case, temporarily copy the cell into the aOvflSpace[]
43421      ** buffer. It will be copied out again as soon as the aSpace[] buffer
43422      ** is allocated.  */
43423#ifdef SQLITE_SECURE_DELETE
43424      memcpy(&aOvflSpace[apDiv[i]-pParent->aData], apDiv[i], szNew[i]);
43425      apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
43426#endif
43427      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
43428    }
43429  }
43430
43431  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
43432  ** alignment */
43433  nMaxCells = (nMaxCells + 3)&~3;
43434
43435  /*
43436  ** Allocate space for memory structures
43437  */
43438  k = pBt->pageSize + ROUND8(sizeof(MemPage));
43439  szScratch =
43440       nMaxCells*sizeof(u8*)                       /* apCell */
43441     + nMaxCells*sizeof(u16)                       /* szCell */
43442     + pBt->pageSize                               /* aSpace1 */
43443     + k*nOld;                                     /* Page copies (apCopy) */
43444  apCell = sqlite3ScratchMalloc( szScratch );
43445  if( apCell==0 ){
43446    rc = SQLITE_NOMEM;
43447    goto balance_cleanup;
43448  }
43449  szCell = (u16*)&apCell[nMaxCells];
43450  aSpace1 = (u8*)&szCell[nMaxCells];
43451  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
43452
43453  /*
43454  ** Load pointers to all cells on sibling pages and the divider cells
43455  ** into the local apCell[] array.  Make copies of the divider cells
43456  ** into space obtained from aSpace1[] and remove the the divider Cells
43457  ** from pParent.
43458  **
43459  ** If the siblings are on leaf pages, then the child pointers of the
43460  ** divider cells are stripped from the cells before they are copied
43461  ** into aSpace1[].  In this way, all cells in apCell[] are without
43462  ** child pointers.  If siblings are not leaves, then all cell in
43463  ** apCell[] include child pointers.  Either way, all cells in apCell[]
43464  ** are alike.
43465  **
43466  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
43467  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
43468  */
43469  leafCorrection = apOld[0]->leaf*4;
43470  leafData = apOld[0]->hasData;
43471  for(i=0; i<nOld; i++){
43472    int limit;
43473
43474    /* Before doing anything else, take a copy of the i'th original sibling
43475    ** The rest of this function will use data from the copies rather
43476    ** that the original pages since the original pages will be in the
43477    ** process of being overwritten.  */
43478    MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
43479    memcpy(pOld, apOld[i], sizeof(MemPage));
43480    pOld->aData = (void*)&pOld[1];
43481    memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
43482
43483    limit = pOld->nCell+pOld->nOverflow;
43484    for(j=0; j<limit; j++){
43485      assert( nCell<nMaxCells );
43486      apCell[nCell] = findOverflowCell(pOld, j);
43487      szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
43488      nCell++;
43489    }
43490    if( i<nOld-1 && !leafData){
43491      u16 sz = (u16)szNew[i];
43492      u8 *pTemp;
43493      assert( nCell<nMaxCells );
43494      szCell[nCell] = sz;
43495      pTemp = &aSpace1[iSpace1];
43496      iSpace1 += sz;
43497      assert( sz<=pBt->pageSize/4 );
43498      assert( iSpace1<=pBt->pageSize );
43499      memcpy(pTemp, apDiv[i], sz);
43500      apCell[nCell] = pTemp+leafCorrection;
43501      assert( leafCorrection==0 || leafCorrection==4 );
43502      szCell[nCell] = szCell[nCell] - leafCorrection;
43503      if( !pOld->leaf ){
43504        assert( leafCorrection==0 );
43505        assert( pOld->hdrOffset==0 );
43506        /* The right pointer of the child page pOld becomes the left
43507        ** pointer of the divider cell */
43508        memcpy(apCell[nCell], &pOld->aData[8], 4);
43509      }else{
43510        assert( leafCorrection==4 );
43511        if( szCell[nCell]<4 ){
43512          /* Do not allow any cells smaller than 4 bytes. */
43513          szCell[nCell] = 4;
43514        }
43515      }
43516      nCell++;
43517    }
43518  }
43519
43520  /*
43521  ** Figure out the number of pages needed to hold all nCell cells.
43522  ** Store this number in "k".  Also compute szNew[] which is the total
43523  ** size of all cells on the i-th page and cntNew[] which is the index
43524  ** in apCell[] of the cell that divides page i from page i+1.
43525  ** cntNew[k] should equal nCell.
43526  **
43527  ** Values computed by this block:
43528  **
43529  **           k: The total number of sibling pages
43530  **    szNew[i]: Spaced used on the i-th sibling page.
43531  **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
43532  **              the right of the i-th sibling page.
43533  ** usableSpace: Number of bytes of space available on each sibling.
43534  **
43535  */
43536  usableSpace = pBt->usableSize - 12 + leafCorrection;
43537  for(subtotal=k=i=0; i<nCell; i++){
43538    assert( i<nMaxCells );
43539    subtotal += szCell[i] + 2;
43540    if( subtotal > usableSpace ){
43541      szNew[k] = subtotal - szCell[i];
43542      cntNew[k] = i;
43543      if( leafData ){ i--; }
43544      subtotal = 0;
43545      k++;
43546      if( k>NB+1 ){ rc = SQLITE_CORRUPT; goto balance_cleanup; }
43547    }
43548  }
43549  szNew[k] = subtotal;
43550  cntNew[k] = nCell;
43551  k++;
43552
43553  /*
43554  ** The packing computed by the previous block is biased toward the siblings
43555  ** on the left side.  The left siblings are always nearly full, while the
43556  ** right-most sibling might be nearly empty.  This block of code attempts
43557  ** to adjust the packing of siblings to get a better balance.
43558  **
43559  ** This adjustment is more than an optimization.  The packing above might
43560  ** be so out of balance as to be illegal.  For example, the right-most
43561  ** sibling might be completely empty.  This adjustment is not optional.
43562  */
43563  for(i=k-1; i>0; i--){
43564    int szRight = szNew[i];  /* Size of sibling on the right */
43565    int szLeft = szNew[i-1]; /* Size of sibling on the left */
43566    int r;              /* Index of right-most cell in left sibling */
43567    int d;              /* Index of first cell to the left of right sibling */
43568
43569    r = cntNew[i-1] - 1;
43570    d = r + 1 - leafData;
43571    assert( d<nMaxCells );
43572    assert( r<nMaxCells );
43573    while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
43574      szRight += szCell[d] + 2;
43575      szLeft -= szCell[r] + 2;
43576      cntNew[i-1]--;
43577      r = cntNew[i-1] - 1;
43578      d = r + 1 - leafData;
43579    }
43580    szNew[i] = szRight;
43581    szNew[i-1] = szLeft;
43582  }
43583
43584  /* Either we found one or more cells (cntnew[0])>0) or pPage is
43585  ** a virtual root page.  A virtual root page is when the real root
43586  ** page is page 1 and we are the only child of that page.
43587  */
43588  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
43589
43590  TRACE(("BALANCE: old: %d %d %d  ",
43591    apOld[0]->pgno,
43592    nOld>=2 ? apOld[1]->pgno : 0,
43593    nOld>=3 ? apOld[2]->pgno : 0
43594  ));
43595
43596  /*
43597  ** Allocate k new pages.  Reuse old pages where possible.
43598  */
43599  if( apOld[0]->pgno<=1 ){
43600    rc = SQLITE_CORRUPT;
43601    goto balance_cleanup;
43602  }
43603  pageFlags = apOld[0]->aData[0];
43604  for(i=0; i<k; i++){
43605    MemPage *pNew;
43606    if( i<nOld ){
43607      pNew = apNew[i] = apOld[i];
43608      apOld[i] = 0;
43609      rc = sqlite3PagerWrite(pNew->pDbPage);
43610      nNew++;
43611      if( rc ) goto balance_cleanup;
43612    }else{
43613      assert( i>0 );
43614      rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
43615      if( rc ) goto balance_cleanup;
43616      apNew[i] = pNew;
43617      nNew++;
43618
43619      /* Set the pointer-map entry for the new sibling page. */
43620      if( ISAUTOVACUUM ){
43621        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
43622        if( rc!=SQLITE_OK ){
43623          goto balance_cleanup;
43624        }
43625      }
43626    }
43627  }
43628
43629  /* Free any old pages that were not reused as new pages.
43630  */
43631  while( i<nOld ){
43632    freePage(apOld[i], &rc);
43633    if( rc ) goto balance_cleanup;
43634    releasePage(apOld[i]);
43635    apOld[i] = 0;
43636    i++;
43637  }
43638
43639  /*
43640  ** Put the new pages in accending order.  This helps to
43641  ** keep entries in the disk file in order so that a scan
43642  ** of the table is a linear scan through the file.  That
43643  ** in turn helps the operating system to deliver pages
43644  ** from the disk more rapidly.
43645  **
43646  ** An O(n^2) insertion sort algorithm is used, but since
43647  ** n is never more than NB (a small constant), that should
43648  ** not be a problem.
43649  **
43650  ** When NB==3, this one optimization makes the database
43651  ** about 25% faster for large insertions and deletions.
43652  */
43653  for(i=0; i<k-1; i++){
43654    int minV = apNew[i]->pgno;
43655    int minI = i;
43656    for(j=i+1; j<k; j++){
43657      if( apNew[j]->pgno<(unsigned)minV ){
43658        minI = j;
43659        minV = apNew[j]->pgno;
43660      }
43661    }
43662    if( minI>i ){
43663      int t;
43664      MemPage *pT;
43665      t = apNew[i]->pgno;
43666      pT = apNew[i];
43667      apNew[i] = apNew[minI];
43668      apNew[minI] = pT;
43669    }
43670  }
43671  TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
43672    apNew[0]->pgno, szNew[0],
43673    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
43674    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
43675    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
43676    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
43677
43678  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43679  put4byte(pRight, apNew[nNew-1]->pgno);
43680
43681  /*
43682  ** Evenly distribute the data in apCell[] across the new pages.
43683  ** Insert divider cells into pParent as necessary.
43684  */
43685  j = 0;
43686  for(i=0; i<nNew; i++){
43687    /* Assemble the new sibling page. */
43688    MemPage *pNew = apNew[i];
43689    assert( j<nMaxCells );
43690    zeroPage(pNew, pageFlags);
43691    assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
43692    assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
43693    assert( pNew->nOverflow==0 );
43694
43695    j = cntNew[i];
43696
43697    /* If the sibling page assembled above was not the right-most sibling,
43698    ** insert a divider cell into the parent page.
43699    */
43700    assert( i<nNew-1 || j==nCell );
43701    if( j<nCell ){
43702      u8 *pCell;
43703      u8 *pTemp;
43704      int sz;
43705
43706      assert( j<nMaxCells );
43707      pCell = apCell[j];
43708      sz = szCell[j] + leafCorrection;
43709      pTemp = &aOvflSpace[iOvflSpace];
43710      if( !pNew->leaf ){
43711        memcpy(&pNew->aData[8], pCell, 4);
43712      }else if( leafData ){
43713        /* If the tree is a leaf-data tree, and the siblings are leaves,
43714        ** then there is no divider cell in apCell[]. Instead, the divider
43715        ** cell consists of the integer key for the right-most cell of
43716        ** the sibling-page assembled above only.
43717        */
43718        CellInfo info;
43719        j--;
43720        btreeParseCellPtr(pNew, apCell[j], &info);
43721        pCell = pTemp;
43722        sz = 4 + putVarint(&pCell[4], info.nKey);
43723        pTemp = 0;
43724      }else{
43725        pCell -= 4;
43726        /* Obscure case for non-leaf-data trees: If the cell at pCell was
43727        ** previously stored on a leaf node, and its reported size was 4
43728        ** bytes, then it may actually be smaller than this
43729        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
43730        ** any cell). But it is important to pass the correct size to
43731        ** insertCell(), so reparse the cell now.
43732        **
43733        ** Note that this can never happen in an SQLite data file, as all
43734        ** cells are at least 4 bytes. It only happens in b-trees used
43735        ** to evaluate "IN (SELECT ...)" and similar clauses.
43736        */
43737        if( szCell[j]==4 ){
43738          assert(leafCorrection==4);
43739          sz = cellSizePtr(pParent, pCell);
43740        }
43741      }
43742      iOvflSpace += sz;
43743      assert( sz<=pBt->pageSize/4 );
43744      assert( iOvflSpace<=pBt->pageSize );
43745      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
43746      if( rc!=SQLITE_OK ) goto balance_cleanup;
43747      assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43748
43749      j++;
43750      nxDiv++;
43751    }
43752  }
43753  assert( j==nCell );
43754  assert( nOld>0 );
43755  assert( nNew>0 );
43756  if( (pageFlags & PTF_LEAF)==0 ){
43757    u8 *zChild = &apCopy[nOld-1]->aData[8];
43758    memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
43759  }
43760
43761  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
43762    /* The root page of the b-tree now contains no cells. The only sibling
43763    ** page is the right-child of the parent. Copy the contents of the
43764    ** child page into the parent, decreasing the overall height of the
43765    ** b-tree structure by one. This is described as the "balance-shallower"
43766    ** sub-algorithm in some documentation.
43767    **
43768    ** If this is an auto-vacuum database, the call to copyNodeContent()
43769    ** sets all pointer-map entries corresponding to database image pages
43770    ** for which the pointer is stored within the content being copied.
43771    **
43772    ** The second assert below verifies that the child page is defragmented
43773    ** (it must be, as it was just reconstructed using assemblePage()). This
43774    ** is important if the parent page happens to be page 1 of the database
43775    ** image.  */
43776    assert( nNew==1 );
43777    assert( apNew[0]->nFree ==
43778        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
43779    );
43780    copyNodeContent(apNew[0], pParent, &rc);
43781    freePage(apNew[0], &rc);
43782  }else if( ISAUTOVACUUM ){
43783    /* Fix the pointer-map entries for all the cells that were shifted around.
43784    ** There are several different types of pointer-map entries that need to
43785    ** be dealt with by this routine. Some of these have been set already, but
43786    ** many have not. The following is a summary:
43787    **
43788    **   1) The entries associated with new sibling pages that were not
43789    **      siblings when this function was called. These have already
43790    **      been set. We don't need to worry about old siblings that were
43791    **      moved to the free-list - the freePage() code has taken care
43792    **      of those.
43793    **
43794    **   2) The pointer-map entries associated with the first overflow
43795    **      page in any overflow chains used by new divider cells. These
43796    **      have also already been taken care of by the insertCell() code.
43797    **
43798    **   3) If the sibling pages are not leaves, then the child pages of
43799    **      cells stored on the sibling pages may need to be updated.
43800    **
43801    **   4) If the sibling pages are not internal intkey nodes, then any
43802    **      overflow pages used by these cells may need to be updated
43803    **      (internal intkey nodes never contain pointers to overflow pages).
43804    **
43805    **   5) If the sibling pages are not leaves, then the pointer-map
43806    **      entries for the right-child pages of each sibling may need
43807    **      to be updated.
43808    **
43809    ** Cases 1 and 2 are dealt with above by other code. The next
43810    ** block deals with cases 3 and 4 and the one after that, case 5. Since
43811    ** setting a pointer map entry is a relatively expensive operation, this
43812    ** code only sets pointer map entries for child or overflow pages that have
43813    ** actually moved between pages.  */
43814    MemPage *pNew = apNew[0];
43815    MemPage *pOld = apCopy[0];
43816    int nOverflow = pOld->nOverflow;
43817    int iNextOld = pOld->nCell + nOverflow;
43818    int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
43819    j = 0;                             /* Current 'old' sibling page */
43820    k = 0;                             /* Current 'new' sibling page */
43821    for(i=0; i<nCell; i++){
43822      int isDivider = 0;
43823      while( i==iNextOld ){
43824        /* Cell i is the cell immediately following the last cell on old
43825        ** sibling page j. If the siblings are not leaf pages of an
43826        ** intkey b-tree, then cell i was a divider cell. */
43827        pOld = apCopy[++j];
43828        iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
43829        if( pOld->nOverflow ){
43830          nOverflow = pOld->nOverflow;
43831          iOverflow = i + !leafData + pOld->aOvfl[0].idx;
43832        }
43833        isDivider = !leafData;
43834      }
43835
43836      assert(nOverflow>0 || iOverflow<i );
43837      assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
43838      assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
43839      if( i==iOverflow ){
43840        isDivider = 1;
43841        if( (--nOverflow)>0 ){
43842          iOverflow++;
43843        }
43844      }
43845
43846      if( i==cntNew[k] ){
43847        /* Cell i is the cell immediately following the last cell on new
43848        ** sibling page k. If the siblings are not leaf pages of an
43849        ** intkey b-tree, then cell i is a divider cell.  */
43850        pNew = apNew[++k];
43851        if( !leafData ) continue;
43852      }
43853      assert( j<nOld );
43854      assert( k<nNew );
43855
43856      /* If the cell was originally divider cell (and is not now) or
43857      ** an overflow cell, or if the cell was located on a different sibling
43858      ** page before the balancing, then the pointer map entries associated
43859      ** with any child or overflow pages need to be updated.  */
43860      if( isDivider || pOld->pgno!=pNew->pgno ){
43861        if( !leafCorrection ){
43862          ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
43863        }
43864        if( szCell[i]>pNew->minLocal ){
43865          ptrmapPutOvflPtr(pNew, apCell[i], &rc);
43866        }
43867      }
43868    }
43869
43870    if( !leafCorrection ){
43871      for(i=0; i<nNew; i++){
43872        u32 key = get4byte(&apNew[i]->aData[8]);
43873        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
43874      }
43875    }
43876
43877#if 0
43878    /* The ptrmapCheckPages() contains assert() statements that verify that
43879    ** all pointer map pages are set correctly. This is helpful while
43880    ** debugging. This is usually disabled because a corrupt database may
43881    ** cause an assert() statement to fail.  */
43882    ptrmapCheckPages(apNew, nNew);
43883    ptrmapCheckPages(&pParent, 1);
43884#endif
43885  }
43886
43887  assert( pParent->isInit );
43888  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
43889          nOld, nNew, nCell));
43890
43891  /*
43892  ** Cleanup before returning.
43893  */
43894balance_cleanup:
43895  sqlite3ScratchFree(apCell);
43896  for(i=0; i<nOld; i++){
43897    releasePage(apOld[i]);
43898  }
43899  for(i=0; i<nNew; i++){
43900    releasePage(apNew[i]);
43901  }
43902
43903  return rc;
43904}
43905
43906
43907/*
43908** This function is called when the root page of a b-tree structure is
43909** overfull (has one or more overflow pages).
43910**
43911** A new child page is allocated and the contents of the current root
43912** page, including overflow cells, are copied into the child. The root
43913** page is then overwritten to make it an empty page with the right-child
43914** pointer pointing to the new page.
43915**
43916** Before returning, all pointer-map entries corresponding to pages
43917** that the new child-page now contains pointers to are updated. The
43918** entry corresponding to the new right-child pointer of the root
43919** page is also updated.
43920**
43921** If successful, *ppChild is set to contain a reference to the child
43922** page and SQLITE_OK is returned. In this case the caller is required
43923** to call releasePage() on *ppChild exactly once. If an error occurs,
43924** an error code is returned and *ppChild is set to 0.
43925*/
43926static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
43927  int rc;                        /* Return value from subprocedures */
43928  MemPage *pChild = 0;           /* Pointer to a new child page */
43929  Pgno pgnoChild = 0;            /* Page number of the new child page */
43930  BtShared *pBt = pRoot->pBt;    /* The BTree */
43931
43932  assert( pRoot->nOverflow>0 );
43933  assert( sqlite3_mutex_held(pBt->mutex) );
43934
43935  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
43936  ** page that will become the new right-child of pPage. Copy the contents
43937  ** of the node stored on pRoot into the new child page.
43938  */
43939  rc = sqlite3PagerWrite(pRoot->pDbPage);
43940  if( rc==SQLITE_OK ){
43941    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
43942    copyNodeContent(pRoot, pChild, &rc);
43943    if( ISAUTOVACUUM ){
43944      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
43945    }
43946  }
43947  if( rc ){
43948    *ppChild = 0;
43949    releasePage(pChild);
43950    return rc;
43951  }
43952  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
43953  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
43954  assert( pChild->nCell==pRoot->nCell );
43955
43956  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
43957
43958  /* Copy the overflow cells from pRoot to pChild */
43959  memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
43960  pChild->nOverflow = pRoot->nOverflow;
43961
43962  /* Zero the contents of pRoot. Then install pChild as the right-child. */
43963  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
43964  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
43965
43966  *ppChild = pChild;
43967  return SQLITE_OK;
43968}
43969
43970/*
43971** The page that pCur currently points to has just been modified in
43972** some way. This function figures out if this modification means the
43973** tree needs to be balanced, and if so calls the appropriate balancing
43974** routine. Balancing routines are:
43975**
43976**   balance_quick()
43977**   balance_deeper()
43978**   balance_nonroot()
43979*/
43980static int balance(BtCursor *pCur){
43981  int rc = SQLITE_OK;
43982  const int nMin = pCur->pBt->usableSize * 2 / 3;
43983  u8 aBalanceQuickSpace[13];
43984  u8 *pFree = 0;
43985
43986  TESTONLY( int balance_quick_called = 0 );
43987  TESTONLY( int balance_deeper_called = 0 );
43988
43989  do {
43990    int iPage = pCur->iPage;
43991    MemPage *pPage = pCur->apPage[iPage];
43992
43993    if( iPage==0 ){
43994      if( pPage->nOverflow ){
43995        /* The root page of the b-tree is overfull. In this case call the
43996        ** balance_deeper() function to create a new child for the root-page
43997        ** and copy the current contents of the root-page to it. The
43998        ** next iteration of the do-loop will balance the child page.
43999        */
44000        assert( (balance_deeper_called++)==0 );
44001        rc = balance_deeper(pPage, &pCur->apPage[1]);
44002        if( rc==SQLITE_OK ){
44003          pCur->iPage = 1;
44004          pCur->aiIdx[0] = 0;
44005          pCur->aiIdx[1] = 0;
44006          assert( pCur->apPage[1]->nOverflow );
44007        }
44008      }else{
44009        break;
44010      }
44011    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
44012      break;
44013    }else{
44014      MemPage * const pParent = pCur->apPage[iPage-1];
44015      int const iIdx = pCur->aiIdx[iPage-1];
44016
44017      rc = sqlite3PagerWrite(pParent->pDbPage);
44018      if( rc==SQLITE_OK ){
44019#ifndef SQLITE_OMIT_QUICKBALANCE
44020        if( pPage->hasData
44021         && pPage->nOverflow==1
44022         && pPage->aOvfl[0].idx==pPage->nCell
44023         && pParent->pgno!=1
44024         && pParent->nCell==iIdx
44025        ){
44026          /* Call balance_quick() to create a new sibling of pPage on which
44027          ** to store the overflow cell. balance_quick() inserts a new cell
44028          ** into pParent, which may cause pParent overflow. If this
44029          ** happens, the next interation of the do-loop will balance pParent
44030          ** use either balance_nonroot() or balance_deeper(). Until this
44031          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
44032          ** buffer.
44033          **
44034          ** The purpose of the following assert() is to check that only a
44035          ** single call to balance_quick() is made for each call to this
44036          ** function. If this were not verified, a subtle bug involving reuse
44037          ** of the aBalanceQuickSpace[] might sneak in.
44038          */
44039          assert( (balance_quick_called++)==0 );
44040          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
44041        }else
44042#endif
44043        {
44044          /* In this case, call balance_nonroot() to redistribute cells
44045          ** between pPage and up to 2 of its sibling pages. This involves
44046          ** modifying the contents of pParent, which may cause pParent to
44047          ** become overfull or underfull. The next iteration of the do-loop
44048          ** will balance the parent page to correct this.
44049          **
44050          ** If the parent page becomes overfull, the overflow cell or cells
44051          ** are stored in the pSpace buffer allocated immediately below.
44052          ** A subsequent iteration of the do-loop will deal with this by
44053          ** calling balance_nonroot() (balance_deeper() may be called first,
44054          ** but it doesn't deal with overflow cells - just moves them to a
44055          ** different page). Once this subsequent call to balance_nonroot()
44056          ** has completed, it is safe to release the pSpace buffer used by
44057          ** the previous call, as the overflow cell data will have been
44058          ** copied either into the body of a database page or into the new
44059          ** pSpace buffer passed to the latter call to balance_nonroot().
44060          */
44061          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
44062          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
44063          if( pFree ){
44064            /* If pFree is not NULL, it points to the pSpace buffer used
44065            ** by a previous call to balance_nonroot(). Its contents are
44066            ** now stored either on real database pages or within the
44067            ** new pSpace buffer, so it may be safely freed here. */
44068            sqlite3PageFree(pFree);
44069          }
44070
44071          /* The pSpace buffer will be freed after the next call to
44072          ** balance_nonroot(), or just before this function returns, whichever
44073          ** comes first. */
44074          pFree = pSpace;
44075        }
44076      }
44077
44078      pPage->nOverflow = 0;
44079
44080      /* The next iteration of the do-loop balances the parent page. */
44081      releasePage(pPage);
44082      pCur->iPage--;
44083    }
44084  }while( rc==SQLITE_OK );
44085
44086  if( pFree ){
44087    sqlite3PageFree(pFree);
44088  }
44089  return rc;
44090}
44091
44092
44093/*
44094** Insert a new record into the BTree.  The key is given by (pKey,nKey)
44095** and the data is given by (pData,nData).  The cursor is used only to
44096** define what table the record should be inserted into.  The cursor
44097** is left pointing at a random location.
44098**
44099** For an INTKEY table, only the nKey value of the key is used.  pKey is
44100** ignored.  For a ZERODATA table, the pData and nData are both ignored.
44101**
44102** If the seekResult parameter is non-zero, then a successful call to
44103** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
44104** been performed. seekResult is the search result returned (a negative
44105** number if pCur points at an entry that is smaller than (pKey, nKey), or
44106** a positive value if pCur points at an etry that is larger than
44107** (pKey, nKey)).
44108**
44109** If the seekResult parameter is non-zero, then the caller guarantees that
44110** cursor pCur is pointing at the existing copy of a row that is to be
44111** overwritten.  If the seekResult parameter is 0, then cursor pCur may
44112** point to any entry or to no entry at all and so this function has to seek
44113** the cursor before the new key can be inserted.
44114*/
44115SQLITE_PRIVATE int sqlite3BtreeInsert(
44116  BtCursor *pCur,                /* Insert data into the table of this cursor */
44117  const void *pKey, i64 nKey,    /* The key of the new record */
44118  const void *pData, int nData,  /* The data of the new record */
44119  int nZero,                     /* Number of extra 0 bytes to append to data */
44120  int appendBias,                /* True if this is likely an append */
44121  int seekResult                 /* Result of prior MovetoUnpacked() call */
44122){
44123  int rc;
44124  int loc = seekResult;          /* -1: before desired location  +1: after */
44125  int szNew = 0;
44126  int idx;
44127  MemPage *pPage;
44128  Btree *p = pCur->pBtree;
44129  BtShared *pBt = p->pBt;
44130  unsigned char *oldCell;
44131  unsigned char *newCell = 0;
44132
44133  if( pCur->eState==CURSOR_FAULT ){
44134    assert( pCur->skipNext!=SQLITE_OK );
44135    return pCur->skipNext;
44136  }
44137
44138  assert( cursorHoldsMutex(pCur) );
44139  assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
44140  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
44141
44142  /* Assert that the caller has been consistent. If this cursor was opened
44143  ** expecting an index b-tree, then the caller should be inserting blob
44144  ** keys with no associated data. If the cursor was opened expecting an
44145  ** intkey table, the caller should be inserting integer keys with a
44146  ** blob of associated data.  */
44147  assert( (pKey==0)==(pCur->pKeyInfo==0) );
44148
44149  /* If this is an insert into a table b-tree, invalidate any incrblob
44150  ** cursors open on the row being replaced (assuming this is a replace
44151  ** operation - if it is not, the following is a no-op).  */
44152  if( pCur->pKeyInfo==0 ){
44153    invalidateIncrblobCursors(p, nKey, 0);
44154  }
44155
44156  /* Save the positions of any other cursors open on this table.
44157  **
44158  ** In some cases, the call to btreeMoveto() below is a no-op. For
44159  ** example, when inserting data into a table with auto-generated integer
44160  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
44161  ** integer key to use. It then calls this function to actually insert the
44162  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
44163  ** that the cursor is already where it needs to be and returns without
44164  ** doing any work. To avoid thwarting these optimizations, it is important
44165  ** not to clear the cursor here.
44166  */
44167  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
44168  if( rc ) return rc;
44169  if( !loc ){
44170    rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
44171    if( rc ) return rc;
44172  }
44173  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
44174
44175  pPage = pCur->apPage[pCur->iPage];
44176  assert( pPage->intKey || nKey>=0 );
44177  assert( pPage->leaf || !pPage->intKey );
44178
44179  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
44180          pCur->pgnoRoot, nKey, nData, pPage->pgno,
44181          loc==0 ? "overwrite" : "new entry"));
44182  assert( pPage->isInit );
44183  allocateTempSpace(pBt);
44184  newCell = pBt->pTmpSpace;
44185  if( newCell==0 ) return SQLITE_NOMEM;
44186  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
44187  if( rc ) goto end_insert;
44188  assert( szNew==cellSizePtr(pPage, newCell) );
44189  assert( szNew<=MX_CELL_SIZE(pBt) );
44190  idx = pCur->aiIdx[pCur->iPage];
44191  if( loc==0 ){
44192    u16 szOld;
44193    assert( idx<pPage->nCell );
44194    rc = sqlite3PagerWrite(pPage->pDbPage);
44195    if( rc ){
44196      goto end_insert;
44197    }
44198    oldCell = findCell(pPage, idx);
44199    if( !pPage->leaf ){
44200      memcpy(newCell, oldCell, 4);
44201    }
44202    szOld = cellSizePtr(pPage, oldCell);
44203    rc = clearCell(pPage, oldCell);
44204    dropCell(pPage, idx, szOld, &rc);
44205    if( rc ) goto end_insert;
44206  }else if( loc<0 && pPage->nCell>0 ){
44207    assert( pPage->leaf );
44208    idx = ++pCur->aiIdx[pCur->iPage];
44209  }else{
44210    assert( pPage->leaf );
44211  }
44212  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
44213  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
44214
44215  /* If no error has occured and pPage has an overflow cell, call balance()
44216  ** to redistribute the cells within the tree. Since balance() may move
44217  ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
44218  ** variables.
44219  **
44220  ** Previous versions of SQLite called moveToRoot() to move the cursor
44221  ** back to the root page as balance() used to invalidate the contents
44222  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
44223  ** set the cursor state to "invalid". This makes common insert operations
44224  ** slightly faster.
44225  **
44226  ** There is a subtle but important optimization here too. When inserting
44227  ** multiple records into an intkey b-tree using a single cursor (as can
44228  ** happen while processing an "INSERT INTO ... SELECT" statement), it
44229  ** is advantageous to leave the cursor pointing to the last entry in
44230  ** the b-tree if possible. If the cursor is left pointing to the last
44231  ** entry in the table, and the next row inserted has an integer key
44232  ** larger than the largest existing key, it is possible to insert the
44233  ** row without seeking the cursor. This can be a big performance boost.
44234  */
44235  pCur->info.nSize = 0;
44236  pCur->validNKey = 0;
44237  if( rc==SQLITE_OK && pPage->nOverflow ){
44238    rc = balance(pCur);
44239
44240    /* Must make sure nOverflow is reset to zero even if the balance()
44241    ** fails. Internal data structure corruption will result otherwise.
44242    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
44243    ** from trying to save the current position of the cursor.  */
44244    pCur->apPage[pCur->iPage]->nOverflow = 0;
44245    pCur->eState = CURSOR_INVALID;
44246  }
44247  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
44248
44249end_insert:
44250  return rc;
44251}
44252
44253/*
44254** Delete the entry that the cursor is pointing to.  The cursor
44255** is left pointing at a arbitrary location.
44256*/
44257SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
44258  Btree *p = pCur->pBtree;
44259  BtShared *pBt = p->pBt;
44260  int rc;                              /* Return code */
44261  MemPage *pPage;                      /* Page to delete cell from */
44262  unsigned char *pCell;                /* Pointer to cell to delete */
44263  int iCellIdx;                        /* Index of cell to delete */
44264  int iCellDepth;                      /* Depth of node containing pCell */
44265
44266  assert( cursorHoldsMutex(pCur) );
44267  assert( pBt->inTransaction==TRANS_WRITE );
44268  assert( !pBt->readOnly );
44269  assert( pCur->wrFlag );
44270  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
44271  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
44272
44273  if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
44274   || NEVER(pCur->eState!=CURSOR_VALID)
44275  ){
44276    return SQLITE_ERROR;  /* Something has gone awry. */
44277  }
44278
44279  /* If this is a delete operation to remove a row from a table b-tree,
44280  ** invalidate any incrblob cursors open on the row being deleted.  */
44281  if( pCur->pKeyInfo==0 ){
44282    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
44283  }
44284
44285  iCellDepth = pCur->iPage;
44286  iCellIdx = pCur->aiIdx[iCellDepth];
44287  pPage = pCur->apPage[iCellDepth];
44288  pCell = findCell(pPage, iCellIdx);
44289
44290  /* If the page containing the entry to delete is not a leaf page, move
44291  ** the cursor to the largest entry in the tree that is smaller than
44292  ** the entry being deleted. This cell will replace the cell being deleted
44293  ** from the internal node. The 'previous' entry is used for this instead
44294  ** of the 'next' entry, as the previous entry is always a part of the
44295  ** sub-tree headed by the child page of the cell being deleted. This makes
44296  ** balancing the tree following the delete operation easier.  */
44297  if( !pPage->leaf ){
44298    int notUsed;
44299    rc = sqlite3BtreePrevious(pCur, &notUsed);
44300    if( rc ) return rc;
44301  }
44302
44303  /* Save the positions of any other cursors open on this table before
44304  ** making any modifications. Make the page containing the entry to be
44305  ** deleted writable. Then free any overflow pages associated with the
44306  ** entry and finally remove the cell itself from within the page.
44307  */
44308  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
44309  if( rc ) return rc;
44310  rc = sqlite3PagerWrite(pPage->pDbPage);
44311  if( rc ) return rc;
44312  rc = clearCell(pPage, pCell);
44313  dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
44314  if( rc ) return rc;
44315
44316  /* If the cell deleted was not located on a leaf page, then the cursor
44317  ** is currently pointing to the largest entry in the sub-tree headed
44318  ** by the child-page of the cell that was just deleted from an internal
44319  ** node. The cell from the leaf node needs to be moved to the internal
44320  ** node to replace the deleted cell.  */
44321  if( !pPage->leaf ){
44322    MemPage *pLeaf = pCur->apPage[pCur->iPage];
44323    int nCell;
44324    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
44325    unsigned char *pTmp;
44326
44327    pCell = findCell(pLeaf, pLeaf->nCell-1);
44328    nCell = cellSizePtr(pLeaf, pCell);
44329    assert( MX_CELL_SIZE(pBt)>=nCell );
44330
44331    allocateTempSpace(pBt);
44332    pTmp = pBt->pTmpSpace;
44333
44334    rc = sqlite3PagerWrite(pLeaf->pDbPage);
44335    insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
44336    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
44337    if( rc ) return rc;
44338  }
44339
44340  /* Balance the tree. If the entry deleted was located on a leaf page,
44341  ** then the cursor still points to that page. In this case the first
44342  ** call to balance() repairs the tree, and the if(...) condition is
44343  ** never true.
44344  **
44345  ** Otherwise, if the entry deleted was on an internal node page, then
44346  ** pCur is pointing to the leaf page from which a cell was removed to
44347  ** replace the cell deleted from the internal node. This is slightly
44348  ** tricky as the leaf node may be underfull, and the internal node may
44349  ** be either under or overfull. In this case run the balancing algorithm
44350  ** on the leaf node first. If the balance proceeds far enough up the
44351  ** tree that we can be sure that any problem in the internal node has
44352  ** been corrected, so be it. Otherwise, after balancing the leaf node,
44353  ** walk the cursor up the tree to the internal node and balance it as
44354  ** well.  */
44355  rc = balance(pCur);
44356  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
44357    while( pCur->iPage>iCellDepth ){
44358      releasePage(pCur->apPage[pCur->iPage--]);
44359    }
44360    rc = balance(pCur);
44361  }
44362
44363  if( rc==SQLITE_OK ){
44364    moveToRoot(pCur);
44365  }
44366  return rc;
44367}
44368
44369/*
44370** Create a new BTree table.  Write into *piTable the page
44371** number for the root page of the new table.
44372**
44373** The type of type is determined by the flags parameter.  Only the
44374** following values of flags are currently in use.  Other values for
44375** flags might not work:
44376**
44377**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
44378**     BTREE_ZERODATA                  Used for SQL indices
44379*/
44380static int btreeCreateTable(Btree *p, int *piTable, int flags){
44381  BtShared *pBt = p->pBt;
44382  MemPage *pRoot;
44383  Pgno pgnoRoot;
44384  int rc;
44385
44386  assert( sqlite3BtreeHoldsMutex(p) );
44387  assert( pBt->inTransaction==TRANS_WRITE );
44388  assert( !pBt->readOnly );
44389
44390#ifdef SQLITE_OMIT_AUTOVACUUM
44391  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
44392  if( rc ){
44393    return rc;
44394  }
44395#else
44396  if( pBt->autoVacuum ){
44397    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
44398    MemPage *pPageMove; /* The page to move to. */
44399
44400    /* Creating a new table may probably require moving an existing database
44401    ** to make room for the new tables root page. In case this page turns
44402    ** out to be an overflow page, delete all overflow page-map caches
44403    ** held by open cursors.
44404    */
44405    invalidateAllOverflowCache(pBt);
44406
44407    /* Read the value of meta[3] from the database to determine where the
44408    ** root page of the new table should go. meta[3] is the largest root-page
44409    ** created so far, so the new root-page is (meta[3]+1).
44410    */
44411    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
44412    pgnoRoot++;
44413
44414    /* The new root-page may not be allocated on a pointer-map page, or the
44415    ** PENDING_BYTE page.
44416    */
44417    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
44418        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
44419      pgnoRoot++;
44420    }
44421    assert( pgnoRoot>=3 );
44422
44423    /* Allocate a page. The page that currently resides at pgnoRoot will
44424    ** be moved to the allocated page (unless the allocated page happens
44425    ** to reside at pgnoRoot).
44426    */
44427    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
44428    if( rc!=SQLITE_OK ){
44429      return rc;
44430    }
44431
44432    if( pgnoMove!=pgnoRoot ){
44433      /* pgnoRoot is the page that will be used for the root-page of
44434      ** the new table (assuming an error did not occur). But we were
44435      ** allocated pgnoMove. If required (i.e. if it was not allocated
44436      ** by extending the file), the current page at position pgnoMove
44437      ** is already journaled.
44438      */
44439      u8 eType = 0;
44440      Pgno iPtrPage = 0;
44441
44442      releasePage(pPageMove);
44443
44444      /* Move the page currently at pgnoRoot to pgnoMove. */
44445      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
44446      if( rc!=SQLITE_OK ){
44447        return rc;
44448      }
44449      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
44450      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
44451        rc = SQLITE_CORRUPT_BKPT(BTREE_CREATE_TABLE_CORRUPTION); // Android Change
44452      }
44453      if( rc!=SQLITE_OK ){
44454        releasePage(pRoot);
44455        return rc;
44456      }
44457      assert( eType!=PTRMAP_ROOTPAGE );
44458      assert( eType!=PTRMAP_FREEPAGE );
44459      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
44460      releasePage(pRoot);
44461
44462      /* Obtain the page at pgnoRoot */
44463      if( rc!=SQLITE_OK ){
44464        return rc;
44465      }
44466      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
44467      if( rc!=SQLITE_OK ){
44468        return rc;
44469      }
44470      rc = sqlite3PagerWrite(pRoot->pDbPage);
44471      if( rc!=SQLITE_OK ){
44472        releasePage(pRoot);
44473        return rc;
44474      }
44475    }else{
44476      pRoot = pPageMove;
44477    }
44478
44479    /* Update the pointer-map and meta-data with the new root-page number. */
44480    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
44481    if( rc ){
44482      releasePage(pRoot);
44483      return rc;
44484    }
44485    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
44486    if( rc ){
44487      releasePage(pRoot);
44488      return rc;
44489    }
44490
44491  }else{
44492    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
44493    if( rc ) return rc;
44494  }
44495#endif
44496  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
44497  zeroPage(pRoot, flags | PTF_LEAF);
44498  sqlite3PagerUnref(pRoot->pDbPage);
44499  *piTable = (int)pgnoRoot;
44500  return SQLITE_OK;
44501}
44502SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
44503  int rc;
44504  sqlite3BtreeEnter(p);
44505  rc = btreeCreateTable(p, piTable, flags);
44506  sqlite3BtreeLeave(p);
44507  return rc;
44508}
44509
44510/*
44511** Erase the given database page and all its children.  Return
44512** the page to the freelist.
44513*/
44514static int clearDatabasePage(
44515  BtShared *pBt,           /* The BTree that contains the table */
44516  Pgno pgno,               /* Page number to clear */
44517  int freePageFlag,        /* Deallocate page if true */
44518  int *pnChange            /* Add number of Cells freed to this counter */
44519){
44520  MemPage *pPage;
44521  int rc;
44522  unsigned char *pCell;
44523  int i;
44524
44525  assert( sqlite3_mutex_held(pBt->mutex) );
44526  if( pgno>pagerPagecount(pBt) ){
44527    return SQLITE_CORRUPT_BKPT(CLEAR_DB_PAGE_CORRUPTION); // Android Change
44528  }
44529
44530  rc = getAndInitPage(pBt, pgno, &pPage);
44531  if( rc ) return rc;
44532  for(i=0; i<pPage->nCell; i++){
44533    pCell = findCell(pPage, i);
44534    if( !pPage->leaf ){
44535      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
44536      if( rc ) goto cleardatabasepage_out;
44537    }
44538    rc = clearCell(pPage, pCell);
44539    if( rc ) goto cleardatabasepage_out;
44540  }
44541  if( !pPage->leaf ){
44542    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
44543    if( rc ) goto cleardatabasepage_out;
44544  }else if( pnChange ){
44545    assert( pPage->intKey );
44546    *pnChange += pPage->nCell;
44547  }
44548  if( freePageFlag ){
44549    freePage(pPage, &rc);
44550  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
44551    zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
44552  }
44553
44554cleardatabasepage_out:
44555  releasePage(pPage);
44556  return rc;
44557}
44558
44559/*
44560** Delete all information from a single table in the database.  iTable is
44561** the page number of the root of the table.  After this routine returns,
44562** the root page is empty, but still exists.
44563**
44564** This routine will fail with SQLITE_LOCKED if there are any open
44565** read cursors on the table.  Open write cursors are moved to the
44566** root of the table.
44567**
44568** If pnChange is not NULL, then table iTable must be an intkey table. The
44569** integer value pointed to by pnChange is incremented by the number of
44570** entries in the table.
44571*/
44572SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
44573  int rc;
44574  BtShared *pBt = p->pBt;
44575  sqlite3BtreeEnter(p);
44576  assert( p->inTrans==TRANS_WRITE );
44577
44578  /* Invalidate all incrblob cursors open on table iTable (assuming iTable
44579  ** is the root of a table b-tree - if it is not, the following call is
44580  ** a no-op).  */
44581  invalidateIncrblobCursors(p, 0, 1);
44582
44583  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
44584  if( SQLITE_OK==rc ){
44585    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
44586  }
44587  sqlite3BtreeLeave(p);
44588  return rc;
44589}
44590
44591/*
44592** Erase all information in a table and add the root of the table to
44593** the freelist.  Except, the root of the principle table (the one on
44594** page 1) is never added to the freelist.
44595**
44596** This routine will fail with SQLITE_LOCKED if there are any open
44597** cursors on the table.
44598**
44599** If AUTOVACUUM is enabled and the page at iTable is not the last
44600** root page in the database file, then the last root page
44601** in the database file is moved into the slot formerly occupied by
44602** iTable and that last slot formerly occupied by the last root page
44603** is added to the freelist instead of iTable.  In this say, all
44604** root pages are kept at the beginning of the database file, which
44605** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
44606** page number that used to be the last root page in the file before
44607** the move.  If no page gets moved, *piMoved is set to 0.
44608** The last root page is recorded in meta[3] and the value of
44609** meta[3] is updated by this procedure.
44610*/
44611static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
44612  int rc;
44613  MemPage *pPage = 0;
44614  BtShared *pBt = p->pBt;
44615
44616  assert( sqlite3BtreeHoldsMutex(p) );
44617  assert( p->inTrans==TRANS_WRITE );
44618
44619  /* It is illegal to drop a table if any cursors are open on the
44620  ** database. This is because in auto-vacuum mode the backend may
44621  ** need to move another root-page to fill a gap left by the deleted
44622  ** root page. If an open cursor was using this page a problem would
44623  ** occur.
44624  **
44625  ** This error is caught long before control reaches this point.
44626  */
44627  if( NEVER(pBt->pCursor) ){
44628    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
44629    return SQLITE_LOCKED_SHAREDCACHE;
44630  }
44631
44632  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
44633  if( rc ) return rc;
44634  rc = sqlite3BtreeClearTable(p, iTable, 0);
44635  if( rc ){
44636    releasePage(pPage);
44637    return rc;
44638  }
44639
44640  *piMoved = 0;
44641
44642  if( iTable>1 ){
44643#ifdef SQLITE_OMIT_AUTOVACUUM
44644    freePage(pPage, &rc);
44645    releasePage(pPage);
44646#else
44647    if( pBt->autoVacuum ){
44648      Pgno maxRootPgno;
44649      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
44650
44651      if( iTable==maxRootPgno ){
44652        /* If the table being dropped is the table with the largest root-page
44653        ** number in the database, put the root page on the free list.
44654        */
44655        freePage(pPage, &rc);
44656        releasePage(pPage);
44657        if( rc!=SQLITE_OK ){
44658          return rc;
44659        }
44660      }else{
44661        /* The table being dropped does not have the largest root-page
44662        ** number in the database. So move the page that does into the
44663        ** gap left by the deleted root-page.
44664        */
44665        MemPage *pMove;
44666        releasePage(pPage);
44667        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
44668        if( rc!=SQLITE_OK ){
44669          return rc;
44670        }
44671        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
44672        releasePage(pMove);
44673        if( rc!=SQLITE_OK ){
44674          return rc;
44675        }
44676        pMove = 0;
44677        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
44678        freePage(pMove, &rc);
44679        releasePage(pMove);
44680        if( rc!=SQLITE_OK ){
44681          return rc;
44682        }
44683        *piMoved = maxRootPgno;
44684      }
44685
44686      /* Set the new 'max-root-page' value in the database header. This
44687      ** is the old value less one, less one more if that happens to
44688      ** be a root-page number, less one again if that is the
44689      ** PENDING_BYTE_PAGE.
44690      */
44691      maxRootPgno--;
44692      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
44693             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
44694        maxRootPgno--;
44695      }
44696      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
44697
44698      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
44699    }else{
44700      freePage(pPage, &rc);
44701      releasePage(pPage);
44702    }
44703#endif
44704  }else{
44705    /* If sqlite3BtreeDropTable was called on page 1.
44706    ** This really never should happen except in a corrupt
44707    ** database.
44708    */
44709    zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
44710    releasePage(pPage);
44711  }
44712  return rc;
44713}
44714SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
44715  int rc;
44716  sqlite3BtreeEnter(p);
44717  rc = btreeDropTable(p, iTable, piMoved);
44718  sqlite3BtreeLeave(p);
44719  return rc;
44720}
44721
44722
44723/*
44724** This function may only be called if the b-tree connection already
44725** has a read or write transaction open on the database.
44726**
44727** Read the meta-information out of a database file.  Meta[0]
44728** is the number of free pages currently in the database.  Meta[1]
44729** through meta[15] are available for use by higher layers.  Meta[0]
44730** is read-only, the others are read/write.
44731**
44732** The schema layer numbers meta values differently.  At the schema
44733** layer (and the SetCookie and ReadCookie opcodes) the number of
44734** free pages is not visible.  So Cookie[0] is the same as Meta[1].
44735*/
44736SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
44737  BtShared *pBt = p->pBt;
44738
44739  sqlite3BtreeEnter(p);
44740  assert( p->inTrans>TRANS_NONE );
44741  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
44742  assert( pBt->pPage1 );
44743  assert( idx>=0 && idx<=15 );
44744
44745  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
44746
44747  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
44748  ** database, mark the database as read-only.  */
44749#ifdef SQLITE_OMIT_AUTOVACUUM
44750  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
44751#endif
44752
44753  sqlite3BtreeLeave(p);
44754}
44755
44756/*
44757** Write meta-information back into the database.  Meta[0] is
44758** read-only and may not be written.
44759*/
44760SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
44761  BtShared *pBt = p->pBt;
44762  unsigned char *pP1;
44763  int rc;
44764  assert( idx>=1 && idx<=15 );
44765  sqlite3BtreeEnter(p);
44766  assert( p->inTrans==TRANS_WRITE );
44767  assert( pBt->pPage1!=0 );
44768  pP1 = pBt->pPage1->aData;
44769  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
44770  if( rc==SQLITE_OK ){
44771    put4byte(&pP1[36 + idx*4], iMeta);
44772#ifndef SQLITE_OMIT_AUTOVACUUM
44773    if( idx==BTREE_INCR_VACUUM ){
44774      assert( pBt->autoVacuum || iMeta==0 );
44775      assert( iMeta==0 || iMeta==1 );
44776      pBt->incrVacuum = (u8)iMeta;
44777    }
44778#endif
44779  }
44780  sqlite3BtreeLeave(p);
44781  return rc;
44782}
44783
44784#ifndef SQLITE_OMIT_BTREECOUNT
44785/*
44786** The first argument, pCur, is a cursor opened on some b-tree. Count the
44787** number of entries in the b-tree and write the result to *pnEntry.
44788**
44789** SQLITE_OK is returned if the operation is successfully executed.
44790** Otherwise, if an error is encountered (i.e. an IO error or database
44791** corruption) an SQLite error code is returned.
44792*/
44793SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
44794  i64 nEntry = 0;                      /* Value to return in *pnEntry */
44795  int rc;                              /* Return code */
44796  rc = moveToRoot(pCur);
44797
44798  /* Unless an error occurs, the following loop runs one iteration for each
44799  ** page in the B-Tree structure (not including overflow pages).
44800  */
44801  while( rc==SQLITE_OK ){
44802    int iIdx;                          /* Index of child node in parent */
44803    MemPage *pPage;                    /* Current page of the b-tree */
44804
44805    /* If this is a leaf page or the tree is not an int-key tree, then
44806    ** this page contains countable entries. Increment the entry counter
44807    ** accordingly.
44808    */
44809    pPage = pCur->apPage[pCur->iPage];
44810    if( pPage->leaf || !pPage->intKey ){
44811      nEntry += pPage->nCell;
44812    }
44813
44814    /* pPage is a leaf node. This loop navigates the cursor so that it
44815    ** points to the first interior cell that it points to the parent of
44816    ** the next page in the tree that has not yet been visited. The
44817    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
44818    ** of the page, or to the number of cells in the page if the next page
44819    ** to visit is the right-child of its parent.
44820    **
44821    ** If all pages in the tree have been visited, return SQLITE_OK to the
44822    ** caller.
44823    */
44824    if( pPage->leaf ){
44825      do {
44826        if( pCur->iPage==0 ){
44827          /* All pages of the b-tree have been visited. Return successfully. */
44828          *pnEntry = nEntry;
44829          return SQLITE_OK;
44830        }
44831        moveToParent(pCur);
44832      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
44833
44834      pCur->aiIdx[pCur->iPage]++;
44835      pPage = pCur->apPage[pCur->iPage];
44836    }
44837
44838    /* Descend to the child node of the cell that the cursor currently
44839    ** points at. This is the right-child if (iIdx==pPage->nCell).
44840    */
44841    iIdx = pCur->aiIdx[pCur->iPage];
44842    if( iIdx==pPage->nCell ){
44843      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
44844    }else{
44845      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
44846    }
44847  }
44848
44849  /* An error has occurred. Return an error code. */
44850  return rc;
44851}
44852#endif
44853
44854/*
44855** Return the pager associated with a BTree.  This routine is used for
44856** testing and debugging only.
44857*/
44858SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
44859  return p->pBt->pPager;
44860}
44861
44862#ifndef SQLITE_OMIT_INTEGRITY_CHECK
44863/*
44864** Append a message to the error message string.
44865*/
44866static void checkAppendMsg(
44867  IntegrityCk *pCheck,
44868  char *zMsg1,
44869  const char *zFormat,
44870  ...
44871){
44872  va_list ap;
44873  if( !pCheck->mxErr ) return;
44874  pCheck->mxErr--;
44875  pCheck->nErr++;
44876  va_start(ap, zFormat);
44877  if( pCheck->errMsg.nChar ){
44878    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
44879  }
44880  if( zMsg1 ){
44881    sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
44882  }
44883  sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
44884  va_end(ap);
44885  if( pCheck->errMsg.mallocFailed ){
44886    pCheck->mallocFailed = 1;
44887  }
44888}
44889#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
44890
44891#ifndef SQLITE_OMIT_INTEGRITY_CHECK
44892/*
44893** Add 1 to the reference count for page iPage.  If this is the second
44894** reference to the page, add an error message to pCheck->zErrMsg.
44895** Return 1 if there are 2 ore more references to the page and 0 if
44896** if this is the first reference to the page.
44897**
44898** Also check that the page number is in bounds.
44899*/
44900static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
44901  if( iPage==0 ) return 1;
44902  if( iPage>pCheck->nPage ){
44903    checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
44904    return 1;
44905  }
44906  if( pCheck->anRef[iPage]==1 ){
44907    checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
44908    return 1;
44909  }
44910  return  (pCheck->anRef[iPage]++)>1;
44911}
44912
44913#ifndef SQLITE_OMIT_AUTOVACUUM
44914/*
44915** Check that the entry in the pointer-map for page iChild maps to
44916** page iParent, pointer type ptrType. If not, append an error message
44917** to pCheck.
44918*/
44919static void checkPtrmap(
44920  IntegrityCk *pCheck,   /* Integrity check context */
44921  Pgno iChild,           /* Child page number */
44922  u8 eType,              /* Expected pointer map type */
44923  Pgno iParent,          /* Expected pointer map parent page number */
44924  char *zContext         /* Context description (used for error msg) */
44925){
44926  int rc;
44927  u8 ePtrmapType;
44928  Pgno iPtrmapParent;
44929
44930  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
44931  if( rc!=SQLITE_OK ){
44932    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
44933    checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
44934    return;
44935  }
44936
44937  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
44938    checkAppendMsg(pCheck, zContext,
44939      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
44940      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
44941  }
44942}
44943#endif
44944
44945/*
44946** Check the integrity of the freelist or of an overflow page list.
44947** Verify that the number of pages on the list is N.
44948*/
44949static void checkList(
44950  IntegrityCk *pCheck,  /* Integrity checking context */
44951  int isFreeList,       /* True for a freelist.  False for overflow page list */
44952  int iPage,            /* Page number for first page in the list */
44953  int N,                /* Expected number of pages in the list */
44954  char *zContext        /* Context for error messages */
44955){
44956  int i;
44957  int expected = N;
44958  int iFirst = iPage;
44959  while( N-- > 0 && pCheck->mxErr ){
44960    DbPage *pOvflPage;
44961    unsigned char *pOvflData;
44962    if( iPage<1 ){
44963      checkAppendMsg(pCheck, zContext,
44964         "%d of %d pages missing from overflow list starting at %d",
44965          N+1, expected, iFirst);
44966      break;
44967    }
44968    if( checkRef(pCheck, iPage, zContext) ) break;
44969    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
44970      checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
44971      break;
44972    }
44973    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
44974    if( isFreeList ){
44975      int n = get4byte(&pOvflData[4]);
44976#ifndef SQLITE_OMIT_AUTOVACUUM
44977      if( pCheck->pBt->autoVacuum ){
44978        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
44979      }
44980#endif
44981      if( n>pCheck->pBt->usableSize/4-2 ){
44982        checkAppendMsg(pCheck, zContext,
44983           "freelist leaf count too big on page %d", iPage);
44984        N--;
44985      }else{
44986        for(i=0; i<n; i++){
44987          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
44988#ifndef SQLITE_OMIT_AUTOVACUUM
44989          if( pCheck->pBt->autoVacuum ){
44990            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
44991          }
44992#endif
44993          checkRef(pCheck, iFreePage, zContext);
44994        }
44995        N -= n;
44996      }
44997    }
44998#ifndef SQLITE_OMIT_AUTOVACUUM
44999    else{
45000      /* If this database supports auto-vacuum and iPage is not the last
45001      ** page in this overflow list, check that the pointer-map entry for
45002      ** the following page matches iPage.
45003      */
45004      if( pCheck->pBt->autoVacuum && N>0 ){
45005        i = get4byte(pOvflData);
45006        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
45007      }
45008    }
45009#endif
45010    iPage = get4byte(pOvflData);
45011    sqlite3PagerUnref(pOvflPage);
45012  }
45013}
45014#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45015
45016#ifndef SQLITE_OMIT_INTEGRITY_CHECK
45017/*
45018** Do various sanity checks on a single page of a tree.  Return
45019** the tree depth.  Root pages return 0.  Parents of root pages
45020** return 1, and so forth.
45021**
45022** These checks are done:
45023**
45024**      1.  Make sure that cells and freeblocks do not overlap
45025**          but combine to completely cover the page.
45026**  NO  2.  Make sure cell keys are in order.
45027**  NO  3.  Make sure no key is less than or equal to zLowerBound.
45028**  NO  4.  Make sure no key is greater than or equal to zUpperBound.
45029**      5.  Check the integrity of overflow pages.
45030**      6.  Recursively call checkTreePage on all children.
45031**      7.  Verify that the depth of all children is the same.
45032**      8.  Make sure this page is at least 33% full or else it is
45033**          the root of the tree.
45034*/
45035static int checkTreePage(
45036  IntegrityCk *pCheck,  /* Context for the sanity check */
45037  int iPage,            /* Page number of the page to check */
45038  char *zParentContext  /* Parent context */
45039){
45040  MemPage *pPage;
45041  int i, rc, depth, d2, pgno, cnt;
45042  int hdr, cellStart;
45043  int nCell;
45044  u8 *data;
45045  BtShared *pBt;
45046  int usableSize;
45047  char zContext[100];
45048  char *hit = 0;
45049
45050  sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
45051
45052  /* Check that the page exists
45053  */
45054  pBt = pCheck->pBt;
45055  usableSize = pBt->usableSize;
45056  if( iPage==0 ) return 0;
45057  if( checkRef(pCheck, iPage, zParentContext) ) return 0;
45058  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
45059    checkAppendMsg(pCheck, zContext,
45060       "unable to get the page. error code=%d", rc);
45061    return 0;
45062  }
45063
45064  /* Clear MemPage.isInit to make sure the corruption detection code in
45065  ** btreeInitPage() is executed.  */
45066  pPage->isInit = 0;
45067  if( (rc = btreeInitPage(pPage))!=0 ){
45068    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
45069    checkAppendMsg(pCheck, zContext,
45070                   "btreeInitPage() returns error code %d", rc);
45071    releasePage(pPage);
45072    return 0;
45073  }
45074
45075  /* Check out all the cells.
45076  */
45077  depth = 0;
45078  for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
45079    u8 *pCell;
45080    u32 sz;
45081    CellInfo info;
45082
45083    /* Check payload overflow pages
45084    */
45085    sqlite3_snprintf(sizeof(zContext), zContext,
45086             "On tree page %d cell %d: ", iPage, i);
45087    pCell = findCell(pPage,i);
45088    btreeParseCellPtr(pPage, pCell, &info);
45089    sz = info.nData;
45090    if( !pPage->intKey ) sz += (int)info.nKey;
45091    assert( sz==info.nPayload );
45092    if( (sz>info.nLocal)
45093     && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
45094    ){
45095      int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
45096      Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
45097#ifndef SQLITE_OMIT_AUTOVACUUM
45098      if( pBt->autoVacuum ){
45099        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
45100      }
45101#endif
45102      checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
45103    }
45104
45105    /* Check sanity of left child page.
45106    */
45107    if( !pPage->leaf ){
45108      pgno = get4byte(pCell);
45109#ifndef SQLITE_OMIT_AUTOVACUUM
45110      if( pBt->autoVacuum ){
45111        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
45112      }
45113#endif
45114      d2 = checkTreePage(pCheck, pgno, zContext);
45115      if( i>0 && d2!=depth ){
45116        checkAppendMsg(pCheck, zContext, "Child page depth differs");
45117      }
45118      depth = d2;
45119    }
45120  }
45121  if( !pPage->leaf ){
45122    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
45123    sqlite3_snprintf(sizeof(zContext), zContext,
45124                     "On page %d at right child: ", iPage);
45125#ifndef SQLITE_OMIT_AUTOVACUUM
45126    if( pBt->autoVacuum ){
45127      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
45128    }
45129#endif
45130    checkTreePage(pCheck, pgno, zContext);
45131  }
45132
45133  /* Check for complete coverage of the page
45134  */
45135  data = pPage->aData;
45136  hdr = pPage->hdrOffset;
45137  hit = sqlite3PageMalloc( pBt->pageSize );
45138  if( hit==0 ){
45139    pCheck->mallocFailed = 1;
45140  }else{
45141    u16 contentOffset = get2byte(&data[hdr+5]);
45142    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
45143    memset(hit+contentOffset, 0, usableSize-contentOffset);
45144    memset(hit, 1, contentOffset);
45145    nCell = get2byte(&data[hdr+3]);
45146    cellStart = hdr + 12 - 4*pPage->leaf;
45147    for(i=0; i<nCell; i++){
45148      int pc = get2byte(&data[cellStart+i*2]);
45149      u16 size = 1024;
45150      int j;
45151      if( pc<=usableSize-4 ){
45152        size = cellSizePtr(pPage, &data[pc]);
45153      }
45154      if( (pc+size-1)>=usableSize ){
45155        checkAppendMsg(pCheck, 0,
45156            "Corruption detected in cell %d on page %d",i,iPage,0);
45157      }else{
45158        for(j=pc+size-1; j>=pc; j--) hit[j]++;
45159      }
45160    }
45161    i = get2byte(&data[hdr+1]);
45162    while( i>0 ){
45163      int size, j;
45164      assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
45165      size = get2byte(&data[i+2]);
45166      assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
45167      for(j=i+size-1; j>=i; j--) hit[j]++;
45168      j = get2byte(&data[i]);
45169      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
45170      assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
45171      i = j;
45172    }
45173    for(i=cnt=0; i<usableSize; i++){
45174      if( hit[i]==0 ){
45175        cnt++;
45176      }else if( hit[i]>1 ){
45177        checkAppendMsg(pCheck, 0,
45178          "Multiple uses for byte %d of page %d", i, iPage);
45179        break;
45180      }
45181    }
45182    if( cnt!=data[hdr+7] ){
45183      checkAppendMsg(pCheck, 0,
45184          "Fragmentation of %d bytes reported as %d on page %d",
45185          cnt, data[hdr+7], iPage);
45186    }
45187  }
45188  sqlite3PageFree(hit);
45189  releasePage(pPage);
45190  return depth+1;
45191}
45192#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45193
45194#ifndef SQLITE_OMIT_INTEGRITY_CHECK
45195/*
45196** This routine does a complete check of the given BTree file.  aRoot[] is
45197** an array of pages numbers were each page number is the root page of
45198** a table.  nRoot is the number of entries in aRoot.
45199**
45200** A read-only or read-write transaction must be opened before calling
45201** this function.
45202**
45203** Write the number of error seen in *pnErr.  Except for some memory
45204** allocation errors,  an error message held in memory obtained from
45205** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
45206** returned.  If a memory allocation error occurs, NULL is returned.
45207*/
45208SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
45209  Btree *p,     /* The btree to be checked */
45210  int *aRoot,   /* An array of root pages numbers for individual trees */
45211  int nRoot,    /* Number of entries in aRoot[] */
45212  int mxErr,    /* Stop reporting errors after this many */
45213  int *pnErr    /* Write number of errors seen to this variable */
45214){
45215  Pgno i;
45216  int nRef;
45217  IntegrityCk sCheck;
45218  BtShared *pBt = p->pBt;
45219  char zErr[100];
45220
45221  sqlite3BtreeEnter(p);
45222  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
45223  nRef = sqlite3PagerRefcount(pBt->pPager);
45224  sCheck.pBt = pBt;
45225  sCheck.pPager = pBt->pPager;
45226  sCheck.nPage = pagerPagecount(sCheck.pBt);
45227  sCheck.mxErr = mxErr;
45228  sCheck.nErr = 0;
45229  sCheck.mallocFailed = 0;
45230  *pnErr = 0;
45231  if( sCheck.nPage==0 ){
45232    sqlite3BtreeLeave(p);
45233    return 0;
45234  }
45235  sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
45236  if( !sCheck.anRef ){
45237    *pnErr = 1;
45238    sqlite3BtreeLeave(p);
45239    return 0;
45240  }
45241  for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
45242  i = PENDING_BYTE_PAGE(pBt);
45243  if( i<=sCheck.nPage ){
45244    sCheck.anRef[i] = 1;
45245  }
45246  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
45247
45248  /* Check the integrity of the freelist
45249  */
45250  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
45251            get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
45252
45253  /* Check all the tables.
45254  */
45255  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
45256    if( aRoot[i]==0 ) continue;
45257#ifndef SQLITE_OMIT_AUTOVACUUM
45258    if( pBt->autoVacuum && aRoot[i]>1 ){
45259      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
45260    }
45261#endif
45262    checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
45263  }
45264
45265  /* Make sure every page in the file is referenced
45266  */
45267  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
45268#ifdef SQLITE_OMIT_AUTOVACUUM
45269    if( sCheck.anRef[i]==0 ){
45270      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
45271    }
45272#else
45273    /* If the database supports auto-vacuum, make sure no tables contain
45274    ** references to pointer-map pages.
45275    */
45276    if( sCheck.anRef[i]==0 &&
45277       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
45278      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
45279    }
45280    if( sCheck.anRef[i]!=0 &&
45281       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
45282      checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
45283    }
45284#endif
45285  }
45286
45287  /* Make sure this analysis did not leave any unref() pages.
45288  ** This is an internal consistency check; an integrity check
45289  ** of the integrity check.
45290  */
45291  if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
45292    checkAppendMsg(&sCheck, 0,
45293      "Outstanding page count goes from %d to %d during this analysis",
45294      nRef, sqlite3PagerRefcount(pBt->pPager)
45295    );
45296  }
45297
45298  /* Clean  up and report errors.
45299  */
45300  sqlite3BtreeLeave(p);
45301  sqlite3_free(sCheck.anRef);
45302  if( sCheck.mallocFailed ){
45303    sqlite3StrAccumReset(&sCheck.errMsg);
45304    *pnErr = sCheck.nErr+1;
45305    return 0;
45306  }
45307  *pnErr = sCheck.nErr;
45308  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
45309  return sqlite3StrAccumFinish(&sCheck.errMsg);
45310}
45311#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45312
45313/*
45314** Return the full pathname of the underlying database file.
45315**
45316** The pager filename is invariant as long as the pager is
45317** open so it is safe to access without the BtShared mutex.
45318*/
45319SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
45320  assert( p->pBt->pPager!=0 );
45321  return sqlite3PagerFilename(p->pBt->pPager);
45322}
45323
45324/*
45325** Return the pathname of the journal file for this database. The return
45326** value of this routine is the same regardless of whether the journal file
45327** has been created or not.
45328**
45329** The pager journal filename is invariant as long as the pager is
45330** open so it is safe to access without the BtShared mutex.
45331*/
45332SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
45333  assert( p->pBt->pPager!=0 );
45334  return sqlite3PagerJournalname(p->pBt->pPager);
45335}
45336
45337/*
45338** Return non-zero if a transaction is active.
45339*/
45340SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
45341  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
45342  return (p && (p->inTrans==TRANS_WRITE));
45343}
45344
45345/*
45346** Return non-zero if a read (or write) transaction is active.
45347*/
45348SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
45349  assert( p );
45350  assert( sqlite3_mutex_held(p->db->mutex) );
45351  return p->inTrans!=TRANS_NONE;
45352}
45353
45354SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
45355  assert( p );
45356  assert( sqlite3_mutex_held(p->db->mutex) );
45357  return p->nBackup!=0;
45358}
45359
45360/*
45361** This function returns a pointer to a blob of memory associated with
45362** a single shared-btree. The memory is used by client code for its own
45363** purposes (for example, to store a high-level schema associated with
45364** the shared-btree). The btree layer manages reference counting issues.
45365**
45366** The first time this is called on a shared-btree, nBytes bytes of memory
45367** are allocated, zeroed, and returned to the caller. For each subsequent
45368** call the nBytes parameter is ignored and a pointer to the same blob
45369** of memory returned.
45370**
45371** If the nBytes parameter is 0 and the blob of memory has not yet been
45372** allocated, a null pointer is returned. If the blob has already been
45373** allocated, it is returned as normal.
45374**
45375** Just before the shared-btree is closed, the function passed as the
45376** xFree argument when the memory allocation was made is invoked on the
45377** blob of allocated memory. This function should not call sqlite3_free()
45378** on the memory, the btree layer does that.
45379*/
45380SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
45381  BtShared *pBt = p->pBt;
45382  sqlite3BtreeEnter(p);
45383  if( !pBt->pSchema && nBytes ){
45384    pBt->pSchema = sqlite3MallocZero(nBytes);
45385    pBt->xFreeSchema = xFree;
45386  }
45387  sqlite3BtreeLeave(p);
45388  return pBt->pSchema;
45389}
45390
45391/*
45392** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
45393** btree as the argument handle holds an exclusive lock on the
45394** sqlite_master table. Otherwise SQLITE_OK.
45395*/
45396SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
45397  int rc;
45398  assert( sqlite3_mutex_held(p->db->mutex) );
45399  sqlite3BtreeEnter(p);
45400  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
45401  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
45402  sqlite3BtreeLeave(p);
45403  return rc;
45404}
45405
45406
45407#ifndef SQLITE_OMIT_SHARED_CACHE
45408/*
45409** Obtain a lock on the table whose root page is iTab.  The
45410** lock is a write lock if isWritelock is true or a read lock
45411** if it is false.
45412*/
45413SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
45414  int rc = SQLITE_OK;
45415  assert( p->inTrans!=TRANS_NONE );
45416  if( p->sharable ){
45417    u8 lockType = READ_LOCK + isWriteLock;
45418    assert( READ_LOCK+1==WRITE_LOCK );
45419    assert( isWriteLock==0 || isWriteLock==1 );
45420
45421    sqlite3BtreeEnter(p);
45422    rc = querySharedCacheTableLock(p, iTab, lockType);
45423    if( rc==SQLITE_OK ){
45424      rc = setSharedCacheTableLock(p, iTab, lockType);
45425    }
45426    sqlite3BtreeLeave(p);
45427  }
45428  return rc;
45429}
45430#endif
45431
45432#ifndef SQLITE_OMIT_INCRBLOB
45433/*
45434** Argument pCsr must be a cursor opened for writing on an
45435** INTKEY table currently pointing at a valid table entry.
45436** This function modifies the data stored as part of that entry.
45437**
45438** Only the data content may only be modified, it is not possible to
45439** change the length of the data stored. If this function is called with
45440** parameters that attempt to write past the end of the existing data,
45441** no modifications are made and SQLITE_CORRUPT is returned.
45442*/
45443SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
45444  int rc;
45445  assert( cursorHoldsMutex(pCsr) );
45446  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
45447  assert( pCsr->isIncrblobHandle );
45448
45449  rc = restoreCursorPosition(pCsr);
45450  if( rc!=SQLITE_OK ){
45451    return rc;
45452  }
45453  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
45454  if( pCsr->eState!=CURSOR_VALID ){
45455    return SQLITE_ABORT;
45456  }
45457
45458  /* Check some assumptions:
45459  **   (a) the cursor is open for writing,
45460  **   (b) there is a read/write transaction open,
45461  **   (c) the connection holds a write-lock on the table (if required),
45462  **   (d) there are no conflicting read-locks, and
45463  **   (e) the cursor points at a valid row of an intKey table.
45464  */
45465  if( !pCsr->wrFlag ){
45466    return SQLITE_READONLY;
45467  }
45468  assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
45469  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
45470  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
45471  assert( pCsr->apPage[pCsr->iPage]->intKey );
45472
45473  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
45474}
45475
45476/*
45477** Set a flag on this cursor to cache the locations of pages from the
45478** overflow list for the current row. This is used by cursors opened
45479** for incremental blob IO only.
45480**
45481** This function sets a flag only. The actual page location cache
45482** (stored in BtCursor.aOverflow[]) is allocated and used by function
45483** accessPayload() (the worker function for sqlite3BtreeData() and
45484** sqlite3BtreePutData()).
45485*/
45486SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
45487  assert( cursorHoldsMutex(pCur) );
45488  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
45489  assert(!pCur->isIncrblobHandle);
45490  assert(!pCur->aOverflow);
45491  pCur->isIncrblobHandle = 1;
45492}
45493#endif
45494
45495/************** End of btree.c ***********************************************/
45496/************** Begin file backup.c ******************************************/
45497/*
45498** 2009 January 28
45499**
45500** The author disclaims copyright to this source code.  In place of
45501** a legal notice, here is a blessing:
45502**
45503**    May you do good and not evil.
45504**    May you find forgiveness for yourself and forgive others.
45505**    May you share freely, never taking more than you give.
45506**
45507*************************************************************************
45508** This file contains the implementation of the sqlite3_backup_XXX()
45509** API functions and the related features.
45510*/
45511
45512/* Macro to find the minimum of two numeric values.
45513*/
45514#ifndef MIN
45515# define MIN(x,y) ((x)<(y)?(x):(y))
45516#endif
45517
45518/*
45519** Structure allocated for each backup operation.
45520*/
45521struct sqlite3_backup {
45522  sqlite3* pDestDb;        /* Destination database handle */
45523  Btree *pDest;            /* Destination b-tree file */
45524  u32 iDestSchema;         /* Original schema cookie in destination */
45525  int bDestLocked;         /* True once a write-transaction is open on pDest */
45526
45527  Pgno iNext;              /* Page number of the next source page to copy */
45528  sqlite3* pSrcDb;         /* Source database handle */
45529  Btree *pSrc;             /* Source b-tree file */
45530
45531  int rc;                  /* Backup process error code */
45532
45533  /* These two variables are set by every call to backup_step(). They are
45534  ** read by calls to backup_remaining() and backup_pagecount().
45535  */
45536  Pgno nRemaining;         /* Number of pages left to copy */
45537  Pgno nPagecount;         /* Total number of pages to copy */
45538
45539  int isAttached;          /* True once backup has been registered with pager */
45540  sqlite3_backup *pNext;   /* Next backup associated with source pager */
45541};
45542
45543/*
45544** THREAD SAFETY NOTES:
45545**
45546**   Once it has been created using backup_init(), a single sqlite3_backup
45547**   structure may be accessed via two groups of thread-safe entry points:
45548**
45549**     * Via the sqlite3_backup_XXX() API function backup_step() and
45550**       backup_finish(). Both these functions obtain the source database
45551**       handle mutex and the mutex associated with the source BtShared
45552**       structure, in that order.
45553**
45554**     * Via the BackupUpdate() and BackupRestart() functions, which are
45555**       invoked by the pager layer to report various state changes in
45556**       the page cache associated with the source database. The mutex
45557**       associated with the source database BtShared structure will always
45558**       be held when either of these functions are invoked.
45559**
45560**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
45561**   backup_pagecount() are not thread-safe functions. If they are called
45562**   while some other thread is calling backup_step() or backup_finish(),
45563**   the values returned may be invalid. There is no way for a call to
45564**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
45565**   or backup_pagecount().
45566**
45567**   Depending on the SQLite configuration, the database handles and/or
45568**   the Btree objects may have their own mutexes that require locking.
45569**   Non-sharable Btrees (in-memory databases for example), do not have
45570**   associated mutexes.
45571*/
45572
45573/*
45574** Return a pointer corresponding to database zDb (i.e. "main", "temp")
45575** in connection handle pDb. If such a database cannot be found, return
45576** a NULL pointer and write an error message to pErrorDb.
45577**
45578** If the "temp" database is requested, it may need to be opened by this
45579** function. If an error occurs while doing so, return 0 and write an
45580** error message to pErrorDb.
45581*/
45582static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
45583  int i = sqlite3FindDbName(pDb, zDb);
45584
45585  if( i==1 ){
45586    Parse *pParse;
45587    int rc = 0;
45588    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
45589    if( pParse==0 ){
45590      sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
45591      rc = SQLITE_NOMEM;
45592    }else{
45593      pParse->db = pDb;
45594      if( sqlite3OpenTempDatabase(pParse) ){
45595        sqlite3ErrorClear(pParse);
45596        sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
45597        rc = SQLITE_ERROR;
45598      }
45599      sqlite3StackFree(pErrorDb, pParse);
45600    }
45601    if( rc ){
45602      return 0;
45603    }
45604  }
45605
45606  if( i<0 ){
45607    sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
45608    return 0;
45609  }
45610
45611  return pDb->aDb[i].pBt;
45612}
45613
45614/*
45615** Create an sqlite3_backup process to copy the contents of zSrcDb from
45616** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
45617** a pointer to the new sqlite3_backup object.
45618**
45619** If an error occurs, NULL is returned and an error code and error message
45620** stored in database handle pDestDb.
45621*/
45622SQLITE_API sqlite3_backup *sqlite3_backup_init(
45623  sqlite3* pDestDb,                     /* Database to write to */
45624  const char *zDestDb,                  /* Name of database within pDestDb */
45625  sqlite3* pSrcDb,                      /* Database connection to read from */
45626  const char *zSrcDb                    /* Name of database within pSrcDb */
45627){
45628  sqlite3_backup *p;                    /* Value to return */
45629
45630  /* Lock the source database handle. The destination database
45631  ** handle is not locked in this routine, but it is locked in
45632  ** sqlite3_backup_step(). The user is required to ensure that no
45633  ** other thread accesses the destination handle for the duration
45634  ** of the backup operation.  Any attempt to use the destination
45635  ** database connection while a backup is in progress may cause
45636  ** a malfunction or a deadlock.
45637  */
45638  sqlite3_mutex_enter(pSrcDb->mutex);
45639  sqlite3_mutex_enter(pDestDb->mutex);
45640
45641  if( pSrcDb==pDestDb ){
45642    sqlite3Error(
45643        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
45644    );
45645    p = 0;
45646  }else {
45647    /* Allocate space for a new sqlite3_backup object */
45648    p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
45649    if( !p ){
45650      sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
45651    }
45652  }
45653
45654  /* If the allocation succeeded, populate the new object. */
45655  if( p ){
45656    memset(p, 0, sizeof(sqlite3_backup));
45657    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
45658    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
45659    p->pDestDb = pDestDb;
45660    p->pSrcDb = pSrcDb;
45661    p->iNext = 1;
45662    p->isAttached = 0;
45663
45664    if( 0==p->pSrc || 0==p->pDest ){
45665      /* One (or both) of the named databases did not exist. An error has
45666      ** already been written into the pDestDb handle. All that is left
45667      ** to do here is free the sqlite3_backup structure.
45668      */
45669      sqlite3_free(p);
45670      p = 0;
45671    }
45672  }
45673  if( p ){
45674    p->pSrc->nBackup++;
45675  }
45676
45677  sqlite3_mutex_leave(pDestDb->mutex);
45678  sqlite3_mutex_leave(pSrcDb->mutex);
45679  return p;
45680}
45681
45682/*
45683** Argument rc is an SQLite error code. Return true if this error is
45684** considered fatal if encountered during a backup operation. All errors
45685** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
45686*/
45687static int isFatalError(int rc){
45688  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
45689}
45690
45691/*
45692** Parameter zSrcData points to a buffer containing the data for
45693** page iSrcPg from the source database. Copy this data into the
45694** destination database.
45695*/
45696static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
45697  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
45698  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
45699  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
45700  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
45701  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
45702
45703  int rc = SQLITE_OK;
45704  i64 iOff;
45705
45706  assert( p->bDestLocked );
45707  assert( !isFatalError(p->rc) );
45708  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
45709  assert( zSrcData );
45710
45711  /* Catch the case where the destination is an in-memory database and the
45712  ** page sizes of the source and destination differ.
45713  */
45714  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(sqlite3BtreePager(p->pDest)) ){
45715    rc = SQLITE_READONLY;
45716  }
45717
45718  /* This loop runs once for each destination page spanned by the source
45719  ** page. For each iteration, variable iOff is set to the byte offset
45720  ** of the destination page.
45721  */
45722  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
45723    DbPage *pDestPg = 0;
45724    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
45725    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
45726    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
45727     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
45728    ){
45729      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
45730      u8 *zDestData = sqlite3PagerGetData(pDestPg);
45731      u8 *zOut = &zDestData[iOff%nDestPgsz];
45732
45733      /* Copy the data from the source page into the destination page.
45734      ** Then clear the Btree layer MemPage.isInit flag. Both this module
45735      ** and the pager code use this trick (clearing the first byte
45736      ** of the page 'extra' space to invalidate the Btree layers
45737      ** cached parse of the page). MemPage.isInit is marked
45738      ** "MUST BE FIRST" for this purpose.
45739      */
45740      memcpy(zOut, zIn, nCopy);
45741      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
45742    }
45743    sqlite3PagerUnref(pDestPg);
45744  }
45745
45746  return rc;
45747}
45748
45749/*
45750** If pFile is currently larger than iSize bytes, then truncate it to
45751** exactly iSize bytes. If pFile is not larger than iSize bytes, then
45752** this function is a no-op.
45753**
45754** Return SQLITE_OK if everything is successful, or an SQLite error
45755** code if an error occurs.
45756*/
45757static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
45758  i64 iCurrent;
45759  int rc = sqlite3OsFileSize(pFile, &iCurrent);
45760  if( rc==SQLITE_OK && iCurrent>iSize ){
45761    rc = sqlite3OsTruncate(pFile, iSize);
45762  }
45763  return rc;
45764}
45765
45766/*
45767** Register this backup object with the associated source pager for
45768** callbacks when pages are changed or the cache invalidated.
45769*/
45770static void attachBackupObject(sqlite3_backup *p){
45771  sqlite3_backup **pp;
45772  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
45773  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
45774  p->pNext = *pp;
45775  *pp = p;
45776  p->isAttached = 1;
45777}
45778
45779/*
45780** Copy nPage pages from the source b-tree to the destination.
45781*/
45782SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
45783  int rc;
45784
45785  sqlite3_mutex_enter(p->pSrcDb->mutex);
45786  sqlite3BtreeEnter(p->pSrc);
45787  if( p->pDestDb ){
45788    sqlite3_mutex_enter(p->pDestDb->mutex);
45789  }
45790
45791  rc = p->rc;
45792  if( !isFatalError(rc) ){
45793    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
45794    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
45795    int ii;                            /* Iterator variable */
45796    int nSrcPage = -1;                 /* Size of source db in pages */
45797    int bCloseTrans = 0;               /* True if src db requires unlocking */
45798
45799    /* If the source pager is currently in a write-transaction, return
45800    ** SQLITE_BUSY immediately.
45801    */
45802    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
45803      rc = SQLITE_BUSY;
45804    }else{
45805      rc = SQLITE_OK;
45806    }
45807
45808    /* Lock the destination database, if it is not locked already. */
45809    if( SQLITE_OK==rc && p->bDestLocked==0
45810     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
45811    ){
45812      p->bDestLocked = 1;
45813      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
45814    }
45815
45816    /* If there is no open read-transaction on the source database, open
45817    ** one now. If a transaction is opened here, then it will be closed
45818    ** before this function exits.
45819    */
45820    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
45821      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
45822      bCloseTrans = 1;
45823    }
45824
45825    /* Now that there is a read-lock on the source database, query the
45826    ** source pager for the number of pages in the database.
45827    */
45828    if( rc==SQLITE_OK ){
45829      rc = sqlite3PagerPagecount(pSrcPager, &nSrcPage);
45830    }
45831    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
45832      const Pgno iSrcPg = p->iNext;                 /* Source page number */
45833      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
45834        DbPage *pSrcPg;                             /* Source page object */
45835        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
45836        if( rc==SQLITE_OK ){
45837          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
45838          sqlite3PagerUnref(pSrcPg);
45839        }
45840      }
45841      p->iNext++;
45842    }
45843    if( rc==SQLITE_OK ){
45844      p->nPagecount = nSrcPage;
45845      p->nRemaining = nSrcPage+1-p->iNext;
45846      if( p->iNext>(Pgno)nSrcPage ){
45847        rc = SQLITE_DONE;
45848      }else if( !p->isAttached ){
45849        attachBackupObject(p);
45850      }
45851    }
45852
45853    /* Update the schema version field in the destination database. This
45854    ** is to make sure that the schema-version really does change in
45855    ** the case where the source and destination databases have the
45856    ** same schema version.
45857    */
45858    if( rc==SQLITE_DONE
45859     && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
45860    ){
45861      const int nSrcPagesize = sqlite3BtreeGetPageSize(p->pSrc);
45862      const int nDestPagesize = sqlite3BtreeGetPageSize(p->pDest);
45863      int nDestTruncate;
45864
45865      if( p->pDestDb ){
45866        sqlite3ResetInternalSchema(p->pDestDb, 0);
45867      }
45868
45869      /* Set nDestTruncate to the final number of pages in the destination
45870      ** database. The complication here is that the destination page
45871      ** size may be different to the source page size.
45872      **
45873      ** If the source page size is smaller than the destination page size,
45874      ** round up. In this case the call to sqlite3OsTruncate() below will
45875      ** fix the size of the file. However it is important to call
45876      ** sqlite3PagerTruncateImage() here so that any pages in the
45877      ** destination file that lie beyond the nDestTruncate page mark are
45878      ** journalled by PagerCommitPhaseOne() before they are destroyed
45879      ** by the file truncation.
45880      */
45881      if( nSrcPagesize<nDestPagesize ){
45882        int ratio = nDestPagesize/nSrcPagesize;
45883        nDestTruncate = (nSrcPage+ratio-1)/ratio;
45884        if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
45885          nDestTruncate--;
45886        }
45887      }else{
45888        nDestTruncate = nSrcPage * (nSrcPagesize/nDestPagesize);
45889      }
45890      sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
45891
45892      if( nSrcPagesize<nDestPagesize ){
45893        /* If the source page-size is smaller than the destination page-size,
45894        ** two extra things may need to happen:
45895        **
45896        **   * The destination may need to be truncated, and
45897        **
45898        **   * Data stored on the pages immediately following the
45899        **     pending-byte page in the source database may need to be
45900        **     copied into the destination database.
45901        */
45902        const i64 iSize = (i64)nSrcPagesize * (i64)nSrcPage;
45903        sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
45904
45905        assert( pFile );
45906        assert( (i64)nDestTruncate*(i64)nDestPagesize >= iSize || (
45907              nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
45908           && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+nDestPagesize
45909        ));
45910        if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
45911         && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
45912         && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
45913        ){
45914          i64 iOff;
45915          i64 iEnd = MIN(PENDING_BYTE + nDestPagesize, iSize);
45916          for(
45917            iOff=PENDING_BYTE+nSrcPagesize;
45918            rc==SQLITE_OK && iOff<iEnd;
45919            iOff+=nSrcPagesize
45920          ){
45921            PgHdr *pSrcPg = 0;
45922            const Pgno iSrcPg = (Pgno)((iOff/nSrcPagesize)+1);
45923            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
45924            if( rc==SQLITE_OK ){
45925              u8 *zData = sqlite3PagerGetData(pSrcPg);
45926              rc = sqlite3OsWrite(pFile, zData, nSrcPagesize, iOff);
45927            }
45928            sqlite3PagerUnref(pSrcPg);
45929          }
45930        }
45931      }else{
45932        rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
45933      }
45934
45935      /* Finish committing the transaction to the destination database. */
45936      if( SQLITE_OK==rc
45937       && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
45938      ){
45939        rc = SQLITE_DONE;
45940      }
45941    }
45942
45943    /* If bCloseTrans is true, then this function opened a read transaction
45944    ** on the source database. Close the read transaction here. There is
45945    ** no need to check the return values of the btree methods here, as
45946    ** "committing" a read-only transaction cannot fail.
45947    */
45948    if( bCloseTrans ){
45949      TESTONLY( int rc2 );
45950      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
45951      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
45952      assert( rc2==SQLITE_OK );
45953    }
45954
45955    p->rc = rc;
45956  }
45957  if( p->pDestDb ){
45958    sqlite3_mutex_leave(p->pDestDb->mutex);
45959  }
45960  sqlite3BtreeLeave(p->pSrc);
45961  sqlite3_mutex_leave(p->pSrcDb->mutex);
45962  return rc;
45963}
45964
45965/*
45966** Release all resources associated with an sqlite3_backup* handle.
45967*/
45968SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
45969  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
45970  sqlite3_mutex *mutex;                /* Mutex to protect source database */
45971  int rc;                              /* Value to return */
45972
45973  /* Enter the mutexes */
45974  if( p==0 ) return SQLITE_OK;
45975  sqlite3_mutex_enter(p->pSrcDb->mutex);
45976  sqlite3BtreeEnter(p->pSrc);
45977  mutex = p->pSrcDb->mutex;
45978  if( p->pDestDb ){
45979    sqlite3_mutex_enter(p->pDestDb->mutex);
45980  }
45981
45982  /* Detach this backup from the source pager. */
45983  if( p->pDestDb ){
45984    p->pSrc->nBackup--;
45985  }
45986  if( p->isAttached ){
45987    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
45988    while( *pp!=p ){
45989      pp = &(*pp)->pNext;
45990    }
45991    *pp = p->pNext;
45992  }
45993
45994  /* If a transaction is still open on the Btree, roll it back. */
45995  sqlite3BtreeRollback(p->pDest);
45996
45997  /* Set the error code of the destination database handle. */
45998  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
45999  sqlite3Error(p->pDestDb, rc, 0);
46000
46001  /* Exit the mutexes and free the backup context structure. */
46002  if( p->pDestDb ){
46003    sqlite3_mutex_leave(p->pDestDb->mutex);
46004  }
46005  sqlite3BtreeLeave(p->pSrc);
46006  if( p->pDestDb ){
46007    sqlite3_free(p);
46008  }
46009  sqlite3_mutex_leave(mutex);
46010  return rc;
46011}
46012
46013/*
46014** Return the number of pages still to be backed up as of the most recent
46015** call to sqlite3_backup_step().
46016*/
46017SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
46018  return p->nRemaining;
46019}
46020
46021/*
46022** Return the total number of pages in the source database as of the most
46023** recent call to sqlite3_backup_step().
46024*/
46025SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
46026  return p->nPagecount;
46027}
46028
46029/*
46030** This function is called after the contents of page iPage of the
46031** source database have been modified. If page iPage has already been
46032** copied into the destination database, then the data written to the
46033** destination is now invalidated. The destination copy of iPage needs
46034** to be updated with the new data before the backup operation is
46035** complete.
46036**
46037** It is assumed that the mutex associated with the BtShared object
46038** corresponding to the source database is held when this function is
46039** called.
46040*/
46041SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
46042  sqlite3_backup *p;                   /* Iterator variable */
46043  for(p=pBackup; p; p=p->pNext){
46044    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
46045    if( !isFatalError(p->rc) && iPage<p->iNext ){
46046      /* The backup process p has already copied page iPage. But now it
46047      ** has been modified by a transaction on the source pager. Copy
46048      ** the new data into the backup.
46049      */
46050      int rc = backupOnePage(p, iPage, aData);
46051      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
46052      if( rc!=SQLITE_OK ){
46053        p->rc = rc;
46054      }
46055    }
46056  }
46057}
46058
46059/*
46060** Restart the backup process. This is called when the pager layer
46061** detects that the database has been modified by an external database
46062** connection. In this case there is no way of knowing which of the
46063** pages that have been copied into the destination database are still
46064** valid and which are not, so the entire process needs to be restarted.
46065**
46066** It is assumed that the mutex associated with the BtShared object
46067** corresponding to the source database is held when this function is
46068** called.
46069*/
46070SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
46071  sqlite3_backup *p;                   /* Iterator variable */
46072  for(p=pBackup; p; p=p->pNext){
46073    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
46074    p->iNext = 1;
46075  }
46076}
46077
46078#ifndef SQLITE_OMIT_VACUUM
46079/*
46080** Copy the complete content of pBtFrom into pBtTo.  A transaction
46081** must be active for both files.
46082**
46083** The size of file pTo may be reduced by this operation. If anything
46084** goes wrong, the transaction on pTo is rolled back. If successful, the
46085** transaction is committed before returning.
46086*/
46087SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
46088  int rc;
46089  sqlite3_backup b;
46090  sqlite3BtreeEnter(pTo);
46091  sqlite3BtreeEnter(pFrom);
46092
46093  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
46094  ** to 0. This is used by the implementations of sqlite3_backup_step()
46095  ** and sqlite3_backup_finish() to detect that they are being called
46096  ** from this function, not directly by the user.
46097  */
46098  memset(&b, 0, sizeof(b));
46099  b.pSrcDb = pFrom->db;
46100  b.pSrc = pFrom;
46101  b.pDest = pTo;
46102  b.iNext = 1;
46103
46104  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
46105  ** file. By passing this as the number of pages to copy to
46106  ** sqlite3_backup_step(), we can guarantee that the copy finishes
46107  ** within a single call (unless an error occurs). The assert() statement
46108  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
46109  ** or an error code.
46110  */
46111  sqlite3_backup_step(&b, 0x7FFFFFFF);
46112  assert( b.rc!=SQLITE_OK );
46113  rc = sqlite3_backup_finish(&b);
46114  if( rc==SQLITE_OK ){
46115    pTo->pBt->pageSizeFixed = 0;
46116  }
46117
46118  sqlite3BtreeLeave(pFrom);
46119  sqlite3BtreeLeave(pTo);
46120  return rc;
46121}
46122#endif /* SQLITE_OMIT_VACUUM */
46123
46124/************** End of backup.c **********************************************/
46125/************** Begin file vdbemem.c *****************************************/
46126/*
46127** 2004 May 26
46128**
46129** The author disclaims copyright to this source code.  In place of
46130** a legal notice, here is a blessing:
46131**
46132**    May you do good and not evil.
46133**    May you find forgiveness for yourself and forgive others.
46134**    May you share freely, never taking more than you give.
46135**
46136*************************************************************************
46137**
46138** This file contains code use to manipulate "Mem" structure.  A "Mem"
46139** stores a single value in the VDBE.  Mem is an opaque structure visible
46140** only within the VDBE.  Interface routines refer to a Mem using the
46141** name sqlite_value
46142*/
46143
46144/*
46145** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
46146** P if required.
46147*/
46148#define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
46149
46150/*
46151** If pMem is an object with a valid string representation, this routine
46152** ensures the internal encoding for the string representation is
46153** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
46154**
46155** If pMem is not a string object, or the encoding of the string
46156** representation is already stored using the requested encoding, then this
46157** routine is a no-op.
46158**
46159** SQLITE_OK is returned if the conversion is successful (or not required).
46160** SQLITE_NOMEM may be returned if a malloc() fails during conversion
46161** between formats.
46162*/
46163SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
46164  int rc;
46165  assert( (pMem->flags&MEM_RowSet)==0 );
46166  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
46167           || desiredEnc==SQLITE_UTF16BE );
46168  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
46169    return SQLITE_OK;
46170  }
46171  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46172#ifdef SQLITE_OMIT_UTF16
46173  return SQLITE_ERROR;
46174#else
46175
46176  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
46177  ** then the encoding of the value may not have changed.
46178  */
46179  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
46180  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
46181  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
46182  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
46183  return rc;
46184#endif
46185}
46186
46187/*
46188** Make sure pMem->z points to a writable allocation of at least
46189** n bytes.
46190**
46191** If the memory cell currently contains string or blob data
46192** and the third argument passed to this function is true, the
46193** current content of the cell is preserved. Otherwise, it may
46194** be discarded.
46195**
46196** This function sets the MEM_Dyn flag and clears any xDel callback.
46197** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
46198** not set, Mem.n is zeroed.
46199*/
46200SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
46201  assert( 1 >=
46202    ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
46203    (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
46204    ((pMem->flags&MEM_Ephem) ? 1 : 0) +
46205    ((pMem->flags&MEM_Static) ? 1 : 0)
46206  );
46207  assert( (pMem->flags&MEM_RowSet)==0 );
46208
46209  if( n<32 ) n = 32;
46210  if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
46211    if( preserve && pMem->z==pMem->zMalloc ){
46212      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
46213      preserve = 0;
46214    }else{
46215      sqlite3DbFree(pMem->db, pMem->zMalloc);
46216      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
46217    }
46218  }
46219
46220  if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
46221    memcpy(pMem->zMalloc, pMem->z, pMem->n);
46222  }
46223  if( pMem->flags&MEM_Dyn && pMem->xDel ){
46224    pMem->xDel((void *)(pMem->z));
46225  }
46226
46227  pMem->z = pMem->zMalloc;
46228  if( pMem->z==0 ){
46229    pMem->flags = MEM_Null;
46230  }else{
46231    pMem->flags &= ~(MEM_Ephem|MEM_Static);
46232  }
46233  pMem->xDel = 0;
46234  return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
46235}
46236
46237/*
46238** Make the given Mem object MEM_Dyn.  In other words, make it so
46239** that any TEXT or BLOB content is stored in memory obtained from
46240** malloc().  In this way, we know that the memory is safe to be
46241** overwritten or altered.
46242**
46243** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
46244*/
46245SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
46246  int f;
46247  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46248  assert( (pMem->flags&MEM_RowSet)==0 );
46249  expandBlob(pMem);
46250  f = pMem->flags;
46251  if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
46252    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
46253      return SQLITE_NOMEM;
46254    }
46255    pMem->z[pMem->n] = 0;
46256    pMem->z[pMem->n+1] = 0;
46257    pMem->flags |= MEM_Term;
46258  }
46259
46260  return SQLITE_OK;
46261}
46262
46263/*
46264** If the given Mem* has a zero-filled tail, turn it into an ordinary
46265** blob stored in dynamically allocated space.
46266*/
46267#ifndef SQLITE_OMIT_INCRBLOB
46268SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
46269  if( pMem->flags & MEM_Zero ){
46270    int nByte;
46271    assert( pMem->flags&MEM_Blob );
46272    assert( (pMem->flags&MEM_RowSet)==0 );
46273    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46274
46275    /* Set nByte to the number of bytes required to store the expanded blob. */
46276    nByte = pMem->n + pMem->u.nZero;
46277    if( nByte<=0 ){
46278      nByte = 1;
46279    }
46280    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
46281      return SQLITE_NOMEM;
46282    }
46283
46284    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
46285    pMem->n += pMem->u.nZero;
46286    pMem->flags &= ~(MEM_Zero|MEM_Term);
46287  }
46288  return SQLITE_OK;
46289}
46290#endif
46291
46292
46293/*
46294** Make sure the given Mem is \u0000 terminated.
46295*/
46296SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
46297  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46298  if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
46299    return SQLITE_OK;   /* Nothing to do */
46300  }
46301  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
46302    return SQLITE_NOMEM;
46303  }
46304  pMem->z[pMem->n] = 0;
46305  pMem->z[pMem->n+1] = 0;
46306  pMem->flags |= MEM_Term;
46307  return SQLITE_OK;
46308}
46309
46310/*
46311** Add MEM_Str to the set of representations for the given Mem.  Numbers
46312** are converted using sqlite3_snprintf().  Converting a BLOB to a string
46313** is a no-op.
46314**
46315** Existing representations MEM_Int and MEM_Real are *not* invalidated.
46316**
46317** A MEM_Null value will never be passed to this function. This function is
46318** used for converting values to text for returning to the user (i.e. via
46319** sqlite3_value_text()), or for ensuring that values to be used as btree
46320** keys are strings. In the former case a NULL pointer is returned the
46321** user and the later is an internal programming error.
46322*/
46323SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
46324  int rc = SQLITE_OK;
46325  int fg = pMem->flags;
46326  const int nByte = 32;
46327
46328  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46329  assert( !(fg&MEM_Zero) );
46330  assert( !(fg&(MEM_Str|MEM_Blob)) );
46331  assert( fg&(MEM_Int|MEM_Real) );
46332  assert( (pMem->flags&MEM_RowSet)==0 );
46333  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46334
46335
46336  if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
46337    return SQLITE_NOMEM;
46338  }
46339
46340  /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
46341  ** string representation of the value. Then, if the required encoding
46342  ** is UTF-16le or UTF-16be do a translation.
46343  **
46344  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
46345  */
46346  if( fg & MEM_Int ){
46347    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
46348  }else{
46349    assert( fg & MEM_Real );
46350    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
46351  }
46352  pMem->n = sqlite3Strlen30(pMem->z);
46353  pMem->enc = SQLITE_UTF8;
46354  pMem->flags |= MEM_Str|MEM_Term;
46355  sqlite3VdbeChangeEncoding(pMem, enc);
46356  return rc;
46357}
46358
46359/*
46360** Memory cell pMem contains the context of an aggregate function.
46361** This routine calls the finalize method for that function.  The
46362** result of the aggregate is stored back into pMem.
46363**
46364** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
46365** otherwise.
46366*/
46367SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
46368  int rc = SQLITE_OK;
46369  if( ALWAYS(pFunc && pFunc->xFinalize) ){
46370    sqlite3_context ctx;
46371    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
46372    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46373    memset(&ctx, 0, sizeof(ctx));
46374    ctx.s.flags = MEM_Null;
46375    ctx.s.db = pMem->db;
46376    ctx.pMem = pMem;
46377    ctx.pFunc = pFunc;
46378    pFunc->xFinalize(&ctx);
46379    assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
46380    sqlite3DbFree(pMem->db, pMem->zMalloc);
46381    memcpy(pMem, &ctx.s, sizeof(ctx.s));
46382    rc = ctx.isError;
46383  }
46384  return rc;
46385}
46386
46387/*
46388** If the memory cell contains a string value that must be freed by
46389** invoking an external callback, free it now. Calling this function
46390** does not free any Mem.zMalloc buffer.
46391*/
46392SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
46393  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
46394  testcase( p->flags & MEM_Agg );
46395  testcase( p->flags & MEM_Dyn );
46396  testcase( p->flags & MEM_RowSet );
46397  testcase( p->flags & MEM_Frame );
46398  if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
46399    if( p->flags&MEM_Agg ){
46400      sqlite3VdbeMemFinalize(p, p->u.pDef);
46401      assert( (p->flags & MEM_Agg)==0 );
46402      sqlite3VdbeMemRelease(p);
46403    }else if( p->flags&MEM_Dyn && p->xDel ){
46404      assert( (p->flags&MEM_RowSet)==0 );
46405      p->xDel((void *)p->z);
46406      p->xDel = 0;
46407    }else if( p->flags&MEM_RowSet ){
46408      sqlite3RowSetClear(p->u.pRowSet);
46409    }else if( p->flags&MEM_Frame ){
46410      sqlite3VdbeMemSetNull(p);
46411    }
46412  }
46413}
46414
46415/*
46416** Release any memory held by the Mem. This may leave the Mem in an
46417** inconsistent state, for example with (Mem.z==0) and
46418** (Mem.type==SQLITE_TEXT).
46419*/
46420SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
46421  sqlite3VdbeMemReleaseExternal(p);
46422  sqlite3DbFree(p->db, p->zMalloc);
46423  p->z = 0;
46424  p->zMalloc = 0;
46425  p->xDel = 0;
46426}
46427
46428/*
46429** Convert a 64-bit IEEE double into a 64-bit signed integer.
46430** If the double is too large, return 0x8000000000000000.
46431**
46432** Most systems appear to do this simply by assigning
46433** variables and without the extra range tests.  But
46434** there are reports that windows throws an expection
46435** if the floating point value is out of range. (See ticket #2880.)
46436** Because we do not completely understand the problem, we will
46437** take the conservative approach and always do range tests
46438** before attempting the conversion.
46439*/
46440static i64 doubleToInt64(double r){
46441  /*
46442  ** Many compilers we encounter do not define constants for the
46443  ** minimum and maximum 64-bit integers, or they define them
46444  ** inconsistently.  And many do not understand the "LL" notation.
46445  ** So we define our own static constants here using nothing
46446  ** larger than a 32-bit integer constant.
46447  */
46448  static const i64 maxInt = LARGEST_INT64;
46449  static const i64 minInt = SMALLEST_INT64;
46450
46451  if( r<(double)minInt ){
46452    return minInt;
46453  }else if( r>(double)maxInt ){
46454    /* minInt is correct here - not maxInt.  It turns out that assigning
46455    ** a very large positive number to an integer results in a very large
46456    ** negative integer.  This makes no sense, but it is what x86 hardware
46457    ** does so for compatibility we will do the same in software. */
46458    return minInt;
46459  }else{
46460    return (i64)r;
46461  }
46462}
46463
46464/*
46465** Return some kind of integer value which is the best we can do
46466** at representing the value that *pMem describes as an integer.
46467** If pMem is an integer, then the value is exact.  If pMem is
46468** a floating-point then the value returned is the integer part.
46469** If pMem is a string or blob, then we make an attempt to convert
46470** it into a integer and return that.  If pMem represents an
46471** an SQL-NULL value, return 0.
46472**
46473** If pMem represents a string value, its encoding might be changed.
46474*/
46475SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
46476  int flags;
46477  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46478  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46479  flags = pMem->flags;
46480  if( flags & MEM_Int ){
46481    return pMem->u.i;
46482  }else if( flags & MEM_Real ){
46483    return doubleToInt64(pMem->r);
46484  }else if( flags & (MEM_Str|MEM_Blob) ){
46485    i64 value;
46486    pMem->flags |= MEM_Str;
46487    if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
46488       || sqlite3VdbeMemNulTerminate(pMem) ){
46489      return 0;
46490    }
46491    assert( pMem->z );
46492    sqlite3Atoi64(pMem->z, &value);
46493    return value;
46494  }else{
46495    return 0;
46496  }
46497}
46498
46499/*
46500** Return the best representation of pMem that we can get into a
46501** double.  If pMem is already a double or an integer, return its
46502** value.  If it is a string or blob, try to convert it to a double.
46503** If it is a NULL, return 0.0.
46504*/
46505SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
46506  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46507  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46508  if( pMem->flags & MEM_Real ){
46509    return pMem->r;
46510  }else if( pMem->flags & MEM_Int ){
46511    return (double)pMem->u.i;
46512  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
46513    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
46514    double val = (double)0;
46515    pMem->flags |= MEM_Str;
46516    if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
46517       || sqlite3VdbeMemNulTerminate(pMem) ){
46518      /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
46519      return (double)0;
46520    }
46521    assert( pMem->z );
46522    sqlite3AtoF(pMem->z, &val);
46523    return val;
46524  }else{
46525    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
46526    return (double)0;
46527  }
46528}
46529
46530/*
46531** The MEM structure is already a MEM_Real.  Try to also make it a
46532** MEM_Int if we can.
46533*/
46534SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
46535  assert( pMem->flags & MEM_Real );
46536  assert( (pMem->flags & MEM_RowSet)==0 );
46537  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46538  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46539
46540  pMem->u.i = doubleToInt64(pMem->r);
46541
46542  /* Only mark the value as an integer if
46543  **
46544  **    (1) the round-trip conversion real->int->real is a no-op, and
46545  **    (2) The integer is neither the largest nor the smallest
46546  **        possible integer (ticket #3922)
46547  **
46548  ** The second and third terms in the following conditional enforces
46549  ** the second condition under the assumption that addition overflow causes
46550  ** values to wrap around.  On x86 hardware, the third term is always
46551  ** true and could be omitted.  But we leave it in because other
46552  ** architectures might behave differently.
46553  */
46554  if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
46555      && ALWAYS(pMem->u.i<LARGEST_INT64) ){
46556    pMem->flags |= MEM_Int;
46557  }
46558}
46559
46560/*
46561** Convert pMem to type integer.  Invalidate any prior representations.
46562*/
46563SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
46564  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46565  assert( (pMem->flags & MEM_RowSet)==0 );
46566  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46567
46568  pMem->u.i = sqlite3VdbeIntValue(pMem);
46569  MemSetTypeFlag(pMem, MEM_Int);
46570  return SQLITE_OK;
46571}
46572
46573/*
46574** Convert pMem so that it is of type MEM_Real.
46575** Invalidate any prior representations.
46576*/
46577SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
46578  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46579  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46580
46581  pMem->r = sqlite3VdbeRealValue(pMem);
46582  MemSetTypeFlag(pMem, MEM_Real);
46583  return SQLITE_OK;
46584}
46585
46586/*
46587** Convert pMem so that it has types MEM_Real or MEM_Int or both.
46588** Invalidate any prior representations.
46589*/
46590SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
46591  double r1, r2;
46592  i64 i;
46593  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
46594  assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
46595  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46596  r1 = sqlite3VdbeRealValue(pMem);
46597  i = doubleToInt64(r1);
46598  r2 = (double)i;
46599  if( r1==r2 ){
46600    sqlite3VdbeMemIntegerify(pMem);
46601  }else{
46602    pMem->r = r1;
46603    MemSetTypeFlag(pMem, MEM_Real);
46604  }
46605  return SQLITE_OK;
46606}
46607
46608/*
46609** Delete any previous value and set the value stored in *pMem to NULL.
46610*/
46611SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
46612  if( pMem->flags & MEM_Frame ){
46613    sqlite3VdbeFrameDelete(pMem->u.pFrame);
46614  }
46615  if( pMem->flags & MEM_RowSet ){
46616    sqlite3RowSetClear(pMem->u.pRowSet);
46617  }
46618  MemSetTypeFlag(pMem, MEM_Null);
46619  pMem->type = SQLITE_NULL;
46620}
46621
46622/*
46623** Delete any previous value and set the value to be a BLOB of length
46624** n containing all zeros.
46625*/
46626SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
46627  sqlite3VdbeMemRelease(pMem);
46628  pMem->flags = MEM_Blob|MEM_Zero;
46629  pMem->type = SQLITE_BLOB;
46630  pMem->n = 0;
46631  if( n<0 ) n = 0;
46632  pMem->u.nZero = n;
46633  pMem->enc = SQLITE_UTF8;
46634
46635#ifdef SQLITE_OMIT_INCRBLOB
46636  sqlite3VdbeMemGrow(pMem, n, 0);
46637  if( pMem->z ){
46638    pMem->n = n;
46639    memset(pMem->z, 0, n);
46640  }
46641#endif
46642}
46643
46644/*
46645** Delete any previous value and set the value stored in *pMem to val,
46646** manifest type INTEGER.
46647*/
46648SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
46649  sqlite3VdbeMemRelease(pMem);
46650  pMem->u.i = val;
46651  pMem->flags = MEM_Int;
46652  pMem->type = SQLITE_INTEGER;
46653}
46654
46655/*
46656** Delete any previous value and set the value stored in *pMem to val,
46657** manifest type REAL.
46658*/
46659SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
46660  if( sqlite3IsNaN(val) ){
46661    sqlite3VdbeMemSetNull(pMem);
46662  }else{
46663    sqlite3VdbeMemRelease(pMem);
46664    pMem->r = val;
46665    pMem->flags = MEM_Real;
46666    pMem->type = SQLITE_FLOAT;
46667  }
46668}
46669
46670/*
46671** Delete any previous value and set the value of pMem to be an
46672** empty boolean index.
46673*/
46674SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
46675  sqlite3 *db = pMem->db;
46676  assert( db!=0 );
46677  assert( (pMem->flags & MEM_RowSet)==0 );
46678  sqlite3VdbeMemRelease(pMem);
46679  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
46680  if( db->mallocFailed ){
46681    pMem->flags = MEM_Null;
46682  }else{
46683    assert( pMem->zMalloc );
46684    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
46685                                       sqlite3DbMallocSize(db, pMem->zMalloc));
46686    assert( pMem->u.pRowSet!=0 );
46687    pMem->flags = MEM_RowSet;
46688  }
46689}
46690
46691/*
46692** Return true if the Mem object contains a TEXT or BLOB that is
46693** too large - whose size exceeds SQLITE_MAX_LENGTH.
46694*/
46695SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
46696  assert( p->db!=0 );
46697  if( p->flags & (MEM_Str|MEM_Blob) ){
46698    int n = p->n;
46699    if( p->flags & MEM_Zero ){
46700      n += p->u.nZero;
46701    }
46702    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
46703  }
46704  return 0;
46705}
46706
46707/*
46708** Size of struct Mem not including the Mem.zMalloc member.
46709*/
46710#define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
46711
46712/*
46713** Make an shallow copy of pFrom into pTo.  Prior contents of
46714** pTo are freed.  The pFrom->z field is not duplicated.  If
46715** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
46716** and flags gets srcType (either MEM_Ephem or MEM_Static).
46717*/
46718SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
46719  assert( (pFrom->flags & MEM_RowSet)==0 );
46720  sqlite3VdbeMemReleaseExternal(pTo);
46721  memcpy(pTo, pFrom, MEMCELLSIZE);
46722  pTo->xDel = 0;
46723  if( (pFrom->flags&MEM_Dyn)!=0 || pFrom->z==pFrom->zMalloc ){
46724    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
46725    assert( srcType==MEM_Ephem || srcType==MEM_Static );
46726    pTo->flags |= srcType;
46727  }
46728}
46729
46730/*
46731** Make a full copy of pFrom into pTo.  Prior contents of pTo are
46732** freed before the copy is made.
46733*/
46734SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
46735  int rc = SQLITE_OK;
46736
46737  assert( (pFrom->flags & MEM_RowSet)==0 );
46738  sqlite3VdbeMemReleaseExternal(pTo);
46739  memcpy(pTo, pFrom, MEMCELLSIZE);
46740  pTo->flags &= ~MEM_Dyn;
46741
46742  if( pTo->flags&(MEM_Str|MEM_Blob) ){
46743    if( 0==(pFrom->flags&MEM_Static) ){
46744      pTo->flags |= MEM_Ephem;
46745      rc = sqlite3VdbeMemMakeWriteable(pTo);
46746    }
46747  }
46748
46749  return rc;
46750}
46751
46752/*
46753** Transfer the contents of pFrom to pTo. Any existing value in pTo is
46754** freed. If pFrom contains ephemeral data, a copy is made.
46755**
46756** pFrom contains an SQL NULL when this routine returns.
46757*/
46758SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
46759  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
46760  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
46761  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
46762
46763  sqlite3VdbeMemRelease(pTo);
46764  memcpy(pTo, pFrom, sizeof(Mem));
46765  pFrom->flags = MEM_Null;
46766  pFrom->xDel = 0;
46767  pFrom->zMalloc = 0;
46768}
46769
46770/*
46771** Change the value of a Mem to be a string or a BLOB.
46772**
46773** The memory management strategy depends on the value of the xDel
46774** parameter. If the value passed is SQLITE_TRANSIENT, then the
46775** string is copied into a (possibly existing) buffer managed by the
46776** Mem structure. Otherwise, any existing buffer is freed and the
46777** pointer copied.
46778**
46779** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
46780** size limit) then no memory allocation occurs.  If the string can be
46781** stored without allocating memory, then it is.  If a memory allocation
46782** is required to store the string, then value of pMem is unchanged.  In
46783** either case, SQLITE_TOOBIG is returned.
46784*/
46785SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
46786  Mem *pMem,          /* Memory cell to set to string value */
46787  const char *z,      /* String pointer */
46788  int n,              /* Bytes in string, or negative */
46789  u8 enc,             /* Encoding of z.  0 for BLOBs */
46790  void (*xDel)(void*) /* Destructor function */
46791){
46792  int nByte = n;      /* New value for pMem->n */
46793  int iLimit;         /* Maximum allowed string or blob size */
46794  u16 flags = 0;      /* New value for pMem->flags */
46795
46796  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46797  assert( (pMem->flags & MEM_RowSet)==0 );
46798
46799  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
46800  if( !z ){
46801    sqlite3VdbeMemSetNull(pMem);
46802    return SQLITE_OK;
46803  }
46804
46805  if( pMem->db ){
46806    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
46807  }else{
46808    iLimit = SQLITE_MAX_LENGTH;
46809  }
46810  flags = (enc==0?MEM_Blob:MEM_Str);
46811  if( nByte<0 ){
46812    assert( enc!=0 );
46813    if( enc==SQLITE_UTF8 ){
46814      for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
46815    }else{
46816      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
46817    }
46818    flags |= MEM_Term;
46819  }
46820
46821  /* The following block sets the new values of Mem.z and Mem.xDel. It
46822  ** also sets a flag in local variable "flags" to indicate the memory
46823  ** management (one of MEM_Dyn or MEM_Static).
46824  */
46825  if( xDel==SQLITE_TRANSIENT ){
46826    int nAlloc = nByte;
46827    if( flags&MEM_Term ){
46828      nAlloc += (enc==SQLITE_UTF8?1:2);
46829    }
46830    if( nByte>iLimit ){
46831      return SQLITE_TOOBIG;
46832    }
46833    if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
46834      return SQLITE_NOMEM;
46835    }
46836    memcpy(pMem->z, z, nAlloc);
46837  }else if( xDel==SQLITE_DYNAMIC ){
46838    sqlite3VdbeMemRelease(pMem);
46839    pMem->zMalloc = pMem->z = (char *)z;
46840    pMem->xDel = 0;
46841  }else{
46842    sqlite3VdbeMemRelease(pMem);
46843    pMem->z = (char *)z;
46844    pMem->xDel = xDel;
46845    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
46846  }
46847
46848  pMem->n = nByte;
46849  pMem->flags = flags;
46850  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
46851  pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
46852
46853#ifndef SQLITE_OMIT_UTF16
46854  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
46855    return SQLITE_NOMEM;
46856  }
46857#endif
46858
46859  if( nByte>iLimit ){
46860    return SQLITE_TOOBIG;
46861  }
46862
46863  return SQLITE_OK;
46864}
46865
46866/*
46867** Compare the values contained by the two memory cells, returning
46868** negative, zero or positive if pMem1 is less than, equal to, or greater
46869** than pMem2. Sorting order is NULL's first, followed by numbers (integers
46870** and reals) sorted numerically, followed by text ordered by the collating
46871** sequence pColl and finally blob's ordered by memcmp().
46872**
46873** Two NULL values are considered equal by this function.
46874*/
46875SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
46876  int rc;
46877  int f1, f2;
46878  int combined_flags;
46879
46880  f1 = pMem1->flags;
46881  f2 = pMem2->flags;
46882  combined_flags = f1|f2;
46883  assert( (combined_flags & MEM_RowSet)==0 );
46884
46885  /* If one value is NULL, it is less than the other. If both values
46886  ** are NULL, return 0.
46887  */
46888  if( combined_flags&MEM_Null ){
46889    return (f2&MEM_Null) - (f1&MEM_Null);
46890  }
46891
46892  /* If one value is a number and the other is not, the number is less.
46893  ** If both are numbers, compare as reals if one is a real, or as integers
46894  ** if both values are integers.
46895  */
46896  if( combined_flags&(MEM_Int|MEM_Real) ){
46897    if( !(f1&(MEM_Int|MEM_Real)) ){
46898      return 1;
46899    }
46900    if( !(f2&(MEM_Int|MEM_Real)) ){
46901      return -1;
46902    }
46903    if( (f1 & f2 & MEM_Int)==0 ){
46904      double r1, r2;
46905      if( (f1&MEM_Real)==0 ){
46906        r1 = (double)pMem1->u.i;
46907      }else{
46908        r1 = pMem1->r;
46909      }
46910      if( (f2&MEM_Real)==0 ){
46911        r2 = (double)pMem2->u.i;
46912      }else{
46913        r2 = pMem2->r;
46914      }
46915      if( r1<r2 ) return -1;
46916      if( r1>r2 ) return 1;
46917      return 0;
46918    }else{
46919      assert( f1&MEM_Int );
46920      assert( f2&MEM_Int );
46921      if( pMem1->u.i < pMem2->u.i ) return -1;
46922      if( pMem1->u.i > pMem2->u.i ) return 1;
46923      return 0;
46924    }
46925  }
46926
46927  /* If one value is a string and the other is a blob, the string is less.
46928  ** If both are strings, compare using the collating functions.
46929  */
46930  if( combined_flags&MEM_Str ){
46931    if( (f1 & MEM_Str)==0 ){
46932      return 1;
46933    }
46934    if( (f2 & MEM_Str)==0 ){
46935      return -1;
46936    }
46937
46938    assert( pMem1->enc==pMem2->enc );
46939    assert( pMem1->enc==SQLITE_UTF8 ||
46940            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
46941
46942    /* The collation sequence must be defined at this point, even if
46943    ** the user deletes the collation sequence after the vdbe program is
46944    ** compiled (this was not always the case).
46945    */
46946    assert( !pColl || pColl->xCmp );
46947
46948    if( pColl ){
46949      if( pMem1->enc==pColl->enc ){
46950        /* The strings are already in the correct encoding.  Call the
46951        ** comparison function directly */
46952        return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
46953      }else{
46954        const void *v1, *v2;
46955        int n1, n2;
46956        Mem c1;
46957        Mem c2;
46958        memset(&c1, 0, sizeof(c1));
46959        memset(&c2, 0, sizeof(c2));
46960        sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
46961        sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
46962        v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
46963        n1 = v1==0 ? 0 : c1.n;
46964        v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
46965        n2 = v2==0 ? 0 : c2.n;
46966        rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
46967        sqlite3VdbeMemRelease(&c1);
46968        sqlite3VdbeMemRelease(&c2);
46969        return rc;
46970      }
46971    }
46972    /* If a NULL pointer was passed as the collate function, fall through
46973    ** to the blob case and use memcmp().  */
46974  }
46975
46976  /* Both values must be blobs.  Compare using memcmp().  */
46977  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
46978  if( rc==0 ){
46979    rc = pMem1->n - pMem2->n;
46980  }
46981  return rc;
46982}
46983
46984/*
46985** Move data out of a btree key or data field and into a Mem structure.
46986** The data or key is taken from the entry that pCur is currently pointing
46987** to.  offset and amt determine what portion of the data or key to retrieve.
46988** key is true to get the key or false to get data.  The result is written
46989** into the pMem element.
46990**
46991** The pMem structure is assumed to be uninitialized.  Any prior content
46992** is overwritten without being freed.
46993**
46994** If this routine fails for any reason (malloc returns NULL or unable
46995** to read from the disk) then the pMem is left in an inconsistent state.
46996*/
46997SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
46998  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
46999  int offset,       /* Offset from the start of data to return bytes from. */
47000  int amt,          /* Number of bytes to return. */
47001  int key,          /* If true, retrieve from the btree key, not data. */
47002  Mem *pMem         /* OUT: Return data in this Mem structure. */
47003){
47004  char *zData;        /* Data from the btree layer */
47005  int available = 0;  /* Number of bytes available on the local btree page */
47006  int rc = SQLITE_OK; /* Return code */
47007
47008  assert( sqlite3BtreeCursorIsValid(pCur) );
47009
47010  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
47011  ** that both the BtShared and database handle mutexes are held. */
47012  assert( (pMem->flags & MEM_RowSet)==0 );
47013  if( key ){
47014    zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
47015  }else{
47016    zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
47017  }
47018  assert( zData!=0 );
47019
47020  if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
47021    sqlite3VdbeMemRelease(pMem);
47022    pMem->z = &zData[offset];
47023    pMem->flags = MEM_Blob|MEM_Ephem;
47024  }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
47025    pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
47026    pMem->enc = 0;
47027    pMem->type = SQLITE_BLOB;
47028    if( key ){
47029      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
47030    }else{
47031      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
47032    }
47033    pMem->z[amt] = 0;
47034    pMem->z[amt+1] = 0;
47035    if( rc!=SQLITE_OK ){
47036      sqlite3VdbeMemRelease(pMem);
47037    }
47038  }
47039  pMem->n = amt;
47040
47041  return rc;
47042}
47043
47044/* This function is only available internally, it is not part of the
47045** external API. It works in a similar way to sqlite3_value_text(),
47046** except the data returned is in the encoding specified by the second
47047** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
47048** SQLITE_UTF8.
47049**
47050** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
47051** If that is the case, then the result must be aligned on an even byte
47052** boundary.
47053*/
47054SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
47055  if( !pVal ) return 0;
47056
47057  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
47058  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
47059  assert( (pVal->flags & MEM_RowSet)==0 );
47060
47061  if( pVal->flags&MEM_Null ){
47062    return 0;
47063  }
47064  assert( (MEM_Blob>>3) == MEM_Str );
47065  pVal->flags |= (pVal->flags & MEM_Blob)>>3;
47066  expandBlob(pVal);
47067  if( pVal->flags&MEM_Str ){
47068    sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
47069    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
47070      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
47071      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
47072        return 0;
47073      }
47074    }
47075    sqlite3VdbeMemNulTerminate(pVal);
47076  }else{
47077    assert( (pVal->flags&MEM_Blob)==0 );
47078    sqlite3VdbeMemStringify(pVal, enc);
47079    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
47080  }
47081  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
47082              || pVal->db->mallocFailed );
47083  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
47084    return pVal->z;
47085  }else{
47086    return 0;
47087  }
47088}
47089
47090/*
47091** Create a new sqlite3_value object.
47092*/
47093SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
47094  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
47095  if( p ){
47096    p->flags = MEM_Null;
47097    p->type = SQLITE_NULL;
47098    p->db = db;
47099  }
47100  return p;
47101}
47102
47103/*
47104** Create a new sqlite3_value object, containing the value of pExpr.
47105**
47106** This only works for very simple expressions that consist of one constant
47107** token (i.e. "5", "5.1", "'a string'"). If the expression can
47108** be converted directly into a value, then the value is allocated and
47109** a pointer written to *ppVal. The caller is responsible for deallocating
47110** the value by passing it to sqlite3ValueFree() later on. If the expression
47111** cannot be converted to a value, then *ppVal is set to NULL.
47112*/
47113SQLITE_PRIVATE int sqlite3ValueFromExpr(
47114  sqlite3 *db,              /* The database connection */
47115  Expr *pExpr,              /* The expression to evaluate */
47116  u8 enc,                   /* Encoding to use */
47117  u8 affinity,              /* Affinity to use */
47118  sqlite3_value **ppVal     /* Write the new value here */
47119){
47120  int op;
47121  char *zVal = 0;
47122  sqlite3_value *pVal = 0;
47123
47124  if( !pExpr ){
47125    *ppVal = 0;
47126    return SQLITE_OK;
47127  }
47128  op = pExpr->op;
47129  if( op==TK_REGISTER ){
47130    op = pExpr->op2;  /* This only happens with SQLITE_ENABLE_STAT2 */
47131  }
47132
47133  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
47134    pVal = sqlite3ValueNew(db);
47135    if( pVal==0 ) goto no_mem;
47136    if( ExprHasProperty(pExpr, EP_IntValue) ){
47137      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue);
47138    }else{
47139      zVal = sqlite3DbStrDup(db, pExpr->u.zToken);
47140      if( zVal==0 ) goto no_mem;
47141      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
47142      if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
47143    }
47144    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
47145      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
47146    }else{
47147      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
47148    }
47149    if( enc!=SQLITE_UTF8 ){
47150      sqlite3VdbeChangeEncoding(pVal, enc);
47151    }
47152  }else if( op==TK_UMINUS ) {
47153    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
47154      pVal->u.i = -1 * pVal->u.i;
47155      /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
47156      pVal->r = (double)-1 * pVal->r;
47157    }
47158  }
47159#ifndef SQLITE_OMIT_BLOB_LITERAL
47160  else if( op==TK_BLOB ){
47161    int nVal;
47162    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
47163    assert( pExpr->u.zToken[1]=='\'' );
47164    pVal = sqlite3ValueNew(db);
47165    if( !pVal ) goto no_mem;
47166    zVal = &pExpr->u.zToken[2];
47167    nVal = sqlite3Strlen30(zVal)-1;
47168    assert( zVal[nVal]=='\'' );
47169    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
47170                         0, SQLITE_DYNAMIC);
47171  }
47172#endif
47173
47174  if( pVal ){
47175    sqlite3VdbeMemStoreType(pVal);
47176  }
47177  *ppVal = pVal;
47178  return SQLITE_OK;
47179
47180no_mem:
47181  db->mallocFailed = 1;
47182  sqlite3DbFree(db, zVal);
47183  sqlite3ValueFree(pVal);
47184  *ppVal = 0;
47185  return SQLITE_NOMEM;
47186}
47187
47188/*
47189** Change the string value of an sqlite3_value object
47190*/
47191SQLITE_PRIVATE void sqlite3ValueSetStr(
47192  sqlite3_value *v,     /* Value to be set */
47193  int n,                /* Length of string z */
47194  const void *z,        /* Text of the new string */
47195  u8 enc,               /* Encoding to use */
47196  void (*xDel)(void*)   /* Destructor for the string */
47197){
47198  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
47199}
47200
47201/*
47202** Free an sqlite3_value object
47203*/
47204SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
47205  if( !v ) return;
47206  sqlite3VdbeMemRelease((Mem *)v);
47207  sqlite3DbFree(((Mem*)v)->db, v);
47208}
47209
47210/*
47211** Return the number of bytes in the sqlite3_value object assuming
47212** that it uses the encoding "enc"
47213*/
47214SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
47215  Mem *p = (Mem*)pVal;
47216  if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
47217    if( p->flags & MEM_Zero ){
47218      return p->n + p->u.nZero;
47219    }else{
47220      return p->n;
47221    }
47222  }
47223  return 0;
47224}
47225
47226/************** End of vdbemem.c *********************************************/
47227/************** Begin file vdbeaux.c *****************************************/
47228/*
47229** 2003 September 6
47230**
47231** The author disclaims copyright to this source code.  In place of
47232** a legal notice, here is a blessing:
47233**
47234**    May you do good and not evil.
47235**    May you find forgiveness for yourself and forgive others.
47236**    May you share freely, never taking more than you give.
47237**
47238*************************************************************************
47239** This file contains code used for creating, destroying, and populating
47240** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
47241** to version 2.8.7, all this code was combined into the vdbe.c source file.
47242** But that file was getting too big so this subroutines were split out.
47243*/
47244
47245
47246
47247/*
47248** When debugging the code generator in a symbolic debugger, one can
47249** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
47250** as they are added to the instruction stream.
47251*/
47252#ifdef SQLITE_DEBUG
47253SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
47254#endif
47255
47256
47257/*
47258** Create a new virtual database engine.
47259*/
47260SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
47261  Vdbe *p;
47262  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
47263  if( p==0 ) return 0;
47264  p->db = db;
47265  if( db->pVdbe ){
47266    db->pVdbe->pPrev = p;
47267  }
47268  p->pNext = db->pVdbe;
47269  p->pPrev = 0;
47270  db->pVdbe = p;
47271  p->magic = VDBE_MAGIC_INIT;
47272  return p;
47273}
47274
47275/*
47276** Remember the SQL string for a prepared statement.
47277*/
47278SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
47279  assert( isPrepareV2==1 || isPrepareV2==0 );
47280  if( p==0 ) return;
47281#ifdef SQLITE_OMIT_TRACE
47282  if( !isPrepareV2 ) return;
47283#endif
47284  assert( p->zSql==0 );
47285  p->zSql = sqlite3DbStrNDup(p->db, z, n);
47286  p->isPrepareV2 = (u8)isPrepareV2;
47287}
47288
47289/*
47290** Return the SQL associated with a prepared statement
47291*/
47292SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
47293  Vdbe *p = (Vdbe *)pStmt;
47294  return (p->isPrepareV2 ? p->zSql : 0);
47295}
47296
47297/*
47298** Swap all content between two VDBE structures.
47299*/
47300SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
47301  Vdbe tmp, *pTmp;
47302  char *zTmp;
47303  tmp = *pA;
47304  *pA = *pB;
47305  *pB = tmp;
47306  pTmp = pA->pNext;
47307  pA->pNext = pB->pNext;
47308  pB->pNext = pTmp;
47309  pTmp = pA->pPrev;
47310  pA->pPrev = pB->pPrev;
47311  pB->pPrev = pTmp;
47312  zTmp = pA->zSql;
47313  pA->zSql = pB->zSql;
47314  pB->zSql = zTmp;
47315  pB->isPrepareV2 = pA->isPrepareV2;
47316}
47317
47318#ifdef SQLITE_DEBUG
47319/*
47320** Turn tracing on or off
47321*/
47322SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
47323  p->trace = trace;
47324}
47325#endif
47326
47327/*
47328** Resize the Vdbe.aOp array so that it is at least one op larger than
47329** it was.
47330**
47331** If an out-of-memory error occurs while resizing the array, return
47332** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
47333** unchanged (this is so that any opcodes already allocated can be
47334** correctly deallocated along with the rest of the Vdbe).
47335*/
47336static int growOpArray(Vdbe *p){
47337  VdbeOp *pNew;
47338  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
47339  pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
47340  if( pNew ){
47341    p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
47342    p->aOp = pNew;
47343  }
47344  return (pNew ? SQLITE_OK : SQLITE_NOMEM);
47345}
47346
47347/*
47348** Add a new instruction to the list of instructions current in the
47349** VDBE.  Return the address of the new instruction.
47350**
47351** Parameters:
47352**
47353**    p               Pointer to the VDBE
47354**
47355**    op              The opcode for this instruction
47356**
47357**    p1, p2, p3      Operands
47358**
47359** Use the sqlite3VdbeResolveLabel() function to fix an address and
47360** the sqlite3VdbeChangeP4() function to change the value of the P4
47361** operand.
47362*/
47363SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
47364  int i;
47365  VdbeOp *pOp;
47366
47367  i = p->nOp;
47368  assert( p->magic==VDBE_MAGIC_INIT );
47369  assert( op>0 && op<0xff );
47370  if( p->nOpAlloc<=i ){
47371    if( growOpArray(p) ){
47372      return 1;
47373    }
47374  }
47375  p->nOp++;
47376  pOp = &p->aOp[i];
47377  pOp->opcode = (u8)op;
47378  pOp->p5 = 0;
47379  pOp->p1 = p1;
47380  pOp->p2 = p2;
47381  pOp->p3 = p3;
47382  pOp->p4.p = 0;
47383  pOp->p4type = P4_NOTUSED;
47384  p->expired = 0;
47385#ifdef SQLITE_DEBUG
47386  pOp->zComment = 0;
47387  if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
47388#endif
47389#ifdef VDBE_PROFILE
47390  pOp->cycles = 0;
47391  pOp->cnt = 0;
47392#endif
47393  return i;
47394}
47395SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
47396  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
47397}
47398SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
47399  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
47400}
47401SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
47402  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
47403}
47404
47405
47406/*
47407** Add an opcode that includes the p4 value as a pointer.
47408*/
47409SQLITE_PRIVATE int sqlite3VdbeAddOp4(
47410  Vdbe *p,            /* Add the opcode to this VM */
47411  int op,             /* The new opcode */
47412  int p1,             /* The P1 operand */
47413  int p2,             /* The P2 operand */
47414  int p3,             /* The P3 operand */
47415  const char *zP4,    /* The P4 operand */
47416  int p4type          /* P4 operand type */
47417){
47418  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
47419  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
47420  return addr;
47421}
47422
47423/*
47424** Add an opcode that includes the p4 value as an integer.
47425*/
47426SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
47427  Vdbe *p,            /* Add the opcode to this VM */
47428  int op,             /* The new opcode */
47429  int p1,             /* The P1 operand */
47430  int p2,             /* The P2 operand */
47431  int p3,             /* The P3 operand */
47432  int p4              /* The P4 operand as an integer */
47433){
47434  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
47435  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
47436  return addr;
47437}
47438
47439/*
47440** Create a new symbolic label for an instruction that has yet to be
47441** coded.  The symbolic label is really just a negative number.  The
47442** label can be used as the P2 value of an operation.  Later, when
47443** the label is resolved to a specific address, the VDBE will scan
47444** through its operation list and change all values of P2 which match
47445** the label into the resolved address.
47446**
47447** The VDBE knows that a P2 value is a label because labels are
47448** always negative and P2 values are suppose to be non-negative.
47449** Hence, a negative P2 value is a label that has yet to be resolved.
47450**
47451** Zero is returned if a malloc() fails.
47452*/
47453SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
47454  int i;
47455  i = p->nLabel++;
47456  assert( p->magic==VDBE_MAGIC_INIT );
47457  if( i>=p->nLabelAlloc ){
47458    int n = p->nLabelAlloc*2 + 5;
47459    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
47460                                       n*sizeof(p->aLabel[0]));
47461    p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
47462  }
47463  if( p->aLabel ){
47464    p->aLabel[i] = -1;
47465  }
47466  return -1-i;
47467}
47468
47469/*
47470** Resolve label "x" to be the address of the next instruction to
47471** be inserted.  The parameter "x" must have been obtained from
47472** a prior call to sqlite3VdbeMakeLabel().
47473*/
47474SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
47475  int j = -1-x;
47476  assert( p->magic==VDBE_MAGIC_INIT );
47477  assert( j>=0 && j<p->nLabel );
47478  if( p->aLabel ){
47479    p->aLabel[j] = p->nOp;
47480  }
47481}
47482
47483#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
47484
47485/*
47486** The following type and function are used to iterate through all opcodes
47487** in a Vdbe main program and each of the sub-programs (triggers) it may
47488** invoke directly or indirectly. It should be used as follows:
47489**
47490**   Op *pOp;
47491**   VdbeOpIter sIter;
47492**
47493**   memset(&sIter, 0, sizeof(sIter));
47494**   sIter.v = v;                            // v is of type Vdbe*
47495**   while( (pOp = opIterNext(&sIter)) ){
47496**     // Do something with pOp
47497**   }
47498**   sqlite3DbFree(v->db, sIter.apSub);
47499**
47500*/
47501typedef struct VdbeOpIter VdbeOpIter;
47502struct VdbeOpIter {
47503  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
47504  SubProgram **apSub;        /* Array of subprograms */
47505  int nSub;                  /* Number of entries in apSub */
47506  int iAddr;                 /* Address of next instruction to return */
47507  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
47508};
47509static Op *opIterNext(VdbeOpIter *p){
47510  Vdbe *v = p->v;
47511  Op *pRet = 0;
47512  Op *aOp;
47513  int nOp;
47514
47515  if( p->iSub<=p->nSub ){
47516
47517    if( p->iSub==0 ){
47518      aOp = v->aOp;
47519      nOp = v->nOp;
47520    }else{
47521      aOp = p->apSub[p->iSub-1]->aOp;
47522      nOp = p->apSub[p->iSub-1]->nOp;
47523    }
47524    assert( p->iAddr<nOp );
47525
47526    pRet = &aOp[p->iAddr];
47527    p->iAddr++;
47528    if( p->iAddr==nOp ){
47529      p->iSub++;
47530      p->iAddr = 0;
47531    }
47532
47533    if( pRet->p4type==P4_SUBPROGRAM ){
47534      int nByte = (p->nSub+1)*sizeof(SubProgram*);
47535      int j;
47536      for(j=0; j<p->nSub; j++){
47537        if( p->apSub[j]==pRet->p4.pProgram ) break;
47538      }
47539      if( j==p->nSub ){
47540        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
47541        if( !p->apSub ){
47542          pRet = 0;
47543        }else{
47544          p->apSub[p->nSub++] = pRet->p4.pProgram;
47545        }
47546      }
47547    }
47548  }
47549
47550  return pRet;
47551}
47552
47553/*
47554** Check if the program stored in the VM associated with pParse may
47555** throw an ABORT exception (causing the statement, but not entire transaction
47556** to be rolled back). This condition is true if the main program or any
47557** sub-programs contains any of the following:
47558**
47559**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
47560**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
47561**   *  OP_Destroy
47562**   *  OP_VUpdate
47563**   *  OP_VRename
47564**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
47565**
47566** Then check that the value of Parse.mayAbort is true if an
47567** ABORT may be thrown, or false otherwise. Return true if it does
47568** match, or false otherwise. This function is intended to be used as
47569** part of an assert statement in the compiler. Similar to:
47570**
47571**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
47572*/
47573SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
47574  int hasAbort = 0;
47575  Op *pOp;
47576  VdbeOpIter sIter;
47577  memset(&sIter, 0, sizeof(sIter));
47578  sIter.v = v;
47579
47580  while( (pOp = opIterNext(&sIter))!=0 ){
47581    int opcode = pOp->opcode;
47582    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
47583#ifndef SQLITE_OMIT_FOREIGN_KEY
47584     || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
47585#endif
47586     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
47587      && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
47588    ){
47589      hasAbort = 1;
47590      break;
47591    }
47592  }
47593  sqlite3DbFree(v->db, sIter.apSub);
47594
47595  /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
47596  ** If malloc failed, then the while() loop above may not have iterated
47597  ** through all opcodes and hasAbort may be set incorrectly. Return
47598  ** true for this case to prevent the assert() in the callers frame
47599  ** from failing.  */
47600  return ( v->db->mallocFailed || hasAbort==mayAbort );
47601}
47602#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
47603
47604/*
47605** Loop through the program looking for P2 values that are negative
47606** on jump instructions.  Each such value is a label.  Resolve the
47607** label by setting the P2 value to its correct non-zero value.
47608**
47609** This routine is called once after all opcodes have been inserted.
47610**
47611** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
47612** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
47613** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
47614**
47615** The Op.opflags field is set on all opcodes.
47616*/
47617static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
47618  int i;
47619  int nMaxArgs = *pMaxFuncArgs;
47620  Op *pOp;
47621  int *aLabel = p->aLabel;
47622  p->readOnly = 1;
47623  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
47624    u8 opcode = pOp->opcode;
47625
47626    pOp->opflags = sqlite3OpcodeProperty[opcode];
47627    if( opcode==OP_Function || opcode==OP_AggStep ){
47628      if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
47629    }else if( opcode==OP_Transaction && pOp->p2!=0 ){
47630      p->readOnly = 0;
47631#ifndef SQLITE_OMIT_VIRTUALTABLE
47632    }else if( opcode==OP_VUpdate ){
47633      if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
47634    }else if( opcode==OP_VFilter ){
47635      int n;
47636      assert( p->nOp - i >= 3 );
47637      assert( pOp[-1].opcode==OP_Integer );
47638      n = pOp[-1].p1;
47639      if( n>nMaxArgs ) nMaxArgs = n;
47640#endif
47641    }
47642
47643    if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
47644      assert( -1-pOp->p2<p->nLabel );
47645      pOp->p2 = aLabel[-1-pOp->p2];
47646    }
47647  }
47648  sqlite3DbFree(p->db, p->aLabel);
47649  p->aLabel = 0;
47650
47651  *pMaxFuncArgs = nMaxArgs;
47652}
47653
47654/*
47655** Return the address of the next instruction to be inserted.
47656*/
47657SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
47658  assert( p->magic==VDBE_MAGIC_INIT );
47659  return p->nOp;
47660}
47661
47662/*
47663** This function returns a pointer to the array of opcodes associated with
47664** the Vdbe passed as the first argument. It is the callers responsibility
47665** to arrange for the returned array to be eventually freed using the
47666** vdbeFreeOpArray() function.
47667**
47668** Before returning, *pnOp is set to the number of entries in the returned
47669** array. Also, *pnMaxArg is set to the larger of its current value and
47670** the number of entries in the Vdbe.apArg[] array required to execute the
47671** returned program.
47672*/
47673SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
47674  VdbeOp *aOp = p->aOp;
47675  assert( aOp && !p->db->mallocFailed );
47676
47677  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
47678  assert( p->aMutex.nMutex==0 );
47679
47680  resolveP2Values(p, pnMaxArg);
47681  *pnOp = p->nOp;
47682  p->aOp = 0;
47683  return aOp;
47684}
47685
47686/*
47687** Add a whole list of operations to the operation stack.  Return the
47688** address of the first operation added.
47689*/
47690SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
47691  int addr;
47692  assert( p->magic==VDBE_MAGIC_INIT );
47693  if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
47694    return 0;
47695  }
47696  addr = p->nOp;
47697  if( ALWAYS(nOp>0) ){
47698    int i;
47699    VdbeOpList const *pIn = aOp;
47700    for(i=0; i<nOp; i++, pIn++){
47701      int p2 = pIn->p2;
47702      VdbeOp *pOut = &p->aOp[i+addr];
47703      pOut->opcode = pIn->opcode;
47704      pOut->p1 = pIn->p1;
47705      if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
47706        pOut->p2 = addr + ADDR(p2);
47707      }else{
47708        pOut->p2 = p2;
47709      }
47710      pOut->p3 = pIn->p3;
47711      pOut->p4type = P4_NOTUSED;
47712      pOut->p4.p = 0;
47713      pOut->p5 = 0;
47714#ifdef SQLITE_DEBUG
47715      pOut->zComment = 0;
47716      if( sqlite3VdbeAddopTrace ){
47717        sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
47718      }
47719#endif
47720    }
47721    p->nOp += nOp;
47722  }
47723  return addr;
47724}
47725
47726/*
47727** Change the value of the P1 operand for a specific instruction.
47728** This routine is useful when a large program is loaded from a
47729** static array using sqlite3VdbeAddOpList but we want to make a
47730** few minor changes to the program.
47731*/
47732SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
47733  assert( p!=0 );
47734  assert( addr>=0 );
47735  if( p->nOp>addr ){
47736    p->aOp[addr].p1 = val;
47737  }
47738}
47739
47740/*
47741** Change the value of the P2 operand for a specific instruction.
47742** This routine is useful for setting a jump destination.
47743*/
47744SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
47745  assert( p!=0 );
47746  assert( addr>=0 );
47747  if( p->nOp>addr ){
47748    p->aOp[addr].p2 = val;
47749  }
47750}
47751
47752/*
47753** Change the value of the P3 operand for a specific instruction.
47754*/
47755SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
47756  assert( p!=0 );
47757  assert( addr>=0 );
47758  if( p->nOp>addr ){
47759    p->aOp[addr].p3 = val;
47760  }
47761}
47762
47763/*
47764** Change the value of the P5 operand for the most recently
47765** added operation.
47766*/
47767SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
47768  assert( p!=0 );
47769  if( p->aOp ){
47770    assert( p->nOp>0 );
47771    p->aOp[p->nOp-1].p5 = val;
47772  }
47773}
47774
47775/*
47776** Change the P2 operand of instruction addr so that it points to
47777** the address of the next instruction to be coded.
47778*/
47779SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
47780  sqlite3VdbeChangeP2(p, addr, p->nOp);
47781}
47782
47783
47784/*
47785** If the input FuncDef structure is ephemeral, then free it.  If
47786** the FuncDef is not ephermal, then do nothing.
47787*/
47788static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
47789  if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
47790    sqlite3DbFree(db, pDef);
47791  }
47792}
47793
47794/*
47795** Delete a P4 value if necessary.
47796*/
47797static void freeP4(sqlite3 *db, int p4type, void *p4){
47798  if( p4 ){
47799    switch( p4type ){
47800      case P4_REAL:
47801      case P4_INT64:
47802      case P4_MPRINTF:
47803      case P4_DYNAMIC:
47804      case P4_KEYINFO:
47805      case P4_INTARRAY:
47806      case P4_KEYINFO_HANDOFF: {
47807        sqlite3DbFree(db, p4);
47808        break;
47809      }
47810      case P4_VDBEFUNC: {
47811        VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
47812        freeEphemeralFunction(db, pVdbeFunc->pFunc);
47813        sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
47814        sqlite3DbFree(db, pVdbeFunc);
47815        break;
47816      }
47817      case P4_FUNCDEF: {
47818        freeEphemeralFunction(db, (FuncDef*)p4);
47819        break;
47820      }
47821      case P4_MEM: {
47822        sqlite3ValueFree((sqlite3_value*)p4);
47823        break;
47824      }
47825      case P4_VTAB : {
47826        sqlite3VtabUnlock((VTable *)p4);
47827        break;
47828      }
47829      case P4_SUBPROGRAM : {
47830        sqlite3VdbeProgramDelete(db, (SubProgram *)p4, 1);
47831        break;
47832      }
47833    }
47834  }
47835}
47836
47837/*
47838** Free the space allocated for aOp and any p4 values allocated for the
47839** opcodes contained within. If aOp is not NULL it is assumed to contain
47840** nOp entries.
47841*/
47842static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
47843  if( aOp ){
47844    Op *pOp;
47845    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
47846      freeP4(db, pOp->p4type, pOp->p4.p);
47847#ifdef SQLITE_DEBUG
47848      sqlite3DbFree(db, pOp->zComment);
47849#endif
47850    }
47851  }
47852  sqlite3DbFree(db, aOp);
47853}
47854
47855/*
47856** Decrement the ref-count on the SubProgram structure passed as the
47857** second argument. If the ref-count reaches zero, free the structure.
47858**
47859** The array of VDBE opcodes stored as SubProgram.aOp is freed if
47860** either the ref-count reaches zero or parameter freeop is non-zero.
47861**
47862** Since the array of opcodes pointed to by SubProgram.aOp may directly
47863** or indirectly contain a reference to the SubProgram structure itself.
47864** By passing a non-zero freeop parameter, the caller may ensure that all
47865** SubProgram structures and their aOp arrays are freed, even when there
47866** are such circular references.
47867*/
47868SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *db, SubProgram *p, int freeop){
47869  if( p ){
47870    assert( p->nRef>0 );
47871    if( freeop || p->nRef==1 ){
47872      Op *aOp = p->aOp;
47873      p->aOp = 0;
47874      vdbeFreeOpArray(db, aOp, p->nOp);
47875      p->nOp = 0;
47876    }
47877    p->nRef--;
47878    if( p->nRef==0 ){
47879      sqlite3DbFree(db, p);
47880    }
47881  }
47882}
47883
47884
47885/*
47886** Change N opcodes starting at addr to No-ops.
47887*/
47888SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
47889  if( p->aOp ){
47890    VdbeOp *pOp = &p->aOp[addr];
47891    sqlite3 *db = p->db;
47892    while( N-- ){
47893      freeP4(db, pOp->p4type, pOp->p4.p);
47894      memset(pOp, 0, sizeof(pOp[0]));
47895      pOp->opcode = OP_Noop;
47896      pOp++;
47897    }
47898  }
47899}
47900
47901/*
47902** Change the value of the P4 operand for a specific instruction.
47903** This routine is useful when a large program is loaded from a
47904** static array using sqlite3VdbeAddOpList but we want to make a
47905** few minor changes to the program.
47906**
47907** If n>=0 then the P4 operand is dynamic, meaning that a copy of
47908** the string is made into memory obtained from sqlite3_malloc().
47909** A value of n==0 means copy bytes of zP4 up to and including the
47910** first null byte.  If n>0 then copy n+1 bytes of zP4.
47911**
47912** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
47913** A copy is made of the KeyInfo structure into memory obtained from
47914** sqlite3_malloc, to be freed when the Vdbe is finalized.
47915** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
47916** stored in memory that the caller has obtained from sqlite3_malloc. The
47917** caller should not free the allocation, it will be freed when the Vdbe is
47918** finalized.
47919**
47920** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
47921** to a string or structure that is guaranteed to exist for the lifetime of
47922** the Vdbe. In these cases we can just copy the pointer.
47923**
47924** If addr<0 then change P4 on the most recently inserted instruction.
47925*/
47926SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
47927  Op *pOp;
47928  sqlite3 *db;
47929  assert( p!=0 );
47930  db = p->db;
47931  assert( p->magic==VDBE_MAGIC_INIT );
47932  if( p->aOp==0 || db->mallocFailed ){
47933    if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
47934      freeP4(db, n, (void*)*(char**)&zP4);
47935    }
47936    return;
47937  }
47938  assert( p->nOp>0 );
47939  assert( addr<p->nOp );
47940  if( addr<0 ){
47941    addr = p->nOp - 1;
47942  }
47943  pOp = &p->aOp[addr];
47944  freeP4(db, pOp->p4type, pOp->p4.p);
47945  pOp->p4.p = 0;
47946  if( n==P4_INT32 ){
47947    /* Note: this cast is safe, because the origin data point was an int
47948    ** that was cast to a (const char *). */
47949    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
47950    pOp->p4type = P4_INT32;
47951  }else if( zP4==0 ){
47952    pOp->p4.p = 0;
47953    pOp->p4type = P4_NOTUSED;
47954  }else if( n==P4_KEYINFO ){
47955    KeyInfo *pKeyInfo;
47956    int nField, nByte;
47957
47958    nField = ((KeyInfo*)zP4)->nField;
47959    nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
47960    pKeyInfo = sqlite3Malloc( nByte );
47961    pOp->p4.pKeyInfo = pKeyInfo;
47962    if( pKeyInfo ){
47963      u8 *aSortOrder;
47964      memcpy(pKeyInfo, zP4, nByte);
47965      aSortOrder = pKeyInfo->aSortOrder;
47966      if( aSortOrder ){
47967        pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
47968        memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
47969      }
47970      pOp->p4type = P4_KEYINFO;
47971    }else{
47972      p->db->mallocFailed = 1;
47973      pOp->p4type = P4_NOTUSED;
47974    }
47975  }else if( n==P4_KEYINFO_HANDOFF ){
47976    pOp->p4.p = (void*)zP4;
47977    pOp->p4type = P4_KEYINFO;
47978  }else if( n==P4_VTAB ){
47979    pOp->p4.p = (void*)zP4;
47980    pOp->p4type = P4_VTAB;
47981    sqlite3VtabLock((VTable *)zP4);
47982    assert( ((VTable *)zP4)->db==p->db );
47983  }else if( n<0 ){
47984    pOp->p4.p = (void*)zP4;
47985    pOp->p4type = (signed char)n;
47986  }else{
47987    if( n==0 ) n = sqlite3Strlen30(zP4);
47988    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
47989    pOp->p4type = P4_DYNAMIC;
47990  }
47991}
47992
47993#ifndef NDEBUG
47994/*
47995** Change the comment on the the most recently coded instruction.  Or
47996** insert a No-op and add the comment to that new instruction.  This
47997** makes the code easier to read during debugging.  None of this happens
47998** in a production build.
47999*/
48000SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
48001  va_list ap;
48002  if( !p ) return;
48003  assert( p->nOp>0 || p->aOp==0 );
48004  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
48005  if( p->nOp ){
48006    char **pz = &p->aOp[p->nOp-1].zComment;
48007    va_start(ap, zFormat);
48008    sqlite3DbFree(p->db, *pz);
48009    *pz = sqlite3VMPrintf(p->db, zFormat, ap);
48010    va_end(ap);
48011  }
48012}
48013SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
48014  va_list ap;
48015  if( !p ) return;
48016  sqlite3VdbeAddOp0(p, OP_Noop);
48017  assert( p->nOp>0 || p->aOp==0 );
48018  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
48019  if( p->nOp ){
48020    char **pz = &p->aOp[p->nOp-1].zComment;
48021    va_start(ap, zFormat);
48022    sqlite3DbFree(p->db, *pz);
48023    *pz = sqlite3VMPrintf(p->db, zFormat, ap);
48024    va_end(ap);
48025  }
48026}
48027#endif  /* NDEBUG */
48028
48029/*
48030** Return the opcode for a given address.  If the address is -1, then
48031** return the most recently inserted opcode.
48032**
48033** If a memory allocation error has occurred prior to the calling of this
48034** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
48035** is readable and writable, but it has no effect.  The return of a dummy
48036** opcode allows the call to continue functioning after a OOM fault without
48037** having to check to see if the return from this routine is a valid pointer.
48038**
48039** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
48040** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
48041** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
48042** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
48043** having to double-check to make sure that the result is non-negative. But
48044** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
48045** check the value of p->nOp-1 before continuing.
48046*/
48047SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
48048  static VdbeOp dummy;
48049  assert( p->magic==VDBE_MAGIC_INIT );
48050  if( addr<0 ){
48051#ifdef SQLITE_OMIT_TRACE
48052    if( p->nOp==0 ) return &dummy;
48053#endif
48054    addr = p->nOp - 1;
48055  }
48056  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
48057  if( p->db->mallocFailed ){
48058    return &dummy;
48059  }else{
48060    return &p->aOp[addr];
48061  }
48062}
48063
48064#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
48065     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
48066/*
48067** Compute a string that describes the P4 parameter for an opcode.
48068** Use zTemp for any required temporary buffer space.
48069*/
48070static char *displayP4(Op *pOp, char *zTemp, int nTemp){
48071  char *zP4 = zTemp;
48072  assert( nTemp>=20 );
48073  switch( pOp->p4type ){
48074    case P4_KEYINFO_STATIC:
48075    case P4_KEYINFO: {
48076      int i, j;
48077      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
48078      sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
48079      i = sqlite3Strlen30(zTemp);
48080      for(j=0; j<pKeyInfo->nField; j++){
48081        CollSeq *pColl = pKeyInfo->aColl[j];
48082        if( pColl ){
48083          int n = sqlite3Strlen30(pColl->zName);
48084          if( i+n>nTemp-6 ){
48085            memcpy(&zTemp[i],",...",4);
48086            break;
48087          }
48088          zTemp[i++] = ',';
48089          if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
48090            zTemp[i++] = '-';
48091          }
48092          memcpy(&zTemp[i], pColl->zName,n+1);
48093          i += n;
48094        }else if( i+4<nTemp-6 ){
48095          memcpy(&zTemp[i],",nil",4);
48096          i += 4;
48097        }
48098      }
48099      zTemp[i++] = ')';
48100      zTemp[i] = 0;
48101      assert( i<nTemp );
48102      break;
48103    }
48104    case P4_COLLSEQ: {
48105      CollSeq *pColl = pOp->p4.pColl;
48106      sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
48107      break;
48108    }
48109    case P4_FUNCDEF: {
48110      FuncDef *pDef = pOp->p4.pFunc;
48111      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
48112      break;
48113    }
48114    case P4_INT64: {
48115      sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
48116      break;
48117    }
48118    case P4_INT32: {
48119      sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
48120      break;
48121    }
48122    case P4_REAL: {
48123      sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
48124      break;
48125    }
48126    case P4_MEM: {
48127      Mem *pMem = pOp->p4.pMem;
48128      assert( (pMem->flags & MEM_Null)==0 );
48129      if( pMem->flags & MEM_Str ){
48130        zP4 = pMem->z;
48131      }else if( pMem->flags & MEM_Int ){
48132        sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
48133      }else if( pMem->flags & MEM_Real ){
48134        sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
48135      }else{
48136        assert( pMem->flags & MEM_Blob );
48137        zP4 = "(blob)";
48138      }
48139      break;
48140    }
48141#ifndef SQLITE_OMIT_VIRTUALTABLE
48142    case P4_VTAB: {
48143      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
48144      sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
48145      break;
48146    }
48147#endif
48148    case P4_INTARRAY: {
48149      sqlite3_snprintf(nTemp, zTemp, "intarray");
48150      break;
48151    }
48152    case P4_SUBPROGRAM: {
48153      sqlite3_snprintf(nTemp, zTemp, "program");
48154      break;
48155    }
48156    default: {
48157      zP4 = pOp->p4.z;
48158      if( zP4==0 ){
48159        zP4 = zTemp;
48160        zTemp[0] = 0;
48161      }
48162    }
48163  }
48164  assert( zP4!=0 );
48165  return zP4;
48166}
48167#endif
48168
48169/*
48170** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
48171*/
48172SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
48173  int mask;
48174  assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
48175  assert( i<(int)sizeof(p->btreeMask)*8 );
48176  mask = ((u32)1)<<i;
48177  if( (p->btreeMask & mask)==0 ){
48178    p->btreeMask |= mask;
48179    sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
48180  }
48181}
48182
48183
48184#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
48185/*
48186** Print a single opcode.  This routine is used for debugging only.
48187*/
48188SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
48189  char *zP4;
48190  char zPtr[50];
48191  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
48192  if( pOut==0 ) pOut = stdout;
48193  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
48194  fprintf(pOut, zFormat1, pc,
48195      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
48196#ifdef SQLITE_DEBUG
48197      pOp->zComment ? pOp->zComment : ""
48198#else
48199      ""
48200#endif
48201  );
48202  fflush(pOut);
48203}
48204#endif
48205
48206/*
48207** Release an array of N Mem elements
48208*/
48209static void releaseMemArray(Mem *p, int N){
48210  if( p && N ){
48211    Mem *pEnd;
48212    sqlite3 *db = p->db;
48213    u8 malloc_failed = db->mallocFailed;
48214    for(pEnd=&p[N]; p<pEnd; p++){
48215      assert( (&p[1])==pEnd || p[0].db==p[1].db );
48216
48217      /* This block is really an inlined version of sqlite3VdbeMemRelease()
48218      ** that takes advantage of the fact that the memory cell value is
48219      ** being set to NULL after releasing any dynamic resources.
48220      **
48221      ** The justification for duplicating code is that according to
48222      ** callgrind, this causes a certain test case to hit the CPU 4.7
48223      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
48224      ** sqlite3MemRelease() were called from here. With -O2, this jumps
48225      ** to 6.6 percent. The test case is inserting 1000 rows into a table
48226      ** with no indexes using a single prepared INSERT statement, bind()
48227      ** and reset(). Inserts are grouped into a transaction.
48228      */
48229      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
48230        sqlite3VdbeMemRelease(p);
48231      }else if( p->zMalloc ){
48232        sqlite3DbFree(db, p->zMalloc);
48233        p->zMalloc = 0;
48234      }
48235
48236      p->flags = MEM_Null;
48237    }
48238    db->mallocFailed = malloc_failed;
48239  }
48240}
48241
48242/*
48243** Delete a VdbeFrame object and its contents. VdbeFrame objects are
48244** allocated by the OP_Program opcode in sqlite3VdbeExec().
48245*/
48246SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
48247  int i;
48248  Mem *aMem = VdbeFrameMem(p);
48249  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
48250  for(i=0; i<p->nChildCsr; i++){
48251    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
48252  }
48253  releaseMemArray(aMem, p->nChildMem);
48254  sqlite3DbFree(p->v->db, p);
48255}
48256
48257#ifndef SQLITE_OMIT_EXPLAIN
48258/*
48259** Give a listing of the program in the virtual machine.
48260**
48261** The interface is the same as sqlite3VdbeExec().  But instead of
48262** running the code, it invokes the callback once for each instruction.
48263** This feature is used to implement "EXPLAIN".
48264**
48265** When p->explain==1, each instruction is listed.  When
48266** p->explain==2, only OP_Explain instructions are listed and these
48267** are shown in a different format.  p->explain==2 is used to implement
48268** EXPLAIN QUERY PLAN.
48269**
48270** When p->explain==1, first the main program is listed, then each of
48271** the trigger subprograms are listed one by one.
48272*/
48273SQLITE_PRIVATE int sqlite3VdbeList(
48274  Vdbe *p                   /* The VDBE */
48275){
48276  int nRow;                            /* Stop when row count reaches this */
48277  int nSub = 0;                        /* Number of sub-vdbes seen so far */
48278  SubProgram **apSub = 0;              /* Array of sub-vdbes */
48279  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
48280  sqlite3 *db = p->db;                 /* The database connection */
48281  int i;                               /* Loop counter */
48282  int rc = SQLITE_OK;                  /* Return code */
48283  Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
48284
48285  assert( p->explain );
48286  assert( p->magic==VDBE_MAGIC_RUN );
48287  assert( db->magic==SQLITE_MAGIC_BUSY );
48288  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
48289
48290  /* Even though this opcode does not use dynamic strings for
48291  ** the result, result columns may become dynamic if the user calls
48292  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
48293  */
48294  releaseMemArray(pMem, 8);
48295
48296  if( p->rc==SQLITE_NOMEM ){
48297    /* This happens if a malloc() inside a call to sqlite3_column_text() or
48298    ** sqlite3_column_text16() failed.  */
48299    db->mallocFailed = 1;
48300    return SQLITE_ERROR;
48301  }
48302
48303  /* When the number of output rows reaches nRow, that means the
48304  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
48305  ** nRow is the sum of the number of rows in the main program, plus
48306  ** the sum of the number of rows in all trigger subprograms encountered
48307  ** so far.  The nRow value will increase as new trigger subprograms are
48308  ** encountered, but p->pc will eventually catch up to nRow.
48309  */
48310  nRow = p->nOp;
48311  if( p->explain==1 ){
48312    /* The first 8 memory cells are used for the result set.  So we will
48313    ** commandeer the 9th cell to use as storage for an array of pointers
48314    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
48315    ** cells.  */
48316    assert( p->nMem>9 );
48317    pSub = &p->aMem[9];
48318    if( pSub->flags&MEM_Blob ){
48319      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
48320      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
48321      nSub = pSub->n/sizeof(Vdbe*);
48322      apSub = (SubProgram **)pSub->z;
48323    }
48324    for(i=0; i<nSub; i++){
48325      nRow += apSub[i]->nOp;
48326    }
48327  }
48328
48329  do{
48330    i = p->pc++;
48331  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
48332  if( i>=nRow ){
48333    p->rc = SQLITE_OK;
48334    rc = SQLITE_DONE;
48335  }else if( db->u1.isInterrupted ){
48336    p->rc = SQLITE_INTERRUPT;
48337    rc = SQLITE_ERROR;
48338    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
48339  }else{
48340    char *z;
48341    Op *pOp;
48342    if( i<p->nOp ){
48343      /* The output line number is small enough that we are still in the
48344      ** main program. */
48345      pOp = &p->aOp[i];
48346    }else{
48347      /* We are currently listing subprograms.  Figure out which one and
48348      ** pick up the appropriate opcode. */
48349      int j;
48350      i -= p->nOp;
48351      for(j=0; i>=apSub[j]->nOp; j++){
48352        i -= apSub[j]->nOp;
48353      }
48354      pOp = &apSub[j]->aOp[i];
48355    }
48356    if( p->explain==1 ){
48357      pMem->flags = MEM_Int;
48358      pMem->type = SQLITE_INTEGER;
48359      pMem->u.i = i;                                /* Program counter */
48360      pMem++;
48361
48362      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
48363      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
48364      assert( pMem->z!=0 );
48365      pMem->n = sqlite3Strlen30(pMem->z);
48366      pMem->type = SQLITE_TEXT;
48367      pMem->enc = SQLITE_UTF8;
48368      pMem++;
48369
48370      /* When an OP_Program opcode is encounter (the only opcode that has
48371      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
48372      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
48373      ** has not already been seen.
48374      */
48375      if( pOp->p4type==P4_SUBPROGRAM ){
48376        int nByte = (nSub+1)*sizeof(SubProgram*);
48377        int j;
48378        for(j=0; j<nSub; j++){
48379          if( apSub[j]==pOp->p4.pProgram ) break;
48380        }
48381        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
48382          apSub = (SubProgram **)pSub->z;
48383          apSub[nSub++] = pOp->p4.pProgram;
48384          pSub->flags |= MEM_Blob;
48385          pSub->n = nSub*sizeof(SubProgram*);
48386        }
48387      }
48388    }
48389
48390    pMem->flags = MEM_Int;
48391    pMem->u.i = pOp->p1;                          /* P1 */
48392    pMem->type = SQLITE_INTEGER;
48393    pMem++;
48394
48395    pMem->flags = MEM_Int;
48396    pMem->u.i = pOp->p2;                          /* P2 */
48397    pMem->type = SQLITE_INTEGER;
48398    pMem++;
48399
48400    if( p->explain==1 ){
48401      pMem->flags = MEM_Int;
48402      pMem->u.i = pOp->p3;                          /* P3 */
48403      pMem->type = SQLITE_INTEGER;
48404      pMem++;
48405    }
48406
48407    if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
48408      assert( p->db->mallocFailed );
48409      return SQLITE_ERROR;
48410    }
48411    pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
48412    z = displayP4(pOp, pMem->z, 32);
48413    if( z!=pMem->z ){
48414      sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
48415    }else{
48416      assert( pMem->z!=0 );
48417      pMem->n = sqlite3Strlen30(pMem->z);
48418      pMem->enc = SQLITE_UTF8;
48419    }
48420    pMem->type = SQLITE_TEXT;
48421    pMem++;
48422
48423    if( p->explain==1 ){
48424      if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
48425        assert( p->db->mallocFailed );
48426        return SQLITE_ERROR;
48427      }
48428      pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
48429      pMem->n = 2;
48430      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
48431      pMem->type = SQLITE_TEXT;
48432      pMem->enc = SQLITE_UTF8;
48433      pMem++;
48434
48435#ifdef SQLITE_DEBUG
48436      if( pOp->zComment ){
48437        pMem->flags = MEM_Str|MEM_Term;
48438        pMem->z = pOp->zComment;
48439        pMem->n = sqlite3Strlen30(pMem->z);
48440        pMem->enc = SQLITE_UTF8;
48441        pMem->type = SQLITE_TEXT;
48442      }else
48443#endif
48444      {
48445        pMem->flags = MEM_Null;                       /* Comment */
48446        pMem->type = SQLITE_NULL;
48447      }
48448    }
48449
48450    p->nResColumn = 8 - 5*(p->explain-1);
48451    p->rc = SQLITE_OK;
48452    rc = SQLITE_ROW;
48453  }
48454  return rc;
48455}
48456#endif /* SQLITE_OMIT_EXPLAIN */
48457
48458#ifdef SQLITE_DEBUG
48459/*
48460** Print the SQL that was used to generate a VDBE program.
48461*/
48462SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
48463  int nOp = p->nOp;
48464  VdbeOp *pOp;
48465  if( nOp<1 ) return;
48466  pOp = &p->aOp[0];
48467  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
48468    const char *z = pOp->p4.z;
48469    while( sqlite3Isspace(*z) ) z++;
48470    printf("SQL: [%s]\n", z);
48471  }
48472}
48473#endif
48474
48475#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
48476/*
48477** Print an IOTRACE message showing SQL content.
48478*/
48479SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
48480  int nOp = p->nOp;
48481  VdbeOp *pOp;
48482  if( sqlite3IoTrace==0 ) return;
48483  if( nOp<1 ) return;
48484  pOp = &p->aOp[0];
48485  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
48486    int i, j;
48487    char z[1000];
48488    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
48489    for(i=0; sqlite3Isspace(z[i]); i++){}
48490    for(j=0; z[i]; i++){
48491      if( sqlite3Isspace(z[i]) ){
48492        if( z[i-1]!=' ' ){
48493          z[j++] = ' ';
48494        }
48495      }else{
48496        z[j++] = z[i];
48497      }
48498    }
48499    z[j] = 0;
48500    sqlite3IoTrace("SQL %s\n", z);
48501  }
48502}
48503#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
48504
48505/*
48506** Allocate space from a fixed size buffer and return a pointer to
48507** that space.  If insufficient space is available, return NULL.
48508**
48509** The pBuf parameter is the initial value of a pointer which will
48510** receive the new memory.  pBuf is normally NULL.  If pBuf is not
48511** NULL, it means that memory space has already been allocated and that
48512** this routine should not allocate any new memory.  When pBuf is not
48513** NULL simply return pBuf.  Only allocate new memory space when pBuf
48514** is NULL.
48515**
48516** nByte is the number of bytes of space needed.
48517**
48518** *ppFrom points to available space and pEnd points to the end of the
48519** available space.  When space is allocated, *ppFrom is advanced past
48520** the end of the allocated space.
48521**
48522** *pnByte is a counter of the number of bytes of space that have failed
48523** to allocate.  If there is insufficient space in *ppFrom to satisfy the
48524** request, then increment *pnByte by the amount of the request.
48525*/
48526static void *allocSpace(
48527  void *pBuf,          /* Where return pointer will be stored */
48528  int nByte,           /* Number of bytes to allocate */
48529  u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
48530  u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
48531  int *pnByte          /* If allocation cannot be made, increment *pnByte */
48532){
48533  assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
48534  if( pBuf ) return pBuf;
48535  nByte = ROUND8(nByte);
48536  if( &(*ppFrom)[nByte] <= pEnd ){
48537    pBuf = (void*)*ppFrom;
48538    *ppFrom += nByte;
48539  }else{
48540    *pnByte += nByte;
48541  }
48542  return pBuf;
48543}
48544
48545/*
48546** Prepare a virtual machine for execution.  This involves things such
48547** as allocating stack space and initializing the program counter.
48548** After the VDBE has be prepped, it can be executed by one or more
48549** calls to sqlite3VdbeExec().
48550**
48551** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
48552** VDBE_MAGIC_RUN.
48553**
48554** This function may be called more than once on a single virtual machine.
48555** The first call is made while compiling the SQL statement. Subsequent
48556** calls are made as part of the process of resetting a statement to be
48557** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor
48558** and isExplain parameters are only passed correct values the first time
48559** the function is called. On subsequent calls, from sqlite3_reset(), nVar
48560** is passed -1 and nMem, nCursor and isExplain are all passed zero.
48561*/
48562SQLITE_PRIVATE void sqlite3VdbeMakeReady(
48563  Vdbe *p,                       /* The VDBE */
48564  int nVar,                      /* Number of '?' see in the SQL statement */
48565  int nMem,                      /* Number of memory cells to allocate */
48566  int nCursor,                   /* Number of cursors to allocate */
48567  int nArg,                      /* Maximum number of args in SubPrograms */
48568  int isExplain,                 /* True if the EXPLAIN keywords is present */
48569  int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
48570){
48571  int n;
48572  sqlite3 *db = p->db;
48573
48574  assert( p!=0 );
48575  assert( p->magic==VDBE_MAGIC_INIT );
48576
48577  /* There should be at least one opcode.
48578  */
48579  assert( p->nOp>0 );
48580
48581  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
48582  p->magic = VDBE_MAGIC_RUN;
48583
48584  /* For each cursor required, also allocate a memory cell. Memory
48585  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
48586  ** the vdbe program. Instead they are used to allocate space for
48587  ** VdbeCursor/BtCursor structures. The blob of memory associated with
48588  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
48589  ** stores the blob of memory associated with cursor 1, etc.
48590  **
48591  ** See also: allocateCursor().
48592  */
48593  nMem += nCursor;
48594
48595  /* Allocate space for memory registers, SQL variables, VDBE cursors and
48596  ** an array to marshal SQL function arguments in. This is only done the
48597  ** first time this function is called for a given VDBE, not when it is
48598  ** being called from sqlite3_reset() to reset the virtual machine.
48599  */
48600  if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
48601    u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
48602    u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
48603    int nByte;                              /* How much extra memory needed */
48604
48605    resolveP2Values(p, &nArg);
48606    p->usesStmtJournal = (u8)usesStmtJournal;
48607    if( isExplain && nMem<10 ){
48608      nMem = 10;
48609    }
48610    memset(zCsr, 0, zEnd-zCsr);
48611    zCsr += (zCsr - (u8*)0)&7;
48612    assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
48613
48614    /* Memory for registers, parameters, cursor, etc, is allocated in two
48615    ** passes.  On the first pass, we try to reuse unused space at the
48616    ** end of the opcode array.  If we are unable to satisfy all memory
48617    ** requirements by reusing the opcode array tail, then the second
48618    ** pass will fill in the rest using a fresh allocation.
48619    **
48620    ** This two-pass approach that reuses as much memory as possible from
48621    ** the leftover space at the end of the opcode array can significantly
48622    ** reduce the amount of memory held by a prepared statement.
48623    */
48624    do {
48625      nByte = 0;
48626      p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
48627      p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
48628      p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
48629      p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
48630      p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
48631                            &zCsr, zEnd, &nByte);
48632      if( nByte ){
48633        p->pFree = sqlite3DbMallocZero(db, nByte);
48634      }
48635      zCsr = p->pFree;
48636      zEnd = &zCsr[nByte];
48637    }while( nByte && !db->mallocFailed );
48638
48639    p->nCursor = (u16)nCursor;
48640    if( p->aVar ){
48641      p->nVar = (ynVar)nVar;
48642      for(n=0; n<nVar; n++){
48643        p->aVar[n].flags = MEM_Null;
48644        p->aVar[n].db = db;
48645      }
48646    }
48647    if( p->aMem ){
48648      p->aMem--;                      /* aMem[] goes from 1..nMem */
48649      p->nMem = nMem;                 /*       not from 0..nMem-1 */
48650      for(n=1; n<=nMem; n++){
48651        p->aMem[n].flags = MEM_Null;
48652        p->aMem[n].db = db;
48653      }
48654    }
48655  }
48656#ifdef SQLITE_DEBUG
48657  for(n=1; n<p->nMem; n++){
48658    assert( p->aMem[n].db==db );
48659  }
48660#endif
48661
48662  p->pc = -1;
48663  p->rc = SQLITE_OK;
48664  p->errorAction = OE_Abort;
48665  p->explain |= isExplain;
48666  p->magic = VDBE_MAGIC_RUN;
48667  p->nChange = 0;
48668  p->cacheCtr = 1;
48669  p->minWriteFileFormat = 255;
48670  p->iStatement = 0;
48671#ifdef VDBE_PROFILE
48672  {
48673    int i;
48674    for(i=0; i<p->nOp; i++){
48675      p->aOp[i].cnt = 0;
48676      p->aOp[i].cycles = 0;
48677    }
48678  }
48679#endif
48680}
48681
48682/*
48683** Close a VDBE cursor and release all the resources that cursor
48684** happens to hold.
48685*/
48686SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
48687  if( pCx==0 ){
48688    return;
48689  }
48690  if( pCx->pBt ){
48691    sqlite3BtreeClose(pCx->pBt);
48692    /* The pCx->pCursor will be close automatically, if it exists, by
48693    ** the call above. */
48694  }else if( pCx->pCursor ){
48695    sqlite3BtreeCloseCursor(pCx->pCursor);
48696  }
48697#ifndef SQLITE_OMIT_VIRTUALTABLE
48698  if( pCx->pVtabCursor ){
48699    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
48700    const sqlite3_module *pModule = pCx->pModule;
48701    p->inVtabMethod = 1;
48702    (void)sqlite3SafetyOff(p->db);
48703    pModule->xClose(pVtabCursor);
48704    (void)sqlite3SafetyOn(p->db);
48705    p->inVtabMethod = 0;
48706  }
48707#endif
48708}
48709
48710/*
48711** Copy the values stored in the VdbeFrame structure to its Vdbe. This
48712** is used, for example, when a trigger sub-program is halted to restore
48713** control to the main program.
48714*/
48715SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
48716  Vdbe *v = pFrame->v;
48717  v->aOp = pFrame->aOp;
48718  v->nOp = pFrame->nOp;
48719  v->aMem = pFrame->aMem;
48720  v->nMem = pFrame->nMem;
48721  v->apCsr = pFrame->apCsr;
48722  v->nCursor = pFrame->nCursor;
48723  v->db->lastRowid = pFrame->lastRowid;
48724  v->nChange = pFrame->nChange;
48725  return pFrame->pc;
48726}
48727
48728/*
48729** Close all cursors.
48730**
48731** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
48732** cell array. This is necessary as the memory cell array may contain
48733** pointers to VdbeFrame objects, which may in turn contain pointers to
48734** open cursors.
48735*/
48736static void closeAllCursors(Vdbe *p){
48737  if( p->pFrame ){
48738    VdbeFrame *pFrame = p->pFrame;
48739    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
48740    sqlite3VdbeFrameRestore(pFrame);
48741  }
48742  p->pFrame = 0;
48743  p->nFrame = 0;
48744
48745  if( p->apCsr ){
48746    int i;
48747    for(i=0; i<p->nCursor; i++){
48748      VdbeCursor *pC = p->apCsr[i];
48749      if( pC ){
48750        sqlite3VdbeFreeCursor(p, pC);
48751        p->apCsr[i] = 0;
48752      }
48753    }
48754  }
48755  if( p->aMem ){
48756    releaseMemArray(&p->aMem[1], p->nMem);
48757  }
48758}
48759
48760/*
48761** Clean up the VM after execution.
48762**
48763** This routine will automatically close any cursors, lists, and/or
48764** sorters that were left open.  It also deletes the values of
48765** variables in the aVar[] array.
48766*/
48767static void Cleanup(Vdbe *p){
48768  sqlite3 *db = p->db;
48769
48770#ifdef SQLITE_DEBUG
48771  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
48772  ** Vdbe.aMem[] arrays have already been cleaned up.  */
48773  int i;
48774  for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
48775  for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
48776#endif
48777
48778  sqlite3DbFree(db, p->zErrMsg);
48779  p->zErrMsg = 0;
48780  p->pResultSet = 0;
48781}
48782
48783/*
48784** Set the number of result columns that will be returned by this SQL
48785** statement. This is now set at compile time, rather than during
48786** execution of the vdbe program so that sqlite3_column_count() can
48787** be called on an SQL statement before sqlite3_step().
48788*/
48789SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
48790  Mem *pColName;
48791  int n;
48792  sqlite3 *db = p->db;
48793
48794  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
48795  sqlite3DbFree(db, p->aColName);
48796  n = nResColumn*COLNAME_N;
48797  p->nResColumn = (u16)nResColumn;
48798  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
48799  if( p->aColName==0 ) return;
48800  while( n-- > 0 ){
48801    pColName->flags = MEM_Null;
48802    pColName->db = p->db;
48803    pColName++;
48804  }
48805}
48806
48807/*
48808** Set the name of the idx'th column to be returned by the SQL statement.
48809** zName must be a pointer to a nul terminated string.
48810**
48811** This call must be made after a call to sqlite3VdbeSetNumCols().
48812**
48813** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
48814** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
48815** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
48816*/
48817SQLITE_PRIVATE int sqlite3VdbeSetColName(
48818  Vdbe *p,                         /* Vdbe being configured */
48819  int idx,                         /* Index of column zName applies to */
48820  int var,                         /* One of the COLNAME_* constants */
48821  const char *zName,               /* Pointer to buffer containing name */
48822  void (*xDel)(void*)              /* Memory management strategy for zName */
48823){
48824  int rc;
48825  Mem *pColName;
48826  assert( idx<p->nResColumn );
48827  assert( var<COLNAME_N );
48828  if( p->db->mallocFailed ){
48829    assert( !zName || xDel!=SQLITE_DYNAMIC );
48830    return SQLITE_NOMEM;
48831  }
48832  assert( p->aColName!=0 );
48833  pColName = &(p->aColName[idx+var*p->nResColumn]);
48834  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
48835  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
48836  return rc;
48837}
48838
48839/*
48840** A read or write transaction may or may not be active on database handle
48841** db. If a transaction is active, commit it. If there is a
48842** write-transaction spanning more than one database file, this routine
48843** takes care of the master journal trickery.
48844*/
48845static int vdbeCommit(sqlite3 *db, Vdbe *p){
48846  int i;
48847  int nTrans = 0;  /* Number of databases with an active write-transaction */
48848  int rc = SQLITE_OK;
48849  int needXcommit = 0;
48850
48851#ifdef SQLITE_OMIT_VIRTUALTABLE
48852  /* With this option, sqlite3VtabSync() is defined to be simply
48853  ** SQLITE_OK so p is not used.
48854  */
48855  UNUSED_PARAMETER(p);
48856#endif
48857
48858  /* Before doing anything else, call the xSync() callback for any
48859  ** virtual module tables written in this transaction. This has to
48860  ** be done before determining whether a master journal file is
48861  ** required, as an xSync() callback may add an attached database
48862  ** to the transaction.
48863  */
48864  rc = sqlite3VtabSync(db, &p->zErrMsg);
48865  if( rc!=SQLITE_OK ){
48866    return rc;
48867  }
48868
48869  /* This loop determines (a) if the commit hook should be invoked and
48870  ** (b) how many database files have open write transactions, not
48871  ** including the temp database. (b) is important because if more than
48872  ** one database file has an open write transaction, a master journal
48873  ** file is required for an atomic commit.
48874  */
48875  for(i=0; i<db->nDb; i++){
48876    Btree *pBt = db->aDb[i].pBt;
48877    if( sqlite3BtreeIsInTrans(pBt) ){
48878      needXcommit = 1;
48879      if( i!=1 ) nTrans++;
48880    }
48881  }
48882
48883  /* If there are any write-transactions at all, invoke the commit hook */
48884  if( needXcommit && db->xCommitCallback ){
48885    (void)sqlite3SafetyOff(db);
48886    rc = db->xCommitCallback(db->pCommitArg);
48887    (void)sqlite3SafetyOn(db);
48888    if( rc ){
48889      return SQLITE_CONSTRAINT;
48890    }
48891  }
48892
48893  /* The simple case - no more than one database file (not counting the
48894  ** TEMP database) has a transaction active.   There is no need for the
48895  ** master-journal.
48896  **
48897  ** If the return value of sqlite3BtreeGetFilename() is a zero length
48898  ** string, it means the main database is :memory: or a temp file.  In
48899  ** that case we do not support atomic multi-file commits, so use the
48900  ** simple case then too.
48901  */
48902  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
48903   || nTrans<=1
48904  ){
48905    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
48906      Btree *pBt = db->aDb[i].pBt;
48907      if( pBt ){
48908        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
48909      }
48910    }
48911
48912    /* Do the commit only if all databases successfully complete phase 1.
48913    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
48914    ** IO error while deleting or truncating a journal file. It is unlikely,
48915    ** but could happen. In this case abandon processing and return the error.
48916    */
48917    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
48918      Btree *pBt = db->aDb[i].pBt;
48919      if( pBt ){
48920        rc = sqlite3BtreeCommitPhaseTwo(pBt);
48921      }
48922    }
48923    if( rc==SQLITE_OK ){
48924      sqlite3VtabCommit(db);
48925    }
48926  }
48927
48928  /* The complex case - There is a multi-file write-transaction active.
48929  ** This requires a master journal file to ensure the transaction is
48930  ** committed atomicly.
48931  */
48932#ifndef SQLITE_OMIT_DISKIO
48933  else{
48934    sqlite3_vfs *pVfs = db->pVfs;
48935    int needSync = 0;
48936    char *zMaster = 0;   /* File-name for the master journal */
48937    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
48938    sqlite3_file *pMaster = 0;
48939    i64 offset = 0;
48940    int res;
48941
48942    /* Select a master journal file name */
48943    do {
48944      u32 iRandom;
48945      sqlite3DbFree(db, zMaster);
48946      sqlite3_randomness(sizeof(iRandom), &iRandom);
48947      zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
48948      if( !zMaster ){
48949        return SQLITE_NOMEM;
48950      }
48951      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
48952    }while( rc==SQLITE_OK && res );
48953    if( rc==SQLITE_OK ){
48954      /* Open the master journal. */
48955      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
48956          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
48957          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
48958      );
48959    }
48960    if( rc!=SQLITE_OK ){
48961      sqlite3DbFree(db, zMaster);
48962      return rc;
48963    }
48964
48965    /* Write the name of each database file in the transaction into the new
48966    ** master journal file. If an error occurs at this point close
48967    ** and delete the master journal file. All the individual journal files
48968    ** still have 'null' as the master journal pointer, so they will roll
48969    ** back independently if a failure occurs.
48970    */
48971    for(i=0; i<db->nDb; i++){
48972      Btree *pBt = db->aDb[i].pBt;
48973      if( sqlite3BtreeIsInTrans(pBt) ){
48974        char const *zFile = sqlite3BtreeGetJournalname(pBt);
48975        if( zFile==0 || zFile[0]==0 ){
48976          continue;  /* Ignore TEMP and :memory: databases */
48977        }
48978        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
48979          needSync = 1;
48980        }
48981        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
48982        offset += sqlite3Strlen30(zFile)+1;
48983        if( rc!=SQLITE_OK ){
48984          sqlite3OsCloseFree(pMaster);
48985          sqlite3OsDelete(pVfs, zMaster, 0);
48986          sqlite3DbFree(db, zMaster);
48987          return rc;
48988        }
48989      }
48990    }
48991
48992    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
48993    ** flag is set this is not required.
48994    */
48995    if( needSync
48996     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
48997     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
48998    ){
48999      sqlite3OsCloseFree(pMaster);
49000      sqlite3OsDelete(pVfs, zMaster, 0);
49001      sqlite3DbFree(db, zMaster);
49002      return rc;
49003    }
49004
49005    /* Sync all the db files involved in the transaction. The same call
49006    ** sets the master journal pointer in each individual journal. If
49007    ** an error occurs here, do not delete the master journal file.
49008    **
49009    ** If the error occurs during the first call to
49010    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
49011    ** master journal file will be orphaned. But we cannot delete it,
49012    ** in case the master journal file name was written into the journal
49013    ** file before the failure occurred.
49014    */
49015    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
49016      Btree *pBt = db->aDb[i].pBt;
49017      if( pBt ){
49018        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
49019      }
49020    }
49021    sqlite3OsCloseFree(pMaster);
49022    if( rc!=SQLITE_OK ){
49023      sqlite3DbFree(db, zMaster);
49024      return rc;
49025    }
49026
49027    /* Delete the master journal file. This commits the transaction. After
49028    ** doing this the directory is synced again before any individual
49029    ** transaction files are deleted.
49030    */
49031    rc = sqlite3OsDelete(pVfs, zMaster, 1);
49032    sqlite3DbFree(db, zMaster);
49033    zMaster = 0;
49034    if( rc ){
49035      return rc;
49036    }
49037
49038    /* All files and directories have already been synced, so the following
49039    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
49040    ** deleting or truncating journals. If something goes wrong while
49041    ** this is happening we don't really care. The integrity of the
49042    ** transaction is already guaranteed, but some stray 'cold' journals
49043    ** may be lying around. Returning an error code won't help matters.
49044    */
49045    disable_simulated_io_errors();
49046    sqlite3BeginBenignMalloc();
49047    for(i=0; i<db->nDb; i++){
49048      Btree *pBt = db->aDb[i].pBt;
49049      if( pBt ){
49050        sqlite3BtreeCommitPhaseTwo(pBt);
49051      }
49052    }
49053    sqlite3EndBenignMalloc();
49054    enable_simulated_io_errors();
49055
49056    sqlite3VtabCommit(db);
49057  }
49058#endif
49059
49060  return rc;
49061}
49062
49063/*
49064** This routine checks that the sqlite3.activeVdbeCnt count variable
49065** matches the number of vdbe's in the list sqlite3.pVdbe that are
49066** currently active. An assertion fails if the two counts do not match.
49067** This is an internal self-check only - it is not an essential processing
49068** step.
49069**
49070** This is a no-op if NDEBUG is defined.
49071*/
49072#ifndef NDEBUG
49073static void checkActiveVdbeCnt(sqlite3 *db){
49074  Vdbe *p;
49075  int cnt = 0;
49076  int nWrite = 0;
49077  p = db->pVdbe;
49078  while( p ){
49079    if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
49080      cnt++;
49081      if( p->readOnly==0 ) nWrite++;
49082    }
49083    p = p->pNext;
49084  }
49085  assert( cnt==db->activeVdbeCnt );
49086  assert( nWrite==db->writeVdbeCnt );
49087}
49088#else
49089#define checkActiveVdbeCnt(x)
49090#endif
49091
49092/*
49093** For every Btree that in database connection db which
49094** has been modified, "trip" or invalidate each cursor in
49095** that Btree might have been modified so that the cursor
49096** can never be used again.  This happens when a rollback
49097*** occurs.  We have to trip all the other cursors, even
49098** cursor from other VMs in different database connections,
49099** so that none of them try to use the data at which they
49100** were pointing and which now may have been changed due
49101** to the rollback.
49102**
49103** Remember that a rollback can delete tables complete and
49104** reorder rootpages.  So it is not sufficient just to save
49105** the state of the cursor.  We have to invalidate the cursor
49106** so that it is never used again.
49107*/
49108static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
49109  int i;
49110  for(i=0; i<db->nDb; i++){
49111    Btree *p = db->aDb[i].pBt;
49112    if( p && sqlite3BtreeIsInTrans(p) ){
49113      sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
49114    }
49115  }
49116}
49117
49118/*
49119** If the Vdbe passed as the first argument opened a statement-transaction,
49120** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
49121** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
49122** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
49123** statement transaction is commtted.
49124**
49125** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
49126** Otherwise SQLITE_OK.
49127*/
49128SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
49129  sqlite3 *const db = p->db;
49130  int rc = SQLITE_OK;
49131
49132  /* If p->iStatement is greater than zero, then this Vdbe opened a
49133  ** statement transaction that should be closed here. The only exception
49134  ** is that an IO error may have occured, causing an emergency rollback.
49135  ** In this case (db->nStatement==0), and there is nothing to do.
49136  */
49137  if( db->nStatement && p->iStatement ){
49138    int i;
49139    const int iSavepoint = p->iStatement-1;
49140
49141    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
49142    assert( db->nStatement>0 );
49143    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
49144
49145    for(i=0; i<db->nDb; i++){
49146      int rc2 = SQLITE_OK;
49147      Btree *pBt = db->aDb[i].pBt;
49148      if( pBt ){
49149        if( eOp==SAVEPOINT_ROLLBACK ){
49150          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
49151        }
49152        if( rc2==SQLITE_OK ){
49153          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
49154        }
49155        if( rc==SQLITE_OK ){
49156          rc = rc2;
49157        }
49158      }
49159    }
49160    db->nStatement--;
49161    p->iStatement = 0;
49162
49163    /* If the statement transaction is being rolled back, also restore the
49164    ** database handles deferred constraint counter to the value it had when
49165    ** the statement transaction was opened.  */
49166    if( eOp==SAVEPOINT_ROLLBACK ){
49167      db->nDeferredCons = p->nStmtDefCons;
49168    }
49169  }
49170  return rc;
49171}
49172
49173/*
49174** If SQLite is compiled to support shared-cache mode and to be threadsafe,
49175** this routine obtains the mutex associated with each BtShared structure
49176** that may be accessed by the VM passed as an argument. In doing so it
49177** sets the BtShared.db member of each of the BtShared structures, ensuring
49178** that the correct busy-handler callback is invoked if required.
49179**
49180** If SQLite is not threadsafe but does support shared-cache mode, then
49181** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
49182** of all of BtShared structures accessible via the database handle
49183** associated with the VM. Of course only a subset of these structures
49184** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
49185** that subset out, but there is no advantage to doing so.
49186**
49187** If SQLite is not threadsafe and does not support shared-cache mode, this
49188** function is a no-op.
49189*/
49190#ifndef SQLITE_OMIT_SHARED_CACHE
49191SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p){
49192#if SQLITE_THREADSAFE
49193  sqlite3BtreeMutexArrayEnter(&p->aMutex);
49194#else
49195  sqlite3BtreeEnterAll(p->db);
49196#endif
49197}
49198#endif
49199
49200/*
49201** This function is called when a transaction opened by the database
49202** handle associated with the VM passed as an argument is about to be
49203** committed. If there are outstanding deferred foreign key constraint
49204** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
49205**
49206** If there are outstanding FK violations and this function returns
49207** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
49208** an error message to it. Then return SQLITE_ERROR.
49209*/
49210#ifndef SQLITE_OMIT_FOREIGN_KEY
49211SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
49212  sqlite3 *db = p->db;
49213  if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
49214    p->rc = SQLITE_CONSTRAINT;
49215    p->errorAction = OE_Abort;
49216    sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
49217    return SQLITE_ERROR;
49218  }
49219  return SQLITE_OK;
49220}
49221#endif
49222
49223/*
49224** This routine is called the when a VDBE tries to halt.  If the VDBE
49225** has made changes and is in autocommit mode, then commit those
49226** changes.  If a rollback is needed, then do the rollback.
49227**
49228** This routine is the only way to move the state of a VM from
49229** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
49230** call this on a VM that is in the SQLITE_MAGIC_HALT state.
49231**
49232** Return an error code.  If the commit could not complete because of
49233** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
49234** means the close did not happen and needs to be repeated.
49235*/
49236SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
49237  int rc;                         /* Used to store transient return codes */
49238  sqlite3 *db = p->db;
49239
49240  /* This function contains the logic that determines if a statement or
49241  ** transaction will be committed or rolled back as a result of the
49242  ** execution of this virtual machine.
49243  **
49244  ** If any of the following errors occur:
49245  **
49246  **     SQLITE_NOMEM
49247  **     SQLITE_IOERR
49248  **     SQLITE_FULL
49249  **     SQLITE_INTERRUPT
49250  **
49251  ** Then the internal cache might have been left in an inconsistent
49252  ** state.  We need to rollback the statement transaction, if there is
49253  ** one, or the complete transaction if there is no statement transaction.
49254  */
49255
49256  if( p->db->mallocFailed ){
49257    p->rc = SQLITE_NOMEM;
49258  }
49259  closeAllCursors(p);
49260  if( p->magic!=VDBE_MAGIC_RUN ){
49261    return SQLITE_OK;
49262  }
49263  checkActiveVdbeCnt(db);
49264
49265  /* No commit or rollback needed if the program never started */
49266  if( p->pc>=0 ){
49267    int mrc;   /* Primary error code from p->rc */
49268    int eStatementOp = 0;
49269    int isSpecialError;            /* Set to true if a 'special' error */
49270
49271    /* Lock all btrees used by the statement */
49272    sqlite3VdbeMutexArrayEnter(p);
49273
49274    /* Check for one of the special errors */
49275    mrc = p->rc & 0xff;
49276    assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
49277    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
49278                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
49279    if( isSpecialError ){
49280      /* If the query was read-only, we need do no rollback at all. Otherwise,
49281      ** proceed with the special handling.
49282      */
49283      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
49284        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
49285          eStatementOp = SAVEPOINT_ROLLBACK;
49286        }else{
49287          /* We are forced to roll back the active transaction. Before doing
49288          ** so, abort any other statements this handle currently has active.
49289          */
49290          invalidateCursorsOnModifiedBtrees(db);
49291          sqlite3RollbackAll(db);
49292          sqlite3CloseSavepoints(db);
49293          db->autoCommit = 1;
49294        }
49295      }
49296    }
49297
49298    /* Check for immediate foreign key violations. */
49299    if( p->rc==SQLITE_OK ){
49300      sqlite3VdbeCheckFk(p, 0);
49301    }
49302
49303    /* If the auto-commit flag is set and this is the only active writer
49304    ** VM, then we do either a commit or rollback of the current transaction.
49305    **
49306    ** Note: This block also runs if one of the special errors handled
49307    ** above has occurred.
49308    */
49309    if( !sqlite3VtabInSync(db)
49310     && db->autoCommit
49311     && db->writeVdbeCnt==(p->readOnly==0)
49312    ){
49313      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
49314        if( sqlite3VdbeCheckFk(p, 1) ){
49315          sqlite3BtreeMutexArrayLeave(&p->aMutex);
49316          return SQLITE_ERROR;
49317        }
49318        /* The auto-commit flag is true, the vdbe program was successful
49319        ** or hit an 'OR FAIL' constraint and there are no deferred foreign
49320        ** key constraints to hold up the transaction. This means a commit
49321        ** is required.  */
49322        rc = vdbeCommit(db, p);
49323        if( rc==SQLITE_BUSY ){
49324          sqlite3BtreeMutexArrayLeave(&p->aMutex);
49325          return SQLITE_BUSY;
49326        }else if( rc!=SQLITE_OK ){
49327          p->rc = rc;
49328          sqlite3RollbackAll(db);
49329        }else{
49330          db->nDeferredCons = 0;
49331          sqlite3CommitInternalChanges(db);
49332        }
49333      }else{
49334        sqlite3RollbackAll(db);
49335      }
49336      db->nStatement = 0;
49337    }else if( eStatementOp==0 ){
49338      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
49339        eStatementOp = SAVEPOINT_RELEASE;
49340      }else if( p->errorAction==OE_Abort ){
49341        eStatementOp = SAVEPOINT_ROLLBACK;
49342      }else{
49343        invalidateCursorsOnModifiedBtrees(db);
49344        sqlite3RollbackAll(db);
49345        sqlite3CloseSavepoints(db);
49346        db->autoCommit = 1;
49347      }
49348    }
49349
49350    /* If eStatementOp is non-zero, then a statement transaction needs to
49351    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
49352    ** do so. If this operation returns an error, and the current statement
49353    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then set the error
49354    ** code to the new value.
49355    */
49356    if( eStatementOp ){
49357      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
49358      if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
49359        p->rc = rc;
49360        sqlite3DbFree(db, p->zErrMsg);
49361        p->zErrMsg = 0;
49362      }
49363    }
49364
49365    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
49366    ** has been rolled back, update the database connection change-counter.
49367    */
49368    if( p->changeCntOn ){
49369      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
49370        sqlite3VdbeSetChanges(db, p->nChange);
49371      }else{
49372        sqlite3VdbeSetChanges(db, 0);
49373      }
49374      p->nChange = 0;
49375    }
49376
49377    /* Rollback or commit any schema changes that occurred. */
49378    if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
49379      sqlite3ResetInternalSchema(db, 0);
49380      db->flags = (db->flags | SQLITE_InternChanges);
49381    }
49382
49383    /* Release the locks */
49384    sqlite3BtreeMutexArrayLeave(&p->aMutex);
49385  }
49386
49387  /* We have successfully halted and closed the VM.  Record this fact. */
49388  if( p->pc>=0 ){
49389    db->activeVdbeCnt--;
49390    if( !p->readOnly ){
49391      db->writeVdbeCnt--;
49392    }
49393    assert( db->activeVdbeCnt>=db->writeVdbeCnt );
49394  }
49395  p->magic = VDBE_MAGIC_HALT;
49396  checkActiveVdbeCnt(db);
49397  if( p->db->mallocFailed ){
49398    p->rc = SQLITE_NOMEM;
49399  }
49400
49401  /* If the auto-commit flag is set to true, then any locks that were held
49402  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
49403  ** to invoke any required unlock-notify callbacks.
49404  */
49405  if( db->autoCommit ){
49406    sqlite3ConnectionUnlocked(db);
49407  }
49408
49409  assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
49410  return SQLITE_OK;
49411}
49412
49413
49414/*
49415** Each VDBE holds the result of the most recent sqlite3_step() call
49416** in p->rc.  This routine sets that result back to SQLITE_OK.
49417*/
49418SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
49419  p->rc = SQLITE_OK;
49420}
49421
49422/*
49423** Clean up a VDBE after execution but do not delete the VDBE just yet.
49424** Write any error messages into *pzErrMsg.  Return the result code.
49425**
49426** After this routine is run, the VDBE should be ready to be executed
49427** again.
49428**
49429** To look at it another way, this routine resets the state of the
49430** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
49431** VDBE_MAGIC_INIT.
49432*/
49433SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
49434  sqlite3 *db;
49435  db = p->db;
49436
49437  /* If the VM did not run to completion or if it encountered an
49438  ** error, then it might not have been halted properly.  So halt
49439  ** it now.
49440  */
49441  (void)sqlite3SafetyOn(db);
49442  sqlite3VdbeHalt(p);
49443  (void)sqlite3SafetyOff(db);
49444
49445  /* If the VDBE has be run even partially, then transfer the error code
49446  ** and error message from the VDBE into the main database structure.  But
49447  ** if the VDBE has just been set to run but has not actually executed any
49448  ** instructions yet, leave the main database error information unchanged.
49449  */
49450  if( p->pc>=0 ){
49451    if( p->zErrMsg ){
49452      sqlite3BeginBenignMalloc();
49453      sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
49454      sqlite3EndBenignMalloc();
49455      db->errCode = p->rc;
49456      sqlite3DbFree(db, p->zErrMsg);
49457      p->zErrMsg = 0;
49458    }else if( p->rc ){
49459      sqlite3Error(db, p->rc, 0);
49460    }else{
49461      sqlite3Error(db, SQLITE_OK, 0);
49462    }
49463  }else if( p->rc && p->expired ){
49464    /* The expired flag was set on the VDBE before the first call
49465    ** to sqlite3_step(). For consistency (since sqlite3_step() was
49466    ** called), set the database error in this case as well.
49467    */
49468    sqlite3Error(db, p->rc, 0);
49469    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
49470    sqlite3DbFree(db, p->zErrMsg);
49471    p->zErrMsg = 0;
49472  }
49473
49474  /* Reclaim all memory used by the VDBE
49475  */
49476  Cleanup(p);
49477
49478  /* Save profiling information from this VDBE run.
49479  */
49480#ifdef VDBE_PROFILE
49481  {
49482    FILE *out = fopen("vdbe_profile.out", "a");
49483    if( out ){
49484      int i;
49485      fprintf(out, "---- ");
49486      for(i=0; i<p->nOp; i++){
49487        fprintf(out, "%02x", p->aOp[i].opcode);
49488      }
49489      fprintf(out, "\n");
49490      for(i=0; i<p->nOp; i++){
49491        fprintf(out, "%6d %10lld %8lld ",
49492           p->aOp[i].cnt,
49493           p->aOp[i].cycles,
49494           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
49495        );
49496        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
49497      }
49498      fclose(out);
49499    }
49500  }
49501#endif
49502  p->magic = VDBE_MAGIC_INIT;
49503  return p->rc & db->errMask;
49504}
49505
49506/*
49507** Clean up and delete a VDBE after execution.  Return an integer which is
49508** the result code.  Write any error message text into *pzErrMsg.
49509*/
49510SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
49511  int rc = SQLITE_OK;
49512  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
49513    rc = sqlite3VdbeReset(p);
49514    assert( (rc & p->db->errMask)==rc );
49515  }
49516  sqlite3VdbeDelete(p);
49517  return rc;
49518}
49519
49520/*
49521** Call the destructor for each auxdata entry in pVdbeFunc for which
49522** the corresponding bit in mask is clear.  Auxdata entries beyond 31
49523** are always destroyed.  To destroy all auxdata entries, call this
49524** routine with mask==0.
49525*/
49526SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
49527  int i;
49528  for(i=0; i<pVdbeFunc->nAux; i++){
49529    struct AuxData *pAux = &pVdbeFunc->apAux[i];
49530    if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
49531      if( pAux->xDelete ){
49532        pAux->xDelete(pAux->pAux);
49533      }
49534      pAux->pAux = 0;
49535    }
49536  }
49537}
49538
49539/*
49540** Delete an entire VDBE.
49541*/
49542SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
49543  sqlite3 *db;
49544
49545  if( NEVER(p==0) ) return;
49546  db = p->db;
49547  if( p->pPrev ){
49548    p->pPrev->pNext = p->pNext;
49549  }else{
49550    assert( db->pVdbe==p );
49551    db->pVdbe = p->pNext;
49552  }
49553  if( p->pNext ){
49554    p->pNext->pPrev = p->pPrev;
49555  }
49556  releaseMemArray(p->aVar, p->nVar);
49557  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
49558  vdbeFreeOpArray(db, p->aOp, p->nOp);
49559  sqlite3DbFree(db, p->aLabel);
49560  sqlite3DbFree(db, p->aColName);
49561  sqlite3DbFree(db, p->zSql);
49562  p->magic = VDBE_MAGIC_DEAD;
49563  sqlite3DbFree(db, p->pFree);
49564  sqlite3DbFree(db, p);
49565}
49566
49567/*
49568** Make sure the cursor p is ready to read or write the row to which it
49569** was last positioned.  Return an error code if an OOM fault or I/O error
49570** prevents us from positioning the cursor to its correct position.
49571**
49572** If a MoveTo operation is pending on the given cursor, then do that
49573** MoveTo now.  If no move is pending, check to see if the row has been
49574** deleted out from under the cursor and if it has, mark the row as
49575** a NULL row.
49576**
49577** If the cursor is already pointing to the correct row and that row has
49578** not been deleted out from under the cursor, then this routine is a no-op.
49579*/
49580SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
49581  if( p->deferredMoveto ){
49582    int res, rc;
49583#ifdef SQLITE_TEST
49584    extern int sqlite3_search_count;
49585#endif
49586    assert( p->isTable );
49587    rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
49588    if( rc ) return rc;
49589    p->lastRowid = p->movetoTarget;
49590    p->rowidIsValid = ALWAYS(res==0) ?1:0;
49591    if( NEVER(res<0) ){
49592      rc = sqlite3BtreeNext(p->pCursor, &res);
49593      if( rc ) return rc;
49594    }
49595#ifdef SQLITE_TEST
49596    sqlite3_search_count++;
49597#endif
49598    p->deferredMoveto = 0;
49599    p->cacheStatus = CACHE_STALE;
49600  }else if( ALWAYS(p->pCursor) ){
49601    int hasMoved;
49602    int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
49603    if( rc ) return rc;
49604    if( hasMoved ){
49605      p->cacheStatus = CACHE_STALE;
49606      p->nullRow = 1;
49607    }
49608  }
49609  return SQLITE_OK;
49610}
49611
49612/*
49613** The following functions:
49614**
49615** sqlite3VdbeSerialType()
49616** sqlite3VdbeSerialTypeLen()
49617** sqlite3VdbeSerialLen()
49618** sqlite3VdbeSerialPut()
49619** sqlite3VdbeSerialGet()
49620**
49621** encapsulate the code that serializes values for storage in SQLite
49622** data and index records. Each serialized value consists of a
49623** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
49624** integer, stored as a varint.
49625**
49626** In an SQLite index record, the serial type is stored directly before
49627** the blob of data that it corresponds to. In a table record, all serial
49628** types are stored at the start of the record, and the blobs of data at
49629** the end. Hence these functions allow the caller to handle the
49630** serial-type and data blob seperately.
49631**
49632** The following table describes the various storage classes for data:
49633**
49634**   serial type        bytes of data      type
49635**   --------------     ---------------    ---------------
49636**      0                     0            NULL
49637**      1                     1            signed integer
49638**      2                     2            signed integer
49639**      3                     3            signed integer
49640**      4                     4            signed integer
49641**      5                     6            signed integer
49642**      6                     8            signed integer
49643**      7                     8            IEEE float
49644**      8                     0            Integer constant 0
49645**      9                     0            Integer constant 1
49646**     10,11                               reserved for expansion
49647**    N>=12 and even       (N-12)/2        BLOB
49648**    N>=13 and odd        (N-13)/2        text
49649**
49650** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
49651** of SQLite will not understand those serial types.
49652*/
49653
49654/*
49655** Return the serial-type for the value stored in pMem.
49656*/
49657SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
49658  int flags = pMem->flags;
49659  int n;
49660
49661  if( flags&MEM_Null ){
49662    return 0;
49663  }
49664  if( flags&MEM_Int ){
49665    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
49666#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
49667    i64 i = pMem->u.i;
49668    u64 u;
49669    if( file_format>=4 && (i&1)==i ){
49670      return 8+(u32)i;
49671    }
49672    u = i<0 ? -i : i;
49673    if( u<=127 ) return 1;
49674    if( u<=32767 ) return 2;
49675    if( u<=8388607 ) return 3;
49676    if( u<=2147483647 ) return 4;
49677    if( u<=MAX_6BYTE ) return 5;
49678    return 6;
49679  }
49680  if( flags&MEM_Real ){
49681    return 7;
49682  }
49683  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
49684  n = pMem->n;
49685  if( flags & MEM_Zero ){
49686    n += pMem->u.nZero;
49687  }
49688  assert( n>=0 );
49689  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
49690}
49691
49692/*
49693** Return the length of the data corresponding to the supplied serial-type.
49694*/
49695SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
49696  if( serial_type>=12 ){
49697    return (serial_type-12)/2;
49698  }else{
49699    static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
49700    return aSize[serial_type];
49701  }
49702}
49703
49704/*
49705** If we are on an architecture with mixed-endian floating
49706** points (ex: ARM7) then swap the lower 4 bytes with the
49707** upper 4 bytes.  Return the result.
49708**
49709** For most architectures, this is a no-op.
49710**
49711** (later):  It is reported to me that the mixed-endian problem
49712** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
49713** that early versions of GCC stored the two words of a 64-bit
49714** float in the wrong order.  And that error has been propagated
49715** ever since.  The blame is not necessarily with GCC, though.
49716** GCC might have just copying the problem from a prior compiler.
49717** I am also told that newer versions of GCC that follow a different
49718** ABI get the byte order right.
49719**
49720** Developers using SQLite on an ARM7 should compile and run their
49721** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
49722** enabled, some asserts below will ensure that the byte order of
49723** floating point values is correct.
49724**
49725** (2007-08-30)  Frank van Vugt has studied this problem closely
49726** and has send his findings to the SQLite developers.  Frank
49727** writes that some Linux kernels offer floating point hardware
49728** emulation that uses only 32-bit mantissas instead of a full
49729** 48-bits as required by the IEEE standard.  (This is the
49730** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
49731** byte swapping becomes very complicated.  To avoid problems,
49732** the necessary byte swapping is carried out using a 64-bit integer
49733** rather than a 64-bit float.  Frank assures us that the code here
49734** works for him.  We, the developers, have no way to independently
49735** verify this, but Frank seems to know what he is talking about
49736** so we trust him.
49737*/
49738#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
49739static u64 floatSwap(u64 in){
49740  union {
49741    u64 r;
49742    u32 i[2];
49743  } u;
49744  u32 t;
49745
49746  u.r = in;
49747  t = u.i[0];
49748  u.i[0] = u.i[1];
49749  u.i[1] = t;
49750  return u.r;
49751}
49752# define swapMixedEndianFloat(X)  X = floatSwap(X)
49753#else
49754# define swapMixedEndianFloat(X)
49755#endif
49756
49757/*
49758** Write the serialized data blob for the value stored in pMem into
49759** buf. It is assumed that the caller has allocated sufficient space.
49760** Return the number of bytes written.
49761**
49762** nBuf is the amount of space left in buf[].  nBuf must always be
49763** large enough to hold the entire field.  Except, if the field is
49764** a blob with a zero-filled tail, then buf[] might be just the right
49765** size to hold everything except for the zero-filled tail.  If buf[]
49766** is only big enough to hold the non-zero prefix, then only write that
49767** prefix into buf[].  But if buf[] is large enough to hold both the
49768** prefix and the tail then write the prefix and set the tail to all
49769** zeros.
49770**
49771** Return the number of bytes actually written into buf[].  The number
49772** of bytes in the zero-filled tail is included in the return value only
49773** if those bytes were zeroed in buf[].
49774*/
49775SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
49776  u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
49777  u32 len;
49778
49779  /* Integer and Real */
49780  if( serial_type<=7 && serial_type>0 ){
49781    u64 v;
49782    u32 i;
49783    if( serial_type==7 ){
49784      assert( sizeof(v)==sizeof(pMem->r) );
49785      memcpy(&v, &pMem->r, sizeof(v));
49786      swapMixedEndianFloat(v);
49787    }else{
49788      v = pMem->u.i;
49789    }
49790    len = i = sqlite3VdbeSerialTypeLen(serial_type);
49791    assert( len<=(u32)nBuf );
49792    while( i-- ){
49793      buf[i] = (u8)(v&0xFF);
49794      v >>= 8;
49795    }
49796    return len;
49797  }
49798
49799  /* String or blob */
49800  if( serial_type>=12 ){
49801    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
49802             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
49803    assert( pMem->n<=nBuf );
49804    len = pMem->n;
49805    memcpy(buf, pMem->z, len);
49806    if( pMem->flags & MEM_Zero ){
49807      len += pMem->u.nZero;
49808      assert( nBuf>=0 );
49809      if( len > (u32)nBuf ){
49810        len = (u32)nBuf;
49811      }
49812      memset(&buf[pMem->n], 0, len-pMem->n);
49813    }
49814    return len;
49815  }
49816
49817  /* NULL or constants 0 or 1 */
49818  return 0;
49819}
49820
49821/*
49822** Deserialize the data blob pointed to by buf as serial type serial_type
49823** and store the result in pMem.  Return the number of bytes read.
49824*/
49825SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
49826  const unsigned char *buf,     /* Buffer to deserialize from */
49827  u32 serial_type,              /* Serial type to deserialize */
49828  Mem *pMem                     /* Memory cell to write value into */
49829){
49830  switch( serial_type ){
49831    case 10:   /* Reserved for future use */
49832    case 11:   /* Reserved for future use */
49833    case 0: {  /* NULL */
49834      pMem->flags = MEM_Null;
49835      break;
49836    }
49837    case 1: { /* 1-byte signed integer */
49838      pMem->u.i = (signed char)buf[0];
49839      pMem->flags = MEM_Int;
49840      return 1;
49841    }
49842    case 2: { /* 2-byte signed integer */
49843      pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
49844      pMem->flags = MEM_Int;
49845      return 2;
49846    }
49847    case 3: { /* 3-byte signed integer */
49848      pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
49849      pMem->flags = MEM_Int;
49850      return 3;
49851    }
49852    case 4: { /* 4-byte signed integer */
49853      pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
49854      pMem->flags = MEM_Int;
49855      return 4;
49856    }
49857    case 5: { /* 6-byte signed integer */
49858      u64 x = (((signed char)buf[0])<<8) | buf[1];
49859      u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
49860      x = (x<<32) | y;
49861      pMem->u.i = *(i64*)&x;
49862      pMem->flags = MEM_Int;
49863      return 6;
49864    }
49865    case 6:   /* 8-byte signed integer */
49866    case 7: { /* IEEE floating point */
49867      u64 x;
49868      u32 y;
49869#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
49870      /* Verify that integers and floating point values use the same
49871      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
49872      ** defined that 64-bit floating point values really are mixed
49873      ** endian.
49874      */
49875      static const u64 t1 = ((u64)0x3ff00000)<<32;
49876      static const double r1 = 1.0;
49877      u64 t2 = t1;
49878      swapMixedEndianFloat(t2);
49879      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
49880#endif
49881
49882      x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
49883      y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
49884      x = (x<<32) | y;
49885      if( serial_type==6 ){
49886        pMem->u.i = *(i64*)&x;
49887        pMem->flags = MEM_Int;
49888      }else{
49889        assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
49890        swapMixedEndianFloat(x);
49891        memcpy(&pMem->r, &x, sizeof(x));
49892        pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
49893      }
49894      return 8;
49895    }
49896    case 8:    /* Integer 0 */
49897    case 9: {  /* Integer 1 */
49898      pMem->u.i = serial_type-8;
49899      pMem->flags = MEM_Int;
49900      return 0;
49901    }
49902    default: {
49903      u32 len = (serial_type-12)/2;
49904      pMem->z = (char *)buf;
49905      pMem->n = len;
49906      pMem->xDel = 0;
49907      if( serial_type&0x01 ){
49908        pMem->flags = MEM_Str | MEM_Ephem;
49909      }else{
49910        pMem->flags = MEM_Blob | MEM_Ephem;
49911      }
49912      return len;
49913    }
49914  }
49915  return 0;
49916}
49917
49918
49919/*
49920** Given the nKey-byte encoding of a record in pKey[], parse the
49921** record into a UnpackedRecord structure.  Return a pointer to
49922** that structure.
49923**
49924** The calling function might provide szSpace bytes of memory
49925** space at pSpace.  This space can be used to hold the returned
49926** VDbeParsedRecord structure if it is large enough.  If it is
49927** not big enough, space is obtained from sqlite3_malloc().
49928**
49929** The returned structure should be closed by a call to
49930** sqlite3VdbeDeleteUnpackedRecord().
49931*/
49932SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
49933  KeyInfo *pKeyInfo,     /* Information about the record format */
49934  int nKey,              /* Size of the binary record */
49935  const void *pKey,      /* The binary record */
49936  char *pSpace,          /* Unaligned space available to hold the object */
49937  int szSpace            /* Size of pSpace[] in bytes */
49938){
49939  const unsigned char *aKey = (const unsigned char *)pKey;
49940  UnpackedRecord *p;  /* The unpacked record that we will return */
49941  int nByte;          /* Memory space needed to hold p, in bytes */
49942  int d;
49943  u32 idx;
49944  u16 u;              /* Unsigned loop counter */
49945  u32 szHdr;
49946  Mem *pMem;
49947  int nOff;           /* Increase pSpace by this much to 8-byte align it */
49948
49949  /*
49950  ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
49951  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
49952  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
49953  */
49954  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
49955  pSpace += nOff;
49956  szSpace -= nOff;
49957  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
49958  if( nByte>szSpace ){
49959    p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
49960    if( p==0 ) return 0;
49961    p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
49962  }else{
49963    p = (UnpackedRecord*)pSpace;
49964    p->flags = UNPACKED_NEED_DESTROY;
49965  }
49966  p->pKeyInfo = pKeyInfo;
49967  p->nField = pKeyInfo->nField + 1;
49968  p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
49969  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
49970  idx = getVarint32(aKey, szHdr);
49971  d = szHdr;
49972  u = 0;
49973  while( idx<szHdr && u<p->nField && d<=nKey ){
49974    u32 serial_type;
49975
49976    idx += getVarint32(&aKey[idx], serial_type);
49977    pMem->enc = pKeyInfo->enc;
49978    pMem->db = pKeyInfo->db;
49979    pMem->flags = 0;
49980    pMem->zMalloc = 0;
49981    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
49982    pMem++;
49983    u++;
49984  }
49985  assert( u<=pKeyInfo->nField + 1 );
49986  p->nField = u;
49987  return (void*)p;
49988}
49989
49990/*
49991** This routine destroys a UnpackedRecord object.
49992*/
49993SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
49994  int i;
49995  Mem *pMem;
49996
49997  assert( p!=0 );
49998  assert( p->flags & UNPACKED_NEED_DESTROY );
49999  for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
50000    /* The unpacked record is always constructed by the
50001    ** sqlite3VdbeUnpackRecord() function above, which makes all
50002    ** strings and blobs static.  And none of the elements are
50003    ** ever transformed, so there is never anything to delete.
50004    */
50005    if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
50006  }
50007  if( p->flags & UNPACKED_NEED_FREE ){
50008    sqlite3DbFree(p->pKeyInfo->db, p);
50009  }
50010}
50011
50012/*
50013** This function compares the two table rows or index records
50014** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
50015** or positive integer if key1 is less than, equal to or
50016** greater than key2.  The {nKey1, pKey1} key must be a blob
50017** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
50018** key must be a parsed key such as obtained from
50019** sqlite3VdbeParseRecord.
50020**
50021** Key1 and Key2 do not have to contain the same number of fields.
50022** The key with fewer fields is usually compares less than the
50023** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
50024** and the common prefixes are equal, then key1 is less than key2.
50025** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
50026** equal, then the keys are considered to be equal and
50027** the parts beyond the common prefix are ignored.
50028**
50029** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
50030** the header of pKey1 is ignored.  It is assumed that pKey1 is
50031** an index key, and thus ends with a rowid value.  The last byte
50032** of the header will therefore be the serial type of the rowid:
50033** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
50034** The serial type of the final rowid will always be a single byte.
50035** By ignoring this last byte of the header, we force the comparison
50036** to ignore the rowid at the end of key1.
50037*/
50038SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
50039  int nKey1, const void *pKey1, /* Left key */
50040  UnpackedRecord *pPKey2        /* Right key */
50041){
50042  int d1;            /* Offset into aKey[] of next data element */
50043  u32 idx1;          /* Offset into aKey[] of next header element */
50044  u32 szHdr1;        /* Number of bytes in header */
50045  int i = 0;
50046  int nField;
50047  int rc = 0;
50048  const unsigned char *aKey1 = (const unsigned char *)pKey1;
50049  KeyInfo *pKeyInfo;
50050  Mem mem1;
50051
50052  pKeyInfo = pPKey2->pKeyInfo;
50053  mem1.enc = pKeyInfo->enc;
50054  mem1.db = pKeyInfo->db;
50055  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
50056  VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
50057
50058  /* Compilers may complain that mem1.u.i is potentially uninitialized.
50059  ** We could initialize it, as shown here, to silence those complaints.
50060  ** But in fact, mem1.u.i will never actually be used initialized, and doing
50061  ** the unnecessary initialization has a measurable negative performance
50062  ** impact, since this routine is a very high runner.  And so, we choose
50063  ** to ignore the compiler warnings and leave this variable uninitialized.
50064  */
50065  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
50066
50067  idx1 = getVarint32(aKey1, szHdr1);
50068  d1 = szHdr1;
50069  if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
50070    szHdr1--;
50071  }
50072  nField = pKeyInfo->nField;
50073  while( idx1<szHdr1 && i<pPKey2->nField ){
50074    u32 serial_type1;
50075
50076    /* Read the serial types for the next element in each key. */
50077    idx1 += getVarint32( aKey1+idx1, serial_type1 );
50078    if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
50079
50080    /* Extract the values to be compared.
50081    */
50082    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
50083
50084    /* Do the comparison
50085    */
50086    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
50087                           i<nField ? pKeyInfo->aColl[i] : 0);
50088    if( rc!=0 ){
50089      assert( mem1.zMalloc==0 );  /* See comment below */
50090
50091      /* Invert the result if we are using DESC sort order. */
50092      if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
50093        rc = -rc;
50094      }
50095
50096      /* If the PREFIX_SEARCH flag is set and all fields except the final
50097      ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
50098      ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
50099      ** This is used by the OP_IsUnique opcode.
50100      */
50101      if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
50102        assert( idx1==szHdr1 && rc );
50103        assert( mem1.flags & MEM_Int );
50104        pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
50105        pPKey2->rowid = mem1.u.i;
50106      }
50107
50108      return rc;
50109    }
50110    i++;
50111  }
50112
50113  /* No memory allocation is ever used on mem1.  Prove this using
50114  ** the following assert().  If the assert() fails, it indicates a
50115  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
50116  */
50117  assert( mem1.zMalloc==0 );
50118
50119  /* rc==0 here means that one of the keys ran out of fields and
50120  ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
50121  ** flag is set, then break the tie by treating key2 as larger.
50122  ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
50123  ** are considered to be equal.  Otherwise, the longer key is the
50124  ** larger.  As it happens, the pPKey2 will always be the longer
50125  ** if there is a difference.
50126  */
50127  assert( rc==0 );
50128  if( pPKey2->flags & UNPACKED_INCRKEY ){
50129    rc = -1;
50130  }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
50131    /* Leave rc==0 */
50132  }else if( idx1<szHdr1 ){
50133    rc = 1;
50134  }
50135  return rc;
50136}
50137
50138
50139/*
50140** pCur points at an index entry created using the OP_MakeRecord opcode.
50141** Read the rowid (the last field in the record) and store it in *rowid.
50142** Return SQLITE_OK if everything works, or an error code otherwise.
50143**
50144** pCur might be pointing to text obtained from a corrupt database file.
50145** So the content cannot be trusted.  Do appropriate checks on the content.
50146*/
50147SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
50148  i64 nCellKey = 0;
50149  int rc;
50150  u32 szHdr;        /* Size of the header */
50151  u32 typeRowid;    /* Serial type of the rowid */
50152  u32 lenRowid;     /* Size of the rowid */
50153  Mem m, v;
50154
50155  UNUSED_PARAMETER(db);
50156
50157  /* Get the size of the index entry.  Only indices entries of less
50158  ** than 2GiB are support - anything large must be database corruption.
50159  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
50160  ** this code can safely assume that nCellKey is 32-bits
50161  */
50162  assert( sqlite3BtreeCursorIsValid(pCur) );
50163  rc = sqlite3BtreeKeySize(pCur, &nCellKey);
50164  assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
50165  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
50166
50167  /* Read in the complete content of the index entry */
50168  memset(&m, 0, sizeof(m));
50169  rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
50170  if( rc ){
50171    return rc;
50172  }
50173
50174  /* The index entry must begin with a header size */
50175  (void)getVarint32((u8*)m.z, szHdr);
50176  testcase( szHdr==3 );
50177  testcase( szHdr==m.n );
50178  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
50179    goto idx_rowid_corruption;
50180  }
50181
50182  /* The last field of the index should be an integer - the ROWID.
50183  ** Verify that the last entry really is an integer. */
50184  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
50185  testcase( typeRowid==1 );
50186  testcase( typeRowid==2 );
50187  testcase( typeRowid==3 );
50188  testcase( typeRowid==4 );
50189  testcase( typeRowid==5 );
50190  testcase( typeRowid==6 );
50191  testcase( typeRowid==8 );
50192  testcase( typeRowid==9 );
50193  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
50194    goto idx_rowid_corruption;
50195  }
50196  lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
50197  testcase( (u32)m.n==szHdr+lenRowid );
50198  if( unlikely((u32)m.n<szHdr+lenRowid) ){
50199    goto idx_rowid_corruption;
50200  }
50201
50202  /* Fetch the integer off the end of the index record */
50203  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
50204  *rowid = v.u.i;
50205  sqlite3VdbeMemRelease(&m);
50206  return SQLITE_OK;
50207
50208  /* Jump here if database corruption is detected after m has been
50209  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
50210idx_rowid_corruption:
50211  testcase( m.zMalloc!=0 );
50212  sqlite3VdbeMemRelease(&m);
50213  return SQLITE_CORRUPT_BKPT(VDBE_INDEX_ROWID_CORRUPTION); // Android Change
50214}
50215
50216/*
50217** Compare the key of the index entry that cursor pC is pointing to against
50218** the key string in pUnpacked.  Write into *pRes a number
50219** that is negative, zero, or positive if pC is less than, equal to,
50220** or greater than pUnpacked.  Return SQLITE_OK on success.
50221**
50222** pUnpacked is either created without a rowid or is truncated so that it
50223** omits the rowid at the end.  The rowid at the end of the index entry
50224** is ignored as well.  Hence, this routine only compares the prefixes
50225** of the keys prior to the final rowid, not the entire key.
50226*/
50227SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
50228  VdbeCursor *pC,             /* The cursor to compare against */
50229  UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
50230  int *res                    /* Write the comparison result here */
50231){
50232  i64 nCellKey = 0;
50233  int rc;
50234  BtCursor *pCur = pC->pCursor;
50235  Mem m;
50236
50237  assert( sqlite3BtreeCursorIsValid(pCur) );
50238  rc = sqlite3BtreeKeySize(pCur, &nCellKey);
50239  assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
50240  /* nCellKey will always be between 0 and 0xffffffff because of the say
50241  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
50242  if( nCellKey<=0 || nCellKey>0x7fffffff ){
50243    *res = 0;
50244    return SQLITE_CORRUPT;
50245  }
50246  memset(&m, 0, sizeof(m));
50247  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
50248  if( rc ){
50249    return rc;
50250  }
50251  assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
50252  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
50253  sqlite3VdbeMemRelease(&m);
50254  return SQLITE_OK;
50255}
50256
50257/*
50258** This routine sets the value to be returned by subsequent calls to
50259** sqlite3_changes() on the database handle 'db'.
50260*/
50261SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
50262  assert( sqlite3_mutex_held(db->mutex) );
50263  db->nChange = nChange;
50264  db->nTotalChange += nChange;
50265}
50266
50267/*
50268** Set a flag in the vdbe to update the change counter when it is finalised
50269** or reset.
50270*/
50271SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
50272  v->changeCntOn = 1;
50273}
50274
50275/*
50276** Mark every prepared statement associated with a database connection
50277** as expired.
50278**
50279** An expired statement means that recompilation of the statement is
50280** recommend.  Statements expire when things happen that make their
50281** programs obsolete.  Removing user-defined functions or collating
50282** sequences, or changing an authorization function are the types of
50283** things that make prepared statements obsolete.
50284*/
50285SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
50286  Vdbe *p;
50287  for(p = db->pVdbe; p; p=p->pNext){
50288    p->expired = 1;
50289  }
50290}
50291
50292/*
50293** Return the database associated with the Vdbe.
50294*/
50295SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
50296  return v->db;
50297}
50298
50299/*
50300** Return a pointer to an sqlite3_value structure containing the value bound
50301** parameter iVar of VM v. Except, if the value is an SQL NULL, return
50302** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
50303** constants) to the value before returning it.
50304**
50305** The returned value must be freed by the caller using sqlite3ValueFree().
50306*/
50307SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
50308  assert( iVar>0 );
50309  if( v ){
50310    Mem *pMem = &v->aVar[iVar-1];
50311    if( 0==(pMem->flags & MEM_Null) ){
50312      sqlite3_value *pRet = sqlite3ValueNew(v->db);
50313      if( pRet ){
50314        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
50315        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
50316        sqlite3VdbeMemStoreType((Mem *)pRet);
50317      }
50318      return pRet;
50319    }
50320  }
50321  return 0;
50322}
50323
50324/*
50325** Configure SQL variable iVar so that binding a new value to it signals
50326** to sqlite3_reoptimize() that re-preparing the statement may result
50327** in a better query plan.
50328*/
50329SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
50330  assert( iVar>0 );
50331  if( iVar>32 ){
50332    v->expmask = 0xffffffff;
50333  }else{
50334    v->expmask |= ((u32)1 << (iVar-1));
50335  }
50336}
50337
50338/************** End of vdbeaux.c *********************************************/
50339/************** Begin file vdbeapi.c *****************************************/
50340/*
50341** 2004 May 26
50342**
50343** The author disclaims copyright to this source code.  In place of
50344** a legal notice, here is a blessing:
50345**
50346**    May you do good and not evil.
50347**    May you find forgiveness for yourself and forgive others.
50348**    May you share freely, never taking more than you give.
50349**
50350*************************************************************************
50351**
50352** This file contains code use to implement APIs that are part of the
50353** VDBE.
50354*/
50355
50356#ifndef SQLITE_OMIT_DEPRECATED
50357/*
50358** Return TRUE (non-zero) of the statement supplied as an argument needs
50359** to be recompiled.  A statement needs to be recompiled whenever the
50360** execution environment changes in a way that would alter the program
50361** that sqlite3_prepare() generates.  For example, if new functions or
50362** collating sequences are registered or if an authorizer function is
50363** added or changed.
50364*/
50365SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
50366  Vdbe *p = (Vdbe*)pStmt;
50367  return p==0 || p->expired;
50368}
50369#endif
50370
50371/*
50372** The following routine destroys a virtual machine that is created by
50373** the sqlite3_compile() routine. The integer returned is an SQLITE_
50374** success/failure code that describes the result of executing the virtual
50375** machine.
50376**
50377** This routine sets the error code and string returned by
50378** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
50379*/
50380SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
50381  int rc;
50382  if( pStmt==0 ){
50383    rc = SQLITE_OK;
50384  }else{
50385    Vdbe *v = (Vdbe*)pStmt;
50386    sqlite3 *db = v->db;
50387#if SQLITE_THREADSAFE
50388    sqlite3_mutex *mutex = v->db->mutex;
50389#endif
50390    sqlite3_mutex_enter(mutex);
50391    rc = sqlite3VdbeFinalize(v);
50392    rc = sqlite3ApiExit(db, rc);
50393    sqlite3_mutex_leave(mutex);
50394  }
50395  return rc;
50396}
50397
50398/*
50399** Terminate the current execution of an SQL statement and reset it
50400** back to its starting state so that it can be reused. A success code from
50401** the prior execution is returned.
50402**
50403** This routine sets the error code and string returned by
50404** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
50405*/
50406SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
50407  int rc;
50408  if( pStmt==0 ){
50409    rc = SQLITE_OK;
50410  }else{
50411    Vdbe *v = (Vdbe*)pStmt;
50412    sqlite3_mutex_enter(v->db->mutex);
50413    rc = sqlite3VdbeReset(v);
50414    sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
50415    assert( (rc & (v->db->errMask))==rc );
50416    rc = sqlite3ApiExit(v->db, rc);
50417    sqlite3_mutex_leave(v->db->mutex);
50418  }
50419  return rc;
50420}
50421
50422/*
50423** Set all the parameters in the compiled SQL statement to NULL.
50424*/
50425SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
50426  int i;
50427  int rc = SQLITE_OK;
50428  Vdbe *p = (Vdbe*)pStmt;
50429#if SQLITE_THREADSAFE
50430  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
50431#endif
50432  sqlite3_mutex_enter(mutex);
50433  for(i=0; i<p->nVar; i++){
50434    sqlite3VdbeMemRelease(&p->aVar[i]);
50435    p->aVar[i].flags = MEM_Null;
50436  }
50437  if( p->isPrepareV2 && p->expmask ){
50438    p->expired = 1;
50439  }
50440  sqlite3_mutex_leave(mutex);
50441  return rc;
50442}
50443
50444
50445/**************************** sqlite3_value_  *******************************
50446** The following routines extract information from a Mem or sqlite3_value
50447** structure.
50448*/
50449SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
50450  Mem *p = (Mem*)pVal;
50451  if( p->flags & (MEM_Blob|MEM_Str) ){
50452    sqlite3VdbeMemExpandBlob(p);
50453    p->flags &= ~MEM_Str;
50454    p->flags |= MEM_Blob;
50455    return p->z;
50456  }else{
50457    return sqlite3_value_text(pVal);
50458  }
50459}
50460SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
50461  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
50462}
50463SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
50464  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
50465}
50466SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
50467  return sqlite3VdbeRealValue((Mem*)pVal);
50468}
50469SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
50470  return (int)sqlite3VdbeIntValue((Mem*)pVal);
50471}
50472SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
50473  return sqlite3VdbeIntValue((Mem*)pVal);
50474}
50475SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
50476  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
50477}
50478#ifndef SQLITE_OMIT_UTF16
50479SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
50480  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
50481}
50482SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
50483  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
50484}
50485SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
50486  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
50487}
50488#endif /* SQLITE_OMIT_UTF16 */
50489SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
50490  return pVal->type;
50491}
50492
50493/**************************** sqlite3_result_  *******************************
50494** The following routines are used by user-defined functions to specify
50495** the function result.
50496**
50497** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
50498** result as a string or blob but if the string or blob is too large, it
50499** then sets the error code to SQLITE_TOOBIG
50500*/
50501static void setResultStrOrError(
50502  sqlite3_context *pCtx,  /* Function context */
50503  const char *z,          /* String pointer */
50504  int n,                  /* Bytes in string, or negative */
50505  u8 enc,                 /* Encoding of z.  0 for BLOBs */
50506  void (*xDel)(void*)     /* Destructor function */
50507){
50508  if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
50509    sqlite3_result_error_toobig(pCtx);
50510  }
50511}
50512SQLITE_API void sqlite3_result_blob(
50513  sqlite3_context *pCtx,
50514  const void *z,
50515  int n,
50516  void (*xDel)(void *)
50517){
50518  assert( n>=0 );
50519  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50520  setResultStrOrError(pCtx, z, n, 0, xDel);
50521}
50522SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
50523  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50524  sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
50525}
50526SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
50527  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50528  pCtx->isError = SQLITE_ERROR;
50529  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
50530}
50531#ifndef SQLITE_OMIT_UTF16
50532SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
50533  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50534  pCtx->isError = SQLITE_ERROR;
50535  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
50536}
50537#endif
50538SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
50539  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50540  sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
50541}
50542SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
50543  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50544  sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
50545}
50546SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
50547  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50548  sqlite3VdbeMemSetNull(&pCtx->s);
50549}
50550SQLITE_API void sqlite3_result_text(
50551  sqlite3_context *pCtx,
50552  const char *z,
50553  int n,
50554  void (*xDel)(void *)
50555){
50556  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50557  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
50558}
50559#ifndef SQLITE_OMIT_UTF16
50560SQLITE_API void sqlite3_result_text16(
50561  sqlite3_context *pCtx,
50562  const void *z,
50563  int n,
50564  void (*xDel)(void *)
50565){
50566  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50567  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
50568}
50569SQLITE_API void sqlite3_result_text16be(
50570  sqlite3_context *pCtx,
50571  const void *z,
50572  int n,
50573  void (*xDel)(void *)
50574){
50575  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50576  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
50577}
50578SQLITE_API void sqlite3_result_text16le(
50579  sqlite3_context *pCtx,
50580  const void *z,
50581  int n,
50582  void (*xDel)(void *)
50583){
50584  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50585  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
50586}
50587#endif /* SQLITE_OMIT_UTF16 */
50588SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
50589  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50590  sqlite3VdbeMemCopy(&pCtx->s, pValue);
50591}
50592SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
50593  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50594  sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
50595}
50596SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
50597  pCtx->isError = errCode;
50598  if( pCtx->s.flags & MEM_Null ){
50599    sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
50600                         SQLITE_UTF8, SQLITE_STATIC);
50601  }
50602}
50603
50604/* Force an SQLITE_TOOBIG error. */
50605SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
50606  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50607  pCtx->isError = SQLITE_TOOBIG;
50608  sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
50609                       SQLITE_UTF8, SQLITE_STATIC);
50610}
50611
50612/* An SQLITE_NOMEM error. */
50613SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
50614  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50615  sqlite3VdbeMemSetNull(&pCtx->s);
50616  pCtx->isError = SQLITE_NOMEM;
50617  pCtx->s.db->mallocFailed = 1;
50618}
50619
50620/*
50621** Execute the statement pStmt, either until a row of data is ready, the
50622** statement is completely executed or an error occurs.
50623**
50624** This routine implements the bulk of the logic behind the sqlite_step()
50625** API.  The only thing omitted is the automatic recompile if a
50626** schema change has occurred.  That detail is handled by the
50627** outer sqlite3_step() wrapper procedure.
50628*/
50629static int sqlite3Step(Vdbe *p){
50630  sqlite3 *db;
50631  int rc;
50632
50633  assert(p);
50634  if( p->magic!=VDBE_MAGIC_RUN ){
50635    return SQLITE_MISUSE;
50636  }
50637
50638  /* Assert that malloc() has not failed */
50639  db = p->db;
50640  if( db->mallocFailed ){
50641    return SQLITE_NOMEM;
50642  }
50643
50644  if( p->pc<=0 && p->expired ){
50645    if( ALWAYS(p->rc==SQLITE_OK || p->rc==SQLITE_SCHEMA) ){
50646      p->rc = SQLITE_SCHEMA;
50647    }
50648    rc = SQLITE_ERROR;
50649    goto end_of_step;
50650  }
50651  if( sqlite3SafetyOn(db) ){
50652    p->rc = SQLITE_MISUSE;
50653    return SQLITE_MISUSE;
50654  }
50655  if( p->pc<0 ){
50656    /* If there are no other statements currently running, then
50657    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
50658    ** from interrupting a statement that has not yet started.
50659    */
50660    if( db->activeVdbeCnt==0 ){
50661      db->u1.isInterrupted = 0;
50662    }
50663
50664    assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
50665
50666#ifndef SQLITE_OMIT_TRACE
50667    if( db->xProfile && !db->init.busy ){
50668      double rNow;
50669      sqlite3OsCurrentTime(db->pVfs, &rNow);
50670      p->startTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
50671    }
50672#endif
50673
50674    db->activeVdbeCnt++;
50675    if( p->readOnly==0 ) db->writeVdbeCnt++;
50676    p->pc = 0;
50677  }
50678#ifndef SQLITE_OMIT_EXPLAIN
50679  if( p->explain ){
50680    rc = sqlite3VdbeList(p);
50681  }else
50682#endif /* SQLITE_OMIT_EXPLAIN */
50683  {
50684    rc = sqlite3VdbeExec(p);
50685  }
50686
50687  if( sqlite3SafetyOff(db) ){
50688    rc = SQLITE_MISUSE;
50689  }
50690
50691#ifndef SQLITE_OMIT_TRACE
50692  /* Invoke the profile callback if there is one
50693  */
50694  if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
50695    double rNow;
50696    u64 elapseTime;
50697
50698    sqlite3OsCurrentTime(db->pVfs, &rNow);
50699    elapseTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
50700    elapseTime -= p->startTime;
50701    db->xProfile(db->pProfileArg, p->zSql, elapseTime);
50702  }
50703#endif
50704
50705  db->errCode = rc;
50706  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
50707    p->rc = SQLITE_NOMEM;
50708  }
50709end_of_step:
50710  /* At this point local variable rc holds the value that should be
50711  ** returned if this statement was compiled using the legacy
50712  ** sqlite3_prepare() interface. According to the docs, this can only
50713  ** be one of the values in the first assert() below. Variable p->rc
50714  ** contains the value that would be returned if sqlite3_finalize()
50715  ** were called on statement p.
50716  */
50717  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
50718       || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
50719  );
50720  assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
50721  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
50722    /* If this statement was prepared using sqlite3_prepare_v2(), and an
50723    ** error has occured, then return the error code in p->rc to the
50724    ** caller. Set the error code in the database handle to the same value.
50725    */
50726    rc = db->errCode = p->rc;
50727  }
50728  return (rc&db->errMask);
50729}
50730
50731/*
50732** This is the top-level implementation of sqlite3_step().  Call
50733** sqlite3Step() to do most of the work.  If a schema error occurs,
50734** call sqlite3Reprepare() and try again.
50735*/
50736SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
50737  int rc = SQLITE_MISUSE;
50738  if( pStmt ){
50739    int cnt = 0;
50740    Vdbe *v = (Vdbe*)pStmt;
50741    sqlite3 *db = v->db;
50742    sqlite3_mutex_enter(db->mutex);
50743    while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
50744           && cnt++ < 5
50745           && (rc = sqlite3Reprepare(v))==SQLITE_OK ){
50746      sqlite3_reset(pStmt);
50747      v->expired = 0;
50748    }
50749    if( rc==SQLITE_SCHEMA && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
50750      /* This case occurs after failing to recompile an sql statement.
50751      ** The error message from the SQL compiler has already been loaded
50752      ** into the database handle. This block copies the error message
50753      ** from the database handle into the statement and sets the statement
50754      ** program counter to 0 to ensure that when the statement is
50755      ** finalized or reset the parser error message is available via
50756      ** sqlite3_errmsg() and sqlite3_errcode().
50757      */
50758      const char *zErr = (const char *)sqlite3_value_text(db->pErr);
50759      sqlite3DbFree(db, v->zErrMsg);
50760      if( !db->mallocFailed ){
50761        v->zErrMsg = sqlite3DbStrDup(db, zErr);
50762      } else {
50763        v->zErrMsg = 0;
50764        v->rc = SQLITE_NOMEM;
50765      }
50766    }
50767    rc = sqlite3ApiExit(db, rc);
50768    sqlite3_mutex_leave(db->mutex);
50769  }
50770  return rc;
50771}
50772
50773/*
50774** Extract the user data from a sqlite3_context structure and return a
50775** pointer to it.
50776*/
50777SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
50778  assert( p && p->pFunc );
50779  return p->pFunc->pUserData;
50780}
50781
50782/*
50783** Extract the user data from a sqlite3_context structure and return a
50784** pointer to it.
50785*/
50786SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
50787  assert( p && p->pFunc );
50788  return p->s.db;
50789}
50790
50791/*
50792** The following is the implementation of an SQL function that always
50793** fails with an error message stating that the function is used in the
50794** wrong context.  The sqlite3_overload_function() API might construct
50795** SQL function that use this routine so that the functions will exist
50796** for name resolution but are actually overloaded by the xFindFunction
50797** method of virtual tables.
50798*/
50799SQLITE_PRIVATE void sqlite3InvalidFunction(
50800  sqlite3_context *context,  /* The function calling context */
50801  int NotUsed,               /* Number of arguments to the function */
50802  sqlite3_value **NotUsed2   /* Value of each argument */
50803){
50804  const char *zName = context->pFunc->zName;
50805  char *zErr;
50806  UNUSED_PARAMETER2(NotUsed, NotUsed2);
50807  zErr = sqlite3_mprintf(
50808      "unable to use function %s in the requested context", zName);
50809  sqlite3_result_error(context, zErr, -1);
50810  sqlite3_free(zErr);
50811}
50812
50813/*
50814** Allocate or return the aggregate context for a user function.  A new
50815** context is allocated on the first call.  Subsequent calls return the
50816** same context that was returned on prior calls.
50817*/
50818SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
50819  Mem *pMem;
50820  assert( p && p->pFunc && p->pFunc->xStep );
50821  assert( sqlite3_mutex_held(p->s.db->mutex) );
50822  pMem = p->pMem;
50823  testcase( nByte<0 );
50824  if( (pMem->flags & MEM_Agg)==0 ){
50825    if( nByte<=0 ){
50826      sqlite3VdbeMemReleaseExternal(pMem);
50827      pMem->flags = MEM_Null;
50828      pMem->z = 0;
50829    }else{
50830      sqlite3VdbeMemGrow(pMem, nByte, 0);
50831      pMem->flags = MEM_Agg;
50832      pMem->u.pDef = p->pFunc;
50833      if( pMem->z ){
50834        memset(pMem->z, 0, nByte);
50835      }
50836    }
50837  }
50838  return (void*)pMem->z;
50839}
50840
50841/*
50842** Return the auxilary data pointer, if any, for the iArg'th argument to
50843** the user-function defined by pCtx.
50844*/
50845SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
50846  VdbeFunc *pVdbeFunc;
50847
50848  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50849  pVdbeFunc = pCtx->pVdbeFunc;
50850  if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
50851    return 0;
50852  }
50853  return pVdbeFunc->apAux[iArg].pAux;
50854}
50855
50856/*
50857** Set the auxilary data pointer and delete function, for the iArg'th
50858** argument to the user-function defined by pCtx. Any previous value is
50859** deleted by calling the delete function specified when it was set.
50860*/
50861SQLITE_API void sqlite3_set_auxdata(
50862  sqlite3_context *pCtx,
50863  int iArg,
50864  void *pAux,
50865  void (*xDelete)(void*)
50866){
50867  struct AuxData *pAuxData;
50868  VdbeFunc *pVdbeFunc;
50869  if( iArg<0 ) goto failed;
50870
50871  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50872  pVdbeFunc = pCtx->pVdbeFunc;
50873  if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
50874    int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
50875    int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
50876    pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
50877    if( !pVdbeFunc ){
50878      goto failed;
50879    }
50880    pCtx->pVdbeFunc = pVdbeFunc;
50881    memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
50882    pVdbeFunc->nAux = iArg+1;
50883    pVdbeFunc->pFunc = pCtx->pFunc;
50884  }
50885
50886  pAuxData = &pVdbeFunc->apAux[iArg];
50887  if( pAuxData->pAux && pAuxData->xDelete ){
50888    pAuxData->xDelete(pAuxData->pAux);
50889  }
50890  pAuxData->pAux = pAux;
50891  pAuxData->xDelete = xDelete;
50892  return;
50893
50894failed:
50895  if( xDelete ){
50896    xDelete(pAux);
50897  }
50898}
50899
50900#ifndef SQLITE_OMIT_DEPRECATED
50901/*
50902** Return the number of times the Step function of a aggregate has been
50903** called.
50904**
50905** This function is deprecated.  Do not use it for new code.  It is
50906** provide only to avoid breaking legacy code.  New aggregate function
50907** implementations should keep their own counts within their aggregate
50908** context.
50909*/
50910SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
50911  assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
50912  return p->pMem->n;
50913}
50914#endif
50915
50916/*
50917** Return the number of columns in the result set for the statement pStmt.
50918*/
50919SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
50920  Vdbe *pVm = (Vdbe *)pStmt;
50921  return pVm ? pVm->nResColumn : 0;
50922}
50923
50924/*
50925** Return the number of values available from the current row of the
50926** currently executing statement pStmt.
50927*/
50928SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
50929  Vdbe *pVm = (Vdbe *)pStmt;
50930  if( pVm==0 || pVm->pResultSet==0 ) return 0;
50931  return pVm->nResColumn;
50932}
50933
50934
50935/*
50936** Check to see if column iCol of the given statement is valid.  If
50937** it is, return a pointer to the Mem for the value of that column.
50938** If iCol is not valid, return a pointer to a Mem which has a value
50939** of NULL.
50940*/
50941static Mem *columnMem(sqlite3_stmt *pStmt, int i){
50942  Vdbe *pVm;
50943  int vals;
50944  Mem *pOut;
50945
50946  pVm = (Vdbe *)pStmt;
50947  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
50948    sqlite3_mutex_enter(pVm->db->mutex);
50949    vals = sqlite3_data_count(pStmt);
50950    pOut = &pVm->pResultSet[i];
50951  }else{
50952    /* If the value passed as the second argument is out of range, return
50953    ** a pointer to the following static Mem object which contains the
50954    ** value SQL NULL. Even though the Mem structure contains an element
50955    ** of type i64, on certain architecture (x86) with certain compiler
50956    ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
50957    ** instead of an 8-byte one. This all works fine, except that when
50958    ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
50959    ** that a Mem structure is located on an 8-byte boundary. To prevent
50960    ** this assert() from failing, when building with SQLITE_DEBUG defined
50961    ** using gcc, force nullMem to be 8-byte aligned using the magical
50962    ** __attribute__((aligned(8))) macro.  */
50963    static const Mem nullMem
50964#if defined(SQLITE_DEBUG) && defined(__GNUC__)
50965      __attribute__((aligned(8)))
50966#endif
50967      = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
50968
50969    if( pVm && ALWAYS(pVm->db) ){
50970      sqlite3_mutex_enter(pVm->db->mutex);
50971      sqlite3Error(pVm->db, SQLITE_RANGE, 0);
50972    }
50973    pOut = (Mem*)&nullMem;
50974  }
50975  return pOut;
50976}
50977
50978/*
50979** This function is called after invoking an sqlite3_value_XXX function on a
50980** column value (i.e. a value returned by evaluating an SQL expression in the
50981** select list of a SELECT statement) that may cause a malloc() failure. If
50982** malloc() has failed, the threads mallocFailed flag is cleared and the result
50983** code of statement pStmt set to SQLITE_NOMEM.
50984**
50985** Specifically, this is called from within:
50986**
50987**     sqlite3_column_int()
50988**     sqlite3_column_int64()
50989**     sqlite3_column_text()
50990**     sqlite3_column_text16()
50991**     sqlite3_column_real()
50992**     sqlite3_column_bytes()
50993**     sqlite3_column_bytes16()
50994**
50995** But not for sqlite3_column_blob(), which never calls malloc().
50996*/
50997static void columnMallocFailure(sqlite3_stmt *pStmt)
50998{
50999  /* If malloc() failed during an encoding conversion within an
51000  ** sqlite3_column_XXX API, then set the return code of the statement to
51001  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
51002  ** and _finalize() will return NOMEM.
51003  */
51004  Vdbe *p = (Vdbe *)pStmt;
51005  if( p ){
51006    p->rc = sqlite3ApiExit(p->db, p->rc);
51007    sqlite3_mutex_leave(p->db->mutex);
51008  }
51009}
51010
51011/**************************** sqlite3_column_  *******************************
51012** The following routines are used to access elements of the current row
51013** in the result set.
51014*/
51015SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
51016  const void *val;
51017  val = sqlite3_value_blob( columnMem(pStmt,i) );
51018  /* Even though there is no encoding conversion, value_blob() might
51019  ** need to call malloc() to expand the result of a zeroblob()
51020  ** expression.
51021  */
51022  columnMallocFailure(pStmt);
51023  return val;
51024}
51025SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
51026  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
51027  columnMallocFailure(pStmt);
51028  return val;
51029}
51030SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
51031  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
51032  columnMallocFailure(pStmt);
51033  return val;
51034}
51035SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
51036  double val = sqlite3_value_double( columnMem(pStmt,i) );
51037  columnMallocFailure(pStmt);
51038  return val;
51039}
51040SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
51041  int val = sqlite3_value_int( columnMem(pStmt,i) );
51042  columnMallocFailure(pStmt);
51043  return val;
51044}
51045SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
51046  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
51047  columnMallocFailure(pStmt);
51048  return val;
51049}
51050SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
51051  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
51052  columnMallocFailure(pStmt);
51053  return val;
51054}
51055SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
51056  Mem *pOut = columnMem(pStmt, i);
51057  if( pOut->flags&MEM_Static ){
51058    pOut->flags &= ~MEM_Static;
51059    pOut->flags |= MEM_Ephem;
51060  }
51061  columnMallocFailure(pStmt);
51062  return (sqlite3_value *)pOut;
51063}
51064#ifndef SQLITE_OMIT_UTF16
51065SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
51066  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
51067  columnMallocFailure(pStmt);
51068  return val;
51069}
51070#endif /* SQLITE_OMIT_UTF16 */
51071SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
51072  int iType = sqlite3_value_type( columnMem(pStmt,i) );
51073  columnMallocFailure(pStmt);
51074  return iType;
51075}
51076
51077/* The following function is experimental and subject to change or
51078** removal */
51079/*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
51080**  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
51081**}
51082*/
51083
51084/*
51085** Convert the N-th element of pStmt->pColName[] into a string using
51086** xFunc() then return that string.  If N is out of range, return 0.
51087**
51088** There are up to 5 names for each column.  useType determines which
51089** name is returned.  Here are the names:
51090**
51091**    0      The column name as it should be displayed for output
51092**    1      The datatype name for the column
51093**    2      The name of the database that the column derives from
51094**    3      The name of the table that the column derives from
51095**    4      The name of the table column that the result column derives from
51096**
51097** If the result is not a simple column reference (if it is an expression
51098** or a constant) then useTypes 2, 3, and 4 return NULL.
51099*/
51100static const void *columnName(
51101  sqlite3_stmt *pStmt,
51102  int N,
51103  const void *(*xFunc)(Mem*),
51104  int useType
51105){
51106  const void *ret = 0;
51107  Vdbe *p = (Vdbe *)pStmt;
51108  int n;
51109  sqlite3 *db = p->db;
51110
51111  assert( db!=0 );
51112  n = sqlite3_column_count(pStmt);
51113  if( N<n && N>=0 ){
51114    N += useType*n;
51115    sqlite3_mutex_enter(db->mutex);
51116    assert( db->mallocFailed==0 );
51117    ret = xFunc(&p->aColName[N]);
51118     /* A malloc may have failed inside of the xFunc() call. If this
51119    ** is the case, clear the mallocFailed flag and return NULL.
51120    */
51121    if( db->mallocFailed ){
51122      db->mallocFailed = 0;
51123      ret = 0;
51124    }
51125    sqlite3_mutex_leave(db->mutex);
51126  }
51127  return ret;
51128}
51129
51130/*
51131** Return the name of the Nth column of the result set returned by SQL
51132** statement pStmt.
51133*/
51134SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
51135  return columnName(
51136      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
51137}
51138#ifndef SQLITE_OMIT_UTF16
51139SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
51140  return columnName(
51141      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
51142}
51143#endif
51144
51145/*
51146** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
51147** not define OMIT_DECLTYPE.
51148*/
51149#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
51150# error "Must not define both SQLITE_OMIT_DECLTYPE \
51151         and SQLITE_ENABLE_COLUMN_METADATA"
51152#endif
51153
51154#ifndef SQLITE_OMIT_DECLTYPE
51155/*
51156** Return the column declaration type (if applicable) of the 'i'th column
51157** of the result set of SQL statement pStmt.
51158*/
51159SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
51160  return columnName(
51161      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
51162}
51163#ifndef SQLITE_OMIT_UTF16
51164SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
51165  return columnName(
51166      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
51167}
51168#endif /* SQLITE_OMIT_UTF16 */
51169#endif /* SQLITE_OMIT_DECLTYPE */
51170
51171#ifdef SQLITE_ENABLE_COLUMN_METADATA
51172/*
51173** Return the name of the database from which a result column derives.
51174** NULL is returned if the result column is an expression or constant or
51175** anything else which is not an unabiguous reference to a database column.
51176*/
51177SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
51178  return columnName(
51179      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
51180}
51181#ifndef SQLITE_OMIT_UTF16
51182SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
51183  return columnName(
51184      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
51185}
51186#endif /* SQLITE_OMIT_UTF16 */
51187
51188/*
51189** Return the name of the table from which a result column derives.
51190** NULL is returned if the result column is an expression or constant or
51191** anything else which is not an unabiguous reference to a database column.
51192*/
51193SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
51194  return columnName(
51195      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
51196}
51197#ifndef SQLITE_OMIT_UTF16
51198SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
51199  return columnName(
51200      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
51201}
51202#endif /* SQLITE_OMIT_UTF16 */
51203
51204/*
51205** Return the name of the table column from which a result column derives.
51206** NULL is returned if the result column is an expression or constant or
51207** anything else which is not an unabiguous reference to a database column.
51208*/
51209SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
51210  return columnName(
51211      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
51212}
51213#ifndef SQLITE_OMIT_UTF16
51214SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
51215  return columnName(
51216      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
51217}
51218#endif /* SQLITE_OMIT_UTF16 */
51219#endif /* SQLITE_ENABLE_COLUMN_METADATA */
51220
51221
51222/******************************* sqlite3_bind_  ***************************
51223**
51224** Routines used to attach values to wildcards in a compiled SQL statement.
51225*/
51226/*
51227** Unbind the value bound to variable i in virtual machine p. This is the
51228** the same as binding a NULL value to the column. If the "i" parameter is
51229** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
51230**
51231** A successful evaluation of this routine acquires the mutex on p.
51232** the mutex is released if any kind of error occurs.
51233**
51234** The error code stored in database p->db is overwritten with the return
51235** value in any case.
51236*/
51237static int vdbeUnbind(Vdbe *p, int i){
51238  Mem *pVar;
51239  if( p==0 ) return SQLITE_MISUSE;
51240  sqlite3_mutex_enter(p->db->mutex);
51241  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
51242    sqlite3Error(p->db, SQLITE_MISUSE, 0);
51243    sqlite3_mutex_leave(p->db->mutex);
51244    return SQLITE_MISUSE;
51245  }
51246  if( i<1 || i>p->nVar ){
51247    sqlite3Error(p->db, SQLITE_RANGE, 0);
51248    sqlite3_mutex_leave(p->db->mutex);
51249    return SQLITE_RANGE;
51250  }
51251  i--;
51252  pVar = &p->aVar[i];
51253  sqlite3VdbeMemRelease(pVar);
51254  pVar->flags = MEM_Null;
51255  sqlite3Error(p->db, SQLITE_OK, 0);
51256
51257  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
51258  ** binding a new value to this variable invalidates the current query plan.
51259  */
51260  if( p->isPrepareV2 &&
51261     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
51262  ){
51263    p->expired = 1;
51264  }
51265  return SQLITE_OK;
51266}
51267
51268/*
51269** Bind a text or BLOB value.
51270*/
51271static int bindText(
51272  sqlite3_stmt *pStmt,   /* The statement to bind against */
51273  int i,                 /* Index of the parameter to bind */
51274  const void *zData,     /* Pointer to the data to be bound */
51275  int nData,             /* Number of bytes of data to be bound */
51276  void (*xDel)(void*),   /* Destructor for the data */
51277  u8 encoding            /* Encoding for the data */
51278){
51279  Vdbe *p = (Vdbe *)pStmt;
51280  Mem *pVar;
51281  int rc;
51282
51283  rc = vdbeUnbind(p, i);
51284  if( rc==SQLITE_OK ){
51285    if( zData!=0 ){
51286      pVar = &p->aVar[i-1];
51287      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
51288      if( rc==SQLITE_OK && encoding!=0 ){
51289        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
51290      }
51291      sqlite3Error(p->db, rc, 0);
51292      rc = sqlite3ApiExit(p->db, rc);
51293    }
51294    sqlite3_mutex_leave(p->db->mutex);
51295  }
51296  return rc;
51297}
51298
51299
51300/*
51301** Bind a blob value to an SQL statement variable.
51302*/
51303SQLITE_API int sqlite3_bind_blob(
51304  sqlite3_stmt *pStmt,
51305  int i,
51306  const void *zData,
51307  int nData,
51308  void (*xDel)(void*)
51309){
51310  return bindText(pStmt, i, zData, nData, xDel, 0);
51311}
51312SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
51313  int rc;
51314  Vdbe *p = (Vdbe *)pStmt;
51315  rc = vdbeUnbind(p, i);
51316  if( rc==SQLITE_OK ){
51317    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
51318    sqlite3_mutex_leave(p->db->mutex);
51319  }
51320  return rc;
51321}
51322SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
51323  return sqlite3_bind_int64(p, i, (i64)iValue);
51324}
51325SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
51326  int rc;
51327  Vdbe *p = (Vdbe *)pStmt;
51328  rc = vdbeUnbind(p, i);
51329  if( rc==SQLITE_OK ){
51330    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
51331    sqlite3_mutex_leave(p->db->mutex);
51332  }
51333  return rc;
51334}
51335SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
51336  int rc;
51337  Vdbe *p = (Vdbe*)pStmt;
51338  rc = vdbeUnbind(p, i);
51339  if( rc==SQLITE_OK ){
51340    sqlite3_mutex_leave(p->db->mutex);
51341  }
51342  return rc;
51343}
51344SQLITE_API int sqlite3_bind_text(
51345  sqlite3_stmt *pStmt,
51346  int i,
51347  const char *zData,
51348  int nData,
51349  void (*xDel)(void*)
51350){
51351  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
51352}
51353#ifndef SQLITE_OMIT_UTF16
51354SQLITE_API int sqlite3_bind_text16(
51355  sqlite3_stmt *pStmt,
51356  int i,
51357  const void *zData,
51358  int nData,
51359  void (*xDel)(void*)
51360){
51361  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
51362}
51363#endif /* SQLITE_OMIT_UTF16 */
51364SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
51365  int rc;
51366  switch( pValue->type ){
51367    case SQLITE_INTEGER: {
51368      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
51369      break;
51370    }
51371    case SQLITE_FLOAT: {
51372      rc = sqlite3_bind_double(pStmt, i, pValue->r);
51373      break;
51374    }
51375    case SQLITE_BLOB: {
51376      if( pValue->flags & MEM_Zero ){
51377        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
51378      }else{
51379        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
51380      }
51381      break;
51382    }
51383    case SQLITE_TEXT: {
51384      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
51385                              pValue->enc);
51386      break;
51387    }
51388    default: {
51389      rc = sqlite3_bind_null(pStmt, i);
51390      break;
51391    }
51392  }
51393  return rc;
51394}
51395SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
51396  int rc;
51397  Vdbe *p = (Vdbe *)pStmt;
51398  rc = vdbeUnbind(p, i);
51399  if( rc==SQLITE_OK ){
51400    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
51401    sqlite3_mutex_leave(p->db->mutex);
51402  }
51403  return rc;
51404}
51405
51406/*
51407** Return the number of wildcards that can be potentially bound to.
51408** This routine is added to support DBD::SQLite.
51409*/
51410SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
51411  Vdbe *p = (Vdbe*)pStmt;
51412  return p ? p->nVar : 0;
51413}
51414
51415/*
51416** Create a mapping from variable numbers to variable names
51417** in the Vdbe.azVar[] array, if such a mapping does not already
51418** exist.
51419*/
51420static void createVarMap(Vdbe *p){
51421  if( !p->okVar ){
51422    int j;
51423    Op *pOp;
51424    sqlite3_mutex_enter(p->db->mutex);
51425    /* The race condition here is harmless.  If two threads call this
51426    ** routine on the same Vdbe at the same time, they both might end
51427    ** up initializing the Vdbe.azVar[] array.  That is a little extra
51428    ** work but it results in the same answer.
51429    */
51430    for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
51431      if( pOp->opcode==OP_Variable ){
51432        assert( pOp->p1>0 && pOp->p1<=p->nVar );
51433        p->azVar[pOp->p1-1] = pOp->p4.z;
51434      }
51435    }
51436    p->okVar = 1;
51437    sqlite3_mutex_leave(p->db->mutex);
51438  }
51439}
51440
51441/*
51442** Return the name of a wildcard parameter.  Return NULL if the index
51443** is out of range or if the wildcard is unnamed.
51444**
51445** The result is always UTF-8.
51446*/
51447SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
51448  Vdbe *p = (Vdbe*)pStmt;
51449  if( p==0 || i<1 || i>p->nVar ){
51450    return 0;
51451  }
51452  createVarMap(p);
51453  return p->azVar[i-1];
51454}
51455
51456/*
51457** Given a wildcard parameter name, return the index of the variable
51458** with that name.  If there is no variable with the given name,
51459** return 0.
51460*/
51461SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
51462  int i;
51463  if( p==0 ){
51464    return 0;
51465  }
51466  createVarMap(p);
51467  if( zName ){
51468    for(i=0; i<p->nVar; i++){
51469      const char *z = p->azVar[i];
51470      if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
51471        return i+1;
51472      }
51473    }
51474  }
51475  return 0;
51476}
51477SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
51478  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
51479}
51480
51481/*
51482** Transfer all bindings from the first statement over to the second.
51483*/
51484SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
51485  Vdbe *pFrom = (Vdbe*)pFromStmt;
51486  Vdbe *pTo = (Vdbe*)pToStmt;
51487  int i;
51488  assert( pTo->db==pFrom->db );
51489  assert( pTo->nVar==pFrom->nVar );
51490  sqlite3_mutex_enter(pTo->db->mutex);
51491  for(i=0; i<pFrom->nVar; i++){
51492    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
51493  }
51494  sqlite3_mutex_leave(pTo->db->mutex);
51495  return SQLITE_OK;
51496}
51497
51498#ifndef SQLITE_OMIT_DEPRECATED
51499/*
51500** Deprecated external interface.  Internal/core SQLite code
51501** should call sqlite3TransferBindings.
51502**
51503** Is is misuse to call this routine with statements from different
51504** database connections.  But as this is a deprecated interface, we
51505** will not bother to check for that condition.
51506**
51507** If the two statements contain a different number of bindings, then
51508** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
51509** SQLITE_OK is returned.
51510*/
51511SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
51512  Vdbe *pFrom = (Vdbe*)pFromStmt;
51513  Vdbe *pTo = (Vdbe*)pToStmt;
51514  if( pFrom->nVar!=pTo->nVar ){
51515    return SQLITE_ERROR;
51516  }
51517  if( pTo->isPrepareV2 && pTo->expmask ){
51518    pTo->expired = 1;
51519  }
51520  if( pFrom->isPrepareV2 && pFrom->expmask ){
51521    pFrom->expired = 1;
51522  }
51523  return sqlite3TransferBindings(pFromStmt, pToStmt);
51524}
51525#endif
51526
51527/*
51528** Return the sqlite3* database handle to which the prepared statement given
51529** in the argument belongs.  This is the same database handle that was
51530** the first argument to the sqlite3_prepare() that was used to create
51531** the statement in the first place.
51532*/
51533SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
51534  return pStmt ? ((Vdbe*)pStmt)->db : 0;
51535}
51536
51537/*
51538** Return a pointer to the next prepared statement after pStmt associated
51539** with database connection pDb.  If pStmt is NULL, return the first
51540** prepared statement for the database connection.  Return NULL if there
51541** are no more.
51542*/
51543SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
51544  sqlite3_stmt *pNext;
51545  sqlite3_mutex_enter(pDb->mutex);
51546  if( pStmt==0 ){
51547    pNext = (sqlite3_stmt*)pDb->pVdbe;
51548  }else{
51549    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
51550  }
51551  sqlite3_mutex_leave(pDb->mutex);
51552  return pNext;
51553}
51554
51555/*
51556** Return the value of a status counter for a prepared statement
51557*/
51558SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
51559  Vdbe *pVdbe = (Vdbe*)pStmt;
51560  int v = pVdbe->aCounter[op-1];
51561  if( resetFlag ) pVdbe->aCounter[op-1] = 0;
51562  return v;
51563}
51564
51565/************** End of vdbeapi.c *********************************************/
51566/************** Begin file vdbetrace.c ***************************************/
51567/*
51568** 2009 November 25
51569**
51570** The author disclaims copyright to this source code.  In place of
51571** a legal notice, here is a blessing:
51572**
51573**    May you do good and not evil.
51574**    May you find forgiveness for yourself and forgive others.
51575**    May you share freely, never taking more than you give.
51576**
51577*************************************************************************
51578**
51579** This file contains code used to insert the values of host parameters
51580** (aka "wildcards") into the SQL text output by sqlite3_trace().
51581*/
51582
51583#ifndef SQLITE_OMIT_TRACE
51584
51585/*
51586** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
51587** bytes in this text up to but excluding the first character in
51588** a host parameter.  If the text contains no host parameters, return
51589** the total number of bytes in the text.
51590*/
51591static int findNextHostParameter(const char *zSql, int *pnToken){
51592  int tokenType;
51593  int nTotal = 0;
51594  int n;
51595
51596  *pnToken = 0;
51597  while( zSql[0] ){
51598    n = sqlite3GetToken((u8*)zSql, &tokenType);
51599    assert( n>0 && tokenType!=TK_ILLEGAL );
51600    if( tokenType==TK_VARIABLE ){
51601      *pnToken = n;
51602      break;
51603    }
51604    nTotal += n;
51605    zSql += n;
51606  }
51607  return nTotal;
51608}
51609
51610/*
51611** Return a pointer to a string in memory obtained form sqlite3DbMalloc() which
51612** holds a copy of zRawSql but with host parameters expanded to their
51613** current bindings.
51614**
51615** The calling function is responsible for making sure the memory returned
51616** is eventually freed.
51617**
51618** ALGORITHM:  Scan the input string looking for host parameters in any of
51619** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
51620** string literals, quoted identifier names, and comments.  For text forms,
51621** the host parameter index is found by scanning the perpared
51622** statement for the corresponding OP_Variable opcode.  Once the host
51623** parameter index is known, locate the value in p->aVar[].  Then render
51624** the value as a literal in place of the host parameter name.
51625*/
51626SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
51627  Vdbe *p,                 /* The prepared statement being evaluated */
51628  const char *zRawSql      /* Raw text of the SQL statement */
51629){
51630  sqlite3 *db;             /* The database connection */
51631  int idx = 0;             /* Index of a host parameter */
51632  int nextIndex = 1;       /* Index of next ? host parameter */
51633  int n;                   /* Length of a token prefix */
51634  int nToken;              /* Length of the parameter token */
51635  int i;                   /* Loop counter */
51636  Mem *pVar;               /* Value of a host parameter */
51637  StrAccum out;            /* Accumulate the output here */
51638  char zBase[100];         /* Initial working space */
51639
51640  db = p->db;
51641  sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
51642                      db->aLimit[SQLITE_LIMIT_LENGTH]);
51643  out.db = db;
51644  while( zRawSql[0] ){
51645    n = findNextHostParameter(zRawSql, &nToken);
51646    assert( n>0 );
51647    sqlite3StrAccumAppend(&out, zRawSql, n);
51648    zRawSql += n;
51649    assert( zRawSql[0] || nToken==0 );
51650    if( nToken==0 ) break;
51651    if( zRawSql[0]=='?' ){
51652      if( nToken>1 ){
51653        assert( sqlite3Isdigit(zRawSql[1]) );
51654        sqlite3GetInt32(&zRawSql[1], &idx);
51655      }else{
51656        idx = nextIndex;
51657      }
51658    }else{
51659      assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
51660      testcase( zRawSql[0]==':' );
51661      testcase( zRawSql[0]=='$' );
51662      testcase( zRawSql[0]=='@' );
51663      idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
51664      assert( idx>0 );
51665    }
51666    zRawSql += nToken;
51667    nextIndex = idx + 1;
51668    assert( idx>0 && idx<=p->nVar );
51669    pVar = &p->aVar[idx-1];
51670    if( pVar->flags & MEM_Null ){
51671      sqlite3StrAccumAppend(&out, "NULL", 4);
51672    }else if( pVar->flags & MEM_Int ){
51673      sqlite3XPrintf(&out, "%lld", pVar->u.i);
51674    }else if( pVar->flags & MEM_Real ){
51675      sqlite3XPrintf(&out, "%!.15g", pVar->r);
51676    }else if( pVar->flags & MEM_Str ){
51677#ifndef SQLITE_OMIT_UTF16
51678      u8 enc = ENC(db);
51679      if( enc!=SQLITE_UTF8 ){
51680        Mem utf8;
51681        memset(&utf8, 0, sizeof(utf8));
51682        utf8.db = db;
51683        sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
51684        sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
51685        sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
51686        sqlite3VdbeMemRelease(&utf8);
51687      }else
51688#endif
51689      {
51690        sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
51691      }
51692    }else if( pVar->flags & MEM_Zero ){
51693      sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
51694    }else{
51695      assert( pVar->flags & MEM_Blob );
51696      sqlite3StrAccumAppend(&out, "x'", 2);
51697      for(i=0; i<pVar->n; i++){
51698        sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
51699      }
51700      sqlite3StrAccumAppend(&out, "'", 1);
51701    }
51702  }
51703  return sqlite3StrAccumFinish(&out);
51704}
51705
51706#endif /* #ifndef SQLITE_OMIT_TRACE */
51707
51708/************** End of vdbetrace.c *******************************************/
51709/************** Begin file vdbe.c ********************************************/
51710/*
51711** 2001 September 15
51712**
51713** The author disclaims copyright to this source code.  In place of
51714** a legal notice, here is a blessing:
51715**
51716**    May you do good and not evil.
51717**    May you find forgiveness for yourself and forgive others.
51718**    May you share freely, never taking more than you give.
51719**
51720*************************************************************************
51721** The code in this file implements execution method of the
51722** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
51723** handles housekeeping details such as creating and deleting
51724** VDBE instances.  This file is solely interested in executing
51725** the VDBE program.
51726**
51727** In the external interface, an "sqlite3_stmt*" is an opaque pointer
51728** to a VDBE.
51729**
51730** The SQL parser generates a program which is then executed by
51731** the VDBE to do the work of the SQL statement.  VDBE programs are
51732** similar in form to assembly language.  The program consists of
51733** a linear sequence of operations.  Each operation has an opcode
51734** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
51735** is a null-terminated string.  Operand P5 is an unsigned character.
51736** Few opcodes use all 5 operands.
51737**
51738** Computation results are stored on a set of registers numbered beginning
51739** with 1 and going up to Vdbe.nMem.  Each register can store
51740** either an integer, a null-terminated string, a floating point
51741** number, or the SQL "NULL" value.  An implicit conversion from one
51742** type to the other occurs as necessary.
51743**
51744** Most of the code in this file is taken up by the sqlite3VdbeExec()
51745** function which does the work of interpreting a VDBE program.
51746** But other routines are also provided to help in building up
51747** a program instruction by instruction.
51748**
51749** Various scripts scan this source file in order to generate HTML
51750** documentation, headers files, or other derived files.  The formatting
51751** of the code in this file is, therefore, important.  See other comments
51752** in this file for details.  If in doubt, do not deviate from existing
51753** commenting and indentation practices when changing or adding code.
51754*/
51755
51756/*
51757** The following global variable is incremented every time a cursor
51758** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
51759** procedures use this information to make sure that indices are
51760** working correctly.  This variable has no function other than to
51761** help verify the correct operation of the library.
51762*/
51763#ifdef SQLITE_TEST
51764SQLITE_API int sqlite3_search_count = 0;
51765#endif
51766
51767/*
51768** When this global variable is positive, it gets decremented once before
51769** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
51770** field of the sqlite3 structure is set in order to simulate and interrupt.
51771**
51772** This facility is used for testing purposes only.  It does not function
51773** in an ordinary build.
51774*/
51775#ifdef SQLITE_TEST
51776SQLITE_API int sqlite3_interrupt_count = 0;
51777#endif
51778
51779/*
51780** The next global variable is incremented each type the OP_Sort opcode
51781** is executed.  The test procedures use this information to make sure that
51782** sorting is occurring or not occurring at appropriate times.   This variable
51783** has no function other than to help verify the correct operation of the
51784** library.
51785*/
51786#ifdef SQLITE_TEST
51787SQLITE_API int sqlite3_sort_count = 0;
51788#endif
51789
51790/*
51791** The next global variable records the size of the largest MEM_Blob
51792** or MEM_Str that has been used by a VDBE opcode.  The test procedures
51793** use this information to make sure that the zero-blob functionality
51794** is working correctly.   This variable has no function other than to
51795** help verify the correct operation of the library.
51796*/
51797#ifdef SQLITE_TEST
51798SQLITE_API int sqlite3_max_blobsize = 0;
51799static void updateMaxBlobsize(Mem *p){
51800  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
51801    sqlite3_max_blobsize = p->n;
51802  }
51803}
51804#endif
51805
51806/*
51807** The next global variable is incremented each type the OP_Found opcode
51808** is executed. This is used to test whether or not the foreign key
51809** operation implemented using OP_FkIsZero is working. This variable
51810** has no function other than to help verify the correct operation of the
51811** library.
51812*/
51813#ifdef SQLITE_TEST
51814SQLITE_API int sqlite3_found_count = 0;
51815#endif
51816
51817/*
51818** Test a register to see if it exceeds the current maximum blob size.
51819** If it does, record the new maximum blob size.
51820*/
51821#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
51822# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
51823#else
51824# define UPDATE_MAX_BLOBSIZE(P)
51825#endif
51826
51827/*
51828** Convert the given register into a string if it isn't one
51829** already. Return non-zero if a malloc() fails.
51830*/
51831#define Stringify(P, enc) \
51832   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
51833     { goto no_mem; }
51834
51835/*
51836** An ephemeral string value (signified by the MEM_Ephem flag) contains
51837** a pointer to a dynamically allocated string where some other entity
51838** is responsible for deallocating that string.  Because the register
51839** does not control the string, it might be deleted without the register
51840** knowing it.
51841**
51842** This routine converts an ephemeral string into a dynamically allocated
51843** string that the register itself controls.  In other words, it
51844** converts an MEM_Ephem string into an MEM_Dyn string.
51845*/
51846#define Deephemeralize(P) \
51847   if( ((P)->flags&MEM_Ephem)!=0 \
51848       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
51849
51850/*
51851** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
51852** P if required.
51853*/
51854#define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
51855
51856/*
51857** Argument pMem points at a register that will be passed to a
51858** user-defined function or returned to the user as the result of a query.
51859** This routine sets the pMem->type variable used by the sqlite3_value_*()
51860** routines.
51861*/
51862SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
51863  int flags = pMem->flags;
51864  if( flags & MEM_Null ){
51865    pMem->type = SQLITE_NULL;
51866  }
51867  else if( flags & MEM_Int ){
51868    pMem->type = SQLITE_INTEGER;
51869  }
51870  else if( flags & MEM_Real ){
51871    pMem->type = SQLITE_FLOAT;
51872  }
51873  else if( flags & MEM_Str ){
51874    pMem->type = SQLITE_TEXT;
51875  }else{
51876    pMem->type = SQLITE_BLOB;
51877  }
51878}
51879
51880/*
51881** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
51882** if we run out of memory.
51883*/
51884static VdbeCursor *allocateCursor(
51885  Vdbe *p,              /* The virtual machine */
51886  int iCur,             /* Index of the new VdbeCursor */
51887  int nField,           /* Number of fields in the table or index */
51888  int iDb,              /* When database the cursor belongs to, or -1 */
51889  int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
51890){
51891  /* Find the memory cell that will be used to store the blob of memory
51892  ** required for this VdbeCursor structure. It is convenient to use a
51893  ** vdbe memory cell to manage the memory allocation required for a
51894  ** VdbeCursor structure for the following reasons:
51895  **
51896  **   * Sometimes cursor numbers are used for a couple of different
51897  **     purposes in a vdbe program. The different uses might require
51898  **     different sized allocations. Memory cells provide growable
51899  **     allocations.
51900  **
51901  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
51902  **     be freed lazily via the sqlite3_release_memory() API. This
51903  **     minimizes the number of malloc calls made by the system.
51904  **
51905  ** Memory cells for cursors are allocated at the top of the address
51906  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
51907  ** cursor 1 is managed by memory cell (p->nMem-1), etc.
51908  */
51909  Mem *pMem = &p->aMem[p->nMem-iCur];
51910
51911  int nByte;
51912  VdbeCursor *pCx = 0;
51913  nByte =
51914      ROUND8(sizeof(VdbeCursor)) +
51915      (isBtreeCursor?sqlite3BtreeCursorSize():0) +
51916      2*nField*sizeof(u32);
51917
51918  assert( iCur<p->nCursor );
51919  if( p->apCsr[iCur] ){
51920    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
51921    p->apCsr[iCur] = 0;
51922  }
51923  if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
51924    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
51925    memset(pCx, 0, sizeof(VdbeCursor));
51926    pCx->iDb = iDb;
51927    pCx->nField = nField;
51928    if( nField ){
51929      pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
51930    }
51931    if( isBtreeCursor ){
51932      pCx->pCursor = (BtCursor*)
51933          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
51934      sqlite3BtreeCursorZero(pCx->pCursor);
51935    }
51936  }
51937  return pCx;
51938}
51939
51940/*
51941** Try to convert a value into a numeric representation if we can
51942** do so without loss of information.  In other words, if the string
51943** looks like a number, convert it into a number.  If it does not
51944** look like a number, leave it alone.
51945*/
51946static void applyNumericAffinity(Mem *pRec){
51947  if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
51948    int realnum;
51949    sqlite3VdbeMemNulTerminate(pRec);
51950    if( (pRec->flags&MEM_Str)
51951         && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
51952      i64 value;
51953      sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
51954      if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
51955        pRec->u.i = value;
51956        MemSetTypeFlag(pRec, MEM_Int);
51957      }else{
51958        sqlite3VdbeMemRealify(pRec);
51959      }
51960    }
51961  }
51962}
51963
51964/*
51965** Processing is determine by the affinity parameter:
51966**
51967** SQLITE_AFF_INTEGER:
51968** SQLITE_AFF_REAL:
51969** SQLITE_AFF_NUMERIC:
51970**    Try to convert pRec to an integer representation or a
51971**    floating-point representation if an integer representation
51972**    is not possible.  Note that the integer representation is
51973**    always preferred, even if the affinity is REAL, because
51974**    an integer representation is more space efficient on disk.
51975**
51976** SQLITE_AFF_TEXT:
51977**    Convert pRec to a text representation.
51978**
51979** SQLITE_AFF_NONE:
51980**    No-op.  pRec is unchanged.
51981*/
51982static void applyAffinity(
51983  Mem *pRec,          /* The value to apply affinity to */
51984  char affinity,      /* The affinity to be applied */
51985  u8 enc              /* Use this text encoding */
51986){
51987  if( affinity==SQLITE_AFF_TEXT ){
51988    /* Only attempt the conversion to TEXT if there is an integer or real
51989    ** representation (blob and NULL do not get converted) but no string
51990    ** representation.
51991    */
51992    if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
51993      sqlite3VdbeMemStringify(pRec, enc);
51994    }
51995    pRec->flags &= ~(MEM_Real|MEM_Int);
51996  }else if( affinity!=SQLITE_AFF_NONE ){
51997    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
51998             || affinity==SQLITE_AFF_NUMERIC );
51999    applyNumericAffinity(pRec);
52000    if( pRec->flags & MEM_Real ){
52001      sqlite3VdbeIntegerAffinity(pRec);
52002    }
52003  }
52004}
52005
52006/*
52007** Try to convert the type of a function argument or a result column
52008** into a numeric representation.  Use either INTEGER or REAL whichever
52009** is appropriate.  But only do the conversion if it is possible without
52010** loss of information and return the revised type of the argument.
52011**
52012** This is an EXPERIMENTAL api and is subject to change or removal.
52013*/
52014SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
52015  Mem *pMem = (Mem*)pVal;
52016  applyNumericAffinity(pMem);
52017  sqlite3VdbeMemStoreType(pMem);
52018  return pMem->type;
52019}
52020
52021/*
52022** Exported version of applyAffinity(). This one works on sqlite3_value*,
52023** not the internal Mem* type.
52024*/
52025SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
52026  sqlite3_value *pVal,
52027  u8 affinity,
52028  u8 enc
52029){
52030  applyAffinity((Mem *)pVal, affinity, enc);
52031}
52032
52033#ifdef SQLITE_DEBUG
52034/*
52035** Write a nice string representation of the contents of cell pMem
52036** into buffer zBuf, length nBuf.
52037*/
52038SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
52039  char *zCsr = zBuf;
52040  int f = pMem->flags;
52041
52042  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
52043
52044  if( f&MEM_Blob ){
52045    int i;
52046    char c;
52047    if( f & MEM_Dyn ){
52048      c = 'z';
52049      assert( (f & (MEM_Static|MEM_Ephem))==0 );
52050    }else if( f & MEM_Static ){
52051      c = 't';
52052      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
52053    }else if( f & MEM_Ephem ){
52054      c = 'e';
52055      assert( (f & (MEM_Static|MEM_Dyn))==0 );
52056    }else{
52057      c = 's';
52058    }
52059
52060    sqlite3_snprintf(100, zCsr, "%c", c);
52061    zCsr += sqlite3Strlen30(zCsr);
52062    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
52063    zCsr += sqlite3Strlen30(zCsr);
52064    for(i=0; i<16 && i<pMem->n; i++){
52065      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
52066      zCsr += sqlite3Strlen30(zCsr);
52067    }
52068    for(i=0; i<16 && i<pMem->n; i++){
52069      char z = pMem->z[i];
52070      if( z<32 || z>126 ) *zCsr++ = '.';
52071      else *zCsr++ = z;
52072    }
52073
52074    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
52075    zCsr += sqlite3Strlen30(zCsr);
52076    if( f & MEM_Zero ){
52077      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
52078      zCsr += sqlite3Strlen30(zCsr);
52079    }
52080    *zCsr = '\0';
52081  }else if( f & MEM_Str ){
52082    int j, k;
52083    zBuf[0] = ' ';
52084    if( f & MEM_Dyn ){
52085      zBuf[1] = 'z';
52086      assert( (f & (MEM_Static|MEM_Ephem))==0 );
52087    }else if( f & MEM_Static ){
52088      zBuf[1] = 't';
52089      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
52090    }else if( f & MEM_Ephem ){
52091      zBuf[1] = 'e';
52092      assert( (f & (MEM_Static|MEM_Dyn))==0 );
52093    }else{
52094      zBuf[1] = 's';
52095    }
52096    k = 2;
52097    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
52098    k += sqlite3Strlen30(&zBuf[k]);
52099    zBuf[k++] = '[';
52100    for(j=0; j<15 && j<pMem->n; j++){
52101      u8 c = pMem->z[j];
52102      if( c>=0x20 && c<0x7f ){
52103        zBuf[k++] = c;
52104      }else{
52105        zBuf[k++] = '.';
52106      }
52107    }
52108    zBuf[k++] = ']';
52109    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
52110    k += sqlite3Strlen30(&zBuf[k]);
52111    zBuf[k++] = 0;
52112  }
52113}
52114#endif
52115
52116#ifdef SQLITE_DEBUG
52117/*
52118** Print the value of a register for tracing purposes:
52119*/
52120static void memTracePrint(FILE *out, Mem *p){
52121  if( p->flags & MEM_Null ){
52122    fprintf(out, " NULL");
52123  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
52124    fprintf(out, " si:%lld", p->u.i);
52125  }else if( p->flags & MEM_Int ){
52126    fprintf(out, " i:%lld", p->u.i);
52127#ifndef SQLITE_OMIT_FLOATING_POINT
52128  }else if( p->flags & MEM_Real ){
52129    fprintf(out, " r:%g", p->r);
52130#endif
52131  }else if( p->flags & MEM_RowSet ){
52132    fprintf(out, " (rowset)");
52133  }else{
52134    char zBuf[200];
52135    sqlite3VdbeMemPrettyPrint(p, zBuf);
52136    fprintf(out, " ");
52137    fprintf(out, "%s", zBuf);
52138  }
52139}
52140static void registerTrace(FILE *out, int iReg, Mem *p){
52141  fprintf(out, "REG[%d] = ", iReg);
52142  memTracePrint(out, p);
52143  fprintf(out, "\n");
52144}
52145#endif
52146
52147#ifdef SQLITE_DEBUG
52148#  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
52149#else
52150#  define REGISTER_TRACE(R,M)
52151#endif
52152
52153
52154#ifdef VDBE_PROFILE
52155
52156/*
52157** hwtime.h contains inline assembler code for implementing
52158** high-performance timing routines.
52159*/
52160/************** Include hwtime.h in the middle of vdbe.c *********************/
52161/************** Begin file hwtime.h ******************************************/
52162/*
52163** 2008 May 27
52164**
52165** The author disclaims copyright to this source code.  In place of
52166** a legal notice, here is a blessing:
52167**
52168**    May you do good and not evil.
52169**    May you find forgiveness for yourself and forgive others.
52170**    May you share freely, never taking more than you give.
52171**
52172******************************************************************************
52173**
52174** This file contains inline asm code for retrieving "high-performance"
52175** counters for x86 class CPUs.
52176*/
52177#ifndef _HWTIME_H_
52178#define _HWTIME_H_
52179
52180/*
52181** The following routine only works on pentium-class (or newer) processors.
52182** It uses the RDTSC opcode to read the cycle count value out of the
52183** processor and returns that value.  This can be used for high-res
52184** profiling.
52185*/
52186#if (defined(__GNUC__) || defined(_MSC_VER)) && \
52187      (defined(i386) || defined(__i386__) || defined(_M_IX86))
52188
52189  #if defined(__GNUC__)
52190
52191  __inline__ sqlite_uint64 sqlite3Hwtime(void){
52192     unsigned int lo, hi;
52193     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
52194     return (sqlite_uint64)hi << 32 | lo;
52195  }
52196
52197  #elif defined(_MSC_VER)
52198
52199  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
52200     __asm {
52201        rdtsc
52202        ret       ; return value at EDX:EAX
52203     }
52204  }
52205
52206  #endif
52207
52208#elif (defined(__GNUC__) && defined(__x86_64__))
52209
52210  __inline__ sqlite_uint64 sqlite3Hwtime(void){
52211      unsigned long val;
52212      __asm__ __volatile__ ("rdtsc" : "=A" (val));
52213      return val;
52214  }
52215
52216#elif (defined(__GNUC__) && defined(__ppc__))
52217
52218  __inline__ sqlite_uint64 sqlite3Hwtime(void){
52219      unsigned long long retval;
52220      unsigned long junk;
52221      __asm__ __volatile__ ("\n\
52222          1:      mftbu   %1\n\
52223                  mftb    %L0\n\
52224                  mftbu   %0\n\
52225                  cmpw    %0,%1\n\
52226                  bne     1b"
52227                  : "=r" (retval), "=r" (junk));
52228      return retval;
52229  }
52230
52231#else
52232
52233  #error Need implementation of sqlite3Hwtime() for your platform.
52234
52235  /*
52236  ** To compile without implementing sqlite3Hwtime() for your platform,
52237  ** you can remove the above #error and use the following
52238  ** stub function.  You will lose timing support for many
52239  ** of the debugging and testing utilities, but it should at
52240  ** least compile and run.
52241  */
52242SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
52243
52244#endif
52245
52246#endif /* !defined(_HWTIME_H_) */
52247
52248/************** End of hwtime.h **********************************************/
52249/************** Continuing where we left off in vdbe.c ***********************/
52250
52251#endif
52252
52253/*
52254** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
52255** sqlite3_interrupt() routine has been called.  If it has been, then
52256** processing of the VDBE program is interrupted.
52257**
52258** This macro added to every instruction that does a jump in order to
52259** implement a loop.  This test used to be on every single instruction,
52260** but that meant we more testing that we needed.  By only testing the
52261** flag on jump instructions, we get a (small) speed improvement.
52262*/
52263#define CHECK_FOR_INTERRUPT \
52264   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
52265
52266#ifdef SQLITE_DEBUG
52267static int fileExists(sqlite3 *db, const char *zFile){
52268  int res = 0;
52269  int rc = SQLITE_OK;
52270#ifdef SQLITE_TEST
52271  /* If we are currently testing IO errors, then do not call OsAccess() to
52272  ** test for the presence of zFile. This is because any IO error that
52273  ** occurs here will not be reported, causing the test to fail.
52274  */
52275  extern int sqlite3_io_error_pending;
52276  if( sqlite3_io_error_pending<=0 )
52277#endif
52278    rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
52279  return (res && rc==SQLITE_OK);
52280}
52281#endif
52282
52283#ifndef NDEBUG
52284/*
52285** This function is only called from within an assert() expression. It
52286** checks that the sqlite3.nTransaction variable is correctly set to
52287** the number of non-transaction savepoints currently in the
52288** linked list starting at sqlite3.pSavepoint.
52289**
52290** Usage:
52291**
52292**     assert( checkSavepointCount(db) );
52293*/
52294static int checkSavepointCount(sqlite3 *db){
52295  int n = 0;
52296  Savepoint *p;
52297  for(p=db->pSavepoint; p; p=p->pNext) n++;
52298  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
52299  return 1;
52300}
52301#endif
52302
52303/*
52304** Execute as much of a VDBE program as we can then return.
52305**
52306** sqlite3VdbeMakeReady() must be called before this routine in order to
52307** close the program with a final OP_Halt and to set up the callbacks
52308** and the error message pointer.
52309**
52310** Whenever a row or result data is available, this routine will either
52311** invoke the result callback (if there is one) or return with
52312** SQLITE_ROW.
52313**
52314** If an attempt is made to open a locked database, then this routine
52315** will either invoke the busy callback (if there is one) or it will
52316** return SQLITE_BUSY.
52317**
52318** If an error occurs, an error message is written to memory obtained
52319** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
52320** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
52321**
52322** If the callback ever returns non-zero, then the program exits
52323** immediately.  There will be no error message but the p->rc field is
52324** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
52325**
52326** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
52327** routine to return SQLITE_ERROR.
52328**
52329** Other fatal errors return SQLITE_ERROR.
52330**
52331** After this routine has finished, sqlite3VdbeFinalize() should be
52332** used to clean up the mess that was left behind.
52333*/
52334SQLITE_PRIVATE int sqlite3VdbeExec(
52335  Vdbe *p                    /* The VDBE */
52336){
52337  int pc;                    /* The program counter */
52338  Op *aOp = p->aOp;          /* Copy of p->aOp */
52339  Op *pOp;                   /* Current operation */
52340  int rc = SQLITE_OK;        /* Value to return */
52341  sqlite3 *db = p->db;       /* The database */
52342  u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */
52343  u8 encoding = ENC(db);     /* The database encoding */
52344#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
52345  int checkProgress;         /* True if progress callbacks are enabled */
52346  int nProgressOps = 0;      /* Opcodes executed since progress callback. */
52347#endif
52348  Mem *aMem = p->aMem;       /* Copy of p->aMem */
52349  Mem *pIn1 = 0;             /* 1st input operand */
52350  Mem *pIn2 = 0;             /* 2nd input operand */
52351  Mem *pIn3 = 0;             /* 3rd input operand */
52352  Mem *pOut = 0;             /* Output operand */
52353  int iCompare = 0;          /* Result of last OP_Compare operation */
52354  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
52355#ifdef VDBE_PROFILE
52356  u64 start;                 /* CPU clock count at start of opcode */
52357  int origPc;                /* Program counter at start of opcode */
52358#endif
52359  /********************************************************************
52360  ** Automatically generated code
52361  **
52362  ** The following union is automatically generated by the
52363  ** vdbe-compress.tcl script.  The purpose of this union is to
52364  ** reduce the amount of stack space required by this function.
52365  ** See comments in the vdbe-compress.tcl script for details.
52366  */
52367  union vdbeExecUnion {
52368    struct OP_Yield_stack_vars {
52369      int pcDest;
52370    } aa;
52371    struct OP_Variable_stack_vars {
52372      int p1;          /* Variable to copy from */
52373      int p2;          /* Register to copy to */
52374      int n;           /* Number of values left to copy */
52375      Mem *pVar;       /* Value being transferred */
52376    } ab;
52377    struct OP_Move_stack_vars {
52378      char *zMalloc;   /* Holding variable for allocated memory */
52379      int n;           /* Number of registers left to copy */
52380      int p1;          /* Register to copy from */
52381      int p2;          /* Register to copy to */
52382    } ac;
52383    struct OP_ResultRow_stack_vars {
52384      Mem *pMem;
52385      int i;
52386    } ad;
52387    struct OP_Concat_stack_vars {
52388      i64 nByte;
52389    } ae;
52390    struct OP_Remainder_stack_vars {
52391      int flags;      /* Combined MEM_* flags from both inputs */
52392      i64 iA;         /* Integer value of left operand */
52393      i64 iB;         /* Integer value of right operand */
52394      double rA;      /* Real value of left operand */
52395      double rB;      /* Real value of right operand */
52396    } af;
52397    struct OP_Function_stack_vars {
52398      int i;
52399      Mem *pArg;
52400      sqlite3_context ctx;
52401      sqlite3_value **apVal;
52402      int n;
52403    } ag;
52404    struct OP_ShiftRight_stack_vars {
52405      i64 a;
52406      i64 b;
52407    } ah;
52408    struct OP_Ge_stack_vars {
52409      int res;            /* Result of the comparison of pIn1 against pIn3 */
52410      char affinity;      /* Affinity to use for comparison */
52411    } ai;
52412    struct OP_Compare_stack_vars {
52413      int n;
52414      int i;
52415      int p1;
52416      int p2;
52417      const KeyInfo *pKeyInfo;
52418      int idx;
52419      CollSeq *pColl;    /* Collating sequence to use on this term */
52420      int bRev;          /* True for DESCENDING sort order */
52421    } aj;
52422    struct OP_Or_stack_vars {
52423      int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
52424      int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
52425    } ak;
52426    struct OP_IfNot_stack_vars {
52427      int c;
52428    } al;
52429    struct OP_Column_stack_vars {
52430      u32 payloadSize;   /* Number of bytes in the record */
52431      i64 payloadSize64; /* Number of bytes in the record */
52432      int p1;            /* P1 value of the opcode */
52433      int p2;            /* column number to retrieve */
52434      VdbeCursor *pC;    /* The VDBE cursor */
52435      char *zRec;        /* Pointer to complete record-data */
52436      BtCursor *pCrsr;   /* The BTree cursor */
52437      u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
52438      u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
52439      int nField;        /* number of fields in the record */
52440      int len;           /* The length of the serialized data for the column */
52441      int i;             /* Loop counter */
52442      char *zData;       /* Part of the record being decoded */
52443      Mem *pDest;        /* Where to write the extracted value */
52444      Mem sMem;          /* For storing the record being decoded */
52445      u8 *zIdx;          /* Index into header */
52446      u8 *zEndHdr;       /* Pointer to first byte after the header */
52447      u32 offset;        /* Offset into the data */
52448      u64 offset64;      /* 64-bit offset.  64 bits needed to catch overflow */
52449      int szHdr;         /* Size of the header size field at start of record */
52450      int avail;         /* Number of bytes of available data */
52451      Mem *pReg;         /* PseudoTable input register */
52452    } am;
52453    struct OP_Affinity_stack_vars {
52454      const char *zAffinity;   /* The affinity to be applied */
52455      char cAff;               /* A single character of affinity */
52456    } an;
52457    struct OP_MakeRecord_stack_vars {
52458      u8 *zNewRecord;        /* A buffer to hold the data for the new record */
52459      Mem *pRec;             /* The new record */
52460      u64 nData;             /* Number of bytes of data space */
52461      int nHdr;              /* Number of bytes of header space */
52462      i64 nByte;             /* Data space required for this record */
52463      int nZero;             /* Number of zero bytes at the end of the record */
52464      int nVarint;           /* Number of bytes in a varint */
52465      u32 serial_type;       /* Type field */
52466      Mem *pData0;           /* First field to be combined into the record */
52467      Mem *pLast;            /* Last field of the record */
52468      int nField;            /* Number of fields in the record */
52469      char *zAffinity;       /* The affinity string for the record */
52470      int file_format;       /* File format to use for encoding */
52471      int i;                 /* Space used in zNewRecord[] */
52472      int len;               /* Length of a field */
52473    } ao;
52474    struct OP_Count_stack_vars {
52475      i64 nEntry;
52476      BtCursor *pCrsr;
52477    } ap;
52478    struct OP_Savepoint_stack_vars {
52479      int p1;                         /* Value of P1 operand */
52480      char *zName;                    /* Name of savepoint */
52481      int nName;
52482      Savepoint *pNew;
52483      Savepoint *pSavepoint;
52484      Savepoint *pTmp;
52485      int iSavepoint;
52486      int ii;
52487    } aq;
52488    struct OP_AutoCommit_stack_vars {
52489      int desiredAutoCommit;
52490      int iRollback;
52491      int turnOnAC;
52492    } ar;
52493    struct OP_Transaction_stack_vars {
52494      Btree *pBt;
52495    } as;
52496    struct OP_ReadCookie_stack_vars {
52497      int iMeta;
52498      int iDb;
52499      int iCookie;
52500    } at;
52501    struct OP_SetCookie_stack_vars {
52502      Db *pDb;
52503    } au;
52504    struct OP_VerifyCookie_stack_vars {
52505      int iMeta;
52506      Btree *pBt;
52507    } av;
52508    struct OP_OpenWrite_stack_vars {
52509      int nField;
52510      KeyInfo *pKeyInfo;
52511      int p2;
52512      int iDb;
52513      int wrFlag;
52514      Btree *pX;
52515      VdbeCursor *pCur;
52516      Db *pDb;
52517    } aw;
52518    struct OP_OpenEphemeral_stack_vars {
52519      VdbeCursor *pCx;
52520    } ax;
52521    struct OP_OpenPseudo_stack_vars {
52522      VdbeCursor *pCx;
52523    } ay;
52524    struct OP_SeekGt_stack_vars {
52525      int res;
52526      int oc;
52527      VdbeCursor *pC;
52528      UnpackedRecord r;
52529      int nField;
52530      i64 iKey;      /* The rowid we are to seek to */
52531    } az;
52532    struct OP_Seek_stack_vars {
52533      VdbeCursor *pC;
52534    } ba;
52535    struct OP_Found_stack_vars {
52536      int alreadyExists;
52537      VdbeCursor *pC;
52538      int res;
52539      UnpackedRecord *pIdxKey;
52540      UnpackedRecord r;
52541      char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
52542    } bb;
52543    struct OP_IsUnique_stack_vars {
52544      u16 ii;
52545      VdbeCursor *pCx;
52546      BtCursor *pCrsr;
52547      u16 nField;
52548      Mem *aMx;
52549      UnpackedRecord r;                  /* B-Tree index search key */
52550      i64 R;                             /* Rowid stored in register P3 */
52551    } bc;
52552    struct OP_NotExists_stack_vars {
52553      VdbeCursor *pC;
52554      BtCursor *pCrsr;
52555      int res;
52556      u64 iKey;
52557    } bd;
52558    struct OP_NewRowid_stack_vars {
52559      i64 v;                 /* The new rowid */
52560      VdbeCursor *pC;        /* Cursor of table to get the new rowid */
52561      int res;               /* Result of an sqlite3BtreeLast() */
52562      int cnt;               /* Counter to limit the number of searches */
52563      Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
52564      VdbeFrame *pFrame;     /* Root frame of VDBE */
52565    } be;
52566    struct OP_InsertInt_stack_vars {
52567      Mem *pData;       /* MEM cell holding data for the record to be inserted */
52568      Mem *pKey;        /* MEM cell holding key  for the record */
52569      i64 iKey;         /* The integer ROWID or key for the record to be inserted */
52570      VdbeCursor *pC;   /* Cursor to table into which insert is written */
52571      int nZero;        /* Number of zero-bytes to append */
52572      int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
52573      const char *zDb;  /* database name - used by the update hook */
52574      const char *zTbl; /* Table name - used by the opdate hook */
52575      int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
52576    } bf;
52577    struct OP_Delete_stack_vars {
52578      i64 iKey;
52579      VdbeCursor *pC;
52580    } bg;
52581    struct OP_RowData_stack_vars {
52582      VdbeCursor *pC;
52583      BtCursor *pCrsr;
52584      u32 n;
52585      i64 n64;
52586    } bh;
52587    struct OP_Rowid_stack_vars {
52588      VdbeCursor *pC;
52589      i64 v;
52590      sqlite3_vtab *pVtab;
52591      const sqlite3_module *pModule;
52592    } bi;
52593    struct OP_NullRow_stack_vars {
52594      VdbeCursor *pC;
52595    } bj;
52596    struct OP_Last_stack_vars {
52597      VdbeCursor *pC;
52598      BtCursor *pCrsr;
52599      int res;
52600    } bk;
52601    struct OP_Rewind_stack_vars {
52602      VdbeCursor *pC;
52603      BtCursor *pCrsr;
52604      int res;
52605    } bl;
52606    struct OP_Next_stack_vars {
52607      VdbeCursor *pC;
52608      BtCursor *pCrsr;
52609      int res;
52610    } bm;
52611    struct OP_IdxInsert_stack_vars {
52612      VdbeCursor *pC;
52613      BtCursor *pCrsr;
52614      int nKey;
52615      const char *zKey;
52616    } bn;
52617    struct OP_IdxDelete_stack_vars {
52618      VdbeCursor *pC;
52619      BtCursor *pCrsr;
52620      int res;
52621      UnpackedRecord r;
52622    } bo;
52623    struct OP_IdxRowid_stack_vars {
52624      BtCursor *pCrsr;
52625      VdbeCursor *pC;
52626      i64 rowid;
52627    } bp;
52628    struct OP_IdxGE_stack_vars {
52629      VdbeCursor *pC;
52630      int res;
52631      UnpackedRecord r;
52632    } bq;
52633    struct OP_Destroy_stack_vars {
52634      int iMoved;
52635      int iCnt;
52636      Vdbe *pVdbe;
52637      int iDb;
52638    } br;
52639    struct OP_Clear_stack_vars {
52640      int nChange;
52641    } bs;
52642    struct OP_CreateTable_stack_vars {
52643      int pgno;
52644      int flags;
52645      Db *pDb;
52646    } bt;
52647    struct OP_ParseSchema_stack_vars {
52648      int iDb;
52649      const char *zMaster;
52650      char *zSql;
52651      InitData initData;
52652    } bu;
52653    struct OP_IntegrityCk_stack_vars {
52654      int nRoot;      /* Number of tables to check.  (Number of root pages.) */
52655      int *aRoot;     /* Array of rootpage numbers for tables to be checked */
52656      int j;          /* Loop counter */
52657      int nErr;       /* Number of errors reported */
52658      char *z;        /* Text of the error report */
52659      Mem *pnErr;     /* Register keeping track of errors remaining */
52660    } bv;
52661    struct OP_RowSetRead_stack_vars {
52662      i64 val;
52663    } bw;
52664    struct OP_RowSetTest_stack_vars {
52665      int iSet;
52666      int exists;
52667    } bx;
52668    struct OP_Program_stack_vars {
52669      int nMem;               /* Number of memory registers for sub-program */
52670      int nByte;              /* Bytes of runtime space required for sub-program */
52671      Mem *pRt;               /* Register to allocate runtime space */
52672      Mem *pMem;              /* Used to iterate through memory cells */
52673      Mem *pEnd;              /* Last memory cell in new array */
52674      VdbeFrame *pFrame;      /* New vdbe frame to execute in */
52675      SubProgram *pProgram;   /* Sub-program to execute */
52676      void *t;                /* Token identifying trigger */
52677    } by;
52678    struct OP_Param_stack_vars {
52679      VdbeFrame *pFrame;
52680      Mem *pIn;
52681    } bz;
52682    struct OP_MemMax_stack_vars {
52683      Mem *pIn1;
52684      VdbeFrame *pFrame;
52685    } ca;
52686    struct OP_AggStep_stack_vars {
52687      int n;
52688      int i;
52689      Mem *pMem;
52690      Mem *pRec;
52691      sqlite3_context ctx;
52692      sqlite3_value **apVal;
52693    } cb;
52694    struct OP_AggFinal_stack_vars {
52695      Mem *pMem;
52696    } cc;
52697    struct OP_IncrVacuum_stack_vars {
52698      Btree *pBt;
52699    } cd;
52700    struct OP_VBegin_stack_vars {
52701      VTable *pVTab;
52702    } ce;
52703    struct OP_VOpen_stack_vars {
52704      VdbeCursor *pCur;
52705      sqlite3_vtab_cursor *pVtabCursor;
52706      sqlite3_vtab *pVtab;
52707      sqlite3_module *pModule;
52708    } cf;
52709    struct OP_VFilter_stack_vars {
52710      int nArg;
52711      int iQuery;
52712      const sqlite3_module *pModule;
52713      Mem *pQuery;
52714      Mem *pArgc;
52715      sqlite3_vtab_cursor *pVtabCursor;
52716      sqlite3_vtab *pVtab;
52717      VdbeCursor *pCur;
52718      int res;
52719      int i;
52720      Mem **apArg;
52721    } cg;
52722    struct OP_VColumn_stack_vars {
52723      sqlite3_vtab *pVtab;
52724      const sqlite3_module *pModule;
52725      Mem *pDest;
52726      sqlite3_context sContext;
52727    } ch;
52728    struct OP_VNext_stack_vars {
52729      sqlite3_vtab *pVtab;
52730      const sqlite3_module *pModule;
52731      int res;
52732      VdbeCursor *pCur;
52733    } ci;
52734    struct OP_VRename_stack_vars {
52735      sqlite3_vtab *pVtab;
52736      Mem *pName;
52737    } cj;
52738    struct OP_VUpdate_stack_vars {
52739      sqlite3_vtab *pVtab;
52740      sqlite3_module *pModule;
52741      int nArg;
52742      int i;
52743      sqlite_int64 rowid;
52744      Mem **apArg;
52745      Mem *pX;
52746    } ck;
52747    struct OP_Pagecount_stack_vars {
52748      int p1;
52749      int nPage;
52750      Pager *pPager;
52751    } cl;
52752    struct OP_Trace_stack_vars {
52753      char *zTrace;
52754    } cm;
52755  } u;
52756  /* End automatically generated code
52757  ********************************************************************/
52758
52759  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
52760  assert( db->magic==SQLITE_MAGIC_BUSY );
52761  sqlite3VdbeMutexArrayEnter(p);
52762  if( p->rc==SQLITE_NOMEM ){
52763    /* This happens if a malloc() inside a call to sqlite3_column_text() or
52764    ** sqlite3_column_text16() failed.  */
52765    goto no_mem;
52766  }
52767  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
52768  p->rc = SQLITE_OK;
52769  assert( p->explain==0 );
52770  p->pResultSet = 0;
52771  db->busyHandler.nBusy = 0;
52772  CHECK_FOR_INTERRUPT;
52773  sqlite3VdbeIOTraceSql(p);
52774#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
52775  checkProgress = db->xProgress!=0;
52776#endif
52777#ifdef SQLITE_DEBUG
52778  sqlite3BeginBenignMalloc();
52779  if( p->pc==0
52780   && ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
52781  ){
52782    int i;
52783    printf("VDBE Program Listing:\n");
52784    sqlite3VdbePrintSql(p);
52785    for(i=0; i<p->nOp; i++){
52786      sqlite3VdbePrintOp(stdout, i, &aOp[i]);
52787    }
52788  }
52789  if( fileExists(db, "vdbe_trace") ){
52790    p->trace = stdout;
52791  }
52792  sqlite3EndBenignMalloc();
52793#endif
52794  for(pc=p->pc; rc==SQLITE_OK; pc++){
52795    assert( pc>=0 && pc<p->nOp );
52796    if( db->mallocFailed ) goto no_mem;
52797#ifdef VDBE_PROFILE
52798    origPc = pc;
52799    start = sqlite3Hwtime();
52800#endif
52801    pOp = &aOp[pc];
52802
52803    /* Only allow tracing if SQLITE_DEBUG is defined.
52804    */
52805#ifdef SQLITE_DEBUG
52806    if( p->trace ){
52807      if( pc==0 ){
52808        printf("VDBE Execution Trace:\n");
52809        sqlite3VdbePrintSql(p);
52810      }
52811      sqlite3VdbePrintOp(p->trace, pc, pOp);
52812    }
52813    if( p->trace==0 && pc==0 ){
52814      sqlite3BeginBenignMalloc();
52815      if( fileExists(db, "vdbe_sqltrace") ){
52816        sqlite3VdbePrintSql(p);
52817      }
52818      sqlite3EndBenignMalloc();
52819    }
52820#endif
52821
52822
52823    /* Check to see if we need to simulate an interrupt.  This only happens
52824    ** if we have a special test build.
52825    */
52826#ifdef SQLITE_TEST
52827    if( sqlite3_interrupt_count>0 ){
52828      sqlite3_interrupt_count--;
52829      if( sqlite3_interrupt_count==0 ){
52830        sqlite3_interrupt(db);
52831      }
52832    }
52833#endif
52834
52835#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
52836    /* Call the progress callback if it is configured and the required number
52837    ** of VDBE ops have been executed (either since this invocation of
52838    ** sqlite3VdbeExec() or since last time the progress callback was called).
52839    ** If the progress callback returns non-zero, exit the virtual machine with
52840    ** a return code SQLITE_ABORT.
52841    */
52842    if( checkProgress ){
52843      if( db->nProgressOps==nProgressOps ){
52844        int prc;
52845        if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
52846        prc =db->xProgress(db->pProgressArg);
52847        if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
52848        if( prc!=0 ){
52849          rc = SQLITE_INTERRUPT;
52850          goto vdbe_error_halt;
52851        }
52852        nProgressOps = 0;
52853      }
52854      nProgressOps++;
52855    }
52856#endif
52857
52858    /* On any opcode with the "out2-prerelase" tag, free any
52859    ** external allocations out of mem[p2] and set mem[p2] to be
52860    ** an undefined integer.  Opcodes will either fill in the integer
52861    ** value or convert mem[p2] to a different type.
52862    */
52863    assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
52864    if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
52865      assert( pOp->p2>0 );
52866      assert( pOp->p2<=p->nMem );
52867      pOut = &aMem[pOp->p2];
52868      sqlite3VdbeMemReleaseExternal(pOut);
52869      pOut->flags = MEM_Int;
52870    }
52871
52872    /* Sanity checking on other operands */
52873#ifdef SQLITE_DEBUG
52874    if( (pOp->opflags & OPFLG_IN1)!=0 ){
52875      assert( pOp->p1>0 );
52876      assert( pOp->p1<=p->nMem );
52877      REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
52878    }
52879    if( (pOp->opflags & OPFLG_IN2)!=0 ){
52880      assert( pOp->p2>0 );
52881      assert( pOp->p2<=p->nMem );
52882      REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
52883    }
52884    if( (pOp->opflags & OPFLG_IN3)!=0 ){
52885      assert( pOp->p3>0 );
52886      assert( pOp->p3<=p->nMem );
52887      REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
52888    }
52889    if( (pOp->opflags & OPFLG_OUT2)!=0 ){
52890      assert( pOp->p2>0 );
52891      assert( pOp->p2<=p->nMem );
52892    }
52893    if( (pOp->opflags & OPFLG_OUT3)!=0 ){
52894      assert( pOp->p3>0 );
52895      assert( pOp->p3<=p->nMem );
52896    }
52897#endif
52898
52899    switch( pOp->opcode ){
52900
52901/*****************************************************************************
52902** What follows is a massive switch statement where each case implements a
52903** separate instruction in the virtual machine.  If we follow the usual
52904** indentation conventions, each case should be indented by 6 spaces.  But
52905** that is a lot of wasted space on the left margin.  So the code within
52906** the switch statement will break with convention and be flush-left. Another
52907** big comment (similar to this one) will mark the point in the code where
52908** we transition back to normal indentation.
52909**
52910** The formatting of each case is important.  The makefile for SQLite
52911** generates two C files "opcodes.h" and "opcodes.c" by scanning this
52912** file looking for lines that begin with "case OP_".  The opcodes.h files
52913** will be filled with #defines that give unique integer values to each
52914** opcode and the opcodes.c file is filled with an array of strings where
52915** each string is the symbolic name for the corresponding opcode.  If the
52916** case statement is followed by a comment of the form "/# same as ... #/"
52917** that comment is used to determine the particular value of the opcode.
52918**
52919** Other keywords in the comment that follows each case are used to
52920** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
52921** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
52922** the mkopcodeh.awk script for additional information.
52923**
52924** Documentation about VDBE opcodes is generated by scanning this file
52925** for lines of that contain "Opcode:".  That line and all subsequent
52926** comment lines are used in the generation of the opcode.html documentation
52927** file.
52928**
52929** SUMMARY:
52930**
52931**     Formatting is important to scripts that scan this file.
52932**     Do not deviate from the formatting style currently in use.
52933**
52934*****************************************************************************/
52935
52936/* Opcode:  Goto * P2 * * *
52937**
52938** An unconditional jump to address P2.
52939** The next instruction executed will be
52940** the one at index P2 from the beginning of
52941** the program.
52942*/
52943case OP_Goto: {             /* jump */
52944  CHECK_FOR_INTERRUPT;
52945  pc = pOp->p2 - 1;
52946  break;
52947}
52948
52949/* Opcode:  Gosub P1 P2 * * *
52950**
52951** Write the current address onto register P1
52952** and then jump to address P2.
52953*/
52954case OP_Gosub: {            /* jump, in1 */
52955  pIn1 = &aMem[pOp->p1];
52956  assert( (pIn1->flags & MEM_Dyn)==0 );
52957  pIn1->flags = MEM_Int;
52958  pIn1->u.i = pc;
52959  REGISTER_TRACE(pOp->p1, pIn1);
52960  pc = pOp->p2 - 1;
52961  break;
52962}
52963
52964/* Opcode:  Return P1 * * * *
52965**
52966** Jump to the next instruction after the address in register P1.
52967*/
52968case OP_Return: {           /* in1 */
52969  pIn1 = &aMem[pOp->p1];
52970  assert( pIn1->flags & MEM_Int );
52971  pc = (int)pIn1->u.i;
52972  break;
52973}
52974
52975/* Opcode:  Yield P1 * * * *
52976**
52977** Swap the program counter with the value in register P1.
52978*/
52979case OP_Yield: {            /* in1 */
52980#if 0  /* local variables moved into u.aa */
52981  int pcDest;
52982#endif /* local variables moved into u.aa */
52983  pIn1 = &aMem[pOp->p1];
52984  assert( (pIn1->flags & MEM_Dyn)==0 );
52985  pIn1->flags = MEM_Int;
52986  u.aa.pcDest = (int)pIn1->u.i;
52987  pIn1->u.i = pc;
52988  REGISTER_TRACE(pOp->p1, pIn1);
52989  pc = u.aa.pcDest;
52990  break;
52991}
52992
52993/* Opcode:  HaltIfNull  P1 P2 P3 P4 *
52994**
52995** Check the value in register P3.  If is is NULL then Halt using
52996** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
52997** value in register P3 is not NULL, then this routine is a no-op.
52998*/
52999case OP_HaltIfNull: {      /* in3 */
53000  pIn3 = &aMem[pOp->p3];
53001  if( (pIn3->flags & MEM_Null)==0 ) break;
53002  /* Fall through into OP_Halt */
53003}
53004
53005/* Opcode:  Halt P1 P2 * P4 *
53006**
53007** Exit immediately.  All open cursors, etc are closed
53008** automatically.
53009**
53010** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
53011** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
53012** For errors, it can be some other value.  If P1!=0 then P2 will determine
53013** whether or not to rollback the current transaction.  Do not rollback
53014** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
53015** then back out all changes that have occurred during this execution of the
53016** VDBE, but do not rollback the transaction.
53017**
53018** If P4 is not null then it is an error message string.
53019**
53020** There is an implied "Halt 0 0 0" instruction inserted at the very end of
53021** every program.  So a jump past the last instruction of the program
53022** is the same as executing Halt.
53023*/
53024case OP_Halt: {
53025  if( pOp->p1==SQLITE_OK && p->pFrame ){
53026    /* Halt the sub-program. Return control to the parent frame. */
53027    VdbeFrame *pFrame = p->pFrame;
53028    p->pFrame = pFrame->pParent;
53029    p->nFrame--;
53030    sqlite3VdbeSetChanges(db, p->nChange);
53031    pc = sqlite3VdbeFrameRestore(pFrame);
53032    if( pOp->p2==OE_Ignore ){
53033      /* Instruction pc is the OP_Program that invoked the sub-program
53034      ** currently being halted. If the p2 instruction of this OP_Halt
53035      ** instruction is set to OE_Ignore, then the sub-program is throwing
53036      ** an IGNORE exception. In this case jump to the address specified
53037      ** as the p2 of the calling OP_Program.  */
53038      pc = p->aOp[pc].p2-1;
53039    }
53040    aOp = p->aOp;
53041    aMem = p->aMem;
53042    break;
53043  }
53044
53045  p->rc = pOp->p1;
53046  p->errorAction = (u8)pOp->p2;
53047  p->pc = pc;
53048  if( pOp->p4.z ){
53049    sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
53050  }
53051  rc = sqlite3VdbeHalt(p);
53052  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
53053  if( rc==SQLITE_BUSY ){
53054    p->rc = rc = SQLITE_BUSY;
53055  }else{
53056    assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
53057    assert( rc==SQLITE_OK || db->nDeferredCons>0 );
53058    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
53059  }
53060  goto vdbe_return;
53061}
53062
53063/* Opcode: Integer P1 P2 * * *
53064**
53065** The 32-bit integer value P1 is written into register P2.
53066*/
53067case OP_Integer: {         /* out2-prerelease */
53068  pOut->u.i = pOp->p1;
53069  break;
53070}
53071
53072/* Opcode: Int64 * P2 * P4 *
53073**
53074** P4 is a pointer to a 64-bit integer value.
53075** Write that value into register P2.
53076*/
53077case OP_Int64: {           /* out2-prerelease */
53078  assert( pOp->p4.pI64!=0 );
53079  pOut->u.i = *pOp->p4.pI64;
53080  break;
53081}
53082
53083/* Opcode: Real * P2 * P4 *
53084**
53085** P4 is a pointer to a 64-bit floating point value.
53086** Write that value into register P2.
53087*/
53088case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
53089  pOut->flags = MEM_Real;
53090  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
53091  pOut->r = *pOp->p4.pReal;
53092  break;
53093}
53094
53095/* Opcode: String8 * P2 * P4 *
53096**
53097** P4 points to a nul terminated UTF-8 string. This opcode is transformed
53098** into an OP_String before it is executed for the first time.
53099*/
53100case OP_String8: {         /* same as TK_STRING, out2-prerelease */
53101  assert( pOp->p4.z!=0 );
53102  pOp->opcode = OP_String;
53103  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
53104
53105#ifndef SQLITE_OMIT_UTF16
53106  if( encoding!=SQLITE_UTF8 ){
53107    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
53108    if( rc==SQLITE_TOOBIG ) goto too_big;
53109    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
53110    assert( pOut->zMalloc==pOut->z );
53111    assert( pOut->flags & MEM_Dyn );
53112    pOut->zMalloc = 0;
53113    pOut->flags |= MEM_Static;
53114    pOut->flags &= ~MEM_Dyn;
53115    if( pOp->p4type==P4_DYNAMIC ){
53116      sqlite3DbFree(db, pOp->p4.z);
53117    }
53118    pOp->p4type = P4_DYNAMIC;
53119    pOp->p4.z = pOut->z;
53120    pOp->p1 = pOut->n;
53121  }
53122#endif
53123  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
53124    goto too_big;
53125  }
53126  /* Fall through to the next case, OP_String */
53127}
53128
53129/* Opcode: String P1 P2 * P4 *
53130**
53131** The string value P4 of length P1 (bytes) is stored in register P2.
53132*/
53133case OP_String: {          /* out2-prerelease */
53134  assert( pOp->p4.z!=0 );
53135  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
53136  pOut->z = pOp->p4.z;
53137  pOut->n = pOp->p1;
53138  pOut->enc = encoding;
53139  UPDATE_MAX_BLOBSIZE(pOut);
53140  break;
53141}
53142
53143/* Opcode: Null * P2 * * *
53144**
53145** Write a NULL into register P2.
53146*/
53147case OP_Null: {           /* out2-prerelease */
53148  pOut->flags = MEM_Null;
53149  break;
53150}
53151
53152
53153/* Opcode: Blob P1 P2 * P4
53154**
53155** P4 points to a blob of data P1 bytes long.  Store this
53156** blob in register P2. This instruction is not coded directly
53157** by the compiler. Instead, the compiler layer specifies
53158** an OP_HexBlob opcode, with the hex string representation of
53159** the blob as P4. This opcode is transformed to an OP_Blob
53160** the first time it is executed.
53161*/
53162case OP_Blob: {                /* out2-prerelease */
53163  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
53164  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
53165  pOut->enc = encoding;
53166  UPDATE_MAX_BLOBSIZE(pOut);
53167  break;
53168}
53169
53170/* Opcode: Variable P1 P2 P3 P4 *
53171**
53172** Transfer the values of bound parameters P1..P1+P3-1 into registers
53173** P2..P2+P3-1.
53174**
53175** If the parameter is named, then its name appears in P4 and P3==1.
53176** The P4 value is used by sqlite3_bind_parameter_name().
53177*/
53178case OP_Variable: {
53179#if 0  /* local variables moved into u.ab */
53180  int p1;          /* Variable to copy from */
53181  int p2;          /* Register to copy to */
53182  int n;           /* Number of values left to copy */
53183  Mem *pVar;       /* Value being transferred */
53184#endif /* local variables moved into u.ab */
53185
53186  u.ab.p1 = pOp->p1 - 1;
53187  u.ab.p2 = pOp->p2;
53188  u.ab.n = pOp->p3;
53189  assert( u.ab.p1>=0 && u.ab.p1+u.ab.n<=p->nVar );
53190  assert( u.ab.p2>=1 && u.ab.p2+u.ab.n-1<=p->nMem );
53191  assert( pOp->p4.z==0 || pOp->p3==1 || pOp->p3==0 );
53192
53193  while( u.ab.n-- > 0 ){
53194    u.ab.pVar = &p->aVar[u.ab.p1++];
53195    if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
53196      goto too_big;
53197    }
53198    pOut = &aMem[u.ab.p2++];
53199    sqlite3VdbeMemReleaseExternal(pOut);
53200    pOut->flags = MEM_Null;
53201    sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
53202    UPDATE_MAX_BLOBSIZE(pOut);
53203  }
53204  break;
53205}
53206
53207/* Opcode: Move P1 P2 P3 * *
53208**
53209** Move the values in register P1..P1+P3-1 over into
53210** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
53211** left holding a NULL.  It is an error for register ranges
53212** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
53213*/
53214case OP_Move: {
53215#if 0  /* local variables moved into u.ac */
53216  char *zMalloc;   /* Holding variable for allocated memory */
53217  int n;           /* Number of registers left to copy */
53218  int p1;          /* Register to copy from */
53219  int p2;          /* Register to copy to */
53220#endif /* local variables moved into u.ac */
53221
53222  u.ac.n = pOp->p3;
53223  u.ac.p1 = pOp->p1;
53224  u.ac.p2 = pOp->p2;
53225  assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
53226  assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
53227
53228  pIn1 = &aMem[u.ac.p1];
53229  pOut = &aMem[u.ac.p2];
53230  while( u.ac.n-- ){
53231    assert( pOut<=&aMem[p->nMem] );
53232    assert( pIn1<=&aMem[p->nMem] );
53233    u.ac.zMalloc = pOut->zMalloc;
53234    pOut->zMalloc = 0;
53235    sqlite3VdbeMemMove(pOut, pIn1);
53236    pIn1->zMalloc = u.ac.zMalloc;
53237    REGISTER_TRACE(u.ac.p2++, pOut);
53238    pIn1++;
53239    pOut++;
53240  }
53241  break;
53242}
53243
53244/* Opcode: Copy P1 P2 * * *
53245**
53246** Make a copy of register P1 into register P2.
53247**
53248** This instruction makes a deep copy of the value.  A duplicate
53249** is made of any string or blob constant.  See also OP_SCopy.
53250*/
53251case OP_Copy: {             /* in1, out2 */
53252  pIn1 = &aMem[pOp->p1];
53253  pOut = &aMem[pOp->p2];
53254  assert( pOut!=pIn1 );
53255  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
53256  Deephemeralize(pOut);
53257  REGISTER_TRACE(pOp->p2, pOut);
53258  break;
53259}
53260
53261/* Opcode: SCopy P1 P2 * * *
53262**
53263** Make a shallow copy of register P1 into register P2.
53264**
53265** This instruction makes a shallow copy of the value.  If the value
53266** is a string or blob, then the copy is only a pointer to the
53267** original and hence if the original changes so will the copy.
53268** Worse, if the original is deallocated, the copy becomes invalid.
53269** Thus the program must guarantee that the original will not change
53270** during the lifetime of the copy.  Use OP_Copy to make a complete
53271** copy.
53272*/
53273case OP_SCopy: {            /* in1, out2 */
53274  pIn1 = &aMem[pOp->p1];
53275  pOut = &aMem[pOp->p2];
53276  assert( pOut!=pIn1 );
53277  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
53278  REGISTER_TRACE(pOp->p2, pOut);
53279  break;
53280}
53281
53282/* Opcode: ResultRow P1 P2 * * *
53283**
53284** The registers P1 through P1+P2-1 contain a single row of
53285** results. This opcode causes the sqlite3_step() call to terminate
53286** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
53287** structure to provide access to the top P1 values as the result
53288** row.
53289*/
53290case OP_ResultRow: {
53291#if 0  /* local variables moved into u.ad */
53292  Mem *pMem;
53293  int i;
53294#endif /* local variables moved into u.ad */
53295  assert( p->nResColumn==pOp->p2 );
53296  assert( pOp->p1>0 );
53297  assert( pOp->p1+pOp->p2<=p->nMem+1 );
53298
53299  /* If this statement has violated immediate foreign key constraints, do
53300  ** not return the number of rows modified. And do not RELEASE the statement
53301  ** transaction. It needs to be rolled back.  */
53302  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
53303    assert( db->flags&SQLITE_CountRows );
53304    assert( p->usesStmtJournal );
53305    break;
53306  }
53307
53308  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
53309  ** DML statements invoke this opcode to return the number of rows
53310  ** modified to the user. This is the only way that a VM that
53311  ** opens a statement transaction may invoke this opcode.
53312  **
53313  ** In case this is such a statement, close any statement transaction
53314  ** opened by this VM before returning control to the user. This is to
53315  ** ensure that statement-transactions are always nested, not overlapping.
53316  ** If the open statement-transaction is not closed here, then the user
53317  ** may step another VM that opens its own statement transaction. This
53318  ** may lead to overlapping statement transactions.
53319  **
53320  ** The statement transaction is never a top-level transaction.  Hence
53321  ** the RELEASE call below can never fail.
53322  */
53323  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
53324  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
53325  if( NEVER(rc!=SQLITE_OK) ){
53326    break;
53327  }
53328
53329  /* Invalidate all ephemeral cursor row caches */
53330  p->cacheCtr = (p->cacheCtr + 2)|1;
53331
53332  /* Make sure the results of the current row are \000 terminated
53333  ** and have an assigned type.  The results are de-ephemeralized as
53334  ** as side effect.
53335  */
53336  u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
53337  for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
53338    sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
53339    sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
53340    REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
53341  }
53342  if( db->mallocFailed ) goto no_mem;
53343
53344  /* Return SQLITE_ROW
53345  */
53346  p->pc = pc + 1;
53347  rc = SQLITE_ROW;
53348  goto vdbe_return;
53349}
53350
53351/* Opcode: Concat P1 P2 P3 * *
53352**
53353** Add the text in register P1 onto the end of the text in
53354** register P2 and store the result in register P3.
53355** If either the P1 or P2 text are NULL then store NULL in P3.
53356**
53357**   P3 = P2 || P1
53358**
53359** It is illegal for P1 and P3 to be the same register. Sometimes,
53360** if P3 is the same register as P2, the implementation is able
53361** to avoid a memcpy().
53362*/
53363case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
53364#if 0  /* local variables moved into u.ae */
53365  i64 nByte;
53366#endif /* local variables moved into u.ae */
53367
53368  pIn1 = &aMem[pOp->p1];
53369  pIn2 = &aMem[pOp->p2];
53370  pOut = &aMem[pOp->p3];
53371  assert( pIn1!=pOut );
53372  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
53373    sqlite3VdbeMemSetNull(pOut);
53374    break;
53375  }
53376  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
53377  Stringify(pIn1, encoding);
53378  Stringify(pIn2, encoding);
53379  u.ae.nByte = pIn1->n + pIn2->n;
53380  if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
53381    goto too_big;
53382  }
53383  MemSetTypeFlag(pOut, MEM_Str);
53384  if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
53385    goto no_mem;
53386  }
53387  if( pOut!=pIn2 ){
53388    memcpy(pOut->z, pIn2->z, pIn2->n);
53389  }
53390  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
53391  pOut->z[u.ae.nByte] = 0;
53392  pOut->z[u.ae.nByte+1] = 0;
53393  pOut->flags |= MEM_Term;
53394  pOut->n = (int)u.ae.nByte;
53395  pOut->enc = encoding;
53396  UPDATE_MAX_BLOBSIZE(pOut);
53397  break;
53398}
53399
53400/* Opcode: Add P1 P2 P3 * *
53401**
53402** Add the value in register P1 to the value in register P2
53403** and store the result in register P3.
53404** If either input is NULL, the result is NULL.
53405*/
53406/* Opcode: Multiply P1 P2 P3 * *
53407**
53408**
53409** Multiply the value in register P1 by the value in register P2
53410** and store the result in register P3.
53411** If either input is NULL, the result is NULL.
53412*/
53413/* Opcode: Subtract P1 P2 P3 * *
53414**
53415** Subtract the value in register P1 from the value in register P2
53416** and store the result in register P3.
53417** If either input is NULL, the result is NULL.
53418*/
53419/* Opcode: Divide P1 P2 P3 * *
53420**
53421** Divide the value in register P1 by the value in register P2
53422** and store the result in register P3 (P3=P2/P1). If the value in
53423** register P1 is zero, then the result is NULL. If either input is
53424** NULL, the result is NULL.
53425*/
53426/* Opcode: Remainder P1 P2 P3 * *
53427**
53428** Compute the remainder after integer division of the value in
53429** register P1 by the value in register P2 and store the result in P3.
53430** If the value in register P2 is zero the result is NULL.
53431** If either operand is NULL, the result is NULL.
53432*/
53433case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
53434case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
53435case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
53436case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
53437case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
53438#if 0  /* local variables moved into u.af */
53439  int flags;      /* Combined MEM_* flags from both inputs */
53440  i64 iA;         /* Integer value of left operand */
53441  i64 iB;         /* Integer value of right operand */
53442  double rA;      /* Real value of left operand */
53443  double rB;      /* Real value of right operand */
53444#endif /* local variables moved into u.af */
53445
53446  pIn1 = &aMem[pOp->p1];
53447  applyNumericAffinity(pIn1);
53448  pIn2 = &aMem[pOp->p2];
53449  applyNumericAffinity(pIn2);
53450  pOut = &aMem[pOp->p3];
53451  u.af.flags = pIn1->flags | pIn2->flags;
53452  if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
53453  if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
53454    u.af.iA = pIn1->u.i;
53455    u.af.iB = pIn2->u.i;
53456    switch( pOp->opcode ){
53457      case OP_Add:         u.af.iB += u.af.iA;       break;
53458      case OP_Subtract:    u.af.iB -= u.af.iA;       break;
53459      case OP_Multiply:    u.af.iB *= u.af.iA;       break;
53460      case OP_Divide: {
53461        if( u.af.iA==0 ) goto arithmetic_result_is_null;
53462        /* Dividing the largest possible negative 64-bit integer (1<<63) by
53463        ** -1 returns an integer too large to store in a 64-bit data-type. On
53464        ** some architectures, the value overflows to (1<<63). On others,
53465        ** a SIGFPE is issued. The following statement normalizes this
53466        ** behavior so that all architectures behave as if integer
53467        ** overflow occurred.
53468        */
53469        if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) u.af.iA = 1;
53470        u.af.iB /= u.af.iA;
53471        break;
53472      }
53473      default: {
53474        if( u.af.iA==0 ) goto arithmetic_result_is_null;
53475        if( u.af.iA==-1 ) u.af.iA = 1;
53476        u.af.iB %= u.af.iA;
53477        break;
53478      }
53479    }
53480    pOut->u.i = u.af.iB;
53481    MemSetTypeFlag(pOut, MEM_Int);
53482  }else{
53483    u.af.rA = sqlite3VdbeRealValue(pIn1);
53484    u.af.rB = sqlite3VdbeRealValue(pIn2);
53485    switch( pOp->opcode ){
53486      case OP_Add:         u.af.rB += u.af.rA;       break;
53487      case OP_Subtract:    u.af.rB -= u.af.rA;       break;
53488      case OP_Multiply:    u.af.rB *= u.af.rA;       break;
53489      case OP_Divide: {
53490        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
53491        if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
53492        u.af.rB /= u.af.rA;
53493        break;
53494      }
53495      default: {
53496        u.af.iA = (i64)u.af.rA;
53497        u.af.iB = (i64)u.af.rB;
53498        if( u.af.iA==0 ) goto arithmetic_result_is_null;
53499        if( u.af.iA==-1 ) u.af.iA = 1;
53500        u.af.rB = (double)(u.af.iB % u.af.iA);
53501        break;
53502      }
53503    }
53504    if( sqlite3IsNaN(u.af.rB) ){
53505      goto arithmetic_result_is_null;
53506    }
53507    pOut->r = u.af.rB;
53508    MemSetTypeFlag(pOut, MEM_Real);
53509    if( (u.af.flags & MEM_Real)==0 ){
53510      sqlite3VdbeIntegerAffinity(pOut);
53511    }
53512  }
53513  break;
53514
53515arithmetic_result_is_null:
53516  sqlite3VdbeMemSetNull(pOut);
53517  break;
53518}
53519
53520/* Opcode: CollSeq * * P4
53521**
53522** P4 is a pointer to a CollSeq struct. If the next call to a user function
53523** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
53524** be returned. This is used by the built-in min(), max() and nullif()
53525** functions.
53526**
53527** The interface used by the implementation of the aforementioned functions
53528** to retrieve the collation sequence set by this opcode is not available
53529** publicly, only to user functions defined in func.c.
53530*/
53531case OP_CollSeq: {
53532  assert( pOp->p4type==P4_COLLSEQ );
53533  break;
53534}
53535
53536/* Opcode: Function P1 P2 P3 P4 P5
53537**
53538** Invoke a user function (P4 is a pointer to a Function structure that
53539** defines the function) with P5 arguments taken from register P2 and
53540** successors.  The result of the function is stored in register P3.
53541** Register P3 must not be one of the function inputs.
53542**
53543** P1 is a 32-bit bitmask indicating whether or not each argument to the
53544** function was determined to be constant at compile time. If the first
53545** argument was constant then bit 0 of P1 is set. This is used to determine
53546** whether meta data associated with a user function argument using the
53547** sqlite3_set_auxdata() API may be safely retained until the next
53548** invocation of this opcode.
53549**
53550** See also: AggStep and AggFinal
53551*/
53552case OP_Function: {
53553#if 0  /* local variables moved into u.ag */
53554  int i;
53555  Mem *pArg;
53556  sqlite3_context ctx;
53557  sqlite3_value **apVal;
53558  int n;
53559#endif /* local variables moved into u.ag */
53560
53561  u.ag.n = pOp->p5;
53562  u.ag.apVal = p->apArg;
53563  assert( u.ag.apVal || u.ag.n==0 );
53564
53565  assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
53566  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
53567  u.ag.pArg = &aMem[pOp->p2];
53568  for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
53569    u.ag.apVal[u.ag.i] = u.ag.pArg;
53570    sqlite3VdbeMemStoreType(u.ag.pArg);
53571    REGISTER_TRACE(pOp->p2, u.ag.pArg);
53572  }
53573
53574  assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
53575  if( pOp->p4type==P4_FUNCDEF ){
53576    u.ag.ctx.pFunc = pOp->p4.pFunc;
53577    u.ag.ctx.pVdbeFunc = 0;
53578  }else{
53579    u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
53580    u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
53581  }
53582
53583  assert( pOp->p3>0 && pOp->p3<=p->nMem );
53584  pOut = &aMem[pOp->p3];
53585  u.ag.ctx.s.flags = MEM_Null;
53586  u.ag.ctx.s.db = db;
53587  u.ag.ctx.s.xDel = 0;
53588  u.ag.ctx.s.zMalloc = 0;
53589
53590  /* The output cell may already have a buffer allocated. Move
53591  ** the pointer to u.ag.ctx.s so in case the user-function can use
53592  ** the already allocated buffer instead of allocating a new one.
53593  */
53594  sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
53595  MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
53596
53597  u.ag.ctx.isError = 0;
53598  if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
53599    assert( pOp>aOp );
53600    assert( pOp[-1].p4type==P4_COLLSEQ );
53601    assert( pOp[-1].opcode==OP_CollSeq );
53602    u.ag.ctx.pColl = pOp[-1].p4.pColl;
53603  }
53604  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
53605  (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal);
53606  if( sqlite3SafetyOn(db) ){
53607    sqlite3VdbeMemRelease(&u.ag.ctx.s);
53608    goto abort_due_to_misuse;
53609  }
53610  if( db->mallocFailed ){
53611    /* Even though a malloc() has failed, the implementation of the
53612    ** user function may have called an sqlite3_result_XXX() function
53613    ** to return a value. The following call releases any resources
53614    ** associated with such a value.
53615    **
53616    ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
53617    ** fails also (the if(...) statement above). But if people are
53618    ** misusing sqlite, they have bigger problems than a leaked value.
53619    */
53620    sqlite3VdbeMemRelease(&u.ag.ctx.s);
53621    goto no_mem;
53622  }
53623
53624  /* If any auxiliary data functions have been called by this user function,
53625  ** immediately call the destructor for any non-static values.
53626  */
53627  if( u.ag.ctx.pVdbeFunc ){
53628    sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
53629    pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
53630    pOp->p4type = P4_VDBEFUNC;
53631  }
53632
53633  /* If the function returned an error, throw an exception */
53634  if( u.ag.ctx.isError ){
53635    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
53636    rc = u.ag.ctx.isError;
53637  }
53638
53639  /* Copy the result of the function into register P3 */
53640  sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
53641  sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
53642  if( sqlite3VdbeMemTooBig(pOut) ){
53643    goto too_big;
53644  }
53645  REGISTER_TRACE(pOp->p3, pOut);
53646  UPDATE_MAX_BLOBSIZE(pOut);
53647  break;
53648}
53649
53650/* Opcode: BitAnd P1 P2 P3 * *
53651**
53652** Take the bit-wise AND of the values in register P1 and P2 and
53653** store the result in register P3.
53654** If either input is NULL, the result is NULL.
53655*/
53656/* Opcode: BitOr P1 P2 P3 * *
53657**
53658** Take the bit-wise OR of the values in register P1 and P2 and
53659** store the result in register P3.
53660** If either input is NULL, the result is NULL.
53661*/
53662/* Opcode: ShiftLeft P1 P2 P3 * *
53663**
53664** Shift the integer value in register P2 to the left by the
53665** number of bits specified by the integer in regiser P1.
53666** Store the result in register P3.
53667** If either input is NULL, the result is NULL.
53668*/
53669/* Opcode: ShiftRight P1 P2 P3 * *
53670**
53671** Shift the integer value in register P2 to the right by the
53672** number of bits specified by the integer in register P1.
53673** Store the result in register P3.
53674** If either input is NULL, the result is NULL.
53675*/
53676case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
53677case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
53678case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
53679case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
53680#if 0  /* local variables moved into u.ah */
53681  i64 a;
53682  i64 b;
53683#endif /* local variables moved into u.ah */
53684
53685  pIn1 = &aMem[pOp->p1];
53686  pIn2 = &aMem[pOp->p2];
53687  pOut = &aMem[pOp->p3];
53688  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
53689    sqlite3VdbeMemSetNull(pOut);
53690    break;
53691  }
53692  u.ah.a = sqlite3VdbeIntValue(pIn2);
53693  u.ah.b = sqlite3VdbeIntValue(pIn1);
53694  switch( pOp->opcode ){
53695    case OP_BitAnd:      u.ah.a &= u.ah.b;     break;
53696    case OP_BitOr:       u.ah.a |= u.ah.b;     break;
53697    case OP_ShiftLeft:   u.ah.a <<= u.ah.b;    break;
53698    default:  assert( pOp->opcode==OP_ShiftRight );
53699                         u.ah.a >>= u.ah.b;    break;
53700  }
53701  pOut->u.i = u.ah.a;
53702  MemSetTypeFlag(pOut, MEM_Int);
53703  break;
53704}
53705
53706/* Opcode: AddImm  P1 P2 * * *
53707**
53708** Add the constant P2 to the value in register P1.
53709** The result is always an integer.
53710**
53711** To force any register to be an integer, just add 0.
53712*/
53713case OP_AddImm: {            /* in1 */
53714  pIn1 = &aMem[pOp->p1];
53715  sqlite3VdbeMemIntegerify(pIn1);
53716  pIn1->u.i += pOp->p2;
53717  break;
53718}
53719
53720/* Opcode: MustBeInt P1 P2 * * *
53721**
53722** Force the value in register P1 to be an integer.  If the value
53723** in P1 is not an integer and cannot be converted into an integer
53724** without data loss, then jump immediately to P2, or if P2==0
53725** raise an SQLITE_MISMATCH exception.
53726*/
53727case OP_MustBeInt: {            /* jump, in1 */
53728  pIn1 = &aMem[pOp->p1];
53729  applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
53730  if( (pIn1->flags & MEM_Int)==0 ){
53731    if( pOp->p2==0 ){
53732      rc = SQLITE_MISMATCH;
53733      goto abort_due_to_error;
53734    }else{
53735      pc = pOp->p2 - 1;
53736    }
53737  }else{
53738    MemSetTypeFlag(pIn1, MEM_Int);
53739  }
53740  break;
53741}
53742
53743/* Opcode: RealAffinity P1 * * * *
53744**
53745** If register P1 holds an integer convert it to a real value.
53746**
53747** This opcode is used when extracting information from a column that
53748** has REAL affinity.  Such column values may still be stored as
53749** integers, for space efficiency, but after extraction we want them
53750** to have only a real value.
53751*/
53752case OP_RealAffinity: {                  /* in1 */
53753  pIn1 = &aMem[pOp->p1];
53754  if( pIn1->flags & MEM_Int ){
53755    sqlite3VdbeMemRealify(pIn1);
53756  }
53757  break;
53758}
53759
53760#ifndef SQLITE_OMIT_CAST
53761/* Opcode: ToText P1 * * * *
53762**
53763** Force the value in register P1 to be text.
53764** If the value is numeric, convert it to a string using the
53765** equivalent of printf().  Blob values are unchanged and
53766** are afterwards simply interpreted as text.
53767**
53768** A NULL value is not changed by this routine.  It remains NULL.
53769*/
53770case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
53771  pIn1 = &aMem[pOp->p1];
53772  if( pIn1->flags & MEM_Null ) break;
53773  assert( MEM_Str==(MEM_Blob>>3) );
53774  pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
53775  applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
53776  rc = ExpandBlob(pIn1);
53777  assert( pIn1->flags & MEM_Str || db->mallocFailed );
53778  pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
53779  UPDATE_MAX_BLOBSIZE(pIn1);
53780  break;
53781}
53782
53783/* Opcode: ToBlob P1 * * * *
53784**
53785** Force the value in register P1 to be a BLOB.
53786** If the value is numeric, convert it to a string first.
53787** Strings are simply reinterpreted as blobs with no change
53788** to the underlying data.
53789**
53790** A NULL value is not changed by this routine.  It remains NULL.
53791*/
53792case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
53793  pIn1 = &aMem[pOp->p1];
53794  if( pIn1->flags & MEM_Null ) break;
53795  if( (pIn1->flags & MEM_Blob)==0 ){
53796    applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
53797    assert( pIn1->flags & MEM_Str || db->mallocFailed );
53798    MemSetTypeFlag(pIn1, MEM_Blob);
53799  }else{
53800    pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
53801  }
53802  UPDATE_MAX_BLOBSIZE(pIn1);
53803  break;
53804}
53805
53806/* Opcode: ToNumeric P1 * * * *
53807**
53808** Force the value in register P1 to be numeric (either an
53809** integer or a floating-point number.)
53810** If the value is text or blob, try to convert it to an using the
53811** equivalent of atoi() or atof() and store 0 if no such conversion
53812** is possible.
53813**
53814** A NULL value is not changed by this routine.  It remains NULL.
53815*/
53816case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
53817  pIn1 = &aMem[pOp->p1];
53818  if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
53819    sqlite3VdbeMemNumerify(pIn1);
53820  }
53821  break;
53822}
53823#endif /* SQLITE_OMIT_CAST */
53824
53825/* Opcode: ToInt P1 * * * *
53826**
53827** Force the value in register P1 be an integer.  If
53828** The value is currently a real number, drop its fractional part.
53829** If the value is text or blob, try to convert it to an integer using the
53830** equivalent of atoi() and store 0 if no such conversion is possible.
53831**
53832** A NULL value is not changed by this routine.  It remains NULL.
53833*/
53834case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
53835  pIn1 = &aMem[pOp->p1];
53836  if( (pIn1->flags & MEM_Null)==0 ){
53837    sqlite3VdbeMemIntegerify(pIn1);
53838  }
53839  break;
53840}
53841
53842#ifndef SQLITE_OMIT_CAST
53843/* Opcode: ToReal P1 * * * *
53844**
53845** Force the value in register P1 to be a floating point number.
53846** If The value is currently an integer, convert it.
53847** If the value is text or blob, try to convert it to an integer using the
53848** equivalent of atoi() and store 0.0 if no such conversion is possible.
53849**
53850** A NULL value is not changed by this routine.  It remains NULL.
53851*/
53852case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
53853  pIn1 = &aMem[pOp->p1];
53854  if( (pIn1->flags & MEM_Null)==0 ){
53855    sqlite3VdbeMemRealify(pIn1);
53856  }
53857  break;
53858}
53859#endif /* SQLITE_OMIT_CAST */
53860
53861/* Opcode: Lt P1 P2 P3 P4 P5
53862**
53863** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
53864** jump to address P2.
53865**
53866** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
53867** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
53868** bit is clear then fall thru if either operand is NULL.
53869**
53870** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
53871** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
53872** to coerce both inputs according to this affinity before the
53873** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
53874** affinity is used. Note that the affinity conversions are stored
53875** back into the input registers P1 and P3.  So this opcode can cause
53876** persistent changes to registers P1 and P3.
53877**
53878** Once any conversions have taken place, and neither value is NULL,
53879** the values are compared. If both values are blobs then memcmp() is
53880** used to determine the results of the comparison.  If both values
53881** are text, then the appropriate collating function specified in
53882** P4 is  used to do the comparison.  If P4 is not specified then
53883** memcmp() is used to compare text string.  If both values are
53884** numeric, then a numeric comparison is used. If the two values
53885** are of different types, then numbers are considered less than
53886** strings and strings are considered less than blobs.
53887**
53888** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
53889** store a boolean result (either 0, or 1, or NULL) in register P2.
53890*/
53891/* Opcode: Ne P1 P2 P3 P4 P5
53892**
53893** This works just like the Lt opcode except that the jump is taken if
53894** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
53895** additional information.
53896**
53897** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
53898** true or false and is never NULL.  If both operands are NULL then the result
53899** of comparison is false.  If either operand is NULL then the result is true.
53900** If neither operand is NULL the the result is the same as it would be if
53901** the SQLITE_NULLEQ flag were omitted from P5.
53902*/
53903/* Opcode: Eq P1 P2 P3 P4 P5
53904**
53905** This works just like the Lt opcode except that the jump is taken if
53906** the operands in registers P1 and P3 are equal.
53907** See the Lt opcode for additional information.
53908**
53909** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
53910** true or false and is never NULL.  If both operands are NULL then the result
53911** of comparison is true.  If either operand is NULL then the result is false.
53912** If neither operand is NULL the the result is the same as it would be if
53913** the SQLITE_NULLEQ flag were omitted from P5.
53914*/
53915/* Opcode: Le P1 P2 P3 P4 P5
53916**
53917** This works just like the Lt opcode except that the jump is taken if
53918** the content of register P3 is less than or equal to the content of
53919** register P1.  See the Lt opcode for additional information.
53920*/
53921/* Opcode: Gt P1 P2 P3 P4 P5
53922**
53923** This works just like the Lt opcode except that the jump is taken if
53924** the content of register P3 is greater than the content of
53925** register P1.  See the Lt opcode for additional information.
53926*/
53927/* Opcode: Ge P1 P2 P3 P4 P5
53928**
53929** This works just like the Lt opcode except that the jump is taken if
53930** the content of register P3 is greater than or equal to the content of
53931** register P1.  See the Lt opcode for additional information.
53932*/
53933case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
53934case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
53935case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
53936case OP_Le:               /* same as TK_LE, jump, in1, in3 */
53937case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
53938case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
53939#if 0  /* local variables moved into u.ai */
53940  int res;            /* Result of the comparison of pIn1 against pIn3 */
53941  char affinity;      /* Affinity to use for comparison */
53942#endif /* local variables moved into u.ai */
53943
53944  pIn1 = &aMem[pOp->p1];
53945  pIn3 = &aMem[pOp->p3];
53946  if( (pIn1->flags | pIn3->flags)&MEM_Null ){
53947    /* One or both operands are NULL */
53948    if( pOp->p5 & SQLITE_NULLEQ ){
53949      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
53950      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
53951      ** or not both operands are null.
53952      */
53953      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
53954      u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
53955    }else{
53956      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
53957      ** then the result is always NULL.
53958      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
53959      */
53960      if( pOp->p5 & SQLITE_STOREP2 ){
53961        pOut = &aMem[pOp->p2];
53962        MemSetTypeFlag(pOut, MEM_Null);
53963        REGISTER_TRACE(pOp->p2, pOut);
53964      }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
53965        pc = pOp->p2-1;
53966      }
53967      break;
53968    }
53969  }else{
53970    /* Neither operand is NULL.  Do a comparison. */
53971    u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
53972    if( u.ai.affinity ){
53973      applyAffinity(pIn1, u.ai.affinity, encoding);
53974      applyAffinity(pIn3, u.ai.affinity, encoding);
53975      if( db->mallocFailed ) goto no_mem;
53976    }
53977
53978    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
53979    ExpandBlob(pIn1);
53980    ExpandBlob(pIn3);
53981    u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
53982  }
53983  switch( pOp->opcode ){
53984    case OP_Eq:    u.ai.res = u.ai.res==0;     break;
53985    case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
53986    case OP_Lt:    u.ai.res = u.ai.res<0;      break;
53987    case OP_Le:    u.ai.res = u.ai.res<=0;     break;
53988    case OP_Gt:    u.ai.res = u.ai.res>0;      break;
53989    default:       u.ai.res = u.ai.res>=0;     break;
53990  }
53991
53992  if( pOp->p5 & SQLITE_STOREP2 ){
53993    pOut = &aMem[pOp->p2];
53994    MemSetTypeFlag(pOut, MEM_Int);
53995    pOut->u.i = u.ai.res;
53996    REGISTER_TRACE(pOp->p2, pOut);
53997  }else if( u.ai.res ){
53998    pc = pOp->p2-1;
53999  }
54000  break;
54001}
54002
54003/* Opcode: Permutation * * * P4 *
54004**
54005** Set the permutation used by the OP_Compare operator to be the array
54006** of integers in P4.
54007**
54008** The permutation is only valid until the next OP_Permutation, OP_Compare,
54009** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
54010** immediately prior to the OP_Compare.
54011*/
54012case OP_Permutation: {
54013  assert( pOp->p4type==P4_INTARRAY );
54014  assert( pOp->p4.ai );
54015  aPermute = pOp->p4.ai;
54016  break;
54017}
54018
54019/* Opcode: Compare P1 P2 P3 P4 *
54020**
54021** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
54022** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
54023** the comparison for use by the next OP_Jump instruct.
54024**
54025** P4 is a KeyInfo structure that defines collating sequences and sort
54026** orders for the comparison.  The permutation applies to registers
54027** only.  The KeyInfo elements are used sequentially.
54028**
54029** The comparison is a sort comparison, so NULLs compare equal,
54030** NULLs are less than numbers, numbers are less than strings,
54031** and strings are less than blobs.
54032*/
54033case OP_Compare: {
54034#if 0  /* local variables moved into u.aj */
54035  int n;
54036  int i;
54037  int p1;
54038  int p2;
54039  const KeyInfo *pKeyInfo;
54040  int idx;
54041  CollSeq *pColl;    /* Collating sequence to use on this term */
54042  int bRev;          /* True for DESCENDING sort order */
54043#endif /* local variables moved into u.aj */
54044
54045  u.aj.n = pOp->p3;
54046  u.aj.pKeyInfo = pOp->p4.pKeyInfo;
54047  assert( u.aj.n>0 );
54048  assert( u.aj.pKeyInfo!=0 );
54049  u.aj.p1 = pOp->p1;
54050  u.aj.p2 = pOp->p2;
54051#if SQLITE_DEBUG
54052  if( aPermute ){
54053    int k, mx = 0;
54054    for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
54055    assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
54056    assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
54057  }else{
54058    assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
54059    assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
54060  }
54061#endif /* SQLITE_DEBUG */
54062  for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
54063    u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
54064    REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
54065    REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
54066    assert( u.aj.i<u.aj.pKeyInfo->nField );
54067    u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
54068    u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
54069    iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
54070    if( iCompare ){
54071      if( u.aj.bRev ) iCompare = -iCompare;
54072      break;
54073    }
54074  }
54075  aPermute = 0;
54076  break;
54077}
54078
54079/* Opcode: Jump P1 P2 P3 * *
54080**
54081** Jump to the instruction at address P1, P2, or P3 depending on whether
54082** in the most recent OP_Compare instruction the P1 vector was less than
54083** equal to, or greater than the P2 vector, respectively.
54084*/
54085case OP_Jump: {             /* jump */
54086  if( iCompare<0 ){
54087    pc = pOp->p1 - 1;
54088  }else if( iCompare==0 ){
54089    pc = pOp->p2 - 1;
54090  }else{
54091    pc = pOp->p3 - 1;
54092  }
54093  break;
54094}
54095
54096/* Opcode: And P1 P2 P3 * *
54097**
54098** Take the logical AND of the values in registers P1 and P2 and
54099** write the result into register P3.
54100**
54101** If either P1 or P2 is 0 (false) then the result is 0 even if
54102** the other input is NULL.  A NULL and true or two NULLs give
54103** a NULL output.
54104*/
54105/* Opcode: Or P1 P2 P3 * *
54106**
54107** Take the logical OR of the values in register P1 and P2 and
54108** store the answer in register P3.
54109**
54110** If either P1 or P2 is nonzero (true) then the result is 1 (true)
54111** even if the other input is NULL.  A NULL and false or two NULLs
54112** give a NULL output.
54113*/
54114case OP_And:              /* same as TK_AND, in1, in2, out3 */
54115case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
54116#if 0  /* local variables moved into u.ak */
54117  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
54118  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
54119#endif /* local variables moved into u.ak */
54120
54121  pIn1 = &aMem[pOp->p1];
54122  if( pIn1->flags & MEM_Null ){
54123    u.ak.v1 = 2;
54124  }else{
54125    u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
54126  }
54127  pIn2 = &aMem[pOp->p2];
54128  if( pIn2->flags & MEM_Null ){
54129    u.ak.v2 = 2;
54130  }else{
54131    u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
54132  }
54133  if( pOp->opcode==OP_And ){
54134    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
54135    u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
54136  }else{
54137    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
54138    u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
54139  }
54140  pOut = &aMem[pOp->p3];
54141  if( u.ak.v1==2 ){
54142    MemSetTypeFlag(pOut, MEM_Null);
54143  }else{
54144    pOut->u.i = u.ak.v1;
54145    MemSetTypeFlag(pOut, MEM_Int);
54146  }
54147  break;
54148}
54149
54150/* Opcode: Not P1 P2 * * *
54151**
54152** Interpret the value in register P1 as a boolean value.  Store the
54153** boolean complement in register P2.  If the value in register P1 is
54154** NULL, then a NULL is stored in P2.
54155*/
54156case OP_Not: {                /* same as TK_NOT, in1, out2 */
54157  pIn1 = &aMem[pOp->p1];
54158  pOut = &aMem[pOp->p2];
54159  if( pIn1->flags & MEM_Null ){
54160    sqlite3VdbeMemSetNull(pOut);
54161  }else{
54162    sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
54163  }
54164  break;
54165}
54166
54167/* Opcode: BitNot P1 P2 * * *
54168**
54169** Interpret the content of register P1 as an integer.  Store the
54170** ones-complement of the P1 value into register P2.  If P1 holds
54171** a NULL then store a NULL in P2.
54172*/
54173case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
54174  pIn1 = &aMem[pOp->p1];
54175  pOut = &aMem[pOp->p2];
54176  if( pIn1->flags & MEM_Null ){
54177    sqlite3VdbeMemSetNull(pOut);
54178  }else{
54179    sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
54180  }
54181  break;
54182}
54183
54184/* Opcode: If P1 P2 P3 * *
54185**
54186** Jump to P2 if the value in register P1 is true.  The value is
54187** is considered true if it is numeric and non-zero.  If the value
54188** in P1 is NULL then take the jump if P3 is true.
54189*/
54190/* Opcode: IfNot P1 P2 P3 * *
54191**
54192** Jump to P2 if the value in register P1 is False.  The value is
54193** is considered true if it has a numeric value of zero.  If the value
54194** in P1 is NULL then take the jump if P3 is true.
54195*/
54196case OP_If:                 /* jump, in1 */
54197case OP_IfNot: {            /* jump, in1 */
54198#if 0  /* local variables moved into u.al */
54199  int c;
54200#endif /* local variables moved into u.al */
54201  pIn1 = &aMem[pOp->p1];
54202  if( pIn1->flags & MEM_Null ){
54203    u.al.c = pOp->p3;
54204  }else{
54205#ifdef SQLITE_OMIT_FLOATING_POINT
54206    u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
54207#else
54208    u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
54209#endif
54210    if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
54211  }
54212  if( u.al.c ){
54213    pc = pOp->p2-1;
54214  }
54215  break;
54216}
54217
54218/* Opcode: IsNull P1 P2 * * *
54219**
54220** Jump to P2 if the value in register P1 is NULL.
54221*/
54222case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
54223  pIn1 = &aMem[pOp->p1];
54224  if( (pIn1->flags & MEM_Null)!=0 ){
54225    pc = pOp->p2 - 1;
54226  }
54227  break;
54228}
54229
54230/* Opcode: NotNull P1 P2 * * *
54231**
54232** Jump to P2 if the value in register P1 is not NULL.
54233*/
54234case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
54235  pIn1 = &aMem[pOp->p1];
54236  if( (pIn1->flags & MEM_Null)==0 ){
54237    pc = pOp->p2 - 1;
54238  }
54239  break;
54240}
54241
54242/* Opcode: Column P1 P2 P3 P4 P5
54243**
54244** Interpret the data that cursor P1 points to as a structure built using
54245** the MakeRecord instruction.  (See the MakeRecord opcode for additional
54246** information about the format of the data.)  Extract the P2-th column
54247** from this record.  If there are less that (P2+1)
54248** values in the record, extract a NULL.
54249**
54250** The value extracted is stored in register P3.
54251**
54252** If the column contains fewer than P2 fields, then extract a NULL.  Or,
54253** if the P4 argument is a P4_MEM use the value of the P4 argument as
54254** the result.
54255**
54256** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
54257** then the cache of the cursor is reset prior to extracting the column.
54258** The first OP_Column against a pseudo-table after the value of the content
54259** register has changed should have this bit set.
54260*/
54261case OP_Column: {
54262#if 0  /* local variables moved into u.am */
54263  u32 payloadSize;   /* Number of bytes in the record */
54264  i64 payloadSize64; /* Number of bytes in the record */
54265  int p1;            /* P1 value of the opcode */
54266  int p2;            /* column number to retrieve */
54267  VdbeCursor *pC;    /* The VDBE cursor */
54268  char *zRec;        /* Pointer to complete record-data */
54269  BtCursor *pCrsr;   /* The BTree cursor */
54270  u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
54271  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
54272  int nField;        /* number of fields in the record */
54273  int len;           /* The length of the serialized data for the column */
54274  int i;             /* Loop counter */
54275  char *zData;       /* Part of the record being decoded */
54276  Mem *pDest;        /* Where to write the extracted value */
54277  Mem sMem;          /* For storing the record being decoded */
54278  u8 *zIdx;          /* Index into header */
54279  u8 *zEndHdr;       /* Pointer to first byte after the header */
54280  u32 offset;        /* Offset into the data */
54281  u64 offset64;      /* 64-bit offset.  64 bits needed to catch overflow */
54282  int szHdr;         /* Size of the header size field at start of record */
54283  int avail;         /* Number of bytes of available data */
54284  Mem *pReg;         /* PseudoTable input register */
54285#endif /* local variables moved into u.am */
54286
54287
54288  u.am.p1 = pOp->p1;
54289  u.am.p2 = pOp->p2;
54290  u.am.pC = 0;
54291  memset(&u.am.sMem, 0, sizeof(u.am.sMem));
54292  assert( u.am.p1<p->nCursor );
54293  assert( pOp->p3>0 && pOp->p3<=p->nMem );
54294  u.am.pDest = &aMem[pOp->p3];
54295  MemSetTypeFlag(u.am.pDest, MEM_Null);
54296  u.am.zRec = 0;
54297
54298  /* This block sets the variable u.am.payloadSize to be the total number of
54299  ** bytes in the record.
54300  **
54301  ** u.am.zRec is set to be the complete text of the record if it is available.
54302  ** The complete record text is always available for pseudo-tables
54303  ** If the record is stored in a cursor, the complete record text
54304  ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
54305  ** If the data is unavailable,  u.am.zRec is set to NULL.
54306  **
54307  ** We also compute the number of columns in the record.  For cursors,
54308  ** the number of columns is stored in the VdbeCursor.nField element.
54309  */
54310  u.am.pC = p->apCsr[u.am.p1];
54311  assert( u.am.pC!=0 );
54312#ifndef SQLITE_OMIT_VIRTUALTABLE
54313  assert( u.am.pC->pVtabCursor==0 );
54314#endif
54315  u.am.pCrsr = u.am.pC->pCursor;
54316  if( u.am.pCrsr!=0 ){
54317    /* The record is stored in a B-Tree */
54318    rc = sqlite3VdbeCursorMoveto(u.am.pC);
54319    if( rc ) goto abort_due_to_error;
54320    if( u.am.pC->nullRow ){
54321      u.am.payloadSize = 0;
54322    }else if( u.am.pC->cacheStatus==p->cacheCtr ){
54323      u.am.payloadSize = u.am.pC->payloadSize;
54324      u.am.zRec = (char*)u.am.pC->aRow;
54325    }else if( u.am.pC->isIndex ){
54326      assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
54327      rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
54328      assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
54329      /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
54330      ** payload size, so it is impossible for u.am.payloadSize64 to be
54331      ** larger than 32 bits. */
54332      assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
54333      u.am.payloadSize = (u32)u.am.payloadSize64;
54334    }else{
54335      assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
54336      rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
54337      assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
54338    }
54339  }else if( u.am.pC->pseudoTableReg>0 ){
54340    u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
54341    assert( u.am.pReg->flags & MEM_Blob );
54342    u.am.payloadSize = u.am.pReg->n;
54343    u.am.zRec = u.am.pReg->z;
54344    u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
54345    assert( u.am.payloadSize==0 || u.am.zRec!=0 );
54346  }else{
54347    /* Consider the row to be NULL */
54348    u.am.payloadSize = 0;
54349  }
54350
54351  /* If u.am.payloadSize is 0, then just store a NULL */
54352  if( u.am.payloadSize==0 ){
54353    assert( u.am.pDest->flags&MEM_Null );
54354    goto op_column_out;
54355  }
54356  assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
54357  if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
54358    goto too_big;
54359  }
54360
54361  u.am.nField = u.am.pC->nField;
54362  assert( u.am.p2<u.am.nField );
54363
54364  /* Read and parse the table header.  Store the results of the parse
54365  ** into the record header cache fields of the cursor.
54366  */
54367  u.am.aType = u.am.pC->aType;
54368  if( u.am.pC->cacheStatus==p->cacheCtr ){
54369    u.am.aOffset = u.am.pC->aOffset;
54370  }else{
54371    assert(u.am.aType);
54372    u.am.avail = 0;
54373    u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
54374    u.am.pC->payloadSize = u.am.payloadSize;
54375    u.am.pC->cacheStatus = p->cacheCtr;
54376
54377    /* Figure out how many bytes are in the header */
54378    if( u.am.zRec ){
54379      u.am.zData = u.am.zRec;
54380    }else{
54381      if( u.am.pC->isIndex ){
54382        u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
54383      }else{
54384        u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
54385      }
54386      /* If KeyFetch()/DataFetch() managed to get the entire payload,
54387      ** save the payload in the u.am.pC->aRow cache.  That will save us from
54388      ** having to make additional calls to fetch the content portion of
54389      ** the record.
54390      */
54391      assert( u.am.avail>=0 );
54392      if( u.am.payloadSize <= (u32)u.am.avail ){
54393        u.am.zRec = u.am.zData;
54394        u.am.pC->aRow = (u8*)u.am.zData;
54395      }else{
54396        u.am.pC->aRow = 0;
54397      }
54398    }
54399    /* The following assert is true in all cases accept when
54400    ** the database file has been corrupted externally.
54401    **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
54402    u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
54403
54404    /* Make sure a corrupt database has not given us an oversize header.
54405    ** Do this now to avoid an oversize memory allocation.
54406    **
54407    ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
54408    ** types use so much data space that there can only be 4096 and 32 of
54409    ** them, respectively.  So the maximum header length results from a
54410    ** 3-byte type for each of the maximum of 32768 columns plus three
54411    ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
54412    */
54413    if( u.am.offset > 98307 ){
54414      rc = SQLITE_CORRUPT_BKPT(OVERSIZE_HEADER_CORRUPTION); // Android Change
54415      goto op_column_out;
54416    }
54417
54418    /* Compute in u.am.len the number of bytes of data we need to read in order
54419    ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
54420    ** u.am.nField might be significantly less than the true number of columns
54421    ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
54422    ** We want to minimize u.am.len in order to limit the size of the memory
54423    ** allocation, especially if a corrupt database file has caused u.am.offset
54424    ** to be oversized. Offset is limited to 98307 above.  But 98307 might
54425    ** still exceed Robson memory allocation limits on some configurations.
54426    ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
54427    ** will likely be much smaller since u.am.nField will likely be less than
54428    ** 20 or so.  This insures that Robson memory allocation limits are
54429    ** not exceeded even for corrupt database files.
54430    */
54431    u.am.len = u.am.nField*5 + 3;
54432    if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
54433
54434    /* The KeyFetch() or DataFetch() above are fast and will get the entire
54435    ** record header in most cases.  But they will fail to get the complete
54436    ** record header if the record header does not fit on a single page
54437    ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
54438    ** acquire the complete header text.
54439    */
54440    if( !u.am.zRec && u.am.avail<u.am.len ){
54441      u.am.sMem.flags = 0;
54442      u.am.sMem.db = 0;
54443      rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
54444      if( rc!=SQLITE_OK ){
54445        goto op_column_out;
54446      }
54447      u.am.zData = u.am.sMem.z;
54448    }
54449    u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
54450    u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
54451
54452    /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
54453    ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
54454    ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
54455    ** of the record to the start of the data for the u.am.i-th column
54456    */
54457    u.am.offset64 = u.am.offset;
54458    for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
54459      if( u.am.zIdx<u.am.zEndHdr ){
54460        u.am.aOffset[u.am.i] = (u32)u.am.offset64;
54461        u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
54462        u.am.offset64 += sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
54463      }else{
54464        /* If u.am.i is less that u.am.nField, then there are less fields in this
54465        ** record than SetNumColumns indicated there are columns in the
54466        ** table. Set the u.am.offset for any extra columns not present in
54467        ** the record to 0. This tells code below to store a NULL
54468        ** instead of deserializing a value from the record.
54469        */
54470        u.am.aOffset[u.am.i] = 0;
54471      }
54472    }
54473    sqlite3VdbeMemRelease(&u.am.sMem);
54474    u.am.sMem.flags = MEM_Null;
54475
54476    /* If we have read more header data than was contained in the header,
54477    ** or if the end of the last field appears to be past the end of the
54478    ** record, or if the end of the last field appears to be before the end
54479    ** of the record (when all fields present), then we must be dealing
54480    ** with a corrupt database.
54481    */
54482    if( (u.am.zIdx > u.am.zEndHdr)|| (u.am.offset64 > u.am.payloadSize)
54483     || (u.am.zIdx==u.am.zEndHdr && u.am.offset64!=(u64)u.am.payloadSize) ){
54484      rc = SQLITE_CORRUPT_BKPT(DATA_CORRUPTION); // Android Change
54485      goto op_column_out;
54486    }
54487  }
54488
54489  /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
54490  ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
54491  ** then there are not enough fields in the record to satisfy the
54492  ** request.  In this case, set the value NULL or to P4 if P4 is
54493  ** a pointer to a Mem object.
54494  */
54495  if( u.am.aOffset[u.am.p2] ){
54496    assert( rc==SQLITE_OK );
54497    if( u.am.zRec ){
54498      sqlite3VdbeMemReleaseExternal(u.am.pDest);
54499      sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
54500    }else{
54501      u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
54502      sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
54503      rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
54504      if( rc!=SQLITE_OK ){
54505        goto op_column_out;
54506      }
54507      u.am.zData = u.am.sMem.z;
54508      sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
54509    }
54510    u.am.pDest->enc = encoding;
54511  }else{
54512    if( pOp->p4type==P4_MEM ){
54513      sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
54514    }else{
54515      assert( u.am.pDest->flags&MEM_Null );
54516    }
54517  }
54518
54519  /* If we dynamically allocated space to hold the data (in the
54520  ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
54521  ** dynamically allocated space over to the u.am.pDest structure.
54522  ** This prevents a memory copy.
54523  */
54524  if( u.am.sMem.zMalloc ){
54525    assert( u.am.sMem.z==u.am.sMem.zMalloc );
54526    assert( !(u.am.pDest->flags & MEM_Dyn) );
54527    assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
54528    u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
54529    u.am.pDest->flags |= MEM_Term;
54530    u.am.pDest->z = u.am.sMem.z;
54531    u.am.pDest->zMalloc = u.am.sMem.zMalloc;
54532  }
54533
54534  rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
54535
54536op_column_out:
54537  UPDATE_MAX_BLOBSIZE(u.am.pDest);
54538  REGISTER_TRACE(pOp->p3, u.am.pDest);
54539  break;
54540}
54541
54542/* Opcode: Affinity P1 P2 * P4 *
54543**
54544** Apply affinities to a range of P2 registers starting with P1.
54545**
54546** P4 is a string that is P2 characters long. The nth character of the
54547** string indicates the column affinity that should be used for the nth
54548** memory cell in the range.
54549*/
54550case OP_Affinity: {
54551#if 0  /* local variables moved into u.an */
54552  const char *zAffinity;   /* The affinity to be applied */
54553  char cAff;               /* A single character of affinity */
54554#endif /* local variables moved into u.an */
54555
54556  u.an.zAffinity = pOp->p4.z;
54557  assert( u.an.zAffinity!=0 );
54558  assert( u.an.zAffinity[pOp->p2]==0 );
54559  pIn1 = &aMem[pOp->p1];
54560  while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
54561    assert( pIn1 <= &p->aMem[p->nMem] );
54562    ExpandBlob(pIn1);
54563    applyAffinity(pIn1, u.an.cAff, encoding);
54564    pIn1++;
54565  }
54566  break;
54567}
54568
54569/* Opcode: MakeRecord P1 P2 P3 P4 *
54570**
54571** Convert P2 registers beginning with P1 into a single entry
54572** suitable for use as a data record in a database table or as a key
54573** in an index.  The details of the format are irrelevant as long as
54574** the OP_Column opcode can decode the record later.
54575** Refer to source code comments for the details of the record
54576** format.
54577**
54578** P4 may be a string that is P2 characters long.  The nth character of the
54579** string indicates the column affinity that should be used for the nth
54580** field of the index key.
54581**
54582** The mapping from character to affinity is given by the SQLITE_AFF_
54583** macros defined in sqliteInt.h.
54584**
54585** If P4 is NULL then all index fields have the affinity NONE.
54586*/
54587case OP_MakeRecord: {
54588#if 0  /* local variables moved into u.ao */
54589  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
54590  Mem *pRec;             /* The new record */
54591  u64 nData;             /* Number of bytes of data space */
54592  int nHdr;              /* Number of bytes of header space */
54593  i64 nByte;             /* Data space required for this record */
54594  int nZero;             /* Number of zero bytes at the end of the record */
54595  int nVarint;           /* Number of bytes in a varint */
54596  u32 serial_type;       /* Type field */
54597  Mem *pData0;           /* First field to be combined into the record */
54598  Mem *pLast;            /* Last field of the record */
54599  int nField;            /* Number of fields in the record */
54600  char *zAffinity;       /* The affinity string for the record */
54601  int file_format;       /* File format to use for encoding */
54602  int i;                 /* Space used in zNewRecord[] */
54603  int len;               /* Length of a field */
54604#endif /* local variables moved into u.ao */
54605
54606  /* Assuming the record contains N fields, the record format looks
54607  ** like this:
54608  **
54609  ** ------------------------------------------------------------------------
54610  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
54611  ** ------------------------------------------------------------------------
54612  **
54613  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
54614  ** and so froth.
54615  **
54616  ** Each type field is a varint representing the serial type of the
54617  ** corresponding data element (see sqlite3VdbeSerialType()). The
54618  ** hdr-size field is also a varint which is the offset from the beginning
54619  ** of the record to data0.
54620  */
54621  u.ao.nData = 0;         /* Number of bytes of data space */
54622  u.ao.nHdr = 0;          /* Number of bytes of header space */
54623  u.ao.nByte = 0;         /* Data space required for this record */
54624  u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
54625  u.ao.nField = pOp->p1;
54626  u.ao.zAffinity = pOp->p4.z;
54627  assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
54628  u.ao.pData0 = &aMem[u.ao.nField];
54629  u.ao.nField = pOp->p2;
54630  u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
54631  u.ao.file_format = p->minWriteFileFormat;
54632
54633  /* Loop through the elements that will make up the record to figure
54634  ** out how much space is required for the new record.
54635  */
54636  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
54637    if( u.ao.zAffinity ){
54638      applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
54639    }
54640    if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
54641      sqlite3VdbeMemExpandBlob(u.ao.pRec);
54642    }
54643    u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
54644    u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
54645    u.ao.nData += u.ao.len;
54646    u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
54647    if( u.ao.pRec->flags & MEM_Zero ){
54648      /* Only pure zero-filled BLOBs can be input to this Opcode.
54649      ** We do not allow blobs with a prefix and a zero-filled tail. */
54650      u.ao.nZero += u.ao.pRec->u.nZero;
54651    }else if( u.ao.len ){
54652      u.ao.nZero = 0;
54653    }
54654  }
54655
54656  /* Add the initial header varint and total the size */
54657  u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
54658  if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
54659    u.ao.nHdr++;
54660  }
54661  u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
54662  if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
54663    goto too_big;
54664  }
54665
54666  /* Make sure the output register has a buffer large enough to store
54667  ** the new record. The output register (pOp->p3) is not allowed to
54668  ** be one of the input registers (because the following call to
54669  ** sqlite3VdbeMemGrow() could clobber the value before it is used).
54670  */
54671  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
54672  pOut = &aMem[pOp->p3];
54673  if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
54674    goto no_mem;
54675  }
54676  u.ao.zNewRecord = (u8 *)pOut->z;
54677
54678  /* Write the record */
54679  u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
54680  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
54681    u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
54682    u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
54683  }
54684  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
54685    u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
54686  }
54687  assert( u.ao.i==u.ao.nByte );
54688
54689  assert( pOp->p3>0 && pOp->p3<=p->nMem );
54690  pOut->n = (int)u.ao.nByte;
54691  pOut->flags = MEM_Blob | MEM_Dyn;
54692  pOut->xDel = 0;
54693  if( u.ao.nZero ){
54694    pOut->u.nZero = u.ao.nZero;
54695    pOut->flags |= MEM_Zero;
54696  }
54697  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
54698  REGISTER_TRACE(pOp->p3, pOut);
54699  UPDATE_MAX_BLOBSIZE(pOut);
54700  break;
54701}
54702
54703/* Opcode: Count P1 P2 * * *
54704**
54705** Store the number of entries (an integer value) in the table or index
54706** opened by cursor P1 in register P2
54707*/
54708#ifndef SQLITE_OMIT_BTREECOUNT
54709case OP_Count: {         /* out2-prerelease */
54710#if 0  /* local variables moved into u.ap */
54711  i64 nEntry;
54712  BtCursor *pCrsr;
54713#endif /* local variables moved into u.ap */
54714
54715  u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
54716  if( u.ap.pCrsr ){
54717    rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
54718  }else{
54719    u.ap.nEntry = 0;
54720  }
54721  pOut->u.i = u.ap.nEntry;
54722  break;
54723}
54724#endif
54725
54726/* Opcode: Savepoint P1 * * P4 *
54727**
54728** Open, release or rollback the savepoint named by parameter P4, depending
54729** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
54730** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
54731*/
54732case OP_Savepoint: {
54733#if 0  /* local variables moved into u.aq */
54734  int p1;                         /* Value of P1 operand */
54735  char *zName;                    /* Name of savepoint */
54736  int nName;
54737  Savepoint *pNew;
54738  Savepoint *pSavepoint;
54739  Savepoint *pTmp;
54740  int iSavepoint;
54741  int ii;
54742#endif /* local variables moved into u.aq */
54743
54744  u.aq.p1 = pOp->p1;
54745  u.aq.zName = pOp->p4.z;
54746
54747  /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
54748  ** transaction, then there cannot be any savepoints.
54749  */
54750  assert( db->pSavepoint==0 || db->autoCommit==0 );
54751  assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
54752  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
54753  assert( checkSavepointCount(db) );
54754
54755  if( u.aq.p1==SAVEPOINT_BEGIN ){
54756    if( db->writeVdbeCnt>0 ){
54757      /* A new savepoint cannot be created if there are active write
54758      ** statements (i.e. open read/write incremental blob handles).
54759      */
54760      sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
54761        "SQL statements in progress");
54762      rc = SQLITE_BUSY;
54763    }else{
54764      u.aq.nName = sqlite3Strlen30(u.aq.zName);
54765
54766      /* Create a new savepoint structure. */
54767      u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
54768      if( u.aq.pNew ){
54769        u.aq.pNew->zName = (char *)&u.aq.pNew[1];
54770        memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
54771
54772        /* If there is no open transaction, then mark this as a special
54773        ** "transaction savepoint". */
54774        if( db->autoCommit ){
54775          db->autoCommit = 0;
54776          db->isTransactionSavepoint = 1;
54777        }else{
54778          db->nSavepoint++;
54779        }
54780
54781        /* Link the new savepoint into the database handle's list. */
54782        u.aq.pNew->pNext = db->pSavepoint;
54783        db->pSavepoint = u.aq.pNew;
54784        u.aq.pNew->nDeferredCons = db->nDeferredCons;
54785      }
54786    }
54787  }else{
54788    u.aq.iSavepoint = 0;
54789
54790    /* Find the named savepoint. If there is no such savepoint, then an
54791    ** an error is returned to the user.  */
54792    for(
54793      u.aq.pSavepoint = db->pSavepoint;
54794      u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
54795      u.aq.pSavepoint = u.aq.pSavepoint->pNext
54796    ){
54797      u.aq.iSavepoint++;
54798    }
54799    if( !u.aq.pSavepoint ){
54800      sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
54801      rc = SQLITE_ERROR;
54802    }else if(
54803        db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
54804    ){
54805      /* It is not possible to release (commit) a savepoint if there are
54806      ** active write statements. It is not possible to rollback a savepoint
54807      ** if there are any active statements at all.
54808      */
54809      sqlite3SetString(&p->zErrMsg, db,
54810        "cannot %s savepoint - SQL statements in progress",
54811        (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
54812      );
54813      rc = SQLITE_BUSY;
54814    }else{
54815
54816      /* Determine whether or not this is a transaction savepoint. If so,
54817      ** and this is a RELEASE command, then the current transaction
54818      ** is committed.
54819      */
54820      int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
54821      if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
54822        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
54823          goto vdbe_return;
54824        }
54825        db->autoCommit = 1;
54826        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
54827          p->pc = pc;
54828          db->autoCommit = 0;
54829          p->rc = rc = SQLITE_BUSY;
54830          goto vdbe_return;
54831        }
54832        db->isTransactionSavepoint = 0;
54833        rc = p->rc;
54834      }else{
54835        u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
54836        for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
54837          rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
54838          if( rc!=SQLITE_OK ){
54839            goto abort_due_to_error;
54840          }
54841        }
54842        if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
54843          sqlite3ExpirePreparedStatements(db);
54844          sqlite3ResetInternalSchema(db, 0);
54845        }
54846      }
54847
54848      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
54849      ** savepoints nested inside of the savepoint being operated on. */
54850      while( db->pSavepoint!=u.aq.pSavepoint ){
54851        u.aq.pTmp = db->pSavepoint;
54852        db->pSavepoint = u.aq.pTmp->pNext;
54853        sqlite3DbFree(db, u.aq.pTmp);
54854        db->nSavepoint--;
54855      }
54856
54857      /* If it is a RELEASE, then destroy the savepoint being operated on
54858      ** too. If it is a ROLLBACK TO, then set the number of deferred
54859      ** constraint violations present in the database to the value stored
54860      ** when the savepoint was created.  */
54861      if( u.aq.p1==SAVEPOINT_RELEASE ){
54862        assert( u.aq.pSavepoint==db->pSavepoint );
54863        db->pSavepoint = u.aq.pSavepoint->pNext;
54864        sqlite3DbFree(db, u.aq.pSavepoint);
54865        if( !isTransaction ){
54866          db->nSavepoint--;
54867        }
54868      }else{
54869        db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
54870      }
54871    }
54872  }
54873
54874  break;
54875}
54876
54877/* Opcode: AutoCommit P1 P2 * * *
54878**
54879** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
54880** back any currently active btree transactions. If there are any active
54881** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
54882** there are active writing VMs or active VMs that use shared cache.
54883**
54884** This instruction causes the VM to halt.
54885*/
54886case OP_AutoCommit: {
54887#if 0  /* local variables moved into u.ar */
54888  int desiredAutoCommit;
54889  int iRollback;
54890  int turnOnAC;
54891#endif /* local variables moved into u.ar */
54892
54893  u.ar.desiredAutoCommit = pOp->p1;
54894  u.ar.iRollback = pOp->p2;
54895  u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
54896  assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
54897  assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
54898  assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
54899
54900  if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
54901    /* If this instruction implements a ROLLBACK and other VMs are
54902    ** still running, and a transaction is active, return an error indicating
54903    ** that the other VMs must complete first.
54904    */
54905    sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
54906        "SQL statements in progress");
54907    rc = SQLITE_BUSY;
54908  }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
54909    /* If this instruction implements a COMMIT and other VMs are writing
54910    ** return an error indicating that the other VMs must complete first.
54911    */
54912    sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
54913        "SQL statements in progress");
54914    rc = SQLITE_BUSY;
54915  }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
54916    if( u.ar.iRollback ){
54917      assert( u.ar.desiredAutoCommit==1 );
54918      sqlite3RollbackAll(db);
54919      db->autoCommit = 1;
54920    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
54921      goto vdbe_return;
54922    }else{
54923      db->autoCommit = (u8)u.ar.desiredAutoCommit;
54924      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
54925        p->pc = pc;
54926        db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
54927        p->rc = rc = SQLITE_BUSY;
54928        goto vdbe_return;
54929      }
54930    }
54931    assert( db->nStatement==0 );
54932    sqlite3CloseSavepoints(db);
54933    if( p->rc==SQLITE_OK ){
54934      rc = SQLITE_DONE;
54935    }else{
54936      rc = SQLITE_ERROR;
54937    }
54938    goto vdbe_return;
54939  }else{
54940    sqlite3SetString(&p->zErrMsg, db,
54941        (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
54942        (u.ar.iRollback)?"cannot rollback - no transaction is active":
54943                   "cannot commit - no transaction is active"));
54944
54945    rc = SQLITE_ERROR;
54946  }
54947  break;
54948}
54949
54950/* Opcode: Transaction P1 P2 * * *
54951**
54952** Begin a transaction.  The transaction ends when a Commit or Rollback
54953** opcode is encountered.  Depending on the ON CONFLICT setting, the
54954** transaction might also be rolled back if an error is encountered.
54955**
54956** P1 is the index of the database file on which the transaction is
54957** started.  Index 0 is the main database file and index 1 is the
54958** file used for temporary tables.  Indices of 2 or more are used for
54959** attached databases.
54960**
54961** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
54962** obtained on the database file when a write-transaction is started.  No
54963** other process can start another write transaction while this transaction is
54964** underway.  Starting a write transaction also creates a rollback journal. A
54965** write transaction must be started before any changes can be made to the
54966** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
54967** on the file.
54968**
54969** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
54970** true (this flag is set if the Vdbe may modify more than one row and may
54971** throw an ABORT exception), a statement transaction may also be opened.
54972** More specifically, a statement transaction is opened iff the database
54973** connection is currently not in autocommit mode, or if there are other
54974** active statements. A statement transaction allows the affects of this
54975** VDBE to be rolled back after an error without having to roll back the
54976** entire transaction. If no error is encountered, the statement transaction
54977** will automatically commit when the VDBE halts.
54978**
54979** If P2 is zero, then a read-lock is obtained on the database file.
54980*/
54981case OP_Transaction: {
54982#if 0  /* local variables moved into u.as */
54983  Btree *pBt;
54984#endif /* local variables moved into u.as */
54985
54986  assert( pOp->p1>=0 && pOp->p1<db->nDb );
54987  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
54988  u.as.pBt = db->aDb[pOp->p1].pBt;
54989
54990  if( u.as.pBt ){
54991    rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
54992    if( rc==SQLITE_BUSY ){
54993      p->pc = pc;
54994      p->rc = rc = SQLITE_BUSY;
54995      goto vdbe_return;
54996    }
54997    if( rc!=SQLITE_OK ){
54998      goto abort_due_to_error;
54999    }
55000
55001    if( pOp->p2 && p->usesStmtJournal
55002     && (db->autoCommit==0 || db->activeVdbeCnt>1)
55003    ){
55004      assert( sqlite3BtreeIsInTrans(u.as.pBt) );
55005      if( p->iStatement==0 ){
55006        assert( db->nStatement>=0 && db->nSavepoint>=0 );
55007        db->nStatement++;
55008        p->iStatement = db->nSavepoint + db->nStatement;
55009      }
55010      rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
55011
55012      /* Store the current value of the database handles deferred constraint
55013      ** counter. If the statement transaction needs to be rolled back,
55014      ** the value of this counter needs to be restored too.  */
55015      p->nStmtDefCons = db->nDeferredCons;
55016    }
55017  }
55018  break;
55019}
55020
55021/* Opcode: ReadCookie P1 P2 P3 * *
55022**
55023** Read cookie number P3 from database P1 and write it into register P2.
55024** P3==1 is the schema version.  P3==2 is the database format.
55025** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
55026** the main database file and P1==1 is the database file used to store
55027** temporary tables.
55028**
55029** There must be a read-lock on the database (either a transaction
55030** must be started or there must be an open cursor) before
55031** executing this instruction.
55032*/
55033case OP_ReadCookie: {               /* out2-prerelease */
55034#if 0  /* local variables moved into u.at */
55035  int iMeta;
55036  int iDb;
55037  int iCookie;
55038#endif /* local variables moved into u.at */
55039
55040  u.at.iDb = pOp->p1;
55041  u.at.iCookie = pOp->p3;
55042  assert( pOp->p3<SQLITE_N_BTREE_META );
55043  assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
55044  assert( db->aDb[u.at.iDb].pBt!=0 );
55045  assert( (p->btreeMask & (1<<u.at.iDb))!=0 );
55046
55047  sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
55048  pOut->u.i = u.at.iMeta;
55049  break;
55050}
55051
55052/* Opcode: SetCookie P1 P2 P3 * *
55053**
55054** Write the content of register P3 (interpreted as an integer)
55055** into cookie number P2 of database P1.  P2==1 is the schema version.
55056** P2==2 is the database format. P2==3 is the recommended pager cache
55057** size, and so forth.  P1==0 is the main database file and P1==1 is the
55058** database file used to store temporary tables.
55059**
55060** A transaction must be started before executing this opcode.
55061*/
55062case OP_SetCookie: {       /* in3 */
55063#if 0  /* local variables moved into u.au */
55064  Db *pDb;
55065#endif /* local variables moved into u.au */
55066  assert( pOp->p2<SQLITE_N_BTREE_META );
55067  assert( pOp->p1>=0 && pOp->p1<db->nDb );
55068  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
55069  u.au.pDb = &db->aDb[pOp->p1];
55070  assert( u.au.pDb->pBt!=0 );
55071  pIn3 = &aMem[pOp->p3];
55072  sqlite3VdbeMemIntegerify(pIn3);
55073  /* See note about index shifting on OP_ReadCookie */
55074  rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
55075  if( pOp->p2==BTREE_SCHEMA_VERSION ){
55076    /* When the schema cookie changes, record the new cookie internally */
55077    u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
55078    db->flags |= SQLITE_InternChanges;
55079  }else if( pOp->p2==BTREE_FILE_FORMAT ){
55080    /* Record changes in the file format */
55081    u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
55082  }
55083  if( pOp->p1==1 ){
55084    /* Invalidate all prepared statements whenever the TEMP database
55085    ** schema is changed.  Ticket #1644 */
55086    sqlite3ExpirePreparedStatements(db);
55087    p->expired = 0;
55088  }
55089  break;
55090}
55091
55092/* Opcode: VerifyCookie P1 P2 *
55093**
55094** Check the value of global database parameter number 0 (the
55095** schema version) and make sure it is equal to P2.
55096** P1 is the database number which is 0 for the main database file
55097** and 1 for the file holding temporary tables and some higher number
55098** for auxiliary databases.
55099**
55100** The cookie changes its value whenever the database schema changes.
55101** This operation is used to detect when that the cookie has changed
55102** and that the current process needs to reread the schema.
55103**
55104** Either a transaction needs to have been started or an OP_Open needs
55105** to be executed (to establish a read lock) before this opcode is
55106** invoked.
55107*/
55108case OP_VerifyCookie: {
55109#if 0  /* local variables moved into u.av */
55110  int iMeta;
55111  Btree *pBt;
55112#endif /* local variables moved into u.av */
55113  assert( pOp->p1>=0 && pOp->p1<db->nDb );
55114  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
55115  u.av.pBt = db->aDb[pOp->p1].pBt;
55116  if( u.av.pBt ){
55117    sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
55118  }else{
55119    u.av.iMeta = 0;
55120  }
55121  if( u.av.iMeta!=pOp->p2 ){
55122    sqlite3DbFree(db, p->zErrMsg);
55123    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
55124    /* If the schema-cookie from the database file matches the cookie
55125    ** stored with the in-memory representation of the schema, do
55126    ** not reload the schema from the database file.
55127    **
55128    ** If virtual-tables are in use, this is not just an optimization.
55129    ** Often, v-tables store their data in other SQLite tables, which
55130    ** are queried from within xNext() and other v-table methods using
55131    ** prepared queries. If such a query is out-of-date, we do not want to
55132    ** discard the database schema, as the user code implementing the
55133    ** v-table would have to be ready for the sqlite3_vtab structure itself
55134    ** to be invalidated whenever sqlite3_step() is called from within
55135    ** a v-table method.
55136    */
55137    if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
55138      sqlite3ResetInternalSchema(db, pOp->p1);
55139    }
55140
55141    sqlite3ExpirePreparedStatements(db);
55142    rc = SQLITE_SCHEMA;
55143  }
55144  break;
55145}
55146
55147/* Opcode: OpenRead P1 P2 P3 P4 P5
55148**
55149** Open a read-only cursor for the database table whose root page is
55150** P2 in a database file.  The database file is determined by P3.
55151** P3==0 means the main database, P3==1 means the database used for
55152** temporary tables, and P3>1 means used the corresponding attached
55153** database.  Give the new cursor an identifier of P1.  The P1
55154** values need not be contiguous but all P1 values should be small integers.
55155** It is an error for P1 to be negative.
55156**
55157** If P5!=0 then use the content of register P2 as the root page, not
55158** the value of P2 itself.
55159**
55160** There will be a read lock on the database whenever there is an
55161** open cursor.  If the database was unlocked prior to this instruction
55162** then a read lock is acquired as part of this instruction.  A read
55163** lock allows other processes to read the database but prohibits
55164** any other process from modifying the database.  The read lock is
55165** released when all cursors are closed.  If this instruction attempts
55166** to get a read lock but fails, the script terminates with an
55167** SQLITE_BUSY error code.
55168**
55169** The P4 value may be either an integer (P4_INT32) or a pointer to
55170** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
55171** structure, then said structure defines the content and collating
55172** sequence of the index being opened. Otherwise, if P4 is an integer
55173** value, it is set to the number of columns in the table.
55174**
55175** See also OpenWrite.
55176*/
55177/* Opcode: OpenWrite P1 P2 P3 P4 P5
55178**
55179** Open a read/write cursor named P1 on the table or index whose root
55180** page is P2.  Or if P5!=0 use the content of register P2 to find the
55181** root page.
55182**
55183** The P4 value may be either an integer (P4_INT32) or a pointer to
55184** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
55185** structure, then said structure defines the content and collating
55186** sequence of the index being opened. Otherwise, if P4 is an integer
55187** value, it is set to the number of columns in the table, or to the
55188** largest index of any column of the table that is actually used.
55189**
55190** This instruction works just like OpenRead except that it opens the cursor
55191** in read/write mode.  For a given table, there can be one or more read-only
55192** cursors or a single read/write cursor but not both.
55193**
55194** See also OpenRead.
55195*/
55196case OP_OpenRead:
55197case OP_OpenWrite: {
55198#if 0  /* local variables moved into u.aw */
55199  int nField;
55200  KeyInfo *pKeyInfo;
55201  int p2;
55202  int iDb;
55203  int wrFlag;
55204  Btree *pX;
55205  VdbeCursor *pCur;
55206  Db *pDb;
55207#endif /* local variables moved into u.aw */
55208
55209  if( p->expired ){
55210    rc = SQLITE_ABORT;
55211    break;
55212  }
55213
55214  u.aw.nField = 0;
55215  u.aw.pKeyInfo = 0;
55216  u.aw.p2 = pOp->p2;
55217  u.aw.iDb = pOp->p3;
55218  assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
55219  assert( (p->btreeMask & (1<<u.aw.iDb))!=0 );
55220  u.aw.pDb = &db->aDb[u.aw.iDb];
55221  u.aw.pX = u.aw.pDb->pBt;
55222  assert( u.aw.pX!=0 );
55223  if( pOp->opcode==OP_OpenWrite ){
55224    u.aw.wrFlag = 1;
55225    if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
55226      p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
55227    }
55228  }else{
55229    u.aw.wrFlag = 0;
55230  }
55231  if( pOp->p5 ){
55232    assert( u.aw.p2>0 );
55233    assert( u.aw.p2<=p->nMem );
55234    pIn2 = &aMem[u.aw.p2];
55235    sqlite3VdbeMemIntegerify(pIn2);
55236    u.aw.p2 = (int)pIn2->u.i;
55237    /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
55238    ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
55239    ** If there were a failure, the prepared statement would have halted
55240    ** before reaching this instruction. */
55241    if( NEVER(u.aw.p2<2) ) {
55242      rc = SQLITE_CORRUPT_BKPT(OP_OPENWRITE_CORRUPTION); // Android Change
55243      goto abort_due_to_error;
55244    }
55245  }
55246  if( pOp->p4type==P4_KEYINFO ){
55247    u.aw.pKeyInfo = pOp->p4.pKeyInfo;
55248    u.aw.pKeyInfo->enc = ENC(p->db);
55249    u.aw.nField = u.aw.pKeyInfo->nField+1;
55250  }else if( pOp->p4type==P4_INT32 ){
55251    u.aw.nField = pOp->p4.i;
55252  }
55253  assert( pOp->p1>=0 );
55254  u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
55255  if( u.aw.pCur==0 ) goto no_mem;
55256  u.aw.pCur->nullRow = 1;
55257  rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
55258  u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
55259
55260  /* Since it performs no memory allocation or IO, the only values that
55261  ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
55262  ** SQLITE_EMPTY is only returned when attempting to open the table
55263  ** rooted at page 1 of a zero-byte database.  */
55264  assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
55265  if( rc==SQLITE_EMPTY ){
55266    u.aw.pCur->pCursor = 0;
55267    rc = SQLITE_OK;
55268  }
55269
55270  /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
55271  ** SQLite used to check if the root-page flags were sane at this point
55272  ** and report database corruption if they were not, but this check has
55273  ** since moved into the btree layer.  */
55274  u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
55275  u.aw.pCur->isIndex = !u.aw.pCur->isTable;
55276  break;
55277}
55278
55279/* Opcode: OpenEphemeral P1 P2 * P4 *
55280**
55281** Open a new cursor P1 to a transient table.
55282** The cursor is always opened read/write even if
55283** the main database is read-only.  The transient or virtual
55284** table is deleted automatically when the cursor is closed.
55285**
55286** P2 is the number of columns in the virtual table.
55287** The cursor points to a BTree table if P4==0 and to a BTree index
55288** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
55289** that defines the format of keys in the index.
55290**
55291** This opcode was once called OpenTemp.  But that created
55292** confusion because the term "temp table", might refer either
55293** to a TEMP table at the SQL level, or to a table opened by
55294** this opcode.  Then this opcode was call OpenVirtual.  But
55295** that created confusion with the whole virtual-table idea.
55296*/
55297case OP_OpenEphemeral: {
55298#if 0  /* local variables moved into u.ax */
55299  VdbeCursor *pCx;
55300#endif /* local variables moved into u.ax */
55301  static const int openFlags =
55302      SQLITE_OPEN_READWRITE |
55303      SQLITE_OPEN_CREATE |
55304      SQLITE_OPEN_EXCLUSIVE |
55305      SQLITE_OPEN_DELETEONCLOSE |
55306      SQLITE_OPEN_TRANSIENT_DB;
55307
55308  assert( pOp->p1>=0 );
55309  u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
55310  if( u.ax.pCx==0 ) goto no_mem;
55311  u.ax.pCx->nullRow = 1;
55312  rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
55313                           &u.ax.pCx->pBt);
55314  if( rc==SQLITE_OK ){
55315    rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
55316  }
55317  if( rc==SQLITE_OK ){
55318    /* If a transient index is required, create it by calling
55319    ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
55320    ** opening it. If a transient table is required, just use the
55321    ** automatically created table with root-page 1 (an INTKEY table).
55322    */
55323    if( pOp->p4.pKeyInfo ){
55324      int pgno;
55325      assert( pOp->p4type==P4_KEYINFO );
55326      rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_ZERODATA);
55327      if( rc==SQLITE_OK ){
55328        assert( pgno==MASTER_ROOT+1 );
55329        rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
55330                                (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
55331        u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
55332        u.ax.pCx->pKeyInfo->enc = ENC(p->db);
55333      }
55334      u.ax.pCx->isTable = 0;
55335    }else{
55336      rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
55337      u.ax.pCx->isTable = 1;
55338    }
55339  }
55340  u.ax.pCx->isIndex = !u.ax.pCx->isTable;
55341  break;
55342}
55343
55344/* Opcode: OpenPseudo P1 P2 P3 * *
55345**
55346** Open a new cursor that points to a fake table that contains a single
55347** row of data.  The content of that one row in the content of memory
55348** register P2.  In other words, cursor P1 becomes an alias for the
55349** MEM_Blob content contained in register P2.
55350**
55351** A pseudo-table created by this opcode is used to hold the a single
55352** row output from the sorter so that the row can be decomposed into
55353** individual columns using the OP_Column opcode.  The OP_Column opcode
55354** is the only cursor opcode that works with a pseudo-table.
55355**
55356** P3 is the number of fields in the records that will be stored by
55357** the pseudo-table.
55358*/
55359case OP_OpenPseudo: {
55360#if 0  /* local variables moved into u.ay */
55361  VdbeCursor *pCx;
55362#endif /* local variables moved into u.ay */
55363
55364  assert( pOp->p1>=0 );
55365  u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
55366  if( u.ay.pCx==0 ) goto no_mem;
55367  u.ay.pCx->nullRow = 1;
55368  u.ay.pCx->pseudoTableReg = pOp->p2;
55369  u.ay.pCx->isTable = 1;
55370  u.ay.pCx->isIndex = 0;
55371  break;
55372}
55373
55374/* Opcode: Close P1 * * * *
55375**
55376** Close a cursor previously opened as P1.  If P1 is not
55377** currently open, this instruction is a no-op.
55378*/
55379case OP_Close: {
55380  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55381  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
55382  p->apCsr[pOp->p1] = 0;
55383  break;
55384}
55385
55386/* Opcode: SeekGe P1 P2 P3 P4 *
55387**
55388** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
55389** use the value in register P3 as the key.  If cursor P1 refers
55390** to an SQL index, then P3 is the first in an array of P4 registers
55391** that are used as an unpacked index key.
55392**
55393** Reposition cursor P1 so that  it points to the smallest entry that
55394** is greater than or equal to the key value. If there are no records
55395** greater than or equal to the key and P2 is not zero, then jump to P2.
55396**
55397** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
55398*/
55399/* Opcode: SeekGt P1 P2 P3 P4 *
55400**
55401** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
55402** use the value in register P3 as a key. If cursor P1 refers
55403** to an SQL index, then P3 is the first in an array of P4 registers
55404** that are used as an unpacked index key.
55405**
55406** Reposition cursor P1 so that  it points to the smallest entry that
55407** is greater than the key value. If there are no records greater than
55408** the key and P2 is not zero, then jump to P2.
55409**
55410** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
55411*/
55412/* Opcode: SeekLt P1 P2 P3 P4 *
55413**
55414** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
55415** use the value in register P3 as a key. If cursor P1 refers
55416** to an SQL index, then P3 is the first in an array of P4 registers
55417** that are used as an unpacked index key.
55418**
55419** Reposition cursor P1 so that  it points to the largest entry that
55420** is less than the key value. If there are no records less than
55421** the key and P2 is not zero, then jump to P2.
55422**
55423** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
55424*/
55425/* Opcode: SeekLe P1 P2 P3 P4 *
55426**
55427** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
55428** use the value in register P3 as a key. If cursor P1 refers
55429** to an SQL index, then P3 is the first in an array of P4 registers
55430** that are used as an unpacked index key.
55431**
55432** Reposition cursor P1 so that it points to the largest entry that
55433** is less than or equal to the key value. If there are no records
55434** less than or equal to the key and P2 is not zero, then jump to P2.
55435**
55436** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
55437*/
55438case OP_SeekLt:         /* jump, in3 */
55439case OP_SeekLe:         /* jump, in3 */
55440case OP_SeekGe:         /* jump, in3 */
55441case OP_SeekGt: {       /* jump, in3 */
55442#if 0  /* local variables moved into u.az */
55443  int res;
55444  int oc;
55445  VdbeCursor *pC;
55446  UnpackedRecord r;
55447  int nField;
55448  i64 iKey;      /* The rowid we are to seek to */
55449#endif /* local variables moved into u.az */
55450
55451  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55452  assert( pOp->p2!=0 );
55453  u.az.pC = p->apCsr[pOp->p1];
55454  assert( u.az.pC!=0 );
55455  assert( u.az.pC->pseudoTableReg==0 );
55456  assert( OP_SeekLe == OP_SeekLt+1 );
55457  assert( OP_SeekGe == OP_SeekLt+2 );
55458  assert( OP_SeekGt == OP_SeekLt+3 );
55459  if( u.az.pC->pCursor!=0 ){
55460    u.az.oc = pOp->opcode;
55461    u.az.pC->nullRow = 0;
55462    if( u.az.pC->isTable ){
55463      /* The input value in P3 might be of any type: integer, real, string,
55464      ** blob, or NULL.  But it needs to be an integer before we can do
55465      ** the seek, so covert it. */
55466      pIn3 = &aMem[pOp->p3];
55467      applyNumericAffinity(pIn3);
55468      u.az.iKey = sqlite3VdbeIntValue(pIn3);
55469      u.az.pC->rowidIsValid = 0;
55470
55471      /* If the P3 value could not be converted into an integer without
55472      ** loss of information, then special processing is required... */
55473      if( (pIn3->flags & MEM_Int)==0 ){
55474        if( (pIn3->flags & MEM_Real)==0 ){
55475          /* If the P3 value cannot be converted into any kind of a number,
55476          ** then the seek is not possible, so jump to P2 */
55477          pc = pOp->p2 - 1;
55478          break;
55479        }
55480        /* If we reach this point, then the P3 value must be a floating
55481        ** point number. */
55482        assert( (pIn3->flags & MEM_Real)!=0 );
55483
55484        if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
55485          /* The P3 value is too large in magnitude to be expressed as an
55486          ** integer. */
55487          u.az.res = 1;
55488          if( pIn3->r<0 ){
55489            if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
55490              rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
55491              if( rc!=SQLITE_OK ) goto abort_due_to_error;
55492            }
55493          }else{
55494            if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
55495              rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
55496              if( rc!=SQLITE_OK ) goto abort_due_to_error;
55497            }
55498          }
55499          if( u.az.res ){
55500            pc = pOp->p2 - 1;
55501          }
55502          break;
55503        }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
55504          /* Use the ceiling() function to convert real->int */
55505          if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
55506        }else{
55507          /* Use the floor() function to convert real->int */
55508          assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
55509          if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
55510        }
55511      }
55512      rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
55513      if( rc!=SQLITE_OK ){
55514        goto abort_due_to_error;
55515      }
55516      if( u.az.res==0 ){
55517        u.az.pC->rowidIsValid = 1;
55518        u.az.pC->lastRowid = u.az.iKey;
55519      }
55520    }else{
55521      u.az.nField = pOp->p4.i;
55522      assert( pOp->p4type==P4_INT32 );
55523      assert( u.az.nField>0 );
55524      u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
55525      u.az.r.nField = (u16)u.az.nField;
55526
55527      /* The next line of code computes as follows, only faster:
55528      **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
55529      **     u.az.r.flags = UNPACKED_INCRKEY;
55530      **   }else{
55531      **     u.az.r.flags = 0;
55532      **   }
55533      */
55534      u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
55535      assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
55536      assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
55537      assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
55538      assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
55539
55540      u.az.r.aMem = &aMem[pOp->p3];
55541      ExpandBlob(u.az.r.aMem);
55542      rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
55543      if( rc!=SQLITE_OK ){
55544        goto abort_due_to_error;
55545      }
55546      u.az.pC->rowidIsValid = 0;
55547    }
55548    u.az.pC->deferredMoveto = 0;
55549    u.az.pC->cacheStatus = CACHE_STALE;
55550#ifdef SQLITE_TEST
55551    sqlite3_search_count++;
55552#endif
55553    if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
55554      if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
55555        rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
55556        if( rc!=SQLITE_OK ) goto abort_due_to_error;
55557        u.az.pC->rowidIsValid = 0;
55558      }else{
55559        u.az.res = 0;
55560      }
55561    }else{
55562      assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
55563      if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
55564        rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
55565        if( rc!=SQLITE_OK ) goto abort_due_to_error;
55566        u.az.pC->rowidIsValid = 0;
55567      }else{
55568        /* u.az.res might be negative because the table is empty.  Check to
55569        ** see if this is the case.
55570        */
55571        u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
55572      }
55573    }
55574    assert( pOp->p2>0 );
55575    if( u.az.res ){
55576      pc = pOp->p2 - 1;
55577    }
55578  }else{
55579    /* This happens when attempting to open the sqlite3_master table
55580    ** for read access returns SQLITE_EMPTY. In this case always
55581    ** take the jump (since there are no records in the table).
55582    */
55583    pc = pOp->p2 - 1;
55584  }
55585  break;
55586}
55587
55588/* Opcode: Seek P1 P2 * * *
55589**
55590** P1 is an open table cursor and P2 is a rowid integer.  Arrange
55591** for P1 to move so that it points to the rowid given by P2.
55592**
55593** This is actually a deferred seek.  Nothing actually happens until
55594** the cursor is used to read a record.  That way, if no reads
55595** occur, no unnecessary I/O happens.
55596*/
55597case OP_Seek: {    /* in2 */
55598#if 0  /* local variables moved into u.ba */
55599  VdbeCursor *pC;
55600#endif /* local variables moved into u.ba */
55601
55602  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55603  u.ba.pC = p->apCsr[pOp->p1];
55604  assert( u.ba.pC!=0 );
55605  if( ALWAYS(u.ba.pC->pCursor!=0) ){
55606    assert( u.ba.pC->isTable );
55607    u.ba.pC->nullRow = 0;
55608    pIn2 = &aMem[pOp->p2];
55609    u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
55610    u.ba.pC->rowidIsValid = 0;
55611    u.ba.pC->deferredMoveto = 1;
55612  }
55613  break;
55614}
55615
55616
55617/* Opcode: Found P1 P2 P3 P4 *
55618**
55619** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
55620** P4>0 then register P3 is the first of P4 registers that form an unpacked
55621** record.
55622**
55623** Cursor P1 is on an index btree.  If the record identified by P3 and P4
55624** is a prefix of any entry in P1 then a jump is made to P2 and
55625** P1 is left pointing at the matching entry.
55626*/
55627/* Opcode: NotFound P1 P2 P3 P4 *
55628**
55629** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
55630** P4>0 then register P3 is the first of P4 registers that form an unpacked
55631** record.
55632**
55633** Cursor P1 is on an index btree.  If the record identified by P3 and P4
55634** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
55635** does contain an entry whose prefix matches the P3/P4 record then control
55636** falls through to the next instruction and P1 is left pointing at the
55637** matching entry.
55638**
55639** See also: Found, NotExists, IsUnique
55640*/
55641case OP_NotFound:       /* jump, in3 */
55642case OP_Found: {        /* jump, in3 */
55643#if 0  /* local variables moved into u.bb */
55644  int alreadyExists;
55645  VdbeCursor *pC;
55646  int res;
55647  UnpackedRecord *pIdxKey;
55648  UnpackedRecord r;
55649  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
55650#endif /* local variables moved into u.bb */
55651
55652#ifdef SQLITE_TEST
55653  sqlite3_found_count++;
55654#endif
55655
55656  u.bb.alreadyExists = 0;
55657  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55658  assert( pOp->p4type==P4_INT32 );
55659  u.bb.pC = p->apCsr[pOp->p1];
55660  assert( u.bb.pC!=0 );
55661  pIn3 = &aMem[pOp->p3];
55662  if( ALWAYS(u.bb.pC->pCursor!=0) ){
55663
55664    assert( u.bb.pC->isTable==0 );
55665    if( pOp->p4.i>0 ){
55666      u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
55667      u.bb.r.nField = (u16)pOp->p4.i;
55668      u.bb.r.aMem = pIn3;
55669      u.bb.r.flags = UNPACKED_PREFIX_MATCH;
55670      u.bb.pIdxKey = &u.bb.r;
55671    }else{
55672      assert( pIn3->flags & MEM_Blob );
55673      ExpandBlob(pIn3);
55674      u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
55675                                        u.bb.aTempRec, sizeof(u.bb.aTempRec));
55676      if( u.bb.pIdxKey==0 ){
55677        goto no_mem;
55678      }
55679      u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
55680    }
55681    rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
55682    if( pOp->p4.i==0 ){
55683      sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
55684    }
55685    if( rc!=SQLITE_OK ){
55686      break;
55687    }
55688    u.bb.alreadyExists = (u.bb.res==0);
55689    u.bb.pC->deferredMoveto = 0;
55690    u.bb.pC->cacheStatus = CACHE_STALE;
55691  }
55692  if( pOp->opcode==OP_Found ){
55693    if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
55694  }else{
55695    if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
55696  }
55697  break;
55698}
55699
55700/* Opcode: IsUnique P1 P2 P3 P4 *
55701**
55702** Cursor P1 is open on an index b-tree - that is to say, a btree which
55703** no data and where the key are records generated by OP_MakeRecord with
55704** the list field being the integer ROWID of the entry that the index
55705** entry refers to.
55706**
55707** The P3 register contains an integer record number. Call this record
55708** number R. Register P4 is the first in a set of N contiguous registers
55709** that make up an unpacked index key that can be used with cursor P1.
55710** The value of N can be inferred from the cursor. N includes the rowid
55711** value appended to the end of the index record. This rowid value may
55712** or may not be the same as R.
55713**
55714** If any of the N registers beginning with register P4 contains a NULL
55715** value, jump immediately to P2.
55716**
55717** Otherwise, this instruction checks if cursor P1 contains an entry
55718** where the first (N-1) fields match but the rowid value at the end
55719** of the index entry is not R. If there is no such entry, control jumps
55720** to instruction P2. Otherwise, the rowid of the conflicting index
55721** entry is copied to register P3 and control falls through to the next
55722** instruction.
55723**
55724** See also: NotFound, NotExists, Found
55725*/
55726case OP_IsUnique: {        /* jump, in3 */
55727#if 0  /* local variables moved into u.bc */
55728  u16 ii;
55729  VdbeCursor *pCx;
55730  BtCursor *pCrsr;
55731  u16 nField;
55732  Mem *aMx;
55733  UnpackedRecord r;                  /* B-Tree index search key */
55734  i64 R;                             /* Rowid stored in register P3 */
55735#endif /* local variables moved into u.bc */
55736
55737  pIn3 = &aMem[pOp->p3];
55738  u.bc.aMx = &aMem[pOp->p4.i];
55739  /* Assert that the values of parameters P1 and P4 are in range. */
55740  assert( pOp->p4type==P4_INT32 );
55741  assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
55742  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55743
55744  /* Find the index cursor. */
55745  u.bc.pCx = p->apCsr[pOp->p1];
55746  assert( u.bc.pCx->deferredMoveto==0 );
55747  u.bc.pCx->seekResult = 0;
55748  u.bc.pCx->cacheStatus = CACHE_STALE;
55749  u.bc.pCrsr = u.bc.pCx->pCursor;
55750
55751  /* If any of the values are NULL, take the jump. */
55752  u.bc.nField = u.bc.pCx->pKeyInfo->nField;
55753  for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
55754    if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
55755      pc = pOp->p2 - 1;
55756      u.bc.pCrsr = 0;
55757      break;
55758    }
55759  }
55760  assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
55761
55762  if( u.bc.pCrsr!=0 ){
55763    /* Populate the index search key. */
55764    u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
55765    u.bc.r.nField = u.bc.nField + 1;
55766    u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
55767    u.bc.r.aMem = u.bc.aMx;
55768
55769    /* Extract the value of u.bc.R from register P3. */
55770    sqlite3VdbeMemIntegerify(pIn3);
55771    u.bc.R = pIn3->u.i;
55772
55773    /* Search the B-Tree index. If no conflicting record is found, jump
55774    ** to P2. Otherwise, copy the rowid of the conflicting record to
55775    ** register P3 and fall through to the next instruction.  */
55776    rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
55777    if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
55778      pc = pOp->p2 - 1;
55779    }else{
55780      pIn3->u.i = u.bc.r.rowid;
55781    }
55782  }
55783  break;
55784}
55785
55786/* Opcode: NotExists P1 P2 P3 * *
55787**
55788** Use the content of register P3 as a integer key.  If a record
55789** with that key does not exist in table of P1, then jump to P2.
55790** If the record does exist, then fall thru.  The cursor is left
55791** pointing to the record if it exists.
55792**
55793** The difference between this operation and NotFound is that this
55794** operation assumes the key is an integer and that P1 is a table whereas
55795** NotFound assumes key is a blob constructed from MakeRecord and
55796** P1 is an index.
55797**
55798** See also: Found, NotFound, IsUnique
55799*/
55800case OP_NotExists: {        /* jump, in3 */
55801#if 0  /* local variables moved into u.bd */
55802  VdbeCursor *pC;
55803  BtCursor *pCrsr;
55804  int res;
55805  u64 iKey;
55806#endif /* local variables moved into u.bd */
55807
55808  pIn3 = &aMem[pOp->p3];
55809  assert( pIn3->flags & MEM_Int );
55810  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55811  u.bd.pC = p->apCsr[pOp->p1];
55812  assert( u.bd.pC!=0 );
55813  assert( u.bd.pC->isTable );
55814  assert( u.bd.pC->pseudoTableReg==0 );
55815  u.bd.pCrsr = u.bd.pC->pCursor;
55816  if( u.bd.pCrsr!=0 ){
55817    u.bd.res = 0;
55818    u.bd.iKey = pIn3->u.i;
55819    rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
55820    u.bd.pC->lastRowid = pIn3->u.i;
55821    u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
55822    u.bd.pC->nullRow = 0;
55823    u.bd.pC->cacheStatus = CACHE_STALE;
55824    u.bd.pC->deferredMoveto = 0;
55825    if( u.bd.res!=0 ){
55826      pc = pOp->p2 - 1;
55827      assert( u.bd.pC->rowidIsValid==0 );
55828    }
55829    u.bd.pC->seekResult = u.bd.res;
55830  }else{
55831    /* This happens when an attempt to open a read cursor on the
55832    ** sqlite_master table returns SQLITE_EMPTY.
55833    */
55834    pc = pOp->p2 - 1;
55835    assert( u.bd.pC->rowidIsValid==0 );
55836    u.bd.pC->seekResult = 0;
55837  }
55838  break;
55839}
55840
55841/* Opcode: Sequence P1 P2 * * *
55842**
55843** Find the next available sequence number for cursor P1.
55844** Write the sequence number into register P2.
55845** The sequence number on the cursor is incremented after this
55846** instruction.
55847*/
55848case OP_Sequence: {           /* out2-prerelease */
55849  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55850  assert( p->apCsr[pOp->p1]!=0 );
55851  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
55852  break;
55853}
55854
55855
55856/* Opcode: NewRowid P1 P2 P3 * *
55857**
55858** Get a new integer record number (a.k.a "rowid") used as the key to a table.
55859** The record number is not previously used as a key in the database
55860** table that cursor P1 points to.  The new record number is written
55861** written to register P2.
55862**
55863** If P3>0 then P3 is a register in the root frame of this VDBE that holds
55864** the largest previously generated record number. No new record numbers are
55865** allowed to be less than this value. When this value reaches its maximum,
55866** a SQLITE_FULL error is generated. The P3 register is updated with the '
55867** generated record number. This P3 mechanism is used to help implement the
55868** AUTOINCREMENT feature.
55869*/
55870case OP_NewRowid: {           /* out2-prerelease */
55871#if 0  /* local variables moved into u.be */
55872  i64 v;                 /* The new rowid */
55873  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
55874  int res;               /* Result of an sqlite3BtreeLast() */
55875  int cnt;               /* Counter to limit the number of searches */
55876  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
55877  VdbeFrame *pFrame;     /* Root frame of VDBE */
55878#endif /* local variables moved into u.be */
55879
55880  u.be.v = 0;
55881  u.be.res = 0;
55882  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55883  u.be.pC = p->apCsr[pOp->p1];
55884  assert( u.be.pC!=0 );
55885  if( NEVER(u.be.pC->pCursor==0) ){
55886    /* The zero initialization above is all that is needed */
55887  }else{
55888    /* The next rowid or record number (different terms for the same
55889    ** thing) is obtained in a two-step algorithm.
55890    **
55891    ** First we attempt to find the largest existing rowid and add one
55892    ** to that.  But if the largest existing rowid is already the maximum
55893    ** positive integer, we have to fall through to the second
55894    ** probabilistic algorithm
55895    **
55896    ** The second algorithm is to select a rowid at random and see if
55897    ** it already exists in the table.  If it does not exist, we have
55898    ** succeeded.  If the random rowid does exist, we select a new one
55899    ** and try again, up to 100 times.
55900    */
55901    assert( u.be.pC->isTable );
55902    u.be.cnt = 0;
55903
55904#ifdef SQLITE_32BIT_ROWID
55905#   define MAX_ROWID 0x7fffffff
55906#else
55907    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
55908    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
55909    ** to provide the constant while making all compilers happy.
55910    */
55911#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
55912#endif
55913
55914    if( !u.be.pC->useRandomRowid ){
55915      u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
55916      if( u.be.v==0 ){
55917        rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
55918        if( rc!=SQLITE_OK ){
55919          goto abort_due_to_error;
55920        }
55921        if( u.be.res ){
55922          u.be.v = 1;   /* IMP: R-61914-48074 */
55923        }else{
55924          assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
55925          rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
55926          assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
55927          if( u.be.v==MAX_ROWID ){
55928            u.be.pC->useRandomRowid = 1;
55929          }else{
55930            u.be.v++;   /* IMP: R-29538-34987 */
55931          }
55932        }
55933      }
55934
55935#ifndef SQLITE_OMIT_AUTOINCREMENT
55936      if( pOp->p3 ){
55937        /* Assert that P3 is a valid memory cell. */
55938        assert( pOp->p3>0 );
55939        if( p->pFrame ){
55940          for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
55941          /* Assert that P3 is a valid memory cell. */
55942          assert( pOp->p3<=u.be.pFrame->nMem );
55943          u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
55944        }else{
55945          /* Assert that P3 is a valid memory cell. */
55946          assert( pOp->p3<=p->nMem );
55947          u.be.pMem = &aMem[pOp->p3];
55948        }
55949
55950        REGISTER_TRACE(pOp->p3, u.be.pMem);
55951        sqlite3VdbeMemIntegerify(u.be.pMem);
55952        assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
55953        if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
55954          rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
55955          goto abort_due_to_error;
55956        }
55957        if( u.be.v<u.be.pMem->u.i+1 ){
55958          u.be.v = u.be.pMem->u.i + 1;
55959        }
55960        u.be.pMem->u.i = u.be.v;
55961      }
55962#endif
55963
55964      sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
55965    }
55966    if( u.be.pC->useRandomRowid ){
55967      /* IMPLEMENTATION-OF: R-48598-02938 If the largest ROWID is equal to the
55968      ** largest possible integer (9223372036854775807) then the database
55969      ** engine starts picking candidate ROWIDs at random until it finds one
55970      ** that is not previously used.
55971      */
55972      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
55973                             ** an AUTOINCREMENT table. */
55974      u.be.v = db->lastRowid;
55975      u.be.cnt = 0;
55976      do{
55977        if( u.be.cnt==0 && (u.be.v&0xffffff)==u.be.v ){
55978          u.be.v++;
55979        }else{
55980          sqlite3_randomness(sizeof(u.be.v), &u.be.v);
55981          if( u.be.cnt<5 ) u.be.v &= 0xffffff;
55982        }
55983        rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v, 0, &u.be.res);
55984        u.be.cnt++;
55985      }while( u.be.cnt<100 && rc==SQLITE_OK && u.be.res==0 );
55986      if( rc==SQLITE_OK && u.be.res==0 ){
55987        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
55988        goto abort_due_to_error;
55989      }
55990    }
55991    u.be.pC->rowidIsValid = 0;
55992    u.be.pC->deferredMoveto = 0;
55993    u.be.pC->cacheStatus = CACHE_STALE;
55994  }
55995  pOut->u.i = u.be.v;
55996  break;
55997}
55998
55999/* Opcode: Insert P1 P2 P3 P4 P5
56000**
56001** Write an entry into the table of cursor P1.  A new entry is
56002** created if it doesn't already exist or the data for an existing
56003** entry is overwritten.  The data is the value MEM_Blob stored in register
56004** number P2. The key is stored in register P3. The key must
56005** be a MEM_Int.
56006**
56007** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
56008** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
56009** then rowid is stored for subsequent return by the
56010** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
56011**
56012** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
56013** the last seek operation (OP_NotExists) was a success, then this
56014** operation will not attempt to find the appropriate row before doing
56015** the insert but will instead overwrite the row that the cursor is
56016** currently pointing to.  Presumably, the prior OP_NotExists opcode
56017** has already positioned the cursor correctly.  This is an optimization
56018** that boosts performance by avoiding redundant seeks.
56019**
56020** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
56021** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
56022** is part of an INSERT operation.  The difference is only important to
56023** the update hook.
56024**
56025** Parameter P4 may point to a string containing the table-name, or
56026** may be NULL. If it is not NULL, then the update-hook
56027** (sqlite3.xUpdateCallback) is invoked following a successful insert.
56028**
56029** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
56030** allocated, then ownership of P2 is transferred to the pseudo-cursor
56031** and register P2 becomes ephemeral.  If the cursor is changed, the
56032** value of register P2 will then change.  Make sure this does not
56033** cause any problems.)
56034**
56035** This instruction only works on tables.  The equivalent instruction
56036** for indices is OP_IdxInsert.
56037*/
56038/* Opcode: InsertInt P1 P2 P3 P4 P5
56039**
56040** This works exactly like OP_Insert except that the key is the
56041** integer value P3, not the value of the integer stored in register P3.
56042*/
56043case OP_Insert:
56044case OP_InsertInt: {
56045#if 0  /* local variables moved into u.bf */
56046  Mem *pData;       /* MEM cell holding data for the record to be inserted */
56047  Mem *pKey;        /* MEM cell holding key  for the record */
56048  i64 iKey;         /* The integer ROWID or key for the record to be inserted */
56049  VdbeCursor *pC;   /* Cursor to table into which insert is written */
56050  int nZero;        /* Number of zero-bytes to append */
56051  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
56052  const char *zDb;  /* database name - used by the update hook */
56053  const char *zTbl; /* Table name - used by the opdate hook */
56054  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
56055#endif /* local variables moved into u.bf */
56056
56057  u.bf.pData = &aMem[pOp->p2];
56058  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56059  u.bf.pC = p->apCsr[pOp->p1];
56060  assert( u.bf.pC!=0 );
56061  assert( u.bf.pC->pCursor!=0 );
56062  assert( u.bf.pC->pseudoTableReg==0 );
56063  assert( u.bf.pC->isTable );
56064  REGISTER_TRACE(pOp->p2, u.bf.pData);
56065
56066  if( pOp->opcode==OP_Insert ){
56067    u.bf.pKey = &aMem[pOp->p3];
56068    assert( u.bf.pKey->flags & MEM_Int );
56069    REGISTER_TRACE(pOp->p3, u.bf.pKey);
56070    u.bf.iKey = u.bf.pKey->u.i;
56071  }else{
56072    assert( pOp->opcode==OP_InsertInt );
56073    u.bf.iKey = pOp->p3;
56074  }
56075
56076  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
56077  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
56078  if( u.bf.pData->flags & MEM_Null ){
56079    u.bf.pData->z = 0;
56080    u.bf.pData->n = 0;
56081  }else{
56082    assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
56083  }
56084  u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
56085  if( u.bf.pData->flags & MEM_Zero ){
56086    u.bf.nZero = u.bf.pData->u.nZero;
56087  }else{
56088    u.bf.nZero = 0;
56089  }
56090  sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
56091  rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
56092                          u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
56093                          pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
56094  );
56095  u.bf.pC->rowidIsValid = 0;
56096  u.bf.pC->deferredMoveto = 0;
56097  u.bf.pC->cacheStatus = CACHE_STALE;
56098
56099  /* Invoke the update-hook if required. */
56100  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
56101    u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
56102    u.bf.zTbl = pOp->p4.z;
56103    u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
56104    assert( u.bf.pC->isTable );
56105    db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
56106    assert( u.bf.pC->iDb>=0 );
56107  }
56108  break;
56109}
56110
56111/* Opcode: Delete P1 P2 * P4 *
56112**
56113** Delete the record at which the P1 cursor is currently pointing.
56114**
56115** The cursor will be left pointing at either the next or the previous
56116** record in the table. If it is left pointing at the next record, then
56117** the next Next instruction will be a no-op.  Hence it is OK to delete
56118** a record from within an Next loop.
56119**
56120** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
56121** incremented (otherwise not).
56122**
56123** P1 must not be pseudo-table.  It has to be a real table with
56124** multiple rows.
56125**
56126** If P4 is not NULL, then it is the name of the table that P1 is
56127** pointing to.  The update hook will be invoked, if it exists.
56128** If P4 is not NULL then the P1 cursor must have been positioned
56129** using OP_NotFound prior to invoking this opcode.
56130*/
56131case OP_Delete: {
56132#if 0  /* local variables moved into u.bg */
56133  i64 iKey;
56134  VdbeCursor *pC;
56135#endif /* local variables moved into u.bg */
56136
56137  u.bg.iKey = 0;
56138  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56139  u.bg.pC = p->apCsr[pOp->p1];
56140  assert( u.bg.pC!=0 );
56141  assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
56142
56143  /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
56144  ** row being deleted.
56145  */
56146  if( db->xUpdateCallback && pOp->p4.z ){
56147    assert( u.bg.pC->isTable );
56148    assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
56149    u.bg.iKey = u.bg.pC->lastRowid;
56150  }
56151
56152  /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
56153  ** OP_Column on the same table without any intervening operations that
56154  ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
56155  ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
56156  ** below is always a no-op and cannot fail.  We will run it anyhow, though,
56157  ** to guard against future changes to the code generator.
56158  **/
56159  assert( u.bg.pC->deferredMoveto==0 );
56160  rc = sqlite3VdbeCursorMoveto(u.bg.pC);
56161  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
56162
56163  sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
56164  rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
56165  u.bg.pC->cacheStatus = CACHE_STALE;
56166
56167  /* Invoke the update-hook if required. */
56168  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
56169    const char *zDb = db->aDb[u.bg.pC->iDb].zName;
56170    const char *zTbl = pOp->p4.z;
56171    db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
56172    assert( u.bg.pC->iDb>=0 );
56173  }
56174  if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
56175  break;
56176}
56177/* Opcode: ResetCount * * * * *
56178**
56179** The value of the change counter is copied to the database handle
56180** change counter (returned by subsequent calls to sqlite3_changes()).
56181** Then the VMs internal change counter resets to 0.
56182** This is used by trigger programs.
56183*/
56184case OP_ResetCount: {
56185  sqlite3VdbeSetChanges(db, p->nChange);
56186  p->nChange = 0;
56187  break;
56188}
56189
56190/* Opcode: RowData P1 P2 * * *
56191**
56192** Write into register P2 the complete row data for cursor P1.
56193** There is no interpretation of the data.
56194** It is just copied onto the P2 register exactly as
56195** it is found in the database file.
56196**
56197** If the P1 cursor must be pointing to a valid row (not a NULL row)
56198** of a real table, not a pseudo-table.
56199*/
56200/* Opcode: RowKey P1 P2 * * *
56201**
56202** Write into register P2 the complete row key for cursor P1.
56203** There is no interpretation of the data.
56204** The key is copied onto the P3 register exactly as
56205** it is found in the database file.
56206**
56207** If the P1 cursor must be pointing to a valid row (not a NULL row)
56208** of a real table, not a pseudo-table.
56209*/
56210case OP_RowKey:
56211case OP_RowData: {
56212#if 0  /* local variables moved into u.bh */
56213  VdbeCursor *pC;
56214  BtCursor *pCrsr;
56215  u32 n;
56216  i64 n64;
56217#endif /* local variables moved into u.bh */
56218
56219  pOut = &aMem[pOp->p2];
56220
56221  /* Note that RowKey and RowData are really exactly the same instruction */
56222  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56223  u.bh.pC = p->apCsr[pOp->p1];
56224  assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
56225  assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
56226  assert( u.bh.pC!=0 );
56227  assert( u.bh.pC->nullRow==0 );
56228  assert( u.bh.pC->pseudoTableReg==0 );
56229  assert( u.bh.pC->pCursor!=0 );
56230  u.bh.pCrsr = u.bh.pC->pCursor;
56231  assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
56232
56233  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
56234  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
56235  ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
56236  ** a no-op and can never fail.  But we leave it in place as a safety.
56237  */
56238  assert( u.bh.pC->deferredMoveto==0 );
56239  rc = sqlite3VdbeCursorMoveto(u.bh.pC);
56240  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
56241
56242  if( u.bh.pC->isIndex ){
56243    assert( !u.bh.pC->isTable );
56244    rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
56245    assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
56246    if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
56247      goto too_big;
56248    }
56249    u.bh.n = (u32)u.bh.n64;
56250  }else{
56251    rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
56252    assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
56253    if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
56254      goto too_big;
56255    }
56256  }
56257  if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
56258    goto no_mem;
56259  }
56260  pOut->n = u.bh.n;
56261  MemSetTypeFlag(pOut, MEM_Blob);
56262  if( u.bh.pC->isIndex ){
56263    rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
56264  }else{
56265    rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
56266  }
56267  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
56268  UPDATE_MAX_BLOBSIZE(pOut);
56269  break;
56270}
56271
56272/* Opcode: Rowid P1 P2 * * *
56273**
56274** Store in register P2 an integer which is the key of the table entry that
56275** P1 is currently point to.
56276**
56277** P1 can be either an ordinary table or a virtual table.  There used to
56278** be a separate OP_VRowid opcode for use with virtual tables, but this
56279** one opcode now works for both table types.
56280*/
56281case OP_Rowid: {                 /* out2-prerelease */
56282#if 0  /* local variables moved into u.bi */
56283  VdbeCursor *pC;
56284  i64 v;
56285  sqlite3_vtab *pVtab;
56286  const sqlite3_module *pModule;
56287#endif /* local variables moved into u.bi */
56288
56289  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56290  u.bi.pC = p->apCsr[pOp->p1];
56291  assert( u.bi.pC!=0 );
56292  assert( u.bi.pC->pseudoTableReg==0 );
56293  if( u.bi.pC->nullRow ){
56294    pOut->flags = MEM_Null;
56295    break;
56296  }else if( u.bi.pC->deferredMoveto ){
56297    u.bi.v = u.bi.pC->movetoTarget;
56298#ifndef SQLITE_OMIT_VIRTUALTABLE
56299  }else if( u.bi.pC->pVtabCursor ){
56300    u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
56301    u.bi.pModule = u.bi.pVtab->pModule;
56302    assert( u.bi.pModule->xRowid );
56303    if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
56304    rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
56305    sqlite3DbFree(db, p->zErrMsg);
56306    p->zErrMsg = u.bi.pVtab->zErrMsg;
56307    u.bi.pVtab->zErrMsg = 0;
56308    if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
56309#endif /* SQLITE_OMIT_VIRTUALTABLE */
56310  }else{
56311    assert( u.bi.pC->pCursor!=0 );
56312    rc = sqlite3VdbeCursorMoveto(u.bi.pC);
56313    if( rc ) goto abort_due_to_error;
56314    if( u.bi.pC->rowidIsValid ){
56315      u.bi.v = u.bi.pC->lastRowid;
56316    }else{
56317      rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
56318      assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
56319    }
56320  }
56321  pOut->u.i = u.bi.v;
56322  break;
56323}
56324
56325/* Opcode: NullRow P1 * * * *
56326**
56327** Move the cursor P1 to a null row.  Any OP_Column operations
56328** that occur while the cursor is on the null row will always
56329** write a NULL.
56330*/
56331case OP_NullRow: {
56332#if 0  /* local variables moved into u.bj */
56333  VdbeCursor *pC;
56334#endif /* local variables moved into u.bj */
56335
56336  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56337  u.bj.pC = p->apCsr[pOp->p1];
56338  assert( u.bj.pC!=0 );
56339  u.bj.pC->nullRow = 1;
56340  u.bj.pC->rowidIsValid = 0;
56341  if( u.bj.pC->pCursor ){
56342    sqlite3BtreeClearCursor(u.bj.pC->pCursor);
56343  }
56344  break;
56345}
56346
56347/* Opcode: Last P1 P2 * * *
56348**
56349** The next use of the Rowid or Column or Next instruction for P1
56350** will refer to the last entry in the database table or index.
56351** If the table or index is empty and P2>0, then jump immediately to P2.
56352** If P2 is 0 or if the table or index is not empty, fall through
56353** to the following instruction.
56354*/
56355case OP_Last: {        /* jump */
56356#if 0  /* local variables moved into u.bk */
56357  VdbeCursor *pC;
56358  BtCursor *pCrsr;
56359  int res;
56360#endif /* local variables moved into u.bk */
56361
56362  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56363  u.bk.pC = p->apCsr[pOp->p1];
56364  assert( u.bk.pC!=0 );
56365  u.bk.pCrsr = u.bk.pC->pCursor;
56366  if( u.bk.pCrsr==0 ){
56367    u.bk.res = 1;
56368  }else{
56369    rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
56370  }
56371  u.bk.pC->nullRow = (u8)u.bk.res;
56372  u.bk.pC->deferredMoveto = 0;
56373  u.bk.pC->rowidIsValid = 0;
56374  u.bk.pC->cacheStatus = CACHE_STALE;
56375  if( pOp->p2>0 && u.bk.res ){
56376    pc = pOp->p2 - 1;
56377  }
56378  break;
56379}
56380
56381
56382/* Opcode: Sort P1 P2 * * *
56383**
56384** This opcode does exactly the same thing as OP_Rewind except that
56385** it increments an undocumented global variable used for testing.
56386**
56387** Sorting is accomplished by writing records into a sorting index,
56388** then rewinding that index and playing it back from beginning to
56389** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
56390** rewinding so that the global variable will be incremented and
56391** regression tests can determine whether or not the optimizer is
56392** correctly optimizing out sorts.
56393*/
56394case OP_Sort: {        /* jump */
56395#ifdef SQLITE_TEST
56396  sqlite3_sort_count++;
56397  sqlite3_search_count--;
56398#endif
56399  p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
56400  /* Fall through into OP_Rewind */
56401}
56402/* Opcode: Rewind P1 P2 * * *
56403**
56404** The next use of the Rowid or Column or Next instruction for P1
56405** will refer to the first entry in the database table or index.
56406** If the table or index is empty and P2>0, then jump immediately to P2.
56407** If P2 is 0 or if the table or index is not empty, fall through
56408** to the following instruction.
56409*/
56410case OP_Rewind: {        /* jump */
56411#if 0  /* local variables moved into u.bl */
56412  VdbeCursor *pC;
56413  BtCursor *pCrsr;
56414  int res;
56415#endif /* local variables moved into u.bl */
56416
56417  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56418  u.bl.pC = p->apCsr[pOp->p1];
56419  assert( u.bl.pC!=0 );
56420  if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
56421    rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
56422    u.bl.pC->atFirst = u.bl.res==0 ?1:0;
56423    u.bl.pC->deferredMoveto = 0;
56424    u.bl.pC->cacheStatus = CACHE_STALE;
56425    u.bl.pC->rowidIsValid = 0;
56426  }else{
56427    u.bl.res = 1;
56428  }
56429  u.bl.pC->nullRow = (u8)u.bl.res;
56430  assert( pOp->p2>0 && pOp->p2<p->nOp );
56431  if( u.bl.res ){
56432    pc = pOp->p2 - 1;
56433  }
56434  break;
56435}
56436
56437/* Opcode: Next P1 P2 * * *
56438**
56439** Advance cursor P1 so that it points to the next key/data pair in its
56440** table or index.  If there are no more key/value pairs then fall through
56441** to the following instruction.  But if the cursor advance was successful,
56442** jump immediately to P2.
56443**
56444** The P1 cursor must be for a real table, not a pseudo-table.
56445**
56446** See also: Prev
56447*/
56448/* Opcode: Prev P1 P2 * * *
56449**
56450** Back up cursor P1 so that it points to the previous key/data pair in its
56451** table or index.  If there is no previous key/value pairs then fall through
56452** to the following instruction.  But if the cursor backup was successful,
56453** jump immediately to P2.
56454**
56455** The P1 cursor must be for a real table, not a pseudo-table.
56456*/
56457case OP_Prev:          /* jump */
56458case OP_Next: {        /* jump */
56459#if 0  /* local variables moved into u.bm */
56460  VdbeCursor *pC;
56461  BtCursor *pCrsr;
56462  int res;
56463#endif /* local variables moved into u.bm */
56464
56465  CHECK_FOR_INTERRUPT;
56466  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56467  u.bm.pC = p->apCsr[pOp->p1];
56468  if( u.bm.pC==0 ){
56469    break;  /* See ticket #2273 */
56470  }
56471  u.bm.pCrsr = u.bm.pC->pCursor;
56472  if( u.bm.pCrsr==0 ){
56473    u.bm.pC->nullRow = 1;
56474    break;
56475  }
56476  u.bm.res = 1;
56477  assert( u.bm.pC->deferredMoveto==0 );
56478  rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
56479                              sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
56480  u.bm.pC->nullRow = (u8)u.bm.res;
56481  u.bm.pC->cacheStatus = CACHE_STALE;
56482  if( u.bm.res==0 ){
56483    pc = pOp->p2 - 1;
56484    if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
56485#ifdef SQLITE_TEST
56486    sqlite3_search_count++;
56487#endif
56488  }
56489  u.bm.pC->rowidIsValid = 0;
56490  break;
56491}
56492
56493/* Opcode: IdxInsert P1 P2 P3 * P5
56494**
56495** Register P2 holds a SQL index key made using the
56496** MakeRecord instructions.  This opcode writes that key
56497** into the index P1.  Data for the entry is nil.
56498**
56499** P3 is a flag that provides a hint to the b-tree layer that this
56500** insert is likely to be an append.
56501**
56502** This instruction only works for indices.  The equivalent instruction
56503** for tables is OP_Insert.
56504*/
56505case OP_IdxInsert: {        /* in2 */
56506#if 0  /* local variables moved into u.bn */
56507  VdbeCursor *pC;
56508  BtCursor *pCrsr;
56509  int nKey;
56510  const char *zKey;
56511#endif /* local variables moved into u.bn */
56512
56513  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56514  u.bn.pC = p->apCsr[pOp->p1];
56515  assert( u.bn.pC!=0 );
56516  pIn2 = &aMem[pOp->p2];
56517  assert( pIn2->flags & MEM_Blob );
56518  u.bn.pCrsr = u.bn.pC->pCursor;
56519  if( ALWAYS(u.bn.pCrsr!=0) ){
56520    assert( u.bn.pC->isTable==0 );
56521    rc = ExpandBlob(pIn2);
56522    if( rc==SQLITE_OK ){
56523      u.bn.nKey = pIn2->n;
56524      u.bn.zKey = pIn2->z;
56525      rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
56526          ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
56527      );
56528      assert( u.bn.pC->deferredMoveto==0 );
56529      u.bn.pC->cacheStatus = CACHE_STALE;
56530    }
56531  }
56532  break;
56533}
56534
56535/* Opcode: IdxDelete P1 P2 P3 * *
56536**
56537** The content of P3 registers starting at register P2 form
56538** an unpacked index key. This opcode removes that entry from the
56539** index opened by cursor P1.
56540*/
56541case OP_IdxDelete: {
56542#if 0  /* local variables moved into u.bo */
56543  VdbeCursor *pC;
56544  BtCursor *pCrsr;
56545  int res;
56546  UnpackedRecord r;
56547#endif /* local variables moved into u.bo */
56548
56549  assert( pOp->p3>0 );
56550  assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
56551  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56552  u.bo.pC = p->apCsr[pOp->p1];
56553  assert( u.bo.pC!=0 );
56554  u.bo.pCrsr = u.bo.pC->pCursor;
56555  if( ALWAYS(u.bo.pCrsr!=0) ){
56556    u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
56557    u.bo.r.nField = (u16)pOp->p3;
56558    u.bo.r.flags = 0;
56559    u.bo.r.aMem = &aMem[pOp->p2];
56560    rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
56561    if( rc==SQLITE_OK && u.bo.res==0 ){
56562      rc = sqlite3BtreeDelete(u.bo.pCrsr);
56563    }
56564    assert( u.bo.pC->deferredMoveto==0 );
56565    u.bo.pC->cacheStatus = CACHE_STALE;
56566  }
56567  break;
56568}
56569
56570/* Opcode: IdxRowid P1 P2 * * *
56571**
56572** Write into register P2 an integer which is the last entry in the record at
56573** the end of the index key pointed to by cursor P1.  This integer should be
56574** the rowid of the table entry to which this index entry points.
56575**
56576** See also: Rowid, MakeRecord.
56577*/
56578case OP_IdxRowid: {              /* out2-prerelease */
56579#if 0  /* local variables moved into u.bp */
56580  BtCursor *pCrsr;
56581  VdbeCursor *pC;
56582  i64 rowid;
56583#endif /* local variables moved into u.bp */
56584
56585  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56586  u.bp.pC = p->apCsr[pOp->p1];
56587  assert( u.bp.pC!=0 );
56588  u.bp.pCrsr = u.bp.pC->pCursor;
56589  pOut->flags = MEM_Null;
56590  if( ALWAYS(u.bp.pCrsr!=0) ){
56591    rc = sqlite3VdbeCursorMoveto(u.bp.pC);
56592    if( NEVER(rc) ) goto abort_due_to_error;
56593    assert( u.bp.pC->deferredMoveto==0 );
56594    assert( u.bp.pC->isTable==0 );
56595    if( !u.bp.pC->nullRow ){
56596      rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
56597      if( rc!=SQLITE_OK ){
56598        goto abort_due_to_error;
56599      }
56600      pOut->u.i = u.bp.rowid;
56601      pOut->flags = MEM_Int;
56602    }
56603  }
56604  break;
56605}
56606
56607/* Opcode: IdxGE P1 P2 P3 P4 P5
56608**
56609** The P4 register values beginning with P3 form an unpacked index
56610** key that omits the ROWID.  Compare this key value against the index
56611** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
56612**
56613** If the P1 index entry is greater than or equal to the key value
56614** then jump to P2.  Otherwise fall through to the next instruction.
56615**
56616** If P5 is non-zero then the key value is increased by an epsilon
56617** prior to the comparison.  This make the opcode work like IdxGT except
56618** that if the key from register P3 is a prefix of the key in the cursor,
56619** the result is false whereas it would be true with IdxGT.
56620*/
56621/* Opcode: IdxLT P1 P2 P3 * P5
56622**
56623** The P4 register values beginning with P3 form an unpacked index
56624** key that omits the ROWID.  Compare this key value against the index
56625** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
56626**
56627** If the P1 index entry is less than the key value then jump to P2.
56628** Otherwise fall through to the next instruction.
56629**
56630** If P5 is non-zero then the key value is increased by an epsilon prior
56631** to the comparison.  This makes the opcode work like IdxLE.
56632*/
56633case OP_IdxLT:          /* jump */
56634case OP_IdxGE: {        /* jump */
56635#if 0  /* local variables moved into u.bq */
56636  VdbeCursor *pC;
56637  int res;
56638  UnpackedRecord r;
56639#endif /* local variables moved into u.bq */
56640
56641  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56642  u.bq.pC = p->apCsr[pOp->p1];
56643  assert( u.bq.pC!=0 );
56644  if( ALWAYS(u.bq.pC->pCursor!=0) ){
56645    assert( u.bq.pC->deferredMoveto==0 );
56646    assert( pOp->p5==0 || pOp->p5==1 );
56647    assert( pOp->p4type==P4_INT32 );
56648    u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
56649    u.bq.r.nField = (u16)pOp->p4.i;
56650    if( pOp->p5 ){
56651      u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
56652    }else{
56653      u.bq.r.flags = UNPACKED_IGNORE_ROWID;
56654    }
56655    u.bq.r.aMem = &aMem[pOp->p3];
56656    rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
56657    if( pOp->opcode==OP_IdxLT ){
56658      u.bq.res = -u.bq.res;
56659    }else{
56660      assert( pOp->opcode==OP_IdxGE );
56661      u.bq.res++;
56662    }
56663    if( u.bq.res>0 ){
56664      pc = pOp->p2 - 1 ;
56665    }
56666  }
56667  break;
56668}
56669
56670/* Opcode: Destroy P1 P2 P3 * *
56671**
56672** Delete an entire database table or index whose root page in the database
56673** file is given by P1.
56674**
56675** The table being destroyed is in the main database file if P3==0.  If
56676** P3==1 then the table to be clear is in the auxiliary database file
56677** that is used to store tables create using CREATE TEMPORARY TABLE.
56678**
56679** If AUTOVACUUM is enabled then it is possible that another root page
56680** might be moved into the newly deleted root page in order to keep all
56681** root pages contiguous at the beginning of the database.  The former
56682** value of the root page that moved - its value before the move occurred -
56683** is stored in register P2.  If no page
56684** movement was required (because the table being dropped was already
56685** the last one in the database) then a zero is stored in register P2.
56686** If AUTOVACUUM is disabled then a zero is stored in register P2.
56687**
56688** See also: Clear
56689*/
56690case OP_Destroy: {     /* out2-prerelease */
56691#if 0  /* local variables moved into u.br */
56692  int iMoved;
56693  int iCnt;
56694  Vdbe *pVdbe;
56695  int iDb;
56696#endif /* local variables moved into u.br */
56697#ifndef SQLITE_OMIT_VIRTUALTABLE
56698  u.br.iCnt = 0;
56699  for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
56700    if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
56701      u.br.iCnt++;
56702    }
56703  }
56704#else
56705  u.br.iCnt = db->activeVdbeCnt;
56706#endif
56707  pOut->flags = MEM_Null;
56708  if( u.br.iCnt>1 ){
56709    rc = SQLITE_LOCKED;
56710    p->errorAction = OE_Abort;
56711  }else{
56712    u.br.iDb = pOp->p3;
56713    assert( u.br.iCnt==1 );
56714    assert( (p->btreeMask & (1<<u.br.iDb))!=0 );
56715    rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
56716    pOut->flags = MEM_Int;
56717    pOut->u.i = u.br.iMoved;
56718#ifndef SQLITE_OMIT_AUTOVACUUM
56719    if( rc==SQLITE_OK && u.br.iMoved!=0 ){
56720      sqlite3RootPageMoved(&db->aDb[u.br.iDb], u.br.iMoved, pOp->p1);
56721      resetSchemaOnFault = 1;
56722    }
56723#endif
56724  }
56725  break;
56726}
56727
56728/* Opcode: Clear P1 P2 P3
56729**
56730** Delete all contents of the database table or index whose root page
56731** in the database file is given by P1.  But, unlike Destroy, do not
56732** remove the table or index from the database file.
56733**
56734** The table being clear is in the main database file if P2==0.  If
56735** P2==1 then the table to be clear is in the auxiliary database file
56736** that is used to store tables create using CREATE TEMPORARY TABLE.
56737**
56738** If the P3 value is non-zero, then the table referred to must be an
56739** intkey table (an SQL table, not an index). In this case the row change
56740** count is incremented by the number of rows in the table being cleared.
56741** If P3 is greater than zero, then the value stored in register P3 is
56742** also incremented by the number of rows in the table being cleared.
56743**
56744** See also: Destroy
56745*/
56746case OP_Clear: {
56747#if 0  /* local variables moved into u.bs */
56748  int nChange;
56749#endif /* local variables moved into u.bs */
56750
56751  u.bs.nChange = 0;
56752  assert( (p->btreeMask & (1<<pOp->p2))!=0 );
56753  rc = sqlite3BtreeClearTable(
56754      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
56755  );
56756  if( pOp->p3 ){
56757    p->nChange += u.bs.nChange;
56758    if( pOp->p3>0 ){
56759      aMem[pOp->p3].u.i += u.bs.nChange;
56760    }
56761  }
56762  break;
56763}
56764
56765/* Opcode: CreateTable P1 P2 * * *
56766**
56767** Allocate a new table in the main database file if P1==0 or in the
56768** auxiliary database file if P1==1 or in an attached database if
56769** P1>1.  Write the root page number of the new table into
56770** register P2
56771**
56772** The difference between a table and an index is this:  A table must
56773** have a 4-byte integer key and can have arbitrary data.  An index
56774** has an arbitrary key but no data.
56775**
56776** See also: CreateIndex
56777*/
56778/* Opcode: CreateIndex P1 P2 * * *
56779**
56780** Allocate a new index in the main database file if P1==0 or in the
56781** auxiliary database file if P1==1 or in an attached database if
56782** P1>1.  Write the root page number of the new table into
56783** register P2.
56784**
56785** See documentation on OP_CreateTable for additional information.
56786*/
56787case OP_CreateIndex:            /* out2-prerelease */
56788case OP_CreateTable: {          /* out2-prerelease */
56789#if 0  /* local variables moved into u.bt */
56790  int pgno;
56791  int flags;
56792  Db *pDb;
56793#endif /* local variables moved into u.bt */
56794
56795  u.bt.pgno = 0;
56796  assert( pOp->p1>=0 && pOp->p1<db->nDb );
56797  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
56798  u.bt.pDb = &db->aDb[pOp->p1];
56799  assert( u.bt.pDb->pBt!=0 );
56800  if( pOp->opcode==OP_CreateTable ){
56801    /* u.bt.flags = BTREE_INTKEY; */
56802    u.bt.flags = BTREE_LEAFDATA|BTREE_INTKEY;
56803  }else{
56804    u.bt.flags = BTREE_ZERODATA;
56805  }
56806  rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
56807  pOut->u.i = u.bt.pgno;
56808  break;
56809}
56810
56811/* Opcode: ParseSchema P1 P2 * P4 *
56812**
56813** Read and parse all entries from the SQLITE_MASTER table of database P1
56814** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
56815** the parsing if P2 is true.  If P2 is false, then this routine is a
56816** no-op if the schema is not currently loaded.  In other words, if P2
56817** is false, the SQLITE_MASTER table is only parsed if the rest of the
56818** schema is already loaded into the symbol table.
56819**
56820** This opcode invokes the parser to create a new virtual machine,
56821** then runs the new virtual machine.  It is thus a re-entrant opcode.
56822*/
56823case OP_ParseSchema: {
56824#if 0  /* local variables moved into u.bu */
56825  int iDb;
56826  const char *zMaster;
56827  char *zSql;
56828  InitData initData;
56829#endif /* local variables moved into u.bu */
56830
56831  u.bu.iDb = pOp->p1;
56832  assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
56833
56834  /* If pOp->p2 is 0, then this opcode is being executed to read a
56835  ** single row, for example the row corresponding to a new index
56836  ** created by this VDBE, from the sqlite_master table. It only
56837  ** does this if the corresponding in-memory schema is currently
56838  ** loaded. Otherwise, the new index definition can be loaded along
56839  ** with the rest of the schema when it is required.
56840  **
56841  ** Although the mutex on the BtShared object that corresponds to
56842  ** database u.bu.iDb (the database containing the sqlite_master table
56843  ** read by this instruction) is currently held, it is necessary to
56844  ** obtain the mutexes on all attached databases before checking if
56845  ** the schema of u.bu.iDb is loaded. This is because, at the start of
56846  ** the sqlite3_exec() call below, SQLite will invoke
56847  ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
56848  ** u.bu.iDb mutex may be temporarily released to avoid deadlock. If
56849  ** this happens, then some other thread may delete the in-memory
56850  ** schema of database u.bu.iDb before the SQL statement runs. The schema
56851  ** will not be reloaded becuase the db->init.busy flag is set. This
56852  ** can result in a "no such table: sqlite_master" or "malformed
56853  ** database schema" error being returned to the user.
56854  */
56855  assert( sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
56856  sqlite3BtreeEnterAll(db);
56857  if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){
56858    u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
56859    u.bu.initData.db = db;
56860    u.bu.initData.iDb = pOp->p1;
56861    u.bu.initData.pzErrMsg = &p->zErrMsg;
56862    u.bu.zSql = sqlite3MPrintf(db,
56863       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
56864       db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
56865    if( u.bu.zSql==0 ){
56866      rc = SQLITE_NOMEM;
56867    }else{
56868      (void)sqlite3SafetyOff(db);
56869      assert( db->init.busy==0 );
56870      db->init.busy = 1;
56871      u.bu.initData.rc = SQLITE_OK;
56872      assert( !db->mallocFailed );
56873      rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
56874      if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
56875      sqlite3DbFree(db, u.bu.zSql);
56876      db->init.busy = 0;
56877      (void)sqlite3SafetyOn(db);
56878    }
56879  }
56880  sqlite3BtreeLeaveAll(db);
56881  if( rc==SQLITE_NOMEM ){
56882    goto no_mem;
56883  }
56884  break;
56885}
56886
56887#if !defined(SQLITE_OMIT_ANALYZE)
56888/* Opcode: LoadAnalysis P1 * * * *
56889**
56890** Read the sqlite_stat1 table for database P1 and load the content
56891** of that table into the internal index hash table.  This will cause
56892** the analysis to be used when preparing all subsequent queries.
56893*/
56894case OP_LoadAnalysis: {
56895  assert( pOp->p1>=0 && pOp->p1<db->nDb );
56896  rc = sqlite3AnalysisLoad(db, pOp->p1);
56897  break;
56898}
56899#endif /* !defined(SQLITE_OMIT_ANALYZE) */
56900
56901/* Opcode: DropTable P1 * * P4 *
56902**
56903** Remove the internal (in-memory) data structures that describe
56904** the table named P4 in database P1.  This is called after a table
56905** is dropped in order to keep the internal representation of the
56906** schema consistent with what is on disk.
56907*/
56908case OP_DropTable: {
56909  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
56910  break;
56911}
56912
56913/* Opcode: DropIndex P1 * * P4 *
56914**
56915** Remove the internal (in-memory) data structures that describe
56916** the index named P4 in database P1.  This is called after an index
56917** is dropped in order to keep the internal representation of the
56918** schema consistent with what is on disk.
56919*/
56920case OP_DropIndex: {
56921  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
56922  break;
56923}
56924
56925/* Opcode: DropTrigger P1 * * P4 *
56926**
56927** Remove the internal (in-memory) data structures that describe
56928** the trigger named P4 in database P1.  This is called after a trigger
56929** is dropped in order to keep the internal representation of the
56930** schema consistent with what is on disk.
56931*/
56932case OP_DropTrigger: {
56933  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
56934  break;
56935}
56936
56937
56938#ifndef SQLITE_OMIT_INTEGRITY_CHECK
56939/* Opcode: IntegrityCk P1 P2 P3 * P5
56940**
56941** Do an analysis of the currently open database.  Store in
56942** register P1 the text of an error message describing any problems.
56943** If no problems are found, store a NULL in register P1.
56944**
56945** The register P3 contains the maximum number of allowed errors.
56946** At most reg(P3) errors will be reported.
56947** In other words, the analysis stops as soon as reg(P1) errors are
56948** seen.  Reg(P1) is updated with the number of errors remaining.
56949**
56950** The root page numbers of all tables in the database are integer
56951** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
56952** total.
56953**
56954** If P5 is not zero, the check is done on the auxiliary database
56955** file, not the main database file.
56956**
56957** This opcode is used to implement the integrity_check pragma.
56958*/
56959case OP_IntegrityCk: {
56960#if 0  /* local variables moved into u.bv */
56961  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
56962  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
56963  int j;          /* Loop counter */
56964  int nErr;       /* Number of errors reported */
56965  char *z;        /* Text of the error report */
56966  Mem *pnErr;     /* Register keeping track of errors remaining */
56967#endif /* local variables moved into u.bv */
56968
56969  u.bv.nRoot = pOp->p2;
56970  assert( u.bv.nRoot>0 );
56971  u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
56972  if( u.bv.aRoot==0 ) goto no_mem;
56973  assert( pOp->p3>0 && pOp->p3<=p->nMem );
56974  u.bv.pnErr = &aMem[pOp->p3];
56975  assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
56976  assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
56977  pIn1 = &aMem[pOp->p1];
56978  for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
56979    u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
56980  }
56981  u.bv.aRoot[u.bv.j] = 0;
56982  assert( pOp->p5<db->nDb );
56983  assert( (p->btreeMask & (1<<pOp->p5))!=0 );
56984  u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
56985                                 (int)u.bv.pnErr->u.i, &u.bv.nErr);
56986  sqlite3DbFree(db, u.bv.aRoot);
56987  u.bv.pnErr->u.i -= u.bv.nErr;
56988  sqlite3VdbeMemSetNull(pIn1);
56989  if( u.bv.nErr==0 ){
56990    assert( u.bv.z==0 );
56991  }else if( u.bv.z==0 ){
56992    goto no_mem;
56993  }else{
56994    sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
56995  }
56996  UPDATE_MAX_BLOBSIZE(pIn1);
56997  sqlite3VdbeChangeEncoding(pIn1, encoding);
56998  break;
56999}
57000#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57001
57002/* Opcode: RowSetAdd P1 P2 * * *
57003**
57004** Insert the integer value held by register P2 into a boolean index
57005** held in register P1.
57006**
57007** An assertion fails if P2 is not an integer.
57008*/
57009case OP_RowSetAdd: {       /* in1, in2 */
57010  pIn1 = &aMem[pOp->p1];
57011  pIn2 = &aMem[pOp->p2];
57012  assert( (pIn2->flags & MEM_Int)!=0 );
57013  if( (pIn1->flags & MEM_RowSet)==0 ){
57014    sqlite3VdbeMemSetRowSet(pIn1);
57015    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
57016  }
57017  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
57018  break;
57019}
57020
57021/* Opcode: RowSetRead P1 P2 P3 * *
57022**
57023** Extract the smallest value from boolean index P1 and put that value into
57024** register P3.  Or, if boolean index P1 is initially empty, leave P3
57025** unchanged and jump to instruction P2.
57026*/
57027case OP_RowSetRead: {       /* jump, in1, out3 */
57028#if 0  /* local variables moved into u.bw */
57029  i64 val;
57030#endif /* local variables moved into u.bw */
57031  CHECK_FOR_INTERRUPT;
57032  pIn1 = &aMem[pOp->p1];
57033  if( (pIn1->flags & MEM_RowSet)==0
57034   || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
57035  ){
57036    /* The boolean index is empty */
57037    sqlite3VdbeMemSetNull(pIn1);
57038    pc = pOp->p2 - 1;
57039  }else{
57040    /* A value was pulled from the index */
57041    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
57042  }
57043  break;
57044}
57045
57046/* Opcode: RowSetTest P1 P2 P3 P4
57047**
57048** Register P3 is assumed to hold a 64-bit integer value. If register P1
57049** contains a RowSet object and that RowSet object contains
57050** the value held in P3, jump to register P2. Otherwise, insert the
57051** integer in P3 into the RowSet and continue on to the
57052** next opcode.
57053**
57054** The RowSet object is optimized for the case where successive sets
57055** of integers, where each set contains no duplicates. Each set
57056** of values is identified by a unique P4 value. The first set
57057** must have P4==0, the final set P4=-1.  P4 must be either -1 or
57058** non-negative.  For non-negative values of P4 only the lower 4
57059** bits are significant.
57060**
57061** This allows optimizations: (a) when P4==0 there is no need to test
57062** the rowset object for P3, as it is guaranteed not to contain it,
57063** (b) when P4==-1 there is no need to insert the value, as it will
57064** never be tested for, and (c) when a value that is part of set X is
57065** inserted, there is no need to search to see if the same value was
57066** previously inserted as part of set X (only if it was previously
57067** inserted as part of some other set).
57068*/
57069case OP_RowSetTest: {                     /* jump, in1, in3 */
57070#if 0  /* local variables moved into u.bx */
57071  int iSet;
57072  int exists;
57073#endif /* local variables moved into u.bx */
57074
57075  pIn1 = &aMem[pOp->p1];
57076  pIn3 = &aMem[pOp->p3];
57077  u.bx.iSet = pOp->p4.i;
57078  assert( pIn3->flags&MEM_Int );
57079
57080  /* If there is anything other than a rowset object in memory cell P1,
57081  ** delete it now and initialize P1 with an empty rowset
57082  */
57083  if( (pIn1->flags & MEM_RowSet)==0 ){
57084    sqlite3VdbeMemSetRowSet(pIn1);
57085    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
57086  }
57087
57088  assert( pOp->p4type==P4_INT32 );
57089  assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
57090  if( u.bx.iSet ){
57091    u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
57092                               (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
57093                               pIn3->u.i);
57094    if( u.bx.exists ){
57095      pc = pOp->p2 - 1;
57096      break;
57097    }
57098  }
57099  if( u.bx.iSet>=0 ){
57100    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
57101  }
57102  break;
57103}
57104
57105
57106#ifndef SQLITE_OMIT_TRIGGER
57107
57108/* Opcode: Program P1 P2 P3 P4 *
57109**
57110** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
57111**
57112** P1 contains the address of the memory cell that contains the first memory
57113** cell in an array of values used as arguments to the sub-program. P2
57114** contains the address to jump to if the sub-program throws an IGNORE
57115** exception using the RAISE() function. Register P3 contains the address
57116** of a memory cell in this (the parent) VM that is used to allocate the
57117** memory required by the sub-vdbe at runtime.
57118**
57119** P4 is a pointer to the VM containing the trigger program.
57120*/
57121case OP_Program: {        /* jump */
57122#if 0  /* local variables moved into u.by */
57123  int nMem;               /* Number of memory registers for sub-program */
57124  int nByte;              /* Bytes of runtime space required for sub-program */
57125  Mem *pRt;               /* Register to allocate runtime space */
57126  Mem *pMem;              /* Used to iterate through memory cells */
57127  Mem *pEnd;              /* Last memory cell in new array */
57128  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
57129  SubProgram *pProgram;   /* Sub-program to execute */
57130  void *t;                /* Token identifying trigger */
57131#endif /* local variables moved into u.by */
57132
57133  u.by.pProgram = pOp->p4.pProgram;
57134  u.by.pRt = &aMem[pOp->p3];
57135  assert( u.by.pProgram->nOp>0 );
57136
57137  /* If the p5 flag is clear, then recursive invocation of triggers is
57138  ** disabled for backwards compatibility (p5 is set if this sub-program
57139  ** is really a trigger, not a foreign key action, and the flag set
57140  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
57141  **
57142  ** It is recursive invocation of triggers, at the SQL level, that is
57143  ** disabled. In some cases a single trigger may generate more than one
57144  ** SubProgram (if the trigger may be executed with more than one different
57145  ** ON CONFLICT algorithm). SubProgram structures associated with a
57146  ** single trigger all have the same value for the SubProgram.token
57147  ** variable.  */
57148  if( pOp->p5 ){
57149    u.by.t = u.by.pProgram->token;
57150    for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
57151    if( u.by.pFrame ) break;
57152  }
57153
57154  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
57155    rc = SQLITE_ERROR;
57156    sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
57157    break;
57158  }
57159
57160  /* Register u.by.pRt is used to store the memory required to save the state
57161  ** of the current program, and the memory required at runtime to execute
57162  ** the trigger program. If this trigger has been fired before, then u.by.pRt
57163  ** is already allocated. Otherwise, it must be initialized.  */
57164  if( (u.by.pRt->flags&MEM_Frame)==0 ){
57165    /* SubProgram.nMem is set to the number of memory cells used by the
57166    ** program stored in SubProgram.aOp. As well as these, one memory
57167    ** cell is required for each cursor used by the program. Set local
57168    ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
57169    */
57170    u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
57171    u.by.nByte = ROUND8(sizeof(VdbeFrame))
57172              + u.by.nMem * sizeof(Mem)
57173              + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
57174    u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
57175    if( !u.by.pFrame ){
57176      goto no_mem;
57177    }
57178    sqlite3VdbeMemRelease(u.by.pRt);
57179    u.by.pRt->flags = MEM_Frame;
57180    u.by.pRt->u.pFrame = u.by.pFrame;
57181
57182    u.by.pFrame->v = p;
57183    u.by.pFrame->nChildMem = u.by.nMem;
57184    u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
57185    u.by.pFrame->pc = pc;
57186    u.by.pFrame->aMem = p->aMem;
57187    u.by.pFrame->nMem = p->nMem;
57188    u.by.pFrame->apCsr = p->apCsr;
57189    u.by.pFrame->nCursor = p->nCursor;
57190    u.by.pFrame->aOp = p->aOp;
57191    u.by.pFrame->nOp = p->nOp;
57192    u.by.pFrame->token = u.by.pProgram->token;
57193
57194    u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
57195    for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
57196      u.by.pMem->flags = MEM_Null;
57197      u.by.pMem->db = db;
57198    }
57199  }else{
57200    u.by.pFrame = u.by.pRt->u.pFrame;
57201    assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
57202    assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
57203    assert( pc==u.by.pFrame->pc );
57204  }
57205
57206  p->nFrame++;
57207  u.by.pFrame->pParent = p->pFrame;
57208  u.by.pFrame->lastRowid = db->lastRowid;
57209  u.by.pFrame->nChange = p->nChange;
57210  p->nChange = 0;
57211  p->pFrame = u.by.pFrame;
57212  p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
57213  p->nMem = u.by.pFrame->nChildMem;
57214  p->nCursor = (u16)u.by.pFrame->nChildCsr;
57215  p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
57216  p->aOp = aOp = u.by.pProgram->aOp;
57217  p->nOp = u.by.pProgram->nOp;
57218  pc = -1;
57219
57220  break;
57221}
57222
57223/* Opcode: Param P1 P2 * * *
57224**
57225** This opcode is only ever present in sub-programs called via the
57226** OP_Program instruction. Copy a value currently stored in a memory
57227** cell of the calling (parent) frame to cell P2 in the current frames
57228** address space. This is used by trigger programs to access the new.*
57229** and old.* values.
57230**
57231** The address of the cell in the parent frame is determined by adding
57232** the value of the P1 argument to the value of the P1 argument to the
57233** calling OP_Program instruction.
57234*/
57235case OP_Param: {           /* out2-prerelease */
57236#if 0  /* local variables moved into u.bz */
57237  VdbeFrame *pFrame;
57238  Mem *pIn;
57239#endif /* local variables moved into u.bz */
57240  u.bz.pFrame = p->pFrame;
57241  u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
57242  sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
57243  break;
57244}
57245
57246#endif /* #ifndef SQLITE_OMIT_TRIGGER */
57247
57248#ifndef SQLITE_OMIT_FOREIGN_KEY
57249/* Opcode: FkCounter P1 P2 * * *
57250**
57251** Increment a "constraint counter" by P2 (P2 may be negative or positive).
57252** If P1 is non-zero, the database constraint counter is incremented
57253** (deferred foreign key constraints). Otherwise, if P1 is zero, the
57254** statement counter is incremented (immediate foreign key constraints).
57255*/
57256case OP_FkCounter: {
57257  if( pOp->p1 ){
57258    db->nDeferredCons += pOp->p2;
57259  }else{
57260    p->nFkConstraint += pOp->p2;
57261  }
57262  break;
57263}
57264
57265/* Opcode: FkIfZero P1 P2 * * *
57266**
57267** This opcode tests if a foreign key constraint-counter is currently zero.
57268** If so, jump to instruction P2. Otherwise, fall through to the next
57269** instruction.
57270**
57271** If P1 is non-zero, then the jump is taken if the database constraint-counter
57272** is zero (the one that counts deferred constraint violations). If P1 is
57273** zero, the jump is taken if the statement constraint-counter is zero
57274** (immediate foreign key constraint violations).
57275*/
57276case OP_FkIfZero: {         /* jump */
57277  if( pOp->p1 ){
57278    if( db->nDeferredCons==0 ) pc = pOp->p2-1;
57279  }else{
57280    if( p->nFkConstraint==0 ) pc = pOp->p2-1;
57281  }
57282  break;
57283}
57284#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
57285
57286#ifndef SQLITE_OMIT_AUTOINCREMENT
57287/* Opcode: MemMax P1 P2 * * *
57288**
57289** P1 is a register in the root frame of this VM (the root frame is
57290** different from the current frame if this instruction is being executed
57291** within a sub-program). Set the value of register P1 to the maximum of
57292** its current value and the value in register P2.
57293**
57294** This instruction throws an error if the memory cell is not initially
57295** an integer.
57296*/
57297case OP_MemMax: {        /* in2 */
57298#if 0  /* local variables moved into u.ca */
57299  Mem *pIn1;
57300  VdbeFrame *pFrame;
57301#endif /* local variables moved into u.ca */
57302  if( p->pFrame ){
57303    for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
57304    u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
57305  }else{
57306    u.ca.pIn1 = &aMem[pOp->p1];
57307  }
57308  sqlite3VdbeMemIntegerify(u.ca.pIn1);
57309  pIn2 = &aMem[pOp->p2];
57310  sqlite3VdbeMemIntegerify(pIn2);
57311  if( u.ca.pIn1->u.i<pIn2->u.i){
57312    u.ca.pIn1->u.i = pIn2->u.i;
57313  }
57314  break;
57315}
57316#endif /* SQLITE_OMIT_AUTOINCREMENT */
57317
57318/* Opcode: IfPos P1 P2 * * *
57319**
57320** If the value of register P1 is 1 or greater, jump to P2.
57321**
57322** It is illegal to use this instruction on a register that does
57323** not contain an integer.  An assertion fault will result if you try.
57324*/
57325case OP_IfPos: {        /* jump, in1 */
57326  pIn1 = &aMem[pOp->p1];
57327  assert( pIn1->flags&MEM_Int );
57328  if( pIn1->u.i>0 ){
57329     pc = pOp->p2 - 1;
57330  }
57331  break;
57332}
57333
57334/* Opcode: IfNeg P1 P2 * * *
57335**
57336** If the value of register P1 is less than zero, jump to P2.
57337**
57338** It is illegal to use this instruction on a register that does
57339** not contain an integer.  An assertion fault will result if you try.
57340*/
57341case OP_IfNeg: {        /* jump, in1 */
57342  pIn1 = &aMem[pOp->p1];
57343  assert( pIn1->flags&MEM_Int );
57344  if( pIn1->u.i<0 ){
57345     pc = pOp->p2 - 1;
57346  }
57347  break;
57348}
57349
57350/* Opcode: IfZero P1 P2 P3 * *
57351**
57352** The register P1 must contain an integer.  Add literal P3 to the
57353** value in register P1.  If the result is exactly 0, jump to P2.
57354**
57355** It is illegal to use this instruction on a register that does
57356** not contain an integer.  An assertion fault will result if you try.
57357*/
57358case OP_IfZero: {        /* jump, in1 */
57359  pIn1 = &aMem[pOp->p1];
57360  assert( pIn1->flags&MEM_Int );
57361  pIn1->u.i += pOp->p3;
57362  if( pIn1->u.i==0 ){
57363     pc = pOp->p2 - 1;
57364  }
57365  break;
57366}
57367
57368/* Opcode: AggStep * P2 P3 P4 P5
57369**
57370** Execute the step function for an aggregate.  The
57371** function has P5 arguments.   P4 is a pointer to the FuncDef
57372** structure that specifies the function.  Use register
57373** P3 as the accumulator.
57374**
57375** The P5 arguments are taken from register P2 and its
57376** successors.
57377*/
57378case OP_AggStep: {
57379#if 0  /* local variables moved into u.cb */
57380  int n;
57381  int i;
57382  Mem *pMem;
57383  Mem *pRec;
57384  sqlite3_context ctx;
57385  sqlite3_value **apVal;
57386#endif /* local variables moved into u.cb */
57387
57388  u.cb.n = pOp->p5;
57389  assert( u.cb.n>=0 );
57390  u.cb.pRec = &aMem[pOp->p2];
57391  u.cb.apVal = p->apArg;
57392  assert( u.cb.apVal || u.cb.n==0 );
57393  for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
57394    u.cb.apVal[u.cb.i] = u.cb.pRec;
57395    sqlite3VdbeMemStoreType(u.cb.pRec);
57396  }
57397  u.cb.ctx.pFunc = pOp->p4.pFunc;
57398  assert( pOp->p3>0 && pOp->p3<=p->nMem );
57399  u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
57400  u.cb.pMem->n++;
57401  u.cb.ctx.s.flags = MEM_Null;
57402  u.cb.ctx.s.z = 0;
57403  u.cb.ctx.s.zMalloc = 0;
57404  u.cb.ctx.s.xDel = 0;
57405  u.cb.ctx.s.db = db;
57406  u.cb.ctx.isError = 0;
57407  u.cb.ctx.pColl = 0;
57408  if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
57409    assert( pOp>p->aOp );
57410    assert( pOp[-1].p4type==P4_COLLSEQ );
57411    assert( pOp[-1].opcode==OP_CollSeq );
57412    u.cb.ctx.pColl = pOp[-1].p4.pColl;
57413  }
57414  (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal);
57415  if( u.cb.ctx.isError ){
57416    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
57417    rc = u.cb.ctx.isError;
57418  }
57419  sqlite3VdbeMemRelease(&u.cb.ctx.s);
57420  break;
57421}
57422
57423/* Opcode: AggFinal P1 P2 * P4 *
57424**
57425** Execute the finalizer function for an aggregate.  P1 is
57426** the memory location that is the accumulator for the aggregate.
57427**
57428** P2 is the number of arguments that the step function takes and
57429** P4 is a pointer to the FuncDef for this function.  The P2
57430** argument is not used by this opcode.  It is only there to disambiguate
57431** functions that can take varying numbers of arguments.  The
57432** P4 argument is only needed for the degenerate case where
57433** the step function was not previously called.
57434*/
57435case OP_AggFinal: {
57436#if 0  /* local variables moved into u.cc */
57437  Mem *pMem;
57438#endif /* local variables moved into u.cc */
57439  assert( pOp->p1>0 && pOp->p1<=p->nMem );
57440  u.cc.pMem = &aMem[pOp->p1];
57441  assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
57442  rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
57443  if( rc ){
57444    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
57445  }
57446  sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
57447  UPDATE_MAX_BLOBSIZE(u.cc.pMem);
57448  if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
57449    goto too_big;
57450  }
57451  break;
57452}
57453
57454
57455#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
57456/* Opcode: Vacuum * * * * *
57457**
57458** Vacuum the entire database.  This opcode will cause other virtual
57459** machines to be created and run.  It may not be called from within
57460** a transaction.
57461*/
57462case OP_Vacuum: {
57463  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57464  rc = sqlite3RunVacuum(&p->zErrMsg, db);
57465  if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57466  break;
57467}
57468#endif
57469
57470#if !defined(SQLITE_OMIT_AUTOVACUUM)
57471/* Opcode: IncrVacuum P1 P2 * * *
57472**
57473** Perform a single step of the incremental vacuum procedure on
57474** the P1 database. If the vacuum has finished, jump to instruction
57475** P2. Otherwise, fall through to the next instruction.
57476*/
57477case OP_IncrVacuum: {        /* jump */
57478#if 0  /* local variables moved into u.cd */
57479  Btree *pBt;
57480#endif /* local variables moved into u.cd */
57481
57482  assert( pOp->p1>=0 && pOp->p1<db->nDb );
57483  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
57484  u.cd.pBt = db->aDb[pOp->p1].pBt;
57485  rc = sqlite3BtreeIncrVacuum(u.cd.pBt);
57486  if( rc==SQLITE_DONE ){
57487    pc = pOp->p2 - 1;
57488    rc = SQLITE_OK;
57489  }
57490  break;
57491}
57492#endif
57493
57494/* Opcode: Expire P1 * * * *
57495**
57496** Cause precompiled statements to become expired. An expired statement
57497** fails with an error code of SQLITE_SCHEMA if it is ever executed
57498** (via sqlite3_step()).
57499**
57500** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
57501** then only the currently executing statement is affected.
57502*/
57503case OP_Expire: {
57504  if( !pOp->p1 ){
57505    sqlite3ExpirePreparedStatements(db);
57506  }else{
57507    p->expired = 1;
57508  }
57509  break;
57510}
57511
57512#ifndef SQLITE_OMIT_SHARED_CACHE
57513/* Opcode: TableLock P1 P2 P3 P4 *
57514**
57515** Obtain a lock on a particular table. This instruction is only used when
57516** the shared-cache feature is enabled.
57517**
57518** P1 is the index of the database in sqlite3.aDb[] of the database
57519** on which the lock is acquired.  A readlock is obtained if P3==0 or
57520** a write lock if P3==1.
57521**
57522** P2 contains the root-page of the table to lock.
57523**
57524** P4 contains a pointer to the name of the table being locked. This is only
57525** used to generate an error message if the lock cannot be obtained.
57526*/
57527case OP_TableLock: {
57528  u8 isWriteLock = (u8)pOp->p3;
57529  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
57530    int p1 = pOp->p1;
57531    assert( p1>=0 && p1<db->nDb );
57532    assert( (p->btreeMask & (1<<p1))!=0 );
57533    assert( isWriteLock==0 || isWriteLock==1 );
57534    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
57535    if( (rc&0xFF)==SQLITE_LOCKED ){
57536      const char *z = pOp->p4.z;
57537      sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
57538    }
57539  }
57540  break;
57541}
57542#endif /* SQLITE_OMIT_SHARED_CACHE */
57543
57544#ifndef SQLITE_OMIT_VIRTUALTABLE
57545/* Opcode: VBegin * * * P4 *
57546**
57547** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
57548** xBegin method for that table.
57549**
57550** Also, whether or not P4 is set, check that this is not being called from
57551** within a callback to a virtual table xSync() method. If it is, the error
57552** code will be set to SQLITE_LOCKED.
57553*/
57554case OP_VBegin: {
57555#if 0  /* local variables moved into u.ce */
57556  VTable *pVTab;
57557#endif /* local variables moved into u.ce */
57558  u.ce.pVTab = pOp->p4.pVtab;
57559  rc = sqlite3VtabBegin(db, u.ce.pVTab);
57560  if( u.ce.pVTab ){
57561    sqlite3DbFree(db, p->zErrMsg);
57562    p->zErrMsg = u.ce.pVTab->pVtab->zErrMsg;
57563    u.ce.pVTab->pVtab->zErrMsg = 0;
57564  }
57565  break;
57566}
57567#endif /* SQLITE_OMIT_VIRTUALTABLE */
57568
57569#ifndef SQLITE_OMIT_VIRTUALTABLE
57570/* Opcode: VCreate P1 * * P4 *
57571**
57572** P4 is the name of a virtual table in database P1. Call the xCreate method
57573** for that table.
57574*/
57575case OP_VCreate: {
57576  rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
57577  break;
57578}
57579#endif /* SQLITE_OMIT_VIRTUALTABLE */
57580
57581#ifndef SQLITE_OMIT_VIRTUALTABLE
57582/* Opcode: VDestroy P1 * * P4 *
57583**
57584** P4 is the name of a virtual table in database P1.  Call the xDestroy method
57585** of that table.
57586*/
57587case OP_VDestroy: {
57588  p->inVtabMethod = 2;
57589  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
57590  p->inVtabMethod = 0;
57591  break;
57592}
57593#endif /* SQLITE_OMIT_VIRTUALTABLE */
57594
57595#ifndef SQLITE_OMIT_VIRTUALTABLE
57596/* Opcode: VOpen P1 * * P4 *
57597**
57598** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
57599** P1 is a cursor number.  This opcode opens a cursor to the virtual
57600** table and stores that cursor in P1.
57601*/
57602case OP_VOpen: {
57603#if 0  /* local variables moved into u.cf */
57604  VdbeCursor *pCur;
57605  sqlite3_vtab_cursor *pVtabCursor;
57606  sqlite3_vtab *pVtab;
57607  sqlite3_module *pModule;
57608#endif /* local variables moved into u.cf */
57609
57610  u.cf.pCur = 0;
57611  u.cf.pVtabCursor = 0;
57612  u.cf.pVtab = pOp->p4.pVtab->pVtab;
57613  u.cf.pModule = (sqlite3_module *)u.cf.pVtab->pModule;
57614  assert(u.cf.pVtab && u.cf.pModule);
57615  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57616  rc = u.cf.pModule->xOpen(u.cf.pVtab, &u.cf.pVtabCursor);
57617  sqlite3DbFree(db, p->zErrMsg);
57618  p->zErrMsg = u.cf.pVtab->zErrMsg;
57619  u.cf.pVtab->zErrMsg = 0;
57620  if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57621  if( SQLITE_OK==rc ){
57622    /* Initialize sqlite3_vtab_cursor base class */
57623    u.cf.pVtabCursor->pVtab = u.cf.pVtab;
57624
57625    /* Initialise vdbe cursor object */
57626    u.cf.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
57627    if( u.cf.pCur ){
57628      u.cf.pCur->pVtabCursor = u.cf.pVtabCursor;
57629      u.cf.pCur->pModule = u.cf.pVtabCursor->pVtab->pModule;
57630    }else{
57631      db->mallocFailed = 1;
57632      u.cf.pModule->xClose(u.cf.pVtabCursor);
57633    }
57634  }
57635  break;
57636}
57637#endif /* SQLITE_OMIT_VIRTUALTABLE */
57638
57639#ifndef SQLITE_OMIT_VIRTUALTABLE
57640/* Opcode: VFilter P1 P2 P3 P4 *
57641**
57642** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
57643** the filtered result set is empty.
57644**
57645** P4 is either NULL or a string that was generated by the xBestIndex
57646** method of the module.  The interpretation of the P4 string is left
57647** to the module implementation.
57648**
57649** This opcode invokes the xFilter method on the virtual table specified
57650** by P1.  The integer query plan parameter to xFilter is stored in register
57651** P3. Register P3+1 stores the argc parameter to be passed to the
57652** xFilter method. Registers P3+2..P3+1+argc are the argc
57653** additional parameters which are passed to
57654** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
57655**
57656** A jump is made to P2 if the result set after filtering would be empty.
57657*/
57658case OP_VFilter: {   /* jump */
57659#if 0  /* local variables moved into u.cg */
57660  int nArg;
57661  int iQuery;
57662  const sqlite3_module *pModule;
57663  Mem *pQuery;
57664  Mem *pArgc;
57665  sqlite3_vtab_cursor *pVtabCursor;
57666  sqlite3_vtab *pVtab;
57667  VdbeCursor *pCur;
57668  int res;
57669  int i;
57670  Mem **apArg;
57671#endif /* local variables moved into u.cg */
57672
57673  u.cg.pQuery = &aMem[pOp->p3];
57674  u.cg.pArgc = &u.cg.pQuery[1];
57675  u.cg.pCur = p->apCsr[pOp->p1];
57676  REGISTER_TRACE(pOp->p3, u.cg.pQuery);
57677  assert( u.cg.pCur->pVtabCursor );
57678  u.cg.pVtabCursor = u.cg.pCur->pVtabCursor;
57679  u.cg.pVtab = u.cg.pVtabCursor->pVtab;
57680  u.cg.pModule = u.cg.pVtab->pModule;
57681
57682  /* Grab the index number and argc parameters */
57683  assert( (u.cg.pQuery->flags&MEM_Int)!=0 && u.cg.pArgc->flags==MEM_Int );
57684  u.cg.nArg = (int)u.cg.pArgc->u.i;
57685  u.cg.iQuery = (int)u.cg.pQuery->u.i;
57686
57687  /* Invoke the xFilter method */
57688  {
57689    u.cg.res = 0;
57690    u.cg.apArg = p->apArg;
57691    for(u.cg.i = 0; u.cg.i<u.cg.nArg; u.cg.i++){
57692      u.cg.apArg[u.cg.i] = &u.cg.pArgc[u.cg.i+1];
57693      sqlite3VdbeMemStoreType(u.cg.apArg[u.cg.i]);
57694    }
57695
57696    if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57697    p->inVtabMethod = 1;
57698    rc = u.cg.pModule->xFilter(u.cg.pVtabCursor, u.cg.iQuery, pOp->p4.z, u.cg.nArg, u.cg.apArg);
57699    p->inVtabMethod = 0;
57700    sqlite3DbFree(db, p->zErrMsg);
57701    p->zErrMsg = u.cg.pVtab->zErrMsg;
57702    u.cg.pVtab->zErrMsg = 0;
57703    if( rc==SQLITE_OK ){
57704      u.cg.res = u.cg.pModule->xEof(u.cg.pVtabCursor);
57705    }
57706    if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57707
57708    if( u.cg.res ){
57709      pc = pOp->p2 - 1;
57710    }
57711  }
57712  u.cg.pCur->nullRow = 0;
57713
57714  break;
57715}
57716#endif /* SQLITE_OMIT_VIRTUALTABLE */
57717
57718#ifndef SQLITE_OMIT_VIRTUALTABLE
57719/* Opcode: VColumn P1 P2 P3 * *
57720**
57721** Store the value of the P2-th column of
57722** the row of the virtual-table that the
57723** P1 cursor is pointing to into register P3.
57724*/
57725case OP_VColumn: {
57726#if 0  /* local variables moved into u.ch */
57727  sqlite3_vtab *pVtab;
57728  const sqlite3_module *pModule;
57729  Mem *pDest;
57730  sqlite3_context sContext;
57731#endif /* local variables moved into u.ch */
57732
57733  VdbeCursor *pCur = p->apCsr[pOp->p1];
57734  assert( pCur->pVtabCursor );
57735  assert( pOp->p3>0 && pOp->p3<=p->nMem );
57736  u.ch.pDest = &aMem[pOp->p3];
57737  if( pCur->nullRow ){
57738    sqlite3VdbeMemSetNull(u.ch.pDest);
57739    break;
57740  }
57741  u.ch.pVtab = pCur->pVtabCursor->pVtab;
57742  u.ch.pModule = u.ch.pVtab->pModule;
57743  assert( u.ch.pModule->xColumn );
57744  memset(&u.ch.sContext, 0, sizeof(u.ch.sContext));
57745
57746  /* The output cell may already have a buffer allocated. Move
57747  ** the current contents to u.ch.sContext.s so in case the user-function
57748  ** can use the already allocated buffer instead of allocating a
57749  ** new one.
57750  */
57751  sqlite3VdbeMemMove(&u.ch.sContext.s, u.ch.pDest);
57752  MemSetTypeFlag(&u.ch.sContext.s, MEM_Null);
57753
57754  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57755  rc = u.ch.pModule->xColumn(pCur->pVtabCursor, &u.ch.sContext, pOp->p2);
57756  sqlite3DbFree(db, p->zErrMsg);
57757  p->zErrMsg = u.ch.pVtab->zErrMsg;
57758  u.ch.pVtab->zErrMsg = 0;
57759  if( u.ch.sContext.isError ){
57760    rc = u.ch.sContext.isError;
57761  }
57762
57763  /* Copy the result of the function to the P3 register. We
57764  ** do this regardless of whether or not an error occurred to ensure any
57765  ** dynamic allocation in u.ch.sContext.s (a Mem struct) is  released.
57766  */
57767  sqlite3VdbeChangeEncoding(&u.ch.sContext.s, encoding);
57768  sqlite3VdbeMemMove(u.ch.pDest, &u.ch.sContext.s);
57769  REGISTER_TRACE(pOp->p3, u.ch.pDest);
57770  UPDATE_MAX_BLOBSIZE(u.ch.pDest);
57771
57772  if( sqlite3SafetyOn(db) ){
57773    goto abort_due_to_misuse;
57774  }
57775  if( sqlite3VdbeMemTooBig(u.ch.pDest) ){
57776    goto too_big;
57777  }
57778  break;
57779}
57780#endif /* SQLITE_OMIT_VIRTUALTABLE */
57781
57782#ifndef SQLITE_OMIT_VIRTUALTABLE
57783/* Opcode: VNext P1 P2 * * *
57784**
57785** Advance virtual table P1 to the next row in its result set and
57786** jump to instruction P2.  Or, if the virtual table has reached
57787** the end of its result set, then fall through to the next instruction.
57788*/
57789case OP_VNext: {   /* jump */
57790#if 0  /* local variables moved into u.ci */
57791  sqlite3_vtab *pVtab;
57792  const sqlite3_module *pModule;
57793  int res;
57794  VdbeCursor *pCur;
57795#endif /* local variables moved into u.ci */
57796
57797  u.ci.res = 0;
57798  u.ci.pCur = p->apCsr[pOp->p1];
57799  assert( u.ci.pCur->pVtabCursor );
57800  if( u.ci.pCur->nullRow ){
57801    break;
57802  }
57803  u.ci.pVtab = u.ci.pCur->pVtabCursor->pVtab;
57804  u.ci.pModule = u.ci.pVtab->pModule;
57805  assert( u.ci.pModule->xNext );
57806
57807  /* Invoke the xNext() method of the module. There is no way for the
57808  ** underlying implementation to return an error if one occurs during
57809  ** xNext(). Instead, if an error occurs, true is returned (indicating that
57810  ** data is available) and the error code returned when xColumn or
57811  ** some other method is next invoked on the save virtual table cursor.
57812  */
57813  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57814  p->inVtabMethod = 1;
57815  rc = u.ci.pModule->xNext(u.ci.pCur->pVtabCursor);
57816  p->inVtabMethod = 0;
57817  sqlite3DbFree(db, p->zErrMsg);
57818  p->zErrMsg = u.ci.pVtab->zErrMsg;
57819  u.ci.pVtab->zErrMsg = 0;
57820  if( rc==SQLITE_OK ){
57821    u.ci.res = u.ci.pModule->xEof(u.ci.pCur->pVtabCursor);
57822  }
57823  if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57824
57825  if( !u.ci.res ){
57826    /* If there is data, jump to P2 */
57827    pc = pOp->p2 - 1;
57828  }
57829  break;
57830}
57831#endif /* SQLITE_OMIT_VIRTUALTABLE */
57832
57833#ifndef SQLITE_OMIT_VIRTUALTABLE
57834/* Opcode: VRename P1 * * P4 *
57835**
57836** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
57837** This opcode invokes the corresponding xRename method. The value
57838** in register P1 is passed as the zName argument to the xRename method.
57839*/
57840case OP_VRename: {
57841#if 0  /* local variables moved into u.cj */
57842  sqlite3_vtab *pVtab;
57843  Mem *pName;
57844#endif /* local variables moved into u.cj */
57845
57846  u.cj.pVtab = pOp->p4.pVtab->pVtab;
57847  u.cj.pName = &aMem[pOp->p1];
57848  assert( u.cj.pVtab->pModule->xRename );
57849  REGISTER_TRACE(pOp->p1, u.cj.pName);
57850  assert( u.cj.pName->flags & MEM_Str );
57851  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57852  rc = u.cj.pVtab->pModule->xRename(u.cj.pVtab, u.cj.pName->z);
57853  sqlite3DbFree(db, p->zErrMsg);
57854  p->zErrMsg = u.cj.pVtab->zErrMsg;
57855  u.cj.pVtab->zErrMsg = 0;
57856  if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57857
57858  break;
57859}
57860#endif
57861
57862#ifndef SQLITE_OMIT_VIRTUALTABLE
57863/* Opcode: VUpdate P1 P2 P3 P4 *
57864**
57865** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
57866** This opcode invokes the corresponding xUpdate method. P2 values
57867** are contiguous memory cells starting at P3 to pass to the xUpdate
57868** invocation. The value in register (P3+P2-1) corresponds to the
57869** p2th element of the argv array passed to xUpdate.
57870**
57871** The xUpdate method will do a DELETE or an INSERT or both.
57872** The argv[0] element (which corresponds to memory cell P3)
57873** is the rowid of a row to delete.  If argv[0] is NULL then no
57874** deletion occurs.  The argv[1] element is the rowid of the new
57875** row.  This can be NULL to have the virtual table select the new
57876** rowid for itself.  The subsequent elements in the array are
57877** the values of columns in the new row.
57878**
57879** If P2==1 then no insert is performed.  argv[0] is the rowid of
57880** a row to delete.
57881**
57882** P1 is a boolean flag. If it is set to true and the xUpdate call
57883** is successful, then the value returned by sqlite3_last_insert_rowid()
57884** is set to the value of the rowid for the row just inserted.
57885*/
57886case OP_VUpdate: {
57887#if 0  /* local variables moved into u.ck */
57888  sqlite3_vtab *pVtab;
57889  sqlite3_module *pModule;
57890  int nArg;
57891  int i;
57892  sqlite_int64 rowid;
57893  Mem **apArg;
57894  Mem *pX;
57895#endif /* local variables moved into u.ck */
57896
57897  u.ck.pVtab = pOp->p4.pVtab->pVtab;
57898  u.ck.pModule = (sqlite3_module *)u.ck.pVtab->pModule;
57899  u.ck.nArg = pOp->p2;
57900  assert( pOp->p4type==P4_VTAB );
57901  if( ALWAYS(u.ck.pModule->xUpdate) ){
57902    u.ck.apArg = p->apArg;
57903    u.ck.pX = &aMem[pOp->p3];
57904    for(u.ck.i=0; u.ck.i<u.ck.nArg; u.ck.i++){
57905      sqlite3VdbeMemStoreType(u.ck.pX);
57906      u.ck.apArg[u.ck.i] = u.ck.pX;
57907      u.ck.pX++;
57908    }
57909    if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57910    rc = u.ck.pModule->xUpdate(u.ck.pVtab, u.ck.nArg, u.ck.apArg, &u.ck.rowid);
57911    sqlite3DbFree(db, p->zErrMsg);
57912    p->zErrMsg = u.ck.pVtab->zErrMsg;
57913    u.ck.pVtab->zErrMsg = 0;
57914    if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57915    if( rc==SQLITE_OK && pOp->p1 ){
57916      assert( u.ck.nArg>1 && u.ck.apArg[0] && (u.ck.apArg[0]->flags&MEM_Null) );
57917      db->lastRowid = u.ck.rowid;
57918    }
57919    p->nChange++;
57920  }
57921  break;
57922}
57923#endif /* SQLITE_OMIT_VIRTUALTABLE */
57924
57925#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
57926/* Opcode: Pagecount P1 P2 * * *
57927**
57928** Write the current number of pages in database P1 to memory cell P2.
57929*/
57930case OP_Pagecount: {            /* out2-prerelease */
57931#if 0  /* local variables moved into u.cl */
57932  int p1;
57933  int nPage;
57934  Pager *pPager;
57935#endif /* local variables moved into u.cl */
57936
57937  u.cl.p1 = pOp->p1;
57938  u.cl.pPager = sqlite3BtreePager(db->aDb[u.cl.p1].pBt);
57939  rc = sqlite3PagerPagecount(u.cl.pPager, &u.cl.nPage);
57940  /* OP_Pagecount is always called from within a read transaction.  The
57941  ** page count has already been successfully read and cached.  So the
57942  ** sqlite3PagerPagecount() call above cannot fail. */
57943  if( ALWAYS(rc==SQLITE_OK) ){
57944    pOut->u.i = u.cl.nPage;
57945  }
57946  break;
57947}
57948#endif
57949
57950#ifndef SQLITE_OMIT_TRACE
57951/* Opcode: Trace * * * P4 *
57952**
57953** If tracing is enabled (by the sqlite3_trace()) interface, then
57954** the UTF-8 string contained in P4 is emitted on the trace callback.
57955*/
57956case OP_Trace: {
57957#if 0  /* local variables moved into u.cm */
57958  char *zTrace;
57959#endif /* local variables moved into u.cm */
57960
57961  u.cm.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
57962  if( u.cm.zTrace ){
57963    if( db->xTrace ){
57964      char *z = sqlite3VdbeExpandSql(p, u.cm.zTrace);
57965      db->xTrace(db->pTraceArg, z);
57966      sqlite3DbFree(db, z);
57967    }
57968#ifdef SQLITE_DEBUG
57969    if( (db->flags & SQLITE_SqlTrace)!=0 ){
57970      sqlite3DebugPrintf("SQL-trace: %s\n", u.cm.zTrace);
57971    }
57972#endif /* SQLITE_DEBUG */
57973  }
57974  break;
57975}
57976#endif
57977
57978
57979/* Opcode: Noop * * * * *
57980**
57981** Do nothing.  This instruction is often useful as a jump
57982** destination.
57983*/
57984/*
57985** The magic Explain opcode are only inserted when explain==2 (which
57986** is to say when the EXPLAIN QUERY PLAN syntax is used.)
57987** This opcode records information from the optimizer.  It is the
57988** the same as a no-op.  This opcodesnever appears in a real VM program.
57989*/
57990default: {          /* This is really OP_Noop and OP_Explain */
57991  break;
57992}
57993
57994/*****************************************************************************
57995** The cases of the switch statement above this line should all be indented
57996** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
57997** readability.  From this point on down, the normal indentation rules are
57998** restored.
57999*****************************************************************************/
58000    }
58001
58002#ifdef VDBE_PROFILE
58003    {
58004      u64 elapsed = sqlite3Hwtime() - start;
58005      pOp->cycles += elapsed;
58006      pOp->cnt++;
58007#if 0
58008        fprintf(stdout, "%10llu ", elapsed);
58009        sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
58010#endif
58011    }
58012#endif
58013
58014    /* The following code adds nothing to the actual functionality
58015    ** of the program.  It is only here for testing and debugging.
58016    ** On the other hand, it does burn CPU cycles every time through
58017    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
58018    */
58019#ifndef NDEBUG
58020    assert( pc>=-1 && pc<p->nOp );
58021
58022#ifdef SQLITE_DEBUG
58023    if( p->trace ){
58024      if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
58025      if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
58026        registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
58027      }
58028      if( pOp->opflags & OPFLG_OUT3 ){
58029        registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
58030      }
58031    }
58032#endif  /* SQLITE_DEBUG */
58033#endif  /* NDEBUG */
58034  }  /* The end of the for(;;) loop the loops through opcodes */
58035
58036  /* If we reach this point, it means that execution is finished with
58037  ** an error of some kind.
58038  */
58039vdbe_error_halt:
58040  assert( rc );
58041  p->rc = rc;
58042  sqlite3VdbeHalt(p);
58043  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
58044  rc = SQLITE_ERROR;
58045  if( resetSchemaOnFault ) sqlite3ResetInternalSchema(db, 0);
58046
58047  /* This is the only way out of this procedure.  We have to
58048  ** release the mutexes on btrees that were acquired at the
58049  ** top. */
58050vdbe_return:
58051  sqlite3BtreeMutexArrayLeave(&p->aMutex);
58052  return rc;
58053
58054  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
58055  ** is encountered.
58056  */
58057too_big:
58058  sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
58059  rc = SQLITE_TOOBIG;
58060  goto vdbe_error_halt;
58061
58062  /* Jump to here if a malloc() fails.
58063  */
58064no_mem:
58065  db->mallocFailed = 1;
58066  sqlite3SetString(&p->zErrMsg, db, "out of memory");
58067  rc = SQLITE_NOMEM;
58068  goto vdbe_error_halt;
58069
58070  /* Jump to here for an SQLITE_MISUSE error.
58071  */
58072abort_due_to_misuse:
58073  rc = SQLITE_MISUSE;
58074  /* Fall thru into abort_due_to_error */
58075
58076  /* Jump to here for any other kind of fatal error.  The "rc" variable
58077  ** should hold the error number.
58078  */
58079abort_due_to_error:
58080  assert( p->zErrMsg==0 );
58081  if( db->mallocFailed ) rc = SQLITE_NOMEM;
58082  if( rc!=SQLITE_IOERR_NOMEM ){
58083    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
58084  }
58085  goto vdbe_error_halt;
58086
58087  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
58088  ** flag.
58089  */
58090abort_due_to_interrupt:
58091  assert( db->u1.isInterrupted );
58092  rc = SQLITE_INTERRUPT;
58093  p->rc = rc;
58094  sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
58095  goto vdbe_error_halt;
58096}
58097
58098/************** End of vdbe.c ************************************************/
58099/************** Begin file vdbeblob.c ****************************************/
58100/*
58101** 2007 May 1
58102**
58103** The author disclaims copyright to this source code.  In place of
58104** a legal notice, here is a blessing:
58105**
58106**    May you do good and not evil.
58107**    May you find forgiveness for yourself and forgive others.
58108**    May you share freely, never taking more than you give.
58109**
58110*************************************************************************
58111**
58112** This file contains code used to implement incremental BLOB I/O.
58113*/
58114
58115
58116#ifndef SQLITE_OMIT_INCRBLOB
58117
58118/*
58119** Valid sqlite3_blob* handles point to Incrblob structures.
58120*/
58121typedef struct Incrblob Incrblob;
58122struct Incrblob {
58123  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
58124  int nByte;              /* Size of open blob, in bytes */
58125  int iOffset;            /* Byte offset of blob in cursor data */
58126  BtCursor *pCsr;         /* Cursor pointing at blob row */
58127  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
58128  sqlite3 *db;            /* The associated database */
58129};
58130
58131/*
58132** Open a blob handle.
58133*/
58134SQLITE_API int sqlite3_blob_open(
58135  sqlite3* db,            /* The database connection */
58136  const char *zDb,        /* The attached database containing the blob */
58137  const char *zTable,     /* The table containing the blob */
58138  const char *zColumn,    /* The column containing the blob */
58139  sqlite_int64 iRow,      /* The row containing the glob */
58140  int flags,              /* True -> read/write access, false -> read-only */
58141  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
58142){
58143  int nAttempt = 0;
58144  int iCol;               /* Index of zColumn in row-record */
58145
58146  /* This VDBE program seeks a btree cursor to the identified
58147  ** db/table/row entry. The reason for using a vdbe program instead
58148  ** of writing code to use the b-tree layer directly is that the
58149  ** vdbe program will take advantage of the various transaction,
58150  ** locking and error handling infrastructure built into the vdbe.
58151  **
58152  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
58153  ** Code external to the Vdbe then "borrows" the b-tree cursor and
58154  ** uses it to implement the blob_read(), blob_write() and
58155  ** blob_bytes() functions.
58156  **
58157  ** The sqlite3_blob_close() function finalizes the vdbe program,
58158  ** which closes the b-tree cursor and (possibly) commits the
58159  ** transaction.
58160  */
58161  static const VdbeOpList openBlob[] = {
58162    {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
58163    {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
58164    {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
58165
58166    /* One of the following two instructions is replaced by an OP_Noop. */
58167    {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
58168    {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
58169
58170    {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
58171    {OP_NotExists, 0, 9, 1},       /* 6: Seek the cursor */
58172    {OP_Column, 0, 0, 1},          /* 7  */
58173    {OP_ResultRow, 1, 0, 0},       /* 8  */
58174    {OP_Close, 0, 0, 0},           /* 9  */
58175    {OP_Halt, 0, 0, 0},            /* 10 */
58176  };
58177
58178  Vdbe *v = 0;
58179  int rc = SQLITE_OK;
58180  char *zErr = 0;
58181  Table *pTab;
58182  Parse *pParse;
58183
58184  *ppBlob = 0;
58185  sqlite3_mutex_enter(db->mutex);
58186  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
58187  if( pParse==0 ){
58188    rc = SQLITE_NOMEM;
58189    goto blob_open_out;
58190  }
58191  do {
58192    memset(pParse, 0, sizeof(Parse));
58193    pParse->db = db;
58194
58195    if( sqlite3SafetyOn(db) ){
58196      sqlite3DbFree(db, zErr);
58197      sqlite3StackFree(db, pParse);
58198      sqlite3_mutex_leave(db->mutex);
58199      return SQLITE_MISUSE;
58200    }
58201
58202    sqlite3BtreeEnterAll(db);
58203    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
58204    if( pTab && IsVirtual(pTab) ){
58205      pTab = 0;
58206      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
58207    }
58208#ifndef SQLITE_OMIT_VIEW
58209    if( pTab && pTab->pSelect ){
58210      pTab = 0;
58211      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
58212    }
58213#endif
58214    if( !pTab ){
58215      if( pParse->zErrMsg ){
58216        sqlite3DbFree(db, zErr);
58217        zErr = pParse->zErrMsg;
58218        pParse->zErrMsg = 0;
58219      }
58220      rc = SQLITE_ERROR;
58221      (void)sqlite3SafetyOff(db);
58222      sqlite3BtreeLeaveAll(db);
58223      goto blob_open_out;
58224    }
58225
58226    /* Now search pTab for the exact column. */
58227    for(iCol=0; iCol < pTab->nCol; iCol++) {
58228      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
58229        break;
58230      }
58231    }
58232    if( iCol==pTab->nCol ){
58233      sqlite3DbFree(db, zErr);
58234      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
58235      rc = SQLITE_ERROR;
58236      (void)sqlite3SafetyOff(db);
58237      sqlite3BtreeLeaveAll(db);
58238      goto blob_open_out;
58239    }
58240
58241    /* If the value is being opened for writing, check that the
58242    ** column is not indexed, and that it is not part of a foreign key.
58243    ** It is against the rules to open a column to which either of these
58244    ** descriptions applies for writing.  */
58245    if( flags ){
58246      const char *zFault = 0;
58247      Index *pIdx;
58248#ifndef SQLITE_OMIT_FOREIGN_KEY
58249      if( db->flags&SQLITE_ForeignKeys ){
58250        /* Check that the column is not part of an FK child key definition. It
58251        ** is not necessary to check if it is part of a parent key, as parent
58252        ** key columns must be indexed. The check below will pick up this
58253        ** case.  */
58254        FKey *pFKey;
58255        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
58256          int j;
58257          for(j=0; j<pFKey->nCol; j++){
58258            if( pFKey->aCol[j].iFrom==iCol ){
58259              zFault = "foreign key";
58260            }
58261          }
58262        }
58263      }
58264#endif
58265      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
58266        int j;
58267        for(j=0; j<pIdx->nColumn; j++){
58268          if( pIdx->aiColumn[j]==iCol ){
58269            zFault = "indexed";
58270          }
58271        }
58272      }
58273      if( zFault ){
58274        sqlite3DbFree(db, zErr);
58275        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
58276        rc = SQLITE_ERROR;
58277        (void)sqlite3SafetyOff(db);
58278        sqlite3BtreeLeaveAll(db);
58279        goto blob_open_out;
58280      }
58281    }
58282
58283    v = sqlite3VdbeCreate(db);
58284    if( v ){
58285      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
58286      sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
58287      flags = !!flags;                 /* flags = (flags ? 1 : 0); */
58288
58289      /* Configure the OP_Transaction */
58290      sqlite3VdbeChangeP1(v, 0, iDb);
58291      sqlite3VdbeChangeP2(v, 0, flags);
58292
58293      /* Configure the OP_VerifyCookie */
58294      sqlite3VdbeChangeP1(v, 1, iDb);
58295      sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
58296
58297      /* Make sure a mutex is held on the table to be accessed */
58298      sqlite3VdbeUsesBtree(v, iDb);
58299
58300      /* Configure the OP_TableLock instruction */
58301      sqlite3VdbeChangeP1(v, 2, iDb);
58302      sqlite3VdbeChangeP2(v, 2, pTab->tnum);
58303      sqlite3VdbeChangeP3(v, 2, flags);
58304      sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
58305
58306      /* Remove either the OP_OpenWrite or OpenRead. Set the P2
58307      ** parameter of the other to pTab->tnum.  */
58308      sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
58309      sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
58310      sqlite3VdbeChangeP3(v, 3 + flags, iDb);
58311
58312      /* Configure the number of columns. Configure the cursor to
58313      ** think that the table has one more column than it really
58314      ** does. An OP_Column to retrieve this imaginary column will
58315      ** always return an SQL NULL. This is useful because it means
58316      ** we can invoke OP_Column to fill in the vdbe cursors type
58317      ** and offset cache without causing any IO.
58318      */
58319      sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
58320      sqlite3VdbeChangeP2(v, 7, pTab->nCol);
58321      if( !db->mallocFailed ){
58322        sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
58323      }
58324    }
58325
58326    sqlite3BtreeLeaveAll(db);
58327    rc = sqlite3SafetyOff(db);
58328    if( NEVER(rc!=SQLITE_OK) || db->mallocFailed ){
58329      goto blob_open_out;
58330    }
58331
58332    sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
58333    rc = sqlite3_step((sqlite3_stmt *)v);
58334    if( rc!=SQLITE_ROW ){
58335      nAttempt++;
58336      rc = sqlite3_finalize((sqlite3_stmt *)v);
58337      sqlite3DbFree(db, zErr);
58338      zErr = sqlite3MPrintf(db, sqlite3_errmsg(db));
58339      v = 0;
58340    }
58341  } while( nAttempt<5 && rc==SQLITE_SCHEMA );
58342
58343  if( rc==SQLITE_ROW ){
58344    /* The row-record has been opened successfully. Check that the
58345    ** column in question contains text or a blob. If it contains
58346    ** text, it is up to the caller to get the encoding right.
58347    */
58348    Incrblob *pBlob;
58349    u32 type = v->apCsr[0]->aType[iCol];
58350
58351    if( type<12 ){
58352      sqlite3DbFree(db, zErr);
58353      zErr = sqlite3MPrintf(db, "cannot open value of type %s",
58354          type==0?"null": type==7?"real": "integer"
58355      );
58356      rc = SQLITE_ERROR;
58357      goto blob_open_out;
58358    }
58359    pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
58360    if( db->mallocFailed ){
58361      sqlite3DbFree(db, pBlob);
58362      goto blob_open_out;
58363    }
58364    pBlob->flags = flags;
58365    pBlob->pCsr =  v->apCsr[0]->pCursor;
58366    sqlite3BtreeEnterCursor(pBlob->pCsr);
58367    sqlite3BtreeCacheOverflow(pBlob->pCsr);
58368    sqlite3BtreeLeaveCursor(pBlob->pCsr);
58369    pBlob->pStmt = (sqlite3_stmt *)v;
58370    pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
58371    pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
58372    pBlob->db = db;
58373    *ppBlob = (sqlite3_blob *)pBlob;
58374    rc = SQLITE_OK;
58375  }else if( rc==SQLITE_OK ){
58376    sqlite3DbFree(db, zErr);
58377    zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow);
58378    rc = SQLITE_ERROR;
58379  }
58380
58381blob_open_out:
58382  if( v && (rc!=SQLITE_OK || db->mallocFailed) ){
58383    sqlite3VdbeFinalize(v);
58384  }
58385  sqlite3Error(db, rc, zErr);
58386  sqlite3DbFree(db, zErr);
58387  sqlite3StackFree(db, pParse);
58388  rc = sqlite3ApiExit(db, rc);
58389  sqlite3_mutex_leave(db->mutex);
58390  return rc;
58391}
58392
58393/*
58394** Close a blob handle that was previously created using
58395** sqlite3_blob_open().
58396*/
58397SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
58398  Incrblob *p = (Incrblob *)pBlob;
58399  int rc;
58400  sqlite3 *db;
58401
58402  if( p ){
58403    db = p->db;
58404    sqlite3_mutex_enter(db->mutex);
58405    rc = sqlite3_finalize(p->pStmt);
58406    sqlite3DbFree(db, p);
58407    sqlite3_mutex_leave(db->mutex);
58408  }else{
58409    rc = SQLITE_OK;
58410  }
58411  return rc;
58412}
58413
58414/*
58415** Perform a read or write operation on a blob
58416*/
58417static int blobReadWrite(
58418  sqlite3_blob *pBlob,
58419  void *z,
58420  int n,
58421  int iOffset,
58422  int (*xCall)(BtCursor*, u32, u32, void*)
58423){
58424  int rc;
58425  Incrblob *p = (Incrblob *)pBlob;
58426  Vdbe *v;
58427  sqlite3 *db;
58428
58429  if( p==0 ) return SQLITE_MISUSE;
58430  db = p->db;
58431  sqlite3_mutex_enter(db->mutex);
58432  v = (Vdbe*)p->pStmt;
58433
58434  if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
58435    /* Request is out of range. Return a transient error. */
58436    rc = SQLITE_ERROR;
58437    sqlite3Error(db, SQLITE_ERROR, 0);
58438  } else if( v==0 ){
58439    /* If there is no statement handle, then the blob-handle has
58440    ** already been invalidated. Return SQLITE_ABORT in this case.
58441    */
58442    rc = SQLITE_ABORT;
58443  }else{
58444    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
58445    ** returned, clean-up the statement handle.
58446    */
58447    assert( db == v->db );
58448    sqlite3BtreeEnterCursor(p->pCsr);
58449    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
58450    sqlite3BtreeLeaveCursor(p->pCsr);
58451    if( rc==SQLITE_ABORT ){
58452      sqlite3VdbeFinalize(v);
58453      p->pStmt = 0;
58454    }else{
58455      db->errCode = rc;
58456      v->rc = rc;
58457    }
58458  }
58459  rc = sqlite3ApiExit(db, rc);
58460  sqlite3_mutex_leave(db->mutex);
58461  return rc;
58462}
58463
58464/*
58465** Read data from a blob handle.
58466*/
58467SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
58468  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
58469}
58470
58471/*
58472** Write data to a blob handle.
58473*/
58474SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
58475  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
58476}
58477
58478/*
58479** Query a blob handle for the size of the data.
58480**
58481** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
58482** so no mutex is required for access.
58483*/
58484SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
58485  Incrblob *p = (Incrblob *)pBlob;
58486  return p ? p->nByte : 0;
58487}
58488
58489#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
58490
58491/************** End of vdbeblob.c ********************************************/
58492/************** Begin file journal.c *****************************************/
58493/*
58494** 2007 August 22
58495**
58496** The author disclaims copyright to this source code.  In place of
58497** a legal notice, here is a blessing:
58498**
58499**    May you do good and not evil.
58500**    May you find forgiveness for yourself and forgive others.
58501**    May you share freely, never taking more than you give.
58502**
58503*************************************************************************
58504**
58505** This file implements a special kind of sqlite3_file object used
58506** by SQLite to create journal files if the atomic-write optimization
58507** is enabled.
58508**
58509** The distinctive characteristic of this sqlite3_file is that the
58510** actual on disk file is created lazily. When the file is created,
58511** the caller specifies a buffer size for an in-memory buffer to
58512** be used to service read() and write() requests. The actual file
58513** on disk is not created or populated until either:
58514**
58515**   1) The in-memory representation grows too large for the allocated
58516**      buffer, or
58517**   2) The sqlite3JournalCreate() function is called.
58518*/
58519#ifdef SQLITE_ENABLE_ATOMIC_WRITE
58520
58521
58522/*
58523** A JournalFile object is a subclass of sqlite3_file used by
58524** as an open file handle for journal files.
58525*/
58526struct JournalFile {
58527  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
58528  int nBuf;                       /* Size of zBuf[] in bytes */
58529  char *zBuf;                     /* Space to buffer journal writes */
58530  int iSize;                      /* Amount of zBuf[] currently used */
58531  int flags;                      /* xOpen flags */
58532  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
58533  sqlite3_file *pReal;            /* The "real" underlying file descriptor */
58534  const char *zJournal;           /* Name of the journal file */
58535};
58536typedef struct JournalFile JournalFile;
58537
58538/*
58539** If it does not already exists, create and populate the on-disk file
58540** for JournalFile p.
58541*/
58542static int createFile(JournalFile *p){
58543  int rc = SQLITE_OK;
58544  if( !p->pReal ){
58545    sqlite3_file *pReal = (sqlite3_file *)&p[1];
58546    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
58547    if( rc==SQLITE_OK ){
58548      p->pReal = pReal;
58549      if( p->iSize>0 ){
58550        assert(p->iSize<=p->nBuf);
58551        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
58552      }
58553    }
58554  }
58555  return rc;
58556}
58557
58558/*
58559** Close the file.
58560*/
58561static int jrnlClose(sqlite3_file *pJfd){
58562  JournalFile *p = (JournalFile *)pJfd;
58563  if( p->pReal ){
58564    sqlite3OsClose(p->pReal);
58565  }
58566  sqlite3_free(p->zBuf);
58567  return SQLITE_OK;
58568}
58569
58570/*
58571** Read data from the file.
58572*/
58573static int jrnlRead(
58574  sqlite3_file *pJfd,    /* The journal file from which to read */
58575  void *zBuf,            /* Put the results here */
58576  int iAmt,              /* Number of bytes to read */
58577  sqlite_int64 iOfst     /* Begin reading at this offset */
58578){
58579  int rc = SQLITE_OK;
58580  JournalFile *p = (JournalFile *)pJfd;
58581  if( p->pReal ){
58582    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
58583  }else if( (iAmt+iOfst)>p->iSize ){
58584    rc = SQLITE_IOERR_SHORT_READ;
58585  }else{
58586    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
58587  }
58588  return rc;
58589}
58590
58591/*
58592** Write data to the file.
58593*/
58594static int jrnlWrite(
58595  sqlite3_file *pJfd,    /* The journal file into which to write */
58596  const void *zBuf,      /* Take data to be written from here */
58597  int iAmt,              /* Number of bytes to write */
58598  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
58599){
58600  int rc = SQLITE_OK;
58601  JournalFile *p = (JournalFile *)pJfd;
58602  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
58603    rc = createFile(p);
58604  }
58605  if( rc==SQLITE_OK ){
58606    if( p->pReal ){
58607      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
58608    }else{
58609      memcpy(&p->zBuf[iOfst], zBuf, iAmt);
58610      if( p->iSize<(iOfst+iAmt) ){
58611        p->iSize = (iOfst+iAmt);
58612      }
58613    }
58614  }
58615  return rc;
58616}
58617
58618/*
58619** Truncate the file.
58620*/
58621static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
58622  int rc = SQLITE_OK;
58623  JournalFile *p = (JournalFile *)pJfd;
58624  if( p->pReal ){
58625    rc = sqlite3OsTruncate(p->pReal, size);
58626  }else if( size<p->iSize ){
58627    p->iSize = size;
58628  }
58629  return rc;
58630}
58631
58632/*
58633** Sync the file.
58634*/
58635static int jrnlSync(sqlite3_file *pJfd, int flags){
58636  int rc;
58637  JournalFile *p = (JournalFile *)pJfd;
58638  if( p->pReal ){
58639    rc = sqlite3OsSync(p->pReal, flags);
58640  }else{
58641    rc = SQLITE_OK;
58642  }
58643  return rc;
58644}
58645
58646/*
58647** Query the size of the file in bytes.
58648*/
58649static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
58650  int rc = SQLITE_OK;
58651  JournalFile *p = (JournalFile *)pJfd;
58652  if( p->pReal ){
58653    rc = sqlite3OsFileSize(p->pReal, pSize);
58654  }else{
58655    *pSize = (sqlite_int64) p->iSize;
58656  }
58657  return rc;
58658}
58659
58660/*
58661** Table of methods for JournalFile sqlite3_file object.
58662*/
58663static struct sqlite3_io_methods JournalFileMethods = {
58664  1,             /* iVersion */
58665  jrnlClose,     /* xClose */
58666  jrnlRead,      /* xRead */
58667  jrnlWrite,     /* xWrite */
58668  jrnlTruncate,  /* xTruncate */
58669  jrnlSync,      /* xSync */
58670  jrnlFileSize,  /* xFileSize */
58671  0,             /* xLock */
58672  0,             /* xUnlock */
58673  0,             /* xCheckReservedLock */
58674  0,             /* xFileControl */
58675  0,             /* xSectorSize */
58676  0              /* xDeviceCharacteristics */
58677};
58678
58679/*
58680** Open a journal file.
58681*/
58682SQLITE_PRIVATE int sqlite3JournalOpen(
58683  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
58684  const char *zName,         /* Name of the journal file */
58685  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
58686  int flags,                 /* Opening flags */
58687  int nBuf                   /* Bytes buffered before opening the file */
58688){
58689  JournalFile *p = (JournalFile *)pJfd;
58690  memset(p, 0, sqlite3JournalSize(pVfs));
58691  if( nBuf>0 ){
58692    p->zBuf = sqlite3MallocZero(nBuf);
58693    if( !p->zBuf ){
58694      return SQLITE_NOMEM;
58695    }
58696  }else{
58697    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
58698  }
58699  p->pMethod = &JournalFileMethods;
58700  p->nBuf = nBuf;
58701  p->flags = flags;
58702  p->zJournal = zName;
58703  p->pVfs = pVfs;
58704  return SQLITE_OK;
58705}
58706
58707/*
58708** If the argument p points to a JournalFile structure, and the underlying
58709** file has not yet been created, create it now.
58710*/
58711SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
58712  if( p->pMethods!=&JournalFileMethods ){
58713    return SQLITE_OK;
58714  }
58715  return createFile((JournalFile *)p);
58716}
58717
58718/*
58719** Return the number of bytes required to store a JournalFile that uses vfs
58720** pVfs to create the underlying on-disk files.
58721*/
58722SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
58723  return (pVfs->szOsFile+sizeof(JournalFile));
58724}
58725#endif
58726
58727/************** End of journal.c *********************************************/
58728/************** Begin file memjournal.c **************************************/
58729/*
58730** 2008 October 7
58731**
58732** The author disclaims copyright to this source code.  In place of
58733** a legal notice, here is a blessing:
58734**
58735**    May you do good and not evil.
58736**    May you find forgiveness for yourself and forgive others.
58737**    May you share freely, never taking more than you give.
58738**
58739*************************************************************************
58740**
58741** This file contains code use to implement an in-memory rollback journal.
58742** The in-memory rollback journal is used to journal transactions for
58743** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
58744*/
58745
58746/* Forward references to internal structures */
58747typedef struct MemJournal MemJournal;
58748typedef struct FilePoint FilePoint;
58749typedef struct FileChunk FileChunk;
58750
58751/* Space to hold the rollback journal is allocated in increments of
58752** this many bytes.
58753**
58754** The size chosen is a little less than a power of two.  That way,
58755** the FileChunk object will have a size that almost exactly fills
58756** a power-of-two allocation.  This mimimizes wasted space in power-of-two
58757** memory allocators.
58758*/
58759#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
58760
58761/* Macro to find the minimum of two numeric values.
58762*/
58763#ifndef MIN
58764# define MIN(x,y) ((x)<(y)?(x):(y))
58765#endif
58766
58767/*
58768** The rollback journal is composed of a linked list of these structures.
58769*/
58770struct FileChunk {
58771  FileChunk *pNext;               /* Next chunk in the journal */
58772  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
58773};
58774
58775/*
58776** An instance of this object serves as a cursor into the rollback journal.
58777** The cursor can be either for reading or writing.
58778*/
58779struct FilePoint {
58780  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
58781  FileChunk *pChunk;              /* Specific chunk into which cursor points */
58782};
58783
58784/*
58785** This subclass is a subclass of sqlite3_file.  Each open memory-journal
58786** is an instance of this class.
58787*/
58788struct MemJournal {
58789  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
58790  FileChunk *pFirst;              /* Head of in-memory chunk-list */
58791  FilePoint endpoint;             /* Pointer to the end of the file */
58792  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
58793};
58794
58795/*
58796** Read data from the in-memory journal file.  This is the implementation
58797** of the sqlite3_vfs.xRead method.
58798*/
58799static int memjrnlRead(
58800  sqlite3_file *pJfd,    /* The journal file from which to read */
58801  void *zBuf,            /* Put the results here */
58802  int iAmt,              /* Number of bytes to read */
58803  sqlite_int64 iOfst     /* Begin reading at this offset */
58804){
58805  MemJournal *p = (MemJournal *)pJfd;
58806  u8 *zOut = zBuf;
58807  int nRead = iAmt;
58808  int iChunkOffset;
58809  FileChunk *pChunk;
58810
58811  /* SQLite never tries to read past the end of a rollback journal file */
58812  assert( iOfst+iAmt<=p->endpoint.iOffset );
58813
58814  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
58815    sqlite3_int64 iOff = 0;
58816    for(pChunk=p->pFirst;
58817        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
58818        pChunk=pChunk->pNext
58819    ){
58820      iOff += JOURNAL_CHUNKSIZE;
58821    }
58822  }else{
58823    pChunk = p->readpoint.pChunk;
58824  }
58825
58826  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
58827  do {
58828    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
58829    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
58830    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
58831    zOut += nCopy;
58832    nRead -= iSpace;
58833    iChunkOffset = 0;
58834  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
58835  p->readpoint.iOffset = iOfst+iAmt;
58836  p->readpoint.pChunk = pChunk;
58837
58838  return SQLITE_OK;
58839}
58840
58841/*
58842** Write data to the file.
58843*/
58844static int memjrnlWrite(
58845  sqlite3_file *pJfd,    /* The journal file into which to write */
58846  const void *zBuf,      /* Take data to be written from here */
58847  int iAmt,              /* Number of bytes to write */
58848  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
58849){
58850  MemJournal *p = (MemJournal *)pJfd;
58851  int nWrite = iAmt;
58852  u8 *zWrite = (u8 *)zBuf;
58853
58854  /* An in-memory journal file should only ever be appended to. Random
58855  ** access writes are not required by sqlite.
58856  */
58857  assert( iOfst==p->endpoint.iOffset );
58858  UNUSED_PARAMETER(iOfst);
58859
58860  while( nWrite>0 ){
58861    FileChunk *pChunk = p->endpoint.pChunk;
58862    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
58863    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
58864
58865    if( iChunkOffset==0 ){
58866      /* New chunk is required to extend the file. */
58867      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
58868      if( !pNew ){
58869        return SQLITE_IOERR_NOMEM;
58870      }
58871      pNew->pNext = 0;
58872      if( pChunk ){
58873        assert( p->pFirst );
58874        pChunk->pNext = pNew;
58875      }else{
58876        assert( !p->pFirst );
58877        p->pFirst = pNew;
58878      }
58879      p->endpoint.pChunk = pNew;
58880    }
58881
58882    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
58883    zWrite += iSpace;
58884    nWrite -= iSpace;
58885    p->endpoint.iOffset += iSpace;
58886  }
58887
58888  return SQLITE_OK;
58889}
58890
58891/*
58892** Truncate the file.
58893*/
58894static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
58895  MemJournal *p = (MemJournal *)pJfd;
58896  FileChunk *pChunk;
58897  assert(size==0);
58898  UNUSED_PARAMETER(size);
58899  pChunk = p->pFirst;
58900  while( pChunk ){
58901    FileChunk *pTmp = pChunk;
58902    pChunk = pChunk->pNext;
58903    sqlite3_free(pTmp);
58904  }
58905  sqlite3MemJournalOpen(pJfd);
58906  return SQLITE_OK;
58907}
58908
58909/*
58910** Close the file.
58911*/
58912static int memjrnlClose(sqlite3_file *pJfd){
58913  memjrnlTruncate(pJfd, 0);
58914  return SQLITE_OK;
58915}
58916
58917
58918/*
58919** Sync the file.
58920**
58921** Syncing an in-memory journal is a no-op.  And, in fact, this routine
58922** is never called in a working implementation.  This implementation
58923** exists purely as a contingency, in case some malfunction in some other
58924** part of SQLite causes Sync to be called by mistake.
58925*/
58926static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){   /*NO_TEST*/
58927  UNUSED_PARAMETER2(NotUsed, NotUsed2);                        /*NO_TEST*/
58928  assert( 0 );                                                 /*NO_TEST*/
58929  return SQLITE_OK;                                            /*NO_TEST*/
58930}                                                              /*NO_TEST*/
58931
58932/*
58933** Query the size of the file in bytes.
58934*/
58935static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
58936  MemJournal *p = (MemJournal *)pJfd;
58937  *pSize = (sqlite_int64) p->endpoint.iOffset;
58938  return SQLITE_OK;
58939}
58940
58941/*
58942** Table of methods for MemJournal sqlite3_file object.
58943*/
58944static struct sqlite3_io_methods MemJournalMethods = {
58945  1,                /* iVersion */
58946  memjrnlClose,     /* xClose */
58947  memjrnlRead,      /* xRead */
58948  memjrnlWrite,     /* xWrite */
58949  memjrnlTruncate,  /* xTruncate */
58950  memjrnlSync,      /* xSync */
58951  memjrnlFileSize,  /* xFileSize */
58952  0,                /* xLock */
58953  0,                /* xUnlock */
58954  0,                /* xCheckReservedLock */
58955  0,                /* xFileControl */
58956  0,                /* xSectorSize */
58957  0                 /* xDeviceCharacteristics */
58958};
58959
58960/*
58961** Open a journal file.
58962*/
58963SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
58964  MemJournal *p = (MemJournal *)pJfd;
58965  assert( EIGHT_BYTE_ALIGNMENT(p) );
58966  memset(p, 0, sqlite3MemJournalSize());
58967  p->pMethod = &MemJournalMethods;
58968}
58969
58970/*
58971** Return true if the file-handle passed as an argument is
58972** an in-memory journal
58973*/
58974SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
58975  return pJfd->pMethods==&MemJournalMethods;
58976}
58977
58978/*
58979** Return the number of bytes required to store a MemJournal that uses vfs
58980** pVfs to create the underlying on-disk files.
58981*/
58982SQLITE_PRIVATE int sqlite3MemJournalSize(void){
58983  return sizeof(MemJournal);
58984}
58985
58986/************** End of memjournal.c ******************************************/
58987/************** Begin file walker.c ******************************************/
58988/*
58989** 2008 August 16
58990**
58991** The author disclaims copyright to this source code.  In place of
58992** a legal notice, here is a blessing:
58993**
58994**    May you do good and not evil.
58995**    May you find forgiveness for yourself and forgive others.
58996**    May you share freely, never taking more than you give.
58997**
58998*************************************************************************
58999** This file contains routines used for walking the parser tree for
59000** an SQL statement.
59001*/
59002
59003
59004/*
59005** Walk an expression tree.  Invoke the callback once for each node
59006** of the expression, while decending.  (In other words, the callback
59007** is invoked before visiting children.)
59008**
59009** The return value from the callback should be one of the WRC_*
59010** constants to specify how to proceed with the walk.
59011**
59012**    WRC_Continue      Continue descending down the tree.
59013**
59014**    WRC_Prune         Do not descend into child nodes.  But allow
59015**                      the walk to continue with sibling nodes.
59016**
59017**    WRC_Abort         Do no more callbacks.  Unwind the stack and
59018**                      return the top-level walk call.
59019**
59020** The return value from this routine is WRC_Abort to abandon the tree walk
59021** and WRC_Continue to continue.
59022*/
59023SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
59024  int rc;
59025  if( pExpr==0 ) return WRC_Continue;
59026  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
59027  testcase( ExprHasProperty(pExpr, EP_Reduced) );
59028  rc = pWalker->xExprCallback(pWalker, pExpr);
59029  if( rc==WRC_Continue
59030              && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
59031    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
59032    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
59033    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
59034      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
59035    }else{
59036      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
59037    }
59038  }
59039  return rc & WRC_Abort;
59040}
59041
59042/*
59043** Call sqlite3WalkExpr() for every expression in list p or until
59044** an abort request is seen.
59045*/
59046SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
59047  int i;
59048  struct ExprList_item *pItem;
59049  if( p ){
59050    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
59051      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
59052    }
59053  }
59054  return WRC_Continue;
59055}
59056
59057/*
59058** Walk all expressions associated with SELECT statement p.  Do
59059** not invoke the SELECT callback on p, but do (of course) invoke
59060** any expr callbacks and SELECT callbacks that come from subqueries.
59061** Return WRC_Abort or WRC_Continue.
59062*/
59063SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
59064  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
59065  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
59066  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
59067  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
59068  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
59069  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
59070  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
59071  return WRC_Continue;
59072}
59073
59074/*
59075** Walk the parse trees associated with all subqueries in the
59076** FROM clause of SELECT statement p.  Do not invoke the select
59077** callback on p, but do invoke it on each FROM clause subquery
59078** and on any subqueries further down in the tree.  Return
59079** WRC_Abort or WRC_Continue;
59080*/
59081SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
59082  SrcList *pSrc;
59083  int i;
59084  struct SrcList_item *pItem;
59085
59086  pSrc = p->pSrc;
59087  if( ALWAYS(pSrc) ){
59088    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
59089      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
59090        return WRC_Abort;
59091      }
59092    }
59093  }
59094  return WRC_Continue;
59095}
59096
59097/*
59098** Call sqlite3WalkExpr() for every expression in Select statement p.
59099** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
59100** on the compound select chain, p->pPrior.
59101**
59102** Return WRC_Continue under normal conditions.  Return WRC_Abort if
59103** there is an abort request.
59104**
59105** If the Walker does not have an xSelectCallback() then this routine
59106** is a no-op returning WRC_Continue.
59107*/
59108SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
59109  int rc;
59110  if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
59111  rc = WRC_Continue;
59112  while( p  ){
59113    rc = pWalker->xSelectCallback(pWalker, p);
59114    if( rc ) break;
59115    if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
59116    if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
59117    p = p->pPrior;
59118  }
59119  return rc & WRC_Abort;
59120}
59121
59122/************** End of walker.c **********************************************/
59123/************** Begin file resolve.c *****************************************/
59124/*
59125** 2008 August 18
59126**
59127** The author disclaims copyright to this source code.  In place of
59128** a legal notice, here is a blessing:
59129**
59130**    May you do good and not evil.
59131**    May you find forgiveness for yourself and forgive others.
59132**    May you share freely, never taking more than you give.
59133**
59134*************************************************************************
59135**
59136** This file contains routines used for walking the parser tree and
59137** resolve all identifiers by associating them with a particular
59138** table and column.
59139*/
59140
59141/*
59142** Turn the pExpr expression into an alias for the iCol-th column of the
59143** result set in pEList.
59144**
59145** If the result set column is a simple column reference, then this routine
59146** makes an exact copy.  But for any other kind of expression, this
59147** routine make a copy of the result set column as the argument to the
59148** TK_AS operator.  The TK_AS operator causes the expression to be
59149** evaluated just once and then reused for each alias.
59150**
59151** The reason for suppressing the TK_AS term when the expression is a simple
59152** column reference is so that the column reference will be recognized as
59153** usable by indices within the WHERE clause processing logic.
59154**
59155** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
59156** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
59157**
59158**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
59159**
59160** Is equivalent to:
59161**
59162**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
59163**
59164** The result of random()%5 in the GROUP BY clause is probably different
59165** from the result in the result-set.  We might fix this someday.  Or
59166** then again, we might not...
59167*/
59168static void resolveAlias(
59169  Parse *pParse,         /* Parsing context */
59170  ExprList *pEList,      /* A result set */
59171  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
59172  Expr *pExpr,           /* Transform this into an alias to the result set */
59173  const char *zType      /* "GROUP" or "ORDER" or "" */
59174){
59175  Expr *pOrig;           /* The iCol-th column of the result set */
59176  Expr *pDup;            /* Copy of pOrig */
59177  sqlite3 *db;           /* The database connection */
59178
59179  assert( iCol>=0 && iCol<pEList->nExpr );
59180  pOrig = pEList->a[iCol].pExpr;
59181  assert( pOrig!=0 );
59182  assert( pOrig->flags & EP_Resolved );
59183  db = pParse->db;
59184  if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
59185    pDup = sqlite3ExprDup(db, pOrig, 0);
59186    pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
59187    if( pDup==0 ) return;
59188    if( pEList->a[iCol].iAlias==0 ){
59189      pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
59190    }
59191    pDup->iTable = pEList->a[iCol].iAlias;
59192  }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
59193    pDup = sqlite3ExprDup(db, pOrig, 0);
59194    if( pDup==0 ) return;
59195  }else{
59196    char *zToken = pOrig->u.zToken;
59197    assert( zToken!=0 );
59198    pOrig->u.zToken = 0;
59199    pDup = sqlite3ExprDup(db, pOrig, 0);
59200    pOrig->u.zToken = zToken;
59201    if( pDup==0 ) return;
59202    assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
59203    pDup->flags2 |= EP2_MallocedToken;
59204    pDup->u.zToken = sqlite3DbStrDup(db, zToken);
59205  }
59206  if( pExpr->flags & EP_ExpCollate ){
59207    pDup->pColl = pExpr->pColl;
59208    pDup->flags |= EP_ExpCollate;
59209  }
59210
59211  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
59212  ** prevents ExprDelete() from deleting the Expr structure itself,
59213  ** allowing it to be repopulated by the memcpy() on the following line.
59214  */
59215  ExprSetProperty(pExpr, EP_Static);
59216  sqlite3ExprDelete(db, pExpr);
59217  memcpy(pExpr, pDup, sizeof(*pExpr));
59218  sqlite3DbFree(db, pDup);
59219}
59220
59221/*
59222** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
59223** that name in the set of source tables in pSrcList and make the pExpr
59224** expression node refer back to that source column.  The following changes
59225** are made to pExpr:
59226**
59227**    pExpr->iDb           Set the index in db->aDb[] of the database X
59228**                         (even if X is implied).
59229**    pExpr->iTable        Set to the cursor number for the table obtained
59230**                         from pSrcList.
59231**    pExpr->pTab          Points to the Table structure of X.Y (even if
59232**                         X and/or Y are implied.)
59233**    pExpr->iColumn       Set to the column number within the table.
59234**    pExpr->op            Set to TK_COLUMN.
59235**    pExpr->pLeft         Any expression this points to is deleted
59236**    pExpr->pRight        Any expression this points to is deleted.
59237**
59238** The zDb variable is the name of the database (the "X").  This value may be
59239** NULL meaning that name is of the form Y.Z or Z.  Any available database
59240** can be used.  The zTable variable is the name of the table (the "Y").  This
59241** value can be NULL if zDb is also NULL.  If zTable is NULL it
59242** means that the form of the name is Z and that columns from any table
59243** can be used.
59244**
59245** If the name cannot be resolved unambiguously, leave an error message
59246** in pParse and return WRC_Abort.  Return WRC_Prune on success.
59247*/
59248static int lookupName(
59249  Parse *pParse,       /* The parsing context */
59250  const char *zDb,     /* Name of the database containing table, or NULL */
59251  const char *zTab,    /* Name of table containing column, or NULL */
59252  const char *zCol,    /* Name of the column. */
59253  NameContext *pNC,    /* The name context used to resolve the name */
59254  Expr *pExpr          /* Make this EXPR node point to the selected column */
59255){
59256  int i, j;            /* Loop counters */
59257  int cnt = 0;                      /* Number of matching column names */
59258  int cntTab = 0;                   /* Number of matching table names */
59259  sqlite3 *db = pParse->db;         /* The database connection */
59260  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
59261  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
59262  NameContext *pTopNC = pNC;        /* First namecontext in the list */
59263  Schema *pSchema = 0;              /* Schema of the expression */
59264  int isTrigger = 0;
59265
59266  assert( pNC );     /* the name context cannot be NULL. */
59267  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
59268  assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
59269
59270  /* Initialize the node to no-match */
59271  pExpr->iTable = -1;
59272  pExpr->pTab = 0;
59273  ExprSetIrreducible(pExpr);
59274
59275  /* Start at the inner-most context and move outward until a match is found */
59276  while( pNC && cnt==0 ){
59277    ExprList *pEList;
59278    SrcList *pSrcList = pNC->pSrcList;
59279
59280    if( pSrcList ){
59281      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
59282        Table *pTab;
59283        int iDb;
59284        Column *pCol;
59285
59286        pTab = pItem->pTab;
59287        assert( pTab!=0 && pTab->zName!=0 );
59288        iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
59289        assert( pTab->nCol>0 );
59290        if( zTab ){
59291          if( pItem->zAlias ){
59292            char *zTabName = pItem->zAlias;
59293            if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
59294          }else{
59295            char *zTabName = pTab->zName;
59296            if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
59297              continue;
59298            }
59299            if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
59300              continue;
59301            }
59302          }
59303        }
59304        if( 0==(cntTab++) ){
59305          pExpr->iTable = pItem->iCursor;
59306          pExpr->pTab = pTab;
59307          pSchema = pTab->pSchema;
59308          pMatch = pItem;
59309        }
59310        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
59311          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
59312            IdList *pUsing;
59313            cnt++;
59314            pExpr->iTable = pItem->iCursor;
59315            pExpr->pTab = pTab;
59316            pMatch = pItem;
59317            pSchema = pTab->pSchema;
59318            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
59319            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
59320            if( i<pSrcList->nSrc-1 ){
59321              if( pItem[1].jointype & JT_NATURAL ){
59322                /* If this match occurred in the left table of a natural join,
59323                ** then skip the right table to avoid a duplicate match */
59324                pItem++;
59325                i++;
59326              }else if( (pUsing = pItem[1].pUsing)!=0 ){
59327                /* If this match occurs on a column that is in the USING clause
59328                ** of a join, skip the search of the right table of the join
59329                ** to avoid a duplicate match there. */
59330                int k;
59331                for(k=0; k<pUsing->nId; k++){
59332                  if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
59333                    pItem++;
59334                    i++;
59335                    break;
59336                  }
59337                }
59338              }
59339            }
59340            break;
59341          }
59342        }
59343      }
59344    }
59345
59346#ifndef SQLITE_OMIT_TRIGGER
59347    /* If we have not already resolved the name, then maybe
59348    ** it is a new.* or old.* trigger argument reference
59349    */
59350    if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
59351      int op = pParse->eTriggerOp;
59352      Table *pTab = 0;
59353      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
59354      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
59355        pExpr->iTable = 1;
59356        pTab = pParse->pTriggerTab;
59357      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
59358        pExpr->iTable = 0;
59359        pTab = pParse->pTriggerTab;
59360      }
59361
59362      if( pTab ){
59363        int iCol;
59364        pSchema = pTab->pSchema;
59365        cntTab++;
59366        for(iCol=0; iCol<pTab->nCol; iCol++){
59367          Column *pCol = &pTab->aCol[iCol];
59368          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
59369            if( iCol==pTab->iPKey ){
59370              iCol = -1;
59371            }
59372            break;
59373          }
59374        }
59375        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
59376          iCol = -1;        /* IMP: R-44911-55124 */
59377        }
59378        if( iCol<pTab->nCol ){
59379          cnt++;
59380          if( iCol<0 ){
59381            pExpr->affinity = SQLITE_AFF_INTEGER;
59382          }else if( pExpr->iTable==0 ){
59383            testcase( iCol==31 );
59384            testcase( iCol==32 );
59385            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
59386          }else{
59387            testcase( iCol==31 );
59388            testcase( iCol==32 );
59389            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
59390          }
59391          pExpr->iColumn = (i16)iCol;
59392          pExpr->pTab = pTab;
59393          isTrigger = 1;
59394        }
59395      }
59396    }
59397#endif /* !defined(SQLITE_OMIT_TRIGGER) */
59398
59399    /*
59400    ** Perhaps the name is a reference to the ROWID
59401    */
59402    if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
59403      cnt = 1;
59404      pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
59405      pExpr->affinity = SQLITE_AFF_INTEGER;
59406    }
59407
59408    /*
59409    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
59410    ** might refer to an result-set alias.  This happens, for example, when
59411    ** we are resolving names in the WHERE clause of the following command:
59412    **
59413    **     SELECT a+b AS x FROM table WHERE x<10;
59414    **
59415    ** In cases like this, replace pExpr with a copy of the expression that
59416    ** forms the result set entry ("a+b" in the example) and return immediately.
59417    ** Note that the expression in the result set should have already been
59418    ** resolved by the time the WHERE clause is resolved.
59419    */
59420    if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
59421      for(j=0; j<pEList->nExpr; j++){
59422        char *zAs = pEList->a[j].zName;
59423        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
59424          Expr *pOrig;
59425          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
59426          assert( pExpr->x.pList==0 );
59427          assert( pExpr->x.pSelect==0 );
59428          pOrig = pEList->a[j].pExpr;
59429          if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
59430            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
59431            return WRC_Abort;
59432          }
59433          resolveAlias(pParse, pEList, j, pExpr, "");
59434          cnt = 1;
59435          pMatch = 0;
59436          assert( zTab==0 && zDb==0 );
59437          goto lookupname_end;
59438        }
59439      }
59440    }
59441
59442    /* Advance to the next name context.  The loop will exit when either
59443    ** we have a match (cnt>0) or when we run out of name contexts.
59444    */
59445    if( cnt==0 ){
59446      pNC = pNC->pNext;
59447    }
59448  }
59449
59450  /*
59451  ** If X and Y are NULL (in other words if only the column name Z is
59452  ** supplied) and the value of Z is enclosed in double-quotes, then
59453  ** Z is a string literal if it doesn't match any column names.  In that
59454  ** case, we need to return right away and not make any changes to
59455  ** pExpr.
59456  **
59457  ** Because no reference was made to outer contexts, the pNC->nRef
59458  ** fields are not changed in any context.
59459  */
59460  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
59461    pExpr->op = TK_STRING;
59462    pExpr->pTab = 0;
59463    return WRC_Prune;
59464  }
59465
59466  /*
59467  ** cnt==0 means there was not match.  cnt>1 means there were two or
59468  ** more matches.  Either way, we have an error.
59469  */
59470  if( cnt!=1 ){
59471    const char *zErr;
59472    zErr = cnt==0 ? "no such column" : "ambiguous column name";
59473    if( zDb ){
59474      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
59475    }else if( zTab ){
59476      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
59477    }else{
59478      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
59479    }
59480    pTopNC->nErr++;
59481  }
59482
59483  /* If a column from a table in pSrcList is referenced, then record
59484  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
59485  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
59486  ** column number is greater than the number of bits in the bitmask
59487  ** then set the high-order bit of the bitmask.
59488  */
59489  if( pExpr->iColumn>=0 && pMatch!=0 ){
59490    int n = pExpr->iColumn;
59491    testcase( n==BMS-1 );
59492    if( n>=BMS ){
59493      n = BMS-1;
59494    }
59495    assert( pMatch->iCursor==pExpr->iTable );
59496    pMatch->colUsed |= ((Bitmask)1)<<n;
59497  }
59498
59499  /* Clean up and return
59500  */
59501  sqlite3ExprDelete(db, pExpr->pLeft);
59502  pExpr->pLeft = 0;
59503  sqlite3ExprDelete(db, pExpr->pRight);
59504  pExpr->pRight = 0;
59505  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
59506lookupname_end:
59507  if( cnt==1 ){
59508    assert( pNC!=0 );
59509    sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
59510    /* Increment the nRef value on all name contexts from TopNC up to
59511    ** the point where the name matched. */
59512    for(;;){
59513      assert( pTopNC!=0 );
59514      pTopNC->nRef++;
59515      if( pTopNC==pNC ) break;
59516      pTopNC = pTopNC->pNext;
59517    }
59518    return WRC_Prune;
59519  } else {
59520    return WRC_Abort;
59521  }
59522}
59523
59524/*
59525** Allocate and return a pointer to an expression to load the column iCol
59526** from datasource iSrc datasource in SrcList pSrc.
59527*/
59528SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
59529  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
59530  if( p ){
59531    struct SrcList_item *pItem = &pSrc->a[iSrc];
59532    p->pTab = pItem->pTab;
59533    p->iTable = pItem->iCursor;
59534    if( p->pTab->iPKey==iCol ){
59535      p->iColumn = -1;
59536    }else{
59537      p->iColumn = (ynVar)iCol;
59538      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
59539    }
59540    ExprSetProperty(p, EP_Resolved);
59541  }
59542  return p;
59543}
59544
59545/*
59546** This routine is callback for sqlite3WalkExpr().
59547**
59548** Resolve symbolic names into TK_COLUMN operators for the current
59549** node in the expression tree.  Return 0 to continue the search down
59550** the tree or 2 to abort the tree walk.
59551**
59552** This routine also does error checking and name resolution for
59553** function names.  The operator for aggregate functions is changed
59554** to TK_AGG_FUNCTION.
59555*/
59556static int resolveExprStep(Walker *pWalker, Expr *pExpr){
59557  NameContext *pNC;
59558  Parse *pParse;
59559
59560  pNC = pWalker->u.pNC;
59561  assert( pNC!=0 );
59562  pParse = pNC->pParse;
59563  assert( pParse==pWalker->pParse );
59564
59565  if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
59566  ExprSetProperty(pExpr, EP_Resolved);
59567#ifndef NDEBUG
59568  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
59569    SrcList *pSrcList = pNC->pSrcList;
59570    int i;
59571    for(i=0; i<pNC->pSrcList->nSrc; i++){
59572      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
59573    }
59574  }
59575#endif
59576  switch( pExpr->op ){
59577
59578#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
59579    /* The special operator TK_ROW means use the rowid for the first
59580    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
59581    ** clause processing on UPDATE and DELETE statements.
59582    */
59583    case TK_ROW: {
59584      SrcList *pSrcList = pNC->pSrcList;
59585      struct SrcList_item *pItem;
59586      assert( pSrcList && pSrcList->nSrc==1 );
59587      pItem = pSrcList->a;
59588      pExpr->op = TK_COLUMN;
59589      pExpr->pTab = pItem->pTab;
59590      pExpr->iTable = pItem->iCursor;
59591      pExpr->iColumn = -1;
59592      pExpr->affinity = SQLITE_AFF_INTEGER;
59593      break;
59594    }
59595#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
59596
59597    /* A lone identifier is the name of a column.
59598    */
59599    case TK_ID: {
59600      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
59601    }
59602
59603    /* A table name and column name:     ID.ID
59604    ** Or a database, table and column:  ID.ID.ID
59605    */
59606    case TK_DOT: {
59607      const char *zColumn;
59608      const char *zTable;
59609      const char *zDb;
59610      Expr *pRight;
59611
59612      /* if( pSrcList==0 ) break; */
59613      pRight = pExpr->pRight;
59614      if( pRight->op==TK_ID ){
59615        zDb = 0;
59616        zTable = pExpr->pLeft->u.zToken;
59617        zColumn = pRight->u.zToken;
59618      }else{
59619        assert( pRight->op==TK_DOT );
59620        zDb = pExpr->pLeft->u.zToken;
59621        zTable = pRight->pLeft->u.zToken;
59622        zColumn = pRight->pRight->u.zToken;
59623      }
59624      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
59625    }
59626
59627    /* Resolve function names
59628    */
59629    case TK_CONST_FUNC:
59630    case TK_FUNCTION: {
59631      ExprList *pList = pExpr->x.pList;    /* The argument list */
59632      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
59633      int no_such_func = 0;       /* True if no such function exists */
59634      int wrong_num_args = 0;     /* True if wrong number of arguments */
59635      int is_agg = 0;             /* True if is an aggregate function */
59636      int auth;                   /* Authorization to use the function */
59637      int nId;                    /* Number of characters in function name */
59638      const char *zId;            /* The function name. */
59639      FuncDef *pDef;              /* Information about the function */
59640      u8 enc = ENC(pParse->db);   /* The database encoding */
59641
59642      testcase( pExpr->op==TK_CONST_FUNC );
59643      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
59644      zId = pExpr->u.zToken;
59645      nId = sqlite3Strlen30(zId);
59646      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
59647      if( pDef==0 ){
59648        pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
59649        if( pDef==0 ){
59650          no_such_func = 1;
59651        }else{
59652          wrong_num_args = 1;
59653        }
59654      }else{
59655        is_agg = pDef->xFunc==0;
59656      }
59657#ifndef SQLITE_OMIT_AUTHORIZATION
59658      if( pDef ){
59659        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
59660        if( auth!=SQLITE_OK ){
59661          if( auth==SQLITE_DENY ){
59662            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
59663                                    pDef->zName);
59664            pNC->nErr++;
59665          }
59666          pExpr->op = TK_NULL;
59667          return WRC_Prune;
59668        }
59669      }
59670#endif
59671      if( is_agg && !pNC->allowAgg ){
59672        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
59673        pNC->nErr++;
59674        is_agg = 0;
59675      }else if( no_such_func ){
59676        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
59677        pNC->nErr++;
59678      }else if( wrong_num_args ){
59679        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
59680             nId, zId);
59681        pNC->nErr++;
59682      }
59683      if( is_agg ){
59684        pExpr->op = TK_AGG_FUNCTION;
59685        pNC->hasAgg = 1;
59686      }
59687      if( is_agg ) pNC->allowAgg = 0;
59688      sqlite3WalkExprList(pWalker, pList);
59689      if( is_agg ) pNC->allowAgg = 1;
59690      /* FIX ME:  Compute pExpr->affinity based on the expected return
59691      ** type of the function
59692      */
59693      return WRC_Prune;
59694    }
59695#ifndef SQLITE_OMIT_SUBQUERY
59696    case TK_SELECT:
59697    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
59698#endif
59699    case TK_IN: {
59700      testcase( pExpr->op==TK_IN );
59701      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
59702        int nRef = pNC->nRef;
59703#ifndef SQLITE_OMIT_CHECK
59704        if( pNC->isCheck ){
59705          sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
59706        }
59707#endif
59708        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
59709        assert( pNC->nRef>=nRef );
59710        if( nRef!=pNC->nRef ){
59711          ExprSetProperty(pExpr, EP_VarSelect);
59712        }
59713      }
59714      break;
59715    }
59716#ifndef SQLITE_OMIT_CHECK
59717    case TK_VARIABLE: {
59718      if( pNC->isCheck ){
59719        sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
59720      }
59721      break;
59722    }
59723#endif
59724  }
59725  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
59726}
59727
59728/*
59729** pEList is a list of expressions which are really the result set of the
59730** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
59731** This routine checks to see if pE is a simple identifier which corresponds
59732** to the AS-name of one of the terms of the expression list.  If it is,
59733** this routine return an integer between 1 and N where N is the number of
59734** elements in pEList, corresponding to the matching entry.  If there is
59735** no match, or if pE is not a simple identifier, then this routine
59736** return 0.
59737**
59738** pEList has been resolved.  pE has not.
59739*/
59740static int resolveAsName(
59741  Parse *pParse,     /* Parsing context for error messages */
59742  ExprList *pEList,  /* List of expressions to scan */
59743  Expr *pE           /* Expression we are trying to match */
59744){
59745  int i;             /* Loop counter */
59746
59747  UNUSED_PARAMETER(pParse);
59748
59749  if( pE->op==TK_ID ){
59750    char *zCol = pE->u.zToken;
59751    for(i=0; i<pEList->nExpr; i++){
59752      char *zAs = pEList->a[i].zName;
59753      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
59754        return i+1;
59755      }
59756    }
59757  }
59758  return 0;
59759}
59760
59761/*
59762** pE is a pointer to an expression which is a single term in the
59763** ORDER BY of a compound SELECT.  The expression has not been
59764** name resolved.
59765**
59766** At the point this routine is called, we already know that the
59767** ORDER BY term is not an integer index into the result set.  That
59768** case is handled by the calling routine.
59769**
59770** Attempt to match pE against result set columns in the left-most
59771** SELECT statement.  Return the index i of the matching column,
59772** as an indication to the caller that it should sort by the i-th column.
59773** The left-most column is 1.  In other words, the value returned is the
59774** same integer value that would be used in the SQL statement to indicate
59775** the column.
59776**
59777** If there is no match, return 0.  Return -1 if an error occurs.
59778*/
59779static int resolveOrderByTermToExprList(
59780  Parse *pParse,     /* Parsing context for error messages */
59781  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
59782  Expr *pE           /* The specific ORDER BY term */
59783){
59784  int i;             /* Loop counter */
59785  ExprList *pEList;  /* The columns of the result set */
59786  NameContext nc;    /* Name context for resolving pE */
59787
59788  assert( sqlite3ExprIsInteger(pE, &i)==0 );
59789  pEList = pSelect->pEList;
59790
59791  /* Resolve all names in the ORDER BY term expression
59792  */
59793  memset(&nc, 0, sizeof(nc));
59794  nc.pParse = pParse;
59795  nc.pSrcList = pSelect->pSrc;
59796  nc.pEList = pEList;
59797  nc.allowAgg = 1;
59798  nc.nErr = 0;
59799  if( sqlite3ResolveExprNames(&nc, pE) ){
59800    sqlite3ErrorClear(pParse);
59801    return 0;
59802  }
59803
59804  /* Try to match the ORDER BY expression against an expression
59805  ** in the result set.  Return an 1-based index of the matching
59806  ** result-set entry.
59807  */
59808  for(i=0; i<pEList->nExpr; i++){
59809    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
59810      return i+1;
59811    }
59812  }
59813
59814  /* If no match, return 0. */
59815  return 0;
59816}
59817
59818/*
59819** Generate an ORDER BY or GROUP BY term out-of-range error.
59820*/
59821static void resolveOutOfRangeError(
59822  Parse *pParse,         /* The error context into which to write the error */
59823  const char *zType,     /* "ORDER" or "GROUP" */
59824  int i,                 /* The index (1-based) of the term out of range */
59825  int mx                 /* Largest permissible value of i */
59826){
59827  sqlite3ErrorMsg(pParse,
59828    "%r %s BY term out of range - should be "
59829    "between 1 and %d", i, zType, mx);
59830}
59831
59832/*
59833** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
59834** each term of the ORDER BY clause is a constant integer between 1
59835** and N where N is the number of columns in the compound SELECT.
59836**
59837** ORDER BY terms that are already an integer between 1 and N are
59838** unmodified.  ORDER BY terms that are integers outside the range of
59839** 1 through N generate an error.  ORDER BY terms that are expressions
59840** are matched against result set expressions of compound SELECT
59841** beginning with the left-most SELECT and working toward the right.
59842** At the first match, the ORDER BY expression is transformed into
59843** the integer column number.
59844**
59845** Return the number of errors seen.
59846*/
59847static int resolveCompoundOrderBy(
59848  Parse *pParse,        /* Parsing context.  Leave error messages here */
59849  Select *pSelect       /* The SELECT statement containing the ORDER BY */
59850){
59851  int i;
59852  ExprList *pOrderBy;
59853  ExprList *pEList;
59854  sqlite3 *db;
59855  int moreToDo = 1;
59856
59857  pOrderBy = pSelect->pOrderBy;
59858  if( pOrderBy==0 ) return 0;
59859  db = pParse->db;
59860#if SQLITE_MAX_COLUMN
59861  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
59862    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
59863    return 1;
59864  }
59865#endif
59866  for(i=0; i<pOrderBy->nExpr; i++){
59867    pOrderBy->a[i].done = 0;
59868  }
59869  pSelect->pNext = 0;
59870  while( pSelect->pPrior ){
59871    pSelect->pPrior->pNext = pSelect;
59872    pSelect = pSelect->pPrior;
59873  }
59874  while( pSelect && moreToDo ){
59875    struct ExprList_item *pItem;
59876    moreToDo = 0;
59877    pEList = pSelect->pEList;
59878    assert( pEList!=0 );
59879    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
59880      int iCol = -1;
59881      Expr *pE, *pDup;
59882      if( pItem->done ) continue;
59883      pE = pItem->pExpr;
59884      if( sqlite3ExprIsInteger(pE, &iCol) ){
59885        if( iCol<=0 || iCol>pEList->nExpr ){
59886          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
59887          return 1;
59888        }
59889      }else{
59890        iCol = resolveAsName(pParse, pEList, pE);
59891        if( iCol==0 ){
59892          pDup = sqlite3ExprDup(db, pE, 0);
59893          if( !db->mallocFailed ){
59894            assert(pDup);
59895            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
59896          }
59897          sqlite3ExprDelete(db, pDup);
59898        }
59899      }
59900      if( iCol>0 ){
59901        CollSeq *pColl = pE->pColl;
59902        int flags = pE->flags & EP_ExpCollate;
59903        sqlite3ExprDelete(db, pE);
59904        pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
59905        if( pE==0 ) return 1;
59906        pE->pColl = pColl;
59907        pE->flags |= EP_IntValue | flags;
59908        pE->u.iValue = iCol;
59909        pItem->iCol = (u16)iCol;
59910        pItem->done = 1;
59911      }else{
59912        moreToDo = 1;
59913      }
59914    }
59915    pSelect = pSelect->pNext;
59916  }
59917  for(i=0; i<pOrderBy->nExpr; i++){
59918    if( pOrderBy->a[i].done==0 ){
59919      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
59920            "column in the result set", i+1);
59921      return 1;
59922    }
59923  }
59924  return 0;
59925}
59926
59927/*
59928** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
59929** the SELECT statement pSelect.  If any term is reference to a
59930** result set expression (as determined by the ExprList.a.iCol field)
59931** then convert that term into a copy of the corresponding result set
59932** column.
59933**
59934** If any errors are detected, add an error message to pParse and
59935** return non-zero.  Return zero if no errors are seen.
59936*/
59937SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
59938  Parse *pParse,        /* Parsing context.  Leave error messages here */
59939  Select *pSelect,      /* The SELECT statement containing the clause */
59940  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
59941  const char *zType     /* "ORDER" or "GROUP" */
59942){
59943  int i;
59944  sqlite3 *db = pParse->db;
59945  ExprList *pEList;
59946  struct ExprList_item *pItem;
59947
59948  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
59949#if SQLITE_MAX_COLUMN
59950  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
59951    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
59952    return 1;
59953  }
59954#endif
59955  pEList = pSelect->pEList;
59956  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
59957  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
59958    if( pItem->iCol ){
59959      if( pItem->iCol>pEList->nExpr ){
59960        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
59961        return 1;
59962      }
59963      resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
59964    }
59965  }
59966  return 0;
59967}
59968
59969/*
59970** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
59971** The Name context of the SELECT statement is pNC.  zType is either
59972** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
59973**
59974** This routine resolves each term of the clause into an expression.
59975** If the order-by term is an integer I between 1 and N (where N is the
59976** number of columns in the result set of the SELECT) then the expression
59977** in the resolution is a copy of the I-th result-set expression.  If
59978** the order-by term is an identify that corresponds to the AS-name of
59979** a result-set expression, then the term resolves to a copy of the
59980** result-set expression.  Otherwise, the expression is resolved in
59981** the usual way - using sqlite3ResolveExprNames().
59982**
59983** This routine returns the number of errors.  If errors occur, then
59984** an appropriate error message might be left in pParse.  (OOM errors
59985** excepted.)
59986*/
59987static int resolveOrderGroupBy(
59988  NameContext *pNC,     /* The name context of the SELECT statement */
59989  Select *pSelect,      /* The SELECT statement holding pOrderBy */
59990  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
59991  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
59992){
59993  int i;                         /* Loop counter */
59994  int iCol;                      /* Column number */
59995  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
59996  Parse *pParse;                 /* Parsing context */
59997  int nResult;                   /* Number of terms in the result set */
59998
59999  if( pOrderBy==0 ) return 0;
60000  nResult = pSelect->pEList->nExpr;
60001  pParse = pNC->pParse;
60002  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
60003    Expr *pE = pItem->pExpr;
60004    iCol = resolveAsName(pParse, pSelect->pEList, pE);
60005    if( iCol>0 ){
60006      /* If an AS-name match is found, mark this ORDER BY column as being
60007      ** a copy of the iCol-th result-set column.  The subsequent call to
60008      ** sqlite3ResolveOrderGroupBy() will convert the expression to a
60009      ** copy of the iCol-th result-set expression. */
60010      pItem->iCol = (u16)iCol;
60011      continue;
60012    }
60013    if( sqlite3ExprIsInteger(pE, &iCol) ){
60014      /* The ORDER BY term is an integer constant.  Again, set the column
60015      ** number so that sqlite3ResolveOrderGroupBy() will convert the
60016      ** order-by term to a copy of the result-set expression */
60017      if( iCol<1 ){
60018        resolveOutOfRangeError(pParse, zType, i+1, nResult);
60019        return 1;
60020      }
60021      pItem->iCol = (u16)iCol;
60022      continue;
60023    }
60024
60025    /* Otherwise, treat the ORDER BY term as an ordinary expression */
60026    pItem->iCol = 0;
60027    if( sqlite3ResolveExprNames(pNC, pE) ){
60028      return 1;
60029    }
60030  }
60031  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
60032}
60033
60034/*
60035** Resolve names in the SELECT statement p and all of its descendents.
60036*/
60037static int resolveSelectStep(Walker *pWalker, Select *p){
60038  NameContext *pOuterNC;  /* Context that contains this SELECT */
60039  NameContext sNC;        /* Name context of this SELECT */
60040  int isCompound;         /* True if p is a compound select */
60041  int nCompound;          /* Number of compound terms processed so far */
60042  Parse *pParse;          /* Parsing context */
60043  ExprList *pEList;       /* Result set expression list */
60044  int i;                  /* Loop counter */
60045  ExprList *pGroupBy;     /* The GROUP BY clause */
60046  Select *pLeftmost;      /* Left-most of SELECT of a compound */
60047  sqlite3 *db;            /* Database connection */
60048
60049
60050  assert( p!=0 );
60051  if( p->selFlags & SF_Resolved ){
60052    return WRC_Prune;
60053  }
60054  pOuterNC = pWalker->u.pNC;
60055  pParse = pWalker->pParse;
60056  db = pParse->db;
60057
60058  /* Normally sqlite3SelectExpand() will be called first and will have
60059  ** already expanded this SELECT.  However, if this is a subquery within
60060  ** an expression, sqlite3ResolveExprNames() will be called without a
60061  ** prior call to sqlite3SelectExpand().  When that happens, let
60062  ** sqlite3SelectPrep() do all of the processing for this SELECT.
60063  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
60064  ** this routine in the correct order.
60065  */
60066  if( (p->selFlags & SF_Expanded)==0 ){
60067    sqlite3SelectPrep(pParse, p, pOuterNC);
60068    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
60069  }
60070
60071  isCompound = p->pPrior!=0;
60072  nCompound = 0;
60073  pLeftmost = p;
60074  while( p ){
60075    assert( (p->selFlags & SF_Expanded)!=0 );
60076    assert( (p->selFlags & SF_Resolved)==0 );
60077    p->selFlags |= SF_Resolved;
60078
60079    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
60080    ** are not allowed to refer to any names, so pass an empty NameContext.
60081    */
60082    memset(&sNC, 0, sizeof(sNC));
60083    sNC.pParse = pParse;
60084    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
60085        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
60086      return WRC_Abort;
60087    }
60088
60089    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
60090    ** resolve the result-set expression list.
60091    */
60092    sNC.allowAgg = 1;
60093    sNC.pSrcList = p->pSrc;
60094    sNC.pNext = pOuterNC;
60095
60096    /* Resolve names in the result set. */
60097    pEList = p->pEList;
60098    assert( pEList!=0 );
60099    for(i=0; i<pEList->nExpr; i++){
60100      Expr *pX = pEList->a[i].pExpr;
60101      if( sqlite3ResolveExprNames(&sNC, pX) ){
60102        return WRC_Abort;
60103      }
60104    }
60105
60106    /* Recursively resolve names in all subqueries
60107    */
60108    for(i=0; i<p->pSrc->nSrc; i++){
60109      struct SrcList_item *pItem = &p->pSrc->a[i];
60110      if( pItem->pSelect ){
60111        const char *zSavedContext = pParse->zAuthContext;
60112        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
60113        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
60114        pParse->zAuthContext = zSavedContext;
60115        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
60116      }
60117    }
60118
60119    /* If there are no aggregate functions in the result-set, and no GROUP BY
60120    ** expression, do not allow aggregates in any of the other expressions.
60121    */
60122    assert( (p->selFlags & SF_Aggregate)==0 );
60123    pGroupBy = p->pGroupBy;
60124    if( pGroupBy || sNC.hasAgg ){
60125      p->selFlags |= SF_Aggregate;
60126    }else{
60127      sNC.allowAgg = 0;
60128    }
60129
60130    /* If a HAVING clause is present, then there must be a GROUP BY clause.
60131    */
60132    if( p->pHaving && !pGroupBy ){
60133      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
60134      return WRC_Abort;
60135    }
60136
60137    /* Add the expression list to the name-context before parsing the
60138    ** other expressions in the SELECT statement. This is so that
60139    ** expressions in the WHERE clause (etc.) can refer to expressions by
60140    ** aliases in the result set.
60141    **
60142    ** Minor point: If this is the case, then the expression will be
60143    ** re-evaluated for each reference to it.
60144    */
60145    sNC.pEList = p->pEList;
60146    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
60147       sqlite3ResolveExprNames(&sNC, p->pHaving)
60148    ){
60149      return WRC_Abort;
60150    }
60151
60152    /* The ORDER BY and GROUP BY clauses may not refer to terms in
60153    ** outer queries
60154    */
60155    sNC.pNext = 0;
60156    sNC.allowAgg = 1;
60157
60158    /* Process the ORDER BY clause for singleton SELECT statements.
60159    ** The ORDER BY clause for compounds SELECT statements is handled
60160    ** below, after all of the result-sets for all of the elements of
60161    ** the compound have been resolved.
60162    */
60163    if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
60164      return WRC_Abort;
60165    }
60166    if( db->mallocFailed ){
60167      return WRC_Abort;
60168    }
60169
60170    /* Resolve the GROUP BY clause.  At the same time, make sure
60171    ** the GROUP BY clause does not contain aggregate functions.
60172    */
60173    if( pGroupBy ){
60174      struct ExprList_item *pItem;
60175
60176      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
60177        return WRC_Abort;
60178      }
60179      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
60180        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
60181          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
60182              "the GROUP BY clause");
60183          return WRC_Abort;
60184        }
60185      }
60186    }
60187
60188    /* Advance to the next term of the compound
60189    */
60190    p = p->pPrior;
60191    nCompound++;
60192  }
60193
60194  /* Resolve the ORDER BY on a compound SELECT after all terms of
60195  ** the compound have been resolved.
60196  */
60197  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
60198    return WRC_Abort;
60199  }
60200
60201  return WRC_Prune;
60202}
60203
60204/*
60205** This routine walks an expression tree and resolves references to
60206** table columns and result-set columns.  At the same time, do error
60207** checking on function usage and set a flag if any aggregate functions
60208** are seen.
60209**
60210** To resolve table columns references we look for nodes (or subtrees) of the
60211** form X.Y.Z or Y.Z or just Z where
60212**
60213**      X:   The name of a database.  Ex:  "main" or "temp" or
60214**           the symbolic name assigned to an ATTACH-ed database.
60215**
60216**      Y:   The name of a table in a FROM clause.  Or in a trigger
60217**           one of the special names "old" or "new".
60218**
60219**      Z:   The name of a column in table Y.
60220**
60221** The node at the root of the subtree is modified as follows:
60222**
60223**    Expr.op        Changed to TK_COLUMN
60224**    Expr.pTab      Points to the Table object for X.Y
60225**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
60226**    Expr.iTable    The VDBE cursor number for X.Y
60227**
60228**
60229** To resolve result-set references, look for expression nodes of the
60230** form Z (with no X and Y prefix) where the Z matches the right-hand
60231** size of an AS clause in the result-set of a SELECT.  The Z expression
60232** is replaced by a copy of the left-hand side of the result-set expression.
60233** Table-name and function resolution occurs on the substituted expression
60234** tree.  For example, in:
60235**
60236**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
60237**
60238** The "x" term of the order by is replaced by "a+b" to render:
60239**
60240**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
60241**
60242** Function calls are checked to make sure that the function is
60243** defined and that the correct number of arguments are specified.
60244** If the function is an aggregate function, then the pNC->hasAgg is
60245** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
60246** If an expression contains aggregate functions then the EP_Agg
60247** property on the expression is set.
60248**
60249** An error message is left in pParse if anything is amiss.  The number
60250** if errors is returned.
60251*/
60252SQLITE_PRIVATE int sqlite3ResolveExprNames(
60253  NameContext *pNC,       /* Namespace to resolve expressions in. */
60254  Expr *pExpr             /* The expression to be analyzed. */
60255){
60256  int savedHasAgg;
60257  Walker w;
60258
60259  if( pExpr==0 ) return 0;
60260#if SQLITE_MAX_EXPR_DEPTH>0
60261  {
60262    Parse *pParse = pNC->pParse;
60263    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
60264      return 1;
60265    }
60266    pParse->nHeight += pExpr->nHeight;
60267  }
60268#endif
60269  savedHasAgg = pNC->hasAgg;
60270  pNC->hasAgg = 0;
60271  w.xExprCallback = resolveExprStep;
60272  w.xSelectCallback = resolveSelectStep;
60273  w.pParse = pNC->pParse;
60274  w.u.pNC = pNC;
60275  sqlite3WalkExpr(&w, pExpr);
60276#if SQLITE_MAX_EXPR_DEPTH>0
60277  pNC->pParse->nHeight -= pExpr->nHeight;
60278#endif
60279  if( pNC->nErr>0 || w.pParse->nErr>0 ){
60280    ExprSetProperty(pExpr, EP_Error);
60281  }
60282  if( pNC->hasAgg ){
60283    ExprSetProperty(pExpr, EP_Agg);
60284  }else if( savedHasAgg ){
60285    pNC->hasAgg = 1;
60286  }
60287  return ExprHasProperty(pExpr, EP_Error);
60288}
60289
60290
60291/*
60292** Resolve all names in all expressions of a SELECT and in all
60293** decendents of the SELECT, including compounds off of p->pPrior,
60294** subqueries in expressions, and subqueries used as FROM clause
60295** terms.
60296**
60297** See sqlite3ResolveExprNames() for a description of the kinds of
60298** transformations that occur.
60299**
60300** All SELECT statements should have been expanded using
60301** sqlite3SelectExpand() prior to invoking this routine.
60302*/
60303SQLITE_PRIVATE void sqlite3ResolveSelectNames(
60304  Parse *pParse,         /* The parser context */
60305  Select *p,             /* The SELECT statement being coded. */
60306  NameContext *pOuterNC  /* Name context for parent SELECT statement */
60307){
60308  Walker w;
60309
60310  assert( p!=0 );
60311  w.xExprCallback = resolveExprStep;
60312  w.xSelectCallback = resolveSelectStep;
60313  w.pParse = pParse;
60314  w.u.pNC = pOuterNC;
60315  sqlite3WalkSelect(&w, p);
60316}
60317
60318/************** End of resolve.c *********************************************/
60319/************** Begin file expr.c ********************************************/
60320/*
60321** 2001 September 15
60322**
60323** The author disclaims copyright to this source code.  In place of
60324** a legal notice, here is a blessing:
60325**
60326**    May you do good and not evil.
60327**    May you find forgiveness for yourself and forgive others.
60328**    May you share freely, never taking more than you give.
60329**
60330*************************************************************************
60331** This file contains routines used for analyzing expressions and
60332** for generating VDBE code that evaluates expressions in SQLite.
60333*/
60334
60335/*
60336** Return the 'affinity' of the expression pExpr if any.
60337**
60338** If pExpr is a column, a reference to a column via an 'AS' alias,
60339** or a sub-select with a column as the return value, then the
60340** affinity of that column is returned. Otherwise, 0x00 is returned,
60341** indicating no affinity for the expression.
60342**
60343** i.e. the WHERE clause expresssions in the following statements all
60344** have an affinity:
60345**
60346** CREATE TABLE t1(a);
60347** SELECT * FROM t1 WHERE a;
60348** SELECT a AS b FROM t1 WHERE b;
60349** SELECT * FROM t1 WHERE (select a from t1);
60350*/
60351SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
60352  int op = pExpr->op;
60353  if( op==TK_SELECT ){
60354    assert( pExpr->flags&EP_xIsSelect );
60355    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
60356  }
60357#ifndef SQLITE_OMIT_CAST
60358  if( op==TK_CAST ){
60359    assert( !ExprHasProperty(pExpr, EP_IntValue) );
60360    return sqlite3AffinityType(pExpr->u.zToken);
60361  }
60362#endif
60363  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
60364   && pExpr->pTab!=0
60365  ){
60366    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
60367    ** a TK_COLUMN but was previously evaluated and cached in a register */
60368    int j = pExpr->iColumn;
60369    if( j<0 ) return SQLITE_AFF_INTEGER;
60370    assert( pExpr->pTab && j<pExpr->pTab->nCol );
60371    return pExpr->pTab->aCol[j].affinity;
60372  }
60373  return pExpr->affinity;
60374}
60375
60376/*
60377** Set the collating sequence for expression pExpr to be the collating
60378** sequence named by pToken.   Return a pointer to the revised expression.
60379** The collating sequence is marked as "explicit" using the EP_ExpCollate
60380** flag.  An explicit collating sequence will override implicit
60381** collating sequences.
60382*/
60383SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
60384  char *zColl = 0;            /* Dequoted name of collation sequence */
60385  CollSeq *pColl;
60386  sqlite3 *db = pParse->db;
60387  zColl = sqlite3NameFromToken(db, pCollName);
60388  if( pExpr && zColl ){
60389    pColl = sqlite3LocateCollSeq(pParse, zColl);
60390    if( pColl ){
60391      pExpr->pColl = pColl;
60392      pExpr->flags |= EP_ExpCollate;
60393    }
60394  }
60395  sqlite3DbFree(db, zColl);
60396  return pExpr;
60397}
60398
60399/*
60400** Return the default collation sequence for the expression pExpr. If
60401** there is no default collation type, return 0.
60402*/
60403SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
60404  CollSeq *pColl = 0;
60405  Expr *p = pExpr;
60406  while( ALWAYS(p) ){
60407    int op;
60408    pColl = p->pColl;
60409    if( pColl ) break;
60410    op = p->op;
60411    if( p->pTab!=0 && (
60412        op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
60413    )){
60414      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
60415      ** a TK_COLUMN but was previously evaluated and cached in a register */
60416      const char *zColl;
60417      int j = p->iColumn;
60418      if( j>=0 ){
60419        sqlite3 *db = pParse->db;
60420        zColl = p->pTab->aCol[j].zColl;
60421        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
60422        pExpr->pColl = pColl;
60423      }
60424      break;
60425    }
60426    if( op!=TK_CAST && op!=TK_UPLUS ){
60427      break;
60428    }
60429    p = p->pLeft;
60430  }
60431  if( sqlite3CheckCollSeq(pParse, pColl) ){
60432    pColl = 0;
60433  }
60434  return pColl;
60435}
60436
60437/*
60438** pExpr is an operand of a comparison operator.  aff2 is the
60439** type affinity of the other operand.  This routine returns the
60440** type affinity that should be used for the comparison operator.
60441*/
60442SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
60443  char aff1 = sqlite3ExprAffinity(pExpr);
60444  if( aff1 && aff2 ){
60445    /* Both sides of the comparison are columns. If one has numeric
60446    ** affinity, use that. Otherwise use no affinity.
60447    */
60448    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
60449      return SQLITE_AFF_NUMERIC;
60450    }else{
60451      return SQLITE_AFF_NONE;
60452    }
60453  }else if( !aff1 && !aff2 ){
60454    /* Neither side of the comparison is a column.  Compare the
60455    ** results directly.
60456    */
60457    return SQLITE_AFF_NONE;
60458  }else{
60459    /* One side is a column, the other is not. Use the columns affinity. */
60460    assert( aff1==0 || aff2==0 );
60461    return (aff1 + aff2);
60462  }
60463}
60464
60465/*
60466** pExpr is a comparison operator.  Return the type affinity that should
60467** be applied to both operands prior to doing the comparison.
60468*/
60469static char comparisonAffinity(Expr *pExpr){
60470  char aff;
60471  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
60472          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
60473          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
60474  assert( pExpr->pLeft );
60475  aff = sqlite3ExprAffinity(pExpr->pLeft);
60476  if( pExpr->pRight ){
60477    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
60478  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
60479    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
60480  }else if( !aff ){
60481    aff = SQLITE_AFF_NONE;
60482  }
60483  return aff;
60484}
60485
60486/*
60487** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
60488** idx_affinity is the affinity of an indexed column. Return true
60489** if the index with affinity idx_affinity may be used to implement
60490** the comparison in pExpr.
60491*/
60492SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
60493  char aff = comparisonAffinity(pExpr);
60494  switch( aff ){
60495    case SQLITE_AFF_NONE:
60496      return 1;
60497    case SQLITE_AFF_TEXT:
60498      return idx_affinity==SQLITE_AFF_TEXT;
60499    default:
60500      return sqlite3IsNumericAffinity(idx_affinity);
60501  }
60502}
60503
60504/*
60505** Return the P5 value that should be used for a binary comparison
60506** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
60507*/
60508static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
60509  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
60510  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
60511  return aff;
60512}
60513
60514/*
60515** Return a pointer to the collation sequence that should be used by
60516** a binary comparison operator comparing pLeft and pRight.
60517**
60518** If the left hand expression has a collating sequence type, then it is
60519** used. Otherwise the collation sequence for the right hand expression
60520** is used, or the default (BINARY) if neither expression has a collating
60521** type.
60522**
60523** Argument pRight (but not pLeft) may be a null pointer. In this case,
60524** it is not considered.
60525*/
60526SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
60527  Parse *pParse,
60528  Expr *pLeft,
60529  Expr *pRight
60530){
60531  CollSeq *pColl;
60532  assert( pLeft );
60533  if( pLeft->flags & EP_ExpCollate ){
60534    assert( pLeft->pColl );
60535    pColl = pLeft->pColl;
60536  }else if( pRight && pRight->flags & EP_ExpCollate ){
60537    assert( pRight->pColl );
60538    pColl = pRight->pColl;
60539  }else{
60540    pColl = sqlite3ExprCollSeq(pParse, pLeft);
60541    if( !pColl ){
60542      pColl = sqlite3ExprCollSeq(pParse, pRight);
60543    }
60544  }
60545  return pColl;
60546}
60547
60548/*
60549** Generate code for a comparison operator.
60550*/
60551static int codeCompare(
60552  Parse *pParse,    /* The parsing (and code generating) context */
60553  Expr *pLeft,      /* The left operand */
60554  Expr *pRight,     /* The right operand */
60555  int opcode,       /* The comparison opcode */
60556  int in1, int in2, /* Register holding operands */
60557  int dest,         /* Jump here if true.  */
60558  int jumpIfNull    /* If true, jump if either operand is NULL */
60559){
60560  int p5;
60561  int addr;
60562  CollSeq *p4;
60563
60564  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
60565  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
60566  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
60567                           (void*)p4, P4_COLLSEQ);
60568  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
60569  if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
60570    sqlite3ExprCacheAffinityChange(pParse, in1, 1);
60571    sqlite3ExprCacheAffinityChange(pParse, in2, 1);
60572  }
60573  return addr;
60574}
60575
60576#if SQLITE_MAX_EXPR_DEPTH>0
60577/*
60578** Check that argument nHeight is less than or equal to the maximum
60579** expression depth allowed. If it is not, leave an error message in
60580** pParse.
60581*/
60582SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
60583  int rc = SQLITE_OK;
60584  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
60585  if( nHeight>mxHeight ){
60586    sqlite3ErrorMsg(pParse,
60587       "Expression tree is too large (maximum depth %d)", mxHeight
60588    );
60589    rc = SQLITE_ERROR;
60590  }
60591  return rc;
60592}
60593
60594/* The following three functions, heightOfExpr(), heightOfExprList()
60595** and heightOfSelect(), are used to determine the maximum height
60596** of any expression tree referenced by the structure passed as the
60597** first argument.
60598**
60599** If this maximum height is greater than the current value pointed
60600** to by pnHeight, the second parameter, then set *pnHeight to that
60601** value.
60602*/
60603static void heightOfExpr(Expr *p, int *pnHeight){
60604  if( p ){
60605    if( p->nHeight>*pnHeight ){
60606      *pnHeight = p->nHeight;
60607    }
60608  }
60609}
60610static void heightOfExprList(ExprList *p, int *pnHeight){
60611  if( p ){
60612    int i;
60613    for(i=0; i<p->nExpr; i++){
60614      heightOfExpr(p->a[i].pExpr, pnHeight);
60615    }
60616  }
60617}
60618static void heightOfSelect(Select *p, int *pnHeight){
60619  if( p ){
60620    heightOfExpr(p->pWhere, pnHeight);
60621    heightOfExpr(p->pHaving, pnHeight);
60622    heightOfExpr(p->pLimit, pnHeight);
60623    heightOfExpr(p->pOffset, pnHeight);
60624    heightOfExprList(p->pEList, pnHeight);
60625    heightOfExprList(p->pGroupBy, pnHeight);
60626    heightOfExprList(p->pOrderBy, pnHeight);
60627    heightOfSelect(p->pPrior, pnHeight);
60628  }
60629}
60630
60631/*
60632** Set the Expr.nHeight variable in the structure passed as an
60633** argument. An expression with no children, Expr.pList or
60634** Expr.pSelect member has a height of 1. Any other expression
60635** has a height equal to the maximum height of any other
60636** referenced Expr plus one.
60637*/
60638static void exprSetHeight(Expr *p){
60639  int nHeight = 0;
60640  heightOfExpr(p->pLeft, &nHeight);
60641  heightOfExpr(p->pRight, &nHeight);
60642  if( ExprHasProperty(p, EP_xIsSelect) ){
60643    heightOfSelect(p->x.pSelect, &nHeight);
60644  }else{
60645    heightOfExprList(p->x.pList, &nHeight);
60646  }
60647  p->nHeight = nHeight + 1;
60648}
60649
60650/*
60651** Set the Expr.nHeight variable using the exprSetHeight() function. If
60652** the height is greater than the maximum allowed expression depth,
60653** leave an error in pParse.
60654*/
60655SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
60656  exprSetHeight(p);
60657  sqlite3ExprCheckHeight(pParse, p->nHeight);
60658}
60659
60660/*
60661** Return the maximum height of any expression tree referenced
60662** by the select statement passed as an argument.
60663*/
60664SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
60665  int nHeight = 0;
60666  heightOfSelect(p, &nHeight);
60667  return nHeight;
60668}
60669#else
60670  #define exprSetHeight(y)
60671#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
60672
60673/*
60674** This routine is the core allocator for Expr nodes.
60675**
60676** Construct a new expression node and return a pointer to it.  Memory
60677** for this node and for the pToken argument is a single allocation
60678** obtained from sqlite3DbMalloc().  The calling function
60679** is responsible for making sure the node eventually gets freed.
60680**
60681** If dequote is true, then the token (if it exists) is dequoted.
60682** If dequote is false, no dequoting is performance.  The deQuote
60683** parameter is ignored if pToken is NULL or if the token does not
60684** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
60685** then the EP_DblQuoted flag is set on the expression node.
60686**
60687** Special case:  If op==TK_INTEGER and pToken points to a string that
60688** can be translated into a 32-bit integer, then the token is not
60689** stored in u.zToken.  Instead, the integer values is written
60690** into u.iValue and the EP_IntValue flag is set.  No extra storage
60691** is allocated to hold the integer text and the dequote flag is ignored.
60692*/
60693SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
60694  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
60695  int op,                 /* Expression opcode */
60696  const Token *pToken,    /* Token argument.  Might be NULL */
60697  int dequote             /* True to dequote */
60698){
60699  Expr *pNew;
60700  int nExtra = 0;
60701  int iValue = 0;
60702
60703  if( pToken ){
60704    if( op!=TK_INTEGER || pToken->z==0
60705          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
60706      nExtra = pToken->n+1;
60707    }
60708  }
60709  pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
60710  if( pNew ){
60711    pNew->op = (u8)op;
60712    pNew->iAgg = -1;
60713    if( pToken ){
60714      if( nExtra==0 ){
60715        pNew->flags |= EP_IntValue;
60716        pNew->u.iValue = iValue;
60717      }else{
60718        int c;
60719        pNew->u.zToken = (char*)&pNew[1];
60720        memcpy(pNew->u.zToken, pToken->z, pToken->n);
60721        pNew->u.zToken[pToken->n] = 0;
60722        if( dequote && nExtra>=3
60723             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
60724          sqlite3Dequote(pNew->u.zToken);
60725          if( c=='"' ) pNew->flags |= EP_DblQuoted;
60726        }
60727      }
60728    }
60729#if SQLITE_MAX_EXPR_DEPTH>0
60730    pNew->nHeight = 1;
60731#endif
60732  }
60733  return pNew;
60734}
60735
60736/*
60737** Allocate a new expression node from a zero-terminated token that has
60738** already been dequoted.
60739*/
60740SQLITE_PRIVATE Expr *sqlite3Expr(
60741  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
60742  int op,                 /* Expression opcode */
60743  const char *zToken      /* Token argument.  Might be NULL */
60744){
60745  Token x;
60746  x.z = zToken;
60747  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
60748  return sqlite3ExprAlloc(db, op, &x, 0);
60749}
60750
60751/*
60752** Attach subtrees pLeft and pRight to the Expr node pRoot.
60753**
60754** If pRoot==NULL that means that a memory allocation error has occurred.
60755** In that case, delete the subtrees pLeft and pRight.
60756*/
60757SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
60758  sqlite3 *db,
60759  Expr *pRoot,
60760  Expr *pLeft,
60761  Expr *pRight
60762){
60763  if( pRoot==0 ){
60764    assert( db->mallocFailed );
60765    sqlite3ExprDelete(db, pLeft);
60766    sqlite3ExprDelete(db, pRight);
60767  }else{
60768    if( pRight ){
60769      pRoot->pRight = pRight;
60770      if( pRight->flags & EP_ExpCollate ){
60771        pRoot->flags |= EP_ExpCollate;
60772        pRoot->pColl = pRight->pColl;
60773      }
60774    }
60775    if( pLeft ){
60776      pRoot->pLeft = pLeft;
60777      if( pLeft->flags & EP_ExpCollate ){
60778        pRoot->flags |= EP_ExpCollate;
60779        pRoot->pColl = pLeft->pColl;
60780      }
60781    }
60782    exprSetHeight(pRoot);
60783  }
60784}
60785
60786/*
60787** Allocate a Expr node which joins as many as two subtrees.
60788**
60789** One or both of the subtrees can be NULL.  Return a pointer to the new
60790** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
60791** free the subtrees and return NULL.
60792*/
60793SQLITE_PRIVATE Expr *sqlite3PExpr(
60794  Parse *pParse,          /* Parsing context */
60795  int op,                 /* Expression opcode */
60796  Expr *pLeft,            /* Left operand */
60797  Expr *pRight,           /* Right operand */
60798  const Token *pToken     /* Argument token */
60799){
60800  Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
60801  sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
60802  return p;
60803}
60804
60805/*
60806** Join two expressions using an AND operator.  If either expression is
60807** NULL, then just return the other expression.
60808*/
60809SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
60810  if( pLeft==0 ){
60811    return pRight;
60812  }else if( pRight==0 ){
60813    return pLeft;
60814  }else{
60815    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
60816    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
60817    return pNew;
60818  }
60819}
60820
60821/*
60822** Construct a new expression node for a function with multiple
60823** arguments.
60824*/
60825SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
60826  Expr *pNew;
60827  sqlite3 *db = pParse->db;
60828  assert( pToken );
60829  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
60830  if( pNew==0 ){
60831    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
60832    return 0;
60833  }
60834  pNew->x.pList = pList;
60835  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
60836  sqlite3ExprSetHeight(pParse, pNew);
60837  return pNew;
60838}
60839
60840/*
60841** Assign a variable number to an expression that encodes a wildcard
60842** in the original SQL statement.
60843**
60844** Wildcards consisting of a single "?" are assigned the next sequential
60845** variable number.
60846**
60847** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
60848** sure "nnn" is not too be to avoid a denial of service attack when
60849** the SQL statement comes from an external source.
60850**
60851** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
60852** as the previous instance of the same wildcard.  Or if this is the first
60853** instance of the wildcard, the next sequenial variable number is
60854** assigned.
60855*/
60856SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
60857  sqlite3 *db = pParse->db;
60858  const char *z;
60859
60860  if( pExpr==0 ) return;
60861  assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
60862  z = pExpr->u.zToken;
60863  assert( z!=0 );
60864  assert( z[0]!=0 );
60865  if( z[1]==0 ){
60866    /* Wildcard of the form "?".  Assign the next variable number */
60867    assert( z[0]=='?' );
60868    pExpr->iColumn = (ynVar)(++pParse->nVar);
60869  }else if( z[0]=='?' ){
60870    /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
60871    ** use it as the variable number */
60872    int i = atoi((char*)&z[1]);
60873    pExpr->iColumn = (ynVar)i;
60874    testcase( i==0 );
60875    testcase( i==1 );
60876    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
60877    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
60878    if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
60879      sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
60880          db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
60881    }
60882    if( i>pParse->nVar ){
60883      pParse->nVar = i;
60884    }
60885  }else{
60886    /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
60887    ** number as the prior appearance of the same name, or if the name
60888    ** has never appeared before, reuse the same variable number
60889    */
60890    int i;
60891    u32 n;
60892    n = sqlite3Strlen30(z);
60893    for(i=0; i<pParse->nVarExpr; i++){
60894      Expr *pE = pParse->apVarExpr[i];
60895      assert( pE!=0 );
60896      if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
60897        pExpr->iColumn = pE->iColumn;
60898        break;
60899      }
60900    }
60901    if( i>=pParse->nVarExpr ){
60902      pExpr->iColumn = (ynVar)(++pParse->nVar);
60903      if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
60904        pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
60905        pParse->apVarExpr =
60906            sqlite3DbReallocOrFree(
60907              db,
60908              pParse->apVarExpr,
60909              pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
60910            );
60911      }
60912      if( !db->mallocFailed ){
60913        assert( pParse->apVarExpr!=0 );
60914        pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
60915      }
60916    }
60917  }
60918  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
60919    sqlite3ErrorMsg(pParse, "too many SQL variables");
60920  }
60921}
60922
60923/*
60924** Recursively delete an expression tree.
60925*/
60926SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
60927  if( p==0 ) return;
60928  if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
60929    sqlite3ExprDelete(db, p->pLeft);
60930    sqlite3ExprDelete(db, p->pRight);
60931    if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
60932      sqlite3DbFree(db, p->u.zToken);
60933    }
60934    if( ExprHasProperty(p, EP_xIsSelect) ){
60935      sqlite3SelectDelete(db, p->x.pSelect);
60936    }else{
60937      sqlite3ExprListDelete(db, p->x.pList);
60938    }
60939  }
60940  if( !ExprHasProperty(p, EP_Static) ){
60941    sqlite3DbFree(db, p);
60942  }
60943}
60944
60945/*
60946** Return the number of bytes allocated for the expression structure
60947** passed as the first argument. This is always one of EXPR_FULLSIZE,
60948** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
60949*/
60950static int exprStructSize(Expr *p){
60951  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
60952  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
60953  return EXPR_FULLSIZE;
60954}
60955
60956/*
60957** The dupedExpr*Size() routines each return the number of bytes required
60958** to store a copy of an expression or expression tree.  They differ in
60959** how much of the tree is measured.
60960**
60961**     dupedExprStructSize()     Size of only the Expr structure
60962**     dupedExprNodeSize()       Size of Expr + space for token
60963**     dupedExprSize()           Expr + token + subtree components
60964**
60965***************************************************************************
60966**
60967** The dupedExprStructSize() function returns two values OR-ed together:
60968** (1) the space required for a copy of the Expr structure only and
60969** (2) the EP_xxx flags that indicate what the structure size should be.
60970** The return values is always one of:
60971**
60972**      EXPR_FULLSIZE
60973**      EXPR_REDUCEDSIZE   | EP_Reduced
60974**      EXPR_TOKENONLYSIZE | EP_TokenOnly
60975**
60976** The size of the structure can be found by masking the return value
60977** of this routine with 0xfff.  The flags can be found by masking the
60978** return value with EP_Reduced|EP_TokenOnly.
60979**
60980** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
60981** (unreduced) Expr objects as they or originally constructed by the parser.
60982** During expression analysis, extra information is computed and moved into
60983** later parts of teh Expr object and that extra information might get chopped
60984** off if the expression is reduced.  Note also that it does not work to
60985** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
60986** to reduce a pristine expression tree from the parser.  The implementation
60987** of dupedExprStructSize() contain multiple assert() statements that attempt
60988** to enforce this constraint.
60989*/
60990static int dupedExprStructSize(Expr *p, int flags){
60991  int nSize;
60992  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
60993  if( 0==(flags&EXPRDUP_REDUCE) ){
60994    nSize = EXPR_FULLSIZE;
60995  }else{
60996    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
60997    assert( !ExprHasProperty(p, EP_FromJoin) );
60998    assert( (p->flags2 & EP2_MallocedToken)==0 );
60999    assert( (p->flags2 & EP2_Irreducible)==0 );
61000    if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
61001      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
61002    }else{
61003      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
61004    }
61005  }
61006  return nSize;
61007}
61008
61009/*
61010** This function returns the space in bytes required to store the copy
61011** of the Expr structure and a copy of the Expr.u.zToken string (if that
61012** string is defined.)
61013*/
61014static int dupedExprNodeSize(Expr *p, int flags){
61015  int nByte = dupedExprStructSize(p, flags) & 0xfff;
61016  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
61017    nByte += sqlite3Strlen30(p->u.zToken)+1;
61018  }
61019  return ROUND8(nByte);
61020}
61021
61022/*
61023** Return the number of bytes required to create a duplicate of the
61024** expression passed as the first argument. The second argument is a
61025** mask containing EXPRDUP_XXX flags.
61026**
61027** The value returned includes space to create a copy of the Expr struct
61028** itself and the buffer referred to by Expr.u.zToken, if any.
61029**
61030** If the EXPRDUP_REDUCE flag is set, then the return value includes
61031** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
61032** and Expr.pRight variables (but not for any structures pointed to or
61033** descended from the Expr.x.pList or Expr.x.pSelect variables).
61034*/
61035static int dupedExprSize(Expr *p, int flags){
61036  int nByte = 0;
61037  if( p ){
61038    nByte = dupedExprNodeSize(p, flags);
61039    if( flags&EXPRDUP_REDUCE ){
61040      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
61041    }
61042  }
61043  return nByte;
61044}
61045
61046/*
61047** This function is similar to sqlite3ExprDup(), except that if pzBuffer
61048** is not NULL then *pzBuffer is assumed to point to a buffer large enough
61049** to store the copy of expression p, the copies of p->u.zToken
61050** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
61051** if any. Before returning, *pzBuffer is set to the first byte passed the
61052** portion of the buffer copied into by this function.
61053*/
61054static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
61055  Expr *pNew = 0;                      /* Value to return */
61056  if( p ){
61057    const int isReduced = (flags&EXPRDUP_REDUCE);
61058    u8 *zAlloc;
61059    u32 staticFlag = 0;
61060
61061    assert( pzBuffer==0 || isReduced );
61062
61063    /* Figure out where to write the new Expr structure. */
61064    if( pzBuffer ){
61065      zAlloc = *pzBuffer;
61066      staticFlag = EP_Static;
61067    }else{
61068      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
61069    }
61070    pNew = (Expr *)zAlloc;
61071
61072    if( pNew ){
61073      /* Set nNewSize to the size allocated for the structure pointed to
61074      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
61075      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
61076      ** by the copy of the p->u.zToken string (if any).
61077      */
61078      const unsigned nStructSize = dupedExprStructSize(p, flags);
61079      const int nNewSize = nStructSize & 0xfff;
61080      int nToken;
61081      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
61082        nToken = sqlite3Strlen30(p->u.zToken) + 1;
61083      }else{
61084        nToken = 0;
61085      }
61086      if( isReduced ){
61087        assert( ExprHasProperty(p, EP_Reduced)==0 );
61088        memcpy(zAlloc, p, nNewSize);
61089      }else{
61090        int nSize = exprStructSize(p);
61091        memcpy(zAlloc, p, nSize);
61092        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
61093      }
61094
61095      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
61096      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
61097      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
61098      pNew->flags |= staticFlag;
61099
61100      /* Copy the p->u.zToken string, if any. */
61101      if( nToken ){
61102        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
61103        memcpy(zToken, p->u.zToken, nToken);
61104      }
61105
61106      if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
61107        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
61108        if( ExprHasProperty(p, EP_xIsSelect) ){
61109          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
61110        }else{
61111          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
61112        }
61113      }
61114
61115      /* Fill in pNew->pLeft and pNew->pRight. */
61116      if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
61117        zAlloc += dupedExprNodeSize(p, flags);
61118        if( ExprHasProperty(pNew, EP_Reduced) ){
61119          pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
61120          pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
61121        }
61122        if( pzBuffer ){
61123          *pzBuffer = zAlloc;
61124        }
61125      }else{
61126        pNew->flags2 = 0;
61127        if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
61128          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
61129          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
61130        }
61131      }
61132
61133    }
61134  }
61135  return pNew;
61136}
61137
61138/*
61139** The following group of routines make deep copies of expressions,
61140** expression lists, ID lists, and select statements.  The copies can
61141** be deleted (by being passed to their respective ...Delete() routines)
61142** without effecting the originals.
61143**
61144** The expression list, ID, and source lists return by sqlite3ExprListDup(),
61145** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
61146** by subsequent calls to sqlite*ListAppend() routines.
61147**
61148** Any tables that the SrcList might point to are not duplicated.
61149**
61150** The flags parameter contains a combination of the EXPRDUP_XXX flags.
61151** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
61152** truncated version of the usual Expr structure that will be stored as
61153** part of the in-memory representation of the database schema.
61154*/
61155SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
61156  return exprDup(db, p, flags, 0);
61157}
61158SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
61159  ExprList *pNew;
61160  struct ExprList_item *pItem, *pOldItem;
61161  int i;
61162  if( p==0 ) return 0;
61163  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
61164  if( pNew==0 ) return 0;
61165  pNew->iECursor = 0;
61166  pNew->nExpr = pNew->nAlloc = p->nExpr;
61167  pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
61168  if( pItem==0 ){
61169    sqlite3DbFree(db, pNew);
61170    return 0;
61171  }
61172  pOldItem = p->a;
61173  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
61174    Expr *pOldExpr = pOldItem->pExpr;
61175    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
61176    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
61177    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
61178    pItem->sortOrder = pOldItem->sortOrder;
61179    pItem->done = 0;
61180    pItem->iCol = pOldItem->iCol;
61181    pItem->iAlias = pOldItem->iAlias;
61182  }
61183  return pNew;
61184}
61185
61186/*
61187** If cursors, triggers, views and subqueries are all omitted from
61188** the build, then none of the following routines, except for
61189** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
61190** called with a NULL argument.
61191*/
61192#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
61193 || !defined(SQLITE_OMIT_SUBQUERY)
61194SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
61195  SrcList *pNew;
61196  int i;
61197  int nByte;
61198  if( p==0 ) return 0;
61199  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
61200  pNew = sqlite3DbMallocRaw(db, nByte );
61201  if( pNew==0 ) return 0;
61202  pNew->nSrc = pNew->nAlloc = p->nSrc;
61203  for(i=0; i<p->nSrc; i++){
61204    struct SrcList_item *pNewItem = &pNew->a[i];
61205    struct SrcList_item *pOldItem = &p->a[i];
61206    Table *pTab;
61207    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
61208    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
61209    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
61210    pNewItem->jointype = pOldItem->jointype;
61211    pNewItem->iCursor = pOldItem->iCursor;
61212    pNewItem->isPopulated = pOldItem->isPopulated;
61213    pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
61214    pNewItem->notIndexed = pOldItem->notIndexed;
61215    pNewItem->pIndex = pOldItem->pIndex;
61216    pTab = pNewItem->pTab = pOldItem->pTab;
61217    if( pTab ){
61218      pTab->nRef++;
61219    }
61220    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
61221    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
61222    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
61223    pNewItem->colUsed = pOldItem->colUsed;
61224  }
61225  return pNew;
61226}
61227SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
61228  IdList *pNew;
61229  int i;
61230  if( p==0 ) return 0;
61231  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
61232  if( pNew==0 ) return 0;
61233  pNew->nId = pNew->nAlloc = p->nId;
61234  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
61235  if( pNew->a==0 ){
61236    sqlite3DbFree(db, pNew);
61237    return 0;
61238  }
61239  for(i=0; i<p->nId; i++){
61240    struct IdList_item *pNewItem = &pNew->a[i];
61241    struct IdList_item *pOldItem = &p->a[i];
61242    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
61243    pNewItem->idx = pOldItem->idx;
61244  }
61245  return pNew;
61246}
61247SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
61248  Select *pNew;
61249  if( p==0 ) return 0;
61250  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
61251  if( pNew==0 ) return 0;
61252  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
61253  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
61254  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
61255  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
61256  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
61257  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
61258  pNew->op = p->op;
61259  pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
61260  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
61261  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
61262  pNew->iLimit = 0;
61263  pNew->iOffset = 0;
61264  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
61265  pNew->pRightmost = 0;
61266  pNew->addrOpenEphm[0] = -1;
61267  pNew->addrOpenEphm[1] = -1;
61268  pNew->addrOpenEphm[2] = -1;
61269  return pNew;
61270}
61271#else
61272SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
61273  assert( p==0 );
61274  return 0;
61275}
61276#endif
61277
61278
61279/*
61280** Add a new element to the end of an expression list.  If pList is
61281** initially NULL, then create a new expression list.
61282**
61283** If a memory allocation error occurs, the entire list is freed and
61284** NULL is returned.  If non-NULL is returned, then it is guaranteed
61285** that the new entry was successfully appended.
61286*/
61287SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
61288  Parse *pParse,          /* Parsing context */
61289  ExprList *pList,        /* List to which to append. Might be NULL */
61290  Expr *pExpr             /* Expression to be appended. Might be NULL */
61291){
61292  sqlite3 *db = pParse->db;
61293  if( pList==0 ){
61294    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
61295    if( pList==0 ){
61296      goto no_mem;
61297    }
61298    assert( pList->nAlloc==0 );
61299  }
61300  if( pList->nAlloc<=pList->nExpr ){
61301    struct ExprList_item *a;
61302    int n = pList->nAlloc*2 + 4;
61303    a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
61304    if( a==0 ){
61305      goto no_mem;
61306    }
61307    pList->a = a;
61308    pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
61309  }
61310  assert( pList->a!=0 );
61311  if( 1 ){
61312    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
61313    memset(pItem, 0, sizeof(*pItem));
61314    pItem->pExpr = pExpr;
61315  }
61316  return pList;
61317
61318no_mem:
61319  /* Avoid leaking memory if malloc has failed. */
61320  sqlite3ExprDelete(db, pExpr);
61321  sqlite3ExprListDelete(db, pList);
61322  return 0;
61323}
61324
61325/*
61326** Set the ExprList.a[].zName element of the most recently added item
61327** on the expression list.
61328**
61329** pList might be NULL following an OOM error.  But pName should never be
61330** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
61331** is set.
61332*/
61333SQLITE_PRIVATE void sqlite3ExprListSetName(
61334  Parse *pParse,          /* Parsing context */
61335  ExprList *pList,        /* List to which to add the span. */
61336  Token *pName,           /* Name to be added */
61337  int dequote             /* True to cause the name to be dequoted */
61338){
61339  assert( pList!=0 || pParse->db->mallocFailed!=0 );
61340  if( pList ){
61341    struct ExprList_item *pItem;
61342    assert( pList->nExpr>0 );
61343    pItem = &pList->a[pList->nExpr-1];
61344    assert( pItem->zName==0 );
61345    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
61346    if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
61347  }
61348}
61349
61350/*
61351** Set the ExprList.a[].zSpan element of the most recently added item
61352** on the expression list.
61353**
61354** pList might be NULL following an OOM error.  But pSpan should never be
61355** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
61356** is set.
61357*/
61358SQLITE_PRIVATE void sqlite3ExprListSetSpan(
61359  Parse *pParse,          /* Parsing context */
61360  ExprList *pList,        /* List to which to add the span. */
61361  ExprSpan *pSpan         /* The span to be added */
61362){
61363  sqlite3 *db = pParse->db;
61364  assert( pList!=0 || db->mallocFailed!=0 );
61365  if( pList ){
61366    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
61367    assert( pList->nExpr>0 );
61368    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
61369    sqlite3DbFree(db, pItem->zSpan);
61370    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
61371                                    (int)(pSpan->zEnd - pSpan->zStart));
61372  }
61373}
61374
61375/*
61376** If the expression list pEList contains more than iLimit elements,
61377** leave an error message in pParse.
61378*/
61379SQLITE_PRIVATE void sqlite3ExprListCheckLength(
61380  Parse *pParse,
61381  ExprList *pEList,
61382  const char *zObject
61383){
61384  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
61385  testcase( pEList && pEList->nExpr==mx );
61386  testcase( pEList && pEList->nExpr==mx+1 );
61387  if( pEList && pEList->nExpr>mx ){
61388    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
61389  }
61390}
61391
61392/*
61393** Delete an entire expression list.
61394*/
61395SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
61396  int i;
61397  struct ExprList_item *pItem;
61398  if( pList==0 ) return;
61399  assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
61400  assert( pList->nExpr<=pList->nAlloc );
61401  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
61402    sqlite3ExprDelete(db, pItem->pExpr);
61403    sqlite3DbFree(db, pItem->zName);
61404    sqlite3DbFree(db, pItem->zSpan);
61405  }
61406  sqlite3DbFree(db, pList->a);
61407  sqlite3DbFree(db, pList);
61408}
61409
61410/*
61411** These routines are Walker callbacks.  Walker.u.pi is a pointer
61412** to an integer.  These routines are checking an expression to see
61413** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
61414** not constant.
61415**
61416** These callback routines are used to implement the following:
61417**
61418**     sqlite3ExprIsConstant()
61419**     sqlite3ExprIsConstantNotJoin()
61420**     sqlite3ExprIsConstantOrFunction()
61421**
61422*/
61423static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
61424
61425  /* If pWalker->u.i is 3 then any term of the expression that comes from
61426  ** the ON or USING clauses of a join disqualifies the expression
61427  ** from being considered constant. */
61428  if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
61429    pWalker->u.i = 0;
61430    return WRC_Abort;
61431  }
61432
61433  switch( pExpr->op ){
61434    /* Consider functions to be constant if all their arguments are constant
61435    ** and pWalker->u.i==2 */
61436    case TK_FUNCTION:
61437      if( pWalker->u.i==2 ) return 0;
61438      /* Fall through */
61439    case TK_ID:
61440    case TK_COLUMN:
61441    case TK_AGG_FUNCTION:
61442    case TK_AGG_COLUMN:
61443      testcase( pExpr->op==TK_ID );
61444      testcase( pExpr->op==TK_COLUMN );
61445      testcase( pExpr->op==TK_AGG_FUNCTION );
61446      testcase( pExpr->op==TK_AGG_COLUMN );
61447      pWalker->u.i = 0;
61448      return WRC_Abort;
61449    default:
61450      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
61451      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
61452      return WRC_Continue;
61453  }
61454}
61455static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
61456  UNUSED_PARAMETER(NotUsed);
61457  pWalker->u.i = 0;
61458  return WRC_Abort;
61459}
61460static int exprIsConst(Expr *p, int initFlag){
61461  Walker w;
61462  w.u.i = initFlag;
61463  w.xExprCallback = exprNodeIsConstant;
61464  w.xSelectCallback = selectNodeIsConstant;
61465  sqlite3WalkExpr(&w, p);
61466  return w.u.i;
61467}
61468
61469/*
61470** Walk an expression tree.  Return 1 if the expression is constant
61471** and 0 if it involves variables or function calls.
61472**
61473** For the purposes of this function, a double-quoted string (ex: "abc")
61474** is considered a variable but a single-quoted string (ex: 'abc') is
61475** a constant.
61476*/
61477SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
61478  return exprIsConst(p, 1);
61479}
61480
61481/*
61482** Walk an expression tree.  Return 1 if the expression is constant
61483** that does no originate from the ON or USING clauses of a join.
61484** Return 0 if it involves variables or function calls or terms from
61485** an ON or USING clause.
61486*/
61487SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
61488  return exprIsConst(p, 3);
61489}
61490
61491/*
61492** Walk an expression tree.  Return 1 if the expression is constant
61493** or a function call with constant arguments.  Return and 0 if there
61494** are any variables.
61495**
61496** For the purposes of this function, a double-quoted string (ex: "abc")
61497** is considered a variable but a single-quoted string (ex: 'abc') is
61498** a constant.
61499*/
61500SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
61501  return exprIsConst(p, 2);
61502}
61503
61504/*
61505** If the expression p codes a constant integer that is small enough
61506** to fit in a 32-bit integer, return 1 and put the value of the integer
61507** in *pValue.  If the expression is not an integer or if it is too big
61508** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
61509*/
61510SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
61511  int rc = 0;
61512  if( p->flags & EP_IntValue ){
61513    *pValue = p->u.iValue;
61514    return 1;
61515  }
61516  switch( p->op ){
61517    case TK_INTEGER: {
61518      rc = sqlite3GetInt32(p->u.zToken, pValue);
61519      assert( rc==0 );
61520      break;
61521    }
61522    case TK_UPLUS: {
61523      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
61524      break;
61525    }
61526    case TK_UMINUS: {
61527      int v;
61528      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
61529        *pValue = -v;
61530        rc = 1;
61531      }
61532      break;
61533    }
61534    default: break;
61535  }
61536  if( rc ){
61537    assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
61538               || (p->flags2 & EP2_MallocedToken)==0 );
61539    p->op = TK_INTEGER;
61540    p->flags |= EP_IntValue;
61541    p->u.iValue = *pValue;
61542  }
61543  return rc;
61544}
61545
61546/*
61547** Return FALSE if there is no chance that the expression can be NULL.
61548**
61549** If the expression might be NULL or if the expression is too complex
61550** to tell return TRUE.
61551**
61552** This routine is used as an optimization, to skip OP_IsNull opcodes
61553** when we know that a value cannot be NULL.  Hence, a false positive
61554** (returning TRUE when in fact the expression can never be NULL) might
61555** be a small performance hit but is otherwise harmless.  On the other
61556** hand, a false negative (returning FALSE when the result could be NULL)
61557** will likely result in an incorrect answer.  So when in doubt, return
61558** TRUE.
61559*/
61560SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
61561  u8 op;
61562  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
61563  op = p->op;
61564  if( op==TK_REGISTER ) op = p->op2;
61565  switch( op ){
61566    case TK_INTEGER:
61567    case TK_STRING:
61568    case TK_FLOAT:
61569    case TK_BLOB:
61570      return 0;
61571    default:
61572      return 1;
61573  }
61574}
61575
61576/*
61577** Generate an OP_IsNull instruction that tests register iReg and jumps
61578** to location iDest if the value in iReg is NULL.  The value in iReg
61579** was computed by pExpr.  If we can look at pExpr at compile-time and
61580** determine that it can never generate a NULL, then the OP_IsNull operation
61581** can be omitted.
61582*/
61583SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
61584  Vdbe *v,            /* The VDBE under construction */
61585  const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
61586  int iReg,           /* Test the value in this register for NULL */
61587  int iDest           /* Jump here if the value is null */
61588){
61589  if( sqlite3ExprCanBeNull(pExpr) ){
61590    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
61591  }
61592}
61593
61594/*
61595** Return TRUE if the given expression is a constant which would be
61596** unchanged by OP_Affinity with the affinity given in the second
61597** argument.
61598**
61599** This routine is used to determine if the OP_Affinity operation
61600** can be omitted.  When in doubt return FALSE.  A false negative
61601** is harmless.  A false positive, however, can result in the wrong
61602** answer.
61603*/
61604SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
61605  u8 op;
61606  if( aff==SQLITE_AFF_NONE ) return 1;
61607  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
61608  op = p->op;
61609  if( op==TK_REGISTER ) op = p->op2;
61610  switch( op ){
61611    case TK_INTEGER: {
61612      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
61613    }
61614    case TK_FLOAT: {
61615      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
61616    }
61617    case TK_STRING: {
61618      return aff==SQLITE_AFF_TEXT;
61619    }
61620    case TK_BLOB: {
61621      return 1;
61622    }
61623    case TK_COLUMN: {
61624      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
61625      return p->iColumn<0
61626          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
61627    }
61628    default: {
61629      return 0;
61630    }
61631  }
61632}
61633
61634/*
61635** Return TRUE if the given string is a row-id column name.
61636*/
61637SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
61638  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
61639  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
61640  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
61641  return 0;
61642}
61643
61644/*
61645** Return true if we are able to the IN operator optimization on a
61646** query of the form
61647**
61648**       x IN (SELECT ...)
61649**
61650** Where the SELECT... clause is as specified by the parameter to this
61651** routine.
61652**
61653** The Select object passed in has already been preprocessed and no
61654** errors have been found.
61655*/
61656#ifndef SQLITE_OMIT_SUBQUERY
61657static int isCandidateForInOpt(Select *p){
61658  SrcList *pSrc;
61659  ExprList *pEList;
61660  Table *pTab;
61661  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
61662  if( p->pPrior ) return 0;              /* Not a compound SELECT */
61663  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
61664    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
61665    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
61666    return 0; /* No DISTINCT keyword and no aggregate functions */
61667  }
61668  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
61669  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
61670  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
61671  if( p->pWhere ) return 0;              /* Has no WHERE clause */
61672  pSrc = p->pSrc;
61673  assert( pSrc!=0 );
61674  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
61675  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
61676  pTab = pSrc->a[0].pTab;
61677  if( NEVER(pTab==0) ) return 0;
61678  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
61679  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
61680  pEList = p->pEList;
61681  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
61682  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
61683  return 1;
61684}
61685#endif /* SQLITE_OMIT_SUBQUERY */
61686
61687/*
61688** This function is used by the implementation of the IN (...) operator.
61689** It's job is to find or create a b-tree structure that may be used
61690** either to test for membership of the (...) set or to iterate through
61691** its members, skipping duplicates.
61692**
61693** The index of the cursor opened on the b-tree (database table, database index
61694** or ephermal table) is stored in pX->iTable before this function returns.
61695** The returned value of this function indicates the b-tree type, as follows:
61696**
61697**   IN_INDEX_ROWID - The cursor was opened on a database table.
61698**   IN_INDEX_INDEX - The cursor was opened on a database index.
61699**   IN_INDEX_EPH -   The cursor was opened on a specially created and
61700**                    populated epheremal table.
61701**
61702** An existing b-tree may only be used if the SELECT is of the simple
61703** form:
61704**
61705**     SELECT <column> FROM <table>
61706**
61707** If the prNotFound parameter is 0, then the b-tree will be used to iterate
61708** through the set members, skipping any duplicates. In this case an
61709** epheremal table must be used unless the selected <column> is guaranteed
61710** to be unique - either because it is an INTEGER PRIMARY KEY or it
61711** has a UNIQUE constraint or UNIQUE index.
61712**
61713** If the prNotFound parameter is not 0, then the b-tree will be used
61714** for fast set membership tests. In this case an epheremal table must
61715** be used unless <column> is an INTEGER PRIMARY KEY or an index can
61716** be found with <column> as its left-most column.
61717**
61718** When the b-tree is being used for membership tests, the calling function
61719** needs to know whether or not the structure contains an SQL NULL
61720** value in order to correctly evaluate expressions like "X IN (Y, Z)".
61721** If there is any chance that the (...) might contain a NULL value at
61722** runtime, then a register is allocated and the register number written
61723** to *prNotFound. If there is no chance that the (...) contains a
61724** NULL value, then *prNotFound is left unchanged.
61725**
61726** If a register is allocated and its location stored in *prNotFound, then
61727** its initial value is NULL.  If the (...) does not remain constant
61728** for the duration of the query (i.e. the SELECT within the (...)
61729** is a correlated subquery) then the value of the allocated register is
61730** reset to NULL each time the subquery is rerun. This allows the
61731** caller to use vdbe code equivalent to the following:
61732**
61733**   if( register==NULL ){
61734**     has_null = <test if data structure contains null>
61735**     register = 1
61736**   }
61737**
61738** in order to avoid running the <test if data structure contains null>
61739** test more often than is necessary.
61740*/
61741#ifndef SQLITE_OMIT_SUBQUERY
61742SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
61743  Select *p;                            /* SELECT to the right of IN operator */
61744  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
61745  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
61746  int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
61747
61748  assert( pX->op==TK_IN );
61749
61750  /* Check to see if an existing table or index can be used to
61751  ** satisfy the query.  This is preferable to generating a new
61752  ** ephemeral table.
61753  */
61754  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
61755  if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
61756    sqlite3 *db = pParse->db;              /* Database connection */
61757    Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
61758    int iCol = pExpr->iColumn;             /* Index of column <column> */
61759    Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
61760    Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
61761    int iDb;                               /* Database idx for pTab */
61762
61763    /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
61764    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
61765    sqlite3CodeVerifySchema(pParse, iDb);
61766    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
61767
61768    /* This function is only called from two places. In both cases the vdbe
61769    ** has already been allocated. So assume sqlite3GetVdbe() is always
61770    ** successful here.
61771    */
61772    assert(v);
61773    if( iCol<0 ){
61774      int iMem = ++pParse->nMem;
61775      int iAddr;
61776
61777      iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
61778      sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
61779
61780      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
61781      eType = IN_INDEX_ROWID;
61782
61783      sqlite3VdbeJumpHere(v, iAddr);
61784    }else{
61785      Index *pIdx;                         /* Iterator variable */
61786
61787      /* The collation sequence used by the comparison. If an index is to
61788      ** be used in place of a temp-table, it must be ordered according
61789      ** to this collation sequence.  */
61790      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
61791
61792      /* Check that the affinity that will be used to perform the
61793      ** comparison is the same as the affinity of the column. If
61794      ** it is not, it is not possible to use any index.
61795      */
61796      char aff = comparisonAffinity(pX);
61797      int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
61798
61799      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
61800        if( (pIdx->aiColumn[0]==iCol)
61801         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
61802         && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
61803        ){
61804          int iMem = ++pParse->nMem;
61805          int iAddr;
61806          char *pKey;
61807
61808          pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
61809          iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
61810          sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
61811
61812          sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
61813                               pKey,P4_KEYINFO_HANDOFF);
61814          VdbeComment((v, "%s", pIdx->zName));
61815          eType = IN_INDEX_INDEX;
61816
61817          sqlite3VdbeJumpHere(v, iAddr);
61818          if( prNotFound && !pTab->aCol[iCol].notNull ){
61819            *prNotFound = ++pParse->nMem;
61820          }
61821        }
61822      }
61823    }
61824  }
61825
61826  if( eType==0 ){
61827    /* Could not found an existing table or index to use as the RHS b-tree.
61828    ** We will have to generate an ephemeral table to do the job.
61829    */
61830    int rMayHaveNull = 0;
61831    eType = IN_INDEX_EPH;
61832    if( prNotFound ){
61833      *prNotFound = rMayHaveNull = ++pParse->nMem;
61834    }else if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
61835      eType = IN_INDEX_ROWID;
61836    }
61837    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
61838  }else{
61839    pX->iTable = iTab;
61840  }
61841  return eType;
61842}
61843#endif
61844
61845/*
61846** Generate code for scalar subqueries used as an expression
61847** and IN operators.  Examples:
61848**
61849**     (SELECT a FROM b)          -- subquery
61850**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
61851**     x IN (4,5,11)              -- IN operator with list on right-hand side
61852**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
61853**
61854** The pExpr parameter describes the expression that contains the IN
61855** operator or subquery.
61856**
61857** If parameter isRowid is non-zero, then expression pExpr is guaranteed
61858** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
61859** to some integer key column of a table B-Tree. In this case, use an
61860** intkey B-Tree to store the set of IN(...) values instead of the usual
61861** (slower) variable length keys B-Tree.
61862**
61863** If rMayHaveNull is non-zero, that means that the operation is an IN
61864** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
61865** Furthermore, the IN is in a WHERE clause and that we really want
61866** to iterate over the RHS of the IN operator in order to quickly locate
61867** all corresponding LHS elements.  All this routine does is initialize
61868** the register given by rMayHaveNull to NULL.  Calling routines will take
61869** care of changing this register value to non-NULL if the RHS is NULL-free.
61870**
61871** If rMayHaveNull is zero, that means that the subquery is being used
61872** for membership testing only.  There is no need to initialize any
61873** registers to indicate the presense or absence of NULLs on the RHS.
61874**
61875** For a SELECT or EXISTS operator, return the register that holds the
61876** result.  For IN operators or if an error occurs, the return value is 0.
61877*/
61878#ifndef SQLITE_OMIT_SUBQUERY
61879SQLITE_PRIVATE int sqlite3CodeSubselect(
61880  Parse *pParse,          /* Parsing context */
61881  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
61882  int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
61883  int isRowid             /* If true, LHS of IN operator is a rowid */
61884){
61885  int testAddr = 0;                       /* One-time test address */
61886  int rReg = 0;                           /* Register storing resulting */
61887  Vdbe *v = sqlite3GetVdbe(pParse);
61888  if( NEVER(v==0) ) return 0;
61889  sqlite3ExprCachePush(pParse);
61890
61891  /* This code must be run in its entirety every time it is encountered
61892  ** if any of the following is true:
61893  **
61894  **    *  The right-hand side is a correlated subquery
61895  **    *  The right-hand side is an expression list containing variables
61896  **    *  We are inside a trigger
61897  **
61898  ** If all of the above are false, then we can run this code just once
61899  ** save the results, and reuse the same result on subsequent invocations.
61900  */
61901  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
61902    int mem = ++pParse->nMem;
61903    sqlite3VdbeAddOp1(v, OP_If, mem);
61904    testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
61905    assert( testAddr>0 || pParse->db->mallocFailed );
61906  }
61907
61908  switch( pExpr->op ){
61909    case TK_IN: {
61910      char affinity;
61911      KeyInfo keyInfo;
61912      int addr;        /* Address of OP_OpenEphemeral instruction */
61913      Expr *pLeft = pExpr->pLeft;
61914
61915      if( rMayHaveNull ){
61916        sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
61917      }
61918
61919      affinity = sqlite3ExprAffinity(pLeft);
61920
61921      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
61922      ** expression it is handled the same way.  An ephemeral table is
61923      ** filled with single-field index keys representing the results
61924      ** from the SELECT or the <exprlist>.
61925      **
61926      ** If the 'x' expression is a column value, or the SELECT...
61927      ** statement returns a column value, then the affinity of that
61928      ** column is used to build the index keys. If both 'x' and the
61929      ** SELECT... statement are columns, then numeric affinity is used
61930      ** if either column has NUMERIC or INTEGER affinity. If neither
61931      ** 'x' nor the SELECT... statement are columns, then numeric affinity
61932      ** is used.
61933      */
61934      pExpr->iTable = pParse->nTab++;
61935      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
61936      memset(&keyInfo, 0, sizeof(keyInfo));
61937      keyInfo.nField = 1;
61938
61939      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
61940        /* Case 1:     expr IN (SELECT ...)
61941        **
61942        ** Generate code to write the results of the select into the temporary
61943        ** table allocated and opened above.
61944        */
61945        SelectDest dest;
61946        ExprList *pEList;
61947
61948        assert( !isRowid );
61949        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
61950        dest.affinity = (u8)affinity;
61951        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
61952        if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
61953          return 0;
61954        }
61955        pEList = pExpr->x.pSelect->pEList;
61956        if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
61957          keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
61958              pEList->a[0].pExpr);
61959        }
61960      }else if( pExpr->x.pList!=0 ){
61961        /* Case 2:     expr IN (exprlist)
61962        **
61963        ** For each expression, build an index key from the evaluation and
61964        ** store it in the temporary table. If <expr> is a column, then use
61965        ** that columns affinity when building index keys. If <expr> is not
61966        ** a column, use numeric affinity.
61967        */
61968        int i;
61969        ExprList *pList = pExpr->x.pList;
61970        struct ExprList_item *pItem;
61971        int r1, r2, r3;
61972
61973        if( !affinity ){
61974          affinity = SQLITE_AFF_NONE;
61975        }
61976        keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
61977
61978        /* Loop through each expression in <exprlist>. */
61979        r1 = sqlite3GetTempReg(pParse);
61980        r2 = sqlite3GetTempReg(pParse);
61981        sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
61982        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
61983          Expr *pE2 = pItem->pExpr;
61984          int iValToIns;
61985
61986          /* If the expression is not constant then we will need to
61987          ** disable the test that was generated above that makes sure
61988          ** this code only executes once.  Because for a non-constant
61989          ** expression we need to rerun this code each time.
61990          */
61991          if( testAddr && !sqlite3ExprIsConstant(pE2) ){
61992            sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
61993            testAddr = 0;
61994          }
61995
61996          /* Evaluate the expression and insert it into the temp table */
61997          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
61998            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
61999          }else{
62000            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
62001            if( isRowid ){
62002              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
62003                                sqlite3VdbeCurrentAddr(v)+2);
62004              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
62005            }else{
62006              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
62007              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
62008              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
62009            }
62010          }
62011        }
62012        sqlite3ReleaseTempReg(pParse, r1);
62013        sqlite3ReleaseTempReg(pParse, r2);
62014      }
62015      if( !isRowid ){
62016        sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
62017      }
62018      break;
62019    }
62020
62021    case TK_EXISTS:
62022    case TK_SELECT:
62023    default: {
62024      /* If this has to be a scalar SELECT.  Generate code to put the
62025      ** value of this select in a memory cell and record the number
62026      ** of the memory cell in iColumn.  If this is an EXISTS, write
62027      ** an integer 0 (not exists) or 1 (exists) into a memory cell
62028      ** and record that memory cell in iColumn.
62029      */
62030      static const Token one = { "1", 1 };  /* Token for literal value 1 */
62031      Select *pSel;                         /* SELECT statement to encode */
62032      SelectDest dest;                      /* How to deal with SELECt result */
62033
62034      testcase( pExpr->op==TK_EXISTS );
62035      testcase( pExpr->op==TK_SELECT );
62036      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
62037
62038      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
62039      pSel = pExpr->x.pSelect;
62040      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
62041      if( pExpr->op==TK_SELECT ){
62042        dest.eDest = SRT_Mem;
62043        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
62044        VdbeComment((v, "Init subquery result"));
62045      }else{
62046        dest.eDest = SRT_Exists;
62047        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
62048        VdbeComment((v, "Init EXISTS result"));
62049      }
62050      sqlite3ExprDelete(pParse->db, pSel->pLimit);
62051      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
62052      if( sqlite3Select(pParse, pSel, &dest) ){
62053        return 0;
62054      }
62055      rReg = dest.iParm;
62056      ExprSetIrreducible(pExpr);
62057      break;
62058    }
62059  }
62060
62061  if( testAddr ){
62062    sqlite3VdbeJumpHere(v, testAddr-1);
62063  }
62064  sqlite3ExprCachePop(pParse, 1);
62065
62066  return rReg;
62067}
62068#endif /* SQLITE_OMIT_SUBQUERY */
62069
62070#ifndef SQLITE_OMIT_SUBQUERY
62071/*
62072** Generate code for an IN expression.
62073**
62074**      x IN (SELECT ...)
62075**      x IN (value, value, ...)
62076**
62077** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
62078** is an array of zero or more values.  The expression is true if the LHS is
62079** contained within the RHS.  The value of the expression is unknown (NULL)
62080** if the LHS is NULL or if the LHS is not contained within the RHS and the
62081** RHS contains one or more NULL values.
62082**
62083** This routine generates code will jump to destIfFalse if the LHS is not
62084** contained within the RHS.  If due to NULLs we cannot determine if the LHS
62085** is contained in the RHS then jump to destIfNull.  If the LHS is contained
62086** within the RHS then fall through.
62087*/
62088static void sqlite3ExprCodeIN(
62089  Parse *pParse,        /* Parsing and code generating context */
62090  Expr *pExpr,          /* The IN expression */
62091  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
62092  int destIfNull        /* Jump here if the results are unknown due to NULLs */
62093){
62094  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
62095  char affinity;        /* Comparison affinity to use */
62096  int eType;            /* Type of the RHS */
62097  int r1;               /* Temporary use register */
62098  Vdbe *v;              /* Statement under construction */
62099
62100  /* Compute the RHS.   After this step, the table with cursor
62101  ** pExpr->iTable will contains the values that make up the RHS.
62102  */
62103  v = pParse->pVdbe;
62104  assert( v!=0 );       /* OOM detected prior to this routine */
62105  VdbeNoopComment((v, "begin IN expr"));
62106  eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
62107
62108  /* Figure out the affinity to use to create a key from the results
62109  ** of the expression. affinityStr stores a static string suitable for
62110  ** P4 of OP_MakeRecord.
62111  */
62112  affinity = comparisonAffinity(pExpr);
62113
62114  /* Code the LHS, the <expr> from "<expr> IN (...)".
62115  */
62116  sqlite3ExprCachePush(pParse);
62117  r1 = sqlite3GetTempReg(pParse);
62118  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
62119  sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
62120
62121
62122  if( eType==IN_INDEX_ROWID ){
62123    /* In this case, the RHS is the ROWID of table b-tree
62124    */
62125    sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
62126    sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
62127  }else{
62128    /* In this case, the RHS is an index b-tree.
62129    */
62130    sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
62131
62132    /* If the set membership test fails, then the result of the
62133    ** "x IN (...)" expression must be either 0 or NULL. If the set
62134    ** contains no NULL values, then the result is 0. If the set
62135    ** contains one or more NULL values, then the result of the
62136    ** expression is also NULL.
62137    */
62138    if( rRhsHasNull==0 || destIfFalse==destIfNull ){
62139      /* This branch runs if it is known at compile time that the RHS
62140      ** cannot contain NULL values. This happens as the result
62141      ** of a "NOT NULL" constraint in the database schema.
62142      **
62143      ** Also run this branch if NULL is equivalent to FALSE
62144      ** for this particular IN operator.
62145      */
62146      sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
62147
62148    }else{
62149      /* In this branch, the RHS of the IN might contain a NULL and
62150      ** the presence of a NULL on the RHS makes a difference in the
62151      ** outcome.
62152      */
62153      int j1, j2, j3;
62154
62155      /* First check to see if the LHS is contained in the RHS.  If so,
62156      ** then the presence of NULLs in the RHS does not matter, so jump
62157      ** over all of the code that follows.
62158      */
62159      j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
62160
62161      /* Here we begin generating code that runs if the LHS is not
62162      ** contained within the RHS.  Generate additional code that
62163      ** tests the RHS for NULLs.  If the RHS contains a NULL then
62164      ** jump to destIfNull.  If there are no NULLs in the RHS then
62165      ** jump to destIfFalse.
62166      */
62167      j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
62168      j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
62169      sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
62170      sqlite3VdbeJumpHere(v, j3);
62171      sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
62172      sqlite3VdbeJumpHere(v, j2);
62173
62174      /* Jump to the appropriate target depending on whether or not
62175      ** the RHS contains a NULL
62176      */
62177      sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
62178      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
62179
62180      /* The OP_Found at the top of this branch jumps here when true,
62181      ** causing the overall IN expression evaluation to fall through.
62182      */
62183      sqlite3VdbeJumpHere(v, j1);
62184    }
62185  }
62186  sqlite3ReleaseTempReg(pParse, r1);
62187  sqlite3ExprCachePop(pParse, 1);
62188  VdbeComment((v, "end IN expr"));
62189}
62190#endif /* SQLITE_OMIT_SUBQUERY */
62191
62192/*
62193** Duplicate an 8-byte value
62194*/
62195static char *dup8bytes(Vdbe *v, const char *in){
62196  char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
62197  if( out ){
62198    memcpy(out, in, 8);
62199  }
62200  return out;
62201}
62202
62203/*
62204** Generate an instruction that will put the floating point
62205** value described by z[0..n-1] into register iMem.
62206**
62207** The z[] string will probably not be zero-terminated.  But the
62208** z[n] character is guaranteed to be something that does not look
62209** like the continuation of the number.
62210*/
62211static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
62212  if( ALWAYS(z!=0) ){
62213    double value;
62214    char *zV;
62215    sqlite3AtoF(z, &value);
62216    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
62217    if( negateFlag ) value = -value;
62218    zV = dup8bytes(v, (char*)&value);
62219    sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
62220  }
62221}
62222
62223
62224/*
62225** Generate an instruction that will put the integer describe by
62226** text z[0..n-1] into register iMem.
62227**
62228** The z[] string will probably not be zero-terminated.  But the
62229** z[n] character is guaranteed to be something that does not look
62230** like the continuation of the number.
62231*/
62232static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
62233  if( pExpr->flags & EP_IntValue ){
62234    int i = pExpr->u.iValue;
62235    if( negFlag ) i = -i;
62236    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
62237  }else{
62238    const char *z = pExpr->u.zToken;
62239    assert( z!=0 );
62240    if( sqlite3FitsIn64Bits(z, negFlag) ){
62241      i64 value;
62242      char *zV;
62243      sqlite3Atoi64(z, &value);
62244      if( negFlag ) value = -value;
62245      zV = dup8bytes(v, (char*)&value);
62246      sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
62247    }else{
62248      codeReal(v, z, negFlag, iMem);
62249    }
62250  }
62251}
62252
62253/*
62254** Clear a cache entry.
62255*/
62256static void cacheEntryClear(Parse *pParse, struct yColCache *p){
62257  if( p->tempReg ){
62258    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
62259      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
62260    }
62261    p->tempReg = 0;
62262  }
62263}
62264
62265
62266/*
62267** Record in the column cache that a particular column from a
62268** particular table is stored in a particular register.
62269*/
62270SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
62271  int i;
62272  int minLru;
62273  int idxLru;
62274  struct yColCache *p;
62275
62276  assert( iReg>0 );  /* Register numbers are always positive */
62277  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
62278
62279  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
62280  ** for testing only - to verify that SQLite always gets the same answer
62281  ** with and without the column cache.
62282  */
62283  if( pParse->db->flags & SQLITE_ColumnCache ) return;
62284
62285  /* First replace any existing entry.
62286  **
62287  ** Actually, the way the column cache is currently used, we are guaranteed
62288  ** that the object will never already be in cache.  Verify this guarantee.
62289  */
62290#ifndef NDEBUG
62291  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62292#if 0 /* This code wold remove the entry from the cache if it existed */
62293    if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
62294      cacheEntryClear(pParse, p);
62295      p->iLevel = pParse->iCacheLevel;
62296      p->iReg = iReg;
62297      p->lru = pParse->iCacheCnt++;
62298      return;
62299    }
62300#endif
62301    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
62302  }
62303#endif
62304
62305  /* Find an empty slot and replace it */
62306  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62307    if( p->iReg==0 ){
62308      p->iLevel = pParse->iCacheLevel;
62309      p->iTable = iTab;
62310      p->iColumn = iCol;
62311      p->iReg = iReg;
62312      p->tempReg = 0;
62313      p->lru = pParse->iCacheCnt++;
62314      return;
62315    }
62316  }
62317
62318  /* Replace the last recently used */
62319  minLru = 0x7fffffff;
62320  idxLru = -1;
62321  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62322    if( p->lru<minLru ){
62323      idxLru = i;
62324      minLru = p->lru;
62325    }
62326  }
62327  if( ALWAYS(idxLru>=0) ){
62328    p = &pParse->aColCache[idxLru];
62329    p->iLevel = pParse->iCacheLevel;
62330    p->iTable = iTab;
62331    p->iColumn = iCol;
62332    p->iReg = iReg;
62333    p->tempReg = 0;
62334    p->lru = pParse->iCacheCnt++;
62335    return;
62336  }
62337}
62338
62339/*
62340** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
62341** Purge the range of registers from the column cache.
62342*/
62343SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
62344  int i;
62345  int iLast = iReg + nReg - 1;
62346  struct yColCache *p;
62347  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62348    int r = p->iReg;
62349    if( r>=iReg && r<=iLast ){
62350      cacheEntryClear(pParse, p);
62351      p->iReg = 0;
62352    }
62353  }
62354}
62355
62356/*
62357** Remember the current column cache context.  Any new entries added
62358** added to the column cache after this call are removed when the
62359** corresponding pop occurs.
62360*/
62361SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
62362  pParse->iCacheLevel++;
62363}
62364
62365/*
62366** Remove from the column cache any entries that were added since the
62367** the previous N Push operations.  In other words, restore the cache
62368** to the state it was in N Pushes ago.
62369*/
62370SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
62371  int i;
62372  struct yColCache *p;
62373  assert( N>0 );
62374  assert( pParse->iCacheLevel>=N );
62375  pParse->iCacheLevel -= N;
62376  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62377    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
62378      cacheEntryClear(pParse, p);
62379      p->iReg = 0;
62380    }
62381  }
62382}
62383
62384/*
62385** When a cached column is reused, make sure that its register is
62386** no longer available as a temp register.  ticket #3879:  that same
62387** register might be in the cache in multiple places, so be sure to
62388** get them all.
62389*/
62390static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
62391  int i;
62392  struct yColCache *p;
62393  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62394    if( p->iReg==iReg ){
62395      p->tempReg = 0;
62396    }
62397  }
62398}
62399
62400/*
62401** Generate code that will extract the iColumn-th column from
62402** table pTab and store the column value in a register.  An effort
62403** is made to store the column value in register iReg, but this is
62404** not guaranteed.  The location of the column value is returned.
62405**
62406** There must be an open cursor to pTab in iTable when this routine
62407** is called.  If iColumn<0 then code is generated that extracts the rowid.
62408*/
62409SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
62410  Parse *pParse,   /* Parsing and code generating context */
62411  Table *pTab,     /* Description of the table we are reading from */
62412  int iColumn,     /* Index of the table column */
62413  int iTable,      /* The cursor pointing to the table */
62414  int iReg         /* Store results here */
62415){
62416  Vdbe *v = pParse->pVdbe;
62417  int i;
62418  struct yColCache *p;
62419
62420  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62421    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
62422      p->lru = pParse->iCacheCnt++;
62423      sqlite3ExprCachePinRegister(pParse, p->iReg);
62424      return p->iReg;
62425    }
62426  }
62427  assert( v!=0 );
62428  if( iColumn<0 ){
62429    sqlite3VdbeAddOp2(v, OP_Rowid, iTable, iReg);
62430  }else if( ALWAYS(pTab!=0) ){
62431    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
62432    sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
62433    sqlite3ColumnDefault(v, pTab, iColumn, iReg);
62434  }
62435  sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
62436  return iReg;
62437}
62438
62439/*
62440** Clear all column cache entries.
62441*/
62442SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
62443  int i;
62444  struct yColCache *p;
62445
62446  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62447    if( p->iReg ){
62448      cacheEntryClear(pParse, p);
62449      p->iReg = 0;
62450    }
62451  }
62452}
62453
62454/*
62455** Record the fact that an affinity change has occurred on iCount
62456** registers starting with iStart.
62457*/
62458SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
62459  sqlite3ExprCacheRemove(pParse, iStart, iCount);
62460}
62461
62462/*
62463** Generate code to move content from registers iFrom...iFrom+nReg-1
62464** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
62465*/
62466SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
62467  int i;
62468  struct yColCache *p;
62469  if( NEVER(iFrom==iTo) ) return;
62470  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
62471  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62472    int x = p->iReg;
62473    if( x>=iFrom && x<iFrom+nReg ){
62474      p->iReg += iTo-iFrom;
62475    }
62476  }
62477}
62478
62479/*
62480** Generate code to copy content from registers iFrom...iFrom+nReg-1
62481** over to iTo..iTo+nReg-1.
62482*/
62483SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
62484  int i;
62485  if( NEVER(iFrom==iTo) ) return;
62486  for(i=0; i<nReg; i++){
62487    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
62488  }
62489}
62490
62491#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
62492/*
62493** Return true if any register in the range iFrom..iTo (inclusive)
62494** is used as part of the column cache.
62495**
62496** This routine is used within assert() and testcase() macros only
62497** and does not appear in a normal build.
62498*/
62499static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
62500  int i;
62501  struct yColCache *p;
62502  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62503    int r = p->iReg;
62504    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
62505  }
62506  return 0;
62507}
62508#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
62509
62510/*
62511** If the last instruction coded is an ephemeral copy of any of
62512** the registers in the nReg registers beginning with iReg, then
62513** convert the last instruction from OP_SCopy to OP_Copy.
62514*/
62515SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
62516  VdbeOp *pOp;
62517  Vdbe *v;
62518
62519  assert( pParse->db->mallocFailed==0 );
62520  v = pParse->pVdbe;
62521  assert( v!=0 );
62522  pOp = sqlite3VdbeGetOp(v, -1);
62523  assert( pOp!=0 );
62524  if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
62525    pOp->opcode = OP_Copy;
62526  }
62527}
62528
62529/*
62530** Generate code to store the value of the iAlias-th alias in register
62531** target.  The first time this is called, pExpr is evaluated to compute
62532** the value of the alias.  The value is stored in an auxiliary register
62533** and the number of that register is returned.  On subsequent calls,
62534** the register number is returned without generating any code.
62535**
62536** Note that in order for this to work, code must be generated in the
62537** same order that it is executed.
62538**
62539** Aliases are numbered starting with 1.  So iAlias is in the range
62540** of 1 to pParse->nAlias inclusive.
62541**
62542** pParse->aAlias[iAlias-1] records the register number where the value
62543** of the iAlias-th alias is stored.  If zero, that means that the
62544** alias has not yet been computed.
62545*/
62546static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
62547#if 0
62548  sqlite3 *db = pParse->db;
62549  int iReg;
62550  if( pParse->nAliasAlloc<pParse->nAlias ){
62551    pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
62552                                 sizeof(pParse->aAlias[0])*pParse->nAlias );
62553    testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
62554    if( db->mallocFailed ) return 0;
62555    memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
62556           (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
62557    pParse->nAliasAlloc = pParse->nAlias;
62558  }
62559  assert( iAlias>0 && iAlias<=pParse->nAlias );
62560  iReg = pParse->aAlias[iAlias-1];
62561  if( iReg==0 ){
62562    if( pParse->iCacheLevel>0 ){
62563      iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
62564    }else{
62565      iReg = ++pParse->nMem;
62566      sqlite3ExprCode(pParse, pExpr, iReg);
62567      pParse->aAlias[iAlias-1] = iReg;
62568    }
62569  }
62570  return iReg;
62571#else
62572  UNUSED_PARAMETER(iAlias);
62573  return sqlite3ExprCodeTarget(pParse, pExpr, target);
62574#endif
62575}
62576
62577/*
62578** Generate code into the current Vdbe to evaluate the given
62579** expression.  Attempt to store the results in register "target".
62580** Return the register where results are stored.
62581**
62582** With this routine, there is no guarantee that results will
62583** be stored in target.  The result might be stored in some other
62584** register if it is convenient to do so.  The calling function
62585** must check the return code and move the results to the desired
62586** register.
62587*/
62588SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
62589  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
62590  int op;                   /* The opcode being coded */
62591  int inReg = target;       /* Results stored in register inReg */
62592  int regFree1 = 0;         /* If non-zero free this temporary register */
62593  int regFree2 = 0;         /* If non-zero free this temporary register */
62594  int r1, r2, r3, r4;       /* Various register numbers */
62595  sqlite3 *db = pParse->db; /* The database connection */
62596
62597  assert( target>0 && target<=pParse->nMem );
62598  if( v==0 ){
62599    assert( pParse->db->mallocFailed );
62600    return 0;
62601  }
62602
62603  if( pExpr==0 ){
62604    op = TK_NULL;
62605  }else{
62606    op = pExpr->op;
62607  }
62608  switch( op ){
62609    case TK_AGG_COLUMN: {
62610      AggInfo *pAggInfo = pExpr->pAggInfo;
62611      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
62612      if( !pAggInfo->directMode ){
62613        assert( pCol->iMem>0 );
62614        inReg = pCol->iMem;
62615        break;
62616      }else if( pAggInfo->useSortingIdx ){
62617        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
62618                              pCol->iSorterColumn, target);
62619        break;
62620      }
62621      /* Otherwise, fall thru into the TK_COLUMN case */
62622    }
62623    case TK_COLUMN: {
62624      if( pExpr->iTable<0 ){
62625        /* This only happens when coding check constraints */
62626        assert( pParse->ckBase>0 );
62627        inReg = pExpr->iColumn + pParse->ckBase;
62628      }else{
62629        inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
62630                                 pExpr->iColumn, pExpr->iTable, target);
62631      }
62632      break;
62633    }
62634    case TK_INTEGER: {
62635      codeInteger(v, pExpr, 0, target);
62636      break;
62637    }
62638    case TK_FLOAT: {
62639      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62640      codeReal(v, pExpr->u.zToken, 0, target);
62641      break;
62642    }
62643    case TK_STRING: {
62644      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62645      sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
62646      break;
62647    }
62648    case TK_NULL: {
62649      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
62650      break;
62651    }
62652#ifndef SQLITE_OMIT_BLOB_LITERAL
62653    case TK_BLOB: {
62654      int n;
62655      const char *z;
62656      char *zBlob;
62657      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62658      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
62659      assert( pExpr->u.zToken[1]=='\'' );
62660      z = &pExpr->u.zToken[2];
62661      n = sqlite3Strlen30(z) - 1;
62662      assert( z[n]=='\'' );
62663      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
62664      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
62665      break;
62666    }
62667#endif
62668    case TK_VARIABLE: {
62669      VdbeOp *pOp;
62670      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62671      assert( pExpr->u.zToken!=0 );
62672      assert( pExpr->u.zToken[0]!=0 );
62673      if( pExpr->u.zToken[1]==0
62674         && (pOp = sqlite3VdbeGetOp(v, -1))->opcode==OP_Variable
62675         && pOp->p1+pOp->p3==pExpr->iColumn
62676         && pOp->p2+pOp->p3==target
62677         && pOp->p4.z==0
62678      ){
62679        /* If the previous instruction was a copy of the previous unnamed
62680        ** parameter into the previous register, then simply increment the
62681        ** repeat count on the prior instruction rather than making a new
62682        ** instruction.
62683        */
62684        pOp->p3++;
62685      }else{
62686        sqlite3VdbeAddOp3(v, OP_Variable, pExpr->iColumn, target, 1);
62687        if( pExpr->u.zToken[1]!=0 ){
62688          sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
62689        }
62690      }
62691      break;
62692    }
62693    case TK_REGISTER: {
62694      inReg = pExpr->iTable;
62695      break;
62696    }
62697    case TK_AS: {
62698      inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
62699      break;
62700    }
62701#ifndef SQLITE_OMIT_CAST
62702    case TK_CAST: {
62703      /* Expressions of the form:   CAST(pLeft AS token) */
62704      int aff, to_op;
62705      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
62706      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62707      aff = sqlite3AffinityType(pExpr->u.zToken);
62708      to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
62709      assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
62710      assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
62711      assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
62712      assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
62713      assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
62714      testcase( to_op==OP_ToText );
62715      testcase( to_op==OP_ToBlob );
62716      testcase( to_op==OP_ToNumeric );
62717      testcase( to_op==OP_ToInt );
62718      testcase( to_op==OP_ToReal );
62719      if( inReg!=target ){
62720        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
62721        inReg = target;
62722      }
62723      sqlite3VdbeAddOp1(v, to_op, inReg);
62724      testcase( usedAsColumnCache(pParse, inReg, inReg) );
62725      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
62726      break;
62727    }
62728#endif /* SQLITE_OMIT_CAST */
62729    case TK_LT:
62730    case TK_LE:
62731    case TK_GT:
62732    case TK_GE:
62733    case TK_NE:
62734    case TK_EQ: {
62735      assert( TK_LT==OP_Lt );
62736      assert( TK_LE==OP_Le );
62737      assert( TK_GT==OP_Gt );
62738      assert( TK_GE==OP_Ge );
62739      assert( TK_EQ==OP_Eq );
62740      assert( TK_NE==OP_Ne );
62741      testcase( op==TK_LT );
62742      testcase( op==TK_LE );
62743      testcase( op==TK_GT );
62744      testcase( op==TK_GE );
62745      testcase( op==TK_EQ );
62746      testcase( op==TK_NE );
62747      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62748      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
62749      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
62750                  r1, r2, inReg, SQLITE_STOREP2);
62751      testcase( regFree1==0 );
62752      testcase( regFree2==0 );
62753      break;
62754    }
62755    case TK_IS:
62756    case TK_ISNOT: {
62757      testcase( op==TK_IS );
62758      testcase( op==TK_ISNOT );
62759      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62760      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
62761      op = (op==TK_IS) ? TK_EQ : TK_NE;
62762      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
62763                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
62764      testcase( regFree1==0 );
62765      testcase( regFree2==0 );
62766      break;
62767    }
62768    case TK_AND:
62769    case TK_OR:
62770    case TK_PLUS:
62771    case TK_STAR:
62772    case TK_MINUS:
62773    case TK_REM:
62774    case TK_BITAND:
62775    case TK_BITOR:
62776    case TK_SLASH:
62777    case TK_LSHIFT:
62778    case TK_RSHIFT:
62779    case TK_CONCAT: {
62780      assert( TK_AND==OP_And );
62781      assert( TK_OR==OP_Or );
62782      assert( TK_PLUS==OP_Add );
62783      assert( TK_MINUS==OP_Subtract );
62784      assert( TK_REM==OP_Remainder );
62785      assert( TK_BITAND==OP_BitAnd );
62786      assert( TK_BITOR==OP_BitOr );
62787      assert( TK_SLASH==OP_Divide );
62788      assert( TK_LSHIFT==OP_ShiftLeft );
62789      assert( TK_RSHIFT==OP_ShiftRight );
62790      assert( TK_CONCAT==OP_Concat );
62791      testcase( op==TK_AND );
62792      testcase( op==TK_OR );
62793      testcase( op==TK_PLUS );
62794      testcase( op==TK_MINUS );
62795      testcase( op==TK_REM );
62796      testcase( op==TK_BITAND );
62797      testcase( op==TK_BITOR );
62798      testcase( op==TK_SLASH );
62799      testcase( op==TK_LSHIFT );
62800      testcase( op==TK_RSHIFT );
62801      testcase( op==TK_CONCAT );
62802      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62803      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
62804      sqlite3VdbeAddOp3(v, op, r2, r1, target);
62805      testcase( regFree1==0 );
62806      testcase( regFree2==0 );
62807      break;
62808    }
62809    case TK_UMINUS: {
62810      Expr *pLeft = pExpr->pLeft;
62811      assert( pLeft );
62812      if( pLeft->op==TK_FLOAT ){
62813        assert( !ExprHasProperty(pExpr, EP_IntValue) );
62814        codeReal(v, pLeft->u.zToken, 1, target);
62815      }else if( pLeft->op==TK_INTEGER ){
62816        codeInteger(v, pLeft, 1, target);
62817      }else{
62818        regFree1 = r1 = sqlite3GetTempReg(pParse);
62819        sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
62820        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
62821        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
62822        testcase( regFree2==0 );
62823      }
62824      inReg = target;
62825      break;
62826    }
62827    case TK_BITNOT:
62828    case TK_NOT: {
62829      assert( TK_BITNOT==OP_BitNot );
62830      assert( TK_NOT==OP_Not );
62831      testcase( op==TK_BITNOT );
62832      testcase( op==TK_NOT );
62833      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62834      testcase( regFree1==0 );
62835      inReg = target;
62836      sqlite3VdbeAddOp2(v, op, r1, inReg);
62837      break;
62838    }
62839    case TK_ISNULL:
62840    case TK_NOTNULL: {
62841      int addr;
62842      assert( TK_ISNULL==OP_IsNull );
62843      assert( TK_NOTNULL==OP_NotNull );
62844      testcase( op==TK_ISNULL );
62845      testcase( op==TK_NOTNULL );
62846      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
62847      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62848      testcase( regFree1==0 );
62849      addr = sqlite3VdbeAddOp1(v, op, r1);
62850      sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
62851      sqlite3VdbeJumpHere(v, addr);
62852      break;
62853    }
62854    case TK_AGG_FUNCTION: {
62855      AggInfo *pInfo = pExpr->pAggInfo;
62856      if( pInfo==0 ){
62857        assert( !ExprHasProperty(pExpr, EP_IntValue) );
62858        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
62859      }else{
62860        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
62861      }
62862      break;
62863    }
62864    case TK_CONST_FUNC:
62865    case TK_FUNCTION: {
62866      ExprList *pFarg;       /* List of function arguments */
62867      int nFarg;             /* Number of function arguments */
62868      FuncDef *pDef;         /* The function definition object */
62869      int nId;               /* Length of the function name in bytes */
62870      const char *zId;       /* The function name */
62871      int constMask = 0;     /* Mask of function arguments that are constant */
62872      int i;                 /* Loop counter */
62873      u8 enc = ENC(db);      /* The text encoding used by this database */
62874      CollSeq *pColl = 0;    /* A collating sequence */
62875
62876      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
62877      testcase( op==TK_CONST_FUNC );
62878      testcase( op==TK_FUNCTION );
62879      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
62880        pFarg = 0;
62881      }else{
62882        pFarg = pExpr->x.pList;
62883      }
62884      nFarg = pFarg ? pFarg->nExpr : 0;
62885      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62886      zId = pExpr->u.zToken;
62887      nId = sqlite3Strlen30(zId);
62888      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
62889      if( pDef==0 ){
62890        sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
62891        break;
62892      }
62893
62894      /* Attempt a direct implementation of the built-in COALESCE() and
62895      ** IFNULL() functions.  This avoids unnecessary evalation of
62896      ** arguments past the first non-NULL argument.
62897      */
62898      if( pDef->flags & SQLITE_FUNC_COALESCE ){
62899        int endCoalesce = sqlite3VdbeMakeLabel(v);
62900        assert( nFarg>=2 );
62901        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
62902        for(i=1; i<nFarg; i++){
62903          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
62904          sqlite3ExprCacheRemove(pParse, target, 1);
62905          sqlite3ExprCachePush(pParse);
62906          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
62907          sqlite3ExprCachePop(pParse, 1);
62908        }
62909        sqlite3VdbeResolveLabel(v, endCoalesce);
62910        break;
62911      }
62912
62913
62914      if( pFarg ){
62915        r1 = sqlite3GetTempRange(pParse, nFarg);
62916        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
62917        sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
62918        sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
62919      }else{
62920        r1 = 0;
62921      }
62922#ifndef SQLITE_OMIT_VIRTUALTABLE
62923      /* Possibly overload the function if the first argument is
62924      ** a virtual table column.
62925      **
62926      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
62927      ** second argument, not the first, as the argument to test to
62928      ** see if it is a column in a virtual table.  This is done because
62929      ** the left operand of infix functions (the operand we want to
62930      ** control overloading) ends up as the second argument to the
62931      ** function.  The expression "A glob B" is equivalent to
62932      ** "glob(B,A).  We want to use the A in "A glob B" to test
62933      ** for function overloading.  But we use the B term in "glob(B,A)".
62934      */
62935      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
62936        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
62937      }else if( nFarg>0 ){
62938        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
62939      }
62940#endif
62941      for(i=0; i<nFarg; i++){
62942        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
62943          constMask |= (1<<i);
62944        }
62945        if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
62946          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
62947        }
62948      }
62949      if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
62950        if( !pColl ) pColl = db->pDfltColl;
62951        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
62952      }
62953      sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
62954                        (char*)pDef, P4_FUNCDEF);
62955      sqlite3VdbeChangeP5(v, (u8)nFarg);
62956      if( nFarg ){
62957        sqlite3ReleaseTempRange(pParse, r1, nFarg);
62958      }
62959      break;
62960    }
62961#ifndef SQLITE_OMIT_SUBQUERY
62962    case TK_EXISTS:
62963    case TK_SELECT: {
62964      testcase( op==TK_EXISTS );
62965      testcase( op==TK_SELECT );
62966      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
62967      break;
62968    }
62969    case TK_IN: {
62970      int destIfFalse = sqlite3VdbeMakeLabel(v);
62971      int destIfNull = sqlite3VdbeMakeLabel(v);
62972      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
62973      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
62974      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
62975      sqlite3VdbeResolveLabel(v, destIfFalse);
62976      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
62977      sqlite3VdbeResolveLabel(v, destIfNull);
62978      break;
62979    }
62980#endif /* SQLITE_OMIT_SUBQUERY */
62981
62982
62983    /*
62984    **    x BETWEEN y AND z
62985    **
62986    ** This is equivalent to
62987    **
62988    **    x>=y AND x<=z
62989    **
62990    ** X is stored in pExpr->pLeft.
62991    ** Y is stored in pExpr->pList->a[0].pExpr.
62992    ** Z is stored in pExpr->pList->a[1].pExpr.
62993    */
62994    case TK_BETWEEN: {
62995      Expr *pLeft = pExpr->pLeft;
62996      struct ExprList_item *pLItem = pExpr->x.pList->a;
62997      Expr *pRight = pLItem->pExpr;
62998
62999      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
63000      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
63001      testcase( regFree1==0 );
63002      testcase( regFree2==0 );
63003      r3 = sqlite3GetTempReg(pParse);
63004      r4 = sqlite3GetTempReg(pParse);
63005      codeCompare(pParse, pLeft, pRight, OP_Ge,
63006                  r1, r2, r3, SQLITE_STOREP2);
63007      pLItem++;
63008      pRight = pLItem->pExpr;
63009      sqlite3ReleaseTempReg(pParse, regFree2);
63010      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
63011      testcase( regFree2==0 );
63012      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
63013      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
63014      sqlite3ReleaseTempReg(pParse, r3);
63015      sqlite3ReleaseTempReg(pParse, r4);
63016      break;
63017    }
63018    case TK_UPLUS: {
63019      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
63020      break;
63021    }
63022
63023    case TK_TRIGGER: {
63024      /* If the opcode is TK_TRIGGER, then the expression is a reference
63025      ** to a column in the new.* or old.* pseudo-tables available to
63026      ** trigger programs. In this case Expr.iTable is set to 1 for the
63027      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
63028      ** is set to the column of the pseudo-table to read, or to -1 to
63029      ** read the rowid field.
63030      **
63031      ** The expression is implemented using an OP_Param opcode. The p1
63032      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
63033      ** to reference another column of the old.* pseudo-table, where
63034      ** i is the index of the column. For a new.rowid reference, p1 is
63035      ** set to (n+1), where n is the number of columns in each pseudo-table.
63036      ** For a reference to any other column in the new.* pseudo-table, p1
63037      ** is set to (n+2+i), where n and i are as defined previously. For
63038      ** example, if the table on which triggers are being fired is
63039      ** declared as:
63040      **
63041      **   CREATE TABLE t1(a, b);
63042      **
63043      ** Then p1 is interpreted as follows:
63044      **
63045      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
63046      **   p1==1   ->    old.a         p1==4   ->    new.a
63047      **   p1==2   ->    old.b         p1==5   ->    new.b
63048      */
63049      Table *pTab = pExpr->pTab;
63050      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
63051
63052      assert( pExpr->iTable==0 || pExpr->iTable==1 );
63053      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
63054      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
63055      assert( p1>=0 && p1<(pTab->nCol*2+2) );
63056
63057      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
63058      VdbeComment((v, "%s.%s -> $%d",
63059        (pExpr->iTable ? "new" : "old"),
63060        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
63061        target
63062      ));
63063
63064      /* If the column has REAL affinity, it may currently be stored as an
63065      ** integer. Use OP_RealAffinity to make sure it is really real.  */
63066      if( pExpr->iColumn>=0
63067       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
63068      ){
63069        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
63070      }
63071      break;
63072    }
63073
63074
63075    /*
63076    ** Form A:
63077    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
63078    **
63079    ** Form B:
63080    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
63081    **
63082    ** Form A is can be transformed into the equivalent form B as follows:
63083    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
63084    **        WHEN x=eN THEN rN ELSE y END
63085    **
63086    ** X (if it exists) is in pExpr->pLeft.
63087    ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
63088    ** ELSE clause and no other term matches, then the result of the
63089    ** exprssion is NULL.
63090    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
63091    **
63092    ** The result of the expression is the Ri for the first matching Ei,
63093    ** or if there is no matching Ei, the ELSE term Y, or if there is
63094    ** no ELSE term, NULL.
63095    */
63096    default: assert( op==TK_CASE ); {
63097      int endLabel;                     /* GOTO label for end of CASE stmt */
63098      int nextCase;                     /* GOTO label for next WHEN clause */
63099      int nExpr;                        /* 2x number of WHEN terms */
63100      int i;                            /* Loop counter */
63101      ExprList *pEList;                 /* List of WHEN terms */
63102      struct ExprList_item *aListelem;  /* Array of WHEN terms */
63103      Expr opCompare;                   /* The X==Ei expression */
63104      Expr cacheX;                      /* Cached expression X */
63105      Expr *pX;                         /* The X expression */
63106      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
63107      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
63108
63109      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
63110      assert((pExpr->x.pList->nExpr % 2) == 0);
63111      assert(pExpr->x.pList->nExpr > 0);
63112      pEList = pExpr->x.pList;
63113      aListelem = pEList->a;
63114      nExpr = pEList->nExpr;
63115      endLabel = sqlite3VdbeMakeLabel(v);
63116      if( (pX = pExpr->pLeft)!=0 ){
63117        cacheX = *pX;
63118        testcase( pX->op==TK_COLUMN );
63119        testcase( pX->op==TK_REGISTER );
63120        cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
63121        testcase( regFree1==0 );
63122        cacheX.op = TK_REGISTER;
63123        opCompare.op = TK_EQ;
63124        opCompare.pLeft = &cacheX;
63125        pTest = &opCompare;
63126      }
63127      for(i=0; i<nExpr; i=i+2){
63128        sqlite3ExprCachePush(pParse);
63129        if( pX ){
63130          assert( pTest!=0 );
63131          opCompare.pRight = aListelem[i].pExpr;
63132        }else{
63133          pTest = aListelem[i].pExpr;
63134        }
63135        nextCase = sqlite3VdbeMakeLabel(v);
63136        testcase( pTest->op==TK_COLUMN );
63137        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
63138        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
63139        testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
63140        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
63141        sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
63142        sqlite3ExprCachePop(pParse, 1);
63143        sqlite3VdbeResolveLabel(v, nextCase);
63144      }
63145      if( pExpr->pRight ){
63146        sqlite3ExprCachePush(pParse);
63147        sqlite3ExprCode(pParse, pExpr->pRight, target);
63148        sqlite3ExprCachePop(pParse, 1);
63149      }else{
63150        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
63151      }
63152      assert( db->mallocFailed || pParse->nErr>0
63153           || pParse->iCacheLevel==iCacheLevel );
63154      sqlite3VdbeResolveLabel(v, endLabel);
63155      break;
63156    }
63157#ifndef SQLITE_OMIT_TRIGGER
63158    case TK_RAISE: {
63159      assert( pExpr->affinity==OE_Rollback
63160           || pExpr->affinity==OE_Abort
63161           || pExpr->affinity==OE_Fail
63162           || pExpr->affinity==OE_Ignore
63163      );
63164      if( !pParse->pTriggerTab ){
63165        sqlite3ErrorMsg(pParse,
63166                       "RAISE() may only be used within a trigger-program");
63167        return 0;
63168      }
63169      if( pExpr->affinity==OE_Abort ){
63170        sqlite3MayAbort(pParse);
63171      }
63172      assert( !ExprHasProperty(pExpr, EP_IntValue) );
63173      if( pExpr->affinity==OE_Ignore ){
63174        sqlite3VdbeAddOp4(
63175            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
63176      }else{
63177        sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
63178      }
63179
63180      break;
63181    }
63182#endif
63183  }
63184  sqlite3ReleaseTempReg(pParse, regFree1);
63185  sqlite3ReleaseTempReg(pParse, regFree2);
63186  return inReg;
63187}
63188
63189/*
63190** Generate code to evaluate an expression and store the results
63191** into a register.  Return the register number where the results
63192** are stored.
63193**
63194** If the register is a temporary register that can be deallocated,
63195** then write its number into *pReg.  If the result register is not
63196** a temporary, then set *pReg to zero.
63197*/
63198SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
63199  int r1 = sqlite3GetTempReg(pParse);
63200  int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
63201  if( r2==r1 ){
63202    *pReg = r1;
63203  }else{
63204    sqlite3ReleaseTempReg(pParse, r1);
63205    *pReg = 0;
63206  }
63207  return r2;
63208}
63209
63210/*
63211** Generate code that will evaluate expression pExpr and store the
63212** results in register target.  The results are guaranteed to appear
63213** in register target.
63214*/
63215SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
63216  int inReg;
63217
63218  assert( target>0 && target<=pParse->nMem );
63219  inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
63220  assert( pParse->pVdbe || pParse->db->mallocFailed );
63221  if( inReg!=target && pParse->pVdbe ){
63222    sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
63223  }
63224  return target;
63225}
63226
63227/*
63228** Generate code that evalutes the given expression and puts the result
63229** in register target.
63230**
63231** Also make a copy of the expression results into another "cache" register
63232** and modify the expression so that the next time it is evaluated,
63233** the result is a copy of the cache register.
63234**
63235** This routine is used for expressions that are used multiple
63236** times.  They are evaluated once and the results of the expression
63237** are reused.
63238*/
63239SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
63240  Vdbe *v = pParse->pVdbe;
63241  int inReg;
63242  inReg = sqlite3ExprCode(pParse, pExpr, target);
63243  assert( target>0 );
63244  /* This routine is called for terms to INSERT or UPDATE.  And the only
63245  ** other place where expressions can be converted into TK_REGISTER is
63246  ** in WHERE clause processing.  So as currently implemented, there is
63247  ** no way for a TK_REGISTER to exist here.  But it seems prudent to
63248  ** keep the ALWAYS() in case the conditions above change with future
63249  ** modifications or enhancements. */
63250  if( ALWAYS(pExpr->op!=TK_REGISTER) ){
63251    int iMem;
63252    iMem = ++pParse->nMem;
63253    sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
63254    pExpr->iTable = iMem;
63255    pExpr->op2 = pExpr->op;
63256    pExpr->op = TK_REGISTER;
63257  }
63258  return inReg;
63259}
63260
63261/*
63262** Return TRUE if pExpr is an constant expression that is appropriate
63263** for factoring out of a loop.  Appropriate expressions are:
63264**
63265**    *  Any expression that evaluates to two or more opcodes.
63266**
63267**    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
63268**       or OP_Variable that does not need to be placed in a
63269**       specific register.
63270**
63271** There is no point in factoring out single-instruction constant
63272** expressions that need to be placed in a particular register.
63273** We could factor them out, but then we would end up adding an
63274** OP_SCopy instruction to move the value into the correct register
63275** later.  We might as well just use the original instruction and
63276** avoid the OP_SCopy.
63277*/
63278static int isAppropriateForFactoring(Expr *p){
63279  if( !sqlite3ExprIsConstantNotJoin(p) ){
63280    return 0;  /* Only constant expressions are appropriate for factoring */
63281  }
63282  if( (p->flags & EP_FixedDest)==0 ){
63283    return 1;  /* Any constant without a fixed destination is appropriate */
63284  }
63285  while( p->op==TK_UPLUS ) p = p->pLeft;
63286  switch( p->op ){
63287#ifndef SQLITE_OMIT_BLOB_LITERAL
63288    case TK_BLOB:
63289#endif
63290    case TK_VARIABLE:
63291    case TK_INTEGER:
63292    case TK_FLOAT:
63293    case TK_NULL:
63294    case TK_STRING: {
63295      testcase( p->op==TK_BLOB );
63296      testcase( p->op==TK_VARIABLE );
63297      testcase( p->op==TK_INTEGER );
63298      testcase( p->op==TK_FLOAT );
63299      testcase( p->op==TK_NULL );
63300      testcase( p->op==TK_STRING );
63301      /* Single-instruction constants with a fixed destination are
63302      ** better done in-line.  If we factor them, they will just end
63303      ** up generating an OP_SCopy to move the value to the destination
63304      ** register. */
63305      return 0;
63306    }
63307    case TK_UMINUS: {
63308      if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
63309        return 0;
63310      }
63311      break;
63312    }
63313    default: {
63314      break;
63315    }
63316  }
63317  return 1;
63318}
63319
63320/*
63321** If pExpr is a constant expression that is appropriate for
63322** factoring out of a loop, then evaluate the expression
63323** into a register and convert the expression into a TK_REGISTER
63324** expression.
63325*/
63326static int evalConstExpr(Walker *pWalker, Expr *pExpr){
63327  Parse *pParse = pWalker->pParse;
63328  switch( pExpr->op ){
63329    case TK_IN:
63330    case TK_REGISTER: {
63331      return WRC_Prune;
63332    }
63333    case TK_FUNCTION:
63334    case TK_AGG_FUNCTION:
63335    case TK_CONST_FUNC: {
63336      /* The arguments to a function have a fixed destination.
63337      ** Mark them this way to avoid generated unneeded OP_SCopy
63338      ** instructions.
63339      */
63340      ExprList *pList = pExpr->x.pList;
63341      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
63342      if( pList ){
63343        int i = pList->nExpr;
63344        struct ExprList_item *pItem = pList->a;
63345        for(; i>0; i--, pItem++){
63346          if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
63347        }
63348      }
63349      break;
63350    }
63351  }
63352  if( isAppropriateForFactoring(pExpr) ){
63353    int r1 = ++pParse->nMem;
63354    int r2;
63355    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
63356    if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
63357    pExpr->op2 = pExpr->op;
63358    pExpr->op = TK_REGISTER;
63359    pExpr->iTable = r2;
63360    return WRC_Prune;
63361  }
63362  return WRC_Continue;
63363}
63364
63365/*
63366** Preevaluate constant subexpressions within pExpr and store the
63367** results in registers.  Modify pExpr so that the constant subexpresions
63368** are TK_REGISTER opcodes that refer to the precomputed values.
63369*/
63370SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
63371  Walker w;
63372  w.xExprCallback = evalConstExpr;
63373  w.xSelectCallback = 0;
63374  w.pParse = pParse;
63375  sqlite3WalkExpr(&w, pExpr);
63376}
63377
63378
63379/*
63380** Generate code that pushes the value of every element of the given
63381** expression list into a sequence of registers beginning at target.
63382**
63383** Return the number of elements evaluated.
63384*/
63385SQLITE_PRIVATE int sqlite3ExprCodeExprList(
63386  Parse *pParse,     /* Parsing context */
63387  ExprList *pList,   /* The expression list to be coded */
63388  int target,        /* Where to write results */
63389  int doHardCopy     /* Make a hard copy of every element */
63390){
63391  struct ExprList_item *pItem;
63392  int i, n;
63393  assert( pList!=0 );
63394  assert( target>0 );
63395  n = pList->nExpr;
63396  for(pItem=pList->a, i=0; i<n; i++, pItem++){
63397    if( pItem->iAlias ){
63398      int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
63399      Vdbe *v = sqlite3GetVdbe(pParse);
63400      if( iReg!=target+i ){
63401        sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
63402      }
63403    }else{
63404      sqlite3ExprCode(pParse, pItem->pExpr, target+i);
63405    }
63406    if( doHardCopy && !pParse->db->mallocFailed ){
63407      sqlite3ExprHardCopy(pParse, target, n);
63408    }
63409  }
63410  return n;
63411}
63412
63413/*
63414** Generate code for a BETWEEN operator.
63415**
63416**    x BETWEEN y AND z
63417**
63418** The above is equivalent to
63419**
63420**    x>=y AND x<=z
63421**
63422** Code it as such, taking care to do the common subexpression
63423** elementation of x.
63424*/
63425static void exprCodeBetween(
63426  Parse *pParse,    /* Parsing and code generating context */
63427  Expr *pExpr,      /* The BETWEEN expression */
63428  int dest,         /* Jump here if the jump is taken */
63429  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
63430  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
63431){
63432  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
63433  Expr compLeft;    /* The  x>=y  term */
63434  Expr compRight;   /* The  x<=z  term */
63435  Expr exprX;       /* The  x  subexpression */
63436  int regFree1 = 0; /* Temporary use register */
63437
63438  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
63439  exprX = *pExpr->pLeft;
63440  exprAnd.op = TK_AND;
63441  exprAnd.pLeft = &compLeft;
63442  exprAnd.pRight = &compRight;
63443  compLeft.op = TK_GE;
63444  compLeft.pLeft = &exprX;
63445  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
63446  compRight.op = TK_LE;
63447  compRight.pLeft = &exprX;
63448  compRight.pRight = pExpr->x.pList->a[1].pExpr;
63449  exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
63450  exprX.op = TK_REGISTER;
63451  if( jumpIfTrue ){
63452    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
63453  }else{
63454    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
63455  }
63456  sqlite3ReleaseTempReg(pParse, regFree1);
63457
63458  /* Ensure adequate test coverage */
63459  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
63460  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
63461  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
63462  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
63463  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
63464  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
63465  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
63466  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
63467}
63468
63469/*
63470** Generate code for a boolean expression such that a jump is made
63471** to the label "dest" if the expression is true but execution
63472** continues straight thru if the expression is false.
63473**
63474** If the expression evaluates to NULL (neither true nor false), then
63475** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
63476**
63477** This code depends on the fact that certain token values (ex: TK_EQ)
63478** are the same as opcode values (ex: OP_Eq) that implement the corresponding
63479** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
63480** the make process cause these values to align.  Assert()s in the code
63481** below verify that the numbers are aligned correctly.
63482*/
63483SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
63484  Vdbe *v = pParse->pVdbe;
63485  int op = 0;
63486  int regFree1 = 0;
63487  int regFree2 = 0;
63488  int r1, r2;
63489
63490  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
63491  if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
63492  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
63493  op = pExpr->op;
63494  switch( op ){
63495    case TK_AND: {
63496      int d2 = sqlite3VdbeMakeLabel(v);
63497      testcase( jumpIfNull==0 );
63498      sqlite3ExprCachePush(pParse);
63499      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
63500      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
63501      sqlite3VdbeResolveLabel(v, d2);
63502      sqlite3ExprCachePop(pParse, 1);
63503      break;
63504    }
63505    case TK_OR: {
63506      testcase( jumpIfNull==0 );
63507      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
63508      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
63509      break;
63510    }
63511    case TK_NOT: {
63512      testcase( jumpIfNull==0 );
63513      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
63514      break;
63515    }
63516    case TK_LT:
63517    case TK_LE:
63518    case TK_GT:
63519    case TK_GE:
63520    case TK_NE:
63521    case TK_EQ: {
63522      assert( TK_LT==OP_Lt );
63523      assert( TK_LE==OP_Le );
63524      assert( TK_GT==OP_Gt );
63525      assert( TK_GE==OP_Ge );
63526      assert( TK_EQ==OP_Eq );
63527      assert( TK_NE==OP_Ne );
63528      testcase( op==TK_LT );
63529      testcase( op==TK_LE );
63530      testcase( op==TK_GT );
63531      testcase( op==TK_GE );
63532      testcase( op==TK_EQ );
63533      testcase( op==TK_NE );
63534      testcase( jumpIfNull==0 );
63535      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63536      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63537      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63538                  r1, r2, dest, jumpIfNull);
63539      testcase( regFree1==0 );
63540      testcase( regFree2==0 );
63541      break;
63542    }
63543    case TK_IS:
63544    case TK_ISNOT: {
63545      testcase( op==TK_IS );
63546      testcase( op==TK_ISNOT );
63547      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63548      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63549      op = (op==TK_IS) ? TK_EQ : TK_NE;
63550      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63551                  r1, r2, dest, SQLITE_NULLEQ);
63552      testcase( regFree1==0 );
63553      testcase( regFree2==0 );
63554      break;
63555    }
63556    case TK_ISNULL:
63557    case TK_NOTNULL: {
63558      assert( TK_ISNULL==OP_IsNull );
63559      assert( TK_NOTNULL==OP_NotNull );
63560      testcase( op==TK_ISNULL );
63561      testcase( op==TK_NOTNULL );
63562      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63563      sqlite3VdbeAddOp2(v, op, r1, dest);
63564      testcase( regFree1==0 );
63565      break;
63566    }
63567    case TK_BETWEEN: {
63568      testcase( jumpIfNull==0 );
63569      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
63570      break;
63571    }
63572    case TK_IN: {
63573      int destIfFalse = sqlite3VdbeMakeLabel(v);
63574      int destIfNull = jumpIfNull ? dest : destIfFalse;
63575      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
63576      sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
63577      sqlite3VdbeResolveLabel(v, destIfFalse);
63578      break;
63579    }
63580    default: {
63581      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
63582      sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
63583      testcase( regFree1==0 );
63584      testcase( jumpIfNull==0 );
63585      break;
63586    }
63587  }
63588  sqlite3ReleaseTempReg(pParse, regFree1);
63589  sqlite3ReleaseTempReg(pParse, regFree2);
63590}
63591
63592/*
63593** Generate code for a boolean expression such that a jump is made
63594** to the label "dest" if the expression is false but execution
63595** continues straight thru if the expression is true.
63596**
63597** If the expression evaluates to NULL (neither true nor false) then
63598** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
63599** is 0.
63600*/
63601SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
63602  Vdbe *v = pParse->pVdbe;
63603  int op = 0;
63604  int regFree1 = 0;
63605  int regFree2 = 0;
63606  int r1, r2;
63607
63608  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
63609  if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
63610  if( pExpr==0 )    return;
63611
63612  /* The value of pExpr->op and op are related as follows:
63613  **
63614  **       pExpr->op            op
63615  **       ---------          ----------
63616  **       TK_ISNULL          OP_NotNull
63617  **       TK_NOTNULL         OP_IsNull
63618  **       TK_NE              OP_Eq
63619  **       TK_EQ              OP_Ne
63620  **       TK_GT              OP_Le
63621  **       TK_LE              OP_Gt
63622  **       TK_GE              OP_Lt
63623  **       TK_LT              OP_Ge
63624  **
63625  ** For other values of pExpr->op, op is undefined and unused.
63626  ** The value of TK_ and OP_ constants are arranged such that we
63627  ** can compute the mapping above using the following expression.
63628  ** Assert()s verify that the computation is correct.
63629  */
63630  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
63631
63632  /* Verify correct alignment of TK_ and OP_ constants
63633  */
63634  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
63635  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
63636  assert( pExpr->op!=TK_NE || op==OP_Eq );
63637  assert( pExpr->op!=TK_EQ || op==OP_Ne );
63638  assert( pExpr->op!=TK_LT || op==OP_Ge );
63639  assert( pExpr->op!=TK_LE || op==OP_Gt );
63640  assert( pExpr->op!=TK_GT || op==OP_Le );
63641  assert( pExpr->op!=TK_GE || op==OP_Lt );
63642
63643  switch( pExpr->op ){
63644    case TK_AND: {
63645      testcase( jumpIfNull==0 );
63646      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
63647      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
63648      break;
63649    }
63650    case TK_OR: {
63651      int d2 = sqlite3VdbeMakeLabel(v);
63652      testcase( jumpIfNull==0 );
63653      sqlite3ExprCachePush(pParse);
63654      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
63655      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
63656      sqlite3VdbeResolveLabel(v, d2);
63657      sqlite3ExprCachePop(pParse, 1);
63658      break;
63659    }
63660    case TK_NOT: {
63661      testcase( jumpIfNull==0 );
63662      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
63663      break;
63664    }
63665    case TK_LT:
63666    case TK_LE:
63667    case TK_GT:
63668    case TK_GE:
63669    case TK_NE:
63670    case TK_EQ: {
63671      testcase( op==TK_LT );
63672      testcase( op==TK_LE );
63673      testcase( op==TK_GT );
63674      testcase( op==TK_GE );
63675      testcase( op==TK_EQ );
63676      testcase( op==TK_NE );
63677      testcase( jumpIfNull==0 );
63678      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63679      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63680      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63681                  r1, r2, dest, jumpIfNull);
63682      testcase( regFree1==0 );
63683      testcase( regFree2==0 );
63684      break;
63685    }
63686    case TK_IS:
63687    case TK_ISNOT: {
63688      testcase( pExpr->op==TK_IS );
63689      testcase( pExpr->op==TK_ISNOT );
63690      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63691      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63692      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
63693      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63694                  r1, r2, dest, SQLITE_NULLEQ);
63695      testcase( regFree1==0 );
63696      testcase( regFree2==0 );
63697      break;
63698    }
63699    case TK_ISNULL:
63700    case TK_NOTNULL: {
63701      testcase( op==TK_ISNULL );
63702      testcase( op==TK_NOTNULL );
63703      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63704      sqlite3VdbeAddOp2(v, op, r1, dest);
63705      testcase( regFree1==0 );
63706      break;
63707    }
63708    case TK_BETWEEN: {
63709      testcase( jumpIfNull==0 );
63710      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
63711      break;
63712    }
63713    case TK_IN: {
63714      if( jumpIfNull ){
63715        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
63716      }else{
63717        int destIfNull = sqlite3VdbeMakeLabel(v);
63718        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
63719        sqlite3VdbeResolveLabel(v, destIfNull);
63720      }
63721      break;
63722    }
63723    default: {
63724      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
63725      sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
63726      testcase( regFree1==0 );
63727      testcase( jumpIfNull==0 );
63728      break;
63729    }
63730  }
63731  sqlite3ReleaseTempReg(pParse, regFree1);
63732  sqlite3ReleaseTempReg(pParse, regFree2);
63733}
63734
63735/*
63736** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
63737** if they are identical and return FALSE if they differ in any way.
63738**
63739** Sometimes this routine will return FALSE even if the two expressions
63740** really are equivalent.  If we cannot prove that the expressions are
63741** identical, we return FALSE just to be safe.  So if this routine
63742** returns false, then you do not really know for certain if the two
63743** expressions are the same.  But if you get a TRUE return, then you
63744** can be sure the expressions are the same.  In the places where
63745** this routine is used, it does not hurt to get an extra FALSE - that
63746** just might result in some slightly slower code.  But returning
63747** an incorrect TRUE could lead to a malfunction.
63748*/
63749SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
63750  int i;
63751  if( pA==0||pB==0 ){
63752    return pB==pA;
63753  }
63754  assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
63755  assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
63756  if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
63757    return 0;
63758  }
63759  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
63760  if( pA->op!=pB->op ) return 0;
63761  if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
63762  if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
63763
63764  if( pA->x.pList && pB->x.pList ){
63765    if( pA->x.pList->nExpr!=pB->x.pList->nExpr ) return 0;
63766    for(i=0; i<pA->x.pList->nExpr; i++){
63767      Expr *pExprA = pA->x.pList->a[i].pExpr;
63768      Expr *pExprB = pB->x.pList->a[i].pExpr;
63769      if( !sqlite3ExprCompare(pExprA, pExprB) ) return 0;
63770    }
63771  }else if( pA->x.pList || pB->x.pList ){
63772    return 0;
63773  }
63774
63775  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
63776  if( ExprHasProperty(pA, EP_IntValue) ){
63777    if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
63778      return 0;
63779    }
63780  }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
63781    if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 0;
63782    if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
63783      return 0;
63784    }
63785  }
63786  return 1;
63787}
63788
63789
63790/*
63791** Add a new element to the pAggInfo->aCol[] array.  Return the index of
63792** the new element.  Return a negative number if malloc fails.
63793*/
63794static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
63795  int i;
63796  pInfo->aCol = sqlite3ArrayAllocate(
63797       db,
63798       pInfo->aCol,
63799       sizeof(pInfo->aCol[0]),
63800       3,
63801       &pInfo->nColumn,
63802       &pInfo->nColumnAlloc,
63803       &i
63804  );
63805  return i;
63806}
63807
63808/*
63809** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
63810** the new element.  Return a negative number if malloc fails.
63811*/
63812static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
63813  int i;
63814  pInfo->aFunc = sqlite3ArrayAllocate(
63815       db,
63816       pInfo->aFunc,
63817       sizeof(pInfo->aFunc[0]),
63818       3,
63819       &pInfo->nFunc,
63820       &pInfo->nFuncAlloc,
63821       &i
63822  );
63823  return i;
63824}
63825
63826/*
63827** This is the xExprCallback for a tree walker.  It is used to
63828** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
63829** for additional information.
63830*/
63831static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
63832  int i;
63833  NameContext *pNC = pWalker->u.pNC;
63834  Parse *pParse = pNC->pParse;
63835  SrcList *pSrcList = pNC->pSrcList;
63836  AggInfo *pAggInfo = pNC->pAggInfo;
63837
63838  switch( pExpr->op ){
63839    case TK_AGG_COLUMN:
63840    case TK_COLUMN: {
63841      testcase( pExpr->op==TK_AGG_COLUMN );
63842      testcase( pExpr->op==TK_COLUMN );
63843      /* Check to see if the column is in one of the tables in the FROM
63844      ** clause of the aggregate query */
63845      if( ALWAYS(pSrcList!=0) ){
63846        struct SrcList_item *pItem = pSrcList->a;
63847        for(i=0; i<pSrcList->nSrc; i++, pItem++){
63848          struct AggInfo_col *pCol;
63849          assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
63850          if( pExpr->iTable==pItem->iCursor ){
63851            /* If we reach this point, it means that pExpr refers to a table
63852            ** that is in the FROM clause of the aggregate query.
63853            **
63854            ** Make an entry for the column in pAggInfo->aCol[] if there
63855            ** is not an entry there already.
63856            */
63857            int k;
63858            pCol = pAggInfo->aCol;
63859            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
63860              if( pCol->iTable==pExpr->iTable &&
63861                  pCol->iColumn==pExpr->iColumn ){
63862                break;
63863              }
63864            }
63865            if( (k>=pAggInfo->nColumn)
63866             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
63867            ){
63868              pCol = &pAggInfo->aCol[k];
63869              pCol->pTab = pExpr->pTab;
63870              pCol->iTable = pExpr->iTable;
63871              pCol->iColumn = pExpr->iColumn;
63872              pCol->iMem = ++pParse->nMem;
63873              pCol->iSorterColumn = -1;
63874              pCol->pExpr = pExpr;
63875              if( pAggInfo->pGroupBy ){
63876                int j, n;
63877                ExprList *pGB = pAggInfo->pGroupBy;
63878                struct ExprList_item *pTerm = pGB->a;
63879                n = pGB->nExpr;
63880                for(j=0; j<n; j++, pTerm++){
63881                  Expr *pE = pTerm->pExpr;
63882                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
63883                      pE->iColumn==pExpr->iColumn ){
63884                    pCol->iSorterColumn = j;
63885                    break;
63886                  }
63887                }
63888              }
63889              if( pCol->iSorterColumn<0 ){
63890                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
63891              }
63892            }
63893            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
63894            ** because it was there before or because we just created it).
63895            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
63896            ** pAggInfo->aCol[] entry.
63897            */
63898            ExprSetIrreducible(pExpr);
63899            pExpr->pAggInfo = pAggInfo;
63900            pExpr->op = TK_AGG_COLUMN;
63901            pExpr->iAgg = (i16)k;
63902            break;
63903          } /* endif pExpr->iTable==pItem->iCursor */
63904        } /* end loop over pSrcList */
63905      }
63906      return WRC_Prune;
63907    }
63908    case TK_AGG_FUNCTION: {
63909      /* The pNC->nDepth==0 test causes aggregate functions in subqueries
63910      ** to be ignored */
63911      if( pNC->nDepth==0 ){
63912        /* Check to see if pExpr is a duplicate of another aggregate
63913        ** function that is already in the pAggInfo structure
63914        */
63915        struct AggInfo_func *pItem = pAggInfo->aFunc;
63916        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
63917          if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
63918            break;
63919          }
63920        }
63921        if( i>=pAggInfo->nFunc ){
63922          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
63923          */
63924          u8 enc = ENC(pParse->db);
63925          i = addAggInfoFunc(pParse->db, pAggInfo);
63926          if( i>=0 ){
63927            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
63928            pItem = &pAggInfo->aFunc[i];
63929            pItem->pExpr = pExpr;
63930            pItem->iMem = ++pParse->nMem;
63931            assert( !ExprHasProperty(pExpr, EP_IntValue) );
63932            pItem->pFunc = sqlite3FindFunction(pParse->db,
63933                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
63934                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
63935            if( pExpr->flags & EP_Distinct ){
63936              pItem->iDistinct = pParse->nTab++;
63937            }else{
63938              pItem->iDistinct = -1;
63939            }
63940          }
63941        }
63942        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
63943        */
63944        assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
63945        ExprSetIrreducible(pExpr);
63946        pExpr->iAgg = (i16)i;
63947        pExpr->pAggInfo = pAggInfo;
63948        return WRC_Prune;
63949      }
63950    }
63951  }
63952  return WRC_Continue;
63953}
63954static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
63955  NameContext *pNC = pWalker->u.pNC;
63956  if( pNC->nDepth==0 ){
63957    pNC->nDepth++;
63958    sqlite3WalkSelect(pWalker, pSelect);
63959    pNC->nDepth--;
63960    return WRC_Prune;
63961  }else{
63962    return WRC_Continue;
63963  }
63964}
63965
63966/*
63967** Analyze the given expression looking for aggregate functions and
63968** for variables that need to be added to the pParse->aAgg[] array.
63969** Make additional entries to the pParse->aAgg[] array as necessary.
63970**
63971** This routine should only be called after the expression has been
63972** analyzed by sqlite3ResolveExprNames().
63973*/
63974SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
63975  Walker w;
63976  w.xExprCallback = analyzeAggregate;
63977  w.xSelectCallback = analyzeAggregatesInSelect;
63978  w.u.pNC = pNC;
63979  assert( pNC->pSrcList!=0 );
63980  sqlite3WalkExpr(&w, pExpr);
63981}
63982
63983/*
63984** Call sqlite3ExprAnalyzeAggregates() for every expression in an
63985** expression list.  Return the number of errors.
63986**
63987** If an error is found, the analysis is cut short.
63988*/
63989SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
63990  struct ExprList_item *pItem;
63991  int i;
63992  if( pList ){
63993    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
63994      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
63995    }
63996  }
63997}
63998
63999/*
64000** Allocate a single new register for use to hold some intermediate result.
64001*/
64002SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
64003  if( pParse->nTempReg==0 ){
64004    return ++pParse->nMem;
64005  }
64006  return pParse->aTempReg[--pParse->nTempReg];
64007}
64008
64009/*
64010** Deallocate a register, making available for reuse for some other
64011** purpose.
64012**
64013** If a register is currently being used by the column cache, then
64014** the dallocation is deferred until the column cache line that uses
64015** the register becomes stale.
64016*/
64017SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
64018  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
64019    int i;
64020    struct yColCache *p;
64021    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
64022      if( p->iReg==iReg ){
64023        p->tempReg = 1;
64024        return;
64025      }
64026    }
64027    pParse->aTempReg[pParse->nTempReg++] = iReg;
64028  }
64029}
64030
64031/*
64032** Allocate or deallocate a block of nReg consecutive registers
64033*/
64034SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
64035  int i, n;
64036  i = pParse->iRangeReg;
64037  n = pParse->nRangeReg;
64038  if( nReg<=n ){
64039    assert( !usedAsColumnCache(pParse, i, i+n-1) );
64040    pParse->iRangeReg += nReg;
64041    pParse->nRangeReg -= nReg;
64042  }else{
64043    i = pParse->nMem+1;
64044    pParse->nMem += nReg;
64045  }
64046  return i;
64047}
64048SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
64049  sqlite3ExprCacheRemove(pParse, iReg, nReg);
64050  if( nReg>pParse->nRangeReg ){
64051    pParse->nRangeReg = nReg;
64052    pParse->iRangeReg = iReg;
64053  }
64054}
64055
64056/************** End of expr.c ************************************************/
64057/************** Begin file alter.c *******************************************/
64058/*
64059** 2005 February 15
64060**
64061** The author disclaims copyright to this source code.  In place of
64062** a legal notice, here is a blessing:
64063**
64064**    May you do good and not evil.
64065**    May you find forgiveness for yourself and forgive others.
64066**    May you share freely, never taking more than you give.
64067**
64068*************************************************************************
64069** This file contains C code routines that used to generate VDBE code
64070** that implements the ALTER TABLE command.
64071*/
64072
64073/*
64074** The code in this file only exists if we are not omitting the
64075** ALTER TABLE logic from the build.
64076*/
64077#ifndef SQLITE_OMIT_ALTERTABLE
64078
64079
64080/*
64081** This function is used by SQL generated to implement the
64082** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
64083** CREATE INDEX command. The second is a table name. The table name in
64084** the CREATE TABLE or CREATE INDEX statement is replaced with the third
64085** argument and the result returned. Examples:
64086**
64087** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
64088**     -> 'CREATE TABLE def(a, b, c)'
64089**
64090** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
64091**     -> 'CREATE INDEX i ON def(a, b, c)'
64092*/
64093static void renameTableFunc(
64094  sqlite3_context *context,
64095  int NotUsed,
64096  sqlite3_value **argv
64097){
64098  unsigned char const *zSql = sqlite3_value_text(argv[0]);
64099  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
64100
64101  int token;
64102  Token tname;
64103  unsigned char const *zCsr = zSql;
64104  int len = 0;
64105  char *zRet;
64106
64107  sqlite3 *db = sqlite3_context_db_handle(context);
64108
64109  UNUSED_PARAMETER(NotUsed);
64110
64111  /* The principle used to locate the table name in the CREATE TABLE
64112  ** statement is that the table name is the first non-space token that
64113  ** is immediately followed by a TK_LP or TK_USING token.
64114  */
64115  if( zSql ){
64116    do {
64117      if( !*zCsr ){
64118        /* Ran out of input before finding an opening bracket. Return NULL. */
64119        return;
64120      }
64121
64122      /* Store the token that zCsr points to in tname. */
64123      tname.z = (char*)zCsr;
64124      tname.n = len;
64125
64126      /* Advance zCsr to the next token. Store that token type in 'token',
64127      ** and its length in 'len' (to be used next iteration of this loop).
64128      */
64129      do {
64130        zCsr += len;
64131        len = sqlite3GetToken(zCsr, &token);
64132      } while( token==TK_SPACE );
64133      assert( len>0 );
64134    } while( token!=TK_LP && token!=TK_USING );
64135
64136    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
64137       zTableName, tname.z+tname.n);
64138    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
64139  }
64140}
64141
64142/*
64143** This C function implements an SQL user function that is used by SQL code
64144** generated by the ALTER TABLE ... RENAME command to modify the definition
64145** of any foreign key constraints that use the table being renamed as the
64146** parent table. It is passed three arguments:
64147**
64148**   1) The complete text of the CREATE TABLE statement being modified,
64149**   2) The old name of the table being renamed, and
64150**   3) The new name of the table being renamed.
64151**
64152** It returns the new CREATE TABLE statement. For example:
64153**
64154**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
64155**       -> 'CREATE TABLE t1(a REFERENCES t3)'
64156*/
64157#ifndef SQLITE_OMIT_FOREIGN_KEY
64158static void renameParentFunc(
64159  sqlite3_context *context,
64160  int NotUsed,
64161  sqlite3_value **argv
64162){
64163  sqlite3 *db = sqlite3_context_db_handle(context);
64164  char *zOutput = 0;
64165  char *zResult;
64166  unsigned char const *zInput = sqlite3_value_text(argv[0]);
64167  unsigned char const *zOld = sqlite3_value_text(argv[1]);
64168  unsigned char const *zNew = sqlite3_value_text(argv[2]);
64169
64170  unsigned const char *z;         /* Pointer to token */
64171  int n;                          /* Length of token z */
64172  int token;                      /* Type of token */
64173
64174  UNUSED_PARAMETER(NotUsed);
64175  for(z=zInput; *z; z=z+n){
64176    n = sqlite3GetToken(z, &token);
64177    if( token==TK_REFERENCES ){
64178      char *zParent;
64179      do {
64180        z += n;
64181        n = sqlite3GetToken(z, &token);
64182      }while( token==TK_SPACE );
64183
64184      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
64185      if( zParent==0 ) break;
64186      sqlite3Dequote(zParent);
64187      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
64188        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
64189            (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
64190        );
64191        sqlite3DbFree(db, zOutput);
64192        zOutput = zOut;
64193        zInput = &z[n];
64194      }
64195      sqlite3DbFree(db, zParent);
64196    }
64197  }
64198
64199  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
64200  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
64201  sqlite3DbFree(db, zOutput);
64202}
64203#endif
64204
64205#ifndef SQLITE_OMIT_TRIGGER
64206/* This function is used by SQL generated to implement the
64207** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
64208** statement. The second is a table name. The table name in the CREATE
64209** TRIGGER statement is replaced with the third argument and the result
64210** returned. This is analagous to renameTableFunc() above, except for CREATE
64211** TRIGGER, not CREATE INDEX and CREATE TABLE.
64212*/
64213static void renameTriggerFunc(
64214  sqlite3_context *context,
64215  int NotUsed,
64216  sqlite3_value **argv
64217){
64218  unsigned char const *zSql = sqlite3_value_text(argv[0]);
64219  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
64220
64221  int token;
64222  Token tname;
64223  int dist = 3;
64224  unsigned char const *zCsr = zSql;
64225  int len = 0;
64226  char *zRet;
64227  sqlite3 *db = sqlite3_context_db_handle(context);
64228
64229  UNUSED_PARAMETER(NotUsed);
64230
64231  /* The principle used to locate the table name in the CREATE TRIGGER
64232  ** statement is that the table name is the first token that is immediatedly
64233  ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
64234  ** of TK_WHEN, TK_BEGIN or TK_FOR.
64235  */
64236  if( zSql ){
64237    do {
64238
64239      if( !*zCsr ){
64240        /* Ran out of input before finding the table name. Return NULL. */
64241        return;
64242      }
64243
64244      /* Store the token that zCsr points to in tname. */
64245      tname.z = (char*)zCsr;
64246      tname.n = len;
64247
64248      /* Advance zCsr to the next token. Store that token type in 'token',
64249      ** and its length in 'len' (to be used next iteration of this loop).
64250      */
64251      do {
64252        zCsr += len;
64253        len = sqlite3GetToken(zCsr, &token);
64254      }while( token==TK_SPACE );
64255      assert( len>0 );
64256
64257      /* Variable 'dist' stores the number of tokens read since the most
64258      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
64259      ** token is read and 'dist' equals 2, the condition stated above
64260      ** to be met.
64261      **
64262      ** Note that ON cannot be a database, table or column name, so
64263      ** there is no need to worry about syntax like
64264      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
64265      */
64266      dist++;
64267      if( token==TK_DOT || token==TK_ON ){
64268        dist = 0;
64269      }
64270    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
64271
64272    /* Variable tname now contains the token that is the old table-name
64273    ** in the CREATE TRIGGER statement.
64274    */
64275    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
64276       zTableName, tname.z+tname.n);
64277    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
64278  }
64279}
64280#endif   /* !SQLITE_OMIT_TRIGGER */
64281
64282/*
64283** Register built-in functions used to help implement ALTER TABLE
64284*/
64285SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
64286  sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
64287                         renameTableFunc, 0, 0);
64288#ifndef SQLITE_OMIT_TRIGGER
64289  sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
64290                         renameTriggerFunc, 0, 0);
64291#endif
64292#ifndef SQLITE_OMIT_FOREIGN_KEY
64293  sqlite3CreateFunc(db, "sqlite_rename_parent", 3, SQLITE_UTF8, 0,
64294                         renameParentFunc, 0, 0);
64295#endif
64296}
64297
64298/*
64299** This function is used to create the text of expressions of the form:
64300**
64301**   name=<constant1> OR name=<constant2> OR ...
64302**
64303** If argument zWhere is NULL, then a pointer string containing the text
64304** "name=<constant>" is returned, where <constant> is the quoted version
64305** of the string passed as argument zConstant. The returned buffer is
64306** allocated using sqlite3DbMalloc(). It is the responsibility of the
64307** caller to ensure that it is eventually freed.
64308**
64309** If argument zWhere is not NULL, then the string returned is
64310** "<where> OR name=<constant>", where <where> is the contents of zWhere.
64311** In this case zWhere is passed to sqlite3DbFree() before returning.
64312**
64313*/
64314static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
64315  char *zNew;
64316  if( !zWhere ){
64317    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
64318  }else{
64319    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
64320    sqlite3DbFree(db, zWhere);
64321  }
64322  return zNew;
64323}
64324
64325#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
64326/*
64327** Generate the text of a WHERE expression which can be used to select all
64328** tables that have foreign key constraints that refer to table pTab (i.e.
64329** constraints for which pTab is the parent table) from the sqlite_master
64330** table.
64331*/
64332static char *whereForeignKeys(Parse *pParse, Table *pTab){
64333  FKey *p;
64334  char *zWhere = 0;
64335  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
64336    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
64337  }
64338  return zWhere;
64339}
64340#endif
64341
64342/*
64343** Generate the text of a WHERE expression which can be used to select all
64344** temporary triggers on table pTab from the sqlite_temp_master table. If
64345** table pTab has no temporary triggers, or is itself stored in the
64346** temporary database, NULL is returned.
64347*/
64348static char *whereTempTriggers(Parse *pParse, Table *pTab){
64349  Trigger *pTrig;
64350  char *zWhere = 0;
64351  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
64352
64353  /* If the table is not located in the temp-db (in which case NULL is
64354  ** returned, loop through the tables list of triggers. For each trigger
64355  ** that is not part of the temp-db schema, add a clause to the WHERE
64356  ** expression being built up in zWhere.
64357  */
64358  if( pTab->pSchema!=pTempSchema ){
64359    sqlite3 *db = pParse->db;
64360    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
64361      if( pTrig->pSchema==pTempSchema ){
64362        zWhere = whereOrName(db, zWhere, pTrig->zName);
64363      }
64364    }
64365  }
64366  return zWhere;
64367}
64368
64369/*
64370** Generate code to drop and reload the internal representation of table
64371** pTab from the database, including triggers and temporary triggers.
64372** Argument zName is the name of the table in the database schema at
64373** the time the generated code is executed. This can be different from
64374** pTab->zName if this function is being called to code part of an
64375** "ALTER TABLE RENAME TO" statement.
64376*/
64377static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
64378  Vdbe *v;
64379  char *zWhere;
64380  int iDb;                   /* Index of database containing pTab */
64381#ifndef SQLITE_OMIT_TRIGGER
64382  Trigger *pTrig;
64383#endif
64384
64385  v = sqlite3GetVdbe(pParse);
64386  if( NEVER(v==0) ) return;
64387  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
64388  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
64389  assert( iDb>=0 );
64390
64391#ifndef SQLITE_OMIT_TRIGGER
64392  /* Drop any table triggers from the internal schema. */
64393  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
64394    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
64395    assert( iTrigDb==iDb || iTrigDb==1 );
64396    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
64397  }
64398#endif
64399
64400  /* Drop the table and index from the internal schema.  */
64401  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
64402
64403  /* Reload the table, index and permanent trigger schemas. */
64404  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
64405  if( !zWhere ) return;
64406  sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
64407
64408#ifndef SQLITE_OMIT_TRIGGER
64409  /* Now, if the table is not stored in the temp database, reload any temp
64410  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
64411  */
64412  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
64413    sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
64414  }
64415#endif
64416}
64417
64418/*
64419** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
64420** command.
64421*/
64422SQLITE_PRIVATE void sqlite3AlterRenameTable(
64423  Parse *pParse,            /* Parser context. */
64424  SrcList *pSrc,            /* The table to rename. */
64425  Token *pName              /* The new table name. */
64426){
64427  int iDb;                  /* Database that contains the table */
64428  char *zDb;                /* Name of database iDb */
64429  Table *pTab;              /* Table being renamed */
64430  char *zName = 0;          /* NULL-terminated version of pName */
64431  sqlite3 *db = pParse->db; /* Database connection */
64432  int nTabName;             /* Number of UTF-8 characters in zTabName */
64433  const char *zTabName;     /* Original name of the table */
64434  Vdbe *v;
64435#ifndef SQLITE_OMIT_TRIGGER
64436  char *zWhere = 0;         /* Where clause to locate temp triggers */
64437#endif
64438  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
64439
64440  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
64441  assert( pSrc->nSrc==1 );
64442  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
64443
64444  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
64445  if( !pTab ) goto exit_rename_table;
64446  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
64447  zDb = db->aDb[iDb].zName;
64448
64449  /* Get a NULL terminated version of the new table name. */
64450  zName = sqlite3NameFromToken(db, pName);
64451  if( !zName ) goto exit_rename_table;
64452
64453  /* Check that a table or index named 'zName' does not already exist
64454  ** in database iDb. If so, this is an error.
64455  */
64456  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
64457    sqlite3ErrorMsg(pParse,
64458        "there is already another table or index with this name: %s", zName);
64459    goto exit_rename_table;
64460  }
64461
64462  /* Make sure it is not a system table being altered, or a reserved name
64463  ** that the table is being renamed to.
64464  */
64465  if( sqlite3Strlen30(pTab->zName)>6
64466   && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
64467  ){
64468    sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
64469    goto exit_rename_table;
64470  }
64471  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
64472    goto exit_rename_table;
64473  }
64474
64475#ifndef SQLITE_OMIT_VIEW
64476  if( pTab->pSelect ){
64477    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
64478    goto exit_rename_table;
64479  }
64480#endif
64481
64482#ifndef SQLITE_OMIT_AUTHORIZATION
64483  /* Invoke the authorization callback. */
64484  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
64485    goto exit_rename_table;
64486  }
64487#endif
64488
64489#ifndef SQLITE_OMIT_VIRTUALTABLE
64490  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
64491    goto exit_rename_table;
64492  }
64493  if( IsVirtual(pTab) ){
64494    pVTab = sqlite3GetVTable(db, pTab);
64495    if( pVTab->pVtab->pModule->xRename==0 ){
64496      pVTab = 0;
64497    }
64498  }
64499#endif
64500
64501  /* Begin a transaction and code the VerifyCookie for database iDb.
64502  ** Then modify the schema cookie (since the ALTER TABLE modifies the
64503  ** schema). Open a statement transaction if the table is a virtual
64504  ** table.
64505  */
64506  v = sqlite3GetVdbe(pParse);
64507  if( v==0 ){
64508    goto exit_rename_table;
64509  }
64510  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
64511  sqlite3ChangeCookie(pParse, iDb);
64512
64513  /* If this is a virtual table, invoke the xRename() function if
64514  ** one is defined. The xRename() callback will modify the names
64515  ** of any resources used by the v-table implementation (including other
64516  ** SQLite tables) that are identified by the name of the virtual table.
64517  */
64518#ifndef SQLITE_OMIT_VIRTUALTABLE
64519  if( pVTab ){
64520    int i = ++pParse->nMem;
64521    sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
64522    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
64523    sqlite3MayAbort(pParse);
64524  }
64525#endif
64526
64527  /* figure out how many UTF-8 characters are in zName */
64528  zTabName = pTab->zName;
64529  nTabName = sqlite3Utf8CharLen(zTabName, -1);
64530
64531#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
64532  if( db->flags&SQLITE_ForeignKeys ){
64533    /* If foreign-key support is enabled, rewrite the CREATE TABLE
64534    ** statements corresponding to all child tables of foreign key constraints
64535    ** for which the renamed table is the parent table.  */
64536    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
64537      sqlite3NestedParse(pParse,
64538          "UPDATE sqlite_master SET "
64539              "sql = sqlite_rename_parent(sql, %Q, %Q) "
64540              "WHERE %s;", zTabName, zName, zWhere);
64541      sqlite3DbFree(db, zWhere);
64542    }
64543  }
64544#endif
64545
64546  /* Modify the sqlite_master table to use the new table name. */
64547  sqlite3NestedParse(pParse,
64548      "UPDATE %Q.%s SET "
64549#ifdef SQLITE_OMIT_TRIGGER
64550          "sql = sqlite_rename_table(sql, %Q), "
64551#else
64552          "sql = CASE "
64553            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
64554            "ELSE sqlite_rename_table(sql, %Q) END, "
64555#endif
64556          "tbl_name = %Q, "
64557          "name = CASE "
64558            "WHEN type='table' THEN %Q "
64559            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
64560             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
64561            "ELSE name END "
64562      "WHERE tbl_name=%Q AND "
64563          "(type='table' OR type='index' OR type='trigger');",
64564      zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
64565#ifndef SQLITE_OMIT_TRIGGER
64566      zName,
64567#endif
64568      zName, nTabName, zTabName
64569  );
64570
64571#ifndef SQLITE_OMIT_AUTOINCREMENT
64572  /* If the sqlite_sequence table exists in this database, then update
64573  ** it with the new table name.
64574  */
64575  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
64576    sqlite3NestedParse(pParse,
64577        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
64578        zDb, zName, pTab->zName);
64579  }
64580#endif
64581
64582#ifndef SQLITE_OMIT_TRIGGER
64583  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
64584  ** table. Don't do this if the table being ALTERed is itself located in
64585  ** the temp database.
64586  */
64587  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
64588    sqlite3NestedParse(pParse,
64589        "UPDATE sqlite_temp_master SET "
64590            "sql = sqlite_rename_trigger(sql, %Q), "
64591            "tbl_name = %Q "
64592            "WHERE %s;", zName, zName, zWhere);
64593    sqlite3DbFree(db, zWhere);
64594  }
64595#endif
64596
64597#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
64598  if( db->flags&SQLITE_ForeignKeys ){
64599    FKey *p;
64600    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
64601      Table *pFrom = p->pFrom;
64602      if( pFrom!=pTab ){
64603        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
64604      }
64605    }
64606  }
64607#endif
64608
64609  /* Drop and reload the internal table schema. */
64610  reloadTableSchema(pParse, pTab, zName);
64611
64612exit_rename_table:
64613  sqlite3SrcListDelete(db, pSrc);
64614  sqlite3DbFree(db, zName);
64615}
64616
64617
64618/*
64619** Generate code to make sure the file format number is at least minFormat.
64620** The generated code will increase the file format number if necessary.
64621*/
64622SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
64623  Vdbe *v;
64624  v = sqlite3GetVdbe(pParse);
64625  /* The VDBE should have been allocated before this routine is called.
64626  ** If that allocation failed, we would have quit before reaching this
64627  ** point */
64628  if( ALWAYS(v) ){
64629    int r1 = sqlite3GetTempReg(pParse);
64630    int r2 = sqlite3GetTempReg(pParse);
64631    int j1;
64632    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
64633    sqlite3VdbeUsesBtree(v, iDb);
64634    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
64635    j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
64636    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
64637    sqlite3VdbeJumpHere(v, j1);
64638    sqlite3ReleaseTempReg(pParse, r1);
64639    sqlite3ReleaseTempReg(pParse, r2);
64640  }
64641}
64642
64643/*
64644** This function is called after an "ALTER TABLE ... ADD" statement
64645** has been parsed. Argument pColDef contains the text of the new
64646** column definition.
64647**
64648** The Table structure pParse->pNewTable was extended to include
64649** the new column during parsing.
64650*/
64651SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
64652  Table *pNew;              /* Copy of pParse->pNewTable */
64653  Table *pTab;              /* Table being altered */
64654  int iDb;                  /* Database number */
64655  const char *zDb;          /* Database name */
64656  const char *zTab;         /* Table name */
64657  char *zCol;               /* Null-terminated column definition */
64658  Column *pCol;             /* The new column */
64659  Expr *pDflt;              /* Default value for the new column */
64660  sqlite3 *db;              /* The database connection; */
64661
64662  db = pParse->db;
64663  if( pParse->nErr || db->mallocFailed ) return;
64664  pNew = pParse->pNewTable;
64665  assert( pNew );
64666
64667  assert( sqlite3BtreeHoldsAllMutexes(db) );
64668  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
64669  zDb = db->aDb[iDb].zName;
64670  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
64671  pCol = &pNew->aCol[pNew->nCol-1];
64672  pDflt = pCol->pDflt;
64673  pTab = sqlite3FindTable(db, zTab, zDb);
64674  assert( pTab );
64675
64676#ifndef SQLITE_OMIT_AUTHORIZATION
64677  /* Invoke the authorization callback. */
64678  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
64679    return;
64680  }
64681#endif
64682
64683  /* If the default value for the new column was specified with a
64684  ** literal NULL, then set pDflt to 0. This simplifies checking
64685  ** for an SQL NULL default below.
64686  */
64687  if( pDflt && pDflt->op==TK_NULL ){
64688    pDflt = 0;
64689  }
64690
64691  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
64692  ** If there is a NOT NULL constraint, then the default value for the
64693  ** column must not be NULL.
64694  */
64695  if( pCol->isPrimKey ){
64696    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
64697    return;
64698  }
64699  if( pNew->pIndex ){
64700    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
64701    return;
64702  }
64703  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
64704    sqlite3ErrorMsg(pParse,
64705        "Cannot add a REFERENCES column with non-NULL default value");
64706    return;
64707  }
64708  if( pCol->notNull && !pDflt ){
64709    sqlite3ErrorMsg(pParse,
64710        "Cannot add a NOT NULL column with default value NULL");
64711    return;
64712  }
64713
64714  /* Ensure the default expression is something that sqlite3ValueFromExpr()
64715  ** can handle (i.e. not CURRENT_TIME etc.)
64716  */
64717  if( pDflt ){
64718    sqlite3_value *pVal;
64719    if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
64720      db->mallocFailed = 1;
64721      return;
64722    }
64723    if( !pVal ){
64724      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
64725      return;
64726    }
64727    sqlite3ValueFree(pVal);
64728  }
64729
64730  /* Modify the CREATE TABLE statement. */
64731  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
64732  if( zCol ){
64733    char *zEnd = &zCol[pColDef->n-1];
64734    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
64735      *zEnd-- = '\0';
64736    }
64737    sqlite3NestedParse(pParse,
64738        "UPDATE \"%w\".%s SET "
64739          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
64740        "WHERE type = 'table' AND name = %Q",
64741      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
64742      zTab
64743    );
64744    sqlite3DbFree(db, zCol);
64745  }
64746
64747  /* If the default value of the new column is NULL, then set the file
64748  ** format to 2. If the default value of the new column is not NULL,
64749  ** the file format becomes 3.
64750  */
64751  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
64752
64753  /* Reload the schema of the modified table. */
64754  reloadTableSchema(pParse, pTab, pTab->zName);
64755}
64756
64757/*
64758** This function is called by the parser after the table-name in
64759** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
64760** pSrc is the full-name of the table being altered.
64761**
64762** This routine makes a (partial) copy of the Table structure
64763** for the table being altered and sets Parse.pNewTable to point
64764** to it. Routines called by the parser as the column definition
64765** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
64766** the copy. The copy of the Table structure is deleted by tokenize.c
64767** after parsing is finished.
64768**
64769** Routine sqlite3AlterFinishAddColumn() will be called to complete
64770** coding the "ALTER TABLE ... ADD" statement.
64771*/
64772SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
64773  Table *pNew;
64774  Table *pTab;
64775  Vdbe *v;
64776  int iDb;
64777  int i;
64778  int nAlloc;
64779  sqlite3 *db = pParse->db;
64780
64781  /* Look up the table being altered. */
64782  assert( pParse->pNewTable==0 );
64783  assert( sqlite3BtreeHoldsAllMutexes(db) );
64784  if( db->mallocFailed ) goto exit_begin_add_column;
64785  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
64786  if( !pTab ) goto exit_begin_add_column;
64787
64788#ifndef SQLITE_OMIT_VIRTUALTABLE
64789  if( IsVirtual(pTab) ){
64790    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
64791    goto exit_begin_add_column;
64792  }
64793#endif
64794
64795  /* Make sure this is not an attempt to ALTER a view. */
64796  if( pTab->pSelect ){
64797    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
64798    goto exit_begin_add_column;
64799  }
64800
64801  assert( pTab->addColOffset>0 );
64802  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
64803
64804  /* Put a copy of the Table struct in Parse.pNewTable for the
64805  ** sqlite3AddColumn() function and friends to modify.  But modify
64806  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
64807  ** prefix, we insure that the name will not collide with an existing
64808  ** table because user table are not allowed to have the "sqlite_"
64809  ** prefix on their name.
64810  */
64811  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
64812  if( !pNew ) goto exit_begin_add_column;
64813  pParse->pNewTable = pNew;
64814  pNew->nRef = 1;
64815  pNew->dbMem = pTab->dbMem;
64816  pNew->nCol = pTab->nCol;
64817  assert( pNew->nCol>0 );
64818  nAlloc = (((pNew->nCol-1)/8)*8)+8;
64819  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
64820  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
64821  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
64822  if( !pNew->aCol || !pNew->zName ){
64823    db->mallocFailed = 1;
64824    goto exit_begin_add_column;
64825  }
64826  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
64827  for(i=0; i<pNew->nCol; i++){
64828    Column *pCol = &pNew->aCol[i];
64829    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
64830    pCol->zColl = 0;
64831    pCol->zType = 0;
64832    pCol->pDflt = 0;
64833    pCol->zDflt = 0;
64834  }
64835  pNew->pSchema = db->aDb[iDb].pSchema;
64836  pNew->addColOffset = pTab->addColOffset;
64837  pNew->nRef = 1;
64838
64839  /* Begin a transaction and increment the schema cookie.  */
64840  sqlite3BeginWriteOperation(pParse, 0, iDb);
64841  v = sqlite3GetVdbe(pParse);
64842  if( !v ) goto exit_begin_add_column;
64843  sqlite3ChangeCookie(pParse, iDb);
64844
64845exit_begin_add_column:
64846  sqlite3SrcListDelete(db, pSrc);
64847  return;
64848}
64849#endif  /* SQLITE_ALTER_TABLE */
64850
64851/************** End of alter.c ***********************************************/
64852/************** Begin file analyze.c *****************************************/
64853/*
64854** 2005 July 8
64855**
64856** The author disclaims copyright to this source code.  In place of
64857** a legal notice, here is a blessing:
64858**
64859**    May you do good and not evil.
64860**    May you find forgiveness for yourself and forgive others.
64861**    May you share freely, never taking more than you give.
64862**
64863*************************************************************************
64864** This file contains code associated with the ANALYZE command.
64865*/
64866#ifndef SQLITE_OMIT_ANALYZE
64867
64868/*
64869** This routine generates code that opens the sqlite_stat1 table for
64870** writing with cursor iStatCur. If the library was built with the
64871** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
64872** opened for writing using cursor (iStatCur+1)
64873**
64874** If the sqlite_stat1 tables does not previously exist, it is created.
64875** Similarly, if the sqlite_stat2 table does not exist and the library
64876** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
64877**
64878** Argument zWhere may be a pointer to a buffer containing a table name,
64879** or it may be a NULL pointer. If it is not NULL, then all entries in
64880** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
64881** with the named table are deleted. If zWhere==0, then code is generated
64882** to delete all stat table entries.
64883*/
64884static void openStatTable(
64885  Parse *pParse,          /* Parsing context */
64886  int iDb,                /* The database we are looking in */
64887  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
64888  const char *zWhere      /* Delete entries associated with this table */
64889){
64890  static struct {
64891    const char *zName;
64892    const char *zCols;
64893  } aTable[] = {
64894    { "sqlite_stat1", "tbl,idx,stat" },
64895#ifdef SQLITE_ENABLE_STAT2
64896    { "sqlite_stat2", "tbl,idx,sampleno,sample" },
64897#endif
64898  };
64899
64900  int aRoot[] = {0, 0};
64901  u8 aCreateTbl[] = {0, 0};
64902
64903  int i;
64904  sqlite3 *db = pParse->db;
64905  Db *pDb;
64906  Vdbe *v = sqlite3GetVdbe(pParse);
64907  if( v==0 ) return;
64908  assert( sqlite3BtreeHoldsAllMutexes(db) );
64909  assert( sqlite3VdbeDb(v)==db );
64910  pDb = &db->aDb[iDb];
64911
64912  for(i=0; i<ArraySize(aTable); i++){
64913    const char *zTab = aTable[i].zName;
64914    Table *pStat;
64915    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
64916      /* The sqlite_stat[12] table does not exist. Create it. Note that a
64917      ** side-effect of the CREATE TABLE statement is to leave the rootpage
64918      ** of the new table in register pParse->regRoot. This is important
64919      ** because the OpenWrite opcode below will be needing it. */
64920      sqlite3NestedParse(pParse,
64921          "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
64922      );
64923      aRoot[i] = pParse->regRoot;
64924      aCreateTbl[i] = 1;
64925    }else{
64926      /* The table already exists. If zWhere is not NULL, delete all entries
64927      ** associated with the table zWhere. If zWhere is NULL, delete the
64928      ** entire contents of the table. */
64929      aRoot[i] = pStat->tnum;
64930      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
64931      if( zWhere ){
64932        sqlite3NestedParse(pParse,
64933           "DELETE FROM %Q.%s WHERE tbl=%Q", pDb->zName, zTab, zWhere
64934        );
64935      }else{
64936        /* The sqlite_stat[12] table already exists.  Delete all rows. */
64937        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
64938      }
64939    }
64940  }
64941
64942  /* Open the sqlite_stat[12] tables for writing. */
64943  for(i=0; i<ArraySize(aTable); i++){
64944    sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
64945    sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
64946    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
64947  }
64948}
64949
64950/*
64951** Generate code to do an analysis of all indices associated with
64952** a single table.
64953*/
64954static void analyzeOneTable(
64955  Parse *pParse,   /* Parser context */
64956  Table *pTab,     /* Table whose indices are to be analyzed */
64957  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
64958  int iMem         /* Available memory locations begin here */
64959){
64960  sqlite3 *db = pParse->db;    /* Database handle */
64961  Index *pIdx;                 /* An index to being analyzed */
64962  int iIdxCur;                 /* Cursor open on index being analyzed */
64963  Vdbe *v;                     /* The virtual machine being built up */
64964  int i;                       /* Loop counter */
64965  int topOfLoop;               /* The top of the loop */
64966  int endOfLoop;               /* The end of the loop */
64967  int addr;                    /* The address of an instruction */
64968  int iDb;                     /* Index of database containing pTab */
64969  int regTabname = iMem++;     /* Register containing table name */
64970  int regIdxname = iMem++;     /* Register containing index name */
64971  int regSampleno = iMem++;    /* Register containing next sample number */
64972  int regCol = iMem++;         /* Content of a column analyzed table */
64973  int regRec = iMem++;         /* Register holding completed record */
64974  int regTemp = iMem++;        /* Temporary use register */
64975  int regRowid = iMem++;       /* Rowid for the inserted record */
64976
64977#ifdef SQLITE_ENABLE_STAT2
64978  int regTemp2 = iMem++;       /* Temporary use register */
64979  int regSamplerecno = iMem++; /* Index of next sample to record */
64980  int regRecno = iMem++;       /* Current sample index */
64981  int regLast = iMem++;        /* Index of last sample to record */
64982  int regFirst = iMem++;       /* Index of first sample to record */
64983#endif
64984
64985  v = sqlite3GetVdbe(pParse);
64986  if( v==0 || NEVER(pTab==0) || pTab->pIndex==0 ){
64987    /* Do no analysis for tables that have no indices */
64988    return;
64989  }
64990  assert( sqlite3BtreeHoldsAllMutexes(db) );
64991  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
64992  assert( iDb>=0 );
64993#ifndef SQLITE_OMIT_AUTHORIZATION
64994  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
64995      db->aDb[iDb].zName ) ){
64996    return;
64997  }
64998#endif
64999
65000  /* Establish a read-lock on the table at the shared-cache level. */
65001  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
65002
65003  iIdxCur = pParse->nTab++;
65004  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
65005    int nCol = pIdx->nColumn;
65006    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
65007
65008    if( iMem+1+(nCol*2)>pParse->nMem ){
65009      pParse->nMem = iMem+1+(nCol*2);
65010    }
65011
65012    /* Open a cursor to the index to be analyzed. */
65013    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
65014    sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
65015        (char *)pKey, P4_KEYINFO_HANDOFF);
65016    VdbeComment((v, "%s", pIdx->zName));
65017
65018    /* Populate the registers containing the table and index names. */
65019    if( pTab->pIndex==pIdx ){
65020      sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
65021    }
65022    sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
65023
65024#ifdef SQLITE_ENABLE_STAT2
65025
65026    /* If this iteration of the loop is generating code to analyze the
65027    ** first index in the pTab->pIndex list, then register regLast has
65028    ** not been populated. In this case populate it now.  */
65029    if( pTab->pIndex==pIdx ){
65030      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
65031      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
65032      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
65033
65034      sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
65035      sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
65036      addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
65037      sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
65038      sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
65039      sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
65040      sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
65041      sqlite3VdbeJumpHere(v, addr);
65042    }
65043
65044    /* Zero the regSampleno and regRecno registers. */
65045    sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
65046    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
65047    sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
65048#endif
65049
65050    /* The block of memory cells initialized here is used as follows.
65051    **
65052    **    iMem:
65053    **        The total number of rows in the table.
65054    **
65055    **    iMem+1 .. iMem+nCol:
65056    **        Number of distinct entries in index considering the
65057    **        left-most N columns only, where N is between 1 and nCol,
65058    **        inclusive.
65059    **
65060    **    iMem+nCol+1 .. Mem+2*nCol:
65061    **        Previous value of indexed columns, from left to right.
65062    **
65063    ** Cells iMem through iMem+nCol are initialized to 0. The others are
65064    ** initialized to contain an SQL NULL.
65065    */
65066    for(i=0; i<=nCol; i++){
65067      sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
65068    }
65069    for(i=0; i<nCol; i++){
65070      sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
65071    }
65072
65073    /* Start the analysis loop. This loop runs through all the entries in
65074    ** the index b-tree.  */
65075    endOfLoop = sqlite3VdbeMakeLabel(v);
65076    sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
65077    topOfLoop = sqlite3VdbeCurrentAddr(v);
65078    sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
65079
65080    for(i=0; i<nCol; i++){
65081      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
65082#ifdef SQLITE_ENABLE_STAT2
65083      if( i==0 ){
65084        /* Check if the record that cursor iIdxCur points to contains a
65085        ** value that should be stored in the sqlite_stat2 table. If so,
65086        ** store it.  */
65087        int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
65088        assert( regTabname+1==regIdxname
65089             && regTabname+2==regSampleno
65090             && regTabname+3==regCol
65091        );
65092        sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
65093        sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
65094        sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
65095        sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
65096
65097        /* Calculate new values for regSamplerecno and regSampleno.
65098        **
65099        **   sampleno = sampleno + 1
65100        **   samplerecno = samplerecno+(remaining records)/(remaining samples)
65101        */
65102        sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
65103        sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
65104        sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
65105        sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
65106        sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
65107        sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
65108        sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
65109
65110        sqlite3VdbeJumpHere(v, ne);
65111        sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
65112      }
65113#endif
65114
65115      sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
65116      /**** TODO:  add collating sequence *****/
65117      sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
65118    }
65119    if( db->mallocFailed ){
65120      /* If a malloc failure has occurred, then the result of the expression
65121      ** passed as the second argument to the call to sqlite3VdbeJumpHere()
65122      ** below may be negative. Which causes an assert() to fail (or an
65123      ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
65124      return;
65125    }
65126    sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
65127    for(i=0; i<nCol; i++){
65128      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-(nCol*2));
65129      sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
65130      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
65131    }
65132
65133    /* End of the analysis loop. */
65134    sqlite3VdbeResolveLabel(v, endOfLoop);
65135    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
65136    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
65137
65138    /* Store the results in sqlite_stat1.
65139    **
65140    ** The result is a single row of the sqlite_stat1 table.  The first
65141    ** two columns are the names of the table and index.  The third column
65142    ** is a string composed of a list of integer statistics about the
65143    ** index.  The first integer in the list is the total number of entries
65144    ** in the index.  There is one additional integer in the list for each
65145    ** column of the table.  This additional integer is a guess of how many
65146    ** rows of the table the index will select.  If D is the count of distinct
65147    ** values and K is the total number of rows, then the integer is computed
65148    ** as:
65149    **
65150    **        I = (K+D-1)/D
65151    **
65152    ** If K==0 then no entry is made into the sqlite_stat1 table.
65153    ** If K>0 then it is always the case the D>0 so division by zero
65154    ** is never possible.
65155    */
65156    addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
65157    sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
65158    for(i=0; i<nCol; i++){
65159      sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
65160      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
65161      sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
65162      sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
65163      sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
65164      sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
65165      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
65166    }
65167    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
65168    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
65169    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
65170    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
65171    sqlite3VdbeJumpHere(v, addr);
65172  }
65173}
65174
65175/*
65176** Generate code that will cause the most recent index analysis to
65177** be laoded into internal hash tables where is can be used.
65178*/
65179static void loadAnalysis(Parse *pParse, int iDb){
65180  Vdbe *v = sqlite3GetVdbe(pParse);
65181  if( v ){
65182    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
65183  }
65184}
65185
65186/*
65187** Generate code that will do an analysis of an entire database
65188*/
65189static void analyzeDatabase(Parse *pParse, int iDb){
65190  sqlite3 *db = pParse->db;
65191  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
65192  HashElem *k;
65193  int iStatCur;
65194  int iMem;
65195
65196  sqlite3BeginWriteOperation(pParse, 0, iDb);
65197  iStatCur = pParse->nTab;
65198  pParse->nTab += 2;
65199  openStatTable(pParse, iDb, iStatCur, 0);
65200  iMem = pParse->nMem+1;
65201  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
65202    Table *pTab = (Table*)sqliteHashData(k);
65203    analyzeOneTable(pParse, pTab, iStatCur, iMem);
65204  }
65205  loadAnalysis(pParse, iDb);
65206}
65207
65208/*
65209** Generate code that will do an analysis of a single table in
65210** a database.
65211*/
65212static void analyzeTable(Parse *pParse, Table *pTab){
65213  int iDb;
65214  int iStatCur;
65215
65216  assert( pTab!=0 );
65217  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
65218  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
65219  sqlite3BeginWriteOperation(pParse, 0, iDb);
65220  iStatCur = pParse->nTab;
65221  pParse->nTab += 2;
65222  openStatTable(pParse, iDb, iStatCur, pTab->zName);
65223  analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
65224  loadAnalysis(pParse, iDb);
65225}
65226
65227/*
65228** Generate code for the ANALYZE command.  The parser calls this routine
65229** when it recognizes an ANALYZE command.
65230**
65231**        ANALYZE                            -- 1
65232**        ANALYZE  <database>                -- 2
65233**        ANALYZE  ?<database>.?<tablename>  -- 3
65234**
65235** Form 1 causes all indices in all attached databases to be analyzed.
65236** Form 2 analyzes all indices the single database named.
65237** Form 3 analyzes all indices associated with the named table.
65238*/
65239SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
65240  sqlite3 *db = pParse->db;
65241  int iDb;
65242  int i;
65243  char *z, *zDb;
65244  Table *pTab;
65245  Token *pTableName;
65246
65247  /* Read the database schema. If an error occurs, leave an error message
65248  ** and code in pParse and return NULL. */
65249  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
65250  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
65251    return;
65252  }
65253
65254  assert( pName2!=0 || pName1==0 );
65255  if( pName1==0 ){
65256    /* Form 1:  Analyze everything */
65257    for(i=0; i<db->nDb; i++){
65258      if( i==1 ) continue;  /* Do not analyze the TEMP database */
65259      analyzeDatabase(pParse, i);
65260    }
65261  }else if( pName2->n==0 ){
65262    /* Form 2:  Analyze the database or table named */
65263    iDb = sqlite3FindDb(db, pName1);
65264    if( iDb>=0 ){
65265      analyzeDatabase(pParse, iDb);
65266    }else{
65267      z = sqlite3NameFromToken(db, pName1);
65268      if( z ){
65269        pTab = sqlite3LocateTable(pParse, 0, z, 0);
65270        sqlite3DbFree(db, z);
65271        if( pTab ){
65272          analyzeTable(pParse, pTab);
65273        }
65274      }
65275    }
65276  }else{
65277    /* Form 3: Analyze the fully qualified table name */
65278    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
65279    if( iDb>=0 ){
65280      zDb = db->aDb[iDb].zName;
65281      z = sqlite3NameFromToken(db, pTableName);
65282      if( z ){
65283        pTab = sqlite3LocateTable(pParse, 0, z, zDb);
65284        sqlite3DbFree(db, z);
65285        if( pTab ){
65286          analyzeTable(pParse, pTab);
65287        }
65288      }
65289    }
65290  }
65291}
65292
65293/*
65294** Used to pass information from the analyzer reader through to the
65295** callback routine.
65296*/
65297typedef struct analysisInfo analysisInfo;
65298struct analysisInfo {
65299  sqlite3 *db;
65300  const char *zDatabase;
65301};
65302
65303/*
65304** This callback is invoked once for each index when reading the
65305** sqlite_stat1 table.
65306**
65307**     argv[0] = name of the index
65308**     argv[1] = results of analysis - on integer for each column
65309*/
65310static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
65311  analysisInfo *pInfo = (analysisInfo*)pData;
65312  Index *pIndex;
65313  int i, c;
65314  unsigned int v;
65315  const char *z;
65316
65317  assert( argc==2 );
65318  UNUSED_PARAMETER2(NotUsed, argc);
65319
65320  if( argv==0 || argv[0]==0 || argv[1]==0 ){
65321    return 0;
65322  }
65323  pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
65324  if( pIndex==0 ){
65325    return 0;
65326  }
65327  z = argv[1];
65328  for(i=0; *z && i<=pIndex->nColumn; i++){
65329    v = 0;
65330    while( (c=z[0])>='0' && c<='9' ){
65331      v = v*10 + c - '0';
65332      z++;
65333    }
65334    pIndex->aiRowEst[i] = v;
65335    if( *z==' ' ) z++;
65336  }
65337  return 0;
65338}
65339
65340/*
65341** If the Index.aSample variable is not NULL, delete the aSample[] array
65342** and its contents.
65343*/
65344SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index *pIdx){
65345#ifdef SQLITE_ENABLE_STAT2
65346  if( pIdx->aSample ){
65347    int j;
65348    sqlite3 *dbMem = pIdx->pTable->dbMem;
65349    for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
65350      IndexSample *p = &pIdx->aSample[j];
65351      if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
65352        sqlite3DbFree(pIdx->pTable->dbMem, p->u.z);
65353      }
65354    }
65355    sqlite3DbFree(dbMem, pIdx->aSample);
65356    pIdx->aSample = 0;
65357  }
65358#else
65359  UNUSED_PARAMETER(pIdx);
65360#endif
65361}
65362
65363/*
65364** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
65365** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
65366** arrays. The contents of sqlite_stat2 are used to populate the
65367** Index.aSample[] arrays.
65368**
65369** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
65370** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
65371** during compilation and the sqlite_stat2 table is present, no data is
65372** read from it.
65373**
65374** If SQLITE_ENABLE_STAT2 was defined during compilation and the
65375** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
65376** returned. However, in this case, data is read from the sqlite_stat1
65377** table (if it is present) before returning.
65378**
65379** If an OOM error occurs, this function always sets db->mallocFailed.
65380** This means if the caller does not care about other errors, the return
65381** code may be ignored.
65382*/
65383SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
65384  analysisInfo sInfo;
65385  HashElem *i;
65386  char *zSql;
65387  int rc;
65388
65389  assert( iDb>=0 && iDb<db->nDb );
65390  assert( db->aDb[iDb].pBt!=0 );
65391  assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
65392
65393  /* Clear any prior statistics */
65394  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
65395    Index *pIdx = sqliteHashData(i);
65396    sqlite3DefaultRowEst(pIdx);
65397    sqlite3DeleteIndexSamples(pIdx);
65398  }
65399
65400  /* Check to make sure the sqlite_stat1 table exists */
65401  sInfo.db = db;
65402  sInfo.zDatabase = db->aDb[iDb].zName;
65403  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
65404    return SQLITE_ERROR;
65405  }
65406
65407  /* Load new statistics out of the sqlite_stat1 table */
65408  zSql = sqlite3MPrintf(db,
65409      "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
65410  if( zSql==0 ){
65411    rc = SQLITE_NOMEM;
65412  }else{
65413    (void)sqlite3SafetyOff(db);
65414    rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
65415    (void)sqlite3SafetyOn(db);
65416    sqlite3DbFree(db, zSql);
65417  }
65418
65419
65420  /* Load the statistics from the sqlite_stat2 table. */
65421#ifdef SQLITE_ENABLE_STAT2
65422  if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
65423    rc = SQLITE_ERROR;
65424  }
65425  if( rc==SQLITE_OK ){
65426    sqlite3_stmt *pStmt = 0;
65427
65428    zSql = sqlite3MPrintf(db,
65429        "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
65430    if( !zSql ){
65431      rc = SQLITE_NOMEM;
65432    }else{
65433      (void)sqlite3SafetyOff(db);
65434      rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
65435      (void)sqlite3SafetyOn(db);
65436      sqlite3DbFree(db, zSql);
65437    }
65438
65439    if( rc==SQLITE_OK ){
65440      (void)sqlite3SafetyOff(db);
65441      while( sqlite3_step(pStmt)==SQLITE_ROW ){
65442        char *zIndex = (char *)sqlite3_column_text(pStmt, 0);
65443        Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
65444        if( pIdx ){
65445          int iSample = sqlite3_column_int(pStmt, 1);
65446          sqlite3 *dbMem = pIdx->pTable->dbMem;
65447          assert( dbMem==db || dbMem==0 );
65448          if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
65449            int eType = sqlite3_column_type(pStmt, 2);
65450
65451            if( pIdx->aSample==0 ){
65452              static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
65453              pIdx->aSample = (IndexSample *)sqlite3DbMallocZero(dbMem, sz);
65454              if( pIdx->aSample==0 ){
65455                db->mallocFailed = 1;
65456                break;
65457              }
65458            }
65459
65460            assert( pIdx->aSample );
65461            {
65462              IndexSample *pSample = &pIdx->aSample[iSample];
65463              pSample->eType = (u8)eType;
65464              if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
65465                pSample->u.r = sqlite3_column_double(pStmt, 2);
65466              }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
65467                const char *z = (const char *)(
65468                    (eType==SQLITE_BLOB) ?
65469                    sqlite3_column_blob(pStmt, 2):
65470                    sqlite3_column_text(pStmt, 2)
65471                );
65472                int n = sqlite3_column_bytes(pStmt, 2);
65473                if( n>24 ){
65474                  n = 24;
65475                }
65476                pSample->nByte = (u8)n;
65477                pSample->u.z = sqlite3DbMallocRaw(dbMem, n);
65478                if( pSample->u.z ){
65479                  memcpy(pSample->u.z, z, n);
65480                }else{
65481                  db->mallocFailed = 1;
65482                  break;
65483                }
65484              }
65485            }
65486          }
65487        }
65488      }
65489      rc = sqlite3_finalize(pStmt);
65490      (void)sqlite3SafetyOn(db);
65491    }
65492  }
65493#endif
65494
65495  if( rc==SQLITE_NOMEM ){
65496    db->mallocFailed = 1;
65497  }
65498  return rc;
65499}
65500
65501
65502#endif /* SQLITE_OMIT_ANALYZE */
65503
65504/************** End of analyze.c *********************************************/
65505/************** Begin file attach.c ******************************************/
65506/*
65507** 2003 April 6
65508**
65509** The author disclaims copyright to this source code.  In place of
65510** a legal notice, here is a blessing:
65511**
65512**    May you do good and not evil.
65513**    May you find forgiveness for yourself and forgive others.
65514**    May you share freely, never taking more than you give.
65515**
65516*************************************************************************
65517** This file contains code used to implement the ATTACH and DETACH commands.
65518*/
65519
65520#ifndef SQLITE_OMIT_ATTACH
65521/*
65522** Resolve an expression that was part of an ATTACH or DETACH statement. This
65523** is slightly different from resolving a normal SQL expression, because simple
65524** identifiers are treated as strings, not possible column names or aliases.
65525**
65526** i.e. if the parser sees:
65527**
65528**     ATTACH DATABASE abc AS def
65529**
65530** it treats the two expressions as literal strings 'abc' and 'def' instead of
65531** looking for columns of the same name.
65532**
65533** This only applies to the root node of pExpr, so the statement:
65534**
65535**     ATTACH DATABASE abc||def AS 'db2'
65536**
65537** will fail because neither abc or def can be resolved.
65538*/
65539static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
65540{
65541  int rc = SQLITE_OK;
65542  if( pExpr ){
65543    if( pExpr->op!=TK_ID ){
65544      rc = sqlite3ResolveExprNames(pName, pExpr);
65545      if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
65546        sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
65547        return SQLITE_ERROR;
65548      }
65549    }else{
65550      pExpr->op = TK_STRING;
65551    }
65552  }
65553  return rc;
65554}
65555
65556/*
65557** An SQL user-function registered to do the work of an ATTACH statement. The
65558** three arguments to the function come directly from an attach statement:
65559**
65560**     ATTACH DATABASE x AS y KEY z
65561**
65562**     SELECT sqlite_attach(x, y, z)
65563**
65564** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
65565** third argument.
65566*/
65567static void attachFunc(
65568  sqlite3_context *context,
65569  int NotUsed,
65570  sqlite3_value **argv
65571){
65572  int i;
65573  int rc = 0;
65574  sqlite3 *db = sqlite3_context_db_handle(context);
65575  const char *zName;
65576  const char *zFile;
65577  Db *aNew;
65578  char *zErrDyn = 0;
65579
65580  UNUSED_PARAMETER(NotUsed);
65581
65582  zFile = (const char *)sqlite3_value_text(argv[0]);
65583  zName = (const char *)sqlite3_value_text(argv[1]);
65584  if( zFile==0 ) zFile = "";
65585  if( zName==0 ) zName = "";
65586
65587  /* Check for the following errors:
65588  **
65589  **     * Too many attached databases,
65590  **     * Transaction currently open
65591  **     * Specified database name already being used.
65592  */
65593  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
65594    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
65595      db->aLimit[SQLITE_LIMIT_ATTACHED]
65596    );
65597    goto attach_error;
65598  }
65599  if( !db->autoCommit ){
65600    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
65601    goto attach_error;
65602  }
65603  for(i=0; i<db->nDb; i++){
65604    char *z = db->aDb[i].zName;
65605    assert( z && zName );
65606    if( sqlite3StrICmp(z, zName)==0 ){
65607      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
65608      goto attach_error;
65609    }
65610  }
65611
65612  /* Allocate the new entry in the db->aDb[] array and initialise the schema
65613  ** hash tables.
65614  */
65615  if( db->aDb==db->aDbStatic ){
65616    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
65617    if( aNew==0 ) return;
65618    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
65619  }else{
65620    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
65621    if( aNew==0 ) return;
65622  }
65623  db->aDb = aNew;
65624  aNew = &db->aDb[db->nDb];
65625  memset(aNew, 0, sizeof(*aNew));
65626
65627  /* Open the database file. If the btree is successfully opened, use
65628  ** it to obtain the database schema. At this point the schema may
65629  ** or may not be initialised.
65630  */
65631  rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
65632                           db->openFlags | SQLITE_OPEN_MAIN_DB | SQLITE_OPEN_CREATE /* Android Change */,
65633                           &aNew->pBt);
65634  db->nDb++;
65635  if( rc==SQLITE_CONSTRAINT ){
65636    rc = SQLITE_ERROR;
65637    zErrDyn = sqlite3MPrintf(db, "database is already attached");
65638  }else if( rc==SQLITE_OK ){
65639    Pager *pPager;
65640    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
65641    if( !aNew->pSchema ){
65642      rc = SQLITE_NOMEM;
65643    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
65644      zErrDyn = sqlite3MPrintf(db,
65645        "attached databases must use the same text encoding as main database");
65646      rc = SQLITE_ERROR;
65647    }
65648    pPager = sqlite3BtreePager(aNew->pBt);
65649    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
65650    sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
65651  }
65652  aNew->zName = sqlite3DbStrDup(db, zName);
65653  aNew->safety_level = 3;
65654
65655#if SQLITE_HAS_CODEC
65656  if( rc==SQLITE_OK ){
65657    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
65658    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
65659    int nKey;
65660    char *zKey;
65661    int t = sqlite3_value_type(argv[2]);
65662    switch( t ){
65663      case SQLITE_INTEGER:
65664      case SQLITE_FLOAT:
65665        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
65666        rc = SQLITE_ERROR;
65667        break;
65668
65669      case SQLITE_TEXT:
65670      case SQLITE_BLOB:
65671        nKey = sqlite3_value_bytes(argv[2]);
65672        zKey = (char *)sqlite3_value_blob(argv[2]);
65673        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
65674        break;
65675
65676      case SQLITE_NULL:
65677        /* No key specified.  Use the key from the main database */
65678        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
65679        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
65680        break;
65681    }
65682  }
65683#endif
65684
65685  /* If the file was opened successfully, read the schema for the new database.
65686  ** If this fails, or if opening the file failed, then close the file and
65687  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
65688  ** we found it.
65689  */
65690  if( rc==SQLITE_OK ){
65691    (void)sqlite3SafetyOn(db);
65692    sqlite3BtreeEnterAll(db);
65693    rc = sqlite3Init(db, &zErrDyn);
65694    sqlite3BtreeLeaveAll(db);
65695    (void)sqlite3SafetyOff(db);
65696  }
65697  if( rc ){
65698    int iDb = db->nDb - 1;
65699    assert( iDb>=2 );
65700    if( db->aDb[iDb].pBt ){
65701      sqlite3BtreeClose(db->aDb[iDb].pBt);
65702      db->aDb[iDb].pBt = 0;
65703      db->aDb[iDb].pSchema = 0;
65704    }
65705    sqlite3ResetInternalSchema(db, 0);
65706    db->nDb = iDb;
65707    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
65708      db->mallocFailed = 1;
65709      sqlite3DbFree(db, zErrDyn);
65710      zErrDyn = sqlite3MPrintf(db, "out of memory");
65711    }else if( zErrDyn==0 ){
65712      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
65713    }
65714    goto attach_error;
65715  }
65716
65717  return;
65718
65719attach_error:
65720  /* Return an error if we get here */
65721  if( zErrDyn ){
65722    sqlite3_result_error(context, zErrDyn, -1);
65723    sqlite3DbFree(db, zErrDyn);
65724  }
65725  if( rc ) sqlite3_result_error_code(context, rc);
65726}
65727
65728/*
65729** An SQL user-function registered to do the work of an DETACH statement. The
65730** three arguments to the function come directly from a detach statement:
65731**
65732**     DETACH DATABASE x
65733**
65734**     SELECT sqlite_detach(x)
65735*/
65736static void detachFunc(
65737  sqlite3_context *context,
65738  int NotUsed,
65739  sqlite3_value **argv
65740){
65741  const char *zName = (const char *)sqlite3_value_text(argv[0]);
65742  sqlite3 *db = sqlite3_context_db_handle(context);
65743  int i;
65744  Db *pDb = 0;
65745  char zErr[128];
65746
65747  UNUSED_PARAMETER(NotUsed);
65748
65749  if( zName==0 ) zName = "";
65750  for(i=0; i<db->nDb; i++){
65751    pDb = &db->aDb[i];
65752    if( pDb->pBt==0 ) continue;
65753    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
65754  }
65755
65756  if( i>=db->nDb ){
65757    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
65758    goto detach_error;
65759  }
65760  if( i<2 ){
65761    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
65762    goto detach_error;
65763  }
65764  if( !db->autoCommit ){
65765    sqlite3_snprintf(sizeof(zErr), zErr,
65766                     "cannot DETACH database within transaction");
65767    goto detach_error;
65768  }
65769  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
65770    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
65771    goto detach_error;
65772  }
65773
65774  sqlite3BtreeClose(pDb->pBt);
65775  pDb->pBt = 0;
65776  pDb->pSchema = 0;
65777  sqlite3ResetInternalSchema(db, 0);
65778  return;
65779
65780detach_error:
65781  sqlite3_result_error(context, zErr, -1);
65782}
65783
65784/*
65785** This procedure generates VDBE code for a single invocation of either the
65786** sqlite_detach() or sqlite_attach() SQL user functions.
65787*/
65788static void codeAttach(
65789  Parse *pParse,       /* The parser context */
65790  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
65791  FuncDef *pFunc,      /* FuncDef wrapper for detachFunc() or attachFunc() */
65792  Expr *pAuthArg,      /* Expression to pass to authorization callback */
65793  Expr *pFilename,     /* Name of database file */
65794  Expr *pDbname,       /* Name of the database to use internally */
65795  Expr *pKey           /* Database key for encryption extension */
65796){
65797  int rc;
65798  NameContext sName;
65799  Vdbe *v;
65800  sqlite3* db = pParse->db;
65801  int regArgs;
65802
65803  memset(&sName, 0, sizeof(NameContext));
65804  sName.pParse = pParse;
65805
65806  if(
65807      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
65808      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
65809      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
65810  ){
65811    pParse->nErr++;
65812    goto attach_end;
65813  }
65814
65815#ifndef SQLITE_OMIT_AUTHORIZATION
65816  if( pAuthArg ){
65817    char *zAuthArg = pAuthArg->u.zToken;
65818    if( NEVER(zAuthArg==0) ){
65819      goto attach_end;
65820    }
65821    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
65822    if(rc!=SQLITE_OK ){
65823      goto attach_end;
65824    }
65825  }
65826#endif /* SQLITE_OMIT_AUTHORIZATION */
65827
65828
65829  v = sqlite3GetVdbe(pParse);
65830  regArgs = sqlite3GetTempRange(pParse, 4);
65831  sqlite3ExprCode(pParse, pFilename, regArgs);
65832  sqlite3ExprCode(pParse, pDbname, regArgs+1);
65833  sqlite3ExprCode(pParse, pKey, regArgs+2);
65834
65835  assert( v || db->mallocFailed );
65836  if( v ){
65837    sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
65838    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
65839    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
65840    sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
65841
65842    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
65843    ** statement only). For DETACH, set it to false (expire all existing
65844    ** statements).
65845    */
65846    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
65847  }
65848
65849attach_end:
65850  sqlite3ExprDelete(db, pFilename);
65851  sqlite3ExprDelete(db, pDbname);
65852  sqlite3ExprDelete(db, pKey);
65853}
65854
65855/*
65856** Called by the parser to compile a DETACH statement.
65857**
65858**     DETACH pDbname
65859*/
65860SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
65861  static FuncDef detach_func = {
65862    1,                /* nArg */
65863    SQLITE_UTF8,      /* iPrefEnc */
65864    0,                /* flags */
65865    0,                /* pUserData */
65866    0,                /* pNext */
65867    detachFunc,       /* xFunc */
65868    0,                /* xStep */
65869    0,                /* xFinalize */
65870    "sqlite_detach",  /* zName */
65871    0                 /* pHash */
65872  };
65873  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
65874}
65875
65876/*
65877** Called by the parser to compile an ATTACH statement.
65878**
65879**     ATTACH p AS pDbname KEY pKey
65880*/
65881SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
65882  static FuncDef attach_func = {
65883    3,                /* nArg */
65884    SQLITE_UTF8,      /* iPrefEnc */
65885    0,                /* flags */
65886    0,                /* pUserData */
65887    0,                /* pNext */
65888    attachFunc,       /* xFunc */
65889    0,                /* xStep */
65890    0,                /* xFinalize */
65891    "sqlite_attach",  /* zName */
65892    0                 /* pHash */
65893  };
65894  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
65895}
65896#endif /* SQLITE_OMIT_ATTACH */
65897
65898/*
65899** Initialize a DbFixer structure.  This routine must be called prior
65900** to passing the structure to one of the sqliteFixAAAA() routines below.
65901**
65902** The return value indicates whether or not fixation is required.  TRUE
65903** means we do need to fix the database references, FALSE means we do not.
65904*/
65905SQLITE_PRIVATE int sqlite3FixInit(
65906  DbFixer *pFix,      /* The fixer to be initialized */
65907  Parse *pParse,      /* Error messages will be written here */
65908  int iDb,            /* This is the database that must be used */
65909  const char *zType,  /* "view", "trigger", or "index" */
65910  const Token *pName  /* Name of the view, trigger, or index */
65911){
65912  sqlite3 *db;
65913
65914  if( NEVER(iDb<0) || iDb==1 ) return 0;
65915  db = pParse->db;
65916  assert( db->nDb>iDb );
65917  pFix->pParse = pParse;
65918  pFix->zDb = db->aDb[iDb].zName;
65919  pFix->zType = zType;
65920  pFix->pName = pName;
65921  return 1;
65922}
65923
65924/*
65925** The following set of routines walk through the parse tree and assign
65926** a specific database to all table references where the database name
65927** was left unspecified in the original SQL statement.  The pFix structure
65928** must have been initialized by a prior call to sqlite3FixInit().
65929**
65930** These routines are used to make sure that an index, trigger, or
65931** view in one database does not refer to objects in a different database.
65932** (Exception: indices, triggers, and views in the TEMP database are
65933** allowed to refer to anything.)  If a reference is explicitly made
65934** to an object in a different database, an error message is added to
65935** pParse->zErrMsg and these routines return non-zero.  If everything
65936** checks out, these routines return 0.
65937*/
65938SQLITE_PRIVATE int sqlite3FixSrcList(
65939  DbFixer *pFix,       /* Context of the fixation */
65940  SrcList *pList       /* The Source list to check and modify */
65941){
65942  int i;
65943  const char *zDb;
65944  struct SrcList_item *pItem;
65945
65946  if( NEVER(pList==0) ) return 0;
65947  zDb = pFix->zDb;
65948  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
65949    if( pItem->zDatabase==0 ){
65950      pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
65951    }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
65952      sqlite3ErrorMsg(pFix->pParse,
65953         "%s %T cannot reference objects in database %s",
65954         pFix->zType, pFix->pName, pItem->zDatabase);
65955      return 1;
65956    }
65957#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
65958    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
65959    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
65960#endif
65961  }
65962  return 0;
65963}
65964#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
65965SQLITE_PRIVATE int sqlite3FixSelect(
65966  DbFixer *pFix,       /* Context of the fixation */
65967  Select *pSelect      /* The SELECT statement to be fixed to one database */
65968){
65969  while( pSelect ){
65970    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
65971      return 1;
65972    }
65973    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
65974      return 1;
65975    }
65976    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
65977      return 1;
65978    }
65979    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
65980      return 1;
65981    }
65982    pSelect = pSelect->pPrior;
65983  }
65984  return 0;
65985}
65986SQLITE_PRIVATE int sqlite3FixExpr(
65987  DbFixer *pFix,     /* Context of the fixation */
65988  Expr *pExpr        /* The expression to be fixed to one database */
65989){
65990  while( pExpr ){
65991    if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
65992    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
65993      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
65994    }else{
65995      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
65996    }
65997    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
65998      return 1;
65999    }
66000    pExpr = pExpr->pLeft;
66001  }
66002  return 0;
66003}
66004SQLITE_PRIVATE int sqlite3FixExprList(
66005  DbFixer *pFix,     /* Context of the fixation */
66006  ExprList *pList    /* The expression to be fixed to one database */
66007){
66008  int i;
66009  struct ExprList_item *pItem;
66010  if( pList==0 ) return 0;
66011  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
66012    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
66013      return 1;
66014    }
66015  }
66016  return 0;
66017}
66018#endif
66019
66020#ifndef SQLITE_OMIT_TRIGGER
66021SQLITE_PRIVATE int sqlite3FixTriggerStep(
66022  DbFixer *pFix,     /* Context of the fixation */
66023  TriggerStep *pStep /* The trigger step be fixed to one database */
66024){
66025  while( pStep ){
66026    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
66027      return 1;
66028    }
66029    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
66030      return 1;
66031    }
66032    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
66033      return 1;
66034    }
66035    pStep = pStep->pNext;
66036  }
66037  return 0;
66038}
66039#endif
66040
66041/************** End of attach.c **********************************************/
66042/************** Begin file auth.c ********************************************/
66043/*
66044** 2003 January 11
66045**
66046** The author disclaims copyright to this source code.  In place of
66047** a legal notice, here is a blessing:
66048**
66049**    May you do good and not evil.
66050**    May you find forgiveness for yourself and forgive others.
66051**    May you share freely, never taking more than you give.
66052**
66053*************************************************************************
66054** This file contains code used to implement the sqlite3_set_authorizer()
66055** API.  This facility is an optional feature of the library.  Embedded
66056** systems that do not need this facility may omit it by recompiling
66057** the library with -DSQLITE_OMIT_AUTHORIZATION=1
66058*/
66059
66060/*
66061** All of the code in this file may be omitted by defining a single
66062** macro.
66063*/
66064#ifndef SQLITE_OMIT_AUTHORIZATION
66065
66066/*
66067** Set or clear the access authorization function.
66068**
66069** The access authorization function is be called during the compilation
66070** phase to verify that the user has read and/or write access permission on
66071** various fields of the database.  The first argument to the auth function
66072** is a copy of the 3rd argument to this routine.  The second argument
66073** to the auth function is one of these constants:
66074**
66075**       SQLITE_CREATE_INDEX
66076**       SQLITE_CREATE_TABLE
66077**       SQLITE_CREATE_TEMP_INDEX
66078**       SQLITE_CREATE_TEMP_TABLE
66079**       SQLITE_CREATE_TEMP_TRIGGER
66080**       SQLITE_CREATE_TEMP_VIEW
66081**       SQLITE_CREATE_TRIGGER
66082**       SQLITE_CREATE_VIEW
66083**       SQLITE_DELETE
66084**       SQLITE_DROP_INDEX
66085**       SQLITE_DROP_TABLE
66086**       SQLITE_DROP_TEMP_INDEX
66087**       SQLITE_DROP_TEMP_TABLE
66088**       SQLITE_DROP_TEMP_TRIGGER
66089**       SQLITE_DROP_TEMP_VIEW
66090**       SQLITE_DROP_TRIGGER
66091**       SQLITE_DROP_VIEW
66092**       SQLITE_INSERT
66093**       SQLITE_PRAGMA
66094**       SQLITE_READ
66095**       SQLITE_SELECT
66096**       SQLITE_TRANSACTION
66097**       SQLITE_UPDATE
66098**
66099** The third and fourth arguments to the auth function are the name of
66100** the table and the column that are being accessed.  The auth function
66101** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
66102** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
66103** means that the SQL statement will never-run - the sqlite3_exec() call
66104** will return with an error.  SQLITE_IGNORE means that the SQL statement
66105** should run but attempts to read the specified column will return NULL
66106** and attempts to write the column will be ignored.
66107**
66108** Setting the auth function to NULL disables this hook.  The default
66109** setting of the auth function is NULL.
66110*/
66111SQLITE_API int sqlite3_set_authorizer(
66112  sqlite3 *db,
66113  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
66114  void *pArg
66115){
66116  sqlite3_mutex_enter(db->mutex);
66117  db->xAuth = xAuth;
66118  db->pAuthArg = pArg;
66119  sqlite3ExpirePreparedStatements(db);
66120  sqlite3_mutex_leave(db->mutex);
66121  return SQLITE_OK;
66122}
66123
66124/*
66125** Write an error message into pParse->zErrMsg that explains that the
66126** user-supplied authorization function returned an illegal value.
66127*/
66128static void sqliteAuthBadReturnCode(Parse *pParse){
66129  sqlite3ErrorMsg(pParse, "authorizer malfunction");
66130  pParse->rc = SQLITE_ERROR;
66131}
66132
66133/*
66134** Invoke the authorization callback for permission to read column zCol from
66135** table zTab in database zDb. This function assumes that an authorization
66136** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
66137**
66138** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
66139** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
66140** is treated as SQLITE_DENY. In this case an error is left in pParse.
66141*/
66142SQLITE_PRIVATE int sqlite3AuthReadCol(
66143  Parse *pParse,                  /* The parser context */
66144  const char *zTab,               /* Table name */
66145  const char *zCol,               /* Column name */
66146  int iDb                         /* Index of containing database. */
66147){
66148  sqlite3 *db = pParse->db;       /* Database handle */
66149  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
66150  int rc;                         /* Auth callback return code */
66151
66152  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
66153  if( rc==SQLITE_DENY ){
66154    if( db->nDb>2 || iDb!=0 ){
66155      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
66156    }else{
66157      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
66158    }
66159    pParse->rc = SQLITE_AUTH;
66160  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
66161    sqliteAuthBadReturnCode(pParse);
66162  }
66163  return rc;
66164}
66165
66166/*
66167** The pExpr should be a TK_COLUMN expression.  The table referred to
66168** is in pTabList or else it is the NEW or OLD table of a trigger.
66169** Check to see if it is OK to read this particular column.
66170**
66171** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
66172** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
66173** then generate an error.
66174*/
66175SQLITE_PRIVATE void sqlite3AuthRead(
66176  Parse *pParse,        /* The parser context */
66177  Expr *pExpr,          /* The expression to check authorization on */
66178  Schema *pSchema,      /* The schema of the expression */
66179  SrcList *pTabList     /* All table that pExpr might refer to */
66180){
66181  sqlite3 *db = pParse->db;
66182  Table *pTab = 0;      /* The table being read */
66183  const char *zCol;     /* Name of the column of the table */
66184  int iSrc;             /* Index in pTabList->a[] of table being read */
66185  int iDb;              /* The index of the database the expression refers to */
66186  int iCol;             /* Index of column in table */
66187
66188  if( db->xAuth==0 ) return;
66189  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
66190  if( iDb<0 ){
66191    /* An attempt to read a column out of a subquery or other
66192    ** temporary table. */
66193    return;
66194  }
66195
66196  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
66197  if( pExpr->op==TK_TRIGGER ){
66198    pTab = pParse->pTriggerTab;
66199  }else{
66200    assert( pTabList );
66201    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
66202      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
66203        pTab = pTabList->a[iSrc].pTab;
66204        break;
66205      }
66206    }
66207  }
66208  iCol = pExpr->iColumn;
66209  if( NEVER(pTab==0) ) return;
66210
66211  if( iCol>=0 ){
66212    assert( iCol<pTab->nCol );
66213    zCol = pTab->aCol[iCol].zName;
66214  }else if( pTab->iPKey>=0 ){
66215    assert( pTab->iPKey<pTab->nCol );
66216    zCol = pTab->aCol[pTab->iPKey].zName;
66217  }else{
66218    zCol = "ROWID";
66219  }
66220  assert( iDb>=0 && iDb<db->nDb );
66221  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
66222    pExpr->op = TK_NULL;
66223  }
66224}
66225
66226/*
66227** Do an authorization check using the code and arguments given.  Return
66228** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
66229** is returned, then the error count and error message in pParse are
66230** modified appropriately.
66231*/
66232SQLITE_PRIVATE int sqlite3AuthCheck(
66233  Parse *pParse,
66234  int code,
66235  const char *zArg1,
66236  const char *zArg2,
66237  const char *zArg3
66238){
66239  sqlite3 *db = pParse->db;
66240  int rc;
66241
66242  /* Don't do any authorization checks if the database is initialising
66243  ** or if the parser is being invoked from within sqlite3_declare_vtab.
66244  */
66245  if( db->init.busy || IN_DECLARE_VTAB ){
66246    return SQLITE_OK;
66247  }
66248
66249  if( db->xAuth==0 ){
66250    return SQLITE_OK;
66251  }
66252  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
66253  if( rc==SQLITE_DENY ){
66254    sqlite3ErrorMsg(pParse, "not authorized");
66255    pParse->rc = SQLITE_AUTH;
66256  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
66257    rc = SQLITE_DENY;
66258    sqliteAuthBadReturnCode(pParse);
66259  }
66260  return rc;
66261}
66262
66263/*
66264** Push an authorization context.  After this routine is called, the
66265** zArg3 argument to authorization callbacks will be zContext until
66266** popped.  Or if pParse==0, this routine is a no-op.
66267*/
66268SQLITE_PRIVATE void sqlite3AuthContextPush(
66269  Parse *pParse,
66270  AuthContext *pContext,
66271  const char *zContext
66272){
66273  assert( pParse );
66274  pContext->pParse = pParse;
66275  pContext->zAuthContext = pParse->zAuthContext;
66276  pParse->zAuthContext = zContext;
66277}
66278
66279/*
66280** Pop an authorization context that was previously pushed
66281** by sqlite3AuthContextPush
66282*/
66283SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
66284  if( pContext->pParse ){
66285    pContext->pParse->zAuthContext = pContext->zAuthContext;
66286    pContext->pParse = 0;
66287  }
66288}
66289
66290#endif /* SQLITE_OMIT_AUTHORIZATION */
66291
66292/************** End of auth.c ************************************************/
66293/************** Begin file build.c *******************************************/
66294/*
66295** 2001 September 15
66296**
66297** The author disclaims copyright to this source code.  In place of
66298** a legal notice, here is a blessing:
66299**
66300**    May you do good and not evil.
66301**    May you find forgiveness for yourself and forgive others.
66302**    May you share freely, never taking more than you give.
66303**
66304*************************************************************************
66305** This file contains C code routines that are called by the SQLite parser
66306** when syntax rules are reduced.  The routines in this file handle the
66307** following kinds of SQL syntax:
66308**
66309**     CREATE TABLE
66310**     DROP TABLE
66311**     CREATE INDEX
66312**     DROP INDEX
66313**     creating ID lists
66314**     BEGIN TRANSACTION
66315**     COMMIT
66316**     ROLLBACK
66317*/
66318
66319/*
66320** This routine is called when a new SQL statement is beginning to
66321** be parsed.  Initialize the pParse structure as needed.
66322*/
66323SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
66324  pParse->explain = (u8)explainFlag;
66325  pParse->nVar = 0;
66326}
66327
66328#ifndef SQLITE_OMIT_SHARED_CACHE
66329/*
66330** The TableLock structure is only used by the sqlite3TableLock() and
66331** codeTableLocks() functions.
66332*/
66333struct TableLock {
66334  int iDb;             /* The database containing the table to be locked */
66335  int iTab;            /* The root page of the table to be locked */
66336  u8 isWriteLock;      /* True for write lock.  False for a read lock */
66337  const char *zName;   /* Name of the table */
66338};
66339
66340/*
66341** Record the fact that we want to lock a table at run-time.
66342**
66343** The table to be locked has root page iTab and is found in database iDb.
66344** A read or a write lock can be taken depending on isWritelock.
66345**
66346** This routine just records the fact that the lock is desired.  The
66347** code to make the lock occur is generated by a later call to
66348** codeTableLocks() which occurs during sqlite3FinishCoding().
66349*/
66350SQLITE_PRIVATE void sqlite3TableLock(
66351  Parse *pParse,     /* Parsing context */
66352  int iDb,           /* Index of the database containing the table to lock */
66353  int iTab,          /* Root page number of the table to be locked */
66354  u8 isWriteLock,    /* True for a write lock */
66355  const char *zName  /* Name of the table to be locked */
66356){
66357  Parse *pToplevel = sqlite3ParseToplevel(pParse);
66358  int i;
66359  int nBytes;
66360  TableLock *p;
66361  assert( iDb>=0 );
66362
66363  for(i=0; i<pToplevel->nTableLock; i++){
66364    p = &pToplevel->aTableLock[i];
66365    if( p->iDb==iDb && p->iTab==iTab ){
66366      p->isWriteLock = (p->isWriteLock || isWriteLock);
66367      return;
66368    }
66369  }
66370
66371  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
66372  pToplevel->aTableLock =
66373      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
66374  if( pToplevel->aTableLock ){
66375    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
66376    p->iDb = iDb;
66377    p->iTab = iTab;
66378    p->isWriteLock = isWriteLock;
66379    p->zName = zName;
66380  }else{
66381    pToplevel->nTableLock = 0;
66382    pToplevel->db->mallocFailed = 1;
66383  }
66384}
66385
66386/*
66387** Code an OP_TableLock instruction for each table locked by the
66388** statement (configured by calls to sqlite3TableLock()).
66389*/
66390static void codeTableLocks(Parse *pParse){
66391  int i;
66392  Vdbe *pVdbe;
66393
66394  pVdbe = sqlite3GetVdbe(pParse);
66395  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
66396
66397  for(i=0; i<pParse->nTableLock; i++){
66398    TableLock *p = &pParse->aTableLock[i];
66399    int p1 = p->iDb;
66400    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
66401                      p->zName, P4_STATIC);
66402  }
66403}
66404#else
66405  #define codeTableLocks(x)
66406#endif
66407
66408/*
66409** This routine is called after a single SQL statement has been
66410** parsed and a VDBE program to execute that statement has been
66411** prepared.  This routine puts the finishing touches on the
66412** VDBE program and resets the pParse structure for the next
66413** parse.
66414**
66415** Note that if an error occurred, it might be the case that
66416** no VDBE code was generated.
66417*/
66418SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
66419  sqlite3 *db;
66420  Vdbe *v;
66421
66422  db = pParse->db;
66423  if( db->mallocFailed ) return;
66424  if( pParse->nested ) return;
66425  if( pParse->nErr ) return;
66426
66427  /* Begin by generating some termination code at the end of the
66428  ** vdbe program
66429  */
66430  v = sqlite3GetVdbe(pParse);
66431  assert( !pParse->isMultiWrite
66432       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
66433  if( v ){
66434    sqlite3VdbeAddOp0(v, OP_Halt);
66435
66436    /* The cookie mask contains one bit for each database file open.
66437    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
66438    ** set for each database that is used.  Generate code to start a
66439    ** transaction on each used database and to verify the schema cookie
66440    ** on each used database.
66441    */
66442    if( pParse->cookieGoto>0 ){
66443      u32 mask;
66444      int iDb;
66445      sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
66446      for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
66447        if( (mask & pParse->cookieMask)==0 ) continue;
66448        sqlite3VdbeUsesBtree(v, iDb);
66449        sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
66450        if( db->init.busy==0 ){
66451          sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
66452        }
66453      }
66454#ifndef SQLITE_OMIT_VIRTUALTABLE
66455      {
66456        int i;
66457        for(i=0; i<pParse->nVtabLock; i++){
66458          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
66459          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
66460        }
66461        pParse->nVtabLock = 0;
66462      }
66463#endif
66464
66465      /* Once all the cookies have been verified and transactions opened,
66466      ** obtain the required table-locks. This is a no-op unless the
66467      ** shared-cache feature is enabled.
66468      */
66469      codeTableLocks(pParse);
66470
66471      /* Initialize any AUTOINCREMENT data structures required.
66472      */
66473      sqlite3AutoincrementBegin(pParse);
66474
66475      /* Finally, jump back to the beginning of the executable code. */
66476      sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
66477    }
66478  }
66479
66480
66481  /* Get the VDBE program ready for execution
66482  */
66483  if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
66484#ifdef SQLITE_DEBUG
66485    FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
66486    sqlite3VdbeTrace(v, trace);
66487#endif
66488    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
66489    /* A minimum of one cursor is required if autoincrement is used
66490    *  See ticket [a696379c1f08866] */
66491    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
66492    sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
66493                         pParse->nTab, pParse->nMaxArg, pParse->explain,
66494                         pParse->isMultiWrite && pParse->mayAbort);
66495    pParse->rc = SQLITE_DONE;
66496    pParse->colNamesSet = 0;
66497  }else if( pParse->rc==SQLITE_OK ){
66498    pParse->rc = SQLITE_ERROR;
66499  }
66500  pParse->nTab = 0;
66501  pParse->nMem = 0;
66502  pParse->nSet = 0;
66503  pParse->nVar = 0;
66504  pParse->cookieMask = 0;
66505  pParse->cookieGoto = 0;
66506}
66507
66508/*
66509** Run the parser and code generator recursively in order to generate
66510** code for the SQL statement given onto the end of the pParse context
66511** currently under construction.  When the parser is run recursively
66512** this way, the final OP_Halt is not appended and other initialization
66513** and finalization steps are omitted because those are handling by the
66514** outermost parser.
66515**
66516** Not everything is nestable.  This facility is designed to permit
66517** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
66518** care if you decide to try to use this routine for some other purposes.
66519*/
66520SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
66521  va_list ap;
66522  char *zSql;
66523  char *zErrMsg = 0;
66524  sqlite3 *db = pParse->db;
66525# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
66526  char saveBuf[SAVE_SZ];
66527
66528  if( pParse->nErr ) return;
66529  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
66530  va_start(ap, zFormat);
66531  zSql = sqlite3VMPrintf(db, zFormat, ap);
66532  va_end(ap);
66533  if( zSql==0 ){
66534    return;   /* A malloc must have failed */
66535  }
66536  pParse->nested++;
66537  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
66538  memset(&pParse->nVar, 0, SAVE_SZ);
66539  sqlite3RunParser(pParse, zSql, &zErrMsg);
66540  sqlite3DbFree(db, zErrMsg);
66541  sqlite3DbFree(db, zSql);
66542  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
66543  pParse->nested--;
66544}
66545
66546/*
66547** Locate the in-memory structure that describes a particular database
66548** table given the name of that table and (optionally) the name of the
66549** database containing the table.  Return NULL if not found.
66550**
66551** If zDatabase is 0, all databases are searched for the table and the
66552** first matching table is returned.  (No checking for duplicate table
66553** names is done.)  The search order is TEMP first, then MAIN, then any
66554** auxiliary databases added using the ATTACH command.
66555**
66556** See also sqlite3LocateTable().
66557*/
66558SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
66559  Table *p = 0;
66560  int i;
66561  int nName;
66562  assert( zName!=0 );
66563  nName = sqlite3Strlen30(zName);
66564  for(i=OMIT_TEMPDB; i<db->nDb; i++){
66565    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
66566    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
66567    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
66568    if( p ) break;
66569  }
66570  return p;
66571}
66572
66573/*
66574** Locate the in-memory structure that describes a particular database
66575** table given the name of that table and (optionally) the name of the
66576** database containing the table.  Return NULL if not found.  Also leave an
66577** error message in pParse->zErrMsg.
66578**
66579** The difference between this routine and sqlite3FindTable() is that this
66580** routine leaves an error message in pParse->zErrMsg where
66581** sqlite3FindTable() does not.
66582*/
66583SQLITE_PRIVATE Table *sqlite3LocateTable(
66584  Parse *pParse,         /* context in which to report errors */
66585  int isView,            /* True if looking for a VIEW rather than a TABLE */
66586  const char *zName,     /* Name of the table we are looking for */
66587  const char *zDbase     /* Name of the database.  Might be NULL */
66588){
66589  Table *p;
66590
66591  /* Read the database schema. If an error occurs, leave an error message
66592  ** and code in pParse and return NULL. */
66593  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
66594    return 0;
66595  }
66596
66597  p = sqlite3FindTable(pParse->db, zName, zDbase);
66598  if( p==0 ){
66599    const char *zMsg = isView ? "no such view" : "no such table";
66600    if( zDbase ){
66601      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
66602    }else{
66603      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
66604    }
66605    pParse->checkSchema = 1;
66606  }
66607  return p;
66608}
66609
66610/*
66611** Locate the in-memory structure that describes
66612** a particular index given the name of that index
66613** and the name of the database that contains the index.
66614** Return NULL if not found.
66615**
66616** If zDatabase is 0, all databases are searched for the
66617** table and the first matching index is returned.  (No checking
66618** for duplicate index names is done.)  The search order is
66619** TEMP first, then MAIN, then any auxiliary databases added
66620** using the ATTACH command.
66621*/
66622SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
66623  Index *p = 0;
66624  int i;
66625  int nName = sqlite3Strlen30(zName);
66626  for(i=OMIT_TEMPDB; i<db->nDb; i++){
66627    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
66628    Schema *pSchema = db->aDb[j].pSchema;
66629    assert( pSchema );
66630    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
66631    p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
66632    if( p ) break;
66633  }
66634  return p;
66635}
66636
66637/*
66638** Reclaim the memory used by an index
66639*/
66640static void freeIndex(Index *p){
66641  sqlite3 *db = p->pTable->dbMem;
66642#ifndef SQLITE_OMIT_ANALYZE
66643  sqlite3DeleteIndexSamples(p);
66644#endif
66645  sqlite3DbFree(db, p->zColAff);
66646  sqlite3DbFree(db, p);
66647}
66648
66649/*
66650** Remove the given index from the index hash table, and free
66651** its memory structures.
66652**
66653** The index is removed from the database hash tables but
66654** it is not unlinked from the Table that it indexes.
66655** Unlinking from the Table must be done by the calling function.
66656*/
66657static void sqlite3DeleteIndex(Index *p){
66658  Index *pOld;
66659  const char *zName = p->zName;
66660
66661  pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
66662                           sqlite3Strlen30(zName), 0);
66663  assert( pOld==0 || pOld==p );
66664  freeIndex(p);
66665}
66666
66667/*
66668** For the index called zIdxName which is found in the database iDb,
66669** unlike that index from its Table then remove the index from
66670** the index hash table and free all memory structures associated
66671** with the index.
66672*/
66673SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
66674  Index *pIndex;
66675  int len;
66676  Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
66677
66678  len = sqlite3Strlen30(zIdxName);
66679  pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
66680  if( pIndex ){
66681    if( pIndex->pTable->pIndex==pIndex ){
66682      pIndex->pTable->pIndex = pIndex->pNext;
66683    }else{
66684      Index *p;
66685      /* Justification of ALWAYS();  The index must be on the list of
66686      ** indices. */
66687      p = pIndex->pTable->pIndex;
66688      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
66689      if( ALWAYS(p && p->pNext==pIndex) ){
66690        p->pNext = pIndex->pNext;
66691      }
66692    }
66693    freeIndex(pIndex);
66694  }
66695  db->flags |= SQLITE_InternChanges;
66696}
66697
66698/*
66699** Erase all schema information from the in-memory hash tables of
66700** a single database.  This routine is called to reclaim memory
66701** before the database closes.  It is also called during a rollback
66702** if there were schema changes during the transaction or if a
66703** schema-cookie mismatch occurs.
66704**
66705** If iDb==0 then reset the internal schema tables for all database
66706** files.  If iDb>=1 then reset the internal schema for only the
66707** single file indicated.
66708*/
66709SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
66710  int i, j;
66711  assert( iDb>=0 && iDb<db->nDb );
66712
66713  if( iDb==0 ){
66714    sqlite3BtreeEnterAll(db);
66715  }
66716  for(i=iDb; i<db->nDb; i++){
66717    Db *pDb = &db->aDb[i];
66718    if( pDb->pSchema ){
66719      assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
66720      sqlite3SchemaFree(pDb->pSchema);
66721    }
66722    if( iDb>0 ) return;
66723  }
66724  assert( iDb==0 );
66725  db->flags &= ~SQLITE_InternChanges;
66726  sqlite3VtabUnlockList(db);
66727  sqlite3BtreeLeaveAll(db);
66728
66729  /* If one or more of the auxiliary database files has been closed,
66730  ** then remove them from the auxiliary database list.  We take the
66731  ** opportunity to do this here since we have just deleted all of the
66732  ** schema hash tables and therefore do not have to make any changes
66733  ** to any of those tables.
66734  */
66735  for(i=j=2; i<db->nDb; i++){
66736    struct Db *pDb = &db->aDb[i];
66737    if( pDb->pBt==0 ){
66738      sqlite3DbFree(db, pDb->zName);
66739      pDb->zName = 0;
66740      continue;
66741    }
66742    if( j<i ){
66743      db->aDb[j] = db->aDb[i];
66744    }
66745    j++;
66746  }
66747  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
66748  db->nDb = j;
66749  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
66750    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
66751    sqlite3DbFree(db, db->aDb);
66752    db->aDb = db->aDbStatic;
66753  }
66754}
66755
66756/*
66757** This routine is called when a commit occurs.
66758*/
66759SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
66760  db->flags &= ~SQLITE_InternChanges;
66761}
66762
66763/*
66764** Clear the column names from a table or view.
66765*/
66766static void sqliteResetColumnNames(Table *pTable){
66767  int i;
66768  Column *pCol;
66769  sqlite3 *db = pTable->dbMem;
66770  testcase( db==0 );
66771  assert( pTable!=0 );
66772  if( (pCol = pTable->aCol)!=0 ){
66773    for(i=0; i<pTable->nCol; i++, pCol++){
66774      sqlite3DbFree(db, pCol->zName);
66775      sqlite3ExprDelete(db, pCol->pDflt);
66776      sqlite3DbFree(db, pCol->zDflt);
66777      sqlite3DbFree(db, pCol->zType);
66778      sqlite3DbFree(db, pCol->zColl);
66779    }
66780    sqlite3DbFree(db, pTable->aCol);
66781  }
66782  pTable->aCol = 0;
66783  pTable->nCol = 0;
66784}
66785
66786/*
66787** Remove the memory data structures associated with the given
66788** Table.  No changes are made to disk by this routine.
66789**
66790** This routine just deletes the data structure.  It does not unlink
66791** the table data structure from the hash table.  But it does destroy
66792** memory structures of the indices and foreign keys associated with
66793** the table.
66794*/
66795SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
66796  Index *pIndex, *pNext;
66797  sqlite3 *db;
66798
66799  if( pTable==0 ) return;
66800  db = pTable->dbMem;
66801  testcase( db==0 );
66802
66803  /* Do not delete the table until the reference count reaches zero. */
66804  pTable->nRef--;
66805  if( pTable->nRef>0 ){
66806    return;
66807  }
66808  assert( pTable->nRef==0 );
66809
66810  /* Delete all indices associated with this table
66811  */
66812  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
66813    pNext = pIndex->pNext;
66814    assert( pIndex->pSchema==pTable->pSchema );
66815    sqlite3DeleteIndex(pIndex);
66816  }
66817
66818  /* Delete any foreign keys attached to this table. */
66819  sqlite3FkDelete(pTable);
66820
66821  /* Delete the Table structure itself.
66822  */
66823  sqliteResetColumnNames(pTable);
66824  sqlite3DbFree(db, pTable->zName);
66825  sqlite3DbFree(db, pTable->zColAff);
66826  sqlite3SelectDelete(db, pTable->pSelect);
66827#ifndef SQLITE_OMIT_CHECK
66828  sqlite3ExprDelete(db, pTable->pCheck);
66829#endif
66830  sqlite3VtabClear(pTable);
66831  sqlite3DbFree(db, pTable);
66832}
66833
66834/*
66835** Unlink the given table from the hash tables and the delete the
66836** table structure with all its indices and foreign keys.
66837*/
66838SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
66839  Table *p;
66840  Db *pDb;
66841
66842  assert( db!=0 );
66843  assert( iDb>=0 && iDb<db->nDb );
66844  assert( zTabName );
66845  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
66846  pDb = &db->aDb[iDb];
66847  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
66848                        sqlite3Strlen30(zTabName),0);
66849  sqlite3DeleteTable(p);
66850  db->flags |= SQLITE_InternChanges;
66851}
66852
66853/*
66854** Given a token, return a string that consists of the text of that
66855** token.  Space to hold the returned string
66856** is obtained from sqliteMalloc() and must be freed by the calling
66857** function.
66858**
66859** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
66860** surround the body of the token are removed.
66861**
66862** Tokens are often just pointers into the original SQL text and so
66863** are not \000 terminated and are not persistent.  The returned string
66864** is \000 terminated and is persistent.
66865*/
66866SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
66867  char *zName;
66868  if( pName ){
66869    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
66870    sqlite3Dequote(zName);
66871  }else{
66872    zName = 0;
66873  }
66874  return zName;
66875}
66876
66877/*
66878** Open the sqlite_master table stored in database number iDb for
66879** writing. The table is opened using cursor 0.
66880*/
66881SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
66882  Vdbe *v = sqlite3GetVdbe(p);
66883  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
66884  sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
66885  sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
66886  if( p->nTab==0 ){
66887    p->nTab = 1;
66888  }
66889}
66890
66891/*
66892** Parameter zName points to a nul-terminated buffer containing the name
66893** of a database ("main", "temp" or the name of an attached db). This
66894** function returns the index of the named database in db->aDb[], or
66895** -1 if the named db cannot be found.
66896*/
66897SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
66898  int i = -1;         /* Database number */
66899  if( zName ){
66900    Db *pDb;
66901    int n = sqlite3Strlen30(zName);
66902    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
66903      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
66904          0==sqlite3StrICmp(pDb->zName, zName) ){
66905        break;
66906      }
66907    }
66908  }
66909  return i;
66910}
66911
66912/*
66913** The token *pName contains the name of a database (either "main" or
66914** "temp" or the name of an attached db). This routine returns the
66915** index of the named database in db->aDb[], or -1 if the named db
66916** does not exist.
66917*/
66918SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
66919  int i;                               /* Database number */
66920  char *zName;                         /* Name we are searching for */
66921  zName = sqlite3NameFromToken(db, pName);
66922  i = sqlite3FindDbName(db, zName);
66923  sqlite3DbFree(db, zName);
66924  return i;
66925}
66926
66927/* The table or view or trigger name is passed to this routine via tokens
66928** pName1 and pName2. If the table name was fully qualified, for example:
66929**
66930** CREATE TABLE xxx.yyy (...);
66931**
66932** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
66933** the table name is not fully qualified, i.e.:
66934**
66935** CREATE TABLE yyy(...);
66936**
66937** Then pName1 is set to "yyy" and pName2 is "".
66938**
66939** This routine sets the *ppUnqual pointer to point at the token (pName1 or
66940** pName2) that stores the unqualified table name.  The index of the
66941** database "xxx" is returned.
66942*/
66943SQLITE_PRIVATE int sqlite3TwoPartName(
66944  Parse *pParse,      /* Parsing and code generating context */
66945  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
66946  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
66947  Token **pUnqual     /* Write the unqualified object name here */
66948){
66949  int iDb;                    /* Database holding the object */
66950  sqlite3 *db = pParse->db;
66951
66952  if( ALWAYS(pName2!=0) && pName2->n>0 ){
66953    if( db->init.busy ) {
66954      sqlite3ErrorMsg(pParse, "corrupt database");
66955      pParse->nErr++;
66956      return -1;
66957    }
66958    *pUnqual = pName2;
66959    iDb = sqlite3FindDb(db, pName1);
66960    if( iDb<0 ){
66961      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
66962      pParse->nErr++;
66963      return -1;
66964    }
66965  }else{
66966    assert( db->init.iDb==0 || db->init.busy );
66967    iDb = db->init.iDb;
66968    *pUnqual = pName1;
66969  }
66970  return iDb;
66971}
66972
66973/*
66974** This routine is used to check if the UTF-8 string zName is a legal
66975** unqualified name for a new schema object (table, index, view or
66976** trigger). All names are legal except those that begin with the string
66977** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
66978** is reserved for internal use.
66979*/
66980SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
66981  if( !pParse->db->init.busy && pParse->nested==0
66982          && (pParse->db->flags & SQLITE_WriteSchema)==0
66983          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
66984    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
66985    return SQLITE_ERROR;
66986  }
66987  return SQLITE_OK;
66988}
66989
66990/*
66991** Begin constructing a new table representation in memory.  This is
66992** the first of several action routines that get called in response
66993** to a CREATE TABLE statement.  In particular, this routine is called
66994** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
66995** flag is true if the table should be stored in the auxiliary database
66996** file instead of in the main database file.  This is normally the case
66997** when the "TEMP" or "TEMPORARY" keyword occurs in between
66998** CREATE and TABLE.
66999**
67000** The new table record is initialized and put in pParse->pNewTable.
67001** As more of the CREATE TABLE statement is parsed, additional action
67002** routines will be called to add more information to this record.
67003** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
67004** is called to complete the construction of the new table record.
67005*/
67006SQLITE_PRIVATE void sqlite3StartTable(
67007  Parse *pParse,   /* Parser context */
67008  Token *pName1,   /* First part of the name of the table or view */
67009  Token *pName2,   /* Second part of the name of the table or view */
67010  int isTemp,      /* True if this is a TEMP table */
67011  int isView,      /* True if this is a VIEW */
67012  int isVirtual,   /* True if this is a VIRTUAL table */
67013  int noErr        /* Do nothing if table already exists */
67014){
67015  Table *pTable;
67016  char *zName = 0; /* The name of the new table */
67017  sqlite3 *db = pParse->db;
67018  Vdbe *v;
67019  int iDb;         /* Database number to create the table in */
67020  Token *pName;    /* Unqualified name of the table to create */
67021
67022  /* The table or view name to create is passed to this routine via tokens
67023  ** pName1 and pName2. If the table name was fully qualified, for example:
67024  **
67025  ** CREATE TABLE xxx.yyy (...);
67026  **
67027  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
67028  ** the table name is not fully qualified, i.e.:
67029  **
67030  ** CREATE TABLE yyy(...);
67031  **
67032  ** Then pName1 is set to "yyy" and pName2 is "".
67033  **
67034  ** The call below sets the pName pointer to point at the token (pName1 or
67035  ** pName2) that stores the unqualified table name. The variable iDb is
67036  ** set to the index of the database that the table or view is to be
67037  ** created in.
67038  */
67039  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
67040  if( iDb<0 ) return;
67041  if( !OMIT_TEMPDB && isTemp && iDb>1 ){
67042    /* If creating a temp table, the name may not be qualified */
67043    sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
67044    return;
67045  }
67046  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
67047
67048  pParse->sNameToken = *pName;
67049  zName = sqlite3NameFromToken(db, pName);
67050  if( zName==0 ) return;
67051  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
67052    goto begin_table_error;
67053  }
67054  if( db->init.iDb==1 ) isTemp = 1;
67055#ifndef SQLITE_OMIT_AUTHORIZATION
67056  assert( (isTemp & 1)==isTemp );
67057  {
67058    int code;
67059    char *zDb = db->aDb[iDb].zName;
67060    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
67061      goto begin_table_error;
67062    }
67063    if( isView ){
67064      if( !OMIT_TEMPDB && isTemp ){
67065        code = SQLITE_CREATE_TEMP_VIEW;
67066      }else{
67067        code = SQLITE_CREATE_VIEW;
67068      }
67069    }else{
67070      if( !OMIT_TEMPDB && isTemp ){
67071        code = SQLITE_CREATE_TEMP_TABLE;
67072      }else{
67073        code = SQLITE_CREATE_TABLE;
67074      }
67075    }
67076    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
67077      goto begin_table_error;
67078    }
67079  }
67080#endif
67081
67082  /* Make sure the new table name does not collide with an existing
67083  ** index or table name in the same database.  Issue an error message if
67084  ** it does. The exception is if the statement being parsed was passed
67085  ** to an sqlite3_declare_vtab() call. In that case only the column names
67086  ** and types will be used, so there is no need to test for namespace
67087  ** collisions.
67088  */
67089  if( !IN_DECLARE_VTAB ){
67090    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
67091      goto begin_table_error;
67092    }
67093    pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
67094    if( pTable ){
67095      if( !noErr ){
67096        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
67097      }
67098      goto begin_table_error;
67099    }
67100    if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
67101      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
67102      goto begin_table_error;
67103    }
67104  }
67105
67106  pTable = sqlite3DbMallocZero(db, sizeof(Table));
67107  if( pTable==0 ){
67108    db->mallocFailed = 1;
67109    pParse->rc = SQLITE_NOMEM;
67110    pParse->nErr++;
67111    goto begin_table_error;
67112  }
67113  pTable->zName = zName;
67114  pTable->iPKey = -1;
67115  pTable->pSchema = db->aDb[iDb].pSchema;
67116  pTable->nRef = 1;
67117  pTable->dbMem = 0;
67118  assert( pParse->pNewTable==0 );
67119  pParse->pNewTable = pTable;
67120
67121  /* If this is the magic sqlite_sequence table used by autoincrement,
67122  ** then record a pointer to this table in the main database structure
67123  ** so that INSERT can find the table easily.
67124  */
67125#ifndef SQLITE_OMIT_AUTOINCREMENT
67126  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
67127    pTable->pSchema->pSeqTab = pTable;
67128  }
67129#endif
67130
67131  /* Begin generating the code that will insert the table record into
67132  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
67133  ** and allocate the record number for the table entry now.  Before any
67134  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
67135  ** indices to be created and the table record must come before the
67136  ** indices.  Hence, the record number for the table must be allocated
67137  ** now.
67138  */
67139  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
67140    int j1;
67141    int fileFormat;
67142    int reg1, reg2, reg3;
67143    sqlite3BeginWriteOperation(pParse, 0, iDb);
67144
67145#ifndef SQLITE_OMIT_VIRTUALTABLE
67146    if( isVirtual ){
67147      sqlite3VdbeAddOp0(v, OP_VBegin);
67148    }
67149#endif
67150
67151    /* If the file format and encoding in the database have not been set,
67152    ** set them now.
67153    */
67154    reg1 = pParse->regRowid = ++pParse->nMem;
67155    reg2 = pParse->regRoot = ++pParse->nMem;
67156    reg3 = ++pParse->nMem;
67157    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
67158    sqlite3VdbeUsesBtree(v, iDb);
67159    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
67160    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
67161                  1 : SQLITE_MAX_FILE_FORMAT;
67162    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
67163    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
67164    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
67165    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
67166    sqlite3VdbeJumpHere(v, j1);
67167
67168    /* This just creates a place-holder record in the sqlite_master table.
67169    ** The record created does not contain anything yet.  It will be replaced
67170    ** by the real entry in code generated at sqlite3EndTable().
67171    **
67172    ** The rowid for the new entry is left in register pParse->regRowid.
67173    ** The root page number of the new table is left in reg pParse->regRoot.
67174    ** The rowid and root page number values are needed by the code that
67175    ** sqlite3EndTable will generate.
67176    */
67177#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
67178    if( isView || isVirtual ){
67179      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
67180    }else
67181#endif
67182    {
67183      sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
67184    }
67185    sqlite3OpenMasterTable(pParse, iDb);
67186    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
67187    sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
67188    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
67189    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
67190    sqlite3VdbeAddOp0(v, OP_Close);
67191  }
67192
67193  /* Normal (non-error) return. */
67194  return;
67195
67196  /* If an error occurs, we jump here */
67197begin_table_error:
67198  sqlite3DbFree(db, zName);
67199  return;
67200}
67201
67202/*
67203** This macro is used to compare two strings in a case-insensitive manner.
67204** It is slightly faster than calling sqlite3StrICmp() directly, but
67205** produces larger code.
67206**
67207** WARNING: This macro is not compatible with the strcmp() family. It
67208** returns true if the two strings are equal, otherwise false.
67209*/
67210#define STRICMP(x, y) (\
67211sqlite3UpperToLower[*(unsigned char *)(x)]==   \
67212sqlite3UpperToLower[*(unsigned char *)(y)]     \
67213&& sqlite3StrICmp((x)+1,(y)+1)==0 )
67214
67215/*
67216** Add a new column to the table currently being constructed.
67217**
67218** The parser calls this routine once for each column declaration
67219** in a CREATE TABLE statement.  sqlite3StartTable() gets called
67220** first to get things going.  Then this routine is called for each
67221** column.
67222*/
67223SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
67224  Table *p;
67225  int i;
67226  char *z;
67227  Column *pCol;
67228  sqlite3 *db = pParse->db;
67229  if( (p = pParse->pNewTable)==0 ) return;
67230#if SQLITE_MAX_COLUMN
67231  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
67232    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
67233    return;
67234  }
67235#endif
67236  z = sqlite3NameFromToken(db, pName);
67237  if( z==0 ) return;
67238  for(i=0; i<p->nCol; i++){
67239    if( STRICMP(z, p->aCol[i].zName) ){
67240      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
67241      sqlite3DbFree(db, z);
67242      return;
67243    }
67244  }
67245  if( (p->nCol & 0x7)==0 ){
67246    Column *aNew;
67247    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
67248    if( aNew==0 ){
67249      sqlite3DbFree(db, z);
67250      return;
67251    }
67252    p->aCol = aNew;
67253  }
67254  pCol = &p->aCol[p->nCol];
67255  memset(pCol, 0, sizeof(p->aCol[0]));
67256  pCol->zName = z;
67257
67258  /* If there is no type specified, columns have the default affinity
67259  ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
67260  ** be called next to set pCol->affinity correctly.
67261  */
67262  pCol->affinity = SQLITE_AFF_NONE;
67263  p->nCol++;
67264}
67265
67266/*
67267** This routine is called by the parser while in the middle of
67268** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
67269** been seen on a column.  This routine sets the notNull flag on
67270** the column currently under construction.
67271*/
67272SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
67273  Table *p;
67274  p = pParse->pNewTable;
67275  if( p==0 || NEVER(p->nCol<1) ) return;
67276  p->aCol[p->nCol-1].notNull = (u8)onError;
67277}
67278
67279/*
67280** Scan the column type name zType (length nType) and return the
67281** associated affinity type.
67282**
67283** This routine does a case-independent search of zType for the
67284** substrings in the following table. If one of the substrings is
67285** found, the corresponding affinity is returned. If zType contains
67286** more than one of the substrings, entries toward the top of
67287** the table take priority. For example, if zType is 'BLOBINT',
67288** SQLITE_AFF_INTEGER is returned.
67289**
67290** Substring     | Affinity
67291** --------------------------------
67292** 'INT'         | SQLITE_AFF_INTEGER
67293** 'CHAR'        | SQLITE_AFF_TEXT
67294** 'CLOB'        | SQLITE_AFF_TEXT
67295** 'TEXT'        | SQLITE_AFF_TEXT
67296** 'BLOB'        | SQLITE_AFF_NONE
67297** 'REAL'        | SQLITE_AFF_REAL
67298** 'FLOA'        | SQLITE_AFF_REAL
67299** 'DOUB'        | SQLITE_AFF_REAL
67300**
67301** If none of the substrings in the above table are found,
67302** SQLITE_AFF_NUMERIC is returned.
67303*/
67304SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
67305  u32 h = 0;
67306  char aff = SQLITE_AFF_NUMERIC;
67307
67308  if( zIn ) while( zIn[0] ){
67309    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
67310    zIn++;
67311    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
67312      aff = SQLITE_AFF_TEXT;
67313    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
67314      aff = SQLITE_AFF_TEXT;
67315    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
67316      aff = SQLITE_AFF_TEXT;
67317    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
67318        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
67319      aff = SQLITE_AFF_NONE;
67320#ifndef SQLITE_OMIT_FLOATING_POINT
67321    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
67322        && aff==SQLITE_AFF_NUMERIC ){
67323      aff = SQLITE_AFF_REAL;
67324    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
67325        && aff==SQLITE_AFF_NUMERIC ){
67326      aff = SQLITE_AFF_REAL;
67327    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
67328        && aff==SQLITE_AFF_NUMERIC ){
67329      aff = SQLITE_AFF_REAL;
67330#endif
67331    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
67332      aff = SQLITE_AFF_INTEGER;
67333      break;
67334    }
67335  }
67336
67337  return aff;
67338}
67339
67340/*
67341** This routine is called by the parser while in the middle of
67342** parsing a CREATE TABLE statement.  The pFirst token is the first
67343** token in the sequence of tokens that describe the type of the
67344** column currently under construction.   pLast is the last token
67345** in the sequence.  Use this information to construct a string
67346** that contains the typename of the column and store that string
67347** in zType.
67348*/
67349SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
67350  Table *p;
67351  Column *pCol;
67352
67353  p = pParse->pNewTable;
67354  if( p==0 || NEVER(p->nCol<1) ) return;
67355  pCol = &p->aCol[p->nCol-1];
67356  assert( pCol->zType==0 );
67357  pCol->zType = sqlite3NameFromToken(pParse->db, pType);
67358  pCol->affinity = sqlite3AffinityType(pCol->zType);
67359}
67360
67361/*
67362** The expression is the default value for the most recently added column
67363** of the table currently under construction.
67364**
67365** Default value expressions must be constant.  Raise an exception if this
67366** is not the case.
67367**
67368** This routine is called by the parser while in the middle of
67369** parsing a CREATE TABLE statement.
67370*/
67371SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
67372  Table *p;
67373  Column *pCol;
67374  sqlite3 *db = pParse->db;
67375  p = pParse->pNewTable;
67376  if( p!=0 ){
67377    pCol = &(p->aCol[p->nCol-1]);
67378    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
67379      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
67380          pCol->zName);
67381    }else{
67382      /* A copy of pExpr is used instead of the original, as pExpr contains
67383      ** tokens that point to volatile memory. The 'span' of the expression
67384      ** is required by pragma table_info.
67385      */
67386      sqlite3ExprDelete(db, pCol->pDflt);
67387      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
67388      sqlite3DbFree(db, pCol->zDflt);
67389      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
67390                                     (int)(pSpan->zEnd - pSpan->zStart));
67391    }
67392  }
67393  sqlite3ExprDelete(db, pSpan->pExpr);
67394}
67395
67396/*
67397** Designate the PRIMARY KEY for the table.  pList is a list of names
67398** of columns that form the primary key.  If pList is NULL, then the
67399** most recently added column of the table is the primary key.
67400**
67401** A table can have at most one primary key.  If the table already has
67402** a primary key (and this is the second primary key) then create an
67403** error.
67404**
67405** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
67406** then we will try to use that column as the rowid.  Set the Table.iPKey
67407** field of the table under construction to be the index of the
67408** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
67409** no INTEGER PRIMARY KEY.
67410**
67411** If the key is not an INTEGER PRIMARY KEY, then create a unique
67412** index for the key.  No index is created for INTEGER PRIMARY KEYs.
67413*/
67414SQLITE_PRIVATE void sqlite3AddPrimaryKey(
67415  Parse *pParse,    /* Parsing context */
67416  ExprList *pList,  /* List of field names to be indexed */
67417  int onError,      /* What to do with a uniqueness conflict */
67418  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
67419  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
67420){
67421  Table *pTab = pParse->pNewTable;
67422  char *zType = 0;
67423  int iCol = -1, i;
67424  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
67425  if( pTab->tabFlags & TF_HasPrimaryKey ){
67426    sqlite3ErrorMsg(pParse,
67427      "table \"%s\" has more than one primary key", pTab->zName);
67428    goto primary_key_exit;
67429  }
67430  pTab->tabFlags |= TF_HasPrimaryKey;
67431  if( pList==0 ){
67432    iCol = pTab->nCol - 1;
67433    pTab->aCol[iCol].isPrimKey = 1;
67434  }else{
67435    for(i=0; i<pList->nExpr; i++){
67436      for(iCol=0; iCol<pTab->nCol; iCol++){
67437        if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
67438          break;
67439        }
67440      }
67441      if( iCol<pTab->nCol ){
67442        pTab->aCol[iCol].isPrimKey = 1;
67443      }
67444    }
67445    if( pList->nExpr>1 ) iCol = -1;
67446  }
67447  if( iCol>=0 && iCol<pTab->nCol ){
67448    zType = pTab->aCol[iCol].zType;
67449  }
67450  if( zType && sqlite3StrICmp(zType, "INTEGER")==0
67451        && sortOrder==SQLITE_SO_ASC ){
67452    pTab->iPKey = iCol;
67453    pTab->keyConf = (u8)onError;
67454    assert( autoInc==0 || autoInc==1 );
67455    pTab->tabFlags |= autoInc*TF_Autoincrement;
67456  }else if( autoInc ){
67457#ifndef SQLITE_OMIT_AUTOINCREMENT
67458    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
67459       "INTEGER PRIMARY KEY");
67460#endif
67461  }else{
67462    Index *p;
67463    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
67464    if( p ){
67465      p->autoIndex = 2;
67466    }
67467    pList = 0;
67468  }
67469
67470primary_key_exit:
67471  sqlite3ExprListDelete(pParse->db, pList);
67472  return;
67473}
67474
67475/*
67476** Add a new CHECK constraint to the table currently under construction.
67477*/
67478SQLITE_PRIVATE void sqlite3AddCheckConstraint(
67479  Parse *pParse,    /* Parsing context */
67480  Expr *pCheckExpr  /* The check expression */
67481){
67482  sqlite3 *db = pParse->db;
67483#ifndef SQLITE_OMIT_CHECK
67484  Table *pTab = pParse->pNewTable;
67485  if( pTab && !IN_DECLARE_VTAB ){
67486    pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
67487  }else
67488#endif
67489  {
67490    sqlite3ExprDelete(db, pCheckExpr);
67491  }
67492}
67493
67494/*
67495** Set the collation function of the most recently parsed table column
67496** to the CollSeq given.
67497*/
67498SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
67499  Table *p;
67500  int i;
67501  char *zColl;              /* Dequoted name of collation sequence */
67502  sqlite3 *db;
67503
67504  if( (p = pParse->pNewTable)==0 ) return;
67505  i = p->nCol-1;
67506  db = pParse->db;
67507  zColl = sqlite3NameFromToken(db, pToken);
67508  if( !zColl ) return;
67509
67510  if( sqlite3LocateCollSeq(pParse, zColl) ){
67511    Index *pIdx;
67512    p->aCol[i].zColl = zColl;
67513
67514    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
67515    ** then an index may have been created on this column before the
67516    ** collation type was added. Correct this if it is the case.
67517    */
67518    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
67519      assert( pIdx->nColumn==1 );
67520      if( pIdx->aiColumn[0]==i ){
67521        pIdx->azColl[0] = p->aCol[i].zColl;
67522      }
67523    }
67524  }else{
67525    sqlite3DbFree(db, zColl);
67526  }
67527}
67528
67529/*
67530** This function returns the collation sequence for database native text
67531** encoding identified by the string zName, length nName.
67532**
67533** If the requested collation sequence is not available, or not available
67534** in the database native encoding, the collation factory is invoked to
67535** request it. If the collation factory does not supply such a sequence,
67536** and the sequence is available in another text encoding, then that is
67537** returned instead.
67538**
67539** If no versions of the requested collations sequence are available, or
67540** another error occurs, NULL is returned and an error message written into
67541** pParse.
67542**
67543** This routine is a wrapper around sqlite3FindCollSeq().  This routine
67544** invokes the collation factory if the named collation cannot be found
67545** and generates an error message.
67546**
67547** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
67548*/
67549SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
67550  sqlite3 *db = pParse->db;
67551  u8 enc = ENC(db);
67552  u8 initbusy = db->init.busy;
67553  CollSeq *pColl;
67554
67555  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
67556  if( !initbusy && (!pColl || !pColl->xCmp) ){
67557    pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
67558    if( !pColl ){
67559      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
67560    }
67561  }
67562
67563  return pColl;
67564}
67565
67566
67567/*
67568** Generate code that will increment the schema cookie.
67569**
67570** The schema cookie is used to determine when the schema for the
67571** database changes.  After each schema change, the cookie value
67572** changes.  When a process first reads the schema it records the
67573** cookie.  Thereafter, whenever it goes to access the database,
67574** it checks the cookie to make sure the schema has not changed
67575** since it was last read.
67576**
67577** This plan is not completely bullet-proof.  It is possible for
67578** the schema to change multiple times and for the cookie to be
67579** set back to prior value.  But schema changes are infrequent
67580** and the probability of hitting the same cookie value is only
67581** 1 chance in 2^32.  So we're safe enough.
67582*/
67583SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
67584  int r1 = sqlite3GetTempReg(pParse);
67585  sqlite3 *db = pParse->db;
67586  Vdbe *v = pParse->pVdbe;
67587  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
67588  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
67589  sqlite3ReleaseTempReg(pParse, r1);
67590}
67591
67592/*
67593** Measure the number of characters needed to output the given
67594** identifier.  The number returned includes any quotes used
67595** but does not include the null terminator.
67596**
67597** The estimate is conservative.  It might be larger that what is
67598** really needed.
67599*/
67600static int identLength(const char *z){
67601  int n;
67602  for(n=0; *z; n++, z++){
67603    if( *z=='"' ){ n++; }
67604  }
67605  return n + 2;
67606}
67607
67608/*
67609** The first parameter is a pointer to an output buffer. The second
67610** parameter is a pointer to an integer that contains the offset at
67611** which to write into the output buffer. This function copies the
67612** nul-terminated string pointed to by the third parameter, zSignedIdent,
67613** to the specified offset in the buffer and updates *pIdx to refer
67614** to the first byte after the last byte written before returning.
67615**
67616** If the string zSignedIdent consists entirely of alpha-numeric
67617** characters, does not begin with a digit and is not an SQL keyword,
67618** then it is copied to the output buffer exactly as it is. Otherwise,
67619** it is quoted using double-quotes.
67620*/
67621static void identPut(char *z, int *pIdx, char *zSignedIdent){
67622  unsigned char *zIdent = (unsigned char*)zSignedIdent;
67623  int i, j, needQuote;
67624  i = *pIdx;
67625
67626  for(j=0; zIdent[j]; j++){
67627    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
67628  }
67629  needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
67630  if( !needQuote ){
67631    needQuote = zIdent[j];
67632  }
67633
67634  if( needQuote ) z[i++] = '"';
67635  for(j=0; zIdent[j]; j++){
67636    z[i++] = zIdent[j];
67637    if( zIdent[j]=='"' ) z[i++] = '"';
67638  }
67639  if( needQuote ) z[i++] = '"';
67640  z[i] = 0;
67641  *pIdx = i;
67642}
67643
67644/*
67645** Generate a CREATE TABLE statement appropriate for the given
67646** table.  Memory to hold the text of the statement is obtained
67647** from sqliteMalloc() and must be freed by the calling function.
67648*/
67649static char *createTableStmt(sqlite3 *db, Table *p){
67650  int i, k, n;
67651  char *zStmt;
67652  char *zSep, *zSep2, *zEnd;
67653  Column *pCol;
67654  n = 0;
67655  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
67656    n += identLength(pCol->zName) + 5;
67657  }
67658  n += identLength(p->zName);
67659  if( n<50 ){
67660    zSep = "";
67661    zSep2 = ",";
67662    zEnd = ")";
67663  }else{
67664    zSep = "\n  ";
67665    zSep2 = ",\n  ";
67666    zEnd = "\n)";
67667  }
67668  n += 35 + 6*p->nCol;
67669  zStmt = sqlite3Malloc( n );
67670  if( zStmt==0 ){
67671    db->mallocFailed = 1;
67672    return 0;
67673  }
67674  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
67675  k = sqlite3Strlen30(zStmt);
67676  identPut(zStmt, &k, p->zName);
67677  zStmt[k++] = '(';
67678  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
67679    static const char * const azType[] = {
67680        /* SQLITE_AFF_TEXT    */ " TEXT",
67681        /* SQLITE_AFF_NONE    */ "",
67682        /* SQLITE_AFF_NUMERIC */ " NUM",
67683        /* SQLITE_AFF_INTEGER */ " INT",
67684        /* SQLITE_AFF_REAL    */ " REAL"
67685    };
67686    int len;
67687    const char *zType;
67688
67689    sqlite3_snprintf(n-k, &zStmt[k], zSep);
67690    k += sqlite3Strlen30(&zStmt[k]);
67691    zSep = zSep2;
67692    identPut(zStmt, &k, pCol->zName);
67693    assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
67694    assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
67695    testcase( pCol->affinity==SQLITE_AFF_TEXT );
67696    testcase( pCol->affinity==SQLITE_AFF_NONE );
67697    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
67698    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
67699    testcase( pCol->affinity==SQLITE_AFF_REAL );
67700
67701    zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
67702    len = sqlite3Strlen30(zType);
67703    assert( pCol->affinity==SQLITE_AFF_NONE
67704            || pCol->affinity==sqlite3AffinityType(zType) );
67705    memcpy(&zStmt[k], zType, len);
67706    k += len;
67707    assert( k<=n );
67708  }
67709  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
67710  return zStmt;
67711}
67712
67713/*
67714** This routine is called to report the final ")" that terminates
67715** a CREATE TABLE statement.
67716**
67717** The table structure that other action routines have been building
67718** is added to the internal hash tables, assuming no errors have
67719** occurred.
67720**
67721** An entry for the table is made in the master table on disk, unless
67722** this is a temporary table or db->init.busy==1.  When db->init.busy==1
67723** it means we are reading the sqlite_master table because we just
67724** connected to the database or because the sqlite_master table has
67725** recently changed, so the entry for this table already exists in
67726** the sqlite_master table.  We do not want to create it again.
67727**
67728** If the pSelect argument is not NULL, it means that this routine
67729** was called to create a table generated from a
67730** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
67731** the new table will match the result set of the SELECT.
67732*/
67733SQLITE_PRIVATE void sqlite3EndTable(
67734  Parse *pParse,          /* Parse context */
67735  Token *pCons,           /* The ',' token after the last column defn. */
67736  Token *pEnd,            /* The final ')' token in the CREATE TABLE */
67737  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
67738){
67739  Table *p;
67740  sqlite3 *db = pParse->db;
67741  int iDb;
67742
67743  if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
67744    return;
67745  }
67746  p = pParse->pNewTable;
67747  if( p==0 ) return;
67748
67749  assert( !db->init.busy || !pSelect );
67750
67751  iDb = sqlite3SchemaToIndex(db, p->pSchema);
67752
67753#ifndef SQLITE_OMIT_CHECK
67754  /* Resolve names in all CHECK constraint expressions.
67755  */
67756  if( p->pCheck ){
67757    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
67758    NameContext sNC;                /* Name context for pParse->pNewTable */
67759
67760    memset(&sNC, 0, sizeof(sNC));
67761    memset(&sSrc, 0, sizeof(sSrc));
67762    sSrc.nSrc = 1;
67763    sSrc.a[0].zName = p->zName;
67764    sSrc.a[0].pTab = p;
67765    sSrc.a[0].iCursor = -1;
67766    sNC.pParse = pParse;
67767    sNC.pSrcList = &sSrc;
67768    sNC.isCheck = 1;
67769    if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
67770      return;
67771    }
67772  }
67773#endif /* !defined(SQLITE_OMIT_CHECK) */
67774
67775  /* If the db->init.busy is 1 it means we are reading the SQL off the
67776  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
67777  ** So do not write to the disk again.  Extract the root page number
67778  ** for the table from the db->init.newTnum field.  (The page number
67779  ** should have been put there by the sqliteOpenCb routine.)
67780  */
67781  if( db->init.busy ){
67782    p->tnum = db->init.newTnum;
67783  }
67784
67785  /* If not initializing, then create a record for the new table
67786  ** in the SQLITE_MASTER table of the database.
67787  **
67788  ** If this is a TEMPORARY table, write the entry into the auxiliary
67789  ** file instead of into the main database file.
67790  */
67791  if( !db->init.busy ){
67792    int n;
67793    Vdbe *v;
67794    char *zType;    /* "view" or "table" */
67795    char *zType2;   /* "VIEW" or "TABLE" */
67796    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
67797
67798    v = sqlite3GetVdbe(pParse);
67799    if( NEVER(v==0) ) return;
67800
67801    sqlite3VdbeAddOp1(v, OP_Close, 0);
67802
67803    /*
67804    ** Initialize zType for the new view or table.
67805    */
67806    if( p->pSelect==0 ){
67807      /* A regular table */
67808      zType = "table";
67809      zType2 = "TABLE";
67810#ifndef SQLITE_OMIT_VIEW
67811    }else{
67812      /* A view */
67813      zType = "view";
67814      zType2 = "VIEW";
67815#endif
67816    }
67817
67818    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
67819    ** statement to populate the new table. The root-page number for the
67820    ** new table is in register pParse->regRoot.
67821    **
67822    ** Once the SELECT has been coded by sqlite3Select(), it is in a
67823    ** suitable state to query for the column names and types to be used
67824    ** by the new table.
67825    **
67826    ** A shared-cache write-lock is not required to write to the new table,
67827    ** as a schema-lock must have already been obtained to create it. Since
67828    ** a schema-lock excludes all other database users, the write-lock would
67829    ** be redundant.
67830    */
67831    if( pSelect ){
67832      SelectDest dest;
67833      Table *pSelTab;
67834
67835      assert(pParse->nTab==1);
67836      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
67837      sqlite3VdbeChangeP5(v, 1);
67838      pParse->nTab = 2;
67839      sqlite3SelectDestInit(&dest, SRT_Table, 1);
67840      sqlite3Select(pParse, pSelect, &dest);
67841      sqlite3VdbeAddOp1(v, OP_Close, 1);
67842      if( pParse->nErr==0 ){
67843        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
67844        if( pSelTab==0 ) return;
67845        assert( p->aCol==0 );
67846        p->nCol = pSelTab->nCol;
67847        p->aCol = pSelTab->aCol;
67848        pSelTab->nCol = 0;
67849        pSelTab->aCol = 0;
67850        sqlite3DeleteTable(pSelTab);
67851      }
67852    }
67853
67854    /* Compute the complete text of the CREATE statement */
67855    if( pSelect ){
67856      zStmt = createTableStmt(db, p);
67857    }else{
67858      n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
67859      zStmt = sqlite3MPrintf(db,
67860          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
67861      );
67862    }
67863
67864    /* A slot for the record has already been allocated in the
67865    ** SQLITE_MASTER table.  We just need to update that slot with all
67866    ** the information we've collected.
67867    */
67868    sqlite3NestedParse(pParse,
67869      "UPDATE %Q.%s "
67870         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
67871       "WHERE rowid=#%d",
67872      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
67873      zType,
67874      p->zName,
67875      p->zName,
67876      pParse->regRoot,
67877      zStmt,
67878      pParse->regRowid
67879    );
67880    sqlite3DbFree(db, zStmt);
67881    sqlite3ChangeCookie(pParse, iDb);
67882
67883#ifndef SQLITE_OMIT_AUTOINCREMENT
67884    /* Check to see if we need to create an sqlite_sequence table for
67885    ** keeping track of autoincrement keys.
67886    */
67887    if( p->tabFlags & TF_Autoincrement ){
67888      Db *pDb = &db->aDb[iDb];
67889      if( pDb->pSchema->pSeqTab==0 ){
67890        sqlite3NestedParse(pParse,
67891          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
67892          pDb->zName
67893        );
67894      }
67895    }
67896#endif
67897
67898    /* Reparse everything to update our internal data structures */
67899    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
67900        sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
67901  }
67902
67903
67904  /* Add the table to the in-memory representation of the database.
67905  */
67906  if( db->init.busy ){
67907    Table *pOld;
67908    Schema *pSchema = p->pSchema;
67909    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
67910                             sqlite3Strlen30(p->zName),p);
67911    if( pOld ){
67912      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
67913      db->mallocFailed = 1;
67914      return;
67915    }
67916    pParse->pNewTable = 0;
67917    db->nTable++;
67918    db->flags |= SQLITE_InternChanges;
67919
67920#ifndef SQLITE_OMIT_ALTERTABLE
67921    if( !p->pSelect ){
67922      const char *zName = (const char *)pParse->sNameToken.z;
67923      int nName;
67924      assert( !pSelect && pCons && pEnd );
67925      if( pCons->z==0 ){
67926        pCons = pEnd;
67927      }
67928      nName = (int)((const char *)pCons->z - zName);
67929      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
67930    }
67931#endif
67932  }
67933}
67934
67935#ifndef SQLITE_OMIT_VIEW
67936/*
67937** The parser calls this routine in order to create a new VIEW
67938*/
67939SQLITE_PRIVATE void sqlite3CreateView(
67940  Parse *pParse,     /* The parsing context */
67941  Token *pBegin,     /* The CREATE token that begins the statement */
67942  Token *pName1,     /* The token that holds the name of the view */
67943  Token *pName2,     /* The token that holds the name of the view */
67944  Select *pSelect,   /* A SELECT statement that will become the new view */
67945  int isTemp,        /* TRUE for a TEMPORARY view */
67946  int noErr          /* Suppress error messages if VIEW already exists */
67947){
67948  Table *p;
67949  int n;
67950  const char *z;
67951  Token sEnd;
67952  DbFixer sFix;
67953  Token *pName;
67954  int iDb;
67955  sqlite3 *db = pParse->db;
67956
67957  if( pParse->nVar>0 ){
67958    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
67959    sqlite3SelectDelete(db, pSelect);
67960    return;
67961  }
67962  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
67963  p = pParse->pNewTable;
67964  if( p==0 ){
67965    sqlite3SelectDelete(db, pSelect);
67966    return;
67967  }
67968  assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
67969                             ** there could not have been an error */
67970  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
67971  iDb = sqlite3SchemaToIndex(db, p->pSchema);
67972  if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
67973    && sqlite3FixSelect(&sFix, pSelect)
67974  ){
67975    sqlite3SelectDelete(db, pSelect);
67976    return;
67977  }
67978
67979  /* Make a copy of the entire SELECT statement that defines the view.
67980  ** This will force all the Expr.token.z values to be dynamically
67981  ** allocated rather than point to the input string - which means that
67982  ** they will persist after the current sqlite3_exec() call returns.
67983  */
67984  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
67985  sqlite3SelectDelete(db, pSelect);
67986  if( db->mallocFailed ){
67987    return;
67988  }
67989  if( !db->init.busy ){
67990    sqlite3ViewGetColumnNames(pParse, p);
67991  }
67992
67993  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
67994  ** the end.
67995  */
67996  sEnd = pParse->sLastToken;
67997  if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
67998    sEnd.z += sEnd.n;
67999  }
68000  sEnd.n = 0;
68001  n = (int)(sEnd.z - pBegin->z);
68002  z = pBegin->z;
68003  while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
68004  sEnd.z = &z[n-1];
68005  sEnd.n = 1;
68006
68007  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
68008  sqlite3EndTable(pParse, 0, &sEnd, 0);
68009  return;
68010}
68011#endif /* SQLITE_OMIT_VIEW */
68012
68013#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
68014/*
68015** The Table structure pTable is really a VIEW.  Fill in the names of
68016** the columns of the view in the pTable structure.  Return the number
68017** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
68018*/
68019SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
68020  Table *pSelTab;   /* A fake table from which we get the result set */
68021  Select *pSel;     /* Copy of the SELECT that implements the view */
68022  int nErr = 0;     /* Number of errors encountered */
68023  int n;            /* Temporarily holds the number of cursors assigned */
68024  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
68025  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
68026
68027  assert( pTable );
68028
68029#ifndef SQLITE_OMIT_VIRTUALTABLE
68030  if( sqlite3VtabCallConnect(pParse, pTable) ){
68031    return SQLITE_ERROR;
68032  }
68033  if( IsVirtual(pTable) ) return 0;
68034#endif
68035
68036#ifndef SQLITE_OMIT_VIEW
68037  /* A positive nCol means the columns names for this view are
68038  ** already known.
68039  */
68040  if( pTable->nCol>0 ) return 0;
68041
68042  /* A negative nCol is a special marker meaning that we are currently
68043  ** trying to compute the column names.  If we enter this routine with
68044  ** a negative nCol, it means two or more views form a loop, like this:
68045  **
68046  **     CREATE VIEW one AS SELECT * FROM two;
68047  **     CREATE VIEW two AS SELECT * FROM one;
68048  **
68049  ** Actually, the error above is now caught prior to reaching this point.
68050  ** But the following test is still important as it does come up
68051  ** in the following:
68052  **
68053  **     CREATE TABLE main.ex1(a);
68054  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
68055  **     SELECT * FROM temp.ex1;
68056  */
68057  if( pTable->nCol<0 ){
68058    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
68059    return 1;
68060  }
68061  assert( pTable->nCol>=0 );
68062
68063  /* If we get this far, it means we need to compute the table names.
68064  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
68065  ** "*" elements in the results set of the view and will assign cursors
68066  ** to the elements of the FROM clause.  But we do not want these changes
68067  ** to be permanent.  So the computation is done on a copy of the SELECT
68068  ** statement that defines the view.
68069  */
68070  assert( pTable->pSelect );
68071  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
68072  if( pSel ){
68073    u8 enableLookaside = db->lookaside.bEnabled;
68074    n = pParse->nTab;
68075    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
68076    pTable->nCol = -1;
68077    db->lookaside.bEnabled = 0;
68078#ifndef SQLITE_OMIT_AUTHORIZATION
68079    xAuth = db->xAuth;
68080    db->xAuth = 0;
68081    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
68082    db->xAuth = xAuth;
68083#else
68084    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
68085#endif
68086    db->lookaside.bEnabled = enableLookaside;
68087    pParse->nTab = n;
68088    if( pSelTab ){
68089      assert( pTable->aCol==0 );
68090      pTable->nCol = pSelTab->nCol;
68091      pTable->aCol = pSelTab->aCol;
68092      pSelTab->nCol = 0;
68093      pSelTab->aCol = 0;
68094      sqlite3DeleteTable(pSelTab);
68095      pTable->pSchema->flags |= DB_UnresetViews;
68096    }else{
68097      pTable->nCol = 0;
68098      nErr++;
68099    }
68100    sqlite3SelectDelete(db, pSel);
68101  } else {
68102    nErr++;
68103  }
68104#endif /* SQLITE_OMIT_VIEW */
68105  return nErr;
68106}
68107#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
68108
68109#ifndef SQLITE_OMIT_VIEW
68110/*
68111** Clear the column names from every VIEW in database idx.
68112*/
68113static void sqliteViewResetAll(sqlite3 *db, int idx){
68114  HashElem *i;
68115  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
68116  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
68117    Table *pTab = sqliteHashData(i);
68118    if( pTab->pSelect ){
68119      sqliteResetColumnNames(pTab);
68120    }
68121  }
68122  DbClearProperty(db, idx, DB_UnresetViews);
68123}
68124#else
68125# define sqliteViewResetAll(A,B)
68126#endif /* SQLITE_OMIT_VIEW */
68127
68128/*
68129** This function is called by the VDBE to adjust the internal schema
68130** used by SQLite when the btree layer moves a table root page. The
68131** root-page of a table or index in database iDb has changed from iFrom
68132** to iTo.
68133**
68134** Ticket #1728:  The symbol table might still contain information
68135** on tables and/or indices that are the process of being deleted.
68136** If you are unlucky, one of those deleted indices or tables might
68137** have the same rootpage number as the real table or index that is
68138** being moved.  So we cannot stop searching after the first match
68139** because the first match might be for one of the deleted indices
68140** or tables and not the table/index that is actually being moved.
68141** We must continue looping until all tables and indices with
68142** rootpage==iFrom have been converted to have a rootpage of iTo
68143** in order to be certain that we got the right one.
68144*/
68145#ifndef SQLITE_OMIT_AUTOVACUUM
68146SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
68147  HashElem *pElem;
68148  Hash *pHash;
68149
68150  pHash = &pDb->pSchema->tblHash;
68151  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
68152    Table *pTab = sqliteHashData(pElem);
68153    if( pTab->tnum==iFrom ){
68154      pTab->tnum = iTo;
68155    }
68156  }
68157  pHash = &pDb->pSchema->idxHash;
68158  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
68159    Index *pIdx = sqliteHashData(pElem);
68160    if( pIdx->tnum==iFrom ){
68161      pIdx->tnum = iTo;
68162    }
68163  }
68164}
68165#endif
68166
68167/*
68168** Write code to erase the table with root-page iTable from database iDb.
68169** Also write code to modify the sqlite_master table and internal schema
68170** if a root-page of another table is moved by the btree-layer whilst
68171** erasing iTable (this can happen with an auto-vacuum database).
68172*/
68173static void destroyRootPage(Parse *pParse, int iTable, int iDb){
68174  Vdbe *v = sqlite3GetVdbe(pParse);
68175  int r1 = sqlite3GetTempReg(pParse);
68176  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
68177  sqlite3MayAbort(pParse);
68178#ifndef SQLITE_OMIT_AUTOVACUUM
68179  /* OP_Destroy stores an in integer r1. If this integer
68180  ** is non-zero, then it is the root page number of a table moved to
68181  ** location iTable. The following code modifies the sqlite_master table to
68182  ** reflect this.
68183  **
68184  ** The "#NNN" in the SQL is a special constant that means whatever value
68185  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
68186  ** token for additional information.
68187  */
68188  sqlite3NestedParse(pParse,
68189     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
68190     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
68191#endif
68192  sqlite3ReleaseTempReg(pParse, r1);
68193}
68194
68195/*
68196** Write VDBE code to erase table pTab and all associated indices on disk.
68197** Code to update the sqlite_master tables and internal schema definitions
68198** in case a root-page belonging to another table is moved by the btree layer
68199** is also added (this can happen with an auto-vacuum database).
68200*/
68201static void destroyTable(Parse *pParse, Table *pTab){
68202#ifdef SQLITE_OMIT_AUTOVACUUM
68203  Index *pIdx;
68204  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
68205  destroyRootPage(pParse, pTab->tnum, iDb);
68206  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68207    destroyRootPage(pParse, pIdx->tnum, iDb);
68208  }
68209#else
68210  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
68211  ** is not defined), then it is important to call OP_Destroy on the
68212  ** table and index root-pages in order, starting with the numerically
68213  ** largest root-page number. This guarantees that none of the root-pages
68214  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
68215  ** following were coded:
68216  **
68217  ** OP_Destroy 4 0
68218  ** ...
68219  ** OP_Destroy 5 0
68220  **
68221  ** and root page 5 happened to be the largest root-page number in the
68222  ** database, then root page 5 would be moved to page 4 by the
68223  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
68224  ** a free-list page.
68225  */
68226  int iTab = pTab->tnum;
68227  int iDestroyed = 0;
68228
68229  while( 1 ){
68230    Index *pIdx;
68231    int iLargest = 0;
68232
68233    if( iDestroyed==0 || iTab<iDestroyed ){
68234      iLargest = iTab;
68235    }
68236    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68237      int iIdx = pIdx->tnum;
68238      assert( pIdx->pSchema==pTab->pSchema );
68239      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
68240        iLargest = iIdx;
68241      }
68242    }
68243    if( iLargest==0 ){
68244      return;
68245    }else{
68246      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
68247      destroyRootPage(pParse, iLargest, iDb);
68248      iDestroyed = iLargest;
68249    }
68250  }
68251#endif
68252}
68253
68254/*
68255** This routine is called to do the work of a DROP TABLE statement.
68256** pName is the name of the table to be dropped.
68257*/
68258SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
68259  Table *pTab;
68260  Vdbe *v;
68261  sqlite3 *db = pParse->db;
68262  int iDb;
68263
68264  if( db->mallocFailed ){
68265    goto exit_drop_table;
68266  }
68267  assert( pParse->nErr==0 );
68268  assert( pName->nSrc==1 );
68269  pTab = sqlite3LocateTable(pParse, isView,
68270                            pName->a[0].zName, pName->a[0].zDatabase);
68271
68272  if( pTab==0 ){
68273    if( noErr ){
68274      sqlite3ErrorClear(pParse);
68275    }
68276    goto exit_drop_table;
68277  }
68278  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68279  assert( iDb>=0 && iDb<db->nDb );
68280
68281  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
68282  ** it is initialized.
68283  */
68284  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
68285    goto exit_drop_table;
68286  }
68287#ifndef SQLITE_OMIT_AUTHORIZATION
68288  {
68289    int code;
68290    const char *zTab = SCHEMA_TABLE(iDb);
68291    const char *zDb = db->aDb[iDb].zName;
68292    const char *zArg2 = 0;
68293    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
68294      goto exit_drop_table;
68295    }
68296    if( isView ){
68297      if( !OMIT_TEMPDB && iDb==1 ){
68298        code = SQLITE_DROP_TEMP_VIEW;
68299      }else{
68300        code = SQLITE_DROP_VIEW;
68301      }
68302#ifndef SQLITE_OMIT_VIRTUALTABLE
68303    }else if( IsVirtual(pTab) ){
68304      code = SQLITE_DROP_VTABLE;
68305      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
68306#endif
68307    }else{
68308      if( !OMIT_TEMPDB && iDb==1 ){
68309        code = SQLITE_DROP_TEMP_TABLE;
68310      }else{
68311        code = SQLITE_DROP_TABLE;
68312      }
68313    }
68314    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
68315      goto exit_drop_table;
68316    }
68317    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
68318      goto exit_drop_table;
68319    }
68320  }
68321#endif
68322  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
68323    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
68324    goto exit_drop_table;
68325  }
68326
68327#ifndef SQLITE_OMIT_VIEW
68328  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
68329  ** on a table.
68330  */
68331  if( isView && pTab->pSelect==0 ){
68332    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
68333    goto exit_drop_table;
68334  }
68335  if( !isView && pTab->pSelect ){
68336    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
68337    goto exit_drop_table;
68338  }
68339#endif
68340
68341  /* Generate code to remove the table from the master table
68342  ** on disk.
68343  */
68344  v = sqlite3GetVdbe(pParse);
68345  if( v ){
68346    Trigger *pTrigger;
68347    Db *pDb = &db->aDb[iDb];
68348    sqlite3BeginWriteOperation(pParse, 1, iDb);
68349
68350#ifndef SQLITE_OMIT_VIRTUALTABLE
68351    if( IsVirtual(pTab) ){
68352      sqlite3VdbeAddOp0(v, OP_VBegin);
68353    }
68354#endif
68355    sqlite3FkDropTable(pParse, pName, pTab);
68356
68357    /* Drop all triggers associated with the table being dropped. Code
68358    ** is generated to remove entries from sqlite_master and/or
68359    ** sqlite_temp_master if required.
68360    */
68361    pTrigger = sqlite3TriggerList(pParse, pTab);
68362    while( pTrigger ){
68363      assert( pTrigger->pSchema==pTab->pSchema ||
68364          pTrigger->pSchema==db->aDb[1].pSchema );
68365      sqlite3DropTriggerPtr(pParse, pTrigger);
68366      pTrigger = pTrigger->pNext;
68367    }
68368
68369#ifndef SQLITE_OMIT_AUTOINCREMENT
68370    /* Remove any entries of the sqlite_sequence table associated with
68371    ** the table being dropped. This is done before the table is dropped
68372    ** at the btree level, in case the sqlite_sequence table needs to
68373    ** move as a result of the drop (can happen in auto-vacuum mode).
68374    */
68375    if( pTab->tabFlags & TF_Autoincrement ){
68376      sqlite3NestedParse(pParse,
68377        "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
68378        pDb->zName, pTab->zName
68379      );
68380    }
68381#endif
68382
68383    /* Drop all SQLITE_MASTER table and index entries that refer to the
68384    ** table. The program name loops through the master table and deletes
68385    ** every row that refers to a table of the same name as the one being
68386    ** dropped. Triggers are handled seperately because a trigger can be
68387    ** created in the temp database that refers to a table in another
68388    ** database.
68389    */
68390    sqlite3NestedParse(pParse,
68391        "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
68392        pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
68393
68394    /* Drop any statistics from the sqlite_stat1 table, if it exists */
68395    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
68396      sqlite3NestedParse(pParse,
68397        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
68398      );
68399    }
68400
68401    if( !isView && !IsVirtual(pTab) ){
68402      destroyTable(pParse, pTab);
68403    }
68404
68405    /* Remove the table entry from SQLite's internal schema and modify
68406    ** the schema cookie.
68407    */
68408    if( IsVirtual(pTab) ){
68409      sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
68410    }
68411    sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
68412    sqlite3ChangeCookie(pParse, iDb);
68413  }
68414  sqliteViewResetAll(db, iDb);
68415
68416exit_drop_table:
68417  sqlite3SrcListDelete(db, pName);
68418}
68419
68420/*
68421** This routine is called to create a new foreign key on the table
68422** currently under construction.  pFromCol determines which columns
68423** in the current table point to the foreign key.  If pFromCol==0 then
68424** connect the key to the last column inserted.  pTo is the name of
68425** the table referred to.  pToCol is a list of tables in the other
68426** pTo table that the foreign key points to.  flags contains all
68427** information about the conflict resolution algorithms specified
68428** in the ON DELETE, ON UPDATE and ON INSERT clauses.
68429**
68430** An FKey structure is created and added to the table currently
68431** under construction in the pParse->pNewTable field.
68432**
68433** The foreign key is set for IMMEDIATE processing.  A subsequent call
68434** to sqlite3DeferForeignKey() might change this to DEFERRED.
68435*/
68436SQLITE_PRIVATE void sqlite3CreateForeignKey(
68437  Parse *pParse,       /* Parsing context */
68438  ExprList *pFromCol,  /* Columns in this table that point to other table */
68439  Token *pTo,          /* Name of the other table */
68440  ExprList *pToCol,    /* Columns in the other table */
68441  int flags            /* Conflict resolution algorithms. */
68442){
68443  sqlite3 *db = pParse->db;
68444#ifndef SQLITE_OMIT_FOREIGN_KEY
68445  FKey *pFKey = 0;
68446  FKey *pNextTo;
68447  Table *p = pParse->pNewTable;
68448  int nByte;
68449  int i;
68450  int nCol;
68451  char *z;
68452
68453  assert( pTo!=0 );
68454  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
68455  if( pFromCol==0 ){
68456    int iCol = p->nCol-1;
68457    if( NEVER(iCol<0) ) goto fk_end;
68458    if( pToCol && pToCol->nExpr!=1 ){
68459      sqlite3ErrorMsg(pParse, "foreign key on %s"
68460         " should reference only one column of table %T",
68461         p->aCol[iCol].zName, pTo);
68462      goto fk_end;
68463    }
68464    nCol = 1;
68465  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
68466    sqlite3ErrorMsg(pParse,
68467        "number of columns in foreign key does not match the number of "
68468        "columns in the referenced table");
68469    goto fk_end;
68470  }else{
68471    nCol = pFromCol->nExpr;
68472  }
68473  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
68474  if( pToCol ){
68475    for(i=0; i<pToCol->nExpr; i++){
68476      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
68477    }
68478  }
68479  pFKey = sqlite3DbMallocZero(db, nByte );
68480  if( pFKey==0 ){
68481    goto fk_end;
68482  }
68483  pFKey->pFrom = p;
68484  pFKey->pNextFrom = p->pFKey;
68485  z = (char*)&pFKey->aCol[nCol];
68486  pFKey->zTo = z;
68487  memcpy(z, pTo->z, pTo->n);
68488  z[pTo->n] = 0;
68489  sqlite3Dequote(z);
68490  z += pTo->n+1;
68491  pFKey->nCol = nCol;
68492  if( pFromCol==0 ){
68493    pFKey->aCol[0].iFrom = p->nCol-1;
68494  }else{
68495    for(i=0; i<nCol; i++){
68496      int j;
68497      for(j=0; j<p->nCol; j++){
68498        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
68499          pFKey->aCol[i].iFrom = j;
68500          break;
68501        }
68502      }
68503      if( j>=p->nCol ){
68504        sqlite3ErrorMsg(pParse,
68505          "unknown column \"%s\" in foreign key definition",
68506          pFromCol->a[i].zName);
68507        goto fk_end;
68508      }
68509    }
68510  }
68511  if( pToCol ){
68512    for(i=0; i<nCol; i++){
68513      int n = sqlite3Strlen30(pToCol->a[i].zName);
68514      pFKey->aCol[i].zCol = z;
68515      memcpy(z, pToCol->a[i].zName, n);
68516      z[n] = 0;
68517      z += n+1;
68518    }
68519  }
68520  pFKey->isDeferred = 0;
68521  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
68522  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
68523
68524  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
68525      pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
68526  );
68527  if( pNextTo==pFKey ){
68528    db->mallocFailed = 1;
68529    goto fk_end;
68530  }
68531  if( pNextTo ){
68532    assert( pNextTo->pPrevTo==0 );
68533    pFKey->pNextTo = pNextTo;
68534    pNextTo->pPrevTo = pFKey;
68535  }
68536
68537  /* Link the foreign key to the table as the last step.
68538  */
68539  p->pFKey = pFKey;
68540  pFKey = 0;
68541
68542fk_end:
68543  sqlite3DbFree(db, pFKey);
68544#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
68545  sqlite3ExprListDelete(db, pFromCol);
68546  sqlite3ExprListDelete(db, pToCol);
68547}
68548
68549/*
68550** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
68551** clause is seen as part of a foreign key definition.  The isDeferred
68552** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
68553** The behavior of the most recently created foreign key is adjusted
68554** accordingly.
68555*/
68556SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
68557#ifndef SQLITE_OMIT_FOREIGN_KEY
68558  Table *pTab;
68559  FKey *pFKey;
68560  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
68561  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
68562  pFKey->isDeferred = (u8)isDeferred;
68563#endif
68564}
68565
68566/*
68567** Generate code that will erase and refill index *pIdx.  This is
68568** used to initialize a newly created index or to recompute the
68569** content of an index in response to a REINDEX command.
68570**
68571** if memRootPage is not negative, it means that the index is newly
68572** created.  The register specified by memRootPage contains the
68573** root page number of the index.  If memRootPage is negative, then
68574** the index already exists and must be cleared before being refilled and
68575** the root page number of the index is taken from pIndex->tnum.
68576*/
68577static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
68578  Table *pTab = pIndex->pTable;  /* The table that is indexed */
68579  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
68580  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
68581  int addr1;                     /* Address of top of loop */
68582  int tnum;                      /* Root page of index */
68583  Vdbe *v;                       /* Generate code into this virtual machine */
68584  KeyInfo *pKey;                 /* KeyInfo for index */
68585  int regIdxKey;                 /* Registers containing the index key */
68586  int regRecord;                 /* Register holding assemblied index record */
68587  sqlite3 *db = pParse->db;      /* The database connection */
68588  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
68589
68590#ifndef SQLITE_OMIT_AUTHORIZATION
68591  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
68592      db->aDb[iDb].zName ) ){
68593    return;
68594  }
68595#endif
68596
68597  /* Require a write-lock on the table to perform this operation */
68598  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
68599
68600  v = sqlite3GetVdbe(pParse);
68601  if( v==0 ) return;
68602  if( memRootPage>=0 ){
68603    tnum = memRootPage;
68604  }else{
68605    tnum = pIndex->tnum;
68606    sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
68607  }
68608  pKey = sqlite3IndexKeyinfo(pParse, pIndex);
68609  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
68610                    (char *)pKey, P4_KEYINFO_HANDOFF);
68611  if( memRootPage>=0 ){
68612    sqlite3VdbeChangeP5(v, 1);
68613  }
68614  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
68615  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
68616  regRecord = sqlite3GetTempReg(pParse);
68617  regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
68618  if( pIndex->onError!=OE_None ){
68619    const int regRowid = regIdxKey + pIndex->nColumn;
68620    const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
68621    void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
68622
68623    /* The registers accessed by the OP_IsUnique opcode were allocated
68624    ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
68625    ** call above. Just before that function was freed they were released
68626    ** (made available to the compiler for reuse) using
68627    ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
68628    ** opcode use the values stored within seems dangerous. However, since
68629    ** we can be sure that no other temp registers have been allocated
68630    ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
68631    */
68632    sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
68633    sqlite3HaltConstraint(
68634        pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
68635  }
68636  sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
68637  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
68638  sqlite3ReleaseTempReg(pParse, regRecord);
68639  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
68640  sqlite3VdbeJumpHere(v, addr1);
68641  sqlite3VdbeAddOp1(v, OP_Close, iTab);
68642  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
68643}
68644
68645/*
68646** Create a new index for an SQL table.  pName1.pName2 is the name of the index
68647** and pTblList is the name of the table that is to be indexed.  Both will
68648** be NULL for a primary key or an index that is created to satisfy a
68649** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
68650** as the table to be indexed.  pParse->pNewTable is a table that is
68651** currently being constructed by a CREATE TABLE statement.
68652**
68653** pList is a list of columns to be indexed.  pList will be NULL if this
68654** is a primary key or unique-constraint on the most recent column added
68655** to the table currently under construction.
68656**
68657** If the index is created successfully, return a pointer to the new Index
68658** structure. This is used by sqlite3AddPrimaryKey() to mark the index
68659** as the tables primary key (Index.autoIndex==2).
68660*/
68661SQLITE_PRIVATE Index *sqlite3CreateIndex(
68662  Parse *pParse,     /* All information about this parse */
68663  Token *pName1,     /* First part of index name. May be NULL */
68664  Token *pName2,     /* Second part of index name. May be NULL */
68665  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
68666  ExprList *pList,   /* A list of columns to be indexed */
68667  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
68668  Token *pStart,     /* The CREATE token that begins this statement */
68669  Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
68670  int sortOrder,     /* Sort order of primary key when pList==NULL */
68671  int ifNotExist     /* Omit error if index already exists */
68672){
68673  Index *pRet = 0;     /* Pointer to return */
68674  Table *pTab = 0;     /* Table to be indexed */
68675  Index *pIndex = 0;   /* The index to be created */
68676  char *zName = 0;     /* Name of the index */
68677  int nName;           /* Number of characters in zName */
68678  int i, j;
68679  Token nullId;        /* Fake token for an empty ID list */
68680  DbFixer sFix;        /* For assigning database names to pTable */
68681  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
68682  sqlite3 *db = pParse->db;
68683  Db *pDb;             /* The specific table containing the indexed database */
68684  int iDb;             /* Index of the database that is being written */
68685  Token *pName = 0;    /* Unqualified name of the index to create */
68686  struct ExprList_item *pListItem; /* For looping over pList */
68687  int nCol;
68688  int nExtra = 0;
68689  char *zExtra;
68690
68691  assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
68692  assert( pParse->nErr==0 );      /* Never called with prior errors */
68693  if( db->mallocFailed || IN_DECLARE_VTAB ){
68694    goto exit_create_index;
68695  }
68696  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
68697    goto exit_create_index;
68698  }
68699
68700  /*
68701  ** Find the table that is to be indexed.  Return early if not found.
68702  */
68703  if( pTblName!=0 ){
68704
68705    /* Use the two-part index name to determine the database
68706    ** to search for the table. 'Fix' the table name to this db
68707    ** before looking up the table.
68708    */
68709    assert( pName1 && pName2 );
68710    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
68711    if( iDb<0 ) goto exit_create_index;
68712
68713#ifndef SQLITE_OMIT_TEMPDB
68714    /* If the index name was unqualified, check if the the table
68715    ** is a temp table. If so, set the database to 1. Do not do this
68716    ** if initialising a database schema.
68717    */
68718    if( !db->init.busy ){
68719      pTab = sqlite3SrcListLookup(pParse, pTblName);
68720      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
68721        iDb = 1;
68722      }
68723    }
68724#endif
68725
68726    if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
68727        sqlite3FixSrcList(&sFix, pTblName)
68728    ){
68729      /* Because the parser constructs pTblName from a single identifier,
68730      ** sqlite3FixSrcList can never fail. */
68731      assert(0);
68732    }
68733    pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
68734        pTblName->a[0].zDatabase);
68735    if( !pTab || db->mallocFailed ) goto exit_create_index;
68736    assert( db->aDb[iDb].pSchema==pTab->pSchema );
68737  }else{
68738    assert( pName==0 );
68739    pTab = pParse->pNewTable;
68740    if( !pTab ) goto exit_create_index;
68741    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68742  }
68743  pDb = &db->aDb[iDb];
68744
68745  assert( pTab!=0 );
68746  assert( pParse->nErr==0 );
68747  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
68748       && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
68749    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
68750    goto exit_create_index;
68751  }
68752#ifndef SQLITE_OMIT_VIEW
68753  if( pTab->pSelect ){
68754    sqlite3ErrorMsg(pParse, "views may not be indexed");
68755    goto exit_create_index;
68756  }
68757#endif
68758#ifndef SQLITE_OMIT_VIRTUALTABLE
68759  if( IsVirtual(pTab) ){
68760    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
68761    goto exit_create_index;
68762  }
68763#endif
68764
68765  /*
68766  ** Find the name of the index.  Make sure there is not already another
68767  ** index or table with the same name.
68768  **
68769  ** Exception:  If we are reading the names of permanent indices from the
68770  ** sqlite_master table (because some other process changed the schema) and
68771  ** one of the index names collides with the name of a temporary table or
68772  ** index, then we will continue to process this index.
68773  **
68774  ** If pName==0 it means that we are
68775  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
68776  ** own name.
68777  */
68778  if( pName ){
68779    zName = sqlite3NameFromToken(db, pName);
68780    if( zName==0 ) goto exit_create_index;
68781    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
68782      goto exit_create_index;
68783    }
68784    if( !db->init.busy ){
68785      if( sqlite3FindTable(db, zName, 0)!=0 ){
68786        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
68787        goto exit_create_index;
68788      }
68789    }
68790    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
68791      if( !ifNotExist ){
68792        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
68793      }
68794      goto exit_create_index;
68795    }
68796  }else{
68797    int n;
68798    Index *pLoop;
68799    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
68800    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
68801    if( zName==0 ){
68802      goto exit_create_index;
68803    }
68804  }
68805
68806  /* Check for authorization to create an index.
68807  */
68808#ifndef SQLITE_OMIT_AUTHORIZATION
68809  {
68810    const char *zDb = pDb->zName;
68811    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
68812      goto exit_create_index;
68813    }
68814    i = SQLITE_CREATE_INDEX;
68815    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
68816    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
68817      goto exit_create_index;
68818    }
68819  }
68820#endif
68821
68822  /* If pList==0, it means this routine was called to make a primary
68823  ** key out of the last column added to the table under construction.
68824  ** So create a fake list to simulate this.
68825  */
68826  if( pList==0 ){
68827    nullId.z = pTab->aCol[pTab->nCol-1].zName;
68828    nullId.n = sqlite3Strlen30((char*)nullId.z);
68829    pList = sqlite3ExprListAppend(pParse, 0, 0);
68830    if( pList==0 ) goto exit_create_index;
68831    sqlite3ExprListSetName(pParse, pList, &nullId, 0);
68832    pList->a[0].sortOrder = (u8)sortOrder;
68833  }
68834
68835  /* Figure out how many bytes of space are required to store explicitly
68836  ** specified collation sequence names.
68837  */
68838  for(i=0; i<pList->nExpr; i++){
68839    Expr *pExpr = pList->a[i].pExpr;
68840    if( pExpr ){
68841      CollSeq *pColl = pExpr->pColl;
68842      /* Either pColl!=0 or there was an OOM failure.  But if an OOM
68843      ** failure we have quit before reaching this point. */
68844      if( ALWAYS(pColl) ){
68845        nExtra += (1 + sqlite3Strlen30(pColl->zName));
68846      }
68847    }
68848  }
68849
68850  /*
68851  ** Allocate the index structure.
68852  */
68853  nName = sqlite3Strlen30(zName);
68854  nCol = pList->nExpr;
68855  pIndex = sqlite3DbMallocZero(db,
68856      sizeof(Index) +              /* Index structure  */
68857      sizeof(int)*nCol +           /* Index.aiColumn   */
68858      sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
68859      sizeof(char *)*nCol +        /* Index.azColl     */
68860      sizeof(u8)*nCol +            /* Index.aSortOrder */
68861      nName + 1 +                  /* Index.zName      */
68862      nExtra                       /* Collation sequence names */
68863  );
68864  if( db->mallocFailed ){
68865    goto exit_create_index;
68866  }
68867  pIndex->azColl = (char**)(&pIndex[1]);
68868  pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
68869  pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
68870  pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
68871  pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
68872  zExtra = (char *)(&pIndex->zName[nName+1]);
68873  memcpy(pIndex->zName, zName, nName+1);
68874  pIndex->pTable = pTab;
68875  pIndex->nColumn = pList->nExpr;
68876  pIndex->onError = (u8)onError;
68877  pIndex->autoIndex = (u8)(pName==0);
68878  pIndex->pSchema = db->aDb[iDb].pSchema;
68879
68880  /* Check to see if we should honor DESC requests on index columns
68881  */
68882  if( pDb->pSchema->file_format>=4 ){
68883    sortOrderMask = -1;   /* Honor DESC */
68884  }else{
68885    sortOrderMask = 0;    /* Ignore DESC */
68886  }
68887
68888  /* Scan the names of the columns of the table to be indexed and
68889  ** load the column indices into the Index structure.  Report an error
68890  ** if any column is not found.
68891  **
68892  ** TODO:  Add a test to make sure that the same column is not named
68893  ** more than once within the same index.  Only the first instance of
68894  ** the column will ever be used by the optimizer.  Note that using the
68895  ** same column more than once cannot be an error because that would
68896  ** break backwards compatibility - it needs to be a warning.
68897  */
68898  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
68899    const char *zColName = pListItem->zName;
68900    Column *pTabCol;
68901    int requestedSortOrder;
68902    char *zColl;                   /* Collation sequence name */
68903
68904    for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
68905      if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
68906    }
68907    if( j>=pTab->nCol ){
68908      sqlite3ErrorMsg(pParse, "table %s has no column named %s",
68909        pTab->zName, zColName);
68910      goto exit_create_index;
68911    }
68912    pIndex->aiColumn[i] = j;
68913    /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
68914    ** the way the "idxlist" non-terminal is constructed by the parser,
68915    ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
68916    ** must exist or else there must have been an OOM error.  But if there
68917    ** was an OOM error, we would never reach this point. */
68918    if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
68919      int nColl;
68920      zColl = pListItem->pExpr->pColl->zName;
68921      nColl = sqlite3Strlen30(zColl) + 1;
68922      assert( nExtra>=nColl );
68923      memcpy(zExtra, zColl, nColl);
68924      zColl = zExtra;
68925      zExtra += nColl;
68926      nExtra -= nColl;
68927    }else{
68928      zColl = pTab->aCol[j].zColl;
68929      if( !zColl ){
68930        zColl = db->pDfltColl->zName;
68931      }
68932    }
68933    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
68934      goto exit_create_index;
68935    }
68936    pIndex->azColl[i] = zColl;
68937    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
68938    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
68939  }
68940  sqlite3DefaultRowEst(pIndex);
68941
68942  if( pTab==pParse->pNewTable ){
68943    /* This routine has been called to create an automatic index as a
68944    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
68945    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
68946    ** i.e. one of:
68947    **
68948    ** CREATE TABLE t(x PRIMARY KEY, y);
68949    ** CREATE TABLE t(x, y, UNIQUE(x, y));
68950    **
68951    ** Either way, check to see if the table already has such an index. If
68952    ** so, don't bother creating this one. This only applies to
68953    ** automatically created indices. Users can do as they wish with
68954    ** explicit indices.
68955    **
68956    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
68957    ** (and thus suppressing the second one) even if they have different
68958    ** sort orders.
68959    **
68960    ** If there are different collating sequences or if the columns of
68961    ** the constraint occur in different orders, then the constraints are
68962    ** considered distinct and both result in separate indices.
68963    */
68964    Index *pIdx;
68965    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68966      int k;
68967      assert( pIdx->onError!=OE_None );
68968      assert( pIdx->autoIndex );
68969      assert( pIndex->onError!=OE_None );
68970
68971      if( pIdx->nColumn!=pIndex->nColumn ) continue;
68972      for(k=0; k<pIdx->nColumn; k++){
68973        const char *z1;
68974        const char *z2;
68975        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
68976        z1 = pIdx->azColl[k];
68977        z2 = pIndex->azColl[k];
68978        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
68979      }
68980      if( k==pIdx->nColumn ){
68981        if( pIdx->onError!=pIndex->onError ){
68982          /* This constraint creates the same index as a previous
68983          ** constraint specified somewhere in the CREATE TABLE statement.
68984          ** However the ON CONFLICT clauses are different. If both this
68985          ** constraint and the previous equivalent constraint have explicit
68986          ** ON CONFLICT clauses this is an error. Otherwise, use the
68987          ** explicitly specified behaviour for the index.
68988          */
68989          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
68990            sqlite3ErrorMsg(pParse,
68991                "conflicting ON CONFLICT clauses specified", 0);
68992          }
68993          if( pIdx->onError==OE_Default ){
68994            pIdx->onError = pIndex->onError;
68995          }
68996        }
68997        goto exit_create_index;
68998      }
68999    }
69000  }
69001
69002  /* Link the new Index structure to its table and to the other
69003  ** in-memory database structures.
69004  */
69005  if( db->init.busy ){
69006    Index *p;
69007    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
69008                          pIndex->zName, sqlite3Strlen30(pIndex->zName),
69009                          pIndex);
69010    if( p ){
69011      assert( p==pIndex );  /* Malloc must have failed */
69012      db->mallocFailed = 1;
69013      goto exit_create_index;
69014    }
69015    db->flags |= SQLITE_InternChanges;
69016    if( pTblName!=0 ){
69017      pIndex->tnum = db->init.newTnum;
69018    }
69019  }
69020
69021  /* If the db->init.busy is 0 then create the index on disk.  This
69022  ** involves writing the index into the master table and filling in the
69023  ** index with the current table contents.
69024  **
69025  ** The db->init.busy is 0 when the user first enters a CREATE INDEX
69026  ** command.  db->init.busy is 1 when a database is opened and
69027  ** CREATE INDEX statements are read out of the master table.  In
69028  ** the latter case the index already exists on disk, which is why
69029  ** we don't want to recreate it.
69030  **
69031  ** If pTblName==0 it means this index is generated as a primary key
69032  ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
69033  ** has just been created, it contains no data and the index initialization
69034  ** step can be skipped.
69035  */
69036  else{ /* if( db->init.busy==0 ) */
69037    Vdbe *v;
69038    char *zStmt;
69039    int iMem = ++pParse->nMem;
69040
69041    v = sqlite3GetVdbe(pParse);
69042    if( v==0 ) goto exit_create_index;
69043
69044
69045    /* Create the rootpage for the index
69046    */
69047    sqlite3BeginWriteOperation(pParse, 1, iDb);
69048    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
69049
69050    /* Gather the complete text of the CREATE INDEX statement into
69051    ** the zStmt variable
69052    */
69053    if( pStart ){
69054      assert( pEnd!=0 );
69055      /* A named index with an explicit CREATE INDEX statement */
69056      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
69057        onError==OE_None ? "" : " UNIQUE",
69058        pEnd->z - pName->z + 1,
69059        pName->z);
69060    }else{
69061      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
69062      /* zStmt = sqlite3MPrintf(""); */
69063      zStmt = 0;
69064    }
69065
69066    /* Add an entry in sqlite_master for this index
69067    */
69068    sqlite3NestedParse(pParse,
69069        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
69070        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
69071        pIndex->zName,
69072        pTab->zName,
69073        iMem,
69074        zStmt
69075    );
69076    sqlite3DbFree(db, zStmt);
69077
69078    /* Fill the index with data and reparse the schema. Code an OP_Expire
69079    ** to invalidate all pre-compiled statements.
69080    */
69081    if( pTblName ){
69082      sqlite3RefillIndex(pParse, pIndex, iMem);
69083      sqlite3ChangeCookie(pParse, iDb);
69084      sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
69085         sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
69086      sqlite3VdbeAddOp1(v, OP_Expire, 0);
69087    }
69088  }
69089
69090  /* When adding an index to the list of indices for a table, make
69091  ** sure all indices labeled OE_Replace come after all those labeled
69092  ** OE_Ignore.  This is necessary for the correct constraint check
69093  ** processing (in sqlite3GenerateConstraintChecks()) as part of
69094  ** UPDATE and INSERT statements.
69095  */
69096  if( db->init.busy || pTblName==0 ){
69097    if( onError!=OE_Replace || pTab->pIndex==0
69098         || pTab->pIndex->onError==OE_Replace){
69099      pIndex->pNext = pTab->pIndex;
69100      pTab->pIndex = pIndex;
69101    }else{
69102      Index *pOther = pTab->pIndex;
69103      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
69104        pOther = pOther->pNext;
69105      }
69106      pIndex->pNext = pOther->pNext;
69107      pOther->pNext = pIndex;
69108    }
69109    pRet = pIndex;
69110    pIndex = 0;
69111  }
69112
69113  /* Clean up before exiting */
69114exit_create_index:
69115  if( pIndex ){
69116    sqlite3_free(pIndex->zColAff);
69117    sqlite3DbFree(db, pIndex);
69118  }
69119  sqlite3ExprListDelete(db, pList);
69120  sqlite3SrcListDelete(db, pTblName);
69121  sqlite3DbFree(db, zName);
69122  return pRet;
69123}
69124
69125/*
69126** Fill the Index.aiRowEst[] array with default information - information
69127** to be used when we have not run the ANALYZE command.
69128**
69129** aiRowEst[0] is suppose to contain the number of elements in the index.
69130** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
69131** number of rows in the table that match any particular value of the
69132** first column of the index.  aiRowEst[2] is an estimate of the number
69133** of rows that match any particular combiniation of the first 2 columns
69134** of the index.  And so forth.  It must always be the case that
69135*
69136**           aiRowEst[N]<=aiRowEst[N-1]
69137**           aiRowEst[N]>=1
69138**
69139** Apart from that, we have little to go on besides intuition as to
69140** how aiRowEst[] should be initialized.  The numbers generated here
69141** are based on typical values found in actual indices.
69142*/
69143SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
69144  unsigned *a = pIdx->aiRowEst;
69145  int i;
69146  assert( a!=0 );
69147  a[0] = 1000000;
69148  for(i=pIdx->nColumn; i>=5; i--){
69149    a[i] = 5;
69150  }
69151  while( i>=1 ){
69152    a[i] = 11 - i;
69153    i--;
69154  }
69155  if( pIdx->onError!=OE_None ){
69156    a[pIdx->nColumn] = 1;
69157  }
69158}
69159
69160/*
69161** This routine will drop an existing named index.  This routine
69162** implements the DROP INDEX statement.
69163*/
69164SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
69165  Index *pIndex;
69166  Vdbe *v;
69167  sqlite3 *db = pParse->db;
69168  int iDb;
69169
69170  assert( pParse->nErr==0 );   /* Never called with prior errors */
69171  if( db->mallocFailed ){
69172    goto exit_drop_index;
69173  }
69174  assert( pName->nSrc==1 );
69175  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
69176    goto exit_drop_index;
69177  }
69178  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
69179  if( pIndex==0 ){
69180    if( !ifExists ){
69181      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
69182    }
69183    pParse->checkSchema = 1;
69184    goto exit_drop_index;
69185  }
69186  if( pIndex->autoIndex ){
69187    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
69188      "or PRIMARY KEY constraint cannot be dropped", 0);
69189    goto exit_drop_index;
69190  }
69191  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
69192#ifndef SQLITE_OMIT_AUTHORIZATION
69193  {
69194    int code = SQLITE_DROP_INDEX;
69195    Table *pTab = pIndex->pTable;
69196    const char *zDb = db->aDb[iDb].zName;
69197    const char *zTab = SCHEMA_TABLE(iDb);
69198    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
69199      goto exit_drop_index;
69200    }
69201    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
69202    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
69203      goto exit_drop_index;
69204    }
69205  }
69206#endif
69207
69208  /* Generate code to remove the index and from the master table */
69209  v = sqlite3GetVdbe(pParse);
69210  if( v ){
69211    sqlite3BeginWriteOperation(pParse, 1, iDb);
69212    sqlite3NestedParse(pParse,
69213       "DELETE FROM %Q.%s WHERE name=%Q",
69214       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
69215       pIndex->zName
69216    );
69217    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
69218      sqlite3NestedParse(pParse,
69219        "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
69220        db->aDb[iDb].zName, pIndex->zName
69221      );
69222    }
69223    sqlite3ChangeCookie(pParse, iDb);
69224    destroyRootPage(pParse, pIndex->tnum, iDb);
69225    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
69226  }
69227
69228exit_drop_index:
69229  sqlite3SrcListDelete(db, pName);
69230}
69231
69232/*
69233** pArray is a pointer to an array of objects.  Each object in the
69234** array is szEntry bytes in size.  This routine allocates a new
69235** object on the end of the array.
69236**
69237** *pnEntry is the number of entries already in use.  *pnAlloc is
69238** the previously allocated size of the array.  initSize is the
69239** suggested initial array size allocation.
69240**
69241** The index of the new entry is returned in *pIdx.
69242**
69243** This routine returns a pointer to the array of objects.  This
69244** might be the same as the pArray parameter or it might be a different
69245** pointer if the array was resized.
69246*/
69247SQLITE_PRIVATE void *sqlite3ArrayAllocate(
69248  sqlite3 *db,      /* Connection to notify of malloc failures */
69249  void *pArray,     /* Array of objects.  Might be reallocated */
69250  int szEntry,      /* Size of each object in the array */
69251  int initSize,     /* Suggested initial allocation, in elements */
69252  int *pnEntry,     /* Number of objects currently in use */
69253  int *pnAlloc,     /* Current size of the allocation, in elements */
69254  int *pIdx         /* Write the index of a new slot here */
69255){
69256  char *z;
69257  if( *pnEntry >= *pnAlloc ){
69258    void *pNew;
69259    int newSize;
69260    newSize = (*pnAlloc)*2 + initSize;
69261    pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
69262    if( pNew==0 ){
69263      *pIdx = -1;
69264      return pArray;
69265    }
69266    *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
69267    pArray = pNew;
69268  }
69269  z = (char*)pArray;
69270  memset(&z[*pnEntry * szEntry], 0, szEntry);
69271  *pIdx = *pnEntry;
69272  ++*pnEntry;
69273  return pArray;
69274}
69275
69276/*
69277** Append a new element to the given IdList.  Create a new IdList if
69278** need be.
69279**
69280** A new IdList is returned, or NULL if malloc() fails.
69281*/
69282SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
69283  int i;
69284  if( pList==0 ){
69285    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
69286    if( pList==0 ) return 0;
69287    pList->nAlloc = 0;
69288  }
69289  pList->a = sqlite3ArrayAllocate(
69290      db,
69291      pList->a,
69292      sizeof(pList->a[0]),
69293      5,
69294      &pList->nId,
69295      &pList->nAlloc,
69296      &i
69297  );
69298  if( i<0 ){
69299    sqlite3IdListDelete(db, pList);
69300    return 0;
69301  }
69302  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
69303  return pList;
69304}
69305
69306/*
69307** Delete an IdList.
69308*/
69309SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
69310  int i;
69311  if( pList==0 ) return;
69312  for(i=0; i<pList->nId; i++){
69313    sqlite3DbFree(db, pList->a[i].zName);
69314  }
69315  sqlite3DbFree(db, pList->a);
69316  sqlite3DbFree(db, pList);
69317}
69318
69319/*
69320** Return the index in pList of the identifier named zId.  Return -1
69321** if not found.
69322*/
69323SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
69324  int i;
69325  if( pList==0 ) return -1;
69326  for(i=0; i<pList->nId; i++){
69327    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
69328  }
69329  return -1;
69330}
69331
69332/*
69333** Expand the space allocated for the given SrcList object by
69334** creating nExtra new slots beginning at iStart.  iStart is zero based.
69335** New slots are zeroed.
69336**
69337** For example, suppose a SrcList initially contains two entries: A,B.
69338** To append 3 new entries onto the end, do this:
69339**
69340**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
69341**
69342** After the call above it would contain:  A, B, nil, nil, nil.
69343** If the iStart argument had been 1 instead of 2, then the result
69344** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
69345** the iStart value would be 0.  The result then would
69346** be: nil, nil, nil, A, B.
69347**
69348** If a memory allocation fails the SrcList is unchanged.  The
69349** db->mallocFailed flag will be set to true.
69350*/
69351SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
69352  sqlite3 *db,       /* Database connection to notify of OOM errors */
69353  SrcList *pSrc,     /* The SrcList to be enlarged */
69354  int nExtra,        /* Number of new slots to add to pSrc->a[] */
69355  int iStart         /* Index in pSrc->a[] of first new slot */
69356){
69357  int i;
69358
69359  /* Sanity checking on calling parameters */
69360  assert( iStart>=0 );
69361  assert( nExtra>=1 );
69362  assert( pSrc!=0 );
69363  assert( iStart<=pSrc->nSrc );
69364
69365  /* Allocate additional space if needed */
69366  if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
69367    SrcList *pNew;
69368    int nAlloc = pSrc->nSrc+nExtra;
69369    int nGot;
69370    pNew = sqlite3DbRealloc(db, pSrc,
69371               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
69372    if( pNew==0 ){
69373      assert( db->mallocFailed );
69374      return pSrc;
69375    }
69376    pSrc = pNew;
69377    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
69378    pSrc->nAlloc = (u16)nGot;
69379  }
69380
69381  /* Move existing slots that come after the newly inserted slots
69382  ** out of the way */
69383  for(i=pSrc->nSrc-1; i>=iStart; i--){
69384    pSrc->a[i+nExtra] = pSrc->a[i];
69385  }
69386  pSrc->nSrc += (i16)nExtra;
69387
69388  /* Zero the newly allocated slots */
69389  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
69390  for(i=iStart; i<iStart+nExtra; i++){
69391    pSrc->a[i].iCursor = -1;
69392  }
69393
69394  /* Return a pointer to the enlarged SrcList */
69395  return pSrc;
69396}
69397
69398
69399/*
69400** Append a new table name to the given SrcList.  Create a new SrcList if
69401** need be.  A new entry is created in the SrcList even if pTable is NULL.
69402**
69403** A SrcList is returned, or NULL if there is an OOM error.  The returned
69404** SrcList might be the same as the SrcList that was input or it might be
69405** a new one.  If an OOM error does occurs, then the prior value of pList
69406** that is input to this routine is automatically freed.
69407**
69408** If pDatabase is not null, it means that the table has an optional
69409** database name prefix.  Like this:  "database.table".  The pDatabase
69410** points to the table name and the pTable points to the database name.
69411** The SrcList.a[].zName field is filled with the table name which might
69412** come from pTable (if pDatabase is NULL) or from pDatabase.
69413** SrcList.a[].zDatabase is filled with the database name from pTable,
69414** or with NULL if no database is specified.
69415**
69416** In other words, if call like this:
69417**
69418**         sqlite3SrcListAppend(D,A,B,0);
69419**
69420** Then B is a table name and the database name is unspecified.  If called
69421** like this:
69422**
69423**         sqlite3SrcListAppend(D,A,B,C);
69424**
69425** Then C is the table name and B is the database name.  If C is defined
69426** then so is B.  In other words, we never have a case where:
69427**
69428**         sqlite3SrcListAppend(D,A,0,C);
69429**
69430** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
69431** before being added to the SrcList.
69432*/
69433SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
69434  sqlite3 *db,        /* Connection to notify of malloc failures */
69435  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
69436  Token *pTable,      /* Table to append */
69437  Token *pDatabase    /* Database of the table */
69438){
69439  struct SrcList_item *pItem;
69440  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
69441  if( pList==0 ){
69442    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
69443    if( pList==0 ) return 0;
69444    pList->nAlloc = 1;
69445  }
69446  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
69447  if( db->mallocFailed ){
69448    sqlite3SrcListDelete(db, pList);
69449    return 0;
69450  }
69451  pItem = &pList->a[pList->nSrc-1];
69452  if( pDatabase && pDatabase->z==0 ){
69453    pDatabase = 0;
69454  }
69455  if( pDatabase ){
69456    Token *pTemp = pDatabase;
69457    pDatabase = pTable;
69458    pTable = pTemp;
69459  }
69460  pItem->zName = sqlite3NameFromToken(db, pTable);
69461  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
69462  return pList;
69463}
69464
69465/*
69466** Assign VdbeCursor index numbers to all tables in a SrcList
69467*/
69468SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
69469  int i;
69470  struct SrcList_item *pItem;
69471  assert(pList || pParse->db->mallocFailed );
69472  if( pList ){
69473    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
69474      if( pItem->iCursor>=0 ) break;
69475      pItem->iCursor = pParse->nTab++;
69476      if( pItem->pSelect ){
69477        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
69478      }
69479    }
69480  }
69481}
69482
69483/*
69484** Delete an entire SrcList including all its substructure.
69485*/
69486SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
69487  int i;
69488  struct SrcList_item *pItem;
69489  if( pList==0 ) return;
69490  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
69491    sqlite3DbFree(db, pItem->zDatabase);
69492    sqlite3DbFree(db, pItem->zName);
69493    sqlite3DbFree(db, pItem->zAlias);
69494    sqlite3DbFree(db, pItem->zIndex);
69495    sqlite3DeleteTable(pItem->pTab);
69496    sqlite3SelectDelete(db, pItem->pSelect);
69497    sqlite3ExprDelete(db, pItem->pOn);
69498    sqlite3IdListDelete(db, pItem->pUsing);
69499  }
69500  sqlite3DbFree(db, pList);
69501}
69502
69503/*
69504** This routine is called by the parser to add a new term to the
69505** end of a growing FROM clause.  The "p" parameter is the part of
69506** the FROM clause that has already been constructed.  "p" is NULL
69507** if this is the first term of the FROM clause.  pTable and pDatabase
69508** are the name of the table and database named in the FROM clause term.
69509** pDatabase is NULL if the database name qualifier is missing - the
69510** usual case.  If the term has a alias, then pAlias points to the
69511** alias token.  If the term is a subquery, then pSubquery is the
69512** SELECT statement that the subquery encodes.  The pTable and
69513** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
69514** parameters are the content of the ON and USING clauses.
69515**
69516** Return a new SrcList which encodes is the FROM with the new
69517** term added.
69518*/
69519SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
69520  Parse *pParse,          /* Parsing context */
69521  SrcList *p,             /* The left part of the FROM clause already seen */
69522  Token *pTable,          /* Name of the table to add to the FROM clause */
69523  Token *pDatabase,       /* Name of the database containing pTable */
69524  Token *pAlias,          /* The right-hand side of the AS subexpression */
69525  Select *pSubquery,      /* A subquery used in place of a table name */
69526  Expr *pOn,              /* The ON clause of a join */
69527  IdList *pUsing          /* The USING clause of a join */
69528){
69529  struct SrcList_item *pItem;
69530  sqlite3 *db = pParse->db;
69531  if( !p && (pOn || pUsing) ){
69532    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
69533      (pOn ? "ON" : "USING")
69534    );
69535    goto append_from_error;
69536  }
69537  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
69538  if( p==0 || NEVER(p->nSrc==0) ){
69539    goto append_from_error;
69540  }
69541  pItem = &p->a[p->nSrc-1];
69542  assert( pAlias!=0 );
69543  if( pAlias->n ){
69544    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
69545  }
69546  pItem->pSelect = pSubquery;
69547  pItem->pOn = pOn;
69548  pItem->pUsing = pUsing;
69549  return p;
69550
69551 append_from_error:
69552  assert( p==0 );
69553  sqlite3ExprDelete(db, pOn);
69554  sqlite3IdListDelete(db, pUsing);
69555  sqlite3SelectDelete(db, pSubquery);
69556  return 0;
69557}
69558
69559/*
69560** Add an INDEXED BY or NOT INDEXED clause to the most recently added
69561** element of the source-list passed as the second argument.
69562*/
69563SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
69564  assert( pIndexedBy!=0 );
69565  if( p && ALWAYS(p->nSrc>0) ){
69566    struct SrcList_item *pItem = &p->a[p->nSrc-1];
69567    assert( pItem->notIndexed==0 && pItem->zIndex==0 );
69568    if( pIndexedBy->n==1 && !pIndexedBy->z ){
69569      /* A "NOT INDEXED" clause was supplied. See parse.y
69570      ** construct "indexed_opt" for details. */
69571      pItem->notIndexed = 1;
69572    }else{
69573      pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
69574    }
69575  }
69576}
69577
69578/*
69579** When building up a FROM clause in the parser, the join operator
69580** is initially attached to the left operand.  But the code generator
69581** expects the join operator to be on the right operand.  This routine
69582** Shifts all join operators from left to right for an entire FROM
69583** clause.
69584**
69585** Example: Suppose the join is like this:
69586**
69587**           A natural cross join B
69588**
69589** The operator is "natural cross join".  The A and B operands are stored
69590** in p->a[0] and p->a[1], respectively.  The parser initially stores the
69591** operator with A.  This routine shifts that operator over to B.
69592*/
69593SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
69594  if( p && p->a ){
69595    int i;
69596    for(i=p->nSrc-1; i>0; i--){
69597      p->a[i].jointype = p->a[i-1].jointype;
69598    }
69599    p->a[0].jointype = 0;
69600  }
69601}
69602
69603/*
69604** Begin a transaction
69605*/
69606SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
69607  sqlite3 *db;
69608  Vdbe *v;
69609  int i;
69610
69611  assert( pParse!=0 );
69612  db = pParse->db;
69613  assert( db!=0 );
69614/*  if( db->aDb[0].pBt==0 ) return; */
69615  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
69616    return;
69617  }
69618  v = sqlite3GetVdbe(pParse);
69619  if( !v ) return;
69620  if( type!=TK_DEFERRED ){
69621    for(i=0; i<db->nDb; i++){
69622      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
69623      sqlite3VdbeUsesBtree(v, i);
69624    }
69625  }
69626  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
69627}
69628
69629/*
69630** Commit a transaction
69631*/
69632SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
69633  sqlite3 *db;
69634  Vdbe *v;
69635
69636  assert( pParse!=0 );
69637  db = pParse->db;
69638  assert( db!=0 );
69639/*  if( db->aDb[0].pBt==0 ) return; */
69640  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
69641    return;
69642  }
69643  v = sqlite3GetVdbe(pParse);
69644  if( v ){
69645    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
69646  }
69647}
69648
69649/*
69650** Rollback a transaction
69651*/
69652SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
69653  sqlite3 *db;
69654  Vdbe *v;
69655
69656  assert( pParse!=0 );
69657  db = pParse->db;
69658  assert( db!=0 );
69659/*  if( db->aDb[0].pBt==0 ) return; */
69660  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
69661    return;
69662  }
69663  v = sqlite3GetVdbe(pParse);
69664  if( v ){
69665    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
69666  }
69667}
69668
69669/*
69670** This function is called by the parser when it parses a command to create,
69671** release or rollback an SQL savepoint.
69672*/
69673SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
69674  char *zName = sqlite3NameFromToken(pParse->db, pName);
69675  if( zName ){
69676    Vdbe *v = sqlite3GetVdbe(pParse);
69677#ifndef SQLITE_OMIT_AUTHORIZATION
69678    static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
69679    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
69680#endif
69681    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
69682      sqlite3DbFree(pParse->db, zName);
69683      return;
69684    }
69685    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
69686  }
69687}
69688
69689/*
69690** Make sure the TEMP database is open and available for use.  Return
69691** the number of errors.  Leave any error messages in the pParse structure.
69692*/
69693SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
69694  sqlite3 *db = pParse->db;
69695  if( db->aDb[1].pBt==0 && !pParse->explain ){
69696    int rc;
69697    static const int flags =
69698          SQLITE_OPEN_READWRITE |
69699          SQLITE_OPEN_CREATE |
69700          SQLITE_OPEN_EXCLUSIVE |
69701          SQLITE_OPEN_DELETEONCLOSE |
69702          SQLITE_OPEN_TEMP_DB;
69703
69704    rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
69705                                 &db->aDb[1].pBt);
69706    if( rc!=SQLITE_OK ){
69707      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
69708        "file for storing temporary tables");
69709      pParse->rc = rc;
69710      return 1;
69711    }
69712    assert( db->aDb[1].pSchema );
69713    sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
69714                            db->dfltJournalMode);
69715  }
69716  return 0;
69717}
69718
69719/*
69720** Generate VDBE code that will verify the schema cookie and start
69721** a read-transaction for all named database files.
69722**
69723** It is important that all schema cookies be verified and all
69724** read transactions be started before anything else happens in
69725** the VDBE program.  But this routine can be called after much other
69726** code has been generated.  So here is what we do:
69727**
69728** The first time this routine is called, we code an OP_Goto that
69729** will jump to a subroutine at the end of the program.  Then we
69730** record every database that needs its schema verified in the
69731** pParse->cookieMask field.  Later, after all other code has been
69732** generated, the subroutine that does the cookie verifications and
69733** starts the transactions will be coded and the OP_Goto P2 value
69734** will be made to point to that subroutine.  The generation of the
69735** cookie verification subroutine code happens in sqlite3FinishCoding().
69736**
69737** If iDb<0 then code the OP_Goto only - don't set flag to verify the
69738** schema on any databases.  This can be used to position the OP_Goto
69739** early in the code, before we know if any database tables will be used.
69740*/
69741SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
69742  Parse *pToplevel = sqlite3ParseToplevel(pParse);
69743
69744  if( pToplevel->cookieGoto==0 ){
69745    Vdbe *v = sqlite3GetVdbe(pToplevel);
69746    if( v==0 ) return;  /* This only happens if there was a prior error */
69747    pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
69748  }
69749  if( iDb>=0 ){
69750    sqlite3 *db = pToplevel->db;
69751    int mask;
69752
69753    assert( iDb<db->nDb );
69754    assert( db->aDb[iDb].pBt!=0 || iDb==1 );
69755    assert( iDb<SQLITE_MAX_ATTACHED+2 );
69756    mask = 1<<iDb;
69757    if( (pToplevel->cookieMask & mask)==0 ){
69758      pToplevel->cookieMask |= mask;
69759      pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
69760      if( !OMIT_TEMPDB && iDb==1 ){
69761        sqlite3OpenTempDatabase(pToplevel);
69762      }
69763    }
69764  }
69765}
69766
69767/*
69768** Generate VDBE code that prepares for doing an operation that
69769** might change the database.
69770**
69771** This routine starts a new transaction if we are not already within
69772** a transaction.  If we are already within a transaction, then a checkpoint
69773** is set if the setStatement parameter is true.  A checkpoint should
69774** be set for operations that might fail (due to a constraint) part of
69775** the way through and which will need to undo some writes without having to
69776** rollback the whole transaction.  For operations where all constraints
69777** can be checked before any changes are made to the database, it is never
69778** necessary to undo a write and the checkpoint should not be set.
69779*/
69780SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
69781  Parse *pToplevel = sqlite3ParseToplevel(pParse);
69782  sqlite3CodeVerifySchema(pParse, iDb);
69783  pToplevel->writeMask |= 1<<iDb;
69784  pToplevel->isMultiWrite |= setStatement;
69785}
69786
69787/*
69788** Indicate that the statement currently under construction might write
69789** more than one entry (example: deleting one row then inserting another,
69790** inserting multiple rows in a table, or inserting a row and index entries.)
69791** If an abort occurs after some of these writes have completed, then it will
69792** be necessary to undo the completed writes.
69793*/
69794SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
69795  Parse *pToplevel = sqlite3ParseToplevel(pParse);
69796  pToplevel->isMultiWrite = 1;
69797}
69798
69799/*
69800** The code generator calls this routine if is discovers that it is
69801** possible to abort a statement prior to completion.  In order to
69802** perform this abort without corrupting the database, we need to make
69803** sure that the statement is protected by a statement transaction.
69804**
69805** Technically, we only need to set the mayAbort flag if the
69806** isMultiWrite flag was previously set.  There is a time dependency
69807** such that the abort must occur after the multiwrite.  This makes
69808** some statements involving the REPLACE conflict resolution algorithm
69809** go a little faster.  But taking advantage of this time dependency
69810** makes it more difficult to prove that the code is correct (in
69811** particular, it prevents us from writing an effective
69812** implementation of sqlite3AssertMayAbort()) and so we have chosen
69813** to take the safe route and skip the optimization.
69814*/
69815SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
69816  Parse *pToplevel = sqlite3ParseToplevel(pParse);
69817  pToplevel->mayAbort = 1;
69818}
69819
69820/*
69821** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
69822** error. The onError parameter determines which (if any) of the statement
69823** and/or current transaction is rolled back.
69824*/
69825SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
69826  Vdbe *v = sqlite3GetVdbe(pParse);
69827  if( onError==OE_Abort ){
69828    sqlite3MayAbort(pParse);
69829  }
69830  sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
69831}
69832
69833/*
69834** Check to see if pIndex uses the collating sequence pColl.  Return
69835** true if it does and false if it does not.
69836*/
69837#ifndef SQLITE_OMIT_REINDEX
69838static int collationMatch(const char *zColl, Index *pIndex){
69839  int i;
69840  assert( zColl!=0 );
69841  for(i=0; i<pIndex->nColumn; i++){
69842    const char *z = pIndex->azColl[i];
69843    assert( z!=0 );
69844    if( 0==sqlite3StrICmp(z, zColl) ){
69845      return 1;
69846    }
69847  }
69848  return 0;
69849}
69850#endif
69851
69852/*
69853** Recompute all indices of pTab that use the collating sequence pColl.
69854** If pColl==0 then recompute all indices of pTab.
69855*/
69856#ifndef SQLITE_OMIT_REINDEX
69857static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
69858  Index *pIndex;              /* An index associated with pTab */
69859
69860  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
69861    if( zColl==0 || collationMatch(zColl, pIndex) ){
69862      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
69863      sqlite3BeginWriteOperation(pParse, 0, iDb);
69864      sqlite3RefillIndex(pParse, pIndex, -1);
69865    }
69866  }
69867}
69868#endif
69869
69870/*
69871** Recompute all indices of all tables in all databases where the
69872** indices use the collating sequence pColl.  If pColl==0 then recompute
69873** all indices everywhere.
69874*/
69875#ifndef SQLITE_OMIT_REINDEX
69876static void reindexDatabases(Parse *pParse, char const *zColl){
69877  Db *pDb;                    /* A single database */
69878  int iDb;                    /* The database index number */
69879  sqlite3 *db = pParse->db;   /* The database connection */
69880  HashElem *k;                /* For looping over tables in pDb */
69881  Table *pTab;                /* A table in the database */
69882
69883  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
69884    assert( pDb!=0 );
69885    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
69886      pTab = (Table*)sqliteHashData(k);
69887      reindexTable(pParse, pTab, zColl);
69888    }
69889  }
69890}
69891#endif
69892
69893/*
69894** Generate code for the REINDEX command.
69895**
69896**        REINDEX                            -- 1
69897**        REINDEX  <collation>               -- 2
69898**        REINDEX  ?<database>.?<tablename>  -- 3
69899**        REINDEX  ?<database>.?<indexname>  -- 4
69900**
69901** Form 1 causes all indices in all attached databases to be rebuilt.
69902** Form 2 rebuilds all indices in all databases that use the named
69903** collating function.  Forms 3 and 4 rebuild the named index or all
69904** indices associated with the named table.
69905*/
69906#ifndef SQLITE_OMIT_REINDEX
69907SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
69908  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
69909  char *z;                    /* Name of a table or index */
69910  const char *zDb;            /* Name of the database */
69911  Table *pTab;                /* A table in the database */
69912  Index *pIndex;              /* An index associated with pTab */
69913  int iDb;                    /* The database index number */
69914  sqlite3 *db = pParse->db;   /* The database connection */
69915  Token *pObjName;            /* Name of the table or index to be reindexed */
69916
69917  /* Read the database schema. If an error occurs, leave an error message
69918  ** and code in pParse and return NULL. */
69919  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
69920    return;
69921  }
69922
69923  if( pName1==0 ){
69924    reindexDatabases(pParse, 0);
69925    return;
69926  }else if( NEVER(pName2==0) || pName2->z==0 ){
69927    char *zColl;
69928    assert( pName1->z );
69929    zColl = sqlite3NameFromToken(pParse->db, pName1);
69930    if( !zColl ) return;
69931    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
69932    if( pColl ){
69933      reindexDatabases(pParse, zColl);
69934      sqlite3DbFree(db, zColl);
69935      return;
69936    }
69937    sqlite3DbFree(db, zColl);
69938  }
69939  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
69940  if( iDb<0 ) return;
69941  z = sqlite3NameFromToken(db, pObjName);
69942  if( z==0 ) return;
69943  zDb = db->aDb[iDb].zName;
69944  pTab = sqlite3FindTable(db, z, zDb);
69945  if( pTab ){
69946    reindexTable(pParse, pTab, 0);
69947    sqlite3DbFree(db, z);
69948    return;
69949  }
69950  pIndex = sqlite3FindIndex(db, z, zDb);
69951  sqlite3DbFree(db, z);
69952  if( pIndex ){
69953    sqlite3BeginWriteOperation(pParse, 0, iDb);
69954    sqlite3RefillIndex(pParse, pIndex, -1);
69955    return;
69956  }
69957  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
69958}
69959#endif
69960
69961/*
69962** Return a dynamicly allocated KeyInfo structure that can be used
69963** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
69964**
69965** If successful, a pointer to the new structure is returned. In this case
69966** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
69967** pointer. If an error occurs (out of memory or missing collation
69968** sequence), NULL is returned and the state of pParse updated to reflect
69969** the error.
69970*/
69971SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
69972  int i;
69973  int nCol = pIdx->nColumn;
69974  int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
69975  sqlite3 *db = pParse->db;
69976  KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
69977
69978  if( pKey ){
69979    pKey->db = pParse->db;
69980    pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
69981    assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
69982    for(i=0; i<nCol; i++){
69983      char *zColl = pIdx->azColl[i];
69984      assert( zColl );
69985      pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
69986      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
69987    }
69988    pKey->nField = (u16)nCol;
69989  }
69990
69991  if( pParse->nErr ){
69992    sqlite3DbFree(db, pKey);
69993    pKey = 0;
69994  }
69995  return pKey;
69996}
69997
69998/************** End of build.c ***********************************************/
69999/************** Begin file callback.c ****************************************/
70000/*
70001** 2005 May 23
70002**
70003** The author disclaims copyright to this source code.  In place of
70004** a legal notice, here is a blessing:
70005**
70006**    May you do good and not evil.
70007**    May you find forgiveness for yourself and forgive others.
70008**    May you share freely, never taking more than you give.
70009**
70010*************************************************************************
70011**
70012** This file contains functions used to access the internal hash tables
70013** of user defined functions and collation sequences.
70014*/
70015
70016
70017/*
70018** Invoke the 'collation needed' callback to request a collation sequence
70019** in the encoding enc of name zName, length nName.
70020*/
70021static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
70022  assert( !db->xCollNeeded || !db->xCollNeeded16 );
70023  if( db->xCollNeeded ){
70024    char *zExternal = sqlite3DbStrDup(db, zName);
70025    if( !zExternal ) return;
70026    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
70027    sqlite3DbFree(db, zExternal);
70028  }
70029#ifndef SQLITE_OMIT_UTF16
70030  if( db->xCollNeeded16 ){
70031    char const *zExternal;
70032    sqlite3_value *pTmp = sqlite3ValueNew(db);
70033    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
70034    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
70035    if( zExternal ){
70036      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
70037    }
70038    sqlite3ValueFree(pTmp);
70039  }
70040#endif
70041}
70042
70043/*
70044** This routine is called if the collation factory fails to deliver a
70045** collation function in the best encoding but there may be other versions
70046** of this collation function (for other text encodings) available. Use one
70047** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
70048** possible.
70049*/
70050static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
70051  CollSeq *pColl2;
70052  char *z = pColl->zName;
70053  int i;
70054  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
70055  for(i=0; i<3; i++){
70056    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
70057    if( pColl2->xCmp!=0 ){
70058      memcpy(pColl, pColl2, sizeof(CollSeq));
70059      pColl->xDel = 0;         /* Do not copy the destructor */
70060      return SQLITE_OK;
70061    }
70062  }
70063  return SQLITE_ERROR;
70064}
70065
70066/*
70067** This function is responsible for invoking the collation factory callback
70068** or substituting a collation sequence of a different encoding when the
70069** requested collation sequence is not available in the desired encoding.
70070**
70071** If it is not NULL, then pColl must point to the database native encoding
70072** collation sequence with name zName, length nName.
70073**
70074** The return value is either the collation sequence to be used in database
70075** db for collation type name zName, length nName, or NULL, if no collation
70076** sequence can be found.
70077**
70078** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
70079*/
70080SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
70081  sqlite3* db,          /* The database connection */
70082  u8 enc,               /* The desired encoding for the collating sequence */
70083  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
70084  const char *zName     /* Collating sequence name */
70085){
70086  CollSeq *p;
70087
70088  p = pColl;
70089  if( !p ){
70090    p = sqlite3FindCollSeq(db, enc, zName, 0);
70091  }
70092  if( !p || !p->xCmp ){
70093    /* No collation sequence of this type for this encoding is registered.
70094    ** Call the collation factory to see if it can supply us with one.
70095    */
70096    callCollNeeded(db, enc, zName);
70097    p = sqlite3FindCollSeq(db, enc, zName, 0);
70098  }
70099  if( p && !p->xCmp && synthCollSeq(db, p) ){
70100    p = 0;
70101  }
70102  assert( !p || p->xCmp );
70103  return p;
70104}
70105
70106/*
70107** This routine is called on a collation sequence before it is used to
70108** check that it is defined. An undefined collation sequence exists when
70109** a database is loaded that contains references to collation sequences
70110** that have not been defined by sqlite3_create_collation() etc.
70111**
70112** If required, this routine calls the 'collation needed' callback to
70113** request a definition of the collating sequence. If this doesn't work,
70114** an equivalent collating sequence that uses a text encoding different
70115** from the main database is substituted, if one is available.
70116*/
70117SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
70118  if( pColl ){
70119    const char *zName = pColl->zName;
70120    sqlite3 *db = pParse->db;
70121    CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
70122    if( !p ){
70123      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
70124      pParse->nErr++;
70125      return SQLITE_ERROR;
70126    }
70127    assert( p==pColl );
70128  }
70129  return SQLITE_OK;
70130}
70131
70132
70133
70134/*
70135** Locate and return an entry from the db.aCollSeq hash table. If the entry
70136** specified by zName and nName is not found and parameter 'create' is
70137** true, then create a new entry. Otherwise return NULL.
70138**
70139** Each pointer stored in the sqlite3.aCollSeq hash table contains an
70140** array of three CollSeq structures. The first is the collation sequence
70141** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
70142**
70143** Stored immediately after the three collation sequences is a copy of
70144** the collation sequence name. A pointer to this string is stored in
70145** each collation sequence structure.
70146*/
70147static CollSeq *findCollSeqEntry(
70148  sqlite3 *db,          /* Database connection */
70149  const char *zName,    /* Name of the collating sequence */
70150  int create            /* Create a new entry if true */
70151){
70152  CollSeq *pColl;
70153  int nName = sqlite3Strlen30(zName);
70154  pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
70155
70156  if( 0==pColl && create ){
70157    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
70158    if( pColl ){
70159      CollSeq *pDel = 0;
70160      pColl[0].zName = (char*)&pColl[3];
70161      pColl[0].enc = SQLITE_UTF8;
70162      pColl[1].zName = (char*)&pColl[3];
70163      pColl[1].enc = SQLITE_UTF16LE;
70164      pColl[2].zName = (char*)&pColl[3];
70165      pColl[2].enc = SQLITE_UTF16BE;
70166      memcpy(pColl[0].zName, zName, nName);
70167      pColl[0].zName[nName] = 0;
70168      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
70169
70170      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
70171      ** return the pColl pointer to be deleted (because it wasn't added
70172      ** to the hash table).
70173      */
70174      assert( pDel==0 || pDel==pColl );
70175      if( pDel!=0 ){
70176        db->mallocFailed = 1;
70177        sqlite3DbFree(db, pDel);
70178        pColl = 0;
70179      }
70180    }
70181  }
70182  return pColl;
70183}
70184
70185/*
70186** Parameter zName points to a UTF-8 encoded string nName bytes long.
70187** Return the CollSeq* pointer for the collation sequence named zName
70188** for the encoding 'enc' from the database 'db'.
70189**
70190** If the entry specified is not found and 'create' is true, then create a
70191** new entry.  Otherwise return NULL.
70192**
70193** A separate function sqlite3LocateCollSeq() is a wrapper around
70194** this routine.  sqlite3LocateCollSeq() invokes the collation factory
70195** if necessary and generates an error message if the collating sequence
70196** cannot be found.
70197**
70198** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
70199*/
70200SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
70201  sqlite3 *db,
70202  u8 enc,
70203  const char *zName,
70204  int create
70205){
70206  CollSeq *pColl;
70207  if( zName ){
70208    pColl = findCollSeqEntry(db, zName, create);
70209  }else{
70210    pColl = db->pDfltColl;
70211  }
70212  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
70213  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
70214  if( pColl ) pColl += enc-1;
70215  return pColl;
70216}
70217
70218/* During the search for the best function definition, this procedure
70219** is called to test how well the function passed as the first argument
70220** matches the request for a function with nArg arguments in a system
70221** that uses encoding enc. The value returned indicates how well the
70222** request is matched. A higher value indicates a better match.
70223**
70224** The returned value is always between 0 and 6, as follows:
70225**
70226** 0: Not a match, or if nArg<0 and the function is has no implementation.
70227** 1: A variable arguments function that prefers UTF-8 when a UTF-16
70228**    encoding is requested, or vice versa.
70229** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
70230**    requested, or vice versa.
70231** 3: A variable arguments function using the same text encoding.
70232** 4: A function with the exact number of arguments requested that
70233**    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
70234** 5: A function with the exact number of arguments requested that
70235**    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
70236** 6: An exact match.
70237**
70238*/
70239static int matchQuality(FuncDef *p, int nArg, u8 enc){
70240  int match = 0;
70241  if( p->nArg==-1 || p->nArg==nArg
70242   || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
70243  ){
70244    match = 1;
70245    if( p->nArg==nArg || nArg==-1 ){
70246      match = 4;
70247    }
70248    if( enc==p->iPrefEnc ){
70249      match += 2;
70250    }
70251    else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
70252             (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
70253      match += 1;
70254    }
70255  }
70256  return match;
70257}
70258
70259/*
70260** Search a FuncDefHash for a function with the given name.  Return
70261** a pointer to the matching FuncDef if found, or 0 if there is no match.
70262*/
70263static FuncDef *functionSearch(
70264  FuncDefHash *pHash,  /* Hash table to search */
70265  int h,               /* Hash of the name */
70266  const char *zFunc,   /* Name of function */
70267  int nFunc            /* Number of bytes in zFunc */
70268){
70269  FuncDef *p;
70270  for(p=pHash->a[h]; p; p=p->pHash){
70271    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
70272      return p;
70273    }
70274  }
70275  return 0;
70276}
70277
70278/*
70279** Insert a new FuncDef into a FuncDefHash hash table.
70280*/
70281SQLITE_PRIVATE void sqlite3FuncDefInsert(
70282  FuncDefHash *pHash,  /* The hash table into which to insert */
70283  FuncDef *pDef        /* The function definition to insert */
70284){
70285  FuncDef *pOther;
70286  int nName = sqlite3Strlen30(pDef->zName);
70287  u8 c1 = (u8)pDef->zName[0];
70288  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
70289  pOther = functionSearch(pHash, h, pDef->zName, nName);
70290  if( pOther ){
70291    assert( pOther!=pDef && pOther->pNext!=pDef );
70292    pDef->pNext = pOther->pNext;
70293    pOther->pNext = pDef;
70294  }else{
70295    pDef->pNext = 0;
70296    pDef->pHash = pHash->a[h];
70297    pHash->a[h] = pDef;
70298  }
70299}
70300
70301
70302
70303/*
70304** Locate a user function given a name, a number of arguments and a flag
70305** indicating whether the function prefers UTF-16 over UTF-8.  Return a
70306** pointer to the FuncDef structure that defines that function, or return
70307** NULL if the function does not exist.
70308**
70309** If the createFlag argument is true, then a new (blank) FuncDef
70310** structure is created and liked into the "db" structure if a
70311** no matching function previously existed.  When createFlag is true
70312** and the nArg parameter is -1, then only a function that accepts
70313** any number of arguments will be returned.
70314**
70315** If createFlag is false and nArg is -1, then the first valid
70316** function found is returned.  A function is valid if either xFunc
70317** or xStep is non-zero.
70318**
70319** If createFlag is false, then a function with the required name and
70320** number of arguments may be returned even if the eTextRep flag does not
70321** match that requested.
70322*/
70323SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
70324  sqlite3 *db,       /* An open database */
70325  const char *zName, /* Name of the function.  Not null-terminated */
70326  int nName,         /* Number of characters in the name */
70327  int nArg,          /* Number of arguments.  -1 means any number */
70328  u8 enc,            /* Preferred text encoding */
70329  int createFlag     /* Create new entry if true and does not otherwise exist */
70330){
70331  FuncDef *p;         /* Iterator variable */
70332  FuncDef *pBest = 0; /* Best match found so far */
70333  int bestScore = 0;  /* Score of best match */
70334  int h;              /* Hash value */
70335
70336
70337  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
70338  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
70339
70340  /* First search for a match amongst the application-defined functions.
70341  */
70342  p = functionSearch(&db->aFunc, h, zName, nName);
70343  while( p ){
70344    int score = matchQuality(p, nArg, enc);
70345    if( score>bestScore ){
70346      pBest = p;
70347      bestScore = score;
70348    }
70349    p = p->pNext;
70350  }
70351
70352  /* If no match is found, search the built-in functions.
70353  **
70354  ** Except, if createFlag is true, that means that we are trying to
70355  ** install a new function.  Whatever FuncDef structure is returned will
70356  ** have fields overwritten with new information appropriate for the
70357  ** new function.  But the FuncDefs for built-in functions are read-only.
70358  ** So we must not search for built-ins when creating a new function.
70359  */
70360  if( !createFlag && !pBest ){
70361    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
70362    p = functionSearch(pHash, h, zName, nName);
70363    while( p ){
70364      int score = matchQuality(p, nArg, enc);
70365      if( score>bestScore ){
70366        pBest = p;
70367        bestScore = score;
70368      }
70369      p = p->pNext;
70370    }
70371  }
70372
70373  /* If the createFlag parameter is true and the search did not reveal an
70374  ** exact match for the name, number of arguments and encoding, then add a
70375  ** new entry to the hash table and return it.
70376  */
70377  if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
70378      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
70379    pBest->zName = (char *)&pBest[1];
70380    pBest->nArg = (u16)nArg;
70381    pBest->iPrefEnc = enc;
70382    memcpy(pBest->zName, zName, nName);
70383    pBest->zName[nName] = 0;
70384    sqlite3FuncDefInsert(&db->aFunc, pBest);
70385  }
70386
70387  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
70388    return pBest;
70389  }
70390  return 0;
70391}
70392
70393/*
70394** Free all resources held by the schema structure. The void* argument points
70395** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
70396** pointer itself, it just cleans up subsiduary resources (i.e. the contents
70397** of the schema hash tables).
70398**
70399** The Schema.cache_size variable is not cleared.
70400*/
70401SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
70402  Hash temp1;
70403  Hash temp2;
70404  HashElem *pElem;
70405  Schema *pSchema = (Schema *)p;
70406
70407  temp1 = pSchema->tblHash;
70408  temp2 = pSchema->trigHash;
70409  sqlite3HashInit(&pSchema->trigHash);
70410  sqlite3HashClear(&pSchema->idxHash);
70411  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
70412    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
70413  }
70414  sqlite3HashClear(&temp2);
70415  sqlite3HashInit(&pSchema->tblHash);
70416  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
70417    Table *pTab = sqliteHashData(pElem);
70418    assert( pTab->dbMem==0 );
70419    sqlite3DeleteTable(pTab);
70420  }
70421  sqlite3HashClear(&temp1);
70422  sqlite3HashClear(&pSchema->fkeyHash);
70423  pSchema->pSeqTab = 0;
70424  pSchema->flags &= ~DB_SchemaLoaded;
70425}
70426
70427/*
70428** Find and return the schema associated with a BTree.  Create
70429** a new one if necessary.
70430*/
70431SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
70432  Schema * p;
70433  if( pBt ){
70434    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
70435  }else{
70436    p = (Schema *)sqlite3MallocZero(sizeof(Schema));
70437  }
70438  if( !p ){
70439    db->mallocFailed = 1;
70440  }else if ( 0==p->file_format ){
70441    sqlite3HashInit(&p->tblHash);
70442    sqlite3HashInit(&p->idxHash);
70443    sqlite3HashInit(&p->trigHash);
70444    sqlite3HashInit(&p->fkeyHash);
70445    p->enc = SQLITE_UTF8;
70446  }
70447  return p;
70448}
70449
70450/************** End of callback.c ********************************************/
70451/************** Begin file delete.c ******************************************/
70452/*
70453** 2001 September 15
70454**
70455** The author disclaims copyright to this source code.  In place of
70456** a legal notice, here is a blessing:
70457**
70458**    May you do good and not evil.
70459**    May you find forgiveness for yourself and forgive others.
70460**    May you share freely, never taking more than you give.
70461**
70462*************************************************************************
70463** This file contains C code routines that are called by the parser
70464** in order to generate code for DELETE FROM statements.
70465*/
70466
70467/*
70468** Look up every table that is named in pSrc.  If any table is not found,
70469** add an error message to pParse->zErrMsg and return NULL.  If all tables
70470** are found, return a pointer to the last table.
70471*/
70472SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
70473  struct SrcList_item *pItem = pSrc->a;
70474  Table *pTab;
70475  assert( pItem && pSrc->nSrc==1 );
70476  pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
70477  sqlite3DeleteTable(pItem->pTab);
70478  pItem->pTab = pTab;
70479  if( pTab ){
70480    pTab->nRef++;
70481  }
70482  if( sqlite3IndexedByLookup(pParse, pItem) ){
70483    pTab = 0;
70484  }
70485  return pTab;
70486}
70487
70488/*
70489** Check to make sure the given table is writable.  If it is not
70490** writable, generate an error message and return 1.  If it is
70491** writable return 0;
70492*/
70493SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
70494  /* A table is not writable under the following circumstances:
70495  **
70496  **   1) It is a virtual table and no implementation of the xUpdate method
70497  **      has been provided, or
70498  **   2) It is a system table (i.e. sqlite_master), this call is not
70499  **      part of a nested parse and writable_schema pragma has not
70500  **      been specified.
70501  **
70502  ** In either case leave an error message in pParse and return non-zero.
70503  */
70504  if( ( IsVirtual(pTab)
70505     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
70506   || ( (pTab->tabFlags & TF_Readonly)!=0
70507     && (pParse->db->flags & SQLITE_WriteSchema)==0
70508     && pParse->nested==0 )
70509  ){
70510    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
70511    return 1;
70512  }
70513
70514#ifndef SQLITE_OMIT_VIEW
70515  if( !viewOk && pTab->pSelect ){
70516    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
70517    return 1;
70518  }
70519#endif
70520  return 0;
70521}
70522
70523
70524#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
70525/*
70526** Evaluate a view and store its result in an ephemeral table.  The
70527** pWhere argument is an optional WHERE clause that restricts the
70528** set of rows in the view that are to be added to the ephemeral table.
70529*/
70530SQLITE_PRIVATE void sqlite3MaterializeView(
70531  Parse *pParse,       /* Parsing context */
70532  Table *pView,        /* View definition */
70533  Expr *pWhere,        /* Optional WHERE clause to be added */
70534  int iCur             /* Cursor number for ephemerial table */
70535){
70536  SelectDest dest;
70537  Select *pDup;
70538  sqlite3 *db = pParse->db;
70539
70540  pDup = sqlite3SelectDup(db, pView->pSelect, 0);
70541  if( pWhere ){
70542    SrcList *pFrom;
70543
70544    pWhere = sqlite3ExprDup(db, pWhere, 0);
70545    pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
70546    if( pFrom ){
70547      assert( pFrom->nSrc==1 );
70548      pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
70549      pFrom->a[0].pSelect = pDup;
70550      assert( pFrom->a[0].pOn==0 );
70551      assert( pFrom->a[0].pUsing==0 );
70552    }else{
70553      sqlite3SelectDelete(db, pDup);
70554    }
70555    pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
70556  }
70557  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
70558  sqlite3Select(pParse, pDup, &dest);
70559  sqlite3SelectDelete(db, pDup);
70560}
70561#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
70562
70563#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
70564/*
70565** Generate an expression tree to implement the WHERE, ORDER BY,
70566** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
70567**
70568**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
70569**                            \__________________________/
70570**                               pLimitWhere (pInClause)
70571*/
70572SQLITE_PRIVATE Expr *sqlite3LimitWhere(
70573  Parse *pParse,               /* The parser context */
70574  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
70575  Expr *pWhere,                /* The WHERE clause.  May be null */
70576  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
70577  Expr *pLimit,                /* The LIMIT clause.  May be null */
70578  Expr *pOffset,               /* The OFFSET clause.  May be null */
70579  char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
70580){
70581  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
70582  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
70583  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
70584  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
70585  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
70586  Select *pSelect = NULL;      /* Complete SELECT tree */
70587
70588  /* Check that there isn't an ORDER BY without a LIMIT clause.
70589  */
70590  if( pOrderBy && (pLimit == 0) ) {
70591    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
70592    pParse->parseError = 1;
70593    goto limit_where_cleanup_2;
70594  }
70595
70596  /* We only need to generate a select expression if there
70597  ** is a limit/offset term to enforce.
70598  */
70599  if( pLimit == 0 ) {
70600    /* if pLimit is null, pOffset will always be null as well. */
70601    assert( pOffset == 0 );
70602    return pWhere;
70603  }
70604
70605  /* Generate a select expression tree to enforce the limit/offset
70606  ** term for the DELETE or UPDATE statement.  For example:
70607  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
70608  ** becomes:
70609  **   DELETE FROM table_a WHERE rowid IN (
70610  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
70611  **   );
70612  */
70613
70614  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
70615  if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
70616  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
70617  if( pEList == 0 ) goto limit_where_cleanup_2;
70618
70619  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
70620  ** and the SELECT subtree. */
70621  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
70622  if( pSelectSrc == 0 ) {
70623    sqlite3ExprListDelete(pParse->db, pEList);
70624    goto limit_where_cleanup_2;
70625  }
70626
70627  /* generate the SELECT expression tree. */
70628  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
70629                             pOrderBy,0,pLimit,pOffset);
70630  if( pSelect == 0 ) return 0;
70631
70632  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
70633  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
70634  if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
70635  pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
70636  if( pInClause == 0 ) goto limit_where_cleanup_1;
70637
70638  pInClause->x.pSelect = pSelect;
70639  pInClause->flags |= EP_xIsSelect;
70640  sqlite3ExprSetHeight(pParse, pInClause);
70641  return pInClause;
70642
70643  /* something went wrong. clean up anything allocated. */
70644limit_where_cleanup_1:
70645  sqlite3SelectDelete(pParse->db, pSelect);
70646  return 0;
70647
70648limit_where_cleanup_2:
70649  sqlite3ExprDelete(pParse->db, pWhere);
70650  sqlite3ExprListDelete(pParse->db, pOrderBy);
70651  sqlite3ExprDelete(pParse->db, pLimit);
70652  sqlite3ExprDelete(pParse->db, pOffset);
70653  return 0;
70654}
70655#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
70656
70657/*
70658** Generate code for a DELETE FROM statement.
70659**
70660**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
70661**                 \________/       \________________/
70662**                  pTabList              pWhere
70663*/
70664SQLITE_PRIVATE void sqlite3DeleteFrom(
70665  Parse *pParse,         /* The parser context */
70666  SrcList *pTabList,     /* The table from which we should delete things */
70667  Expr *pWhere           /* The WHERE clause.  May be null */
70668){
70669  Vdbe *v;               /* The virtual database engine */
70670  Table *pTab;           /* The table from which records will be deleted */
70671  const char *zDb;       /* Name of database holding pTab */
70672  int end, addr = 0;     /* A couple addresses of generated code */
70673  int i;                 /* Loop counter */
70674  WhereInfo *pWInfo;     /* Information about the WHERE clause */
70675  Index *pIdx;           /* For looping over indices of the table */
70676  int iCur;              /* VDBE Cursor number for pTab */
70677  sqlite3 *db;           /* Main database structure */
70678  AuthContext sContext;  /* Authorization context */
70679  NameContext sNC;       /* Name context to resolve expressions in */
70680  int iDb;               /* Database number */
70681  int memCnt = -1;       /* Memory cell used for change counting */
70682  int rcauth;            /* Value returned by authorization callback */
70683
70684#ifndef SQLITE_OMIT_TRIGGER
70685  int isView;                  /* True if attempting to delete from a view */
70686  Trigger *pTrigger;           /* List of table triggers, if required */
70687#endif
70688
70689  memset(&sContext, 0, sizeof(sContext));
70690  db = pParse->db;
70691  if( pParse->nErr || db->mallocFailed ){
70692    goto delete_from_cleanup;
70693  }
70694  assert( pTabList->nSrc==1 );
70695
70696  /* Locate the table which we want to delete.  This table has to be
70697  ** put in an SrcList structure because some of the subroutines we
70698  ** will be calling are designed to work with multiple tables and expect
70699  ** an SrcList* parameter instead of just a Table* parameter.
70700  */
70701  pTab = sqlite3SrcListLookup(pParse, pTabList);
70702  if( pTab==0 )  goto delete_from_cleanup;
70703
70704  /* Figure out if we have any triggers and if the table being
70705  ** deleted from is a view
70706  */
70707#ifndef SQLITE_OMIT_TRIGGER
70708  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
70709  isView = pTab->pSelect!=0;
70710#else
70711# define pTrigger 0
70712# define isView 0
70713#endif
70714#ifdef SQLITE_OMIT_VIEW
70715# undef isView
70716# define isView 0
70717#endif
70718
70719  /* If pTab is really a view, make sure it has been initialized.
70720  */
70721  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
70722    goto delete_from_cleanup;
70723  }
70724
70725  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
70726    goto delete_from_cleanup;
70727  }
70728  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
70729  assert( iDb<db->nDb );
70730  zDb = db->aDb[iDb].zName;
70731  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
70732  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
70733  if( rcauth==SQLITE_DENY ){
70734    goto delete_from_cleanup;
70735  }
70736  assert(!isView || pTrigger);
70737
70738  /* Assign  cursor number to the table and all its indices.
70739  */
70740  assert( pTabList->nSrc==1 );
70741  iCur = pTabList->a[0].iCursor = pParse->nTab++;
70742  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
70743    pParse->nTab++;
70744  }
70745
70746  /* Start the view context
70747  */
70748  if( isView ){
70749    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
70750  }
70751
70752  /* Begin generating code.
70753  */
70754  v = sqlite3GetVdbe(pParse);
70755  if( v==0 ){
70756    goto delete_from_cleanup;
70757  }
70758  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
70759  sqlite3BeginWriteOperation(pParse, 1, iDb);
70760
70761  /* If we are trying to delete from a view, realize that view into
70762  ** a ephemeral table.
70763  */
70764#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
70765  if( isView ){
70766    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
70767  }
70768#endif
70769
70770  /* Resolve the column names in the WHERE clause.
70771  */
70772  memset(&sNC, 0, sizeof(sNC));
70773  sNC.pParse = pParse;
70774  sNC.pSrcList = pTabList;
70775  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
70776    goto delete_from_cleanup;
70777  }
70778
70779  /* Initialize the counter of the number of rows deleted, if
70780  ** we are counting rows.
70781  */
70782  if( db->flags & SQLITE_CountRows ){
70783    memCnt = ++pParse->nMem;
70784    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
70785  }
70786
70787#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
70788  /* Special case: A DELETE without a WHERE clause deletes everything.
70789  ** It is easier just to erase the whole table. Prior to version 3.6.5,
70790  ** this optimization caused the row change count (the value returned by
70791  ** API function sqlite3_count_changes) to be set incorrectly.  */
70792  if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
70793   && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
70794  ){
70795    assert( !isView );
70796    sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
70797                      pTab->zName, P4_STATIC);
70798    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
70799      assert( pIdx->pSchema==pTab->pSchema );
70800      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
70801    }
70802  }else
70803#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
70804  /* The usual case: There is a WHERE clause so we have to scan through
70805  ** the table and pick which records to delete.
70806  */
70807  {
70808    int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
70809    int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
70810    int regRowid;                   /* Actual register containing rowids */
70811
70812    /* Collect rowids of every row to be deleted.
70813    */
70814    sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
70815    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
70816    if( pWInfo==0 ) goto delete_from_cleanup;
70817    regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
70818    sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
70819    if( db->flags & SQLITE_CountRows ){
70820      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
70821    }
70822    sqlite3WhereEnd(pWInfo);
70823
70824    /* Delete every item whose key was written to the list during the
70825    ** database scan.  We have to delete items after the scan is complete
70826    ** because deleting an item can change the scan order.  */
70827    end = sqlite3VdbeMakeLabel(v);
70828
70829    /* Unless this is a view, open cursors for the table we are
70830    ** deleting from and all its indices. If this is a view, then the
70831    ** only effect this statement has is to fire the INSTEAD OF
70832    ** triggers.  */
70833    if( !isView ){
70834      sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
70835    }
70836
70837    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
70838
70839    /* Delete the row */
70840#ifndef SQLITE_OMIT_VIRTUALTABLE
70841    if( IsVirtual(pTab) ){
70842      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
70843      sqlite3VtabMakeWritable(pParse, pTab);
70844      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
70845      sqlite3MayAbort(pParse);
70846    }else
70847#endif
70848    {
70849      int count = (pParse->nested==0);    /* True to count changes */
70850      sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
70851    }
70852
70853    /* End of the delete loop */
70854    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
70855    sqlite3VdbeResolveLabel(v, end);
70856
70857    /* Close the cursors open on the table and its indexes. */
70858    if( !isView && !IsVirtual(pTab) ){
70859      for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
70860        sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
70861      }
70862      sqlite3VdbeAddOp1(v, OP_Close, iCur);
70863    }
70864  }
70865
70866  /* Update the sqlite_sequence table by storing the content of the
70867  ** maximum rowid counter values recorded while inserting into
70868  ** autoincrement tables.
70869  */
70870  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
70871    sqlite3AutoincrementEnd(pParse);
70872  }
70873
70874  /* Return the number of rows that were deleted. If this routine is
70875  ** generating code because of a call to sqlite3NestedParse(), do not
70876  ** invoke the callback function.
70877  */
70878  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
70879    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
70880    sqlite3VdbeSetNumCols(v, 1);
70881    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
70882  }
70883
70884delete_from_cleanup:
70885  sqlite3AuthContextPop(&sContext);
70886  sqlite3SrcListDelete(db, pTabList);
70887  sqlite3ExprDelete(db, pWhere);
70888  return;
70889}
70890/* Make sure "isView" and other macros defined above are undefined. Otherwise
70891** thely may interfere with compilation of other functions in this file
70892** (or in another file, if this file becomes part of the amalgamation).  */
70893#ifdef isView
70894 #undef isView
70895#endif
70896#ifdef pTrigger
70897 #undef pTrigger
70898#endif
70899
70900/*
70901** This routine generates VDBE code that causes a single row of a
70902** single table to be deleted.
70903**
70904** The VDBE must be in a particular state when this routine is called.
70905** These are the requirements:
70906**
70907**   1.  A read/write cursor pointing to pTab, the table containing the row
70908**       to be deleted, must be opened as cursor number $iCur.
70909**
70910**   2.  Read/write cursors for all indices of pTab must be open as
70911**       cursor number base+i for the i-th index.
70912**
70913**   3.  The record number of the row to be deleted must be stored in
70914**       memory cell iRowid.
70915**
70916** This routine generates code to remove both the table record and all
70917** index entries that point to that record.
70918*/
70919SQLITE_PRIVATE void sqlite3GenerateRowDelete(
70920  Parse *pParse,     /* Parsing context */
70921  Table *pTab,       /* Table containing the row to be deleted */
70922  int iCur,          /* Cursor number for the table */
70923  int iRowid,        /* Memory cell that contains the rowid to delete */
70924  int count,         /* If non-zero, increment the row change counter */
70925  Trigger *pTrigger, /* List of triggers to (potentially) fire */
70926  int onconf         /* Default ON CONFLICT policy for triggers */
70927){
70928  Vdbe *v = pParse->pVdbe;        /* Vdbe */
70929  int iOld = 0;                   /* First register in OLD.* array */
70930  int iLabel;                     /* Label resolved to end of generated code */
70931
70932  /* Vdbe is guaranteed to have been allocated by this stage. */
70933  assert( v );
70934
70935  /* Seek cursor iCur to the row to delete. If this row no longer exists
70936  ** (this can happen if a trigger program has already deleted it), do
70937  ** not attempt to delete it or fire any DELETE triggers.  */
70938  iLabel = sqlite3VdbeMakeLabel(v);
70939  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
70940
70941  /* If there are any triggers to fire, allocate a range of registers to
70942  ** use for the old.* references in the triggers.  */
70943  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
70944    u32 mask;                     /* Mask of OLD.* columns in use */
70945    int iCol;                     /* Iterator used while populating OLD.* */
70946
70947    /* TODO: Could use temporary registers here. Also could attempt to
70948    ** avoid copying the contents of the rowid register.  */
70949    mask = sqlite3TriggerColmask(
70950        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
70951    );
70952    mask |= sqlite3FkOldmask(pParse, pTab);
70953    iOld = pParse->nMem+1;
70954    pParse->nMem += (1 + pTab->nCol);
70955
70956    /* Populate the OLD.* pseudo-table register array. These values will be
70957    ** used by any BEFORE and AFTER triggers that exist.  */
70958    sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
70959    for(iCol=0; iCol<pTab->nCol; iCol++){
70960      if( mask==0xffffffff || mask&(1<<iCol) ){
70961        int iTarget = iOld + iCol + 1;
70962        sqlite3VdbeAddOp3(v, OP_Column, iCur, iCol, iTarget);
70963        sqlite3ColumnDefault(v, pTab, iCol, iTarget);
70964      }
70965    }
70966
70967    /* Invoke BEFORE DELETE trigger programs. */
70968    sqlite3CodeRowTrigger(pParse, pTrigger,
70969        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
70970    );
70971
70972    /* Seek the cursor to the row to be deleted again. It may be that
70973    ** the BEFORE triggers coded above have already removed the row
70974    ** being deleted. Do not attempt to delete the row a second time, and
70975    ** do not fire AFTER triggers.  */
70976    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
70977
70978    /* Do FK processing. This call checks that any FK constraints that
70979    ** refer to this table (i.e. constraints attached to other tables)
70980    ** are not violated by deleting this row.  */
70981    sqlite3FkCheck(pParse, pTab, iOld, 0);
70982  }
70983
70984  /* Delete the index and table entries. Skip this step if pTab is really
70985  ** a view (in which case the only effect of the DELETE statement is to
70986  ** fire the INSTEAD OF triggers).  */
70987  if( pTab->pSelect==0 ){
70988    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
70989    sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
70990    if( count ){
70991      sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
70992    }
70993  }
70994
70995  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
70996  ** handle rows (possibly in other tables) that refer via a foreign key
70997  ** to the row just deleted. */
70998  sqlite3FkActions(pParse, pTab, 0, iOld);
70999
71000  /* Invoke AFTER DELETE trigger programs. */
71001  sqlite3CodeRowTrigger(pParse, pTrigger,
71002      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
71003  );
71004
71005  /* Jump here if the row had already been deleted before any BEFORE
71006  ** trigger programs were invoked. Or if a trigger program throws a
71007  ** RAISE(IGNORE) exception.  */
71008  sqlite3VdbeResolveLabel(v, iLabel);
71009}
71010
71011/*
71012** This routine generates VDBE code that causes the deletion of all
71013** index entries associated with a single row of a single table.
71014**
71015** The VDBE must be in a particular state when this routine is called.
71016** These are the requirements:
71017**
71018**   1.  A read/write cursor pointing to pTab, the table containing the row
71019**       to be deleted, must be opened as cursor number "iCur".
71020**
71021**   2.  Read/write cursors for all indices of pTab must be open as
71022**       cursor number iCur+i for the i-th index.
71023**
71024**   3.  The "iCur" cursor must be pointing to the row that is to be
71025**       deleted.
71026*/
71027SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
71028  Parse *pParse,     /* Parsing and code generating context */
71029  Table *pTab,       /* Table containing the row to be deleted */
71030  int iCur,          /* Cursor number for the table */
71031  int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
71032){
71033  int i;
71034  Index *pIdx;
71035  int r1;
71036
71037  for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
71038    if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
71039    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
71040    sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
71041  }
71042}
71043
71044/*
71045** Generate code that will assemble an index key and put it in register
71046** regOut.  The key with be for index pIdx which is an index on pTab.
71047** iCur is the index of a cursor open on the pTab table and pointing to
71048** the entry that needs indexing.
71049**
71050** Return a register number which is the first in a block of
71051** registers that holds the elements of the index key.  The
71052** block of registers has already been deallocated by the time
71053** this routine returns.
71054*/
71055SQLITE_PRIVATE int sqlite3GenerateIndexKey(
71056  Parse *pParse,     /* Parsing context */
71057  Index *pIdx,       /* The index for which to generate a key */
71058  int iCur,          /* Cursor number for the pIdx->pTable table */
71059  int regOut,        /* Write the new index key to this register */
71060  int doMakeRec      /* Run the OP_MakeRecord instruction if true */
71061){
71062  Vdbe *v = pParse->pVdbe;
71063  int j;
71064  Table *pTab = pIdx->pTable;
71065  int regBase;
71066  int nCol;
71067
71068  nCol = pIdx->nColumn;
71069  regBase = sqlite3GetTempRange(pParse, nCol+1);
71070  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
71071  for(j=0; j<nCol; j++){
71072    int idx = pIdx->aiColumn[j];
71073    if( idx==pTab->iPKey ){
71074      sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
71075    }else{
71076      sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
71077      sqlite3ColumnDefault(v, pTab, idx, -1);
71078    }
71079  }
71080  if( doMakeRec ){
71081    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
71082    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
71083  }
71084  sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
71085  return regBase;
71086}
71087
71088/************** End of delete.c **********************************************/
71089/************** Begin file func.c ********************************************/
71090/*
71091** 2002 February 23
71092**
71093** The author disclaims copyright to this source code.  In place of
71094** a legal notice, here is a blessing:
71095**
71096**    May you do good and not evil.
71097**    May you find forgiveness for yourself and forgive others.
71098**    May you share freely, never taking more than you give.
71099**
71100*************************************************************************
71101** This file contains the C functions that implement various SQL
71102** functions of SQLite.
71103**
71104** There is only one exported symbol in this file - the function
71105** sqliteRegisterBuildinFunctions() found at the bottom of the file.
71106** All other code has file scope.
71107*/
71108
71109/*
71110** Return the collating function associated with a function.
71111*/
71112static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
71113  return context->pColl;
71114}
71115
71116/*
71117** Implementation of the non-aggregate min() and max() functions
71118*/
71119static void minmaxFunc(
71120  sqlite3_context *context,
71121  int argc,
71122  sqlite3_value **argv
71123){
71124  int i;
71125  int mask;    /* 0 for min() or 0xffffffff for max() */
71126  int iBest;
71127  CollSeq *pColl;
71128
71129  assert( argc>1 );
71130  mask = sqlite3_user_data(context)==0 ? 0 : -1;
71131  pColl = sqlite3GetFuncCollSeq(context);
71132  assert( pColl );
71133  assert( mask==-1 || mask==0 );
71134  iBest = 0;
71135  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
71136  for(i=1; i<argc; i++){
71137    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
71138    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
71139      testcase( mask==0 );
71140      iBest = i;
71141    }
71142  }
71143  sqlite3_result_value(context, argv[iBest]);
71144}
71145
71146/*
71147** Return the type of the argument.
71148*/
71149static void typeofFunc(
71150  sqlite3_context *context,
71151  int NotUsed,
71152  sqlite3_value **argv
71153){
71154  const char *z = 0;
71155  UNUSED_PARAMETER(NotUsed);
71156  switch( sqlite3_value_type(argv[0]) ){
71157    case SQLITE_INTEGER: z = "integer"; break;
71158    case SQLITE_TEXT:    z = "text";    break;
71159    case SQLITE_FLOAT:   z = "real";    break;
71160    case SQLITE_BLOB:    z = "blob";    break;
71161    default:             z = "null";    break;
71162  }
71163  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
71164}
71165
71166
71167/*
71168** Implementation of the length() function
71169*/
71170static void lengthFunc(
71171  sqlite3_context *context,
71172  int argc,
71173  sqlite3_value **argv
71174){
71175  int len;
71176
71177  assert( argc==1 );
71178  UNUSED_PARAMETER(argc);
71179  switch( sqlite3_value_type(argv[0]) ){
71180    case SQLITE_BLOB:
71181    case SQLITE_INTEGER:
71182    case SQLITE_FLOAT: {
71183      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
71184      break;
71185    }
71186    case SQLITE_TEXT: {
71187      const unsigned char *z = sqlite3_value_text(argv[0]);
71188      if( z==0 ) return;
71189      len = 0;
71190      while( *z ){
71191        len++;
71192        SQLITE_SKIP_UTF8(z);
71193      }
71194      sqlite3_result_int(context, len);
71195      break;
71196    }
71197    default: {
71198      sqlite3_result_null(context);
71199      break;
71200    }
71201  }
71202}
71203
71204/*
71205** Implementation of the abs() function.
71206**
71207** IMP: R-23979-26855 The abs(X) function returns the absolute value of
71208** the numeric argument X.
71209*/
71210static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71211  assert( argc==1 );
71212  UNUSED_PARAMETER(argc);
71213  switch( sqlite3_value_type(argv[0]) ){
71214    case SQLITE_INTEGER: {
71215      i64 iVal = sqlite3_value_int64(argv[0]);
71216      if( iVal<0 ){
71217        if( (iVal<<1)==0 ){
71218          /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
71219          ** abs(X) throws an integer overflow error since there is no
71220          ** equivalent positive 64-bit two complement value. */
71221          sqlite3_result_error(context, "integer overflow", -1);
71222          return;
71223        }
71224        iVal = -iVal;
71225      }
71226      sqlite3_result_int64(context, iVal);
71227      break;
71228    }
71229    case SQLITE_NULL: {
71230      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
71231      sqlite3_result_null(context);
71232      break;
71233    }
71234    default: {
71235      /* Because sqlite3_value_double() returns 0.0 if the argument is not
71236      ** something that can be converted into a number, we have:
71237      ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
71238      ** cannot be converted to a numeric value.
71239      */
71240      double rVal = sqlite3_value_double(argv[0]);
71241      if( rVal<0 ) rVal = -rVal;
71242      sqlite3_result_double(context, rVal);
71243      break;
71244    }
71245  }
71246}
71247
71248/*
71249** Implementation of the substr() function.
71250**
71251** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
71252** p1 is 1-indexed.  So substr(x,1,1) returns the first character
71253** of x.  If x is text, then we actually count UTF-8 characters.
71254** If x is a blob, then we count bytes.
71255**
71256** If p1 is negative, then we begin abs(p1) from the end of x[].
71257**
71258** If p2 is negative, return the p2 characters preceeding p1.
71259*/
71260static void substrFunc(
71261  sqlite3_context *context,
71262  int argc,
71263  sqlite3_value **argv
71264){
71265  const unsigned char *z;
71266  const unsigned char *z2;
71267  int len;
71268  int p0type;
71269  i64 p1, p2;
71270  int negP2 = 0;
71271
71272  assert( argc==3 || argc==2 );
71273  if( sqlite3_value_type(argv[1])==SQLITE_NULL
71274   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
71275  ){
71276    return;
71277  }
71278  p0type = sqlite3_value_type(argv[0]);
71279  p1 = sqlite3_value_int(argv[1]);
71280  if( p0type==SQLITE_BLOB ){
71281    len = sqlite3_value_bytes(argv[0]);
71282    z = sqlite3_value_blob(argv[0]);
71283    if( z==0 ) return;
71284    assert( len==sqlite3_value_bytes(argv[0]) );
71285  }else{
71286    z = sqlite3_value_text(argv[0]);
71287    if( z==0 ) return;
71288    len = 0;
71289    if( p1<0 ){
71290      for(z2=z; *z2; len++){
71291        SQLITE_SKIP_UTF8(z2);
71292      }
71293    }
71294  }
71295  if( argc==3 ){
71296    p2 = sqlite3_value_int(argv[2]);
71297    if( p2<0 ){
71298      p2 = -p2;
71299      negP2 = 1;
71300    }
71301  }else{
71302    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
71303  }
71304  if( p1<0 ){
71305    p1 += len;
71306    if( p1<0 ){
71307      p2 += p1;
71308      if( p2<0 ) p2 = 0;
71309      p1 = 0;
71310    }
71311  }else if( p1>0 ){
71312    p1--;
71313  }else if( p2>0 ){
71314    p2--;
71315  }
71316  if( negP2 ){
71317    p1 -= p2;
71318    if( p1<0 ){
71319      p2 += p1;
71320      p1 = 0;
71321    }
71322  }
71323  assert( p1>=0 && p2>=0 );
71324  if( p0type!=SQLITE_BLOB ){
71325    while( *z && p1 ){
71326      SQLITE_SKIP_UTF8(z);
71327      p1--;
71328    }
71329    for(z2=z; *z2 && p2; p2--){
71330      SQLITE_SKIP_UTF8(z2);
71331    }
71332    sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
71333  }else{
71334    if( p1+p2>len ){
71335      p2 = len-p1;
71336      if( p2<0 ) p2 = 0;
71337    }
71338    sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
71339  }
71340}
71341
71342/*
71343** Implementation of the round() function
71344*/
71345#ifndef SQLITE_OMIT_FLOATING_POINT
71346static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71347  int n = 0;
71348  double r;
71349  char *zBuf;
71350  assert( argc==1 || argc==2 );
71351  if( argc==2 ){
71352    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
71353    n = sqlite3_value_int(argv[1]);
71354    if( n>30 ) n = 30;
71355    if( n<0 ) n = 0;
71356  }
71357  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
71358  r = sqlite3_value_double(argv[0]);
71359  zBuf = sqlite3_mprintf("%.*f",n,r);
71360  if( zBuf==0 ){
71361    sqlite3_result_error_nomem(context);
71362  }else{
71363    sqlite3AtoF(zBuf, &r);
71364    sqlite3_free(zBuf);
71365    sqlite3_result_double(context, r);
71366  }
71367}
71368#endif
71369
71370/*
71371** Allocate nByte bytes of space using sqlite3_malloc(). If the
71372** allocation fails, call sqlite3_result_error_nomem() to notify
71373** the database handle that malloc() has failed and return NULL.
71374** If nByte is larger than the maximum string or blob length, then
71375** raise an SQLITE_TOOBIG exception and return NULL.
71376*/
71377static void *contextMalloc(sqlite3_context *context, i64 nByte){
71378  char *z;
71379  sqlite3 *db = sqlite3_context_db_handle(context);
71380  assert( nByte>0 );
71381  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
71382  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
71383  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
71384    sqlite3_result_error_toobig(context);
71385    z = 0;
71386  }else{
71387    z = sqlite3Malloc((int)nByte);
71388    if( !z ){
71389      sqlite3_result_error_nomem(context);
71390    }
71391  }
71392  return z;
71393}
71394
71395/*
71396** Implementation of the upper() and lower() SQL functions.
71397*/
71398static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71399  char *z1;
71400  const char *z2;
71401  int i, n;
71402  UNUSED_PARAMETER(argc);
71403  z2 = (char*)sqlite3_value_text(argv[0]);
71404  n = sqlite3_value_bytes(argv[0]);
71405  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
71406  assert( z2==(char*)sqlite3_value_text(argv[0]) );
71407  if( z2 ){
71408    z1 = contextMalloc(context, ((i64)n)+1);
71409    if( z1 ){
71410      memcpy(z1, z2, n+1);
71411      for(i=0; z1[i]; i++){
71412        z1[i] = (char)sqlite3Toupper(z1[i]);
71413      }
71414      sqlite3_result_text(context, z1, -1, sqlite3_free);
71415    }
71416  }
71417}
71418static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71419  u8 *z1;
71420  const char *z2;
71421  int i, n;
71422  UNUSED_PARAMETER(argc);
71423  z2 = (char*)sqlite3_value_text(argv[0]);
71424  n = sqlite3_value_bytes(argv[0]);
71425  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
71426  assert( z2==(char*)sqlite3_value_text(argv[0]) );
71427  if( z2 ){
71428    z1 = contextMalloc(context, ((i64)n)+1);
71429    if( z1 ){
71430      memcpy(z1, z2, n+1);
71431      for(i=0; z1[i]; i++){
71432        z1[i] = sqlite3Tolower(z1[i]);
71433      }
71434      sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
71435    }
71436  }
71437}
71438
71439
71440#if 0  /* This function is never used. */
71441/*
71442** The COALESCE() and IFNULL() functions used to be implemented as shown
71443** here.  But now they are implemented as VDBE code so that unused arguments
71444** do not have to be computed.  This legacy implementation is retained as
71445** comment.
71446*/
71447/*
71448** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
71449** All three do the same thing.  They return the first non-NULL
71450** argument.
71451*/
71452static void ifnullFunc(
71453  sqlite3_context *context,
71454  int argc,
71455  sqlite3_value **argv
71456){
71457  int i;
71458  for(i=0; i<argc; i++){
71459    if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
71460      sqlite3_result_value(context, argv[i]);
71461      break;
71462    }
71463  }
71464}
71465#endif /* NOT USED */
71466#define ifnullFunc versionFunc   /* Substitute function - never called */
71467
71468/*
71469** Implementation of random().  Return a random integer.
71470*/
71471static void randomFunc(
71472  sqlite3_context *context,
71473  int NotUsed,
71474  sqlite3_value **NotUsed2
71475){
71476  sqlite_int64 r;
71477  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71478  sqlite3_randomness(sizeof(r), &r);
71479  if( r<0 ){
71480    /* We need to prevent a random number of 0x8000000000000000
71481    ** (or -9223372036854775808) since when you do abs() of that
71482    ** number of you get the same value back again.  To do this
71483    ** in a way that is testable, mask the sign bit off of negative
71484    ** values, resulting in a positive value.  Then take the
71485    ** 2s complement of that positive value.  The end result can
71486    ** therefore be no less than -9223372036854775807.
71487    */
71488    r = -(r ^ (((sqlite3_int64)1)<<63));
71489  }
71490  sqlite3_result_int64(context, r);
71491}
71492
71493/*
71494** Implementation of randomblob(N).  Return a random blob
71495** that is N bytes long.
71496*/
71497static void randomBlob(
71498  sqlite3_context *context,
71499  int argc,
71500  sqlite3_value **argv
71501){
71502  int n;
71503  unsigned char *p;
71504  assert( argc==1 );
71505  UNUSED_PARAMETER(argc);
71506  n = sqlite3_value_int(argv[0]);
71507  if( n<1 ){
71508    n = 1;
71509  }
71510  p = contextMalloc(context, n);
71511  if( p ){
71512    sqlite3_randomness(n, p);
71513    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
71514  }
71515}
71516
71517/*
71518** Implementation of the last_insert_rowid() SQL function.  The return
71519** value is the same as the sqlite3_last_insert_rowid() API function.
71520*/
71521static void last_insert_rowid(
71522  sqlite3_context *context,
71523  int NotUsed,
71524  sqlite3_value **NotUsed2
71525){
71526  sqlite3 *db = sqlite3_context_db_handle(context);
71527  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71528  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
71529}
71530
71531/*
71532** Implementation of the changes() SQL function.  The return value is the
71533** same as the sqlite3_changes() API function.
71534*/
71535static void changes(
71536  sqlite3_context *context,
71537  int NotUsed,
71538  sqlite3_value **NotUsed2
71539){
71540  sqlite3 *db = sqlite3_context_db_handle(context);
71541  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71542  sqlite3_result_int(context, sqlite3_changes(db));
71543}
71544
71545/*
71546** Implementation of the total_changes() SQL function.  The return value is
71547** the same as the sqlite3_total_changes() API function.
71548*/
71549static void total_changes(
71550  sqlite3_context *context,
71551  int NotUsed,
71552  sqlite3_value **NotUsed2
71553){
71554  sqlite3 *db = sqlite3_context_db_handle(context);
71555  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71556  sqlite3_result_int(context, sqlite3_total_changes(db));
71557}
71558
71559/*
71560** A structure defining how to do GLOB-style comparisons.
71561*/
71562struct compareInfo {
71563  u8 matchAll;
71564  u8 matchOne;
71565  u8 matchSet;
71566  u8 noCase;
71567};
71568
71569/*
71570** For LIKE and GLOB matching on EBCDIC machines, assume that every
71571** character is exactly one byte in size.  Also, all characters are
71572** able to participate in upper-case-to-lower-case mappings in EBCDIC
71573** whereas only characters less than 0x80 do in ASCII.
71574*/
71575#if defined(SQLITE_EBCDIC)
71576# define sqlite3Utf8Read(A,C)    (*(A++))
71577# define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
71578#else
71579# define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
71580#endif
71581
71582static const struct compareInfo globInfo = { '*', '?', '[', 0 };
71583/* The correct SQL-92 behavior is for the LIKE operator to ignore
71584** case.  Thus  'a' LIKE 'A' would be true. */
71585static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
71586/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
71587** is case sensitive causing 'a' LIKE 'A' to be false */
71588static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
71589
71590/*
71591** Compare two UTF-8 strings for equality where the first string can
71592** potentially be a "glob" expression.  Return true (1) if they
71593** are the same and false (0) if they are different.
71594**
71595** Globbing rules:
71596**
71597**      '*'       Matches any sequence of zero or more characters.
71598**
71599**      '?'       Matches exactly one character.
71600**
71601**     [...]      Matches one character from the enclosed list of
71602**                characters.
71603**
71604**     [^...]     Matches one character not in the enclosed list.
71605**
71606** With the [...] and [^...] matching, a ']' character can be included
71607** in the list by making it the first character after '[' or '^'.  A
71608** range of characters can be specified using '-'.  Example:
71609** "[a-z]" matches any single lower-case letter.  To match a '-', make
71610** it the last character in the list.
71611**
71612** This routine is usually quick, but can be N**2 in the worst case.
71613**
71614** Hints: to match '*' or '?', put them in "[]".  Like this:
71615**
71616**         abc[*]xyz        Matches "abc*xyz" only
71617*/
71618static int patternCompare(
71619  const u8 *zPattern,              /* The glob pattern */
71620  const u8 *zString,               /* The string to compare against the glob */
71621  const struct compareInfo *pInfo, /* Information about how to do the compare */
71622  const int esc                    /* The escape character */
71623){
71624  int c, c2;
71625  int invert;
71626  int seen;
71627  u8 matchOne = pInfo->matchOne;
71628  u8 matchAll = pInfo->matchAll;
71629  u8 matchSet = pInfo->matchSet;
71630  u8 noCase = pInfo->noCase;
71631  int prevEscape = 0;     /* True if the previous character was 'escape' */
71632
71633  while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
71634    if( !prevEscape && c==matchAll ){
71635      while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
71636               || c == matchOne ){
71637        if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
71638          return 0;
71639        }
71640      }
71641      if( c==0 ){
71642        return 1;
71643      }else if( c==esc ){
71644        c = sqlite3Utf8Read(zPattern, &zPattern);
71645        if( c==0 ){
71646          return 0;
71647        }
71648      }else if( c==matchSet ){
71649        assert( esc==0 );         /* This is GLOB, not LIKE */
71650        assert( matchSet<0x80 );  /* '[' is a single-byte character */
71651        while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
71652          SQLITE_SKIP_UTF8(zString);
71653        }
71654        return *zString!=0;
71655      }
71656      while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
71657        if( noCase ){
71658          GlogUpperToLower(c2);
71659          GlogUpperToLower(c);
71660          while( c2 != 0 && c2 != c ){
71661            c2 = sqlite3Utf8Read(zString, &zString);
71662            GlogUpperToLower(c2);
71663          }
71664        }else{
71665          while( c2 != 0 && c2 != c ){
71666            c2 = sqlite3Utf8Read(zString, &zString);
71667          }
71668        }
71669        if( c2==0 ) return 0;
71670        if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
71671      }
71672      return 0;
71673    }else if( !prevEscape && c==matchOne ){
71674      if( sqlite3Utf8Read(zString, &zString)==0 ){
71675        return 0;
71676      }
71677    }else if( c==matchSet ){
71678      int prior_c = 0;
71679      assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
71680      seen = 0;
71681      invert = 0;
71682      c = sqlite3Utf8Read(zString, &zString);
71683      if( c==0 ) return 0;
71684      c2 = sqlite3Utf8Read(zPattern, &zPattern);
71685      if( c2=='^' ){
71686        invert = 1;
71687        c2 = sqlite3Utf8Read(zPattern, &zPattern);
71688      }
71689      if( c2==']' ){
71690        if( c==']' ) seen = 1;
71691        c2 = sqlite3Utf8Read(zPattern, &zPattern);
71692      }
71693      while( c2 && c2!=']' ){
71694        if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
71695          c2 = sqlite3Utf8Read(zPattern, &zPattern);
71696          if( c>=prior_c && c<=c2 ) seen = 1;
71697          prior_c = 0;
71698        }else{
71699          if( c==c2 ){
71700            seen = 1;
71701          }
71702          prior_c = c2;
71703        }
71704        c2 = sqlite3Utf8Read(zPattern, &zPattern);
71705      }
71706      if( c2==0 || (seen ^ invert)==0 ){
71707        return 0;
71708      }
71709    }else if( esc==c && !prevEscape ){
71710      prevEscape = 1;
71711    }else{
71712      c2 = sqlite3Utf8Read(zString, &zString);
71713      if( noCase ){
71714        GlogUpperToLower(c);
71715        GlogUpperToLower(c2);
71716      }
71717      if( c!=c2 ){
71718        return 0;
71719      }
71720      prevEscape = 0;
71721    }
71722  }
71723  return *zString==0;
71724}
71725
71726/*
71727** Count the number of times that the LIKE operator (or GLOB which is
71728** just a variation of LIKE) gets called.  This is used for testing
71729** only.
71730*/
71731#ifdef SQLITE_TEST
71732SQLITE_API int sqlite3_like_count = 0;
71733#endif
71734
71735
71736/*
71737** Implementation of the like() SQL function.  This function implements
71738** the build-in LIKE operator.  The first argument to the function is the
71739** pattern and the second argument is the string.  So, the SQL statements:
71740**
71741**       A LIKE B
71742**
71743** is implemented as like(B,A).
71744**
71745** This same function (with a different compareInfo structure) computes
71746** the GLOB operator.
71747*/
71748static void likeFunc(
71749  sqlite3_context *context,
71750  int argc,
71751  sqlite3_value **argv
71752){
71753  const unsigned char *zA, *zB;
71754  int escape = 0;
71755  int nPat;
71756  sqlite3 *db = sqlite3_context_db_handle(context);
71757
71758  zB = sqlite3_value_text(argv[0]);
71759  zA = sqlite3_value_text(argv[1]);
71760
71761  /* Limit the length of the LIKE or GLOB pattern to avoid problems
71762  ** of deep recursion and N*N behavior in patternCompare().
71763  */
71764  nPat = sqlite3_value_bytes(argv[0]);
71765  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
71766  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
71767  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
71768    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
71769    return;
71770  }
71771  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
71772
71773  if( argc==3 ){
71774    /* The escape character string must consist of a single UTF-8 character.
71775    ** Otherwise, return an error.
71776    */
71777    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
71778    if( zEsc==0 ) return;
71779    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
71780      sqlite3_result_error(context,
71781          "ESCAPE expression must be a single character", -1);
71782      return;
71783    }
71784    escape = sqlite3Utf8Read(zEsc, &zEsc);
71785  }
71786  if( zA && zB ){
71787    struct compareInfo *pInfo = sqlite3_user_data(context);
71788#ifdef SQLITE_TEST
71789    sqlite3_like_count++;
71790#endif
71791
71792    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
71793  }
71794}
71795
71796/*
71797** Implementation of the NULLIF(x,y) function.  The result is the first
71798** argument if the arguments are different.  The result is NULL if the
71799** arguments are equal to each other.
71800*/
71801static void nullifFunc(
71802  sqlite3_context *context,
71803  int NotUsed,
71804  sqlite3_value **argv
71805){
71806  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
71807  UNUSED_PARAMETER(NotUsed);
71808  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
71809    sqlite3_result_value(context, argv[0]);
71810  }
71811}
71812
71813/*
71814** Implementation of the sqlite_version() function.  The result is the version
71815** of the SQLite library that is running.
71816*/
71817static void versionFunc(
71818  sqlite3_context *context,
71819  int NotUsed,
71820  sqlite3_value **NotUsed2
71821){
71822  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71823  sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
71824}
71825
71826/*
71827** Implementation of the sqlite_source_id() function. The result is a string
71828** that identifies the particular version of the source code used to build
71829** SQLite.
71830*/
71831static void sourceidFunc(
71832  sqlite3_context *context,
71833  int NotUsed,
71834  sqlite3_value **NotUsed2
71835){
71836  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71837  sqlite3_result_text(context, SQLITE_SOURCE_ID, -1, SQLITE_STATIC);
71838}
71839
71840/* Array for converting from half-bytes (nybbles) into ASCII hex
71841** digits. */
71842static const char hexdigits[] = {
71843  '0', '1', '2', '3', '4', '5', '6', '7',
71844  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
71845};
71846
71847/*
71848** EXPERIMENTAL - This is not an official function.  The interface may
71849** change.  This function may disappear.  Do not write code that depends
71850** on this function.
71851**
71852** Implementation of the QUOTE() function.  This function takes a single
71853** argument.  If the argument is numeric, the return value is the same as
71854** the argument.  If the argument is NULL, the return value is the string
71855** "NULL".  Otherwise, the argument is enclosed in single quotes with
71856** single-quote escapes.
71857*/
71858static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71859  assert( argc==1 );
71860  UNUSED_PARAMETER(argc);
71861  switch( sqlite3_value_type(argv[0]) ){
71862    case SQLITE_INTEGER:
71863    case SQLITE_FLOAT: {
71864      sqlite3_result_value(context, argv[0]);
71865      break;
71866    }
71867    case SQLITE_BLOB: {
71868      char *zText = 0;
71869      char const *zBlob = sqlite3_value_blob(argv[0]);
71870      int nBlob = sqlite3_value_bytes(argv[0]);
71871      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
71872      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
71873      if( zText ){
71874        int i;
71875        for(i=0; i<nBlob; i++){
71876          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
71877          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
71878        }
71879        zText[(nBlob*2)+2] = '\'';
71880        zText[(nBlob*2)+3] = '\0';
71881        zText[0] = 'X';
71882        zText[1] = '\'';
71883        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
71884        sqlite3_free(zText);
71885      }
71886      break;
71887    }
71888    case SQLITE_TEXT: {
71889      int i,j;
71890      u64 n;
71891      const unsigned char *zArg = sqlite3_value_text(argv[0]);
71892      char *z;
71893
71894      if( zArg==0 ) return;
71895      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
71896      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
71897      if( z ){
71898        z[0] = '\'';
71899        for(i=0, j=1; zArg[i]; i++){
71900          z[j++] = zArg[i];
71901          if( zArg[i]=='\'' ){
71902            z[j++] = '\'';
71903          }
71904        }
71905        z[j++] = '\'';
71906        z[j] = 0;
71907        sqlite3_result_text(context, z, j, sqlite3_free);
71908      }
71909      break;
71910    }
71911    default: {
71912      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
71913      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
71914      break;
71915    }
71916  }
71917}
71918
71919/*
71920** The hex() function.  Interpret the argument as a blob.  Return
71921** a hexadecimal rendering as text.
71922*/
71923static void hexFunc(
71924  sqlite3_context *context,
71925  int argc,
71926  sqlite3_value **argv
71927){
71928  int i, n;
71929  const unsigned char *pBlob;
71930  char *zHex, *z;
71931  assert( argc==1 );
71932  UNUSED_PARAMETER(argc);
71933  pBlob = sqlite3_value_blob(argv[0]);
71934  n = sqlite3_value_bytes(argv[0]);
71935  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
71936  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
71937  if( zHex ){
71938    for(i=0; i<n; i++, pBlob++){
71939      unsigned char c = *pBlob;
71940      *(z++) = hexdigits[(c>>4)&0xf];
71941      *(z++) = hexdigits[c&0xf];
71942    }
71943    *z = 0;
71944    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
71945  }
71946}
71947
71948/*
71949** The zeroblob(N) function returns a zero-filled blob of size N bytes.
71950*/
71951static void zeroblobFunc(
71952  sqlite3_context *context,
71953  int argc,
71954  sqlite3_value **argv
71955){
71956  i64 n;
71957  sqlite3 *db = sqlite3_context_db_handle(context);
71958  assert( argc==1 );
71959  UNUSED_PARAMETER(argc);
71960  n = sqlite3_value_int64(argv[0]);
71961  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
71962  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
71963  if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
71964    sqlite3_result_error_toobig(context);
71965  }else{
71966    sqlite3_result_zeroblob(context, (int)n);
71967  }
71968}
71969
71970/*
71971** The replace() function.  Three arguments are all strings: call
71972** them A, B, and C. The result is also a string which is derived
71973** from A by replacing every occurance of B with C.  The match
71974** must be exact.  Collating sequences are not used.
71975*/
71976static void replaceFunc(
71977  sqlite3_context *context,
71978  int argc,
71979  sqlite3_value **argv
71980){
71981  const unsigned char *zStr;        /* The input string A */
71982  const unsigned char *zPattern;    /* The pattern string B */
71983  const unsigned char *zRep;        /* The replacement string C */
71984  unsigned char *zOut;              /* The output */
71985  int nStr;                /* Size of zStr */
71986  int nPattern;            /* Size of zPattern */
71987  int nRep;                /* Size of zRep */
71988  i64 nOut;                /* Maximum size of zOut */
71989  int loopLimit;           /* Last zStr[] that might match zPattern[] */
71990  int i, j;                /* Loop counters */
71991
71992  assert( argc==3 );
71993  UNUSED_PARAMETER(argc);
71994  zStr = sqlite3_value_text(argv[0]);
71995  if( zStr==0 ) return;
71996  nStr = sqlite3_value_bytes(argv[0]);
71997  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
71998  zPattern = sqlite3_value_text(argv[1]);
71999  if( zPattern==0 ){
72000    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
72001            || sqlite3_context_db_handle(context)->mallocFailed );
72002    return;
72003  }
72004  if( zPattern[0]==0 ){
72005    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
72006    sqlite3_result_value(context, argv[0]);
72007    return;
72008  }
72009  nPattern = sqlite3_value_bytes(argv[1]);
72010  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
72011  zRep = sqlite3_value_text(argv[2]);
72012  if( zRep==0 ) return;
72013  nRep = sqlite3_value_bytes(argv[2]);
72014  assert( zRep==sqlite3_value_text(argv[2]) );
72015  nOut = nStr + 1;
72016  assert( nOut<SQLITE_MAX_LENGTH );
72017  zOut = contextMalloc(context, (i64)nOut);
72018  if( zOut==0 ){
72019    return;
72020  }
72021  loopLimit = nStr - nPattern;
72022  for(i=j=0; i<=loopLimit; i++){
72023    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
72024      zOut[j++] = zStr[i];
72025    }else{
72026      u8 *zOld;
72027      sqlite3 *db = sqlite3_context_db_handle(context);
72028      nOut += nRep - nPattern;
72029      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
72030      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
72031      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
72032        sqlite3_result_error_toobig(context);
72033        sqlite3DbFree(db, zOut);
72034        return;
72035      }
72036      zOld = zOut;
72037      zOut = sqlite3_realloc(zOut, (int)nOut);
72038      if( zOut==0 ){
72039        sqlite3_result_error_nomem(context);
72040        sqlite3DbFree(db, zOld);
72041        return;
72042      }
72043      memcpy(&zOut[j], zRep, nRep);
72044      j += nRep;
72045      i += nPattern-1;
72046    }
72047  }
72048  assert( j+nStr-i+1==nOut );
72049  memcpy(&zOut[j], &zStr[i], nStr-i);
72050  j += nStr - i;
72051  assert( j<=nOut );
72052  zOut[j] = 0;
72053  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
72054}
72055
72056/*
72057** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
72058** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
72059*/
72060static void trimFunc(
72061  sqlite3_context *context,
72062  int argc,
72063  sqlite3_value **argv
72064){
72065  const unsigned char *zIn;         /* Input string */
72066  const unsigned char *zCharSet;    /* Set of characters to trim */
72067  int nIn;                          /* Number of bytes in input */
72068  int flags;                        /* 1: trimleft  2: trimright  3: trim */
72069  int i;                            /* Loop counter */
72070  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
72071  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
72072  int nChar;                        /* Number of characters in zCharSet */
72073
72074  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
72075    return;
72076  }
72077  zIn = sqlite3_value_text(argv[0]);
72078  if( zIn==0 ) return;
72079  nIn = sqlite3_value_bytes(argv[0]);
72080  assert( zIn==sqlite3_value_text(argv[0]) );
72081  if( argc==1 ){
72082    static const unsigned char lenOne[] = { 1 };
72083    static unsigned char * const azOne[] = { (u8*)" " };
72084    nChar = 1;
72085    aLen = (u8*)lenOne;
72086    azChar = (unsigned char **)azOne;
72087    zCharSet = 0;
72088  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
72089    return;
72090  }else{
72091    const unsigned char *z;
72092    for(z=zCharSet, nChar=0; *z; nChar++){
72093      SQLITE_SKIP_UTF8(z);
72094    }
72095    if( nChar>0 ){
72096      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
72097      if( azChar==0 ){
72098        return;
72099      }
72100      aLen = (unsigned char*)&azChar[nChar];
72101      for(z=zCharSet, nChar=0; *z; nChar++){
72102        azChar[nChar] = (unsigned char *)z;
72103        SQLITE_SKIP_UTF8(z);
72104        aLen[nChar] = (u8)(z - azChar[nChar]);
72105      }
72106    }
72107  }
72108  if( nChar>0 ){
72109    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
72110    if( flags & 1 ){
72111      while( nIn>0 ){
72112        int len = 0;
72113        for(i=0; i<nChar; i++){
72114          len = aLen[i];
72115          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
72116        }
72117        if( i>=nChar ) break;
72118        zIn += len;
72119        nIn -= len;
72120      }
72121    }
72122    if( flags & 2 ){
72123      while( nIn>0 ){
72124        int len = 0;
72125        for(i=0; i<nChar; i++){
72126          len = aLen[i];
72127          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
72128        }
72129        if( i>=nChar ) break;
72130        nIn -= len;
72131      }
72132    }
72133    if( zCharSet ){
72134      sqlite3_free(azChar);
72135    }
72136  }
72137  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
72138}
72139
72140
72141/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
72142** is only available if the SQLITE_SOUNDEX compile-time option is used
72143** when SQLite is built.
72144*/
72145#ifdef SQLITE_SOUNDEX
72146/*
72147** Compute the soundex encoding of a word.
72148**
72149** IMP: R-59782-00072 The soundex(X) function returns a string that is the
72150** soundex encoding of the string X.
72151*/
72152static void soundexFunc(
72153  sqlite3_context *context,
72154  int argc,
72155  sqlite3_value **argv
72156){
72157  char zResult[8];
72158  const u8 *zIn;
72159  int i, j;
72160  static const unsigned char iCode[] = {
72161    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72162    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72163    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72164    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72165    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
72166    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
72167    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
72168    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
72169  };
72170  assert( argc==1 );
72171  zIn = (u8*)sqlite3_value_text(argv[0]);
72172  if( zIn==0 ) zIn = (u8*)"";
72173  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
72174  if( zIn[i] ){
72175    u8 prevcode = iCode[zIn[i]&0x7f];
72176    zResult[0] = sqlite3Toupper(zIn[i]);
72177    for(j=1; j<4 && zIn[i]; i++){
72178      int code = iCode[zIn[i]&0x7f];
72179      if( code>0 ){
72180        if( code!=prevcode ){
72181          prevcode = code;
72182          zResult[j++] = code + '0';
72183        }
72184      }else{
72185        prevcode = 0;
72186      }
72187    }
72188    while( j<4 ){
72189      zResult[j++] = '0';
72190    }
72191    zResult[j] = 0;
72192    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
72193  }else{
72194    /* IMP: R-64894-50321 The string "?000" is returned if the argument
72195    ** is NULL or contains no ASCII alphabetic characters. */
72196    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
72197  }
72198}
72199#endif /* SQLITE_SOUNDEX */
72200
72201#ifndef SQLITE_OMIT_LOAD_EXTENSION
72202/*
72203** A function that loads a shared-library extension then returns NULL.
72204*/
72205static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
72206  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
72207  const char *zProc;
72208  sqlite3 *db = sqlite3_context_db_handle(context);
72209  char *zErrMsg = 0;
72210
72211  if( argc==2 ){
72212    zProc = (const char *)sqlite3_value_text(argv[1]);
72213  }else{
72214    zProc = 0;
72215  }
72216  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
72217    sqlite3_result_error(context, zErrMsg, -1);
72218    sqlite3_free(zErrMsg);
72219  }
72220}
72221#endif
72222
72223
72224/*
72225** An instance of the following structure holds the context of a
72226** sum() or avg() aggregate computation.
72227*/
72228typedef struct SumCtx SumCtx;
72229struct SumCtx {
72230  double rSum;      /* Floating point sum */
72231  i64 iSum;         /* Integer sum */
72232  i64 cnt;          /* Number of elements summed */
72233  u8 overflow;      /* True if integer overflow seen */
72234  u8 approx;        /* True if non-integer value was input to the sum */
72235};
72236
72237/*
72238** Routines used to compute the sum, average, and total.
72239**
72240** The SUM() function follows the (broken) SQL standard which means
72241** that it returns NULL if it sums over no inputs.  TOTAL returns
72242** 0.0 in that case.  In addition, TOTAL always returns a float where
72243** SUM might return an integer if it never encounters a floating point
72244** value.  TOTAL never fails, but SUM might through an exception if
72245** it overflows an integer.
72246*/
72247static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
72248  SumCtx *p;
72249  int type;
72250  assert( argc==1 );
72251  UNUSED_PARAMETER(argc);
72252  p = sqlite3_aggregate_context(context, sizeof(*p));
72253  type = sqlite3_value_numeric_type(argv[0]);
72254  if( p && type!=SQLITE_NULL ){
72255    p->cnt++;
72256    if( type==SQLITE_INTEGER ){
72257      i64 v = sqlite3_value_int64(argv[0]);
72258      p->rSum += v;
72259      if( (p->approx|p->overflow)==0 ){
72260        i64 iNewSum = p->iSum + v;
72261        int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
72262        int s2 = (int)(v       >> (sizeof(i64)*8-1));
72263        int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
72264        p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
72265        p->iSum = iNewSum;
72266      }
72267    }else{
72268      p->rSum += sqlite3_value_double(argv[0]);
72269      p->approx = 1;
72270    }
72271  }
72272}
72273static void sumFinalize(sqlite3_context *context){
72274  SumCtx *p;
72275  p = sqlite3_aggregate_context(context, 0);
72276  if( p && p->cnt>0 ){
72277    if( p->overflow ){
72278      sqlite3_result_error(context,"integer overflow",-1);
72279    }else if( p->approx ){
72280      sqlite3_result_double(context, p->rSum);
72281    }else{
72282      sqlite3_result_int64(context, p->iSum);
72283    }
72284  }
72285}
72286static void avgFinalize(sqlite3_context *context){
72287  SumCtx *p;
72288  p = sqlite3_aggregate_context(context, 0);
72289  if( p && p->cnt>0 ){
72290    sqlite3_result_double(context, p->rSum/(double)p->cnt);
72291  }
72292}
72293static void totalFinalize(sqlite3_context *context){
72294  SumCtx *p;
72295  p = sqlite3_aggregate_context(context, 0);
72296  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
72297  sqlite3_result_double(context, p ? p->rSum : (double)0);
72298}
72299
72300/*
72301** The following structure keeps track of state information for the
72302** count() aggregate function.
72303*/
72304typedef struct CountCtx CountCtx;
72305struct CountCtx {
72306  i64 n;
72307};
72308
72309/*
72310** Routines to implement the count() aggregate function.
72311*/
72312static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
72313  CountCtx *p;
72314  p = sqlite3_aggregate_context(context, sizeof(*p));
72315  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
72316    p->n++;
72317  }
72318
72319#ifndef SQLITE_OMIT_DEPRECATED
72320  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
72321  ** sure it still operates correctly, verify that its count agrees with our
72322  ** internal count when using count(*) and when the total count can be
72323  ** expressed as a 32-bit integer. */
72324  assert( argc==1 || p==0 || p->n>0x7fffffff
72325          || p->n==sqlite3_aggregate_count(context) );
72326#endif
72327}
72328static void countFinalize(sqlite3_context *context){
72329  CountCtx *p;
72330  p = sqlite3_aggregate_context(context, 0);
72331  sqlite3_result_int64(context, p ? p->n : 0);
72332}
72333
72334/*
72335** Routines to implement min() and max() aggregate functions.
72336*/
72337static void minmaxStep(
72338  sqlite3_context *context,
72339  int NotUsed,
72340  sqlite3_value **argv
72341){
72342  Mem *pArg  = (Mem *)argv[0];
72343  Mem *pBest;
72344  UNUSED_PARAMETER(NotUsed);
72345
72346  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
72347  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
72348  if( !pBest ) return;
72349
72350  if( pBest->flags ){
72351    int max;
72352    int cmp;
72353    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
72354    /* This step function is used for both the min() and max() aggregates,
72355    ** the only difference between the two being that the sense of the
72356    ** comparison is inverted. For the max() aggregate, the
72357    ** sqlite3_user_data() function returns (void *)-1. For min() it
72358    ** returns (void *)db, where db is the sqlite3* database pointer.
72359    ** Therefore the next statement sets variable 'max' to 1 for the max()
72360    ** aggregate, or 0 for min().
72361    */
72362    max = sqlite3_user_data(context)!=0;
72363    cmp = sqlite3MemCompare(pBest, pArg, pColl);
72364    if( (max && cmp<0) || (!max && cmp>0) ){
72365      sqlite3VdbeMemCopy(pBest, pArg);
72366    }
72367  }else{
72368    sqlite3VdbeMemCopy(pBest, pArg);
72369  }
72370}
72371static void minMaxFinalize(sqlite3_context *context){
72372  sqlite3_value *pRes;
72373  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
72374  if( pRes ){
72375    if( ALWAYS(pRes->flags) ){
72376      sqlite3_result_value(context, pRes);
72377    }
72378    sqlite3VdbeMemRelease(pRes);
72379  }
72380}
72381
72382/*
72383** group_concat(EXPR, ?SEPARATOR?)
72384*/
72385static void groupConcatStep(
72386  sqlite3_context *context,
72387  int argc,
72388  sqlite3_value **argv
72389){
72390  const char *zVal;
72391  StrAccum *pAccum;
72392  const char *zSep;
72393  int nVal, nSep;
72394  assert( argc==1 || argc==2 );
72395  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
72396  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
72397
72398  if( pAccum ){
72399    sqlite3 *db = sqlite3_context_db_handle(context);
72400    int firstTerm = pAccum->useMalloc==0;
72401    pAccum->useMalloc = 1;
72402    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
72403    if( !firstTerm ){
72404      if( argc==2 ){
72405        zSep = (char*)sqlite3_value_text(argv[1]);
72406        nSep = sqlite3_value_bytes(argv[1]);
72407      }else{
72408        zSep = ",";
72409        nSep = 1;
72410      }
72411      sqlite3StrAccumAppend(pAccum, zSep, nSep);
72412    }
72413    zVal = (char*)sqlite3_value_text(argv[0]);
72414    nVal = sqlite3_value_bytes(argv[0]);
72415    sqlite3StrAccumAppend(pAccum, zVal, nVal);
72416  }
72417}
72418static void groupConcatFinalize(sqlite3_context *context){
72419  StrAccum *pAccum;
72420  pAccum = sqlite3_aggregate_context(context, 0);
72421  if( pAccum ){
72422    if( pAccum->tooBig ){
72423      sqlite3_result_error_toobig(context);
72424    }else if( pAccum->mallocFailed ){
72425      sqlite3_result_error_nomem(context);
72426    }else{
72427      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
72428                          sqlite3_free);
72429    }
72430  }
72431}
72432
72433/*
72434** This function registered all of the above C functions as SQL
72435** functions.  This should be the only routine in this file with
72436** external linkage.
72437*/
72438SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
72439#ifndef SQLITE_OMIT_ALTERTABLE
72440  sqlite3AlterFunctions(db);
72441#endif
72442  if( !db->mallocFailed ){
72443    int rc = sqlite3_overload_function(db, "MATCH", 2);
72444    assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
72445    if( rc==SQLITE_NOMEM ){
72446      db->mallocFailed = 1;
72447    }
72448  }
72449}
72450
72451/*
72452** Set the LIKEOPT flag on the 2-argument function with the given name.
72453*/
72454static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
72455  FuncDef *pDef;
72456  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
72457                             2, SQLITE_UTF8, 0);
72458  if( ALWAYS(pDef) ){
72459    pDef->flags = flagVal;
72460  }
72461}
72462
72463/*
72464** Register the built-in LIKE and GLOB functions.  The caseSensitive
72465** parameter determines whether or not the LIKE operator is case
72466** sensitive.  GLOB is always case sensitive.
72467*/
72468SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
72469  struct compareInfo *pInfo;
72470  if( caseSensitive ){
72471    pInfo = (struct compareInfo*)&likeInfoAlt;
72472  }else{
72473    pInfo = (struct compareInfo*)&likeInfoNorm;
72474  }
72475  sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0);
72476  sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0);
72477  sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY,
72478      (struct compareInfo*)&globInfo, likeFunc, 0,0);
72479  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
72480  setLikeOptFlag(db, "like",
72481      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
72482}
72483
72484/*
72485** pExpr points to an expression which implements a function.  If
72486** it is appropriate to apply the LIKE optimization to that function
72487** then set aWc[0] through aWc[2] to the wildcard characters and
72488** return TRUE.  If the function is not a LIKE-style function then
72489** return FALSE.
72490*/
72491SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
72492  FuncDef *pDef;
72493  if( pExpr->op!=TK_FUNCTION
72494   || !pExpr->x.pList
72495   || pExpr->x.pList->nExpr!=2
72496  ){
72497    return 0;
72498  }
72499  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
72500  pDef = sqlite3FindFunction(db, pExpr->u.zToken,
72501                             sqlite3Strlen30(pExpr->u.zToken),
72502                             2, SQLITE_UTF8, 0);
72503  if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
72504    return 0;
72505  }
72506
72507  /* The memcpy() statement assumes that the wildcard characters are
72508  ** the first three statements in the compareInfo structure.  The
72509  ** asserts() that follow verify that assumption
72510  */
72511  memcpy(aWc, pDef->pUserData, 3);
72512  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
72513  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
72514  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
72515  *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
72516  return 1;
72517}
72518
72519/*
72520** All all of the FuncDef structures in the aBuiltinFunc[] array above
72521** to the global function hash table.  This occurs at start-time (as
72522** a consequence of calling sqlite3_initialize()).
72523**
72524** After this routine runs
72525*/
72526SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
72527  /*
72528  ** The following array holds FuncDef structures for all of the functions
72529  ** defined in this file.
72530  **
72531  ** The array cannot be constant since changes are made to the
72532  ** FuncDef.pHash elements at start-time.  The elements of this array
72533  ** are read-only after initialization is complete.
72534  */
72535  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
72536    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
72537    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
72538    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
72539    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
72540    FUNCTION(trim,               1, 3, 0, trimFunc         ),
72541    FUNCTION(trim,               2, 3, 0, trimFunc         ),
72542    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
72543    FUNCTION(min,                0, 0, 1, 0                ),
72544    AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
72545    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
72546    FUNCTION(max,                0, 1, 1, 0                ),
72547    AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
72548    FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
72549    FUNCTION(length,             1, 0, 0, lengthFunc       ),
72550    FUNCTION(substr,             2, 0, 0, substrFunc       ),
72551    FUNCTION(substr,             3, 0, 0, substrFunc       ),
72552    FUNCTION(abs,                1, 0, 0, absFunc          ),
72553#ifndef SQLITE_OMIT_FLOATING_POINT
72554    FUNCTION(round,              1, 0, 0, roundFunc        ),
72555    FUNCTION(round,              2, 0, 0, roundFunc        ),
72556#endif
72557    FUNCTION(upper,              1, 0, 0, upperFunc        ),
72558    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
72559    FUNCTION(coalesce,           1, 0, 0, 0                ),
72560    FUNCTION(coalesce,           0, 0, 0, 0                ),
72561/*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
72562    {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0},
72563    FUNCTION(hex,                1, 0, 0, hexFunc          ),
72564/*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
72565    {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0},
72566    FUNCTION(random,             0, 0, 0, randomFunc       ),
72567    FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
72568    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
72569    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
72570    FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
72571    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
72572    FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
72573    FUNCTION(changes,            0, 0, 0, changes          ),
72574    FUNCTION(total_changes,      0, 0, 0, total_changes    ),
72575    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
72576    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
72577  #ifdef SQLITE_SOUNDEX
72578    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
72579  #endif
72580  #ifndef SQLITE_OMIT_LOAD_EXTENSION
72581    FUNCTION(load_extension,     1, 0, 0, loadExt          ),
72582    FUNCTION(load_extension,     2, 0, 0, loadExt          ),
72583  #endif
72584    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
72585    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
72586    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
72587 /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
72588    {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0},
72589    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
72590    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
72591    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
72592
72593    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
72594  #ifdef SQLITE_CASE_SENSITIVE_LIKE
72595    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
72596    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
72597  #else
72598    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
72599    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
72600  #endif
72601  };
72602
72603  int i;
72604  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
72605  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
72606
72607  for(i=0; i<ArraySize(aBuiltinFunc); i++){
72608    sqlite3FuncDefInsert(pHash, &aFunc[i]);
72609  }
72610  sqlite3RegisterDateTimeFunctions();
72611}
72612
72613/************** End of func.c ************************************************/
72614/************** Begin file fkey.c ********************************************/
72615/*
72616**
72617** The author disclaims copyright to this source code.  In place of
72618** a legal notice, here is a blessing:
72619**
72620**    May you do good and not evil.
72621**    May you find forgiveness for yourself and forgive others.
72622**    May you share freely, never taking more than you give.
72623**
72624*************************************************************************
72625** This file contains code used by the compiler to add foreign key
72626** support to compiled SQL statements.
72627*/
72628
72629#ifndef SQLITE_OMIT_FOREIGN_KEY
72630#ifndef SQLITE_OMIT_TRIGGER
72631
72632/*
72633** Deferred and Immediate FKs
72634** --------------------------
72635**
72636** Foreign keys in SQLite come in two flavours: deferred and immediate.
72637** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
72638** is returned and the current statement transaction rolled back. If a
72639** deferred foreign key constraint is violated, no action is taken
72640** immediately. However if the application attempts to commit the
72641** transaction before fixing the constraint violation, the attempt fails.
72642**
72643** Deferred constraints are implemented using a simple counter associated
72644** with the database handle. The counter is set to zero each time a
72645** database transaction is opened. Each time a statement is executed
72646** that causes a foreign key violation, the counter is incremented. Each
72647** time a statement is executed that removes an existing violation from
72648** the database, the counter is decremented. When the transaction is
72649** committed, the commit fails if the current value of the counter is
72650** greater than zero. This scheme has two big drawbacks:
72651**
72652**   * When a commit fails due to a deferred foreign key constraint,
72653**     there is no way to tell which foreign constraint is not satisfied,
72654**     or which row it is not satisfied for.
72655**
72656**   * If the database contains foreign key violations when the
72657**     transaction is opened, this may cause the mechanism to malfunction.
72658**
72659** Despite these problems, this approach is adopted as it seems simpler
72660** than the alternatives.
72661**
72662** INSERT operations:
72663**
72664**   I.1) For each FK for which the table is the child table, search
72665**        the parent table for a match. If none is found increment the
72666**        constraint counter.
72667**
72668**   I.2) For each FK for which the table is the parent table,
72669**        search the child table for rows that correspond to the new
72670**        row in the parent table. Decrement the counter for each row
72671**        found (as the constraint is now satisfied).
72672**
72673** DELETE operations:
72674**
72675**   D.1) For each FK for which the table is the child table,
72676**        search the parent table for a row that corresponds to the
72677**        deleted row in the child table. If such a row is not found,
72678**        decrement the counter.
72679**
72680**   D.2) For each FK for which the table is the parent table, search
72681**        the child table for rows that correspond to the deleted row
72682**        in the parent table. For each found increment the counter.
72683**
72684** UPDATE operations:
72685**
72686**   An UPDATE command requires that all 4 steps above are taken, but only
72687**   for FK constraints for which the affected columns are actually
72688**   modified (values must be compared at runtime).
72689**
72690** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
72691** This simplifies the implementation a bit.
72692**
72693** For the purposes of immediate FK constraints, the OR REPLACE conflict
72694** resolution is considered to delete rows before the new row is inserted.
72695** If a delete caused by OR REPLACE violates an FK constraint, an exception
72696** is thrown, even if the FK constraint would be satisfied after the new
72697** row is inserted.
72698**
72699** Immediate constraints are usually handled similarly. The only difference
72700** is that the counter used is stored as part of each individual statement
72701** object (struct Vdbe). If, after the statement has run, its immediate
72702** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
72703** and the statement transaction is rolled back. An exception is an INSERT
72704** statement that inserts a single row only (no triggers). In this case,
72705** instead of using a counter, an exception is thrown immediately if the
72706** INSERT violates a foreign key constraint. This is necessary as such
72707** an INSERT does not open a statement transaction.
72708**
72709** TODO: How should dropping a table be handled? How should renaming a
72710** table be handled?
72711**
72712**
72713** Query API Notes
72714** ---------------
72715**
72716** Before coding an UPDATE or DELETE row operation, the code-generator
72717** for those two operations needs to know whether or not the operation
72718** requires any FK processing and, if so, which columns of the original
72719** row are required by the FK processing VDBE code (i.e. if FKs were
72720** implemented using triggers, which of the old.* columns would be
72721** accessed). No information is required by the code-generator before
72722** coding an INSERT operation. The functions used by the UPDATE/DELETE
72723** generation code to query for this information are:
72724**
72725**   sqlite3FkRequired() - Test to see if FK processing is required.
72726**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
72727**
72728**
72729** Externally accessible module functions
72730** --------------------------------------
72731**
72732**   sqlite3FkCheck()    - Check for foreign key violations.
72733**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
72734**   sqlite3FkDelete()   - Delete an FKey structure.
72735*/
72736
72737/*
72738** VDBE Calling Convention
72739** -----------------------
72740**
72741** Example:
72742**
72743**   For the following INSERT statement:
72744**
72745**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
72746**     INSERT INTO t1 VALUES(1, 2, 3.1);
72747**
72748**   Register (x):        2    (type integer)
72749**   Register (x+1):      1    (type integer)
72750**   Register (x+2):      NULL (type NULL)
72751**   Register (x+3):      3.1  (type real)
72752*/
72753
72754/*
72755** A foreign key constraint requires that the key columns in the parent
72756** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
72757** Given that pParent is the parent table for foreign key constraint pFKey,
72758** search the schema a unique index on the parent key columns.
72759**
72760** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
72761** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
72762** is set to point to the unique index.
72763**
72764** If the parent key consists of a single column (the foreign key constraint
72765** is not a composite foreign key), output variable *paiCol is set to NULL.
72766** Otherwise, it is set to point to an allocated array of size N, where
72767** N is the number of columns in the parent key. The first element of the
72768** array is the index of the child table column that is mapped by the FK
72769** constraint to the parent table column stored in the left-most column
72770** of index *ppIdx. The second element of the array is the index of the
72771** child table column that corresponds to the second left-most column of
72772** *ppIdx, and so on.
72773**
72774** If the required index cannot be found, either because:
72775**
72776**   1) The named parent key columns do not exist, or
72777**
72778**   2) The named parent key columns do exist, but are not subject to a
72779**      UNIQUE or PRIMARY KEY constraint, or
72780**
72781**   3) No parent key columns were provided explicitly as part of the
72782**      foreign key definition, and the parent table does not have a
72783**      PRIMARY KEY, or
72784**
72785**   4) No parent key columns were provided explicitly as part of the
72786**      foreign key definition, and the PRIMARY KEY of the parent table
72787**      consists of a a different number of columns to the child key in
72788**      the child table.
72789**
72790** then non-zero is returned, and a "foreign key mismatch" error loaded
72791** into pParse. If an OOM error occurs, non-zero is returned and the
72792** pParse->db->mallocFailed flag is set.
72793*/
72794static int locateFkeyIndex(
72795  Parse *pParse,                  /* Parse context to store any error in */
72796  Table *pParent,                 /* Parent table of FK constraint pFKey */
72797  FKey *pFKey,                    /* Foreign key to find index for */
72798  Index **ppIdx,                  /* OUT: Unique index on parent table */
72799  int **paiCol                    /* OUT: Map of index columns in pFKey */
72800){
72801  Index *pIdx = 0;                    /* Value to return via *ppIdx */
72802  int *aiCol = 0;                     /* Value to return via *paiCol */
72803  int nCol = pFKey->nCol;             /* Number of columns in parent key */
72804  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
72805
72806  /* The caller is responsible for zeroing output parameters. */
72807  assert( ppIdx && *ppIdx==0 );
72808  assert( !paiCol || *paiCol==0 );
72809  assert( pParse );
72810
72811  /* If this is a non-composite (single column) foreign key, check if it
72812  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
72813  ** and *paiCol set to zero and return early.
72814  **
72815  ** Otherwise, for a composite foreign key (more than one column), allocate
72816  ** space for the aiCol array (returned via output parameter *paiCol).
72817  ** Non-composite foreign keys do not require the aiCol array.
72818  */
72819  if( nCol==1 ){
72820    /* The FK maps to the IPK if any of the following are true:
72821    **
72822    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
72823    **      mapped to the primary key of table pParent, or
72824    **   2) The FK is explicitly mapped to a column declared as INTEGER
72825    **      PRIMARY KEY.
72826    */
72827    if( pParent->iPKey>=0 ){
72828      if( !zKey ) return 0;
72829      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
72830    }
72831  }else if( paiCol ){
72832    assert( nCol>1 );
72833    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
72834    if( !aiCol ) return 1;
72835    *paiCol = aiCol;
72836  }
72837
72838  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
72839    if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
72840      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
72841      ** of columns. If each indexed column corresponds to a foreign key
72842      ** column of pFKey, then this index is a winner.  */
72843
72844      if( zKey==0 ){
72845        /* If zKey is NULL, then this foreign key is implicitly mapped to
72846        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
72847        ** identified by the test (Index.autoIndex==2).  */
72848        if( pIdx->autoIndex==2 ){
72849          if( aiCol ){
72850            int i;
72851            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
72852          }
72853          break;
72854        }
72855      }else{
72856        /* If zKey is non-NULL, then this foreign key was declared to
72857        ** map to an explicit list of columns in table pParent. Check if this
72858        ** index matches those columns. Also, check that the index uses
72859        ** the default collation sequences for each column. */
72860        int i, j;
72861        for(i=0; i<nCol; i++){
72862          int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
72863          char *zDfltColl;                  /* Def. collation for column */
72864          char *zIdxCol;                    /* Name of indexed column */
72865
72866          /* If the index uses a collation sequence that is different from
72867          ** the default collation sequence for the column, this index is
72868          ** unusable. Bail out early in this case.  */
72869          zDfltColl = pParent->aCol[iCol].zColl;
72870          if( !zDfltColl ){
72871            zDfltColl = "BINARY";
72872          }
72873          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
72874
72875          zIdxCol = pParent->aCol[iCol].zName;
72876          for(j=0; j<nCol; j++){
72877            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
72878              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
72879              break;
72880            }
72881          }
72882          if( j==nCol ) break;
72883        }
72884        if( i==nCol ) break;      /* pIdx is usable */
72885      }
72886    }
72887  }
72888
72889  if( !pIdx ){
72890    if( !pParse->disableTriggers ){
72891      sqlite3ErrorMsg(pParse, "foreign key mismatch");
72892    }
72893    sqlite3DbFree(pParse->db, aiCol);
72894    return 1;
72895  }
72896
72897  *ppIdx = pIdx;
72898  return 0;
72899}
72900
72901/*
72902** This function is called when a row is inserted into or deleted from the
72903** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
72904** on the child table of pFKey, this function is invoked twice for each row
72905** affected - once to "delete" the old row, and then again to "insert" the
72906** new row.
72907**
72908** Each time it is called, this function generates VDBE code to locate the
72909** row in the parent table that corresponds to the row being inserted into
72910** or deleted from the child table. If the parent row can be found, no
72911** special action is taken. Otherwise, if the parent row can *not* be
72912** found in the parent table:
72913**
72914**   Operation | FK type   | Action taken
72915**   --------------------------------------------------------------------------
72916**   INSERT      immediate   Increment the "immediate constraint counter".
72917**
72918**   DELETE      immediate   Decrement the "immediate constraint counter".
72919**
72920**   INSERT      deferred    Increment the "deferred constraint counter".
72921**
72922**   DELETE      deferred    Decrement the "deferred constraint counter".
72923**
72924** These operations are identified in the comment at the top of this file
72925** (fkey.c) as "I.1" and "D.1".
72926*/
72927static void fkLookupParent(
72928  Parse *pParse,        /* Parse context */
72929  int iDb,              /* Index of database housing pTab */
72930  Table *pTab,          /* Parent table of FK pFKey */
72931  Index *pIdx,          /* Unique index on parent key columns in pTab */
72932  FKey *pFKey,          /* Foreign key constraint */
72933  int *aiCol,           /* Map from parent key columns to child table columns */
72934  int regData,          /* Address of array containing child table row */
72935  int nIncr,            /* Increment constraint counter by this */
72936  int isIgnore          /* If true, pretend pTab contains all NULL values */
72937){
72938  int i;                                    /* Iterator variable */
72939  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
72940  int iCur = pParse->nTab - 1;              /* Cursor number to use */
72941  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
72942
72943  /* If nIncr is less than zero, then check at runtime if there are any
72944  ** outstanding constraints to resolve. If there are not, there is no need
72945  ** to check if deleting this row resolves any outstanding violations.
72946  **
72947  ** Check if any of the key columns in the child table row are NULL. If
72948  ** any are, then the constraint is considered satisfied. No need to
72949  ** search for a matching row in the parent table.  */
72950  if( nIncr<0 ){
72951    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
72952  }
72953  for(i=0; i<pFKey->nCol; i++){
72954    int iReg = aiCol[i] + regData + 1;
72955    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
72956  }
72957
72958  if( isIgnore==0 ){
72959    if( pIdx==0 ){
72960      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
72961      ** column of the parent table (table pTab).  */
72962      int iMustBeInt;               /* Address of MustBeInt instruction */
72963      int regTemp = sqlite3GetTempReg(pParse);
72964
72965      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
72966      ** apply the affinity of the parent key). If this fails, then there
72967      ** is no matching parent key. Before using MustBeInt, make a copy of
72968      ** the value. Otherwise, the value inserted into the child key column
72969      ** will have INTEGER affinity applied to it, which may not be correct.  */
72970      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
72971      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
72972
72973      /* If the parent table is the same as the child table, and we are about
72974      ** to increment the constraint-counter (i.e. this is an INSERT operation),
72975      ** then check if the row being inserted matches itself. If so, do not
72976      ** increment the constraint-counter.  */
72977      if( pTab==pFKey->pFrom && nIncr==1 ){
72978        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
72979      }
72980
72981      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
72982      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
72983      sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
72984      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
72985      sqlite3VdbeJumpHere(v, iMustBeInt);
72986      sqlite3ReleaseTempReg(pParse, regTemp);
72987    }else{
72988      int nCol = pFKey->nCol;
72989      int regTemp = sqlite3GetTempRange(pParse, nCol);
72990      int regRec = sqlite3GetTempReg(pParse);
72991      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
72992
72993      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
72994      sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
72995      for(i=0; i<nCol; i++){
72996        sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
72997      }
72998
72999      /* If the parent table is the same as the child table, and we are about
73000      ** to increment the constraint-counter (i.e. this is an INSERT operation),
73001      ** then check if the row being inserted matches itself. If so, do not
73002      ** increment the constraint-counter.  */
73003      if( pTab==pFKey->pFrom && nIncr==1 ){
73004        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
73005        for(i=0; i<nCol; i++){
73006          int iChild = aiCol[i]+1+regData;
73007          int iParent = pIdx->aiColumn[i]+1+regData;
73008          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
73009        }
73010        sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
73011      }
73012
73013      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
73014      sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
73015      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
73016
73017      sqlite3ReleaseTempReg(pParse, regRec);
73018      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
73019    }
73020  }
73021
73022  if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
73023    /* Special case: If this is an INSERT statement that will insert exactly
73024    ** one row into the table, raise a constraint immediately instead of
73025    ** incrementing a counter. This is necessary as the VM code is being
73026    ** generated for will not open a statement transaction.  */
73027    assert( nIncr==1 );
73028    sqlite3HaltConstraint(
73029        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
73030    );
73031  }else{
73032    if( nIncr>0 && pFKey->isDeferred==0 ){
73033      sqlite3ParseToplevel(pParse)->mayAbort = 1;
73034    }
73035    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
73036  }
73037
73038  sqlite3VdbeResolveLabel(v, iOk);
73039  sqlite3VdbeAddOp1(v, OP_Close, iCur);
73040}
73041
73042/*
73043** This function is called to generate code executed when a row is deleted
73044** from the parent table of foreign key constraint pFKey and, if pFKey is
73045** deferred, when a row is inserted into the same table. When generating
73046** code for an SQL UPDATE operation, this function may be called twice -
73047** once to "delete" the old row and once to "insert" the new row.
73048**
73049** The code generated by this function scans through the rows in the child
73050** table that correspond to the parent table row being deleted or inserted.
73051** For each child row found, one of the following actions is taken:
73052**
73053**   Operation | FK type   | Action taken
73054**   --------------------------------------------------------------------------
73055**   DELETE      immediate   Increment the "immediate constraint counter".
73056**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
73057**                           throw a "foreign key constraint failed" exception.
73058**
73059**   INSERT      immediate   Decrement the "immediate constraint counter".
73060**
73061**   DELETE      deferred    Increment the "deferred constraint counter".
73062**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
73063**                           throw a "foreign key constraint failed" exception.
73064**
73065**   INSERT      deferred    Decrement the "deferred constraint counter".
73066**
73067** These operations are identified in the comment at the top of this file
73068** (fkey.c) as "I.2" and "D.2".
73069*/
73070static void fkScanChildren(
73071  Parse *pParse,                  /* Parse context */
73072  SrcList *pSrc,                  /* SrcList containing the table to scan */
73073  Table *pTab,
73074  Index *pIdx,                    /* Foreign key index */
73075  FKey *pFKey,                    /* Foreign key relationship */
73076  int *aiCol,                     /* Map from pIdx cols to child table cols */
73077  int regData,                    /* Referenced table data starts here */
73078  int nIncr                       /* Amount to increment deferred counter by */
73079){
73080  sqlite3 *db = pParse->db;       /* Database handle */
73081  int i;                          /* Iterator variable */
73082  Expr *pWhere = 0;               /* WHERE clause to scan with */
73083  NameContext sNameContext;       /* Context used to resolve WHERE clause */
73084  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
73085  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
73086  Vdbe *v = sqlite3GetVdbe(pParse);
73087
73088  assert( !pIdx || pIdx->pTable==pTab );
73089
73090  if( nIncr<0 ){
73091    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
73092  }
73093
73094  /* Create an Expr object representing an SQL expression like:
73095  **
73096  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
73097  **
73098  ** The collation sequence used for the comparison should be that of
73099  ** the parent key columns. The affinity of the parent key column should
73100  ** be applied to each child key value before the comparison takes place.
73101  */
73102  for(i=0; i<pFKey->nCol; i++){
73103    Expr *pLeft;                  /* Value from parent table row */
73104    Expr *pRight;                 /* Column ref to child table */
73105    Expr *pEq;                    /* Expression (pLeft = pRight) */
73106    int iCol;                     /* Index of column in child table */
73107    const char *zCol;             /* Name of column in child table */
73108
73109    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
73110    if( pLeft ){
73111      /* Set the collation sequence and affinity of the LHS of each TK_EQ
73112      ** expression to the parent key column defaults.  */
73113      if( pIdx ){
73114        Column *pCol;
73115        iCol = pIdx->aiColumn[i];
73116        pCol = &pIdx->pTable->aCol[iCol];
73117        pLeft->iTable = regData+iCol+1;
73118        pLeft->affinity = pCol->affinity;
73119        pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
73120      }else{
73121        pLeft->iTable = regData;
73122        pLeft->affinity = SQLITE_AFF_INTEGER;
73123      }
73124    }
73125    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
73126    assert( iCol>=0 );
73127    zCol = pFKey->pFrom->aCol[iCol].zName;
73128    pRight = sqlite3Expr(db, TK_ID, zCol);
73129    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
73130    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
73131  }
73132
73133  /* If the child table is the same as the parent table, and this scan
73134  ** is taking place as part of a DELETE operation (operation D.2), omit the
73135  ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
73136  ** clause, where $rowid is the rowid of the row being deleted.  */
73137  if( pTab==pFKey->pFrom && nIncr>0 ){
73138    Expr *pEq;                    /* Expression (pLeft = pRight) */
73139    Expr *pLeft;                  /* Value from parent table row */
73140    Expr *pRight;                 /* Column ref to child table */
73141    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
73142    pRight = sqlite3Expr(db, TK_COLUMN, 0);
73143    if( pLeft && pRight ){
73144      pLeft->iTable = regData;
73145      pLeft->affinity = SQLITE_AFF_INTEGER;
73146      pRight->iTable = pSrc->a[0].iCursor;
73147      pRight->iColumn = -1;
73148    }
73149    pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
73150    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
73151  }
73152
73153  /* Resolve the references in the WHERE clause. */
73154  memset(&sNameContext, 0, sizeof(NameContext));
73155  sNameContext.pSrcList = pSrc;
73156  sNameContext.pParse = pParse;
73157  sqlite3ResolveExprNames(&sNameContext, pWhere);
73158
73159  /* Create VDBE to loop through the entries in pSrc that match the WHERE
73160  ** clause. If the constraint is not deferred, throw an exception for
73161  ** each row found. Otherwise, for deferred constraints, increment the
73162  ** deferred constraint counter by nIncr for each row selected.  */
73163  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
73164  if( nIncr>0 && pFKey->isDeferred==0 ){
73165    sqlite3ParseToplevel(pParse)->mayAbort = 1;
73166  }
73167  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
73168  if( pWInfo ){
73169    sqlite3WhereEnd(pWInfo);
73170  }
73171
73172  /* Clean up the WHERE clause constructed above. */
73173  sqlite3ExprDelete(db, pWhere);
73174  if( iFkIfZero ){
73175    sqlite3VdbeJumpHere(v, iFkIfZero);
73176  }
73177}
73178
73179/*
73180** This function returns a pointer to the head of a linked list of FK
73181** constraints for which table pTab is the parent table. For example,
73182** given the following schema:
73183**
73184**   CREATE TABLE t1(a PRIMARY KEY);
73185**   CREATE TABLE t2(b REFERENCES t1(a);
73186**
73187** Calling this function with table "t1" as an argument returns a pointer
73188** to the FKey structure representing the foreign key constraint on table
73189** "t2". Calling this function with "t2" as the argument would return a
73190** NULL pointer (as there are no FK constraints for which t2 is the parent
73191** table).
73192*/
73193SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
73194  int nName = sqlite3Strlen30(pTab->zName);
73195  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
73196}
73197
73198/*
73199** The second argument is a Trigger structure allocated by the
73200** fkActionTrigger() routine. This function deletes the Trigger structure
73201** and all of its sub-components.
73202**
73203** The Trigger structure or any of its sub-components may be allocated from
73204** the lookaside buffer belonging to database handle dbMem.
73205*/
73206static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
73207  if( p ){
73208    TriggerStep *pStep = p->step_list;
73209    sqlite3ExprDelete(dbMem, pStep->pWhere);
73210    sqlite3ExprListDelete(dbMem, pStep->pExprList);
73211    sqlite3SelectDelete(dbMem, pStep->pSelect);
73212    sqlite3ExprDelete(dbMem, p->pWhen);
73213    sqlite3DbFree(dbMem, p);
73214  }
73215}
73216
73217/*
73218** This function is called to generate code that runs when table pTab is
73219** being dropped from the database. The SrcList passed as the second argument
73220** to this function contains a single entry guaranteed to resolve to
73221** table pTab.
73222**
73223** Normally, no code is required. However, if either
73224**
73225**   (a) The table is the parent table of a FK constraint, or
73226**   (b) The table is the child table of a deferred FK constraint and it is
73227**       determined at runtime that there are outstanding deferred FK
73228**       constraint violations in the database,
73229**
73230** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
73231** the table from the database. Triggers are disabled while running this
73232** DELETE, but foreign key actions are not.
73233*/
73234SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
73235  sqlite3 *db = pParse->db;
73236  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
73237    int iSkip = 0;
73238    Vdbe *v = sqlite3GetVdbe(pParse);
73239
73240    assert( v );                  /* VDBE has already been allocated */
73241    if( sqlite3FkReferences(pTab)==0 ){
73242      /* Search for a deferred foreign key constraint for which this table
73243      ** is the child table. If one cannot be found, return without
73244      ** generating any VDBE code. If one can be found, then jump over
73245      ** the entire DELETE if there are no outstanding deferred constraints
73246      ** when this statement is run.  */
73247      FKey *p;
73248      for(p=pTab->pFKey; p; p=p->pNextFrom){
73249        if( p->isDeferred ) break;
73250      }
73251      if( !p ) return;
73252      iSkip = sqlite3VdbeMakeLabel(v);
73253      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
73254    }
73255
73256    pParse->disableTriggers = 1;
73257    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
73258    pParse->disableTriggers = 0;
73259
73260    /* If the DELETE has generated immediate foreign key constraint
73261    ** violations, halt the VDBE and return an error at this point, before
73262    ** any modifications to the schema are made. This is because statement
73263    ** transactions are not able to rollback schema changes.  */
73264    sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
73265    sqlite3HaltConstraint(
73266        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
73267    );
73268
73269    if( iSkip ){
73270      sqlite3VdbeResolveLabel(v, iSkip);
73271    }
73272  }
73273}
73274
73275/*
73276** This function is called when inserting, deleting or updating a row of
73277** table pTab to generate VDBE code to perform foreign key constraint
73278** processing for the operation.
73279**
73280** For a DELETE operation, parameter regOld is passed the index of the
73281** first register in an array of (pTab->nCol+1) registers containing the
73282** rowid of the row being deleted, followed by each of the column values
73283** of the row being deleted, from left to right. Parameter regNew is passed
73284** zero in this case.
73285**
73286** For an INSERT operation, regOld is passed zero and regNew is passed the
73287** first register of an array of (pTab->nCol+1) registers containing the new
73288** row data.
73289**
73290** For an UPDATE operation, this function is called twice. Once before
73291** the original record is deleted from the table using the calling convention
73292** described for DELETE. Then again after the original record is deleted
73293** but before the new record is inserted using the INSERT convention.
73294*/
73295SQLITE_PRIVATE void sqlite3FkCheck(
73296  Parse *pParse,                  /* Parse context */
73297  Table *pTab,                    /* Row is being deleted from this table */
73298  int regOld,                     /* Previous row data is stored here */
73299  int regNew                      /* New row data is stored here */
73300){
73301  sqlite3 *db = pParse->db;       /* Database handle */
73302  Vdbe *v;                        /* VM to write code to */
73303  FKey *pFKey;                    /* Used to iterate through FKs */
73304  int iDb;                        /* Index of database containing pTab */
73305  const char *zDb;                /* Name of database containing pTab */
73306  int isIgnoreErrors = pParse->disableTriggers;
73307
73308  /* Exactly one of regOld and regNew should be non-zero. */
73309  assert( (regOld==0)!=(regNew==0) );
73310
73311  /* If foreign-keys are disabled, this function is a no-op. */
73312  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
73313
73314  v = sqlite3GetVdbe(pParse);
73315  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
73316  zDb = db->aDb[iDb].zName;
73317
73318  /* Loop through all the foreign key constraints for which pTab is the
73319  ** child table (the table that the foreign key definition is part of).  */
73320  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
73321    Table *pTo;                   /* Parent table of foreign key pFKey */
73322    Index *pIdx = 0;              /* Index on key columns in pTo */
73323    int *aiFree = 0;
73324    int *aiCol;
73325    int iCol;
73326    int i;
73327    int isIgnore = 0;
73328
73329    /* Find the parent table of this foreign key. Also find a unique index
73330    ** on the parent key columns in the parent table. If either of these
73331    ** schema items cannot be located, set an error in pParse and return
73332    ** early.  */
73333    if( pParse->disableTriggers ){
73334      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
73335    }else{
73336      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
73337    }
73338    if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
73339      if( !isIgnoreErrors || db->mallocFailed ) return;
73340      continue;
73341    }
73342    assert( pFKey->nCol==1 || (aiFree && pIdx) );
73343
73344    if( aiFree ){
73345      aiCol = aiFree;
73346    }else{
73347      iCol = pFKey->aCol[0].iFrom;
73348      aiCol = &iCol;
73349    }
73350    for(i=0; i<pFKey->nCol; i++){
73351      if( aiCol[i]==pTab->iPKey ){
73352        aiCol[i] = -1;
73353      }
73354#ifndef SQLITE_OMIT_AUTHORIZATION
73355      /* Request permission to read the parent key columns. If the
73356      ** authorization callback returns SQLITE_IGNORE, behave as if any
73357      ** values read from the parent table are NULL. */
73358      if( db->xAuth ){
73359        int rcauth;
73360        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
73361        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
73362        isIgnore = (rcauth==SQLITE_IGNORE);
73363      }
73364#endif
73365    }
73366
73367    /* Take a shared-cache advisory read-lock on the parent table. Allocate
73368    ** a cursor to use to search the unique index on the parent key columns
73369    ** in the parent table.  */
73370    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
73371    pParse->nTab++;
73372
73373    if( regOld!=0 ){
73374      /* A row is being removed from the child table. Search for the parent.
73375      ** If the parent does not exist, removing the child row resolves an
73376      ** outstanding foreign key constraint violation. */
73377      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
73378    }
73379    if( regNew!=0 ){
73380      /* A row is being added to the child table. If a parent row cannot
73381      ** be found, adding the child row has violated the FK constraint. */
73382      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
73383    }
73384
73385    sqlite3DbFree(db, aiFree);
73386  }
73387
73388  /* Loop through all the foreign key constraints that refer to this table */
73389  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
73390    Index *pIdx = 0;              /* Foreign key index for pFKey */
73391    SrcList *pSrc;
73392    int *aiCol = 0;
73393
73394    if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
73395      assert( regOld==0 && regNew!=0 );
73396      /* Inserting a single row into a parent table cannot cause an immediate
73397      ** foreign key violation. So do nothing in this case.  */
73398      continue;
73399    }
73400
73401    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
73402      if( !isIgnoreErrors || db->mallocFailed ) return;
73403      continue;
73404    }
73405    assert( aiCol || pFKey->nCol==1 );
73406
73407    /* Create a SrcList structure containing a single table (the table
73408    ** the foreign key that refers to this table is attached to). This
73409    ** is required for the sqlite3WhereXXX() interface.  */
73410    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
73411    if( pSrc ){
73412      struct SrcList_item *pItem = pSrc->a;
73413      pItem->pTab = pFKey->pFrom;
73414      pItem->zName = pFKey->pFrom->zName;
73415      pItem->pTab->nRef++;
73416      pItem->iCursor = pParse->nTab++;
73417
73418      if( regNew!=0 ){
73419        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
73420      }
73421      if( regOld!=0 ){
73422        /* If there is a RESTRICT action configured for the current operation
73423        ** on the parent table of this FK, then throw an exception
73424        ** immediately if the FK constraint is violated, even if this is a
73425        ** deferred trigger. That's what RESTRICT means. To defer checking
73426        ** the constraint, the FK should specify NO ACTION (represented
73427        ** using OE_None). NO ACTION is the default.  */
73428        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
73429      }
73430      pItem->zName = 0;
73431      sqlite3SrcListDelete(db, pSrc);
73432    }
73433    sqlite3DbFree(db, aiCol);
73434  }
73435}
73436
73437#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
73438
73439/*
73440** This function is called before generating code to update or delete a
73441** row contained in table pTab.
73442*/
73443SQLITE_PRIVATE u32 sqlite3FkOldmask(
73444  Parse *pParse,                  /* Parse context */
73445  Table *pTab                     /* Table being modified */
73446){
73447  u32 mask = 0;
73448  if( pParse->db->flags&SQLITE_ForeignKeys ){
73449    FKey *p;
73450    int i;
73451    for(p=pTab->pFKey; p; p=p->pNextFrom){
73452      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
73453    }
73454    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
73455      Index *pIdx = 0;
73456      locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
73457      if( pIdx ){
73458        for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
73459      }
73460    }
73461  }
73462  return mask;
73463}
73464
73465/*
73466** This function is called before generating code to update or delete a
73467** row contained in table pTab. If the operation is a DELETE, then
73468** parameter aChange is passed a NULL value. For an UPDATE, aChange points
73469** to an array of size N, where N is the number of columns in table pTab.
73470** If the i'th column is not modified by the UPDATE, then the corresponding
73471** entry in the aChange[] array is set to -1. If the column is modified,
73472** the value is 0 or greater. Parameter chngRowid is set to true if the
73473** UPDATE statement modifies the rowid fields of the table.
73474**
73475** If any foreign key processing will be required, this function returns
73476** true. If there is no foreign key related processing, this function
73477** returns false.
73478*/
73479SQLITE_PRIVATE int sqlite3FkRequired(
73480  Parse *pParse,                  /* Parse context */
73481  Table *pTab,                    /* Table being modified */
73482  int *aChange,                   /* Non-NULL for UPDATE operations */
73483  int chngRowid                   /* True for UPDATE that affects rowid */
73484){
73485  if( pParse->db->flags&SQLITE_ForeignKeys ){
73486    if( !aChange ){
73487      /* A DELETE operation. Foreign key processing is required if the
73488      ** table in question is either the child or parent table for any
73489      ** foreign key constraint.  */
73490      return (sqlite3FkReferences(pTab) || pTab->pFKey);
73491    }else{
73492      /* This is an UPDATE. Foreign key processing is only required if the
73493      ** operation modifies one or more child or parent key columns. */
73494      int i;
73495      FKey *p;
73496
73497      /* Check if any child key columns are being modified. */
73498      for(p=pTab->pFKey; p; p=p->pNextFrom){
73499        for(i=0; i<p->nCol; i++){
73500          int iChildKey = p->aCol[i].iFrom;
73501          if( aChange[iChildKey]>=0 ) return 1;
73502          if( iChildKey==pTab->iPKey && chngRowid ) return 1;
73503        }
73504      }
73505
73506      /* Check if any parent key columns are being modified. */
73507      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
73508        for(i=0; i<p->nCol; i++){
73509          char *zKey = p->aCol[i].zCol;
73510          int iKey;
73511          for(iKey=0; iKey<pTab->nCol; iKey++){
73512            Column *pCol = &pTab->aCol[iKey];
73513            if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
73514              if( aChange[iKey]>=0 ) return 1;
73515              if( iKey==pTab->iPKey && chngRowid ) return 1;
73516            }
73517          }
73518        }
73519      }
73520    }
73521  }
73522  return 0;
73523}
73524
73525/*
73526** This function is called when an UPDATE or DELETE operation is being
73527** compiled on table pTab, which is the parent table of foreign-key pFKey.
73528** If the current operation is an UPDATE, then the pChanges parameter is
73529** passed a pointer to the list of columns being modified. If it is a
73530** DELETE, pChanges is passed a NULL pointer.
73531**
73532** It returns a pointer to a Trigger structure containing a trigger
73533** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
73534** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
73535** returned (these actions require no special handling by the triggers
73536** sub-system, code for them is created by fkScanChildren()).
73537**
73538** For example, if pFKey is the foreign key and pTab is table "p" in
73539** the following schema:
73540**
73541**   CREATE TABLE p(pk PRIMARY KEY);
73542**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
73543**
73544** then the returned trigger structure is equivalent to:
73545**
73546**   CREATE TRIGGER ... DELETE ON p BEGIN
73547**     DELETE FROM c WHERE ck = old.pk;
73548**   END;
73549**
73550** The returned pointer is cached as part of the foreign key object. It
73551** is eventually freed along with the rest of the foreign key object by
73552** sqlite3FkDelete().
73553*/
73554static Trigger *fkActionTrigger(
73555  Parse *pParse,                  /* Parse context */
73556  Table *pTab,                    /* Table being updated or deleted from */
73557  FKey *pFKey,                    /* Foreign key to get action for */
73558  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
73559){
73560  sqlite3 *db = pParse->db;       /* Database handle */
73561  int action;                     /* One of OE_None, OE_Cascade etc. */
73562  Trigger *pTrigger;              /* Trigger definition to return */
73563  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
73564
73565  action = pFKey->aAction[iAction];
73566  pTrigger = pFKey->apTrigger[iAction];
73567
73568  if( action!=OE_None && !pTrigger ){
73569    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
73570    char const *zFrom;            /* Name of child table */
73571    int nFrom;                    /* Length in bytes of zFrom */
73572    Index *pIdx = 0;              /* Parent key index for this FK */
73573    int *aiCol = 0;               /* child table cols -> parent key cols */
73574    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
73575    Expr *pWhere = 0;             /* WHERE clause of trigger step */
73576    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
73577    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
73578    int i;                        /* Iterator variable */
73579    Expr *pWhen = 0;              /* WHEN clause for the trigger */
73580
73581    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
73582    assert( aiCol || pFKey->nCol==1 );
73583
73584    for(i=0; i<pFKey->nCol; i++){
73585      Token tOld = { "old", 3 };  /* Literal "old" token */
73586      Token tNew = { "new", 3 };  /* Literal "new" token */
73587      Token tFromCol;             /* Name of column in child table */
73588      Token tToCol;               /* Name of column in parent table */
73589      int iFromCol;               /* Idx of column in child table */
73590      Expr *pEq;                  /* tFromCol = OLD.tToCol */
73591
73592      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
73593      assert( iFromCol>=0 );
73594      tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
73595      tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
73596
73597      tToCol.n = sqlite3Strlen30(tToCol.z);
73598      tFromCol.n = sqlite3Strlen30(tFromCol.z);
73599
73600      /* Create the expression "OLD.zToCol = zFromCol". It is important
73601      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
73602      ** that the affinity and collation sequence associated with the
73603      ** parent table are used for the comparison. */
73604      pEq = sqlite3PExpr(pParse, TK_EQ,
73605          sqlite3PExpr(pParse, TK_DOT,
73606            sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
73607            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
73608          , 0),
73609          sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
73610      , 0);
73611      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
73612
73613      /* For ON UPDATE, construct the next term of the WHEN clause.
73614      ** The final WHEN clause will be like this:
73615      **
73616      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
73617      */
73618      if( pChanges ){
73619        pEq = sqlite3PExpr(pParse, TK_IS,
73620            sqlite3PExpr(pParse, TK_DOT,
73621              sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
73622              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
73623              0),
73624            sqlite3PExpr(pParse, TK_DOT,
73625              sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
73626              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
73627              0),
73628            0);
73629        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
73630      }
73631
73632      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
73633        Expr *pNew;
73634        if( action==OE_Cascade ){
73635          pNew = sqlite3PExpr(pParse, TK_DOT,
73636            sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
73637            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
73638          , 0);
73639        }else if( action==OE_SetDflt ){
73640          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
73641          if( pDflt ){
73642            pNew = sqlite3ExprDup(db, pDflt, 0);
73643          }else{
73644            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
73645          }
73646        }else{
73647          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
73648        }
73649        pList = sqlite3ExprListAppend(pParse, pList, pNew);
73650        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
73651      }
73652    }
73653    sqlite3DbFree(db, aiCol);
73654
73655    zFrom = pFKey->pFrom->zName;
73656    nFrom = sqlite3Strlen30(zFrom);
73657
73658    if( action==OE_Restrict ){
73659      Token tFrom;
73660      Expr *pRaise;
73661
73662      tFrom.z = zFrom;
73663      tFrom.n = nFrom;
73664      pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
73665      if( pRaise ){
73666        pRaise->affinity = OE_Abort;
73667      }
73668      pSelect = sqlite3SelectNew(pParse,
73669          sqlite3ExprListAppend(pParse, 0, pRaise),
73670          sqlite3SrcListAppend(db, 0, &tFrom, 0),
73671          pWhere,
73672          0, 0, 0, 0, 0, 0
73673      );
73674      pWhere = 0;
73675    }
73676
73677    /* In the current implementation, pTab->dbMem==0 for all tables except
73678    ** for temporary tables used to describe subqueries.  And temporary
73679    ** tables do not have foreign key constraints.  Hence, pTab->dbMem
73680    ** should always be 0 there.
73681    */
73682    enableLookaside = db->lookaside.bEnabled;
73683    db->lookaside.bEnabled = 0;
73684
73685    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
73686        sizeof(Trigger) +         /* struct Trigger */
73687        sizeof(TriggerStep) +     /* Single step in trigger program */
73688        nFrom + 1                 /* Space for pStep->target.z */
73689    );
73690    if( pTrigger ){
73691      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
73692      pStep->target.z = (char *)&pStep[1];
73693      pStep->target.n = nFrom;
73694      memcpy((char *)pStep->target.z, zFrom, nFrom);
73695
73696      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
73697      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
73698      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
73699      if( pWhen ){
73700        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
73701        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
73702      }
73703    }
73704
73705    /* Re-enable the lookaside buffer, if it was disabled earlier. */
73706    db->lookaside.bEnabled = enableLookaside;
73707
73708    sqlite3ExprDelete(db, pWhere);
73709    sqlite3ExprDelete(db, pWhen);
73710    sqlite3ExprListDelete(db, pList);
73711    sqlite3SelectDelete(db, pSelect);
73712    if( db->mallocFailed==1 ){
73713      fkTriggerDelete(db, pTrigger);
73714      return 0;
73715    }
73716
73717    switch( action ){
73718      case OE_Restrict:
73719        pStep->op = TK_SELECT;
73720        break;
73721      case OE_Cascade:
73722        if( !pChanges ){
73723          pStep->op = TK_DELETE;
73724          break;
73725        }
73726      default:
73727        pStep->op = TK_UPDATE;
73728    }
73729    pStep->pTrig = pTrigger;
73730    pTrigger->pSchema = pTab->pSchema;
73731    pTrigger->pTabSchema = pTab->pSchema;
73732    pFKey->apTrigger[iAction] = pTrigger;
73733    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
73734  }
73735
73736  return pTrigger;
73737}
73738
73739/*
73740** This function is called when deleting or updating a row to implement
73741** any required CASCADE, SET NULL or SET DEFAULT actions.
73742*/
73743SQLITE_PRIVATE void sqlite3FkActions(
73744  Parse *pParse,                  /* Parse context */
73745  Table *pTab,                    /* Table being updated or deleted from */
73746  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
73747  int regOld                      /* Address of array containing old row */
73748){
73749  /* If foreign-key support is enabled, iterate through all FKs that
73750  ** refer to table pTab. If there is an action associated with the FK
73751  ** for this operation (either update or delete), invoke the associated
73752  ** trigger sub-program.  */
73753  if( pParse->db->flags&SQLITE_ForeignKeys ){
73754    FKey *pFKey;                  /* Iterator variable */
73755    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
73756      Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
73757      if( pAction ){
73758        sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
73759      }
73760    }
73761  }
73762}
73763
73764#endif /* ifndef SQLITE_OMIT_TRIGGER */
73765
73766/*
73767** Free all memory associated with foreign key definitions attached to
73768** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
73769** hash table.
73770*/
73771SQLITE_PRIVATE void sqlite3FkDelete(Table *pTab){
73772  FKey *pFKey;                    /* Iterator variable */
73773  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
73774
73775  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
73776
73777    /* Remove the FK from the fkeyHash hash table. */
73778    if( pFKey->pPrevTo ){
73779      pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
73780    }else{
73781      void *data = (void *)pFKey->pNextTo;
73782      const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
73783      sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
73784    }
73785    if( pFKey->pNextTo ){
73786      pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
73787    }
73788
73789    /* Delete any triggers created to implement actions for this FK. */
73790#ifndef SQLITE_OMIT_TRIGGER
73791    fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
73792    fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
73793#endif
73794
73795    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
73796    ** classified as either immediate or deferred.
73797    */
73798    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
73799
73800    pNext = pFKey->pNextFrom;
73801    sqlite3DbFree(pTab->dbMem, pFKey);
73802  }
73803}
73804#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
73805
73806/************** End of fkey.c ************************************************/
73807/************** Begin file insert.c ******************************************/
73808/*
73809** 2001 September 15
73810**
73811** The author disclaims copyright to this source code.  In place of
73812** a legal notice, here is a blessing:
73813**
73814**    May you do good and not evil.
73815**    May you find forgiveness for yourself and forgive others.
73816**    May you share freely, never taking more than you give.
73817**
73818*************************************************************************
73819** This file contains C code routines that are called by the parser
73820** to handle INSERT statements in SQLite.
73821*/
73822
73823/*
73824** Generate code that will open a table for reading.
73825*/
73826SQLITE_PRIVATE void sqlite3OpenTable(
73827  Parse *p,       /* Generate code into this VDBE */
73828  int iCur,       /* The cursor number of the table */
73829  int iDb,        /* The database index in sqlite3.aDb[] */
73830  Table *pTab,    /* The table to be opened */
73831  int opcode      /* OP_OpenRead or OP_OpenWrite */
73832){
73833  Vdbe *v;
73834  if( IsVirtual(pTab) ) return;
73835  v = sqlite3GetVdbe(p);
73836  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
73837  sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
73838  sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
73839  sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
73840  VdbeComment((v, "%s", pTab->zName));
73841}
73842
73843/*
73844** Return a pointer to the column affinity string associated with index
73845** pIdx. A column affinity string has one character for each column in
73846** the table, according to the affinity of the column:
73847**
73848**  Character      Column affinity
73849**  ------------------------------
73850**  'a'            TEXT
73851**  'b'            NONE
73852**  'c'            NUMERIC
73853**  'd'            INTEGER
73854**  'e'            REAL
73855**
73856** An extra 'b' is appended to the end of the string to cover the
73857** rowid that appears as the last column in every index.
73858**
73859** Memory for the buffer containing the column index affinity string
73860** is managed along with the rest of the Index structure. It will be
73861** released when sqlite3DeleteIndex() is called.
73862*/
73863SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
73864  if( !pIdx->zColAff ){
73865    /* The first time a column affinity string for a particular index is
73866    ** required, it is allocated and populated here. It is then stored as
73867    ** a member of the Index structure for subsequent use.
73868    **
73869    ** The column affinity string will eventually be deleted by
73870    ** sqliteDeleteIndex() when the Index structure itself is cleaned
73871    ** up.
73872    */
73873    int n;
73874    Table *pTab = pIdx->pTable;
73875    sqlite3 *db = sqlite3VdbeDb(v);
73876    pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
73877    if( !pIdx->zColAff ){
73878      db->mallocFailed = 1;
73879      return 0;
73880    }
73881    for(n=0; n<pIdx->nColumn; n++){
73882      pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
73883    }
73884    pIdx->zColAff[n++] = SQLITE_AFF_NONE;
73885    pIdx->zColAff[n] = 0;
73886  }
73887
73888  return pIdx->zColAff;
73889}
73890
73891/*
73892** Set P4 of the most recently inserted opcode to a column affinity
73893** string for table pTab. A column affinity string has one character
73894** for each column indexed by the index, according to the affinity of the
73895** column:
73896**
73897**  Character      Column affinity
73898**  ------------------------------
73899**  'a'            TEXT
73900**  'b'            NONE
73901**  'c'            NUMERIC
73902**  'd'            INTEGER
73903**  'e'            REAL
73904*/
73905SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
73906  /* The first time a column affinity string for a particular table
73907  ** is required, it is allocated and populated here. It is then
73908  ** stored as a member of the Table structure for subsequent use.
73909  **
73910  ** The column affinity string will eventually be deleted by
73911  ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
73912  */
73913  if( !pTab->zColAff ){
73914    char *zColAff;
73915    int i;
73916    sqlite3 *db = sqlite3VdbeDb(v);
73917
73918    zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
73919    if( !zColAff ){
73920      db->mallocFailed = 1;
73921      return;
73922    }
73923
73924    for(i=0; i<pTab->nCol; i++){
73925      zColAff[i] = pTab->aCol[i].affinity;
73926    }
73927    zColAff[pTab->nCol] = '\0';
73928
73929    pTab->zColAff = zColAff;
73930  }
73931
73932  sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
73933}
73934
73935/*
73936** Return non-zero if the table pTab in database iDb or any of its indices
73937** have been opened at any point in the VDBE program beginning at location
73938** iStartAddr throught the end of the program.  This is used to see if
73939** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
73940** run without using temporary table for the results of the SELECT.
73941*/
73942static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
73943  Vdbe *v = sqlite3GetVdbe(p);
73944  int i;
73945  int iEnd = sqlite3VdbeCurrentAddr(v);
73946#ifndef SQLITE_OMIT_VIRTUALTABLE
73947  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
73948#endif
73949
73950  for(i=iStartAddr; i<iEnd; i++){
73951    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
73952    assert( pOp!=0 );
73953    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
73954      Index *pIndex;
73955      int tnum = pOp->p2;
73956      if( tnum==pTab->tnum ){
73957        return 1;
73958      }
73959      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
73960        if( tnum==pIndex->tnum ){
73961          return 1;
73962        }
73963      }
73964    }
73965#ifndef SQLITE_OMIT_VIRTUALTABLE
73966    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
73967      assert( pOp->p4.pVtab!=0 );
73968      assert( pOp->p4type==P4_VTAB );
73969      return 1;
73970    }
73971#endif
73972  }
73973  return 0;
73974}
73975
73976#ifndef SQLITE_OMIT_AUTOINCREMENT
73977/*
73978** Locate or create an AutoincInfo structure associated with table pTab
73979** which is in database iDb.  Return the register number for the register
73980** that holds the maximum rowid.
73981**
73982** There is at most one AutoincInfo structure per table even if the
73983** same table is autoincremented multiple times due to inserts within
73984** triggers.  A new AutoincInfo structure is created if this is the
73985** first use of table pTab.  On 2nd and subsequent uses, the original
73986** AutoincInfo structure is used.
73987**
73988** Three memory locations are allocated:
73989**
73990**   (1)  Register to hold the name of the pTab table.
73991**   (2)  Register to hold the maximum ROWID of pTab.
73992**   (3)  Register to hold the rowid in sqlite_sequence of pTab
73993**
73994** The 2nd register is the one that is returned.  That is all the
73995** insert routine needs to know about.
73996*/
73997static int autoIncBegin(
73998  Parse *pParse,      /* Parsing context */
73999  int iDb,            /* Index of the database holding pTab */
74000  Table *pTab         /* The table we are writing to */
74001){
74002  int memId = 0;      /* Register holding maximum rowid */
74003  if( pTab->tabFlags & TF_Autoincrement ){
74004    Parse *pToplevel = sqlite3ParseToplevel(pParse);
74005    AutoincInfo *pInfo;
74006
74007    pInfo = pToplevel->pAinc;
74008    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
74009    if( pInfo==0 ){
74010      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
74011      if( pInfo==0 ) return 0;
74012      pInfo->pNext = pToplevel->pAinc;
74013      pToplevel->pAinc = pInfo;
74014      pInfo->pTab = pTab;
74015      pInfo->iDb = iDb;
74016      pToplevel->nMem++;                  /* Register to hold name of table */
74017      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
74018      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
74019    }
74020    memId = pInfo->regCtr;
74021  }
74022  return memId;
74023}
74024
74025/*
74026** This routine generates code that will initialize all of the
74027** register used by the autoincrement tracker.
74028*/
74029SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
74030  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
74031  sqlite3 *db = pParse->db;  /* The database connection */
74032  Db *pDb;                   /* Database only autoinc table */
74033  int memId;                 /* Register holding max rowid */
74034  int addr;                  /* A VDBE address */
74035  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
74036
74037  /* This routine is never called during trigger-generation.  It is
74038  ** only called from the top-level */
74039  assert( pParse->pTriggerTab==0 );
74040  assert( pParse==sqlite3ParseToplevel(pParse) );
74041
74042  assert( v );   /* We failed long ago if this is not so */
74043  for(p = pParse->pAinc; p; p = p->pNext){
74044    pDb = &db->aDb[p->iDb];
74045    memId = p->regCtr;
74046    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
74047    addr = sqlite3VdbeCurrentAddr(v);
74048    sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
74049    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
74050    sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
74051    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
74052    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
74053    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
74054    sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
74055    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
74056    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
74057    sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
74058    sqlite3VdbeAddOp0(v, OP_Close);
74059  }
74060}
74061
74062/*
74063** Update the maximum rowid for an autoincrement calculation.
74064**
74065** This routine should be called when the top of the stack holds a
74066** new rowid that is about to be inserted.  If that new rowid is
74067** larger than the maximum rowid in the memId memory cell, then the
74068** memory cell is updated.  The stack is unchanged.
74069*/
74070static void autoIncStep(Parse *pParse, int memId, int regRowid){
74071  if( memId>0 ){
74072    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
74073  }
74074}
74075
74076/*
74077** This routine generates the code needed to write autoincrement
74078** maximum rowid values back into the sqlite_sequence register.
74079** Every statement that might do an INSERT into an autoincrement
74080** table (either directly or through triggers) needs to call this
74081** routine just before the "exit" code.
74082*/
74083SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
74084  AutoincInfo *p;
74085  Vdbe *v = pParse->pVdbe;
74086  sqlite3 *db = pParse->db;
74087
74088  assert( v );
74089  for(p = pParse->pAinc; p; p = p->pNext){
74090    Db *pDb = &db->aDb[p->iDb];
74091    int j1, j2, j3, j4, j5;
74092    int iRec;
74093    int memId = p->regCtr;
74094
74095    iRec = sqlite3GetTempReg(pParse);
74096    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
74097    j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
74098    j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
74099    j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
74100    j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
74101    sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
74102    sqlite3VdbeJumpHere(v, j2);
74103    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
74104    j5 = sqlite3VdbeAddOp0(v, OP_Goto);
74105    sqlite3VdbeJumpHere(v, j4);
74106    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
74107    sqlite3VdbeJumpHere(v, j1);
74108    sqlite3VdbeJumpHere(v, j5);
74109    sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
74110    sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
74111    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
74112    sqlite3VdbeAddOp0(v, OP_Close);
74113    sqlite3ReleaseTempReg(pParse, iRec);
74114  }
74115}
74116#else
74117/*
74118** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
74119** above are all no-ops
74120*/
74121# define autoIncBegin(A,B,C) (0)
74122# define autoIncStep(A,B,C)
74123#endif /* SQLITE_OMIT_AUTOINCREMENT */
74124
74125
74126/* Forward declaration */
74127static int xferOptimization(
74128  Parse *pParse,        /* Parser context */
74129  Table *pDest,         /* The table we are inserting into */
74130  Select *pSelect,      /* A SELECT statement to use as the data source */
74131  int onError,          /* How to handle constraint errors */
74132  int iDbDest           /* The database of pDest */
74133);
74134
74135/*
74136** This routine is call to handle SQL of the following forms:
74137**
74138**    insert into TABLE (IDLIST) values(EXPRLIST)
74139**    insert into TABLE (IDLIST) select
74140**
74141** The IDLIST following the table name is always optional.  If omitted,
74142** then a list of all columns for the table is substituted.  The IDLIST
74143** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
74144**
74145** The pList parameter holds EXPRLIST in the first form of the INSERT
74146** statement above, and pSelect is NULL.  For the second form, pList is
74147** NULL and pSelect is a pointer to the select statement used to generate
74148** data for the insert.
74149**
74150** The code generated follows one of four templates.  For a simple
74151** select with data coming from a VALUES clause, the code executes
74152** once straight down through.  Pseudo-code follows (we call this
74153** the "1st template"):
74154**
74155**         open write cursor to <table> and its indices
74156**         puts VALUES clause expressions onto the stack
74157**         write the resulting record into <table>
74158**         cleanup
74159**
74160** The three remaining templates assume the statement is of the form
74161**
74162**   INSERT INTO <table> SELECT ...
74163**
74164** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
74165** in other words if the SELECT pulls all columns from a single table
74166** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
74167** if <table2> and <table1> are distinct tables but have identical
74168** schemas, including all the same indices, then a special optimization
74169** is invoked that copies raw records from <table2> over to <table1>.
74170** See the xferOptimization() function for the implementation of this
74171** template.  This is the 2nd template.
74172**
74173**         open a write cursor to <table>
74174**         open read cursor on <table2>
74175**         transfer all records in <table2> over to <table>
74176**         close cursors
74177**         foreach index on <table>
74178**           open a write cursor on the <table> index
74179**           open a read cursor on the corresponding <table2> index
74180**           transfer all records from the read to the write cursors
74181**           close cursors
74182**         end foreach
74183**
74184** The 3rd template is for when the second template does not apply
74185** and the SELECT clause does not read from <table> at any time.
74186** The generated code follows this template:
74187**
74188**         EOF <- 0
74189**         X <- A
74190**         goto B
74191**      A: setup for the SELECT
74192**         loop over the rows in the SELECT
74193**           load values into registers R..R+n
74194**           yield X
74195**         end loop
74196**         cleanup after the SELECT
74197**         EOF <- 1
74198**         yield X
74199**         goto A
74200**      B: open write cursor to <table> and its indices
74201**      C: yield X
74202**         if EOF goto D
74203**         insert the select result into <table> from R..R+n
74204**         goto C
74205**      D: cleanup
74206**
74207** The 4th template is used if the insert statement takes its
74208** values from a SELECT but the data is being inserted into a table
74209** that is also read as part of the SELECT.  In the third form,
74210** we have to use a intermediate table to store the results of
74211** the select.  The template is like this:
74212**
74213**         EOF <- 0
74214**         X <- A
74215**         goto B
74216**      A: setup for the SELECT
74217**         loop over the tables in the SELECT
74218**           load value into register R..R+n
74219**           yield X
74220**         end loop
74221**         cleanup after the SELECT
74222**         EOF <- 1
74223**         yield X
74224**         halt-error
74225**      B: open temp table
74226**      L: yield X
74227**         if EOF goto M
74228**         insert row from R..R+n into temp table
74229**         goto L
74230**      M: open write cursor to <table> and its indices
74231**         rewind temp table
74232**      C: loop over rows of intermediate table
74233**           transfer values form intermediate table into <table>
74234**         end loop
74235**      D: cleanup
74236*/
74237SQLITE_PRIVATE void sqlite3Insert(
74238  Parse *pParse,        /* Parser context */
74239  SrcList *pTabList,    /* Name of table into which we are inserting */
74240  ExprList *pList,      /* List of values to be inserted */
74241  Select *pSelect,      /* A SELECT statement to use as the data source */
74242  IdList *pColumn,      /* Column names corresponding to IDLIST. */
74243  int onError           /* How to handle constraint errors */
74244){
74245  sqlite3 *db;          /* The main database structure */
74246  Table *pTab;          /* The table to insert into.  aka TABLE */
74247  char *zTab;           /* Name of the table into which we are inserting */
74248  const char *zDb;      /* Name of the database holding this table */
74249  int i, j, idx;        /* Loop counters */
74250  Vdbe *v;              /* Generate code into this virtual machine */
74251  Index *pIdx;          /* For looping over indices of the table */
74252  int nColumn;          /* Number of columns in the data */
74253  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
74254  int baseCur = 0;      /* VDBE Cursor number for pTab */
74255  int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
74256  int endOfLoop;        /* Label for the end of the insertion loop */
74257  int useTempTable = 0; /* Store SELECT results in intermediate table */
74258  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
74259  int addrInsTop = 0;   /* Jump to label "D" */
74260  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
74261  int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
74262  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
74263  int iDb;              /* Index of database holding TABLE */
74264  Db *pDb;              /* The database containing table being inserted into */
74265  int appendFlag = 0;   /* True if the insert is likely to be an append */
74266
74267  /* Register allocations */
74268  int regFromSelect = 0;/* Base register for data coming from SELECT */
74269  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
74270  int regRowCount = 0;  /* Memory cell used for the row counter */
74271  int regIns;           /* Block of regs holding rowid+data being inserted */
74272  int regRowid;         /* registers holding insert rowid */
74273  int regData;          /* register holding first column to insert */
74274  int regRecord;        /* Holds the assemblied row record */
74275  int regEof = 0;       /* Register recording end of SELECT data */
74276  int *aRegIdx = 0;     /* One register allocated to each index */
74277
74278#ifndef SQLITE_OMIT_TRIGGER
74279  int isView;                 /* True if attempting to insert into a view */
74280  Trigger *pTrigger;          /* List of triggers on pTab, if required */
74281  int tmask;                  /* Mask of trigger times */
74282#endif
74283
74284  db = pParse->db;
74285  memset(&dest, 0, sizeof(dest));
74286  if( pParse->nErr || db->mallocFailed ){
74287    goto insert_cleanup;
74288  }
74289
74290  /* Locate the table into which we will be inserting new information.
74291  */
74292  assert( pTabList->nSrc==1 );
74293  zTab = pTabList->a[0].zName;
74294  if( NEVER(zTab==0) ) goto insert_cleanup;
74295  pTab = sqlite3SrcListLookup(pParse, pTabList);
74296  if( pTab==0 ){
74297    goto insert_cleanup;
74298  }
74299  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74300  assert( iDb<db->nDb );
74301  pDb = &db->aDb[iDb];
74302  zDb = pDb->zName;
74303  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
74304    goto insert_cleanup;
74305  }
74306
74307  /* Figure out if we have any triggers and if the table being
74308  ** inserted into is a view
74309  */
74310#ifndef SQLITE_OMIT_TRIGGER
74311  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
74312  isView = pTab->pSelect!=0;
74313#else
74314# define pTrigger 0
74315# define tmask 0
74316# define isView 0
74317#endif
74318#ifdef SQLITE_OMIT_VIEW
74319# undef isView
74320# define isView 0
74321#endif
74322  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
74323
74324  /* If pTab is really a view, make sure it has been initialized.
74325  ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
74326  ** module table).
74327  */
74328  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
74329    goto insert_cleanup;
74330  }
74331
74332  /* Ensure that:
74333  *  (a) the table is not read-only,
74334  *  (b) that if it is a view then ON INSERT triggers exist
74335  */
74336  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
74337    goto insert_cleanup;
74338  }
74339
74340  /* Allocate a VDBE
74341  */
74342  v = sqlite3GetVdbe(pParse);
74343  if( v==0 ) goto insert_cleanup;
74344  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
74345  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
74346
74347#ifndef SQLITE_OMIT_XFER_OPT
74348  /* If the statement is of the form
74349  **
74350  **       INSERT INTO <table1> SELECT * FROM <table2>;
74351  **
74352  ** Then special optimizations can be applied that make the transfer
74353  ** very fast and which reduce fragmentation of indices.
74354  **
74355  ** This is the 2nd template.
74356  */
74357  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
74358    assert( !pTrigger );
74359    assert( pList==0 );
74360    goto insert_end;
74361  }
74362#endif /* SQLITE_OMIT_XFER_OPT */
74363
74364  /* If this is an AUTOINCREMENT table, look up the sequence number in the
74365  ** sqlite_sequence table and store it in memory cell regAutoinc.
74366  */
74367  regAutoinc = autoIncBegin(pParse, iDb, pTab);
74368
74369  /* Figure out how many columns of data are supplied.  If the data
74370  ** is coming from a SELECT statement, then generate a co-routine that
74371  ** produces a single row of the SELECT on each invocation.  The
74372  ** co-routine is the common header to the 3rd and 4th templates.
74373  */
74374  if( pSelect ){
74375    /* Data is coming from a SELECT.  Generate code to implement that SELECT
74376    ** as a co-routine.  The code is common to both the 3rd and 4th
74377    ** templates:
74378    **
74379    **         EOF <- 0
74380    **         X <- A
74381    **         goto B
74382    **      A: setup for the SELECT
74383    **         loop over the tables in the SELECT
74384    **           load value into register R..R+n
74385    **           yield X
74386    **         end loop
74387    **         cleanup after the SELECT
74388    **         EOF <- 1
74389    **         yield X
74390    **         halt-error
74391    **
74392    ** On each invocation of the co-routine, it puts a single row of the
74393    ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
74394    ** (These output registers are allocated by sqlite3Select().)  When
74395    ** the SELECT completes, it sets the EOF flag stored in regEof.
74396    */
74397    int rc, j1;
74398
74399    regEof = ++pParse->nMem;
74400    sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
74401    VdbeComment((v, "SELECT eof flag"));
74402    sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
74403    addrSelect = sqlite3VdbeCurrentAddr(v)+2;
74404    sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
74405    j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
74406    VdbeComment((v, "Jump over SELECT coroutine"));
74407
74408    /* Resolve the expressions in the SELECT statement and execute it. */
74409    rc = sqlite3Select(pParse, pSelect, &dest);
74410    assert( pParse->nErr==0 || rc );
74411    if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
74412      goto insert_cleanup;
74413    }
74414    sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
74415    sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
74416    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
74417    VdbeComment((v, "End of SELECT coroutine"));
74418    sqlite3VdbeJumpHere(v, j1);                          /* label B: */
74419
74420    regFromSelect = dest.iMem;
74421    assert( pSelect->pEList );
74422    nColumn = pSelect->pEList->nExpr;
74423    assert( dest.nMem==nColumn );
74424
74425    /* Set useTempTable to TRUE if the result of the SELECT statement
74426    ** should be written into a temporary table (template 4).  Set to
74427    ** FALSE if each* row of the SELECT can be written directly into
74428    ** the destination table (template 3).
74429    **
74430    ** A temp table must be used if the table being updated is also one
74431    ** of the tables being read by the SELECT statement.  Also use a
74432    ** temp table in the case of row triggers.
74433    */
74434    if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
74435      useTempTable = 1;
74436    }
74437
74438    if( useTempTable ){
74439      /* Invoke the coroutine to extract information from the SELECT
74440      ** and add it to a transient table srcTab.  The code generated
74441      ** here is from the 4th template:
74442      **
74443      **      B: open temp table
74444      **      L: yield X
74445      **         if EOF goto M
74446      **         insert row from R..R+n into temp table
74447      **         goto L
74448      **      M: ...
74449      */
74450      int regRec;          /* Register to hold packed record */
74451      int regTempRowid;    /* Register to hold temp table ROWID */
74452      int addrTop;         /* Label "L" */
74453      int addrIf;          /* Address of jump to M */
74454
74455      srcTab = pParse->nTab++;
74456      regRec = sqlite3GetTempReg(pParse);
74457      regTempRowid = sqlite3GetTempReg(pParse);
74458      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
74459      addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
74460      addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
74461      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
74462      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
74463      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
74464      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
74465      sqlite3VdbeJumpHere(v, addrIf);
74466      sqlite3ReleaseTempReg(pParse, regRec);
74467      sqlite3ReleaseTempReg(pParse, regTempRowid);
74468    }
74469  }else{
74470    /* This is the case if the data for the INSERT is coming from a VALUES
74471    ** clause
74472    */
74473    NameContext sNC;
74474    memset(&sNC, 0, sizeof(sNC));
74475    sNC.pParse = pParse;
74476    srcTab = -1;
74477    assert( useTempTable==0 );
74478    nColumn = pList ? pList->nExpr : 0;
74479    for(i=0; i<nColumn; i++){
74480      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
74481        goto insert_cleanup;
74482      }
74483    }
74484  }
74485
74486  /* Make sure the number of columns in the source data matches the number
74487  ** of columns to be inserted into the table.
74488  */
74489  if( IsVirtual(pTab) ){
74490    for(i=0; i<pTab->nCol; i++){
74491      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
74492    }
74493  }
74494  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
74495    sqlite3ErrorMsg(pParse,
74496       "table %S has %d columns but %d values were supplied",
74497       pTabList, 0, pTab->nCol-nHidden, nColumn);
74498    goto insert_cleanup;
74499  }
74500  if( pColumn!=0 && nColumn!=pColumn->nId ){
74501    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
74502    goto insert_cleanup;
74503  }
74504
74505  /* If the INSERT statement included an IDLIST term, then make sure
74506  ** all elements of the IDLIST really are columns of the table and
74507  ** remember the column indices.
74508  **
74509  ** If the table has an INTEGER PRIMARY KEY column and that column
74510  ** is named in the IDLIST, then record in the keyColumn variable
74511  ** the index into IDLIST of the primary key column.  keyColumn is
74512  ** the index of the primary key as it appears in IDLIST, not as
74513  ** is appears in the original table.  (The index of the primary
74514  ** key in the original table is pTab->iPKey.)
74515  */
74516  if( pColumn ){
74517    for(i=0; i<pColumn->nId; i++){
74518      pColumn->a[i].idx = -1;
74519    }
74520    for(i=0; i<pColumn->nId; i++){
74521      for(j=0; j<pTab->nCol; j++){
74522        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
74523          pColumn->a[i].idx = j;
74524          if( j==pTab->iPKey ){
74525            keyColumn = i;
74526          }
74527          break;
74528        }
74529      }
74530      if( j>=pTab->nCol ){
74531        if( sqlite3IsRowid(pColumn->a[i].zName) ){
74532          keyColumn = i;
74533        }else{
74534          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
74535              pTabList, 0, pColumn->a[i].zName);
74536          pParse->nErr++;
74537          goto insert_cleanup;
74538        }
74539      }
74540    }
74541  }
74542
74543  /* If there is no IDLIST term but the table has an integer primary
74544  ** key, the set the keyColumn variable to the primary key column index
74545  ** in the original table definition.
74546  */
74547  if( pColumn==0 && nColumn>0 ){
74548    keyColumn = pTab->iPKey;
74549  }
74550
74551  /* Initialize the count of rows to be inserted
74552  */
74553  if( db->flags & SQLITE_CountRows ){
74554    regRowCount = ++pParse->nMem;
74555    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
74556  }
74557
74558  /* If this is not a view, open the table and and all indices */
74559  if( !isView ){
74560    int nIdx;
74561
74562    baseCur = pParse->nTab;
74563    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
74564    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
74565    if( aRegIdx==0 ){
74566      goto insert_cleanup;
74567    }
74568    for(i=0; i<nIdx; i++){
74569      aRegIdx[i] = ++pParse->nMem;
74570    }
74571  }
74572
74573  /* This is the top of the main insertion loop */
74574  if( useTempTable ){
74575    /* This block codes the top of loop only.  The complete loop is the
74576    ** following pseudocode (template 4):
74577    **
74578    **         rewind temp table
74579    **      C: loop over rows of intermediate table
74580    **           transfer values form intermediate table into <table>
74581    **         end loop
74582    **      D: ...
74583    */
74584    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
74585    addrCont = sqlite3VdbeCurrentAddr(v);
74586  }else if( pSelect ){
74587    /* This block codes the top of loop only.  The complete loop is the
74588    ** following pseudocode (template 3):
74589    **
74590    **      C: yield X
74591    **         if EOF goto D
74592    **         insert the select result into <table> from R..R+n
74593    **         goto C
74594    **      D: ...
74595    */
74596    addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
74597    addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
74598  }
74599
74600  /* Allocate registers for holding the rowid of the new row,
74601  ** the content of the new row, and the assemblied row record.
74602  */
74603  regRecord = ++pParse->nMem;
74604  regRowid = regIns = pParse->nMem+1;
74605  pParse->nMem += pTab->nCol + 1;
74606  if( IsVirtual(pTab) ){
74607    regRowid++;
74608    pParse->nMem++;
74609  }
74610  regData = regRowid+1;
74611
74612  /* Run the BEFORE and INSTEAD OF triggers, if there are any
74613  */
74614  endOfLoop = sqlite3VdbeMakeLabel(v);
74615  if( tmask & TRIGGER_BEFORE ){
74616    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
74617
74618    /* build the NEW.* reference row.  Note that if there is an INTEGER
74619    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
74620    ** translated into a unique ID for the row.  But on a BEFORE trigger,
74621    ** we do not know what the unique ID will be (because the insert has
74622    ** not happened yet) so we substitute a rowid of -1
74623    */
74624    if( keyColumn<0 ){
74625      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
74626    }else{
74627      int j1;
74628      if( useTempTable ){
74629        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
74630      }else{
74631        assert( pSelect==0 );  /* Otherwise useTempTable is true */
74632        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
74633      }
74634      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
74635      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
74636      sqlite3VdbeJumpHere(v, j1);
74637      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
74638    }
74639
74640    /* Cannot have triggers on a virtual table. If it were possible,
74641    ** this block would have to account for hidden column.
74642    */
74643    assert( !IsVirtual(pTab) );
74644
74645    /* Create the new column data
74646    */
74647    for(i=0; i<pTab->nCol; i++){
74648      if( pColumn==0 ){
74649        j = i;
74650      }else{
74651        for(j=0; j<pColumn->nId; j++){
74652          if( pColumn->a[j].idx==i ) break;
74653        }
74654      }
74655      if( pColumn && j>=pColumn->nId ){
74656        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
74657      }else if( useTempTable ){
74658        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
74659      }else{
74660        assert( pSelect==0 ); /* Otherwise useTempTable is true */
74661        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
74662      }
74663    }
74664
74665    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
74666    ** do not attempt any conversions before assembling the record.
74667    ** If this is a real table, attempt conversions as required by the
74668    ** table column affinities.
74669    */
74670    if( !isView ){
74671      sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
74672      sqlite3TableAffinityStr(v, pTab);
74673    }
74674
74675    /* Fire BEFORE or INSTEAD OF triggers */
74676    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
74677        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
74678
74679    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
74680  }
74681
74682  /* Push the record number for the new entry onto the stack.  The
74683  ** record number is a randomly generate integer created by NewRowid
74684  ** except when the table has an INTEGER PRIMARY KEY column, in which
74685  ** case the record number is the same as that column.
74686  */
74687  if( !isView ){
74688    if( IsVirtual(pTab) ){
74689      /* The row that the VUpdate opcode will delete: none */
74690      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
74691    }
74692    if( keyColumn>=0 ){
74693      if( useTempTable ){
74694        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
74695      }else if( pSelect ){
74696        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
74697      }else{
74698        VdbeOp *pOp;
74699        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
74700        pOp = sqlite3VdbeGetOp(v, -1);
74701        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
74702          appendFlag = 1;
74703          pOp->opcode = OP_NewRowid;
74704          pOp->p1 = baseCur;
74705          pOp->p2 = regRowid;
74706          pOp->p3 = regAutoinc;
74707        }
74708      }
74709      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
74710      ** to generate a unique primary key value.
74711      */
74712      if( !appendFlag ){
74713        int j1;
74714        if( !IsVirtual(pTab) ){
74715          j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
74716          sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
74717          sqlite3VdbeJumpHere(v, j1);
74718        }else{
74719          j1 = sqlite3VdbeCurrentAddr(v);
74720          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
74721        }
74722        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
74723      }
74724    }else if( IsVirtual(pTab) ){
74725      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
74726    }else{
74727      sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
74728      appendFlag = 1;
74729    }
74730    autoIncStep(pParse, regAutoinc, regRowid);
74731
74732    /* Push onto the stack, data for all columns of the new entry, beginning
74733    ** with the first column.
74734    */
74735    nHidden = 0;
74736    for(i=0; i<pTab->nCol; i++){
74737      int iRegStore = regRowid+1+i;
74738      if( i==pTab->iPKey ){
74739        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
74740        ** Whenever this column is read, the record number will be substituted
74741        ** in its place.  So will fill this column with a NULL to avoid
74742        ** taking up data space with information that will never be used. */
74743        sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
74744        continue;
74745      }
74746      if( pColumn==0 ){
74747        if( IsHiddenColumn(&pTab->aCol[i]) ){
74748          assert( IsVirtual(pTab) );
74749          j = -1;
74750          nHidden++;
74751        }else{
74752          j = i - nHidden;
74753        }
74754      }else{
74755        for(j=0; j<pColumn->nId; j++){
74756          if( pColumn->a[j].idx==i ) break;
74757        }
74758      }
74759      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
74760        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
74761      }else if( useTempTable ){
74762        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
74763      }else if( pSelect ){
74764        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
74765      }else{
74766        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
74767      }
74768    }
74769
74770    /* Generate code to check constraints and generate index keys and
74771    ** do the insertion.
74772    */
74773#ifndef SQLITE_OMIT_VIRTUALTABLE
74774    if( IsVirtual(pTab) ){
74775      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
74776      sqlite3VtabMakeWritable(pParse, pTab);
74777      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
74778      sqlite3MayAbort(pParse);
74779    }else
74780#endif
74781    {
74782      int isReplace;    /* Set to true if constraints may cause a replace */
74783      sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
74784          keyColumn>=0, 0, onError, endOfLoop, &isReplace
74785      );
74786      sqlite3FkCheck(pParse, pTab, 0, regIns);
74787      sqlite3CompleteInsertion(
74788          pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
74789      );
74790    }
74791  }
74792
74793  /* Update the count of rows that are inserted
74794  */
74795  if( (db->flags & SQLITE_CountRows)!=0 ){
74796    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
74797  }
74798
74799  if( pTrigger ){
74800    /* Code AFTER triggers */
74801    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
74802        pTab, regData-2-pTab->nCol, onError, endOfLoop);
74803  }
74804
74805  /* The bottom of the main insertion loop, if the data source
74806  ** is a SELECT statement.
74807  */
74808  sqlite3VdbeResolveLabel(v, endOfLoop);
74809  if( useTempTable ){
74810    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
74811    sqlite3VdbeJumpHere(v, addrInsTop);
74812    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
74813  }else if( pSelect ){
74814    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
74815    sqlite3VdbeJumpHere(v, addrInsTop);
74816  }
74817
74818  if( !IsVirtual(pTab) && !isView ){
74819    /* Close all tables opened */
74820    sqlite3VdbeAddOp1(v, OP_Close, baseCur);
74821    for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
74822      sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
74823    }
74824  }
74825
74826insert_end:
74827  /* Update the sqlite_sequence table by storing the content of the
74828  ** maximum rowid counter values recorded while inserting into
74829  ** autoincrement tables.
74830  */
74831  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
74832    sqlite3AutoincrementEnd(pParse);
74833  }
74834
74835  /*
74836  ** Return the number of rows inserted. If this routine is
74837  ** generating code because of a call to sqlite3NestedParse(), do not
74838  ** invoke the callback function.
74839  */
74840  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
74841    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
74842    sqlite3VdbeSetNumCols(v, 1);
74843    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
74844  }
74845
74846insert_cleanup:
74847  sqlite3SrcListDelete(db, pTabList);
74848  sqlite3ExprListDelete(db, pList);
74849  sqlite3SelectDelete(db, pSelect);
74850  sqlite3IdListDelete(db, pColumn);
74851  sqlite3DbFree(db, aRegIdx);
74852}
74853
74854/* Make sure "isView" and other macros defined above are undefined. Otherwise
74855** thely may interfere with compilation of other functions in this file
74856** (or in another file, if this file becomes part of the amalgamation).  */
74857#ifdef isView
74858 #undef isView
74859#endif
74860#ifdef pTrigger
74861 #undef pTrigger
74862#endif
74863#ifdef tmask
74864 #undef tmask
74865#endif
74866
74867
74868/*
74869** Generate code to do constraint checks prior to an INSERT or an UPDATE.
74870**
74871** The input is a range of consecutive registers as follows:
74872**
74873**    1.  The rowid of the row after the update.
74874**
74875**    2.  The data in the first column of the entry after the update.
74876**
74877**    i.  Data from middle columns...
74878**
74879**    N.  The data in the last column of the entry after the update.
74880**
74881** The regRowid parameter is the index of the register containing (1).
74882**
74883** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
74884** the address of a register containing the rowid before the update takes
74885** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
74886** is false, indicating an INSERT statement, then a non-zero rowidChng
74887** indicates that the rowid was explicitly specified as part of the
74888** INSERT statement. If rowidChng is false, it means that  the rowid is
74889** computed automatically in an insert or that the rowid value is not
74890** modified by an update.
74891**
74892** The code generated by this routine store new index entries into
74893** registers identified by aRegIdx[].  No index entry is created for
74894** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
74895** the same as the order of indices on the linked list of indices
74896** attached to the table.
74897**
74898** This routine also generates code to check constraints.  NOT NULL,
74899** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
74900** then the appropriate action is performed.  There are five possible
74901** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
74902**
74903**  Constraint type  Action       What Happens
74904**  ---------------  ----------   ----------------------------------------
74905**  any              ROLLBACK     The current transaction is rolled back and
74906**                                sqlite3_exec() returns immediately with a
74907**                                return code of SQLITE_CONSTRAINT.
74908**
74909**  any              ABORT        Back out changes from the current command
74910**                                only (do not do a complete rollback) then
74911**                                cause sqlite3_exec() to return immediately
74912**                                with SQLITE_CONSTRAINT.
74913**
74914**  any              FAIL         Sqlite_exec() returns immediately with a
74915**                                return code of SQLITE_CONSTRAINT.  The
74916**                                transaction is not rolled back and any
74917**                                prior changes are retained.
74918**
74919**  any              IGNORE       The record number and data is popped from
74920**                                the stack and there is an immediate jump
74921**                                to label ignoreDest.
74922**
74923**  NOT NULL         REPLACE      The NULL value is replace by the default
74924**                                value for that column.  If the default value
74925**                                is NULL, the action is the same as ABORT.
74926**
74927**  UNIQUE           REPLACE      The other row that conflicts with the row
74928**                                being inserted is removed.
74929**
74930**  CHECK            REPLACE      Illegal.  The results in an exception.
74931**
74932** Which action to take is determined by the overrideError parameter.
74933** Or if overrideError==OE_Default, then the pParse->onError parameter
74934** is used.  Or if pParse->onError==OE_Default then the onError value
74935** for the constraint is used.
74936**
74937** The calling routine must open a read/write cursor for pTab with
74938** cursor number "baseCur".  All indices of pTab must also have open
74939** read/write cursors with cursor number baseCur+i for the i-th cursor.
74940** Except, if there is no possibility of a REPLACE action then
74941** cursors do not need to be open for indices where aRegIdx[i]==0.
74942*/
74943SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
74944  Parse *pParse,      /* The parser context */
74945  Table *pTab,        /* the table into which we are inserting */
74946  int baseCur,        /* Index of a read/write cursor pointing at pTab */
74947  int regRowid,       /* Index of the range of input registers */
74948  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
74949  int rowidChng,      /* True if the rowid might collide with existing entry */
74950  int isUpdate,       /* True for UPDATE, False for INSERT */
74951  int overrideError,  /* Override onError to this if not OE_Default */
74952  int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
74953  int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
74954){
74955  int i;              /* loop counter */
74956  Vdbe *v;            /* VDBE under constrution */
74957  int nCol;           /* Number of columns */
74958  int onError;        /* Conflict resolution strategy */
74959  int j1;             /* Addresss of jump instruction */
74960  int j2 = 0, j3;     /* Addresses of jump instructions */
74961  int regData;        /* Register containing first data column */
74962  int iCur;           /* Table cursor number */
74963  Index *pIdx;         /* Pointer to one of the indices */
74964  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
74965  int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
74966
74967  v = sqlite3GetVdbe(pParse);
74968  assert( v!=0 );
74969  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
74970  nCol = pTab->nCol;
74971  regData = regRowid + 1;
74972
74973  /* Test all NOT NULL constraints.
74974  */
74975  for(i=0; i<nCol; i++){
74976    if( i==pTab->iPKey ){
74977      continue;
74978    }
74979    onError = pTab->aCol[i].notNull;
74980    if( onError==OE_None ) continue;
74981    if( overrideError!=OE_Default ){
74982      onError = overrideError;
74983    }else if( onError==OE_Default ){
74984      onError = OE_Abort;
74985    }
74986    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
74987      onError = OE_Abort;
74988    }
74989    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
74990        || onError==OE_Ignore || onError==OE_Replace );
74991    switch( onError ){
74992      case OE_Abort:
74993        sqlite3MayAbort(pParse);
74994      case OE_Rollback:
74995      case OE_Fail: {
74996        char *zMsg;
74997        j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
74998                                  SQLITE_CONSTRAINT, onError, regData+i);
74999        zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
75000                              pTab->zName, pTab->aCol[i].zName);
75001        sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
75002        break;
75003      }
75004      case OE_Ignore: {
75005        sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
75006        break;
75007      }
75008      default: {
75009        assert( onError==OE_Replace );
75010        j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
75011        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
75012        sqlite3VdbeJumpHere(v, j1);
75013        break;
75014      }
75015    }
75016  }
75017
75018  /* Test all CHECK constraints
75019  */
75020#ifndef SQLITE_OMIT_CHECK
75021  if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
75022    int allOk = sqlite3VdbeMakeLabel(v);
75023    pParse->ckBase = regData;
75024    sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
75025    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
75026    if( onError==OE_Ignore ){
75027      sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
75028    }else{
75029      sqlite3HaltConstraint(pParse, onError, 0, 0);
75030    }
75031    sqlite3VdbeResolveLabel(v, allOk);
75032  }
75033#endif /* !defined(SQLITE_OMIT_CHECK) */
75034
75035  /* If we have an INTEGER PRIMARY KEY, make sure the primary key
75036  ** of the new record does not previously exist.  Except, if this
75037  ** is an UPDATE and the primary key is not changing, that is OK.
75038  */
75039  if( rowidChng ){
75040    onError = pTab->keyConf;
75041    if( overrideError!=OE_Default ){
75042      onError = overrideError;
75043    }else if( onError==OE_Default ){
75044      onError = OE_Abort;
75045    }
75046
75047    if( isUpdate ){
75048      j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
75049    }
75050    j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
75051    switch( onError ){
75052      default: {
75053        onError = OE_Abort;
75054        /* Fall thru into the next case */
75055      }
75056      case OE_Rollback:
75057      case OE_Abort:
75058      case OE_Fail: {
75059        sqlite3HaltConstraint(
75060          pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
75061        break;
75062      }
75063      case OE_Replace: {
75064        /* If there are DELETE triggers on this table and the
75065        ** recursive-triggers flag is set, call GenerateRowDelete() to
75066        ** remove the conflicting row from the the table. This will fire
75067        ** the triggers and remove both the table and index b-tree entries.
75068        **
75069        ** Otherwise, if there are no triggers or the recursive-triggers
75070        ** flag is not set, call GenerateRowIndexDelete(). This removes
75071        ** the index b-tree entries only. The table b-tree entry will be
75072        ** replaced by the new entry when it is inserted.  */
75073        Trigger *pTrigger = 0;
75074        if( pParse->db->flags&SQLITE_RecTriggers ){
75075          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
75076        }
75077        sqlite3MultiWrite(pParse);
75078        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
75079          sqlite3GenerateRowDelete(
75080              pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
75081          );
75082        }else{
75083          sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
75084        }
75085        seenReplace = 1;
75086        break;
75087      }
75088      case OE_Ignore: {
75089        assert( seenReplace==0 );
75090        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
75091        break;
75092      }
75093    }
75094    sqlite3VdbeJumpHere(v, j3);
75095    if( isUpdate ){
75096      sqlite3VdbeJumpHere(v, j2);
75097    }
75098  }
75099
75100  /* Test all UNIQUE constraints by creating entries for each UNIQUE
75101  ** index and making sure that duplicate entries do not already exist.
75102  ** Add the new records to the indices as we go.
75103  */
75104  for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
75105    int regIdx;
75106    int regR;
75107
75108    if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
75109
75110    /* Create a key for accessing the index entry */
75111    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
75112    for(i=0; i<pIdx->nColumn; i++){
75113      int idx = pIdx->aiColumn[i];
75114      if( idx==pTab->iPKey ){
75115        sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
75116      }else{
75117        sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
75118      }
75119    }
75120    sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
75121    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
75122    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
75123    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
75124
75125    /* Find out what action to take in case there is an indexing conflict */
75126    onError = pIdx->onError;
75127    if( onError==OE_None ){
75128      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
75129      continue;  /* pIdx is not a UNIQUE index */
75130    }
75131    if( overrideError!=OE_Default ){
75132      onError = overrideError;
75133    }else if( onError==OE_Default ){
75134      onError = OE_Abort;
75135    }
75136    if( seenReplace ){
75137      if( onError==OE_Ignore ) onError = OE_Replace;
75138      else if( onError==OE_Fail ) onError = OE_Abort;
75139    }
75140
75141    /* Check to see if the new index entry will be unique */
75142    regR = sqlite3GetTempReg(pParse);
75143    sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
75144    j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
75145                           regR, SQLITE_INT_TO_PTR(regIdx),
75146                           P4_INT32);
75147    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
75148
75149    /* Generate code that executes if the new index entry is not unique */
75150    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
75151        || onError==OE_Ignore || onError==OE_Replace );
75152    switch( onError ){
75153      case OE_Rollback:
75154      case OE_Abort:
75155      case OE_Fail: {
75156        int j;
75157        StrAccum errMsg;
75158        const char *zSep;
75159        char *zErr;
75160
75161        sqlite3StrAccumInit(&errMsg, 0, 0, 200);
75162        errMsg.db = pParse->db;
75163        zSep = pIdx->nColumn>1 ? "columns " : "column ";
75164        for(j=0; j<pIdx->nColumn; j++){
75165          char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
75166          sqlite3StrAccumAppend(&errMsg, zSep, -1);
75167          zSep = ", ";
75168          sqlite3StrAccumAppend(&errMsg, zCol, -1);
75169        }
75170        sqlite3StrAccumAppend(&errMsg,
75171            pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
75172        zErr = sqlite3StrAccumFinish(&errMsg);
75173        sqlite3HaltConstraint(pParse, onError, zErr, 0);
75174        sqlite3DbFree(errMsg.db, zErr);
75175        break;
75176      }
75177      case OE_Ignore: {
75178        assert( seenReplace==0 );
75179        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
75180        break;
75181      }
75182      default: {
75183        Trigger *pTrigger = 0;
75184        assert( onError==OE_Replace );
75185        sqlite3MultiWrite(pParse);
75186        if( pParse->db->flags&SQLITE_RecTriggers ){
75187          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
75188        }
75189        sqlite3GenerateRowDelete(
75190            pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
75191        );
75192        seenReplace = 1;
75193        break;
75194      }
75195    }
75196    sqlite3VdbeJumpHere(v, j3);
75197    sqlite3ReleaseTempReg(pParse, regR);
75198  }
75199
75200  if( pbMayReplace ){
75201    *pbMayReplace = seenReplace;
75202  }
75203}
75204
75205/*
75206** This routine generates code to finish the INSERT or UPDATE operation
75207** that was started by a prior call to sqlite3GenerateConstraintChecks.
75208** A consecutive range of registers starting at regRowid contains the
75209** rowid and the content to be inserted.
75210**
75211** The arguments to this routine should be the same as the first six
75212** arguments to sqlite3GenerateConstraintChecks.
75213*/
75214SQLITE_PRIVATE void sqlite3CompleteInsertion(
75215  Parse *pParse,      /* The parser context */
75216  Table *pTab,        /* the table into which we are inserting */
75217  int baseCur,        /* Index of a read/write cursor pointing at pTab */
75218  int regRowid,       /* Range of content */
75219  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
75220  int isUpdate,       /* True for UPDATE, False for INSERT */
75221  int appendBias,     /* True if this is likely to be an append */
75222  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
75223){
75224  int i;
75225  Vdbe *v;
75226  int nIdx;
75227  Index *pIdx;
75228  u8 pik_flags;
75229  int regData;
75230  int regRec;
75231
75232  v = sqlite3GetVdbe(pParse);
75233  assert( v!=0 );
75234  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
75235  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
75236  for(i=nIdx-1; i>=0; i--){
75237    if( aRegIdx[i]==0 ) continue;
75238    sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
75239    if( useSeekResult ){
75240      sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
75241    }
75242  }
75243  regData = regRowid + 1;
75244  regRec = sqlite3GetTempReg(pParse);
75245  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
75246  sqlite3TableAffinityStr(v, pTab);
75247  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
75248  if( pParse->nested ){
75249    pik_flags = 0;
75250  }else{
75251    pik_flags = OPFLAG_NCHANGE;
75252    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
75253  }
75254  if( appendBias ){
75255    pik_flags |= OPFLAG_APPEND;
75256  }
75257  if( useSeekResult ){
75258    pik_flags |= OPFLAG_USESEEKRESULT;
75259  }
75260  sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
75261  if( !pParse->nested ){
75262    sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
75263  }
75264  sqlite3VdbeChangeP5(v, pik_flags);
75265}
75266
75267/*
75268** Generate code that will open cursors for a table and for all
75269** indices of that table.  The "baseCur" parameter is the cursor number used
75270** for the table.  Indices are opened on subsequent cursors.
75271**
75272** Return the number of indices on the table.
75273*/
75274SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
75275  Parse *pParse,   /* Parsing context */
75276  Table *pTab,     /* Table to be opened */
75277  int baseCur,     /* Cursor number assigned to the table */
75278  int op           /* OP_OpenRead or OP_OpenWrite */
75279){
75280  int i;
75281  int iDb;
75282  Index *pIdx;
75283  Vdbe *v;
75284
75285  if( IsVirtual(pTab) ) return 0;
75286  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75287  v = sqlite3GetVdbe(pParse);
75288  assert( v!=0 );
75289  sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
75290  for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
75291    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
75292    assert( pIdx->pSchema==pTab->pSchema );
75293    sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
75294                      (char*)pKey, P4_KEYINFO_HANDOFF);
75295    VdbeComment((v, "%s", pIdx->zName));
75296  }
75297  if( pParse->nTab<baseCur+i ){
75298    pParse->nTab = baseCur+i;
75299  }
75300  return i-1;
75301}
75302
75303
75304#ifdef SQLITE_TEST
75305/*
75306** The following global variable is incremented whenever the
75307** transfer optimization is used.  This is used for testing
75308** purposes only - to make sure the transfer optimization really
75309** is happening when it is suppose to.
75310*/
75311SQLITE_API int sqlite3_xferopt_count;
75312#endif /* SQLITE_TEST */
75313
75314
75315#ifndef SQLITE_OMIT_XFER_OPT
75316/*
75317** Check to collation names to see if they are compatible.
75318*/
75319static int xferCompatibleCollation(const char *z1, const char *z2){
75320  if( z1==0 ){
75321    return z2==0;
75322  }
75323  if( z2==0 ){
75324    return 0;
75325  }
75326  return sqlite3StrICmp(z1, z2)==0;
75327}
75328
75329
75330/*
75331** Check to see if index pSrc is compatible as a source of data
75332** for index pDest in an insert transfer optimization.  The rules
75333** for a compatible index:
75334**
75335**    *   The index is over the same set of columns
75336**    *   The same DESC and ASC markings occurs on all columns
75337**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
75338**    *   The same collating sequence on each column
75339*/
75340static int xferCompatibleIndex(Index *pDest, Index *pSrc){
75341  int i;
75342  assert( pDest && pSrc );
75343  assert( pDest->pTable!=pSrc->pTable );
75344  if( pDest->nColumn!=pSrc->nColumn ){
75345    return 0;   /* Different number of columns */
75346  }
75347  if( pDest->onError!=pSrc->onError ){
75348    return 0;   /* Different conflict resolution strategies */
75349  }
75350  for(i=0; i<pSrc->nColumn; i++){
75351    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
75352      return 0;   /* Different columns indexed */
75353    }
75354    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
75355      return 0;   /* Different sort orders */
75356    }
75357    if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
75358      return 0;   /* Different collating sequences */
75359    }
75360  }
75361
75362  /* If no test above fails then the indices must be compatible */
75363  return 1;
75364}
75365
75366/*
75367** Attempt the transfer optimization on INSERTs of the form
75368**
75369**     INSERT INTO tab1 SELECT * FROM tab2;
75370**
75371** This optimization is only attempted if
75372**
75373**    (1)  tab1 and tab2 have identical schemas including all the
75374**         same indices and constraints
75375**
75376**    (2)  tab1 and tab2 are different tables
75377**
75378**    (3)  There must be no triggers on tab1
75379**
75380**    (4)  The result set of the SELECT statement is "*"
75381**
75382**    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
75383**         or LIMIT clause.
75384**
75385**    (6)  The SELECT statement is a simple (not a compound) select that
75386**         contains only tab2 in its FROM clause
75387**
75388** This method for implementing the INSERT transfers raw records from
75389** tab2 over to tab1.  The columns are not decoded.  Raw records from
75390** the indices of tab2 are transfered to tab1 as well.  In so doing,
75391** the resulting tab1 has much less fragmentation.
75392**
75393** This routine returns TRUE if the optimization is attempted.  If any
75394** of the conditions above fail so that the optimization should not
75395** be attempted, then this routine returns FALSE.
75396*/
75397static int xferOptimization(
75398  Parse *pParse,        /* Parser context */
75399  Table *pDest,         /* The table we are inserting into */
75400  Select *pSelect,      /* A SELECT statement to use as the data source */
75401  int onError,          /* How to handle constraint errors */
75402  int iDbDest           /* The database of pDest */
75403){
75404  ExprList *pEList;                /* The result set of the SELECT */
75405  Table *pSrc;                     /* The table in the FROM clause of SELECT */
75406  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
75407  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
75408  int i;                           /* Loop counter */
75409  int iDbSrc;                      /* The database of pSrc */
75410  int iSrc, iDest;                 /* Cursors from source and destination */
75411  int addr1, addr2;                /* Loop addresses */
75412  int emptyDestTest;               /* Address of test for empty pDest */
75413  int emptySrcTest;                /* Address of test for empty pSrc */
75414  Vdbe *v;                         /* The VDBE we are building */
75415  KeyInfo *pKey;                   /* Key information for an index */
75416  int regAutoinc;                  /* Memory register used by AUTOINC */
75417  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
75418  int regData, regRowid;           /* Registers holding data and rowid */
75419
75420  if( pSelect==0 ){
75421    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
75422  }
75423  if( sqlite3TriggerList(pParse, pDest) ){
75424    return 0;   /* tab1 must not have triggers */
75425  }
75426#ifndef SQLITE_OMIT_VIRTUALTABLE
75427  if( pDest->tabFlags & TF_Virtual ){
75428    return 0;   /* tab1 must not be a virtual table */
75429  }
75430#endif
75431  if( onError==OE_Default ){
75432    onError = OE_Abort;
75433  }
75434  if( onError!=OE_Abort && onError!=OE_Rollback ){
75435    return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
75436  }
75437  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
75438  if( pSelect->pSrc->nSrc!=1 ){
75439    return 0;   /* FROM clause must have exactly one term */
75440  }
75441  if( pSelect->pSrc->a[0].pSelect ){
75442    return 0;   /* FROM clause cannot contain a subquery */
75443  }
75444  if( pSelect->pWhere ){
75445    return 0;   /* SELECT may not have a WHERE clause */
75446  }
75447  if( pSelect->pOrderBy ){
75448    return 0;   /* SELECT may not have an ORDER BY clause */
75449  }
75450  /* Do not need to test for a HAVING clause.  If HAVING is present but
75451  ** there is no ORDER BY, we will get an error. */
75452  if( pSelect->pGroupBy ){
75453    return 0;   /* SELECT may not have a GROUP BY clause */
75454  }
75455  if( pSelect->pLimit ){
75456    return 0;   /* SELECT may not have a LIMIT clause */
75457  }
75458  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
75459  if( pSelect->pPrior ){
75460    return 0;   /* SELECT may not be a compound query */
75461  }
75462  if( pSelect->selFlags & SF_Distinct ){
75463    return 0;   /* SELECT may not be DISTINCT */
75464  }
75465  pEList = pSelect->pEList;
75466  assert( pEList!=0 );
75467  if( pEList->nExpr!=1 ){
75468    return 0;   /* The result set must have exactly one column */
75469  }
75470  assert( pEList->a[0].pExpr );
75471  if( pEList->a[0].pExpr->op!=TK_ALL ){
75472    return 0;   /* The result set must be the special operator "*" */
75473  }
75474
75475  /* At this point we have established that the statement is of the
75476  ** correct syntactic form to participate in this optimization.  Now
75477  ** we have to check the semantics.
75478  */
75479  pItem = pSelect->pSrc->a;
75480  pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
75481  if( pSrc==0 ){
75482    return 0;   /* FROM clause does not contain a real table */
75483  }
75484  if( pSrc==pDest ){
75485    return 0;   /* tab1 and tab2 may not be the same table */
75486  }
75487#ifndef SQLITE_OMIT_VIRTUALTABLE
75488  if( pSrc->tabFlags & TF_Virtual ){
75489    return 0;   /* tab2 must not be a virtual table */
75490  }
75491#endif
75492  if( pSrc->pSelect ){
75493    return 0;   /* tab2 may not be a view */
75494  }
75495  if( pDest->nCol!=pSrc->nCol ){
75496    return 0;   /* Number of columns must be the same in tab1 and tab2 */
75497  }
75498  if( pDest->iPKey!=pSrc->iPKey ){
75499    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
75500  }
75501  for(i=0; i<pDest->nCol; i++){
75502    if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
75503      return 0;    /* Affinity must be the same on all columns */
75504    }
75505    if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
75506      return 0;    /* Collating sequence must be the same on all columns */
75507    }
75508    if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
75509      return 0;    /* tab2 must be NOT NULL if tab1 is */
75510    }
75511  }
75512  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
75513    if( pDestIdx->onError!=OE_None ){
75514      destHasUniqueIdx = 1;
75515    }
75516    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
75517      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
75518    }
75519    if( pSrcIdx==0 ){
75520      return 0;    /* pDestIdx has no corresponding index in pSrc */
75521    }
75522  }
75523#ifndef SQLITE_OMIT_CHECK
75524  if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
75525    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
75526  }
75527#endif
75528
75529  /* If we get this far, it means either:
75530  **
75531  **    *   We can always do the transfer if the table contains an
75532  **        an integer primary key
75533  **
75534  **    *   We can conditionally do the transfer if the destination
75535  **        table is empty.
75536  */
75537#ifdef SQLITE_TEST
75538  sqlite3_xferopt_count++;
75539#endif
75540  iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
75541  v = sqlite3GetVdbe(pParse);
75542  sqlite3CodeVerifySchema(pParse, iDbSrc);
75543  iSrc = pParse->nTab++;
75544  iDest = pParse->nTab++;
75545  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
75546  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
75547  if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
75548    /* If tables do not have an INTEGER PRIMARY KEY and there
75549    ** are indices to be copied and the destination is not empty,
75550    ** we have to disallow the transfer optimization because the
75551    ** the rowids might change which will mess up indexing.
75552    **
75553    ** Or if the destination has a UNIQUE index and is not empty,
75554    ** we also disallow the transfer optimization because we cannot
75555    ** insure that all entries in the union of DEST and SRC will be
75556    ** unique.
75557    */
75558    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
75559    emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
75560    sqlite3VdbeJumpHere(v, addr1);
75561  }else{
75562    emptyDestTest = 0;
75563  }
75564  sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
75565  emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
75566  regData = sqlite3GetTempReg(pParse);
75567  regRowid = sqlite3GetTempReg(pParse);
75568  if( pDest->iPKey>=0 ){
75569    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
75570    addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
75571    sqlite3HaltConstraint(
75572        pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
75573    sqlite3VdbeJumpHere(v, addr2);
75574    autoIncStep(pParse, regAutoinc, regRowid);
75575  }else if( pDest->pIndex==0 ){
75576    addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
75577  }else{
75578    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
75579    assert( (pDest->tabFlags & TF_Autoincrement)==0 );
75580  }
75581  sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
75582  sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
75583  sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
75584  sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
75585  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
75586  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
75587    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
75588      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
75589    }
75590    assert( pSrcIdx );
75591    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
75592    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
75593    pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
75594    sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
75595                      (char*)pKey, P4_KEYINFO_HANDOFF);
75596    VdbeComment((v, "%s", pSrcIdx->zName));
75597    pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
75598    sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
75599                      (char*)pKey, P4_KEYINFO_HANDOFF);
75600    VdbeComment((v, "%s", pDestIdx->zName));
75601    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
75602    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
75603    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
75604    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
75605    sqlite3VdbeJumpHere(v, addr1);
75606  }
75607  sqlite3VdbeJumpHere(v, emptySrcTest);
75608  sqlite3ReleaseTempReg(pParse, regRowid);
75609  sqlite3ReleaseTempReg(pParse, regData);
75610  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
75611  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
75612  if( emptyDestTest ){
75613    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
75614    sqlite3VdbeJumpHere(v, emptyDestTest);
75615    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
75616    return 0;
75617  }else{
75618    return 1;
75619  }
75620}
75621#endif /* SQLITE_OMIT_XFER_OPT */
75622
75623/************** End of insert.c **********************************************/
75624/************** Begin file legacy.c ******************************************/
75625/*
75626** 2001 September 15
75627**
75628** The author disclaims copyright to this source code.  In place of
75629** a legal notice, here is a blessing:
75630**
75631**    May you do good and not evil.
75632**    May you find forgiveness for yourself and forgive others.
75633**    May you share freely, never taking more than you give.
75634**
75635*************************************************************************
75636** Main file for the SQLite library.  The routines in this file
75637** implement the programmer interface to the library.  Routines in
75638** other files are for internal use by SQLite and should not be
75639** accessed by users of the library.
75640*/
75641
75642
75643/*
75644** Execute SQL code.  Return one of the SQLITE_ success/failure
75645** codes.  Also write an error message into memory obtained from
75646** malloc() and make *pzErrMsg point to that message.
75647**
75648** If the SQL is a query, then for each row in the query result
75649** the xCallback() function is called.  pArg becomes the first
75650** argument to xCallback().  If xCallback=NULL then no callback
75651** is invoked, even for queries.
75652*/
75653SQLITE_API int sqlite3_exec(
75654  sqlite3 *db,                /* The database on which the SQL executes */
75655  const char *zSql,           /* The SQL to be executed */
75656  sqlite3_callback xCallback, /* Invoke this callback routine */
75657  void *pArg,                 /* First argument to xCallback() */
75658  char **pzErrMsg             /* Write error messages here */
75659){
75660  int rc = SQLITE_OK;         /* Return code */
75661  const char *zLeftover;      /* Tail of unprocessed SQL */
75662  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
75663  char **azCols = 0;          /* Names of result columns */
75664  int nRetry = 0;             /* Number of retry attempts */
75665  int callbackIsInit;         /* True if callback data is initialized */
75666
75667  if( zSql==0 ) zSql = "";
75668
75669  sqlite3_mutex_enter(db->mutex);
75670  sqlite3Error(db, SQLITE_OK, 0);
75671  while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
75672    int nCol;
75673    char **azVals = 0;
75674
75675    pStmt = 0;
75676    rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
75677    assert( rc==SQLITE_OK || pStmt==0 );
75678    if( rc!=SQLITE_OK ){
75679      continue;
75680    }
75681    if( !pStmt ){
75682      /* this happens for a comment or white-space */
75683      zSql = zLeftover;
75684      continue;
75685    }
75686
75687    callbackIsInit = 0;
75688    nCol = sqlite3_column_count(pStmt);
75689
75690    while( 1 ){
75691      int i;
75692      rc = sqlite3_step(pStmt);
75693
75694      /* Invoke the callback function if required */
75695      if( xCallback && (SQLITE_ROW==rc ||
75696          (SQLITE_DONE==rc && !callbackIsInit
75697                           && db->flags&SQLITE_NullCallback)) ){
75698        if( !callbackIsInit ){
75699          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
75700          if( azCols==0 ){
75701            goto exec_out;
75702          }
75703          for(i=0; i<nCol; i++){
75704            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
75705            /* sqlite3VdbeSetColName() installs column names as UTF8
75706            ** strings so there is no way for sqlite3_column_name() to fail. */
75707            assert( azCols[i]!=0 );
75708          }
75709          callbackIsInit = 1;
75710        }
75711        if( rc==SQLITE_ROW ){
75712          azVals = &azCols[nCol];
75713          for(i=0; i<nCol; i++){
75714            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
75715            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
75716              db->mallocFailed = 1;
75717              goto exec_out;
75718            }
75719          }
75720        }
75721        if( xCallback(pArg, nCol, azVals, azCols) ){
75722          rc = SQLITE_ABORT;
75723          sqlite3VdbeFinalize((Vdbe *)pStmt);
75724          pStmt = 0;
75725          sqlite3Error(db, SQLITE_ABORT, 0);
75726          goto exec_out;
75727        }
75728      }
75729
75730      if( rc!=SQLITE_ROW ){
75731        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
75732        pStmt = 0;
75733        if( rc!=SQLITE_SCHEMA ){
75734          nRetry = 0;
75735          zSql = zLeftover;
75736          while( sqlite3Isspace(zSql[0]) ) zSql++;
75737        }
75738        break;
75739      }
75740    }
75741
75742    sqlite3DbFree(db, azCols);
75743    azCols = 0;
75744  }
75745
75746exec_out:
75747  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
75748  sqlite3DbFree(db, azCols);
75749
75750  rc = sqlite3ApiExit(db, rc);
75751  if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
75752    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
75753    *pzErrMsg = sqlite3Malloc(nErrMsg);
75754    if( *pzErrMsg ){
75755      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
75756    }else{
75757      rc = SQLITE_NOMEM;
75758      sqlite3Error(db, SQLITE_NOMEM, 0);
75759    }
75760  }else if( pzErrMsg ){
75761    *pzErrMsg = 0;
75762  }
75763
75764  assert( (rc&db->errMask)==rc );
75765  sqlite3_mutex_leave(db->mutex);
75766  return rc;
75767}
75768
75769/************** End of legacy.c **********************************************/
75770/************** Begin file loadext.c *****************************************/
75771/*
75772** 2006 June 7
75773**
75774** The author disclaims copyright to this source code.  In place of
75775** a legal notice, here is a blessing:
75776**
75777**    May you do good and not evil.
75778**    May you find forgiveness for yourself and forgive others.
75779**    May you share freely, never taking more than you give.
75780**
75781*************************************************************************
75782** This file contains code used to dynamically load extensions into
75783** the SQLite library.
75784*/
75785
75786#ifndef SQLITE_CORE
75787  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
75788#endif
75789/************** Include sqlite3ext.h in the middle of loadext.c **************/
75790/************** Begin file sqlite3ext.h **************************************/
75791/*
75792** 2006 June 7
75793**
75794** The author disclaims copyright to this source code.  In place of
75795** a legal notice, here is a blessing:
75796**
75797**    May you do good and not evil.
75798**    May you find forgiveness for yourself and forgive others.
75799**    May you share freely, never taking more than you give.
75800**
75801*************************************************************************
75802** This header file defines the SQLite interface for use by
75803** shared libraries that want to be imported as extensions into
75804** an SQLite instance.  Shared libraries that intend to be loaded
75805** as extensions by SQLite should #include this file instead of
75806** sqlite3.h.
75807*/
75808#ifndef _SQLITE3EXT_H_
75809#define _SQLITE3EXT_H_
75810
75811typedef struct sqlite3_api_routines sqlite3_api_routines;
75812
75813/*
75814** The following structure holds pointers to all of the SQLite API
75815** routines.
75816**
75817** WARNING:  In order to maintain backwards compatibility, add new
75818** interfaces to the end of this structure only.  If you insert new
75819** interfaces in the middle of this structure, then older different
75820** versions of SQLite will not be able to load each others' shared
75821** libraries!
75822*/
75823struct sqlite3_api_routines {
75824  void * (*aggregate_context)(sqlite3_context*,int nBytes);
75825  int  (*aggregate_count)(sqlite3_context*);
75826  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
75827  int  (*bind_double)(sqlite3_stmt*,int,double);
75828  int  (*bind_int)(sqlite3_stmt*,int,int);
75829  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
75830  int  (*bind_null)(sqlite3_stmt*,int);
75831  int  (*bind_parameter_count)(sqlite3_stmt*);
75832  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
75833  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
75834  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
75835  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
75836  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
75837  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
75838  int  (*busy_timeout)(sqlite3*,int ms);
75839  int  (*changes)(sqlite3*);
75840  int  (*close)(sqlite3*);
75841  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
75842  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
75843  const void * (*column_blob)(sqlite3_stmt*,int iCol);
75844  int  (*column_bytes)(sqlite3_stmt*,int iCol);
75845  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
75846  int  (*column_count)(sqlite3_stmt*pStmt);
75847  const char * (*column_database_name)(sqlite3_stmt*,int);
75848  const void * (*column_database_name16)(sqlite3_stmt*,int);
75849  const char * (*column_decltype)(sqlite3_stmt*,int i);
75850  const void * (*column_decltype16)(sqlite3_stmt*,int);
75851  double  (*column_double)(sqlite3_stmt*,int iCol);
75852  int  (*column_int)(sqlite3_stmt*,int iCol);
75853  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
75854  const char * (*column_name)(sqlite3_stmt*,int);
75855  const void * (*column_name16)(sqlite3_stmt*,int);
75856  const char * (*column_origin_name)(sqlite3_stmt*,int);
75857  const void * (*column_origin_name16)(sqlite3_stmt*,int);
75858  const char * (*column_table_name)(sqlite3_stmt*,int);
75859  const void * (*column_table_name16)(sqlite3_stmt*,int);
75860  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
75861  const void * (*column_text16)(sqlite3_stmt*,int iCol);
75862  int  (*column_type)(sqlite3_stmt*,int iCol);
75863  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
75864  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
75865  int  (*complete)(const char*sql);
75866  int  (*complete16)(const void*sql);
75867  int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
75868  int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
75869  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*));
75870  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*));
75871  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
75872  int  (*data_count)(sqlite3_stmt*pStmt);
75873  sqlite3 * (*db_handle)(sqlite3_stmt*);
75874  int (*declare_vtab)(sqlite3*,const char*);
75875  int  (*enable_shared_cache)(int);
75876  int  (*errcode)(sqlite3*db);
75877  const char * (*errmsg)(sqlite3*);
75878  const void * (*errmsg16)(sqlite3*);
75879  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
75880  int  (*expired)(sqlite3_stmt*);
75881  int  (*finalize)(sqlite3_stmt*pStmt);
75882  void  (*free)(void*);
75883  void  (*free_table)(char**result);
75884  int  (*get_autocommit)(sqlite3*);
75885  void * (*get_auxdata)(sqlite3_context*,int);
75886  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
75887  int  (*global_recover)(void);
75888  void  (*interruptx)(sqlite3*);
75889  sqlite_int64  (*last_insert_rowid)(sqlite3*);
75890  const char * (*libversion)(void);
75891  int  (*libversion_number)(void);
75892  void *(*malloc)(int);
75893  char * (*mprintf)(const char*,...);
75894  int  (*open)(const char*,sqlite3**);
75895  int  (*open16)(const void*,sqlite3**);
75896  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
75897  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
75898  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
75899  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
75900  void *(*realloc)(void*,int);
75901  int  (*reset)(sqlite3_stmt*pStmt);
75902  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
75903  void  (*result_double)(sqlite3_context*,double);
75904  void  (*result_error)(sqlite3_context*,const char*,int);
75905  void  (*result_error16)(sqlite3_context*,const void*,int);
75906  void  (*result_int)(sqlite3_context*,int);
75907  void  (*result_int64)(sqlite3_context*,sqlite_int64);
75908  void  (*result_null)(sqlite3_context*);
75909  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
75910  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
75911  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
75912  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
75913  void  (*result_value)(sqlite3_context*,sqlite3_value*);
75914  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
75915  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
75916  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
75917  char * (*snprintf)(int,char*,const char*,...);
75918  int  (*step)(sqlite3_stmt*);
75919  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
75920  void  (*thread_cleanup)(void);
75921  int  (*total_changes)(sqlite3*);
75922  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
75923  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
75924  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
75925  void * (*user_data)(sqlite3_context*);
75926  const void * (*value_blob)(sqlite3_value*);
75927  int  (*value_bytes)(sqlite3_value*);
75928  int  (*value_bytes16)(sqlite3_value*);
75929  double  (*value_double)(sqlite3_value*);
75930  int  (*value_int)(sqlite3_value*);
75931  sqlite_int64  (*value_int64)(sqlite3_value*);
75932  int  (*value_numeric_type)(sqlite3_value*);
75933  const unsigned char * (*value_text)(sqlite3_value*);
75934  const void * (*value_text16)(sqlite3_value*);
75935  const void * (*value_text16be)(sqlite3_value*);
75936  const void * (*value_text16le)(sqlite3_value*);
75937  int  (*value_type)(sqlite3_value*);
75938  char *(*vmprintf)(const char*,va_list);
75939  /* Added ??? */
75940  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
75941  /* Added by 3.3.13 */
75942  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
75943  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
75944  int (*clear_bindings)(sqlite3_stmt*);
75945  /* Added by 3.4.1 */
75946  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
75947  /* Added by 3.5.0 */
75948  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
75949  int (*blob_bytes)(sqlite3_blob*);
75950  int (*blob_close)(sqlite3_blob*);
75951  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
75952  int (*blob_read)(sqlite3_blob*,void*,int,int);
75953  int (*blob_write)(sqlite3_blob*,const void*,int,int);
75954  int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
75955  int (*file_control)(sqlite3*,const char*,int,void*);
75956  sqlite3_int64 (*memory_highwater)(int);
75957  sqlite3_int64 (*memory_used)(void);
75958  sqlite3_mutex *(*mutex_alloc)(int);
75959  void (*mutex_enter)(sqlite3_mutex*);
75960  void (*mutex_free)(sqlite3_mutex*);
75961  void (*mutex_leave)(sqlite3_mutex*);
75962  int (*mutex_try)(sqlite3_mutex*);
75963  int (*open_v2)(const char*,sqlite3**,int,const char*);
75964  int (*release_memory)(int);
75965  void (*result_error_nomem)(sqlite3_context*);
75966  void (*result_error_toobig)(sqlite3_context*);
75967  int (*sleep)(int);
75968  void (*soft_heap_limit)(int);
75969  sqlite3_vfs *(*vfs_find)(const char*);
75970  int (*vfs_register)(sqlite3_vfs*,int);
75971  int (*vfs_unregister)(sqlite3_vfs*);
75972  int (*xthreadsafe)(void);
75973  void (*result_zeroblob)(sqlite3_context*,int);
75974  void (*result_error_code)(sqlite3_context*,int);
75975  int (*test_control)(int, ...);
75976  void (*randomness)(int,void*);
75977  sqlite3 *(*context_db_handle)(sqlite3_context*);
75978  int (*extended_result_codes)(sqlite3*,int);
75979  int (*limit)(sqlite3*,int,int);
75980  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
75981  const char *(*sql)(sqlite3_stmt*);
75982  int (*status)(int,int*,int*,int);
75983};
75984
75985/*
75986** The following macros redefine the API routines so that they are
75987** redirected throught the global sqlite3_api structure.
75988**
75989** This header file is also used by the loadext.c source file
75990** (part of the main SQLite library - not an extension) so that
75991** it can get access to the sqlite3_api_routines structure
75992** definition.  But the main library does not want to redefine
75993** the API.  So the redefinition macros are only valid if the
75994** SQLITE_CORE macros is undefined.
75995*/
75996#ifndef SQLITE_CORE
75997#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
75998#ifndef SQLITE_OMIT_DEPRECATED
75999#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
76000#endif
76001#define sqlite3_bind_blob              sqlite3_api->bind_blob
76002#define sqlite3_bind_double            sqlite3_api->bind_double
76003#define sqlite3_bind_int               sqlite3_api->bind_int
76004#define sqlite3_bind_int64             sqlite3_api->bind_int64
76005#define sqlite3_bind_null              sqlite3_api->bind_null
76006#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
76007#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
76008#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
76009#define sqlite3_bind_text              sqlite3_api->bind_text
76010#define sqlite3_bind_text16            sqlite3_api->bind_text16
76011#define sqlite3_bind_value             sqlite3_api->bind_value
76012#define sqlite3_busy_handler           sqlite3_api->busy_handler
76013#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
76014#define sqlite3_changes                sqlite3_api->changes
76015#define sqlite3_close                  sqlite3_api->close
76016#define sqlite3_collation_needed       sqlite3_api->collation_needed
76017#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
76018#define sqlite3_column_blob            sqlite3_api->column_blob
76019#define sqlite3_column_bytes           sqlite3_api->column_bytes
76020#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
76021#define sqlite3_column_count           sqlite3_api->column_count
76022#define sqlite3_column_database_name   sqlite3_api->column_database_name
76023#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
76024#define sqlite3_column_decltype        sqlite3_api->column_decltype
76025#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
76026#define sqlite3_column_double          sqlite3_api->column_double
76027#define sqlite3_column_int             sqlite3_api->column_int
76028#define sqlite3_column_int64           sqlite3_api->column_int64
76029#define sqlite3_column_name            sqlite3_api->column_name
76030#define sqlite3_column_name16          sqlite3_api->column_name16
76031#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
76032#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
76033#define sqlite3_column_table_name      sqlite3_api->column_table_name
76034#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
76035#define sqlite3_column_text            sqlite3_api->column_text
76036#define sqlite3_column_text16          sqlite3_api->column_text16
76037#define sqlite3_column_type            sqlite3_api->column_type
76038#define sqlite3_column_value           sqlite3_api->column_value
76039#define sqlite3_commit_hook            sqlite3_api->commit_hook
76040#define sqlite3_complete               sqlite3_api->complete
76041#define sqlite3_complete16             sqlite3_api->complete16
76042#define sqlite3_create_collation       sqlite3_api->create_collation
76043#define sqlite3_create_collation16     sqlite3_api->create_collation16
76044#define sqlite3_create_function        sqlite3_api->create_function
76045#define sqlite3_create_function16      sqlite3_api->create_function16
76046#define sqlite3_create_module          sqlite3_api->create_module
76047#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
76048#define sqlite3_data_count             sqlite3_api->data_count
76049#define sqlite3_db_handle              sqlite3_api->db_handle
76050#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
76051#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
76052#define sqlite3_errcode                sqlite3_api->errcode
76053#define sqlite3_errmsg                 sqlite3_api->errmsg
76054#define sqlite3_errmsg16               sqlite3_api->errmsg16
76055#define sqlite3_exec                   sqlite3_api->exec
76056#ifndef SQLITE_OMIT_DEPRECATED
76057#define sqlite3_expired                sqlite3_api->expired
76058#endif
76059#define sqlite3_finalize               sqlite3_api->finalize
76060#define sqlite3_free                   sqlite3_api->free
76061#define sqlite3_free_table             sqlite3_api->free_table
76062#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
76063#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
76064#define sqlite3_get_table              sqlite3_api->get_table
76065#ifndef SQLITE_OMIT_DEPRECATED
76066#define sqlite3_global_recover         sqlite3_api->global_recover
76067#endif
76068#define sqlite3_interrupt              sqlite3_api->interruptx
76069#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
76070#define sqlite3_libversion             sqlite3_api->libversion
76071#define sqlite3_libversion_number      sqlite3_api->libversion_number
76072#define sqlite3_malloc                 sqlite3_api->malloc
76073#define sqlite3_mprintf                sqlite3_api->mprintf
76074#define sqlite3_open                   sqlite3_api->open
76075#define sqlite3_open16                 sqlite3_api->open16
76076#define sqlite3_prepare                sqlite3_api->prepare
76077#define sqlite3_prepare16              sqlite3_api->prepare16
76078#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
76079#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
76080#define sqlite3_profile                sqlite3_api->profile
76081#define sqlite3_progress_handler       sqlite3_api->progress_handler
76082#define sqlite3_realloc                sqlite3_api->realloc
76083#define sqlite3_reset                  sqlite3_api->reset
76084#define sqlite3_result_blob            sqlite3_api->result_blob
76085#define sqlite3_result_double          sqlite3_api->result_double
76086#define sqlite3_result_error           sqlite3_api->result_error
76087#define sqlite3_result_error16         sqlite3_api->result_error16
76088#define sqlite3_result_int             sqlite3_api->result_int
76089#define sqlite3_result_int64           sqlite3_api->result_int64
76090#define sqlite3_result_null            sqlite3_api->result_null
76091#define sqlite3_result_text            sqlite3_api->result_text
76092#define sqlite3_result_text16          sqlite3_api->result_text16
76093#define sqlite3_result_text16be        sqlite3_api->result_text16be
76094#define sqlite3_result_text16le        sqlite3_api->result_text16le
76095#define sqlite3_result_value           sqlite3_api->result_value
76096#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
76097#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
76098#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
76099#define sqlite3_snprintf               sqlite3_api->snprintf
76100#define sqlite3_step                   sqlite3_api->step
76101#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
76102#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
76103#define sqlite3_total_changes          sqlite3_api->total_changes
76104#define sqlite3_trace                  sqlite3_api->trace
76105#ifndef SQLITE_OMIT_DEPRECATED
76106#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
76107#endif
76108#define sqlite3_update_hook            sqlite3_api->update_hook
76109#define sqlite3_user_data              sqlite3_api->user_data
76110#define sqlite3_value_blob             sqlite3_api->value_blob
76111#define sqlite3_value_bytes            sqlite3_api->value_bytes
76112#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
76113#define sqlite3_value_double           sqlite3_api->value_double
76114#define sqlite3_value_int              sqlite3_api->value_int
76115#define sqlite3_value_int64            sqlite3_api->value_int64
76116#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
76117#define sqlite3_value_text             sqlite3_api->value_text
76118#define sqlite3_value_text16           sqlite3_api->value_text16
76119#define sqlite3_value_text16be         sqlite3_api->value_text16be
76120#define sqlite3_value_text16le         sqlite3_api->value_text16le
76121#define sqlite3_value_type             sqlite3_api->value_type
76122#define sqlite3_vmprintf               sqlite3_api->vmprintf
76123#define sqlite3_overload_function      sqlite3_api->overload_function
76124#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
76125#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
76126#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
76127#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
76128#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
76129#define sqlite3_blob_close             sqlite3_api->blob_close
76130#define sqlite3_blob_open              sqlite3_api->blob_open
76131#define sqlite3_blob_read              sqlite3_api->blob_read
76132#define sqlite3_blob_write             sqlite3_api->blob_write
76133#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
76134#define sqlite3_file_control           sqlite3_api->file_control
76135#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
76136#define sqlite3_memory_used            sqlite3_api->memory_used
76137#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
76138#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
76139#define sqlite3_mutex_free             sqlite3_api->mutex_free
76140#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
76141#define sqlite3_mutex_try              sqlite3_api->mutex_try
76142#define sqlite3_open_v2                sqlite3_api->open_v2
76143#define sqlite3_release_memory         sqlite3_api->release_memory
76144#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
76145#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
76146#define sqlite3_sleep                  sqlite3_api->sleep
76147#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
76148#define sqlite3_vfs_find               sqlite3_api->vfs_find
76149#define sqlite3_vfs_register           sqlite3_api->vfs_register
76150#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
76151#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
76152#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
76153#define sqlite3_result_error_code      sqlite3_api->result_error_code
76154#define sqlite3_test_control           sqlite3_api->test_control
76155#define sqlite3_randomness             sqlite3_api->randomness
76156#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
76157#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
76158#define sqlite3_limit                  sqlite3_api->limit
76159#define sqlite3_next_stmt              sqlite3_api->next_stmt
76160#define sqlite3_sql                    sqlite3_api->sql
76161#define sqlite3_status                 sqlite3_api->status
76162#endif /* SQLITE_CORE */
76163
76164#define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
76165#define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
76166
76167#endif /* _SQLITE3EXT_H_ */
76168
76169/************** End of sqlite3ext.h ******************************************/
76170/************** Continuing where we left off in loadext.c ********************/
76171
76172#ifndef SQLITE_OMIT_LOAD_EXTENSION
76173
76174/*
76175** Some API routines are omitted when various features are
76176** excluded from a build of SQLite.  Substitute a NULL pointer
76177** for any missing APIs.
76178*/
76179#ifndef SQLITE_ENABLE_COLUMN_METADATA
76180# define sqlite3_column_database_name   0
76181# define sqlite3_column_database_name16 0
76182# define sqlite3_column_table_name      0
76183# define sqlite3_column_table_name16    0
76184# define sqlite3_column_origin_name     0
76185# define sqlite3_column_origin_name16   0
76186# define sqlite3_table_column_metadata  0
76187#endif
76188
76189#ifdef SQLITE_OMIT_AUTHORIZATION
76190# define sqlite3_set_authorizer         0
76191#endif
76192
76193#ifdef SQLITE_OMIT_UTF16
76194# define sqlite3_bind_text16            0
76195# define sqlite3_collation_needed16     0
76196# define sqlite3_column_decltype16      0
76197# define sqlite3_column_name16          0
76198# define sqlite3_column_text16          0
76199# define sqlite3_complete16             0
76200# define sqlite3_create_collation16     0
76201# define sqlite3_create_function16      0
76202# define sqlite3_errmsg16               0
76203# define sqlite3_open16                 0
76204# define sqlite3_prepare16              0
76205# define sqlite3_prepare16_v2           0
76206# define sqlite3_result_error16         0
76207# define sqlite3_result_text16          0
76208# define sqlite3_result_text16be        0
76209# define sqlite3_result_text16le        0
76210# define sqlite3_value_text16           0
76211# define sqlite3_value_text16be         0
76212# define sqlite3_value_text16le         0
76213# define sqlite3_column_database_name16 0
76214# define sqlite3_column_table_name16    0
76215# define sqlite3_column_origin_name16   0
76216#endif
76217
76218#ifdef SQLITE_OMIT_COMPLETE
76219# define sqlite3_complete 0
76220# define sqlite3_complete16 0
76221#endif
76222
76223#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
76224# define sqlite3_progress_handler 0
76225#endif
76226
76227#ifdef SQLITE_OMIT_VIRTUALTABLE
76228# define sqlite3_create_module 0
76229# define sqlite3_create_module_v2 0
76230# define sqlite3_declare_vtab 0
76231#endif
76232
76233#ifdef SQLITE_OMIT_SHARED_CACHE
76234# define sqlite3_enable_shared_cache 0
76235#endif
76236
76237#ifdef SQLITE_OMIT_TRACE
76238# define sqlite3_profile       0
76239# define sqlite3_trace         0
76240#endif
76241
76242#ifdef SQLITE_OMIT_GET_TABLE
76243# define sqlite3_free_table    0
76244# define sqlite3_get_table     0
76245#endif
76246
76247#ifdef SQLITE_OMIT_INCRBLOB
76248#define sqlite3_bind_zeroblob  0
76249#define sqlite3_blob_bytes     0
76250#define sqlite3_blob_close     0
76251#define sqlite3_blob_open      0
76252#define sqlite3_blob_read      0
76253#define sqlite3_blob_write     0
76254#endif
76255
76256/*
76257** The following structure contains pointers to all SQLite API routines.
76258** A pointer to this structure is passed into extensions when they are
76259** loaded so that the extension can make calls back into the SQLite
76260** library.
76261**
76262** When adding new APIs, add them to the bottom of this structure
76263** in order to preserve backwards compatibility.
76264**
76265** Extensions that use newer APIs should first call the
76266** sqlite3_libversion_number() to make sure that the API they
76267** intend to use is supported by the library.  Extensions should
76268** also check to make sure that the pointer to the function is
76269** not NULL before calling it.
76270*/
76271static const sqlite3_api_routines sqlite3Apis = {
76272  sqlite3_aggregate_context,
76273#ifndef SQLITE_OMIT_DEPRECATED
76274  sqlite3_aggregate_count,
76275#else
76276  0,
76277#endif
76278  sqlite3_bind_blob,
76279  sqlite3_bind_double,
76280  sqlite3_bind_int,
76281  sqlite3_bind_int64,
76282  sqlite3_bind_null,
76283  sqlite3_bind_parameter_count,
76284  sqlite3_bind_parameter_index,
76285  sqlite3_bind_parameter_name,
76286  sqlite3_bind_text,
76287  sqlite3_bind_text16,
76288  sqlite3_bind_value,
76289  sqlite3_busy_handler,
76290  sqlite3_busy_timeout,
76291  sqlite3_changes,
76292  sqlite3_close,
76293  sqlite3_collation_needed,
76294  sqlite3_collation_needed16,
76295  sqlite3_column_blob,
76296  sqlite3_column_bytes,
76297  sqlite3_column_bytes16,
76298  sqlite3_column_count,
76299  sqlite3_column_database_name,
76300  sqlite3_column_database_name16,
76301  sqlite3_column_decltype,
76302  sqlite3_column_decltype16,
76303  sqlite3_column_double,
76304  sqlite3_column_int,
76305  sqlite3_column_int64,
76306  sqlite3_column_name,
76307  sqlite3_column_name16,
76308  sqlite3_column_origin_name,
76309  sqlite3_column_origin_name16,
76310  sqlite3_column_table_name,
76311  sqlite3_column_table_name16,
76312  sqlite3_column_text,
76313  sqlite3_column_text16,
76314  sqlite3_column_type,
76315  sqlite3_column_value,
76316  sqlite3_commit_hook,
76317  sqlite3_complete,
76318  sqlite3_complete16,
76319  sqlite3_create_collation,
76320  sqlite3_create_collation16,
76321  sqlite3_create_function,
76322  sqlite3_create_function16,
76323  sqlite3_create_module,
76324  sqlite3_data_count,
76325  sqlite3_db_handle,
76326  sqlite3_declare_vtab,
76327  sqlite3_enable_shared_cache,
76328  sqlite3_errcode,
76329  sqlite3_errmsg,
76330  sqlite3_errmsg16,
76331  sqlite3_exec,
76332#ifndef SQLITE_OMIT_DEPRECATED
76333  sqlite3_expired,
76334#else
76335  0,
76336#endif
76337  sqlite3_finalize,
76338  sqlite3_free,
76339  sqlite3_free_table,
76340  sqlite3_get_autocommit,
76341  sqlite3_get_auxdata,
76342  sqlite3_get_table,
76343  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
76344  sqlite3_interrupt,
76345  sqlite3_last_insert_rowid,
76346  sqlite3_libversion,
76347  sqlite3_libversion_number,
76348  sqlite3_malloc,
76349  sqlite3_mprintf,
76350  sqlite3_open,
76351  sqlite3_open16,
76352  sqlite3_prepare,
76353  sqlite3_prepare16,
76354  sqlite3_profile,
76355  sqlite3_progress_handler,
76356  sqlite3_realloc,
76357  sqlite3_reset,
76358  sqlite3_result_blob,
76359  sqlite3_result_double,
76360  sqlite3_result_error,
76361  sqlite3_result_error16,
76362  sqlite3_result_int,
76363  sqlite3_result_int64,
76364  sqlite3_result_null,
76365  sqlite3_result_text,
76366  sqlite3_result_text16,
76367  sqlite3_result_text16be,
76368  sqlite3_result_text16le,
76369  sqlite3_result_value,
76370  sqlite3_rollback_hook,
76371  sqlite3_set_authorizer,
76372  sqlite3_set_auxdata,
76373  sqlite3_snprintf,
76374  sqlite3_step,
76375  sqlite3_table_column_metadata,
76376#ifndef SQLITE_OMIT_DEPRECATED
76377  sqlite3_thread_cleanup,
76378#else
76379  0,
76380#endif
76381  sqlite3_total_changes,
76382  sqlite3_trace,
76383#ifndef SQLITE_OMIT_DEPRECATED
76384  sqlite3_transfer_bindings,
76385#else
76386  0,
76387#endif
76388  sqlite3_update_hook,
76389  sqlite3_user_data,
76390  sqlite3_value_blob,
76391  sqlite3_value_bytes,
76392  sqlite3_value_bytes16,
76393  sqlite3_value_double,
76394  sqlite3_value_int,
76395  sqlite3_value_int64,
76396  sqlite3_value_numeric_type,
76397  sqlite3_value_text,
76398  sqlite3_value_text16,
76399  sqlite3_value_text16be,
76400  sqlite3_value_text16le,
76401  sqlite3_value_type,
76402  sqlite3_vmprintf,
76403  /*
76404  ** The original API set ends here.  All extensions can call any
76405  ** of the APIs above provided that the pointer is not NULL.  But
76406  ** before calling APIs that follow, extension should check the
76407  ** sqlite3_libversion_number() to make sure they are dealing with
76408  ** a library that is new enough to support that API.
76409  *************************************************************************
76410  */
76411  sqlite3_overload_function,
76412
76413  /*
76414  ** Added after 3.3.13
76415  */
76416  sqlite3_prepare_v2,
76417  sqlite3_prepare16_v2,
76418  sqlite3_clear_bindings,
76419
76420  /*
76421  ** Added for 3.4.1
76422  */
76423  sqlite3_create_module_v2,
76424
76425  /*
76426  ** Added for 3.5.0
76427  */
76428  sqlite3_bind_zeroblob,
76429  sqlite3_blob_bytes,
76430  sqlite3_blob_close,
76431  sqlite3_blob_open,
76432  sqlite3_blob_read,
76433  sqlite3_blob_write,
76434  sqlite3_create_collation_v2,
76435  sqlite3_file_control,
76436  sqlite3_memory_highwater,
76437  sqlite3_memory_used,
76438#ifdef SQLITE_MUTEX_OMIT
76439  0,
76440  0,
76441  0,
76442  0,
76443  0,
76444#else
76445  sqlite3_mutex_alloc,
76446  sqlite3_mutex_enter,
76447  sqlite3_mutex_free,
76448  sqlite3_mutex_leave,
76449  sqlite3_mutex_try,
76450#endif
76451  sqlite3_open_v2,
76452  sqlite3_release_memory,
76453  sqlite3_result_error_nomem,
76454  sqlite3_result_error_toobig,
76455  sqlite3_sleep,
76456  sqlite3_soft_heap_limit,
76457  sqlite3_vfs_find,
76458  sqlite3_vfs_register,
76459  sqlite3_vfs_unregister,
76460
76461  /*
76462  ** Added for 3.5.8
76463  */
76464  sqlite3_threadsafe,
76465  sqlite3_result_zeroblob,
76466  sqlite3_result_error_code,
76467  sqlite3_test_control,
76468  sqlite3_randomness,
76469  sqlite3_context_db_handle,
76470
76471  /*
76472  ** Added for 3.6.0
76473  */
76474  sqlite3_extended_result_codes,
76475  sqlite3_limit,
76476  sqlite3_next_stmt,
76477  sqlite3_sql,
76478  sqlite3_status,
76479};
76480
76481/*
76482** Attempt to load an SQLite extension library contained in the file
76483** zFile.  The entry point is zProc.  zProc may be 0 in which case a
76484** default entry point name (sqlite3_extension_init) is used.  Use
76485** of the default name is recommended.
76486**
76487** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
76488**
76489** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
76490** error message text.  The calling function should free this memory
76491** by calling sqlite3DbFree(db, ).
76492*/
76493static int sqlite3LoadExtension(
76494  sqlite3 *db,          /* Load the extension into this database connection */
76495  const char *zFile,    /* Name of the shared library containing extension */
76496  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
76497  char **pzErrMsg       /* Put error message here if not 0 */
76498){
76499  sqlite3_vfs *pVfs = db->pVfs;
76500  void *handle;
76501  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
76502  char *zErrmsg = 0;
76503  void **aHandle;
76504  const int nMsg = 300;
76505
76506  if( pzErrMsg ) *pzErrMsg = 0;
76507
76508  /* Ticket #1863.  To avoid a creating security problems for older
76509  ** applications that relink against newer versions of SQLite, the
76510  ** ability to run load_extension is turned off by default.  One
76511  ** must call sqlite3_enable_load_extension() to turn on extension
76512  ** loading.  Otherwise you get the following error.
76513  */
76514  if( (db->flags & SQLITE_LoadExtension)==0 ){
76515    if( pzErrMsg ){
76516      *pzErrMsg = sqlite3_mprintf("not authorized");
76517    }
76518    return SQLITE_ERROR;
76519  }
76520
76521  if( zProc==0 ){
76522    zProc = "sqlite3_extension_init";
76523  }
76524
76525  handle = sqlite3OsDlOpen(pVfs, zFile);
76526  if( handle==0 ){
76527    if( pzErrMsg ){
76528      zErrmsg = sqlite3StackAllocZero(db, nMsg);
76529      if( zErrmsg ){
76530        sqlite3_snprintf(nMsg, zErrmsg,
76531            "unable to open shared library [%s]", zFile);
76532        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
76533        *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
76534        sqlite3StackFree(db, zErrmsg);
76535      }
76536    }
76537    return SQLITE_ERROR;
76538  }
76539  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
76540                   sqlite3OsDlSym(pVfs, handle, zProc);
76541  if( xInit==0 ){
76542    if( pzErrMsg ){
76543      zErrmsg = sqlite3StackAllocZero(db, nMsg);
76544      if( zErrmsg ){
76545        sqlite3_snprintf(nMsg, zErrmsg,
76546            "no entry point [%s] in shared library [%s]", zProc,zFile);
76547        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
76548        *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
76549        sqlite3StackFree(db, zErrmsg);
76550      }
76551      sqlite3OsDlClose(pVfs, handle);
76552    }
76553    return SQLITE_ERROR;
76554  }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
76555    if( pzErrMsg ){
76556      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
76557    }
76558    sqlite3_free(zErrmsg);
76559    sqlite3OsDlClose(pVfs, handle);
76560    return SQLITE_ERROR;
76561  }
76562
76563  /* Append the new shared library handle to the db->aExtension array. */
76564  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
76565  if( aHandle==0 ){
76566    return SQLITE_NOMEM;
76567  }
76568  if( db->nExtension>0 ){
76569    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
76570  }
76571  sqlite3DbFree(db, db->aExtension);
76572  db->aExtension = aHandle;
76573
76574  db->aExtension[db->nExtension++] = handle;
76575  return SQLITE_OK;
76576}
76577SQLITE_API int sqlite3_load_extension(
76578  sqlite3 *db,          /* Load the extension into this database connection */
76579  const char *zFile,    /* Name of the shared library containing extension */
76580  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
76581  char **pzErrMsg       /* Put error message here if not 0 */
76582){
76583  int rc;
76584  sqlite3_mutex_enter(db->mutex);
76585  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
76586  rc = sqlite3ApiExit(db, rc);
76587  sqlite3_mutex_leave(db->mutex);
76588  return rc;
76589}
76590
76591/*
76592** Call this routine when the database connection is closing in order
76593** to clean up loaded extensions
76594*/
76595SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
76596  int i;
76597  assert( sqlite3_mutex_held(db->mutex) );
76598  for(i=0; i<db->nExtension; i++){
76599    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
76600  }
76601  sqlite3DbFree(db, db->aExtension);
76602}
76603
76604/*
76605** Enable or disable extension loading.  Extension loading is disabled by
76606** default so as not to open security holes in older applications.
76607*/
76608SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
76609  sqlite3_mutex_enter(db->mutex);
76610  if( onoff ){
76611    db->flags |= SQLITE_LoadExtension;
76612  }else{
76613    db->flags &= ~SQLITE_LoadExtension;
76614  }
76615  sqlite3_mutex_leave(db->mutex);
76616  return SQLITE_OK;
76617}
76618
76619#endif /* SQLITE_OMIT_LOAD_EXTENSION */
76620
76621/*
76622** The auto-extension code added regardless of whether or not extension
76623** loading is supported.  We need a dummy sqlite3Apis pointer for that
76624** code if regular extension loading is not available.  This is that
76625** dummy pointer.
76626*/
76627#ifdef SQLITE_OMIT_LOAD_EXTENSION
76628static const sqlite3_api_routines sqlite3Apis = { 0 };
76629#endif
76630
76631
76632/*
76633** The following object holds the list of automatically loaded
76634** extensions.
76635**
76636** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
76637** mutex must be held while accessing this list.
76638*/
76639typedef struct sqlite3AutoExtList sqlite3AutoExtList;
76640static SQLITE_WSD struct sqlite3AutoExtList {
76641  int nExt;              /* Number of entries in aExt[] */
76642  void (**aExt)(void);   /* Pointers to the extension init functions */
76643} sqlite3Autoext = { 0, 0 };
76644
76645/* The "wsdAutoext" macro will resolve to the autoextension
76646** state vector.  If writable static data is unsupported on the target,
76647** we have to locate the state vector at run-time.  In the more common
76648** case where writable static data is supported, wsdStat can refer directly
76649** to the "sqlite3Autoext" state vector declared above.
76650*/
76651#ifdef SQLITE_OMIT_WSD
76652# define wsdAutoextInit \
76653  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
76654# define wsdAutoext x[0]
76655#else
76656# define wsdAutoextInit
76657# define wsdAutoext sqlite3Autoext
76658#endif
76659
76660
76661/*
76662** Register a statically linked extension that is automatically
76663** loaded by every new database connection.
76664*/
76665SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
76666  int rc = SQLITE_OK;
76667#ifndef SQLITE_OMIT_AUTOINIT
76668  rc = sqlite3_initialize();
76669  if( rc ){
76670    return rc;
76671  }else
76672#endif
76673  {
76674    int i;
76675#if SQLITE_THREADSAFE
76676    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
76677#endif
76678    wsdAutoextInit;
76679    sqlite3_mutex_enter(mutex);
76680    for(i=0; i<wsdAutoext.nExt; i++){
76681      if( wsdAutoext.aExt[i]==xInit ) break;
76682    }
76683    if( i==wsdAutoext.nExt ){
76684      int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
76685      void (**aNew)(void);
76686      aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
76687      if( aNew==0 ){
76688        rc = SQLITE_NOMEM;
76689      }else{
76690        wsdAutoext.aExt = aNew;
76691        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
76692        wsdAutoext.nExt++;
76693      }
76694    }
76695    sqlite3_mutex_leave(mutex);
76696    assert( (rc&0xff)==rc );
76697    return rc;
76698  }
76699}
76700
76701/*
76702** Reset the automatic extension loading mechanism.
76703*/
76704SQLITE_API void sqlite3_reset_auto_extension(void){
76705#ifndef SQLITE_OMIT_AUTOINIT
76706  if( sqlite3_initialize()==SQLITE_OK )
76707#endif
76708  {
76709#if SQLITE_THREADSAFE
76710    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
76711#endif
76712    wsdAutoextInit;
76713    sqlite3_mutex_enter(mutex);
76714    sqlite3_free(wsdAutoext.aExt);
76715    wsdAutoext.aExt = 0;
76716    wsdAutoext.nExt = 0;
76717    sqlite3_mutex_leave(mutex);
76718  }
76719}
76720
76721/*
76722** Load all automatic extensions.
76723**
76724** If anything goes wrong, set an error in the database connection.
76725*/
76726SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
76727  int i;
76728  int go = 1;
76729  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
76730
76731  wsdAutoextInit;
76732  if( wsdAutoext.nExt==0 ){
76733    /* Common case: early out without every having to acquire a mutex */
76734    return;
76735  }
76736  for(i=0; go; i++){
76737    char *zErrmsg;
76738#if SQLITE_THREADSAFE
76739    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
76740#endif
76741    sqlite3_mutex_enter(mutex);
76742    if( i>=wsdAutoext.nExt ){
76743      xInit = 0;
76744      go = 0;
76745    }else{
76746      xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
76747              wsdAutoext.aExt[i];
76748    }
76749    sqlite3_mutex_leave(mutex);
76750    zErrmsg = 0;
76751    if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
76752      sqlite3Error(db, SQLITE_ERROR,
76753            "automatic extension loading failed: %s", zErrmsg);
76754      go = 0;
76755    }
76756    sqlite3_free(zErrmsg);
76757  }
76758}
76759
76760/************** End of loadext.c *********************************************/
76761/************** Begin file pragma.c ******************************************/
76762/*
76763** 2003 April 6
76764**
76765** The author disclaims copyright to this source code.  In place of
76766** a legal notice, here is a blessing:
76767**
76768**    May you do good and not evil.
76769**    May you find forgiveness for yourself and forgive others.
76770**    May you share freely, never taking more than you give.
76771**
76772*************************************************************************
76773** This file contains code used to implement the PRAGMA command.
76774*/
76775
76776/* Ignore this whole file if pragmas are disabled
76777*/
76778#if !defined(SQLITE_OMIT_PRAGMA)
76779
76780/*
76781** Interpret the given string as a safety level.  Return 0 for OFF,
76782** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
76783** unrecognized string argument.
76784**
76785** Note that the values returned are one less that the values that
76786** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
76787** to support legacy SQL code.  The safety level used to be boolean
76788** and older scripts may have used numbers 0 for OFF and 1 for ON.
76789*/
76790static u8 getSafetyLevel(const char *z){
76791                             /* 123456789 123456789 */
76792  static const char zText[] = "onoffalseyestruefull";
76793  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
76794  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
76795  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
76796  int i, n;
76797  if( sqlite3Isdigit(*z) ){
76798    return (u8)atoi(z);
76799  }
76800  n = sqlite3Strlen30(z);
76801  for(i=0; i<ArraySize(iLength); i++){
76802    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
76803      return iValue[i];
76804    }
76805  }
76806  return 1;
76807}
76808
76809/*
76810** Interpret the given string as a boolean value.
76811*/
76812static u8 getBoolean(const char *z){
76813  return getSafetyLevel(z)&1;
76814}
76815
76816/*
76817** Interpret the given string as a locking mode value.
76818*/
76819static int getLockingMode(const char *z){
76820  if( z ){
76821    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
76822    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
76823  }
76824  return PAGER_LOCKINGMODE_QUERY;
76825}
76826
76827#ifndef SQLITE_OMIT_AUTOVACUUM
76828/*
76829** Interpret the given string as an auto-vacuum mode value.
76830**
76831** The following strings, "none", "full" and "incremental" are
76832** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
76833*/
76834static int getAutoVacuum(const char *z){
76835  int i;
76836  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
76837  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
76838  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
76839  i = atoi(z);
76840  return (u8)((i>=0&&i<=2)?i:0);
76841}
76842#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
76843
76844#ifndef SQLITE_OMIT_PAGER_PRAGMAS
76845/*
76846** Interpret the given string as a temp db location. Return 1 for file
76847** backed temporary databases, 2 for the Red-Black tree in memory database
76848** and 0 to use the compile-time default.
76849*/
76850static int getTempStore(const char *z){
76851  if( z[0]>='0' && z[0]<='2' ){
76852    return z[0] - '0';
76853  }else if( sqlite3StrICmp(z, "file")==0 ){
76854    return 1;
76855  }else if( sqlite3StrICmp(z, "memory")==0 ){
76856    return 2;
76857  }else{
76858    return 0;
76859  }
76860}
76861#endif /* SQLITE_PAGER_PRAGMAS */
76862
76863#ifndef SQLITE_OMIT_PAGER_PRAGMAS
76864/*
76865** Invalidate temp storage, either when the temp storage is changed
76866** from default, or when 'file' and the temp_store_directory has changed
76867*/
76868static int invalidateTempStorage(Parse *pParse){
76869  sqlite3 *db = pParse->db;
76870  if( db->aDb[1].pBt!=0 ){
76871    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
76872      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
76873        "from within a transaction");
76874      return SQLITE_ERROR;
76875    }
76876    sqlite3BtreeClose(db->aDb[1].pBt);
76877    db->aDb[1].pBt = 0;
76878    sqlite3ResetInternalSchema(db, 0);
76879  }
76880  return SQLITE_OK;
76881}
76882#endif /* SQLITE_PAGER_PRAGMAS */
76883
76884#ifndef SQLITE_OMIT_PAGER_PRAGMAS
76885/*
76886** If the TEMP database is open, close it and mark the database schema
76887** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
76888** or DEFAULT_TEMP_STORE pragmas.
76889*/
76890static int changeTempStorage(Parse *pParse, const char *zStorageType){
76891  int ts = getTempStore(zStorageType);
76892  sqlite3 *db = pParse->db;
76893  if( db->temp_store==ts ) return SQLITE_OK;
76894  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
76895    return SQLITE_ERROR;
76896  }
76897  db->temp_store = (u8)ts;
76898  return SQLITE_OK;
76899}
76900#endif /* SQLITE_PAGER_PRAGMAS */
76901
76902/*
76903** Generate code to return a single integer value.
76904*/
76905static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
76906  Vdbe *v = sqlite3GetVdbe(pParse);
76907  int mem = ++pParse->nMem;
76908  i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
76909  if( pI64 ){
76910    memcpy(pI64, &value, sizeof(value));
76911  }
76912  sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
76913  sqlite3VdbeSetNumCols(v, 1);
76914  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
76915  sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
76916}
76917
76918#ifndef SQLITE_OMIT_FLAG_PRAGMAS
76919/*
76920** Check to see if zRight and zLeft refer to a pragma that queries
76921** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
76922** Also, implement the pragma.
76923*/
76924static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
76925  static const struct sPragmaType {
76926    const char *zName;  /* Name of the pragma */
76927    int mask;           /* Mask for the db->flags value */
76928  } aPragma[] = {
76929    { "full_column_names",        SQLITE_FullColNames  },
76930    { "short_column_names",       SQLITE_ShortColNames },
76931    { "count_changes",            SQLITE_CountRows     },
76932    { "empty_result_callbacks",   SQLITE_NullCallback  },
76933    { "legacy_file_format",       SQLITE_LegacyFileFmt },
76934    { "fullfsync",                SQLITE_FullFSync     },
76935    { "reverse_unordered_selects", SQLITE_ReverseOrder  },
76936#ifdef SQLITE_DEBUG
76937    { "sql_trace",                SQLITE_SqlTrace      },
76938    { "vdbe_listing",             SQLITE_VdbeListing   },
76939    { "vdbe_trace",               SQLITE_VdbeTrace     },
76940#endif
76941#ifndef SQLITE_OMIT_CHECK
76942    { "ignore_check_constraints", SQLITE_IgnoreChecks  },
76943#endif
76944    /* The following is VERY experimental */
76945    { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
76946    { "omit_readlock",            SQLITE_NoReadlock    },
76947
76948    /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
76949    ** flag if there are any active statements. */
76950    { "read_uncommitted",         SQLITE_ReadUncommitted },
76951    { "recursive_triggers",       SQLITE_RecTriggers },
76952
76953    /* This flag may only be set if both foreign-key and trigger support
76954    ** are present in the build.  */
76955#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
76956    { "foreign_keys",             SQLITE_ForeignKeys },
76957#endif
76958  };
76959  int i;
76960  const struct sPragmaType *p;
76961  for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
76962    if( sqlite3StrICmp(zLeft, p->zName)==0 ){
76963      sqlite3 *db = pParse->db;
76964      Vdbe *v;
76965      v = sqlite3GetVdbe(pParse);
76966      assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
76967      if( ALWAYS(v) ){
76968        if( zRight==0 ){
76969          returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
76970        }else{
76971          int mask = p->mask;          /* Mask of bits to set or clear. */
76972          if( db->autoCommit==0 ){
76973            /* Foreign key support may not be enabled or disabled while not
76974            ** in auto-commit mode.  */
76975            mask &= ~(SQLITE_ForeignKeys);
76976          }
76977
76978          if( getBoolean(zRight) ){
76979            db->flags |= mask;
76980          }else{
76981            db->flags &= ~mask;
76982          }
76983
76984          /* Many of the flag-pragmas modify the code generated by the SQL
76985          ** compiler (eg. count_changes). So add an opcode to expire all
76986          ** compiled SQL statements after modifying a pragma value.
76987          */
76988          sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
76989        }
76990      }
76991
76992      return 1;
76993    }
76994  }
76995  return 0;
76996}
76997#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
76998
76999/*
77000** Return a human-readable name for a constraint resolution action.
77001*/
77002#ifndef SQLITE_OMIT_FOREIGN_KEY
77003static const char *actionName(u8 action){
77004  const char *zName;
77005  switch( action ){
77006    case OE_SetNull:  zName = "SET NULL";        break;
77007    case OE_SetDflt:  zName = "SET DEFAULT";     break;
77008    case OE_Cascade:  zName = "CASCADE";         break;
77009    case OE_Restrict: zName = "RESTRICT";        break;
77010    default:          zName = "NO ACTION";
77011                      assert( action==OE_None ); break;
77012  }
77013  return zName;
77014}
77015#endif
77016
77017/*
77018** Process a pragma statement.
77019**
77020** Pragmas are of this form:
77021**
77022**      PRAGMA [database.]id [= value]
77023**
77024** The identifier might also be a string.  The value is a string, and
77025** identifier, or a number.  If minusFlag is true, then the value is
77026** a number that was preceded by a minus sign.
77027**
77028** If the left side is "database.id" then pId1 is the database name
77029** and pId2 is the id.  If the left side is just "id" then pId1 is the
77030** id and pId2 is any empty string.
77031*/
77032SQLITE_PRIVATE void sqlite3Pragma(
77033  Parse *pParse,
77034  Token *pId1,        /* First part of [database.]id field */
77035  Token *pId2,        /* Second part of [database.]id field, or NULL */
77036  Token *pValue,      /* Token for <value>, or NULL */
77037  int minusFlag       /* True if a '-' sign preceded <value> */
77038){
77039  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
77040  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
77041  const char *zDb = 0;   /* The database name */
77042  Token *pId;            /* Pointer to <id> token */
77043  int iDb;               /* Database index for <database> */
77044  sqlite3 *db = pParse->db;
77045  Db *pDb;
77046  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
77047  if( v==0 ) return;
77048  pParse->nMem = 2;
77049
77050  /* Interpret the [database.] part of the pragma statement. iDb is the
77051  ** index of the database this pragma is being applied to in db.aDb[]. */
77052  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
77053  if( iDb<0 ) return;
77054  pDb = &db->aDb[iDb];
77055
77056  /* If the temp database has been explicitly named as part of the
77057  ** pragma, make sure it is open.
77058  */
77059  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
77060    return;
77061  }
77062
77063  zLeft = sqlite3NameFromToken(db, pId);
77064  if( !zLeft ) return;
77065  if( minusFlag ){
77066    zRight = sqlite3MPrintf(db, "-%T", pValue);
77067  }else{
77068    zRight = sqlite3NameFromToken(db, pValue);
77069  }
77070
77071  assert( pId2 );
77072  zDb = pId2->n>0 ? pDb->zName : 0;
77073  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
77074    goto pragma_out;
77075  }
77076
77077#ifndef SQLITE_OMIT_PAGER_PRAGMAS
77078  /*
77079  **  PRAGMA [database.]default_cache_size
77080  **  PRAGMA [database.]default_cache_size=N
77081  **
77082  ** The first form reports the current persistent setting for the
77083  ** page cache size.  The value returned is the maximum number of
77084  ** pages in the page cache.  The second form sets both the current
77085  ** page cache size value and the persistent page cache size value
77086  ** stored in the database file.
77087  **
77088  ** The default cache size is stored in meta-value 2 of page 1 of the
77089  ** database file.  The cache size is actually the absolute value of
77090  ** this memory location.  The sign of meta-value 2 determines the
77091  ** synchronous setting.  A negative value means synchronous is off
77092  ** and a positive value means synchronous is on.
77093  */
77094  if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
77095    static const VdbeOpList getCacheSize[] = {
77096      { OP_Transaction, 0, 0,        0},                         /* 0 */
77097      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
77098      { OP_IfPos,       1, 7,        0},
77099      { OP_Integer,     0, 2,        0},
77100      { OP_Subtract,    1, 2,        1},
77101      { OP_IfPos,       1, 7,        0},
77102      { OP_Integer,     0, 1,        0},                         /* 6 */
77103      { OP_ResultRow,   1, 1,        0},
77104    };
77105    int addr;
77106    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77107    sqlite3VdbeUsesBtree(v, iDb);
77108    if( !zRight ){
77109      sqlite3VdbeSetNumCols(v, 1);
77110      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
77111      pParse->nMem += 2;
77112      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
77113      sqlite3VdbeChangeP1(v, addr, iDb);
77114      sqlite3VdbeChangeP1(v, addr+1, iDb);
77115      sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
77116    }else{
77117      int size = atoi(zRight);
77118      if( size<0 ) size = -size;
77119      sqlite3BeginWriteOperation(pParse, 0, iDb);
77120      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
77121      sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, BTREE_DEFAULT_CACHE_SIZE);
77122      addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
77123      sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
77124      sqlite3VdbeJumpHere(v, addr);
77125      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
77126      pDb->pSchema->cache_size = size;
77127      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
77128    }
77129  }else
77130
77131  /*
77132  **  PRAGMA [database.]page_size
77133  **  PRAGMA [database.]page_size=N
77134  **
77135  ** The first form reports the current setting for the
77136  ** database page size in bytes.  The second form sets the
77137  ** database page size value.  The value can only be set if
77138  ** the database has not yet been created.
77139  */
77140  if( sqlite3StrICmp(zLeft,"page_size")==0 ){
77141    Btree *pBt = pDb->pBt;
77142    assert( pBt!=0 );
77143    if( !zRight ){
77144      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
77145      returnSingleInt(pParse, "page_size", size);
77146    }else{
77147      /* Malloc may fail when setting the page-size, as there is an internal
77148      ** buffer that the pager module resizes using sqlite3_realloc().
77149      */
77150      db->nextPagesize = atoi(zRight);
77151      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
77152        db->mallocFailed = 1;
77153      }
77154    }
77155  }else
77156
77157  /*
77158  **  PRAGMA [database.]max_page_count
77159  **  PRAGMA [database.]max_page_count=N
77160  **
77161  ** The first form reports the current setting for the
77162  ** maximum number of pages in the database file.  The
77163  ** second form attempts to change this setting.  Both
77164  ** forms return the current setting.
77165  */
77166  if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
77167    Btree *pBt = pDb->pBt;
77168    int newMax = 0;
77169    assert( pBt!=0 );
77170    if( zRight ){
77171      newMax = atoi(zRight);
77172    }
77173    if( ALWAYS(pBt) ){
77174      newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
77175    }
77176    returnSingleInt(pParse, "max_page_count", newMax);
77177  }else
77178
77179  /*
77180  **  PRAGMA [database.]page_count
77181  **
77182  ** Return the number of pages in the specified database.
77183  */
77184  if( sqlite3StrICmp(zLeft,"page_count")==0 ){
77185    int iReg;
77186    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77187    sqlite3CodeVerifySchema(pParse, iDb);
77188    iReg = ++pParse->nMem;
77189    sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
77190    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
77191    sqlite3VdbeSetNumCols(v, 1);
77192    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
77193  }else
77194
77195  /*
77196  **  PRAGMA [database.]locking_mode
77197  **  PRAGMA [database.]locking_mode = (normal|exclusive)
77198  */
77199  if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
77200    const char *zRet = "normal";
77201    int eMode = getLockingMode(zRight);
77202
77203    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
77204      /* Simple "PRAGMA locking_mode;" statement. This is a query for
77205      ** the current default locking mode (which may be different to
77206      ** the locking-mode of the main database).
77207      */
77208      eMode = db->dfltLockMode;
77209    }else{
77210      Pager *pPager;
77211      if( pId2->n==0 ){
77212        /* This indicates that no database name was specified as part
77213        ** of the PRAGMA command. In this case the locking-mode must be
77214        ** set on all attached databases, as well as the main db file.
77215        **
77216        ** Also, the sqlite3.dfltLockMode variable is set so that
77217        ** any subsequently attached databases also use the specified
77218        ** locking mode.
77219        */
77220        int ii;
77221        assert(pDb==&db->aDb[0]);
77222        for(ii=2; ii<db->nDb; ii++){
77223          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
77224          sqlite3PagerLockingMode(pPager, eMode);
77225        }
77226        db->dfltLockMode = (u8)eMode;
77227      }
77228      pPager = sqlite3BtreePager(pDb->pBt);
77229      eMode = sqlite3PagerLockingMode(pPager, eMode);
77230    }
77231
77232    assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
77233    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
77234      zRet = "exclusive";
77235    }
77236    sqlite3VdbeSetNumCols(v, 1);
77237    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
77238    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
77239    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77240  }else
77241
77242  /*
77243  **  PRAGMA [database.]journal_mode
77244  **  PRAGMA [database.]journal_mode = (delete|persist|off|truncate|memory)
77245  */
77246  if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
77247    int eMode;
77248    static char * const azModeName[] = {
77249      "delete", "persist", "off", "truncate", "memory"
77250    };
77251
77252    if( zRight==0 ){
77253      eMode = PAGER_JOURNALMODE_QUERY;
77254    }else{
77255      int n = sqlite3Strlen30(zRight);
77256      eMode = sizeof(azModeName)/sizeof(azModeName[0]) - 1;
77257      while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
77258        eMode--;
77259      }
77260    }
77261    if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
77262      /* Simple "PRAGMA journal_mode;" statement. This is a query for
77263      ** the current default journal mode (which may be different to
77264      ** the journal-mode of the main database).
77265      */
77266      eMode = db->dfltJournalMode;
77267    }else{
77268      Pager *pPager;
77269      if( pId2->n==0 ){
77270        /* This indicates that no database name was specified as part
77271        ** of the PRAGMA command. In this case the journal-mode must be
77272        ** set on all attached databases, as well as the main db file.
77273        **
77274        ** Also, the sqlite3.dfltJournalMode variable is set so that
77275        ** any subsequently attached databases also use the specified
77276        ** journal mode.
77277        */
77278        int ii;
77279        assert(pDb==&db->aDb[0]);
77280        for(ii=1; ii<db->nDb; ii++){
77281          if( db->aDb[ii].pBt ){
77282            pPager = sqlite3BtreePager(db->aDb[ii].pBt);
77283            sqlite3PagerJournalMode(pPager, eMode);
77284          }
77285        }
77286        db->dfltJournalMode = (u8)eMode;
77287      }
77288      pPager = sqlite3BtreePager(pDb->pBt);
77289      eMode = sqlite3PagerJournalMode(pPager, eMode);
77290    }
77291    assert( eMode==PAGER_JOURNALMODE_DELETE
77292              || eMode==PAGER_JOURNALMODE_TRUNCATE
77293              || eMode==PAGER_JOURNALMODE_PERSIST
77294              || eMode==PAGER_JOURNALMODE_OFF
77295              || eMode==PAGER_JOURNALMODE_MEMORY );
77296    sqlite3VdbeSetNumCols(v, 1);
77297    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
77298    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0,
77299           azModeName[eMode], P4_STATIC);
77300    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77301  }else
77302
77303  /*
77304  **  PRAGMA [database.]journal_size_limit
77305  **  PRAGMA [database.]journal_size_limit=N
77306  **
77307  ** Get or set the size limit on rollback journal files.
77308  */
77309  if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
77310    Pager *pPager = sqlite3BtreePager(pDb->pBt);
77311    i64 iLimit = -2;
77312    if( zRight ){
77313      sqlite3Atoi64(zRight, &iLimit);
77314      if( iLimit<-1 ) iLimit = -1;
77315    }
77316    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
77317    returnSingleInt(pParse, "journal_size_limit", iLimit);
77318  }else
77319
77320#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
77321
77322  /*
77323  **  PRAGMA [database.]auto_vacuum
77324  **  PRAGMA [database.]auto_vacuum=N
77325  **
77326  ** Get or set the value of the database 'auto-vacuum' parameter.
77327  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
77328  */
77329#ifndef SQLITE_OMIT_AUTOVACUUM
77330  if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
77331    Btree *pBt = pDb->pBt;
77332    assert( pBt!=0 );
77333    if( sqlite3ReadSchema(pParse) ){
77334      goto pragma_out;
77335    }
77336    if( !zRight ){
77337      int auto_vacuum;
77338      if( ALWAYS(pBt) ){
77339         auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
77340      }else{
77341         auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
77342      }
77343      returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
77344    }else{
77345      int eAuto = getAutoVacuum(zRight);
77346      assert( eAuto>=0 && eAuto<=2 );
77347      db->nextAutovac = (u8)eAuto;
77348      if( ALWAYS(eAuto>=0) ){
77349        /* Call SetAutoVacuum() to set initialize the internal auto and
77350        ** incr-vacuum flags. This is required in case this connection
77351        ** creates the database file. It is important that it is created
77352        ** as an auto-vacuum capable db.
77353        */
77354        int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
77355        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
77356          /* When setting the auto_vacuum mode to either "full" or
77357          ** "incremental", write the value of meta[6] in the database
77358          ** file. Before writing to meta[6], check that meta[3] indicates
77359          ** that this really is an auto-vacuum capable database.
77360          */
77361          static const VdbeOpList setMeta6[] = {
77362            { OP_Transaction,    0,         1,                 0},    /* 0 */
77363            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
77364            { OP_If,             1,         0,                 0},    /* 2 */
77365            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
77366            { OP_Integer,        0,         1,                 0},    /* 4 */
77367            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
77368          };
77369          int iAddr;
77370          iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
77371          sqlite3VdbeChangeP1(v, iAddr, iDb);
77372          sqlite3VdbeChangeP1(v, iAddr+1, iDb);
77373          sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
77374          sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
77375          sqlite3VdbeChangeP1(v, iAddr+5, iDb);
77376          sqlite3VdbeUsesBtree(v, iDb);
77377        }
77378      }
77379    }
77380  }else
77381#endif
77382
77383  /*
77384  **  PRAGMA [database.]incremental_vacuum(N)
77385  **
77386  ** Do N steps of incremental vacuuming on a database.
77387  */
77388#ifndef SQLITE_OMIT_AUTOVACUUM
77389  if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
77390    int iLimit, addr;
77391    if( sqlite3ReadSchema(pParse) ){
77392      goto pragma_out;
77393    }
77394    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
77395      iLimit = 0x7fffffff;
77396    }
77397    sqlite3BeginWriteOperation(pParse, 0, iDb);
77398    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
77399    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
77400    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
77401    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
77402    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
77403    sqlite3VdbeJumpHere(v, addr);
77404  }else
77405#endif
77406
77407#ifndef SQLITE_OMIT_PAGER_PRAGMAS
77408  /*
77409  **  PRAGMA [database.]cache_size
77410  **  PRAGMA [database.]cache_size=N
77411  **
77412  ** The first form reports the current local setting for the
77413  ** page cache size.  The local setting can be different from
77414  ** the persistent cache size value that is stored in the database
77415  ** file itself.  The value returned is the maximum number of
77416  ** pages in the page cache.  The second form sets the local
77417  ** page cache size value.  It does not change the persistent
77418  ** cache size stored on the disk so the cache size will revert
77419  ** to its default value when the database is closed and reopened.
77420  ** N should be a positive integer.
77421  */
77422  if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
77423    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77424    if( !zRight ){
77425      returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
77426    }else{
77427      int size = atoi(zRight);
77428      if( size<0 ) size = -size;
77429      pDb->pSchema->cache_size = size;
77430      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
77431    }
77432  }else
77433
77434  /*
77435  **   PRAGMA temp_store
77436  **   PRAGMA temp_store = "default"|"memory"|"file"
77437  **
77438  ** Return or set the local value of the temp_store flag.  Changing
77439  ** the local value does not make changes to the disk file and the default
77440  ** value will be restored the next time the database is opened.
77441  **
77442  ** Note that it is possible for the library compile-time options to
77443  ** override this setting
77444  */
77445  if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
77446    if( !zRight ){
77447      returnSingleInt(pParse, "temp_store", db->temp_store);
77448    }else{
77449      changeTempStorage(pParse, zRight);
77450    }
77451  }else
77452
77453  /*
77454  **   PRAGMA temp_store_directory
77455  **   PRAGMA temp_store_directory = ""|"directory_name"
77456  **
77457  ** Return or set the local value of the temp_store_directory flag.  Changing
77458  ** the value sets a specific directory to be used for temporary files.
77459  ** Setting to a null string reverts to the default temporary directory search.
77460  ** If temporary directory is changed, then invalidateTempStorage.
77461  **
77462  */
77463  if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
77464    if( !zRight ){
77465      if( sqlite3_temp_directory ){
77466        sqlite3VdbeSetNumCols(v, 1);
77467        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
77468            "temp_store_directory", SQLITE_STATIC);
77469        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
77470        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77471      }
77472    }else{
77473#ifndef SQLITE_OMIT_WSD
77474      if( zRight[0] ){
77475        int rc;
77476        int res;
77477        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
77478        if( rc!=SQLITE_OK || res==0 ){
77479          sqlite3ErrorMsg(pParse, "not a writable directory");
77480          goto pragma_out;
77481        }
77482      }
77483      if( SQLITE_TEMP_STORE==0
77484       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
77485       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
77486      ){
77487        invalidateTempStorage(pParse);
77488      }
77489      sqlite3_free(sqlite3_temp_directory);
77490      if( zRight[0] ){
77491        sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
77492      }else{
77493        sqlite3_temp_directory = 0;
77494      }
77495#endif /* SQLITE_OMIT_WSD */
77496    }
77497  }else
77498
77499#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
77500#  if defined(__APPLE__)
77501#    define SQLITE_ENABLE_LOCKING_STYLE 1
77502#  else
77503#    define SQLITE_ENABLE_LOCKING_STYLE 0
77504#  endif
77505#endif
77506#if SQLITE_ENABLE_LOCKING_STYLE
77507  /*
77508   **   PRAGMA [database.]lock_proxy_file
77509   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
77510   **
77511   ** Return or set the value of the lock_proxy_file flag.  Changing
77512   ** the value sets a specific file to be used for database access locks.
77513   **
77514   */
77515  if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
77516    if( !zRight ){
77517      Pager *pPager = sqlite3BtreePager(pDb->pBt);
77518      char *proxy_file_path = NULL;
77519      sqlite3_file *pFile = sqlite3PagerFile(pPager);
77520      sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE,
77521                           &proxy_file_path);
77522
77523      if( proxy_file_path ){
77524        sqlite3VdbeSetNumCols(v, 1);
77525        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
77526                              "lock_proxy_file", SQLITE_STATIC);
77527        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
77528        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77529      }
77530    }else{
77531      Pager *pPager = sqlite3BtreePager(pDb->pBt);
77532      sqlite3_file *pFile = sqlite3PagerFile(pPager);
77533      int res;
77534      if( zRight[0] ){
77535        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
77536                                     zRight);
77537      } else {
77538        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
77539                                     NULL);
77540      }
77541      if( res!=SQLITE_OK ){
77542        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
77543        goto pragma_out;
77544      }
77545    }
77546  }else
77547#endif /* SQLITE_ENABLE_LOCKING_STYLE */
77548
77549  /*
77550  **   PRAGMA [database.]synchronous
77551  **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
77552  **
77553  ** Return or set the local value of the synchronous flag.  Changing
77554  ** the local value does not make changes to the disk file and the
77555  ** default value will be restored the next time the database is
77556  ** opened.
77557  */
77558  if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
77559    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77560    if( !zRight ){
77561      returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
77562    }else{
77563      if( !db->autoCommit ){
77564        sqlite3ErrorMsg(pParse,
77565            "Safety level may not be changed inside a transaction");
77566      }else{
77567        pDb->safety_level = getSafetyLevel(zRight)+1;
77568      }
77569    }
77570  }else
77571#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
77572
77573#ifndef SQLITE_OMIT_FLAG_PRAGMAS
77574  if( flagPragma(pParse, zLeft, zRight) ){
77575    /* The flagPragma() subroutine also generates any necessary code
77576    ** there is nothing more to do here */
77577  }else
77578#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
77579
77580#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
77581  /*
77582  **   PRAGMA table_info(<table>)
77583  **
77584  ** Return a single row for each column of the named table. The columns of
77585  ** the returned data set are:
77586  **
77587  ** cid:        Column id (numbered from left to right, starting at 0)
77588  ** name:       Column name
77589  ** type:       Column declaration type.
77590  ** notnull:    True if 'NOT NULL' is part of column declaration
77591  ** dflt_value: The default value for the column, if any.
77592  */
77593  if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
77594    Table *pTab;
77595    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77596    pTab = sqlite3FindTable(db, zRight, zDb);
77597    if( pTab ){
77598      int i;
77599      int nHidden = 0;
77600      Column *pCol;
77601      sqlite3VdbeSetNumCols(v, 6);
77602      pParse->nMem = 6;
77603      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
77604      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77605      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
77606      sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
77607      sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
77608      sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
77609      sqlite3ViewGetColumnNames(pParse, pTab);
77610      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
77611        if( IsHiddenColumn(pCol) ){
77612          nHidden++;
77613          continue;
77614        }
77615        sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
77616        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
77617        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
77618           pCol->zType ? pCol->zType : "", 0);
77619        sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
77620        if( pCol->zDflt ){
77621          sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
77622        }else{
77623          sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
77624        }
77625        sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
77626        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
77627      }
77628    }
77629  }else
77630
77631  if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
77632    Index *pIdx;
77633    Table *pTab;
77634    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77635    pIdx = sqlite3FindIndex(db, zRight, zDb);
77636    if( pIdx ){
77637      int i;
77638      pTab = pIdx->pTable;
77639      sqlite3VdbeSetNumCols(v, 3);
77640      pParse->nMem = 3;
77641      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
77642      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
77643      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
77644      for(i=0; i<pIdx->nColumn; i++){
77645        int cnum = pIdx->aiColumn[i];
77646        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77647        sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
77648        assert( pTab->nCol>cnum );
77649        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
77650        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
77651      }
77652    }
77653  }else
77654
77655  if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
77656    Index *pIdx;
77657    Table *pTab;
77658    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77659    pTab = sqlite3FindTable(db, zRight, zDb);
77660    if( pTab ){
77661      v = sqlite3GetVdbe(pParse);
77662      pIdx = pTab->pIndex;
77663      if( pIdx ){
77664        int i = 0;
77665        sqlite3VdbeSetNumCols(v, 3);
77666        pParse->nMem = 3;
77667        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
77668        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77669        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
77670        while(pIdx){
77671          sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77672          sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
77673          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
77674          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
77675          ++i;
77676          pIdx = pIdx->pNext;
77677        }
77678      }
77679    }
77680  }else
77681
77682  if( sqlite3StrICmp(zLeft, "database_list")==0 ){
77683    int i;
77684    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77685    sqlite3VdbeSetNumCols(v, 3);
77686    pParse->nMem = 3;
77687    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
77688    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77689    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
77690    for(i=0; i<db->nDb; i++){
77691      if( db->aDb[i].pBt==0 ) continue;
77692      assert( db->aDb[i].zName!=0 );
77693      sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77694      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
77695      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
77696           sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
77697      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
77698    }
77699  }else
77700
77701  if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
77702    int i = 0;
77703    HashElem *p;
77704    sqlite3VdbeSetNumCols(v, 2);
77705    pParse->nMem = 2;
77706    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
77707    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77708    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
77709      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
77710      sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
77711      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
77712      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
77713    }
77714  }else
77715#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
77716
77717#ifndef SQLITE_OMIT_FOREIGN_KEY
77718  if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
77719    FKey *pFK;
77720    Table *pTab;
77721    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77722    pTab = sqlite3FindTable(db, zRight, zDb);
77723    if( pTab ){
77724      v = sqlite3GetVdbe(pParse);
77725      pFK = pTab->pFKey;
77726      if( pFK ){
77727        int i = 0;
77728        sqlite3VdbeSetNumCols(v, 8);
77729        pParse->nMem = 8;
77730        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
77731        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
77732        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
77733        sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
77734        sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
77735        sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
77736        sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
77737        sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
77738        while(pFK){
77739          int j;
77740          for(j=0; j<pFK->nCol; j++){
77741            char *zCol = pFK->aCol[j].zCol;
77742            char *zOnDelete = (char *)actionName(pFK->aAction[0]);
77743            char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
77744            sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77745            sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
77746            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
77747            sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
77748                              pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
77749            sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
77750            sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
77751            sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
77752            sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
77753            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
77754          }
77755          ++i;
77756          pFK = pFK->pNextFrom;
77757        }
77758      }
77759    }
77760  }else
77761#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
77762
77763#ifndef NDEBUG
77764  if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
77765    if( zRight ){
77766      if( getBoolean(zRight) ){
77767        sqlite3ParserTrace(stderr, "parser: ");
77768      }else{
77769        sqlite3ParserTrace(0, 0);
77770      }
77771    }
77772  }else
77773#endif
77774
77775  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
77776  ** used will be case sensitive or not depending on the RHS.
77777  */
77778  if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
77779    if( zRight ){
77780      sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
77781    }
77782  }else
77783
77784#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
77785# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
77786#endif
77787
77788#ifndef SQLITE_OMIT_INTEGRITY_CHECK
77789  /* Pragma "quick_check" is an experimental reduced version of
77790  ** integrity_check designed to detect most database corruption
77791  ** without most of the overhead of a full integrity-check.
77792  */
77793  if( sqlite3StrICmp(zLeft, "integrity_check")==0
77794   || sqlite3StrICmp(zLeft, "quick_check")==0
77795  ){
77796    int i, j, addr, mxErr;
77797
77798    /* Code that appears at the end of the integrity check.  If no error
77799    ** messages have been generated, output OK.  Otherwise output the
77800    ** error message
77801    */
77802    static const VdbeOpList endCode[] = {
77803      { OP_AddImm,      1, 0,        0},    /* 0 */
77804      { OP_IfNeg,       1, 0,        0},    /* 1 */
77805      { OP_String8,     0, 3,        0},    /* 2 */
77806      { OP_ResultRow,   3, 1,        0},
77807    };
77808
77809    int isQuick = (zLeft[0]=='q');
77810
77811    /* Initialize the VDBE program */
77812    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77813    pParse->nMem = 6;
77814    sqlite3VdbeSetNumCols(v, 1);
77815    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
77816
77817    /* Set the maximum error count */
77818    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
77819    if( zRight ){
77820      mxErr = atoi(zRight);
77821      if( mxErr<=0 ){
77822        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
77823      }
77824    }
77825    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
77826
77827    /* Do an integrity check on each database file */
77828    for(i=0; i<db->nDb; i++){
77829      HashElem *x;
77830      Hash *pTbls;
77831      int cnt = 0;
77832
77833      if( OMIT_TEMPDB && i==1 ) continue;
77834
77835      sqlite3CodeVerifySchema(pParse, i);
77836      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
77837      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
77838      sqlite3VdbeJumpHere(v, addr);
77839
77840      /* Do an integrity check of the B-Tree
77841      **
77842      ** Begin by filling registers 2, 3, ... with the root pages numbers
77843      ** for all tables and indices in the database.
77844      */
77845      pTbls = &db->aDb[i].pSchema->tblHash;
77846      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
77847        Table *pTab = sqliteHashData(x);
77848        Index *pIdx;
77849        sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
77850        cnt++;
77851        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
77852          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
77853          cnt++;
77854        }
77855      }
77856
77857      /* Make sure sufficient number of registers have been allocated */
77858      if( pParse->nMem < cnt+4 ){
77859        pParse->nMem = cnt+4;
77860      }
77861
77862      /* Do the b-tree integrity checks */
77863      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
77864      sqlite3VdbeChangeP5(v, (u8)i);
77865      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
77866      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
77867         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
77868         P4_DYNAMIC);
77869      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
77870      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
77871      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
77872      sqlite3VdbeJumpHere(v, addr);
77873
77874      /* Make sure all the indices are constructed correctly.
77875      */
77876      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
77877        Table *pTab = sqliteHashData(x);
77878        Index *pIdx;
77879        int loopTop;
77880
77881        if( pTab->pIndex==0 ) continue;
77882        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
77883        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
77884        sqlite3VdbeJumpHere(v, addr);
77885        sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
77886        sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
77887        loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
77888        sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
77889        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
77890          int jmp2;
77891          int r1;
77892          static const VdbeOpList idxErr[] = {
77893            { OP_AddImm,      1, -1,  0},
77894            { OP_String8,     0,  3,  0},    /* 1 */
77895            { OP_Rowid,       1,  4,  0},
77896            { OP_String8,     0,  5,  0},    /* 3 */
77897            { OP_String8,     0,  6,  0},    /* 4 */
77898            { OP_Concat,      4,  3,  3},
77899            { OP_Concat,      5,  3,  3},
77900            { OP_Concat,      6,  3,  3},
77901            { OP_ResultRow,   3,  1,  0},
77902            { OP_IfPos,       1,  0,  0},    /* 9 */
77903            { OP_Halt,        0,  0,  0},
77904          };
77905          r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
77906          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
77907          addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
77908          sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
77909          sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
77910          sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
77911          sqlite3VdbeJumpHere(v, addr+9);
77912          sqlite3VdbeJumpHere(v, jmp2);
77913        }
77914        sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
77915        sqlite3VdbeJumpHere(v, loopTop);
77916        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
77917          static const VdbeOpList cntIdx[] = {
77918             { OP_Integer,      0,  3,  0},
77919             { OP_Rewind,       0,  0,  0},  /* 1 */
77920             { OP_AddImm,       3,  1,  0},
77921             { OP_Next,         0,  0,  0},  /* 3 */
77922             { OP_Eq,           2,  0,  3},  /* 4 */
77923             { OP_AddImm,       1, -1,  0},
77924             { OP_String8,      0,  2,  0},  /* 6 */
77925             { OP_String8,      0,  3,  0},  /* 7 */
77926             { OP_Concat,       3,  2,  2},
77927             { OP_ResultRow,    2,  1,  0},
77928          };
77929          addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
77930          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
77931          sqlite3VdbeJumpHere(v, addr);
77932          addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
77933          sqlite3VdbeChangeP1(v, addr+1, j+2);
77934          sqlite3VdbeChangeP2(v, addr+1, addr+4);
77935          sqlite3VdbeChangeP1(v, addr+3, j+2);
77936          sqlite3VdbeChangeP2(v, addr+3, addr+2);
77937          sqlite3VdbeJumpHere(v, addr+4);
77938          sqlite3VdbeChangeP4(v, addr+6,
77939                     "wrong # of entries in index ", P4_STATIC);
77940          sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
77941        }
77942      }
77943    }
77944    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
77945    sqlite3VdbeChangeP2(v, addr, -mxErr);
77946    sqlite3VdbeJumpHere(v, addr+1);
77947    sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
77948  }else
77949#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
77950
77951#ifndef SQLITE_OMIT_UTF16
77952  /*
77953  **   PRAGMA encoding
77954  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
77955  **
77956  ** In its first form, this pragma returns the encoding of the main
77957  ** database. If the database is not initialized, it is initialized now.
77958  **
77959  ** The second form of this pragma is a no-op if the main database file
77960  ** has not already been initialized. In this case it sets the default
77961  ** encoding that will be used for the main database file if a new file
77962  ** is created. If an existing main database file is opened, then the
77963  ** default text encoding for the existing database is used.
77964  **
77965  ** In all cases new databases created using the ATTACH command are
77966  ** created to use the same default text encoding as the main database. If
77967  ** the main database has not been initialized and/or created when ATTACH
77968  ** is executed, this is done before the ATTACH operation.
77969  **
77970  ** In the second form this pragma sets the text encoding to be used in
77971  ** new database files created using this database handle. It is only
77972  ** useful if invoked immediately after the main database i
77973  */
77974  if( sqlite3StrICmp(zLeft, "encoding")==0 ){
77975    static const struct EncName {
77976      char *zName;
77977      u8 enc;
77978    } encnames[] = {
77979      { "UTF8",     SQLITE_UTF8        },
77980      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
77981      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
77982      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
77983      { "UTF16le",  SQLITE_UTF16LE     },
77984      { "UTF16be",  SQLITE_UTF16BE     },
77985      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
77986      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
77987      { 0, 0 }
77988    };
77989    const struct EncName *pEnc;
77990    if( !zRight ){    /* "PRAGMA encoding" */
77991      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77992      sqlite3VdbeSetNumCols(v, 1);
77993      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
77994      sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
77995      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
77996      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
77997      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
77998      sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
77999      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
78000    }else{                        /* "PRAGMA encoding = XXX" */
78001      /* Only change the value of sqlite.enc if the database handle is not
78002      ** initialized. If the main database exists, the new sqlite.enc value
78003      ** will be overwritten when the schema is next loaded. If it does not
78004      ** already exists, it will be created to use the new encoding value.
78005      */
78006      if(
78007        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
78008        DbHasProperty(db, 0, DB_Empty)
78009      ){
78010        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
78011          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
78012            ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
78013            break;
78014          }
78015        }
78016        if( !pEnc->zName ){
78017          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
78018        }
78019      }
78020    }
78021  }else
78022#endif /* SQLITE_OMIT_UTF16 */
78023
78024#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
78025  /*
78026  **   PRAGMA [database.]schema_version
78027  **   PRAGMA [database.]schema_version = <integer>
78028  **
78029  **   PRAGMA [database.]user_version
78030  **   PRAGMA [database.]user_version = <integer>
78031  **
78032  ** The pragma's schema_version and user_version are used to set or get
78033  ** the value of the schema-version and user-version, respectively. Both
78034  ** the schema-version and the user-version are 32-bit signed integers
78035  ** stored in the database header.
78036  **
78037  ** The schema-cookie is usually only manipulated internally by SQLite. It
78038  ** is incremented by SQLite whenever the database schema is modified (by
78039  ** creating or dropping a table or index). The schema version is used by
78040  ** SQLite each time a query is executed to ensure that the internal cache
78041  ** of the schema used when compiling the SQL query matches the schema of
78042  ** the database against which the compiled query is actually executed.
78043  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
78044  ** the schema-version is potentially dangerous and may lead to program
78045  ** crashes or database corruption. Use with caution!
78046  **
78047  ** The user-version is not used internally by SQLite. It may be used by
78048  ** applications for any purpose.
78049  */
78050  if( sqlite3StrICmp(zLeft, "schema_version")==0
78051   || sqlite3StrICmp(zLeft, "user_version")==0
78052   || sqlite3StrICmp(zLeft, "freelist_count")==0
78053  ){
78054    int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
78055    sqlite3VdbeUsesBtree(v, iDb);
78056    switch( zLeft[0] ){
78057      case 'f': case 'F':
78058        iCookie = BTREE_FREE_PAGE_COUNT;
78059        break;
78060      case 's': case 'S':
78061        iCookie = BTREE_SCHEMA_VERSION;
78062        break;
78063      default:
78064        iCookie = BTREE_USER_VERSION;
78065        break;
78066    }
78067
78068    if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
78069      /* Write the specified cookie value */
78070      static const VdbeOpList setCookie[] = {
78071        { OP_Transaction,    0,  1,  0},    /* 0 */
78072        { OP_Integer,        0,  1,  0},    /* 1 */
78073        { OP_SetCookie,      0,  0,  1},    /* 2 */
78074      };
78075      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
78076      sqlite3VdbeChangeP1(v, addr, iDb);
78077      sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
78078      sqlite3VdbeChangeP1(v, addr+2, iDb);
78079      sqlite3VdbeChangeP2(v, addr+2, iCookie);
78080    }else{
78081      /* Read the specified cookie value */
78082      static const VdbeOpList readCookie[] = {
78083        { OP_Transaction,     0,  0,  0},    /* 0 */
78084        { OP_ReadCookie,      0,  1,  0},    /* 1 */
78085        { OP_ResultRow,       1,  1,  0}
78086      };
78087      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
78088      sqlite3VdbeChangeP1(v, addr, iDb);
78089      sqlite3VdbeChangeP1(v, addr+1, iDb);
78090      sqlite3VdbeChangeP3(v, addr+1, iCookie);
78091      sqlite3VdbeSetNumCols(v, 1);
78092      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
78093    }
78094  }else
78095#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
78096
78097#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
78098  /*
78099  ** Report the current state of file logs for all databases
78100  */
78101  if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
78102    static const char *const azLockName[] = {
78103      "unlocked", "shared", "reserved", "pending", "exclusive"
78104    };
78105    int i;
78106    sqlite3VdbeSetNumCols(v, 2);
78107    pParse->nMem = 2;
78108    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
78109    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
78110    for(i=0; i<db->nDb; i++){
78111      Btree *pBt;
78112      Pager *pPager;
78113      const char *zState = "unknown";
78114      int j;
78115      if( db->aDb[i].zName==0 ) continue;
78116      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
78117      pBt = db->aDb[i].pBt;
78118      if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
78119        zState = "closed";
78120      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
78121                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
78122         zState = azLockName[j];
78123      }
78124      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
78125      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
78126    }
78127
78128  }else
78129#endif
78130
78131#if SQLITE_HAS_CODEC
78132  if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
78133    sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
78134  }else
78135  if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
78136    sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
78137  }else
78138  if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
78139                 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
78140    int i, h1, h2;
78141    char zKey[40];
78142    for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
78143      h1 += 9*(1&(h1>>6));
78144      h2 += 9*(1&(h2>>6));
78145      zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
78146    }
78147    if( (zLeft[3] & 0xf)==0xb ){
78148      sqlite3_key(db, zKey, i/2);
78149    }else{
78150      sqlite3_rekey(db, zKey, i/2);
78151    }
78152  }else
78153#endif
78154#if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
78155  if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
78156#if SQLITE_HAS_CODEC
78157    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
78158      extern void sqlite3_activate_see(const char*);
78159      sqlite3_activate_see(&zRight[4]);
78160    }
78161#endif
78162#ifdef SQLITE_ENABLE_CEROD
78163    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
78164      extern void sqlite3_activate_cerod(const char*);
78165      sqlite3_activate_cerod(&zRight[6]);
78166    }
78167#endif
78168  }else
78169#endif
78170
78171
78172  {/* Empty ELSE clause */}
78173
78174  /* Code an OP_Expire at the end of each PRAGMA program to cause
78175  ** the VDBE implementing the pragma to expire. Most (all?) pragmas
78176  ** are only valid for a single execution.
78177  */
78178  sqlite3VdbeAddOp2(v, OP_Expire, 1, 0);
78179
78180  /*
78181  ** Reset the safety level, in case the fullfsync flag or synchronous
78182  ** setting changed.
78183  */
78184#ifndef SQLITE_OMIT_PAGER_PRAGMAS
78185  if( db->autoCommit ){
78186    sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
78187               (db->flags&SQLITE_FullFSync)!=0);
78188  }
78189#endif
78190pragma_out:
78191  sqlite3DbFree(db, zLeft);
78192  sqlite3DbFree(db, zRight);
78193}
78194
78195#endif /* SQLITE_OMIT_PRAGMA */
78196
78197/************** End of pragma.c **********************************************/
78198/************** Begin file prepare.c *****************************************/
78199/*
78200** 2005 May 25
78201**
78202** The author disclaims copyright to this source code.  In place of
78203** a legal notice, here is a blessing:
78204**
78205**    May you do good and not evil.
78206**    May you find forgiveness for yourself and forgive others.
78207**    May you share freely, never taking more than you give.
78208**
78209*************************************************************************
78210** This file contains the implementation of the sqlite3_prepare()
78211** interface, and routines that contribute to loading the database schema
78212** from disk.
78213*/
78214
78215/*
78216** Fill the InitData structure with an error message that indicates
78217** that the database is corrupt.
78218*/
78219static void corruptSchema(
78220  InitData *pData,     /* Initialization context */
78221  const char *zObj,    /* Object being parsed at the point of error */
78222  const char *zExtra   /* Error information */
78223){
78224  sqlite3 *db = pData->db;
78225  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
78226    if( zObj==0 ) zObj = "?";
78227    sqlite3SetString(pData->pzErrMsg, db,
78228      "malformed database schema (%s)", zObj);
78229    if( zExtra ){
78230      *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
78231                                 "%s - %s", *pData->pzErrMsg, zExtra);
78232    }
78233  }
78234  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT;
78235}
78236
78237/*
78238** This is the callback routine for the code that initializes the
78239** database.  See sqlite3Init() below for additional information.
78240** This routine is also called from the OP_ParseSchema opcode of the VDBE.
78241**
78242** Each callback contains the following information:
78243**
78244**     argv[0] = name of thing being created
78245**     argv[1] = root page number for table or index. 0 for trigger or view.
78246**     argv[2] = SQL text for the CREATE statement.
78247**
78248*/
78249SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
78250  InitData *pData = (InitData*)pInit;
78251  sqlite3 *db = pData->db;
78252  int iDb = pData->iDb;
78253
78254  assert( argc==3 );
78255  UNUSED_PARAMETER2(NotUsed, argc);
78256  assert( sqlite3_mutex_held(db->mutex) );
78257  DbClearProperty(db, iDb, DB_Empty);
78258  if( db->mallocFailed ){
78259    corruptSchema(pData, argv[0], 0);
78260    return 1;
78261  }
78262
78263  assert( iDb>=0 && iDb<db->nDb );
78264  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
78265  if( argv[1]==0 ){
78266    corruptSchema(pData, argv[0], 0);
78267  }else if( argv[2] && argv[2][0] ){
78268    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
78269    ** But because db->init.busy is set to 1, no VDBE code is generated
78270    ** or executed.  All the parser does is build the internal data
78271    ** structures that describe the table, index, or view.
78272    */
78273    char *zErr;
78274    int rc;
78275    assert( db->init.busy );
78276    db->init.iDb = iDb;
78277    db->init.newTnum = atoi(argv[1]);
78278    db->init.orphanTrigger = 0;
78279    rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
78280    db->init.iDb = 0;
78281    assert( rc!=SQLITE_OK || zErr==0 );
78282    if( SQLITE_OK!=rc ){
78283      if( db->init.orphanTrigger ){
78284        assert( iDb==1 );
78285      }else{
78286        pData->rc = rc;
78287        if( rc==SQLITE_NOMEM ){
78288          db->mallocFailed = 1;
78289        }else if( rc!=SQLITE_INTERRUPT && rc!=SQLITE_LOCKED ){
78290          corruptSchema(pData, argv[0], zErr);
78291        }
78292      }
78293      sqlite3DbFree(db, zErr);
78294    }
78295  }else if( argv[0]==0 ){
78296    corruptSchema(pData, 0, 0);
78297  }else{
78298    /* If the SQL column is blank it means this is an index that
78299    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
78300    ** constraint for a CREATE TABLE.  The index should have already
78301    ** been created when we processed the CREATE TABLE.  All we have
78302    ** to do here is record the root page number for that index.
78303    */
78304    Index *pIndex;
78305    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
78306    if( pIndex==0 ){
78307      /* This can occur if there exists an index on a TEMP table which
78308      ** has the same name as another index on a permanent index.  Since
78309      ** the permanent table is hidden by the TEMP table, we can also
78310      ** safely ignore the index on the permanent table.
78311      */
78312      /* Do Nothing */;
78313    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
78314      corruptSchema(pData, argv[0], "invalid rootpage");
78315    }
78316  }
78317  return 0;
78318}
78319
78320/*
78321** Attempt to read the database schema and initialize internal
78322** data structures for a single database file.  The index of the
78323** database file is given by iDb.  iDb==0 is used for the main
78324** database.  iDb==1 should never be used.  iDb>=2 is used for
78325** auxiliary databases.  Return one of the SQLITE_ error codes to
78326** indicate success or failure.
78327*/
78328static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
78329  int rc;
78330  int i;
78331  int size;
78332  Table *pTab;
78333  Db *pDb;
78334  char const *azArg[4];
78335  int meta[5];
78336  InitData initData;
78337  char const *zMasterSchema;
78338  char const *zMasterName = SCHEMA_TABLE(iDb);
78339  int openedTransaction = 0;
78340
78341  /*
78342  ** The master database table has a structure like this
78343  */
78344  static const char master_schema[] =
78345     "CREATE TABLE sqlite_master(\n"
78346     "  type text,\n"
78347     "  name text,\n"
78348     "  tbl_name text,\n"
78349     "  rootpage integer,\n"
78350     "  sql text\n"
78351     ")"
78352  ;
78353#ifndef SQLITE_OMIT_TEMPDB
78354  static const char temp_master_schema[] =
78355     "CREATE TEMP TABLE sqlite_temp_master(\n"
78356     "  type text,\n"
78357     "  name text,\n"
78358     "  tbl_name text,\n"
78359     "  rootpage integer,\n"
78360     "  sql text\n"
78361     ")"
78362  ;
78363#else
78364  #define temp_master_schema 0
78365#endif
78366
78367  assert( iDb>=0 && iDb<db->nDb );
78368  assert( db->aDb[iDb].pSchema );
78369  assert( sqlite3_mutex_held(db->mutex) );
78370  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
78371
78372  /* zMasterSchema and zInitScript are set to point at the master schema
78373  ** and initialisation script appropriate for the database being
78374  ** initialised. zMasterName is the name of the master table.
78375  */
78376  if( !OMIT_TEMPDB && iDb==1 ){
78377    zMasterSchema = temp_master_schema;
78378  }else{
78379    zMasterSchema = master_schema;
78380  }
78381  zMasterName = SCHEMA_TABLE(iDb);
78382
78383  /* Construct the schema tables.  */
78384  azArg[0] = zMasterName;
78385  azArg[1] = "1";
78386  azArg[2] = zMasterSchema;
78387  azArg[3] = 0;
78388  initData.db = db;
78389  initData.iDb = iDb;
78390  initData.rc = SQLITE_OK;
78391  initData.pzErrMsg = pzErrMsg;
78392  (void)sqlite3SafetyOff(db);
78393  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
78394  (void)sqlite3SafetyOn(db);
78395  if( initData.rc ){
78396    rc = initData.rc;
78397    goto error_out;
78398  }
78399  pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
78400  if( ALWAYS(pTab) ){
78401    pTab->tabFlags |= TF_Readonly;
78402  }
78403
78404  /* Create a cursor to hold the database open
78405  */
78406  pDb = &db->aDb[iDb];
78407  if( pDb->pBt==0 ){
78408    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
78409      DbSetProperty(db, 1, DB_SchemaLoaded);
78410    }
78411    return SQLITE_OK;
78412  }
78413
78414  /* If there is not already a read-only (or read-write) transaction opened
78415  ** on the b-tree database, open one now. If a transaction is opened, it
78416  ** will be closed before this function returns.  */
78417  sqlite3BtreeEnter(pDb->pBt);
78418  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
78419    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
78420    if( rc!=SQLITE_OK ){
78421      sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
78422      goto initone_error_out;
78423    }
78424    openedTransaction = 1;
78425  }
78426
78427  /* Get the database meta information.
78428  **
78429  ** Meta values are as follows:
78430  **    meta[0]   Schema cookie.  Changes with each schema change.
78431  **    meta[1]   File format of schema layer.
78432  **    meta[2]   Size of the page cache.
78433  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
78434  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
78435  **    meta[5]   User version
78436  **    meta[6]   Incremental vacuum mode
78437  **    meta[7]   unused
78438  **    meta[8]   unused
78439  **    meta[9]   unused
78440  **
78441  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
78442  ** the possible values of meta[4].
78443  */
78444  for(i=0; i<ArraySize(meta); i++){
78445    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
78446  }
78447  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
78448
78449  /* If opening a non-empty database, check the text encoding. For the
78450  ** main database, set sqlite3.enc to the encoding of the main database.
78451  ** For an attached db, it is an error if the encoding is not the same
78452  ** as sqlite3.enc.
78453  */
78454  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
78455    if( iDb==0 ){
78456      u8 encoding;
78457      /* If opening the main database, set ENC(db). */
78458      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
78459      if( encoding==0 ) encoding = SQLITE_UTF8;
78460      ENC(db) = encoding;
78461      db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
78462    }else{
78463      /* If opening an attached database, the encoding much match ENC(db) */
78464      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
78465        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
78466            " text encoding as main database");
78467        rc = SQLITE_ERROR;
78468        goto initone_error_out;
78469      }
78470    }
78471  }else{
78472    DbSetProperty(db, iDb, DB_Empty);
78473  }
78474  pDb->pSchema->enc = ENC(db);
78475
78476  if( pDb->pSchema->cache_size==0 ){
78477    size = meta[BTREE_DEFAULT_CACHE_SIZE-1];
78478    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
78479    if( size<0 ) size = -size;
78480    pDb->pSchema->cache_size = size;
78481    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
78482  }
78483
78484  /*
78485  ** file_format==1    Version 3.0.0.
78486  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
78487  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
78488  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
78489  */
78490  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
78491  if( pDb->pSchema->file_format==0 ){
78492    pDb->pSchema->file_format = 1;
78493  }
78494  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
78495    sqlite3SetString(pzErrMsg, db, "unsupported file format");
78496    rc = SQLITE_CORRUPT_BKPT(UNSUPPORTED_FILE_FORMAT_CORRUPTION); // Android Change
78497    goto initone_error_out;
78498  }
78499
78500  /* Ticket #2804:  When we open a database in the newer file format,
78501  ** clear the legacy_file_format pragma flag so that a VACUUM will
78502  ** not downgrade the database and thus invalidate any descending
78503  ** indices that the user might have created.
78504  */
78505  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
78506    db->flags &= ~SQLITE_LegacyFileFmt;
78507  }
78508
78509  /* Read the schema information out of the schema tables
78510  */
78511  assert( db->init.busy );
78512  {
78513    char *zSql;
78514    zSql = sqlite3MPrintf(db,
78515        "SELECT name, rootpage, sql FROM '%q'.%s",
78516        db->aDb[iDb].zName, zMasterName);
78517    (void)sqlite3SafetyOff(db);
78518#ifndef SQLITE_OMIT_AUTHORIZATION
78519    {
78520      int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
78521      xAuth = db->xAuth;
78522      db->xAuth = 0;
78523#endif
78524      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
78525#ifndef SQLITE_OMIT_AUTHORIZATION
78526      db->xAuth = xAuth;
78527    }
78528#endif
78529    if( rc==SQLITE_OK ) rc = initData.rc;
78530    (void)sqlite3SafetyOn(db);
78531    sqlite3DbFree(db, zSql);
78532#ifndef SQLITE_OMIT_ANALYZE
78533    if( rc==SQLITE_OK ){
78534      sqlite3AnalysisLoad(db, iDb);
78535    }
78536#endif
78537  }
78538  if( db->mallocFailed ){
78539    rc = SQLITE_NOMEM;
78540    sqlite3ResetInternalSchema(db, 0);
78541  }
78542  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
78543    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
78544    ** the schema loaded, even if errors occurred. In this situation the
78545    ** current sqlite3_prepare() operation will fail, but the following one
78546    ** will attempt to compile the supplied statement against whatever subset
78547    ** of the schema was loaded before the error occurred. The primary
78548    ** purpose of this is to allow access to the sqlite_master table
78549    ** even when its contents have been corrupted.
78550    */
78551    DbSetProperty(db, iDb, DB_SchemaLoaded);
78552    rc = SQLITE_OK;
78553  }
78554
78555  /* Jump here for an error that occurs after successfully allocating
78556  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
78557  ** before that point, jump to error_out.
78558  */
78559initone_error_out:
78560  if( openedTransaction ){
78561    sqlite3BtreeCommit(pDb->pBt);
78562  }
78563  sqlite3BtreeLeave(pDb->pBt);
78564
78565error_out:
78566  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
78567    db->mallocFailed = 1;
78568  }
78569  return rc;
78570}
78571
78572/*
78573** Initialize all database files - the main database file, the file
78574** used to store temporary tables, and any additional database files
78575** created using ATTACH statements.  Return a success code.  If an
78576** error occurs, write an error message into *pzErrMsg.
78577**
78578** After a database is initialized, the DB_SchemaLoaded bit is set
78579** bit is set in the flags field of the Db structure. If the database
78580** file was of zero-length, then the DB_Empty flag is also set.
78581*/
78582SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
78583  int i, rc;
78584  int commit_internal = !(db->flags&SQLITE_InternChanges);
78585
78586  assert( sqlite3_mutex_held(db->mutex) );
78587  rc = SQLITE_OK;
78588  db->init.busy = 1;
78589  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
78590    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
78591    rc = sqlite3InitOne(db, i, pzErrMsg);
78592    if( rc ){
78593      sqlite3ResetInternalSchema(db, i);
78594    }
78595  }
78596
78597  /* Once all the other databases have been initialised, load the schema
78598  ** for the TEMP database. This is loaded last, as the TEMP database
78599  ** schema may contain references to objects in other databases.
78600  */
78601#ifndef SQLITE_OMIT_TEMPDB
78602  if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
78603                    && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
78604    rc = sqlite3InitOne(db, 1, pzErrMsg);
78605    if( rc ){
78606      sqlite3ResetInternalSchema(db, 1);
78607    }
78608  }
78609#endif
78610
78611  db->init.busy = 0;
78612  if( rc==SQLITE_OK && commit_internal ){
78613    sqlite3CommitInternalChanges(db);
78614  }
78615
78616  return rc;
78617}
78618
78619/*
78620** This routine is a no-op if the database schema is already initialised.
78621** Otherwise, the schema is loaded. An error code is returned.
78622*/
78623SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
78624  int rc = SQLITE_OK;
78625  sqlite3 *db = pParse->db;
78626  assert( sqlite3_mutex_held(db->mutex) );
78627  if( !db->init.busy ){
78628    rc = sqlite3Init(db, &pParse->zErrMsg);
78629  }
78630  if( rc!=SQLITE_OK ){
78631    pParse->rc = rc;
78632    pParse->nErr++;
78633  }
78634  return rc;
78635}
78636
78637
78638/*
78639** Check schema cookies in all databases.  If any cookie is out
78640** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
78641** make no changes to pParse->rc.
78642*/
78643static void schemaIsValid(Parse *pParse){
78644  sqlite3 *db = pParse->db;
78645  int iDb;
78646  int rc;
78647  int cookie;
78648
78649  assert( pParse->checkSchema );
78650  assert( sqlite3_mutex_held(db->mutex) );
78651  for(iDb=0; iDb<db->nDb; iDb++){
78652    int openedTransaction = 0;         /* True if a transaction is opened */
78653    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
78654    if( pBt==0 ) continue;
78655
78656    /* If there is not already a read-only (or read-write) transaction opened
78657    ** on the b-tree database, open one now. If a transaction is opened, it
78658    ** will be closed immediately after reading the meta-value. */
78659    if( !sqlite3BtreeIsInReadTrans(pBt) ){
78660      rc = sqlite3BtreeBeginTrans(pBt, 0);
78661      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
78662        db->mallocFailed = 1;
78663      }
78664      if( rc!=SQLITE_OK ) return;
78665      openedTransaction = 1;
78666    }
78667
78668    /* Read the schema cookie from the database. If it does not match the
78669    ** value stored as part of the in-memory schema representation,
78670    ** set Parse.rc to SQLITE_SCHEMA. */
78671    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
78672    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
78673      pParse->rc = SQLITE_SCHEMA;
78674    }
78675
78676    /* Close the transaction, if one was opened. */
78677    if( openedTransaction ){
78678      sqlite3BtreeCommit(pBt);
78679    }
78680  }
78681}
78682
78683/*
78684** Convert a schema pointer into the iDb index that indicates
78685** which database file in db->aDb[] the schema refers to.
78686**
78687** If the same database is attached more than once, the first
78688** attached database is returned.
78689*/
78690SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
78691  int i = -1000000;
78692
78693  /* If pSchema is NULL, then return -1000000. This happens when code in
78694  ** expr.c is trying to resolve a reference to a transient table (i.e. one
78695  ** created by a sub-select). In this case the return value of this
78696  ** function should never be used.
78697  **
78698  ** We return -1000000 instead of the more usual -1 simply because using
78699  ** -1000000 as the incorrect index into db->aDb[] is much
78700  ** more likely to cause a segfault than -1 (of course there are assert()
78701  ** statements too, but it never hurts to play the odds).
78702  */
78703  assert( sqlite3_mutex_held(db->mutex) );
78704  if( pSchema ){
78705    for(i=0; ALWAYS(i<db->nDb); i++){
78706      if( db->aDb[i].pSchema==pSchema ){
78707        break;
78708      }
78709    }
78710    assert( i>=0 && i<db->nDb );
78711  }
78712  return i;
78713}
78714
78715/*
78716** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
78717*/
78718static int sqlite3Prepare(
78719  sqlite3 *db,              /* Database handle. */
78720  const char *zSql,         /* UTF-8 encoded SQL statement. */
78721  int nBytes,               /* Length of zSql in bytes. */
78722  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
78723  Vdbe *pReprepare,         /* VM being reprepared */
78724  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78725  const char **pzTail       /* OUT: End of parsed string */
78726){
78727  Parse *pParse;            /* Parsing context */
78728  char *zErrMsg = 0;        /* Error message */
78729  int rc = SQLITE_OK;       /* Result code */
78730  int i;                    /* Loop counter */
78731
78732  /* Allocate the parsing context */
78733  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
78734  if( pParse==0 ){
78735    rc = SQLITE_NOMEM;
78736    goto end_prepare;
78737  }
78738  pParse->pReprepare = pReprepare;
78739
78740  if( sqlite3SafetyOn(db) ){
78741    rc = SQLITE_MISUSE;
78742    goto end_prepare;
78743  }
78744  assert( ppStmt && *ppStmt==0 );
78745  assert( !db->mallocFailed );
78746  assert( sqlite3_mutex_held(db->mutex) );
78747
78748  /* Check to verify that it is possible to get a read lock on all
78749  ** database schemas.  The inability to get a read lock indicates that
78750  ** some other database connection is holding a write-lock, which in
78751  ** turn means that the other connection has made uncommitted changes
78752  ** to the schema.
78753  **
78754  ** Were we to proceed and prepare the statement against the uncommitted
78755  ** schema changes and if those schema changes are subsequently rolled
78756  ** back and different changes are made in their place, then when this
78757  ** prepared statement goes to run the schema cookie would fail to detect
78758  ** the schema change.  Disaster would follow.
78759  **
78760  ** This thread is currently holding mutexes on all Btrees (because
78761  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
78762  ** is not possible for another thread to start a new schema change
78763  ** while this routine is running.  Hence, we do not need to hold
78764  ** locks on the schema, we just need to make sure nobody else is
78765  ** holding them.
78766  **
78767  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
78768  ** but it does *not* override schema lock detection, so this all still
78769  ** works even if READ_UNCOMMITTED is set.
78770  */
78771  for(i=0; i<db->nDb; i++) {
78772    Btree *pBt = db->aDb[i].pBt;
78773    if( pBt ){
78774      assert( sqlite3BtreeHoldsMutex(pBt) );
78775      rc = sqlite3BtreeSchemaLocked(pBt);
78776      if( rc ){
78777        const char *zDb = db->aDb[i].zName;
78778        sqlite3Error(db, rc, "database schema is locked: %s", zDb);
78779        (void)sqlite3SafetyOff(db);
78780        testcase( db->flags & SQLITE_ReadUncommitted );
78781        goto end_prepare;
78782      }
78783    }
78784  }
78785
78786  sqlite3VtabUnlockList(db);
78787
78788  pParse->db = db;
78789  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
78790    char *zSqlCopy;
78791    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
78792    testcase( nBytes==mxLen );
78793    testcase( nBytes==mxLen+1 );
78794    if( nBytes>mxLen ){
78795      sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
78796      (void)sqlite3SafetyOff(db);
78797      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
78798      goto end_prepare;
78799    }
78800    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
78801    if( zSqlCopy ){
78802      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
78803      sqlite3DbFree(db, zSqlCopy);
78804      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
78805    }else{
78806      pParse->zTail = &zSql[nBytes];
78807    }
78808  }else{
78809    sqlite3RunParser(pParse, zSql, &zErrMsg);
78810  }
78811
78812  if( db->mallocFailed ){
78813    pParse->rc = SQLITE_NOMEM;
78814  }
78815  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
78816  if( pParse->checkSchema ){
78817    schemaIsValid(pParse);
78818  }
78819  if( pParse->rc==SQLITE_SCHEMA ){
78820    sqlite3ResetInternalSchema(db, 0);
78821  }
78822  if( db->mallocFailed ){
78823    pParse->rc = SQLITE_NOMEM;
78824  }
78825  if( pzTail ){
78826    *pzTail = pParse->zTail;
78827  }
78828  rc = pParse->rc;
78829
78830#ifndef SQLITE_OMIT_EXPLAIN
78831  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
78832    static const char * const azColName[] = {
78833       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
78834       "order", "from", "detail"
78835    };
78836    int iFirst, mx;
78837    if( pParse->explain==2 ){
78838      sqlite3VdbeSetNumCols(pParse->pVdbe, 3);
78839      iFirst = 8;
78840      mx = 11;
78841    }else{
78842      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
78843      iFirst = 0;
78844      mx = 8;
78845    }
78846    for(i=iFirst; i<mx; i++){
78847      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
78848                            azColName[i], SQLITE_STATIC);
78849    }
78850  }
78851#endif
78852
78853  if( sqlite3SafetyOff(db) ){
78854    rc = SQLITE_MISUSE;
78855  }
78856
78857  assert( db->init.busy==0 || saveSqlFlag==0 );
78858  if( db->init.busy==0 ){
78859    Vdbe *pVdbe = pParse->pVdbe;
78860    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
78861  }
78862  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
78863    sqlite3VdbeFinalize(pParse->pVdbe);
78864    assert(!(*ppStmt));
78865  }else{
78866    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
78867  }
78868
78869  if( zErrMsg ){
78870    sqlite3Error(db, rc, "%s", zErrMsg);
78871    sqlite3DbFree(db, zErrMsg);
78872  }else{
78873    sqlite3Error(db, rc, 0);
78874  }
78875
78876  /* Delete any TriggerPrg structures allocated while parsing this statement. */
78877  while( pParse->pTriggerPrg ){
78878    TriggerPrg *pT = pParse->pTriggerPrg;
78879    pParse->pTriggerPrg = pT->pNext;
78880    sqlite3VdbeProgramDelete(db, pT->pProgram, 0);
78881    sqlite3DbFree(db, pT);
78882  }
78883
78884end_prepare:
78885
78886  sqlite3StackFree(db, pParse);
78887  rc = sqlite3ApiExit(db, rc);
78888  assert( (rc&db->errMask)==rc );
78889  return rc;
78890}
78891static int sqlite3LockAndPrepare(
78892  sqlite3 *db,              /* Database handle. */
78893  const char *zSql,         /* UTF-8 encoded SQL statement. */
78894  int nBytes,               /* Length of zSql in bytes. */
78895  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
78896  Vdbe *pOld,               /* VM being reprepared */
78897  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78898  const char **pzTail       /* OUT: End of parsed string */
78899){
78900  int rc;
78901  assert( ppStmt!=0 );
78902  *ppStmt = 0;
78903  if( !sqlite3SafetyCheckOk(db) ){
78904    return SQLITE_MISUSE;
78905  }
78906  sqlite3_mutex_enter(db->mutex);
78907  sqlite3BtreeEnterAll(db);
78908  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
78909  if( rc==SQLITE_SCHEMA ){
78910    sqlite3_finalize(*ppStmt);
78911    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
78912  }
78913  sqlite3BtreeLeaveAll(db);
78914  sqlite3_mutex_leave(db->mutex);
78915  return rc;
78916}
78917
78918/*
78919** Rerun the compilation of a statement after a schema change.
78920**
78921** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
78922** if the statement cannot be recompiled because another connection has
78923** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
78924** occurs, return SQLITE_SCHEMA.
78925*/
78926SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
78927  int rc;
78928  sqlite3_stmt *pNew;
78929  const char *zSql;
78930  sqlite3 *db;
78931
78932  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
78933  zSql = sqlite3_sql((sqlite3_stmt *)p);
78934  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
78935  db = sqlite3VdbeDb(p);
78936  assert( sqlite3_mutex_held(db->mutex) );
78937  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
78938  if( rc ){
78939    if( rc==SQLITE_NOMEM ){
78940      db->mallocFailed = 1;
78941    }
78942    assert( pNew==0 );
78943    return (rc==SQLITE_LOCKED) ? SQLITE_LOCKED : SQLITE_SCHEMA;
78944  }else{
78945    assert( pNew!=0 );
78946  }
78947  sqlite3VdbeSwap((Vdbe*)pNew, p);
78948  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
78949  sqlite3VdbeResetStepResult((Vdbe*)pNew);
78950  sqlite3VdbeFinalize((Vdbe*)pNew);
78951  return SQLITE_OK;
78952}
78953
78954
78955/*
78956** Two versions of the official API.  Legacy and new use.  In the legacy
78957** version, the original SQL text is not saved in the prepared statement
78958** and so if a schema change occurs, SQLITE_SCHEMA is returned by
78959** sqlite3_step().  In the new version, the original SQL text is retained
78960** and the statement is automatically recompiled if an schema change
78961** occurs.
78962*/
78963SQLITE_API int sqlite3_prepare(
78964  sqlite3 *db,              /* Database handle. */
78965  const char *zSql,         /* UTF-8 encoded SQL statement. */
78966  int nBytes,               /* Length of zSql in bytes. */
78967  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78968  const char **pzTail       /* OUT: End of parsed string */
78969){
78970  int rc;
78971  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
78972  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
78973  return rc;
78974}
78975SQLITE_API int sqlite3_prepare_v2(
78976  sqlite3 *db,              /* Database handle. */
78977  const char *zSql,         /* UTF-8 encoded SQL statement. */
78978  int nBytes,               /* Length of zSql in bytes. */
78979  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78980  const char **pzTail       /* OUT: End of parsed string */
78981){
78982  int rc;
78983  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
78984  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
78985  return rc;
78986}
78987
78988
78989#ifndef SQLITE_OMIT_UTF16
78990/*
78991** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
78992*/
78993static int sqlite3Prepare16(
78994  sqlite3 *db,              /* Database handle. */
78995  const void *zSql,         /* UTF-8 encoded SQL statement. */
78996  int nBytes,               /* Length of zSql in bytes. */
78997  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
78998  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78999  const void **pzTail       /* OUT: End of parsed string */
79000){
79001  /* This function currently works by first transforming the UTF-16
79002  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
79003  ** tricky bit is figuring out the pointer to return in *pzTail.
79004  */
79005  char *zSql8;
79006  const char *zTail8 = 0;
79007  int rc = SQLITE_OK;
79008
79009  assert( ppStmt );
79010  *ppStmt = 0;
79011  if( !sqlite3SafetyCheckOk(db) ){
79012    return SQLITE_MISUSE;
79013  }
79014  sqlite3_mutex_enter(db->mutex);
79015  zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
79016  if( zSql8 ){
79017    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
79018  }
79019
79020  if( zTail8 && pzTail ){
79021    /* If sqlite3_prepare returns a tail pointer, we calculate the
79022    ** equivalent pointer into the UTF-16 string by counting the unicode
79023    ** characters between zSql8 and zTail8, and then returning a pointer
79024    ** the same number of characters into the UTF-16 string.
79025    */
79026    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
79027    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
79028  }
79029  sqlite3DbFree(db, zSql8);
79030  rc = sqlite3ApiExit(db, rc);
79031  sqlite3_mutex_leave(db->mutex);
79032  return rc;
79033}
79034
79035/*
79036** Two versions of the official API.  Legacy and new use.  In the legacy
79037** version, the original SQL text is not saved in the prepared statement
79038** and so if a schema change occurs, SQLITE_SCHEMA is returned by
79039** sqlite3_step().  In the new version, the original SQL text is retained
79040** and the statement is automatically recompiled if an schema change
79041** occurs.
79042*/
79043SQLITE_API int sqlite3_prepare16(
79044  sqlite3 *db,              /* Database handle. */
79045  const void *zSql,         /* UTF-8 encoded SQL statement. */
79046  int nBytes,               /* Length of zSql in bytes. */
79047  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
79048  const void **pzTail       /* OUT: End of parsed string */
79049){
79050  int rc;
79051  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
79052  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
79053  return rc;
79054}
79055SQLITE_API int sqlite3_prepare16_v2(
79056  sqlite3 *db,              /* Database handle. */
79057  const void *zSql,         /* UTF-8 encoded SQL statement. */
79058  int nBytes,               /* Length of zSql in bytes. */
79059  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
79060  const void **pzTail       /* OUT: End of parsed string */
79061){
79062  int rc;
79063  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
79064  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
79065  return rc;
79066}
79067
79068#endif /* SQLITE_OMIT_UTF16 */
79069
79070/************** End of prepare.c *********************************************/
79071/************** Begin file select.c ******************************************/
79072/*
79073** 2001 September 15
79074**
79075** The author disclaims copyright to this source code.  In place of
79076** a legal notice, here is a blessing:
79077**
79078**    May you do good and not evil.
79079**    May you find forgiveness for yourself and forgive others.
79080**    May you share freely, never taking more than you give.
79081**
79082*************************************************************************
79083** This file contains C code routines that are called by the parser
79084** to handle SELECT statements in SQLite.
79085*/
79086
79087
79088/*
79089** Delete all the content of a Select structure but do not deallocate
79090** the select structure itself.
79091*/
79092static void clearSelect(sqlite3 *db, Select *p){
79093  sqlite3ExprListDelete(db, p->pEList);
79094  sqlite3SrcListDelete(db, p->pSrc);
79095  sqlite3ExprDelete(db, p->pWhere);
79096  sqlite3ExprListDelete(db, p->pGroupBy);
79097  sqlite3ExprDelete(db, p->pHaving);
79098  sqlite3ExprListDelete(db, p->pOrderBy);
79099  sqlite3SelectDelete(db, p->pPrior);
79100  sqlite3ExprDelete(db, p->pLimit);
79101  sqlite3ExprDelete(db, p->pOffset);
79102}
79103
79104/*
79105** Initialize a SelectDest structure.
79106*/
79107SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
79108  pDest->eDest = (u8)eDest;
79109  pDest->iParm = iParm;
79110  pDest->affinity = 0;
79111  pDest->iMem = 0;
79112  pDest->nMem = 0;
79113}
79114
79115
79116/*
79117** Allocate a new Select structure and return a pointer to that
79118** structure.
79119*/
79120SQLITE_PRIVATE Select *sqlite3SelectNew(
79121  Parse *pParse,        /* Parsing context */
79122  ExprList *pEList,     /* which columns to include in the result */
79123  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
79124  Expr *pWhere,         /* the WHERE clause */
79125  ExprList *pGroupBy,   /* the GROUP BY clause */
79126  Expr *pHaving,        /* the HAVING clause */
79127  ExprList *pOrderBy,   /* the ORDER BY clause */
79128  int isDistinct,       /* true if the DISTINCT keyword is present */
79129  Expr *pLimit,         /* LIMIT value.  NULL means not used */
79130  Expr *pOffset         /* OFFSET value.  NULL means no offset */
79131){
79132  Select *pNew;
79133  Select standin;
79134  sqlite3 *db = pParse->db;
79135  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
79136  assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
79137  if( pNew==0 ){
79138    pNew = &standin;
79139    memset(pNew, 0, sizeof(*pNew));
79140  }
79141  if( pEList==0 ){
79142    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
79143  }
79144  pNew->pEList = pEList;
79145  pNew->pSrc = pSrc;
79146  pNew->pWhere = pWhere;
79147  pNew->pGroupBy = pGroupBy;
79148  pNew->pHaving = pHaving;
79149  pNew->pOrderBy = pOrderBy;
79150  pNew->selFlags = isDistinct ? SF_Distinct : 0;
79151  pNew->op = TK_SELECT;
79152  pNew->pLimit = pLimit;
79153  pNew->pOffset = pOffset;
79154  assert( pOffset==0 || pLimit!=0 );
79155  pNew->addrOpenEphm[0] = -1;
79156  pNew->addrOpenEphm[1] = -1;
79157  pNew->addrOpenEphm[2] = -1;
79158  if( db->mallocFailed ) {
79159    clearSelect(db, pNew);
79160    if( pNew!=&standin ) sqlite3DbFree(db, pNew);
79161    pNew = 0;
79162  }
79163  return pNew;
79164}
79165
79166/*
79167** Delete the given Select structure and all of its substructures.
79168*/
79169SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
79170  if( p ){
79171    clearSelect(db, p);
79172    sqlite3DbFree(db, p);
79173  }
79174}
79175
79176/*
79177** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
79178** type of join.  Return an integer constant that expresses that type
79179** in terms of the following bit values:
79180**
79181**     JT_INNER
79182**     JT_CROSS
79183**     JT_OUTER
79184**     JT_NATURAL
79185**     JT_LEFT
79186**     JT_RIGHT
79187**
79188** A full outer join is the combination of JT_LEFT and JT_RIGHT.
79189**
79190** If an illegal or unsupported join type is seen, then still return
79191** a join type, but put an error in the pParse structure.
79192*/
79193SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
79194  int jointype = 0;
79195  Token *apAll[3];
79196  Token *p;
79197                             /*   0123456789 123456789 123456789 123 */
79198  static const char zKeyText[] = "naturaleftouterightfullinnercross";
79199  static const struct {
79200    u8 i;        /* Beginning of keyword text in zKeyText[] */
79201    u8 nChar;    /* Length of the keyword in characters */
79202    u8 code;     /* Join type mask */
79203  } aKeyword[] = {
79204    /* natural */ { 0,  7, JT_NATURAL                },
79205    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
79206    /* outer   */ { 10, 5, JT_OUTER                  },
79207    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
79208    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
79209    /* inner   */ { 23, 5, JT_INNER                  },
79210    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
79211  };
79212  int i, j;
79213  apAll[0] = pA;
79214  apAll[1] = pB;
79215  apAll[2] = pC;
79216  for(i=0; i<3 && apAll[i]; i++){
79217    p = apAll[i];
79218    for(j=0; j<ArraySize(aKeyword); j++){
79219      if( p->n==aKeyword[j].nChar
79220          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
79221        jointype |= aKeyword[j].code;
79222        break;
79223      }
79224    }
79225    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
79226    if( j>=ArraySize(aKeyword) ){
79227      jointype |= JT_ERROR;
79228      break;
79229    }
79230  }
79231  if(
79232     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
79233     (jointype & JT_ERROR)!=0
79234  ){
79235    const char *zSp = " ";
79236    assert( pB!=0 );
79237    if( pC==0 ){ zSp++; }
79238    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
79239       "%T %T%s%T", pA, pB, zSp, pC);
79240    jointype = JT_INNER;
79241  }else if( (jointype & JT_OUTER)!=0
79242         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
79243    sqlite3ErrorMsg(pParse,
79244      "RIGHT and FULL OUTER JOINs are not currently supported");
79245    jointype = JT_INNER;
79246  }
79247  return jointype;
79248}
79249
79250/*
79251** Return the index of a column in a table.  Return -1 if the column
79252** is not contained in the table.
79253*/
79254static int columnIndex(Table *pTab, const char *zCol){
79255  int i;
79256  for(i=0; i<pTab->nCol; i++){
79257    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
79258  }
79259  return -1;
79260}
79261
79262/*
79263** Search the first N tables in pSrc, from left to right, looking for a
79264** table that has a column named zCol.
79265**
79266** When found, set *piTab and *piCol to the table index and column index
79267** of the matching column and return TRUE.
79268**
79269** If not found, return FALSE.
79270*/
79271static int tableAndColumnIndex(
79272  SrcList *pSrc,       /* Array of tables to search */
79273  int N,               /* Number of tables in pSrc->a[] to search */
79274  const char *zCol,    /* Name of the column we are looking for */
79275  int *piTab,          /* Write index of pSrc->a[] here */
79276  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
79277){
79278  int i;               /* For looping over tables in pSrc */
79279  int iCol;            /* Index of column matching zCol */
79280
79281  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
79282  for(i=0; i<N; i++){
79283    iCol = columnIndex(pSrc->a[i].pTab, zCol);
79284    if( iCol>=0 ){
79285      if( piTab ){
79286        *piTab = i;
79287        *piCol = iCol;
79288      }
79289      return 1;
79290    }
79291  }
79292  return 0;
79293}
79294
79295/*
79296** This function is used to add terms implied by JOIN syntax to the
79297** WHERE clause expression of a SELECT statement. The new term, which
79298** is ANDed with the existing WHERE clause, is of the form:
79299**
79300**    (tab1.col1 = tab2.col2)
79301**
79302** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
79303** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
79304** column iColRight of tab2.
79305*/
79306static void addWhereTerm(
79307  Parse *pParse,                  /* Parsing context */
79308  SrcList *pSrc,                  /* List of tables in FROM clause */
79309  int iLeft,                      /* Index of first table to join in pSrc */
79310  int iColLeft,                   /* Index of column in first table */
79311  int iRight,                     /* Index of second table in pSrc */
79312  int iColRight,                  /* Index of column in second table */
79313  int isOuterJoin,                /* True if this is an OUTER join */
79314  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
79315){
79316  sqlite3 *db = pParse->db;
79317  Expr *pE1;
79318  Expr *pE2;
79319  Expr *pEq;
79320
79321  assert( iLeft<iRight );
79322  assert( pSrc->nSrc>iRight );
79323  assert( pSrc->a[iLeft].pTab );
79324  assert( pSrc->a[iRight].pTab );
79325
79326  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
79327  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
79328
79329  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
79330  if( pEq && isOuterJoin ){
79331    ExprSetProperty(pEq, EP_FromJoin);
79332    assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
79333    ExprSetIrreducible(pEq);
79334    pEq->iRightJoinTable = (i16)pE2->iTable;
79335  }
79336  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
79337}
79338
79339/*
79340** Set the EP_FromJoin property on all terms of the given expression.
79341** And set the Expr.iRightJoinTable to iTable for every term in the
79342** expression.
79343**
79344** The EP_FromJoin property is used on terms of an expression to tell
79345** the LEFT OUTER JOIN processing logic that this term is part of the
79346** join restriction specified in the ON or USING clause and not a part
79347** of the more general WHERE clause.  These terms are moved over to the
79348** WHERE clause during join processing but we need to remember that they
79349** originated in the ON or USING clause.
79350**
79351** The Expr.iRightJoinTable tells the WHERE clause processing that the
79352** expression depends on table iRightJoinTable even if that table is not
79353** explicitly mentioned in the expression.  That information is needed
79354** for cases like this:
79355**
79356**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
79357**
79358** The where clause needs to defer the handling of the t1.x=5
79359** term until after the t2 loop of the join.  In that way, a
79360** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
79361** defer the handling of t1.x=5, it will be processed immediately
79362** after the t1 loop and rows with t1.x!=5 will never appear in
79363** the output, which is incorrect.
79364*/
79365static void setJoinExpr(Expr *p, int iTable){
79366  while( p ){
79367    ExprSetProperty(p, EP_FromJoin);
79368    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
79369    ExprSetIrreducible(p);
79370    p->iRightJoinTable = (i16)iTable;
79371    setJoinExpr(p->pLeft, iTable);
79372    p = p->pRight;
79373  }
79374}
79375
79376/*
79377** This routine processes the join information for a SELECT statement.
79378** ON and USING clauses are converted into extra terms of the WHERE clause.
79379** NATURAL joins also create extra WHERE clause terms.
79380**
79381** The terms of a FROM clause are contained in the Select.pSrc structure.
79382** The left most table is the first entry in Select.pSrc.  The right-most
79383** table is the last entry.  The join operator is held in the entry to
79384** the left.  Thus entry 0 contains the join operator for the join between
79385** entries 0 and 1.  Any ON or USING clauses associated with the join are
79386** also attached to the left entry.
79387**
79388** This routine returns the number of errors encountered.
79389*/
79390static int sqliteProcessJoin(Parse *pParse, Select *p){
79391  SrcList *pSrc;                  /* All tables in the FROM clause */
79392  int i, j;                       /* Loop counters */
79393  struct SrcList_item *pLeft;     /* Left table being joined */
79394  struct SrcList_item *pRight;    /* Right table being joined */
79395
79396  pSrc = p->pSrc;
79397  pLeft = &pSrc->a[0];
79398  pRight = &pLeft[1];
79399  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
79400    Table *pLeftTab = pLeft->pTab;
79401    Table *pRightTab = pRight->pTab;
79402    int isOuter;
79403
79404    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
79405    isOuter = (pRight->jointype & JT_OUTER)!=0;
79406
79407    /* When the NATURAL keyword is present, add WHERE clause terms for
79408    ** every column that the two tables have in common.
79409    */
79410    if( pRight->jointype & JT_NATURAL ){
79411      if( pRight->pOn || pRight->pUsing ){
79412        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
79413           "an ON or USING clause", 0);
79414        return 1;
79415      }
79416      for(j=0; j<pRightTab->nCol; j++){
79417        char *zName;   /* Name of column in the right table */
79418        int iLeft;     /* Matching left table */
79419        int iLeftCol;  /* Matching column in the left table */
79420
79421        zName = pRightTab->aCol[j].zName;
79422        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
79423          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
79424                       isOuter, &p->pWhere);
79425        }
79426      }
79427    }
79428
79429    /* Disallow both ON and USING clauses in the same join
79430    */
79431    if( pRight->pOn && pRight->pUsing ){
79432      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
79433        "clauses in the same join");
79434      return 1;
79435    }
79436
79437    /* Add the ON clause to the end of the WHERE clause, connected by
79438    ** an AND operator.
79439    */
79440    if( pRight->pOn ){
79441      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
79442      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
79443      pRight->pOn = 0;
79444    }
79445
79446    /* Create extra terms on the WHERE clause for each column named
79447    ** in the USING clause.  Example: If the two tables to be joined are
79448    ** A and B and the USING clause names X, Y, and Z, then add this
79449    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
79450    ** Report an error if any column mentioned in the USING clause is
79451    ** not contained in both tables to be joined.
79452    */
79453    if( pRight->pUsing ){
79454      IdList *pList = pRight->pUsing;
79455      for(j=0; j<pList->nId; j++){
79456        char *zName;     /* Name of the term in the USING clause */
79457        int iLeft;       /* Table on the left with matching column name */
79458        int iLeftCol;    /* Column number of matching column on the left */
79459        int iRightCol;   /* Column number of matching column on the right */
79460
79461        zName = pList->a[j].zName;
79462        iRightCol = columnIndex(pRightTab, zName);
79463        if( iRightCol<0
79464         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
79465        ){
79466          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
79467            "not present in both tables", zName);
79468          return 1;
79469        }
79470        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
79471                     isOuter, &p->pWhere);
79472      }
79473    }
79474  }
79475  return 0;
79476}
79477
79478/*
79479** Insert code into "v" that will push the record on the top of the
79480** stack into the sorter.
79481*/
79482static void pushOntoSorter(
79483  Parse *pParse,         /* Parser context */
79484  ExprList *pOrderBy,    /* The ORDER BY clause */
79485  Select *pSelect,       /* The whole SELECT statement */
79486  int regData            /* Register holding data to be sorted */
79487){
79488  Vdbe *v = pParse->pVdbe;
79489  int nExpr = pOrderBy->nExpr;
79490  int regBase = sqlite3GetTempRange(pParse, nExpr+2);
79491  int regRecord = sqlite3GetTempReg(pParse);
79492  sqlite3ExprCacheClear(pParse);
79493  sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
79494  sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
79495  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
79496  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
79497  sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
79498  sqlite3ReleaseTempReg(pParse, regRecord);
79499  sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
79500  if( pSelect->iLimit ){
79501    int addr1, addr2;
79502    int iLimit;
79503    if( pSelect->iOffset ){
79504      iLimit = pSelect->iOffset+1;
79505    }else{
79506      iLimit = pSelect->iLimit;
79507    }
79508    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
79509    sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
79510    addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
79511    sqlite3VdbeJumpHere(v, addr1);
79512    sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
79513    sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
79514    sqlite3VdbeJumpHere(v, addr2);
79515    pSelect->iLimit = 0;
79516  }
79517}
79518
79519/*
79520** Add code to implement the OFFSET
79521*/
79522static void codeOffset(
79523  Vdbe *v,          /* Generate code into this VM */
79524  Select *p,        /* The SELECT statement being coded */
79525  int iContinue     /* Jump here to skip the current record */
79526){
79527  if( p->iOffset && iContinue!=0 ){
79528    int addr;
79529    sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
79530    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
79531    sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
79532    VdbeComment((v, "skip OFFSET records"));
79533    sqlite3VdbeJumpHere(v, addr);
79534  }
79535}
79536
79537/*
79538** Add code that will check to make sure the N registers starting at iMem
79539** form a distinct entry.  iTab is a sorting index that holds previously
79540** seen combinations of the N values.  A new entry is made in iTab
79541** if the current N values are new.
79542**
79543** A jump to addrRepeat is made and the N+1 values are popped from the
79544** stack if the top N elements are not distinct.
79545*/
79546static void codeDistinct(
79547  Parse *pParse,     /* Parsing and code generating context */
79548  int iTab,          /* A sorting index used to test for distinctness */
79549  int addrRepeat,    /* Jump to here if not distinct */
79550  int N,             /* Number of elements */
79551  int iMem           /* First element */
79552){
79553  Vdbe *v;
79554  int r1;
79555
79556  v = pParse->pVdbe;
79557  r1 = sqlite3GetTempReg(pParse);
79558  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
79559  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
79560  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
79561  sqlite3ReleaseTempReg(pParse, r1);
79562}
79563
79564/*
79565** Generate an error message when a SELECT is used within a subexpression
79566** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
79567** column.  We do this in a subroutine because the error occurs in multiple
79568** places.
79569*/
79570static int checkForMultiColumnSelectError(
79571  Parse *pParse,       /* Parse context. */
79572  SelectDest *pDest,   /* Destination of SELECT results */
79573  int nExpr            /* Number of result columns returned by SELECT */
79574){
79575  int eDest = pDest->eDest;
79576  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
79577    sqlite3ErrorMsg(pParse, "only a single result allowed for "
79578       "a SELECT that is part of an expression");
79579    return 1;
79580  }else{
79581    return 0;
79582  }
79583}
79584
79585/*
79586** This routine generates the code for the inside of the inner loop
79587** of a SELECT.
79588**
79589** If srcTab and nColumn are both zero, then the pEList expressions
79590** are evaluated in order to get the data for this row.  If nColumn>0
79591** then data is pulled from srcTab and pEList is used only to get the
79592** datatypes for each column.
79593*/
79594static void selectInnerLoop(
79595  Parse *pParse,          /* The parser context */
79596  Select *p,              /* The complete select statement being coded */
79597  ExprList *pEList,       /* List of values being extracted */
79598  int srcTab,             /* Pull data from this table */
79599  int nColumn,            /* Number of columns in the source table */
79600  ExprList *pOrderBy,     /* If not NULL, sort results using this key */
79601  int distinct,           /* If >=0, make sure results are distinct */
79602  SelectDest *pDest,      /* How to dispose of the results */
79603  int iContinue,          /* Jump here to continue with next row */
79604  int iBreak              /* Jump here to break out of the inner loop */
79605){
79606  Vdbe *v = pParse->pVdbe;
79607  int i;
79608  int hasDistinct;        /* True if the DISTINCT keyword is present */
79609  int regResult;              /* Start of memory holding result set */
79610  int eDest = pDest->eDest;   /* How to dispose of results */
79611  int iParm = pDest->iParm;   /* First argument to disposal method */
79612  int nResultCol;             /* Number of result columns */
79613
79614  assert( v );
79615  if( NEVER(v==0) ) return;
79616  assert( pEList!=0 );
79617  hasDistinct = distinct>=0;
79618  if( pOrderBy==0 && !hasDistinct ){
79619    codeOffset(v, p, iContinue);
79620  }
79621
79622  /* Pull the requested columns.
79623  */
79624  if( nColumn>0 ){
79625    nResultCol = nColumn;
79626  }else{
79627    nResultCol = pEList->nExpr;
79628  }
79629  if( pDest->iMem==0 ){
79630    pDest->iMem = pParse->nMem+1;
79631    pDest->nMem = nResultCol;
79632    pParse->nMem += nResultCol;
79633  }else{
79634    assert( pDest->nMem==nResultCol );
79635  }
79636  regResult = pDest->iMem;
79637  if( nColumn>0 ){
79638    for(i=0; i<nColumn; i++){
79639      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
79640    }
79641  }else if( eDest!=SRT_Exists ){
79642    /* If the destination is an EXISTS(...) expression, the actual
79643    ** values returned by the SELECT are not required.
79644    */
79645    sqlite3ExprCacheClear(pParse);
79646    sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
79647  }
79648  nColumn = nResultCol;
79649
79650  /* If the DISTINCT keyword was present on the SELECT statement
79651  ** and this row has been seen before, then do not make this row
79652  ** part of the result.
79653  */
79654  if( hasDistinct ){
79655    assert( pEList!=0 );
79656    assert( pEList->nExpr==nColumn );
79657    codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
79658    if( pOrderBy==0 ){
79659      codeOffset(v, p, iContinue);
79660    }
79661  }
79662
79663  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
79664    return;
79665  }
79666
79667  switch( eDest ){
79668    /* In this mode, write each query result to the key of the temporary
79669    ** table iParm.
79670    */
79671#ifndef SQLITE_OMIT_COMPOUND_SELECT
79672    case SRT_Union: {
79673      int r1;
79674      r1 = sqlite3GetTempReg(pParse);
79675      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
79676      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
79677      sqlite3ReleaseTempReg(pParse, r1);
79678      break;
79679    }
79680
79681    /* Construct a record from the query result, but instead of
79682    ** saving that record, use it as a key to delete elements from
79683    ** the temporary table iParm.
79684    */
79685    case SRT_Except: {
79686      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
79687      break;
79688    }
79689#endif
79690
79691    /* Store the result as data using a unique key.
79692    */
79693    case SRT_Table:
79694    case SRT_EphemTab: {
79695      int r1 = sqlite3GetTempReg(pParse);
79696      testcase( eDest==SRT_Table );
79697      testcase( eDest==SRT_EphemTab );
79698      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
79699      if( pOrderBy ){
79700        pushOntoSorter(pParse, pOrderBy, p, r1);
79701      }else{
79702        int r2 = sqlite3GetTempReg(pParse);
79703        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
79704        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
79705        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79706        sqlite3ReleaseTempReg(pParse, r2);
79707      }
79708      sqlite3ReleaseTempReg(pParse, r1);
79709      break;
79710    }
79711
79712#ifndef SQLITE_OMIT_SUBQUERY
79713    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
79714    ** then there should be a single item on the stack.  Write this
79715    ** item into the set table with bogus data.
79716    */
79717    case SRT_Set: {
79718      assert( nColumn==1 );
79719      p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
79720      if( pOrderBy ){
79721        /* At first glance you would think we could optimize out the
79722        ** ORDER BY in this case since the order of entries in the set
79723        ** does not matter.  But there might be a LIMIT clause, in which
79724        ** case the order does matter */
79725        pushOntoSorter(pParse, pOrderBy, p, regResult);
79726      }else{
79727        int r1 = sqlite3GetTempReg(pParse);
79728        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
79729        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
79730        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
79731        sqlite3ReleaseTempReg(pParse, r1);
79732      }
79733      break;
79734    }
79735
79736    /* If any row exist in the result set, record that fact and abort.
79737    */
79738    case SRT_Exists: {
79739      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
79740      /* The LIMIT clause will terminate the loop for us */
79741      break;
79742    }
79743
79744    /* If this is a scalar select that is part of an expression, then
79745    ** store the results in the appropriate memory cell and break out
79746    ** of the scan loop.
79747    */
79748    case SRT_Mem: {
79749      assert( nColumn==1 );
79750      if( pOrderBy ){
79751        pushOntoSorter(pParse, pOrderBy, p, regResult);
79752      }else{
79753        sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
79754        /* The LIMIT clause will jump out of the loop for us */
79755      }
79756      break;
79757    }
79758#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
79759
79760    /* Send the data to the callback function or to a subroutine.  In the
79761    ** case of a subroutine, the subroutine itself is responsible for
79762    ** popping the data from the stack.
79763    */
79764    case SRT_Coroutine:
79765    case SRT_Output: {
79766      testcase( eDest==SRT_Coroutine );
79767      testcase( eDest==SRT_Output );
79768      if( pOrderBy ){
79769        int r1 = sqlite3GetTempReg(pParse);
79770        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
79771        pushOntoSorter(pParse, pOrderBy, p, r1);
79772        sqlite3ReleaseTempReg(pParse, r1);
79773      }else if( eDest==SRT_Coroutine ){
79774        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
79775      }else{
79776        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
79777        sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
79778      }
79779      break;
79780    }
79781
79782#if !defined(SQLITE_OMIT_TRIGGER)
79783    /* Discard the results.  This is used for SELECT statements inside
79784    ** the body of a TRIGGER.  The purpose of such selects is to call
79785    ** user-defined functions that have side effects.  We do not care
79786    ** about the actual results of the select.
79787    */
79788    default: {
79789      assert( eDest==SRT_Discard );
79790      break;
79791    }
79792#endif
79793  }
79794
79795  /* Jump to the end of the loop if the LIMIT is reached.
79796  */
79797  if( p->iLimit ){
79798    assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
79799                            ** pushOntoSorter() would have cleared p->iLimit */
79800    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
79801  }
79802}
79803
79804/*
79805** Given an expression list, generate a KeyInfo structure that records
79806** the collating sequence for each expression in that expression list.
79807**
79808** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
79809** KeyInfo structure is appropriate for initializing a virtual index to
79810** implement that clause.  If the ExprList is the result set of a SELECT
79811** then the KeyInfo structure is appropriate for initializing a virtual
79812** index to implement a DISTINCT test.
79813**
79814** Space to hold the KeyInfo structure is obtain from malloc.  The calling
79815** function is responsible for seeing that this structure is eventually
79816** freed.  Add the KeyInfo structure to the P4 field of an opcode using
79817** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
79818*/
79819static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
79820  sqlite3 *db = pParse->db;
79821  int nExpr;
79822  KeyInfo *pInfo;
79823  struct ExprList_item *pItem;
79824  int i;
79825
79826  nExpr = pList->nExpr;
79827  pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
79828  if( pInfo ){
79829    pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
79830    pInfo->nField = (u16)nExpr;
79831    pInfo->enc = ENC(db);
79832    pInfo->db = db;
79833    for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
79834      CollSeq *pColl;
79835      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
79836      if( !pColl ){
79837        pColl = db->pDfltColl;
79838      }
79839      pInfo->aColl[i] = pColl;
79840      pInfo->aSortOrder[i] = pItem->sortOrder;
79841    }
79842  }
79843  return pInfo;
79844}
79845
79846
79847/*
79848** If the inner loop was generated using a non-null pOrderBy argument,
79849** then the results were placed in a sorter.  After the loop is terminated
79850** we need to run the sorter and output the results.  The following
79851** routine generates the code needed to do that.
79852*/
79853static void generateSortTail(
79854  Parse *pParse,    /* Parsing context */
79855  Select *p,        /* The SELECT statement */
79856  Vdbe *v,          /* Generate code into this VDBE */
79857  int nColumn,      /* Number of columns of data */
79858  SelectDest *pDest /* Write the sorted results here */
79859){
79860  int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
79861  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
79862  int addr;
79863  int iTab;
79864  int pseudoTab = 0;
79865  ExprList *pOrderBy = p->pOrderBy;
79866
79867  int eDest = pDest->eDest;
79868  int iParm = pDest->iParm;
79869
79870  int regRow;
79871  int regRowid;
79872
79873  iTab = pOrderBy->iECursor;
79874  regRow = sqlite3GetTempReg(pParse);
79875  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
79876    pseudoTab = pParse->nTab++;
79877    sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
79878    regRowid = 0;
79879  }else{
79880    regRowid = sqlite3GetTempReg(pParse);
79881  }
79882  addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
79883  codeOffset(v, p, addrContinue);
79884  sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
79885  switch( eDest ){
79886    case SRT_Table:
79887    case SRT_EphemTab: {
79888      testcase( eDest==SRT_Table );
79889      testcase( eDest==SRT_EphemTab );
79890      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
79891      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
79892      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79893      break;
79894    }
79895#ifndef SQLITE_OMIT_SUBQUERY
79896    case SRT_Set: {
79897      assert( nColumn==1 );
79898      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
79899      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
79900      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
79901      break;
79902    }
79903    case SRT_Mem: {
79904      assert( nColumn==1 );
79905      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
79906      /* The LIMIT clause will terminate the loop for us */
79907      break;
79908    }
79909#endif
79910    default: {
79911      int i;
79912      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
79913      testcase( eDest==SRT_Output );
79914      testcase( eDest==SRT_Coroutine );
79915      for(i=0; i<nColumn; i++){
79916        assert( regRow!=pDest->iMem+i );
79917        sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
79918        if( i==0 ){
79919          sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
79920        }
79921      }
79922      if( eDest==SRT_Output ){
79923        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
79924        sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
79925      }else{
79926        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
79927      }
79928      break;
79929    }
79930  }
79931  sqlite3ReleaseTempReg(pParse, regRow);
79932  sqlite3ReleaseTempReg(pParse, regRowid);
79933
79934  /* LIMIT has been implemented by the pushOntoSorter() routine.
79935  */
79936  assert( p->iLimit==0 );
79937
79938  /* The bottom of the loop
79939  */
79940  sqlite3VdbeResolveLabel(v, addrContinue);
79941  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
79942  sqlite3VdbeResolveLabel(v, addrBreak);
79943  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
79944    sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
79945  }
79946}
79947
79948/*
79949** Return a pointer to a string containing the 'declaration type' of the
79950** expression pExpr. The string may be treated as static by the caller.
79951**
79952** The declaration type is the exact datatype definition extracted from the
79953** original CREATE TABLE statement if the expression is a column. The
79954** declaration type for a ROWID field is INTEGER. Exactly when an expression
79955** is considered a column can be complex in the presence of subqueries. The
79956** result-set expression in all of the following SELECT statements is
79957** considered a column by this function.
79958**
79959**   SELECT col FROM tbl;
79960**   SELECT (SELECT col FROM tbl;
79961**   SELECT (SELECT col FROM tbl);
79962**   SELECT abc FROM (SELECT col AS abc FROM tbl);
79963**
79964** The declaration type for any expression other than a column is NULL.
79965*/
79966static const char *columnType(
79967  NameContext *pNC,
79968  Expr *pExpr,
79969  const char **pzOriginDb,
79970  const char **pzOriginTab,
79971  const char **pzOriginCol
79972){
79973  char const *zType = 0;
79974  char const *zOriginDb = 0;
79975  char const *zOriginTab = 0;
79976  char const *zOriginCol = 0;
79977  int j;
79978  if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
79979
79980  switch( pExpr->op ){
79981    case TK_AGG_COLUMN:
79982    case TK_COLUMN: {
79983      /* The expression is a column. Locate the table the column is being
79984      ** extracted from in NameContext.pSrcList. This table may be real
79985      ** database table or a subquery.
79986      */
79987      Table *pTab = 0;            /* Table structure column is extracted from */
79988      Select *pS = 0;             /* Select the column is extracted from */
79989      int iCol = pExpr->iColumn;  /* Index of column in pTab */
79990      testcase( pExpr->op==TK_AGG_COLUMN );
79991      testcase( pExpr->op==TK_COLUMN );
79992      while( pNC && !pTab ){
79993        SrcList *pTabList = pNC->pSrcList;
79994        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
79995        if( j<pTabList->nSrc ){
79996          pTab = pTabList->a[j].pTab;
79997          pS = pTabList->a[j].pSelect;
79998        }else{
79999          pNC = pNC->pNext;
80000        }
80001      }
80002
80003      if( pTab==0 ){
80004        /* At one time, code such as "SELECT new.x" within a trigger would
80005        ** cause this condition to run.  Since then, we have restructured how
80006        ** trigger code is generated and so this condition is no longer
80007        ** possible. However, it can still be true for statements like
80008        ** the following:
80009        **
80010        **   CREATE TABLE t1(col INTEGER);
80011        **   SELECT (SELECT t1.col) FROM FROM t1;
80012        **
80013        ** when columnType() is called on the expression "t1.col" in the
80014        ** sub-select. In this case, set the column type to NULL, even
80015        ** though it should really be "INTEGER".
80016        **
80017        ** This is not a problem, as the column type of "t1.col" is never
80018        ** used. When columnType() is called on the expression
80019        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
80020        ** branch below.  */
80021        break;
80022      }
80023
80024      assert( pTab && pExpr->pTab==pTab );
80025      if( pS ){
80026        /* The "table" is actually a sub-select or a view in the FROM clause
80027        ** of the SELECT statement. Return the declaration type and origin
80028        ** data for the result-set column of the sub-select.
80029        */
80030        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
80031          /* If iCol is less than zero, then the expression requests the
80032          ** rowid of the sub-select or view. This expression is legal (see
80033          ** test case misc2.2.2) - it always evaluates to NULL.
80034          */
80035          NameContext sNC;
80036          Expr *p = pS->pEList->a[iCol].pExpr;
80037          sNC.pSrcList = pS->pSrc;
80038          sNC.pNext = pNC;
80039          sNC.pParse = pNC->pParse;
80040          zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
80041        }
80042      }else if( ALWAYS(pTab->pSchema) ){
80043        /* A real table */
80044        assert( !pS );
80045        if( iCol<0 ) iCol = pTab->iPKey;
80046        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
80047        if( iCol<0 ){
80048          zType = "INTEGER";
80049          zOriginCol = "rowid";
80050        }else{
80051          zType = pTab->aCol[iCol].zType;
80052          zOriginCol = pTab->aCol[iCol].zName;
80053        }
80054        zOriginTab = pTab->zName;
80055        if( pNC->pParse ){
80056          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
80057          zOriginDb = pNC->pParse->db->aDb[iDb].zName;
80058        }
80059      }
80060      break;
80061    }
80062#ifndef SQLITE_OMIT_SUBQUERY
80063    case TK_SELECT: {
80064      /* The expression is a sub-select. Return the declaration type and
80065      ** origin info for the single column in the result set of the SELECT
80066      ** statement.
80067      */
80068      NameContext sNC;
80069      Select *pS = pExpr->x.pSelect;
80070      Expr *p = pS->pEList->a[0].pExpr;
80071      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
80072      sNC.pSrcList = pS->pSrc;
80073      sNC.pNext = pNC;
80074      sNC.pParse = pNC->pParse;
80075      zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
80076      break;
80077    }
80078#endif
80079  }
80080
80081  if( pzOriginDb ){
80082    assert( pzOriginTab && pzOriginCol );
80083    *pzOriginDb = zOriginDb;
80084    *pzOriginTab = zOriginTab;
80085    *pzOriginCol = zOriginCol;
80086  }
80087  return zType;
80088}
80089
80090/*
80091** Generate code that will tell the VDBE the declaration types of columns
80092** in the result set.
80093*/
80094static void generateColumnTypes(
80095  Parse *pParse,      /* Parser context */
80096  SrcList *pTabList,  /* List of tables */
80097  ExprList *pEList    /* Expressions defining the result set */
80098){
80099#ifndef SQLITE_OMIT_DECLTYPE
80100  Vdbe *v = pParse->pVdbe;
80101  int i;
80102  NameContext sNC;
80103  sNC.pSrcList = pTabList;
80104  sNC.pParse = pParse;
80105  for(i=0; i<pEList->nExpr; i++){
80106    Expr *p = pEList->a[i].pExpr;
80107    const char *zType;
80108#ifdef SQLITE_ENABLE_COLUMN_METADATA
80109    const char *zOrigDb = 0;
80110    const char *zOrigTab = 0;
80111    const char *zOrigCol = 0;
80112    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
80113
80114    /* The vdbe must make its own copy of the column-type and other
80115    ** column specific strings, in case the schema is reset before this
80116    ** virtual machine is deleted.
80117    */
80118    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
80119    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
80120    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
80121#else
80122    zType = columnType(&sNC, p, 0, 0, 0);
80123#endif
80124    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
80125  }
80126#endif /* SQLITE_OMIT_DECLTYPE */
80127}
80128
80129/*
80130** Generate code that will tell the VDBE the names of columns
80131** in the result set.  This information is used to provide the
80132** azCol[] values in the callback.
80133*/
80134static void generateColumnNames(
80135  Parse *pParse,      /* Parser context */
80136  SrcList *pTabList,  /* List of tables */
80137  ExprList *pEList    /* Expressions defining the result set */
80138){
80139  Vdbe *v = pParse->pVdbe;
80140  int i, j;
80141  sqlite3 *db = pParse->db;
80142  int fullNames, shortNames;
80143
80144#ifndef SQLITE_OMIT_EXPLAIN
80145  /* If this is an EXPLAIN, skip this step */
80146  if( pParse->explain ){
80147    return;
80148  }
80149#endif
80150
80151  if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
80152  pParse->colNamesSet = 1;
80153  fullNames = (db->flags & SQLITE_FullColNames)!=0;
80154  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
80155  sqlite3VdbeSetNumCols(v, pEList->nExpr);
80156  for(i=0; i<pEList->nExpr; i++){
80157    Expr *p;
80158    p = pEList->a[i].pExpr;
80159    if( NEVER(p==0) ) continue;
80160    if( pEList->a[i].zName ){
80161      char *zName = pEList->a[i].zName;
80162      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
80163    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
80164      Table *pTab;
80165      char *zCol;
80166      int iCol = p->iColumn;
80167      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
80168        if( pTabList->a[j].iCursor==p->iTable ) break;
80169      }
80170      assert( j<pTabList->nSrc );
80171      pTab = pTabList->a[j].pTab;
80172      if( iCol<0 ) iCol = pTab->iPKey;
80173      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
80174      if( iCol<0 ){
80175        zCol = "rowid";
80176      }else{
80177        zCol = pTab->aCol[iCol].zName;
80178      }
80179      if( !shortNames && !fullNames ){
80180        sqlite3VdbeSetColName(v, i, COLNAME_NAME,
80181            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
80182      }else if( fullNames ){
80183        char *zName = 0;
80184        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
80185        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
80186      }else{
80187        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
80188      }
80189    }else{
80190      sqlite3VdbeSetColName(v, i, COLNAME_NAME,
80191          sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
80192    }
80193  }
80194  generateColumnTypes(pParse, pTabList, pEList);
80195}
80196
80197#ifndef SQLITE_OMIT_COMPOUND_SELECT
80198/*
80199** Name of the connection operator, used for error messages.
80200*/
80201static const char *selectOpName(int id){
80202  char *z;
80203  switch( id ){
80204    case TK_ALL:       z = "UNION ALL";   break;
80205    case TK_INTERSECT: z = "INTERSECT";   break;
80206    case TK_EXCEPT:    z = "EXCEPT";      break;
80207    default:           z = "UNION";       break;
80208  }
80209  return z;
80210}
80211#endif /* SQLITE_OMIT_COMPOUND_SELECT */
80212
80213/*
80214** Given a an expression list (which is really the list of expressions
80215** that form the result set of a SELECT statement) compute appropriate
80216** column names for a table that would hold the expression list.
80217**
80218** All column names will be unique.
80219**
80220** Only the column names are computed.  Column.zType, Column.zColl,
80221** and other fields of Column are zeroed.
80222**
80223** Return SQLITE_OK on success.  If a memory allocation error occurs,
80224** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
80225*/
80226static int selectColumnsFromExprList(
80227  Parse *pParse,          /* Parsing context */
80228  ExprList *pEList,       /* Expr list from which to derive column names */
80229  int *pnCol,             /* Write the number of columns here */
80230  Column **paCol          /* Write the new column list here */
80231){
80232  sqlite3 *db = pParse->db;   /* Database connection */
80233  int i, j;                   /* Loop counters */
80234  int cnt;                    /* Index added to make the name unique */
80235  Column *aCol, *pCol;        /* For looping over result columns */
80236  int nCol;                   /* Number of columns in the result set */
80237  Expr *p;                    /* Expression for a single result column */
80238  char *zName;                /* Column name */
80239  int nName;                  /* Size of name in zName[] */
80240
80241  *pnCol = nCol = pEList->nExpr;
80242  aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
80243  if( aCol==0 ) return SQLITE_NOMEM;
80244  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
80245    /* Get an appropriate name for the column
80246    */
80247    p = pEList->a[i].pExpr;
80248    assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
80249               || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
80250    if( (zName = pEList->a[i].zName)!=0 ){
80251      /* If the column contains an "AS <name>" phrase, use <name> as the name */
80252      zName = sqlite3DbStrDup(db, zName);
80253    }else{
80254      Expr *pColExpr = p;  /* The expression that is the result column name */
80255      Table *pTab;         /* Table associated with this expression */
80256      while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
80257      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
80258        /* For columns use the column name name */
80259        int iCol = pColExpr->iColumn;
80260        pTab = pColExpr->pTab;
80261        if( iCol<0 ) iCol = pTab->iPKey;
80262        zName = sqlite3MPrintf(db, "%s",
80263                 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
80264      }else if( pColExpr->op==TK_ID ){
80265        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
80266        zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
80267      }else{
80268        /* Use the original text of the column expression as its name */
80269        zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
80270      }
80271    }
80272    if( db->mallocFailed ){
80273      sqlite3DbFree(db, zName);
80274      break;
80275    }
80276
80277    /* Make sure the column name is unique.  If the name is not unique,
80278    ** append a integer to the name so that it becomes unique.
80279    */
80280    nName = sqlite3Strlen30(zName);
80281    for(j=cnt=0; j<i; j++){
80282      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
80283        char *zNewName;
80284        zName[nName] = 0;
80285        zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
80286        sqlite3DbFree(db, zName);
80287        zName = zNewName;
80288        j = -1;
80289        if( zName==0 ) break;
80290      }
80291    }
80292    pCol->zName = zName;
80293  }
80294  if( db->mallocFailed ){
80295    for(j=0; j<i; j++){
80296      sqlite3DbFree(db, aCol[j].zName);
80297    }
80298    sqlite3DbFree(db, aCol);
80299    *paCol = 0;
80300    *pnCol = 0;
80301    return SQLITE_NOMEM;
80302  }
80303  return SQLITE_OK;
80304}
80305
80306/*
80307** Add type and collation information to a column list based on
80308** a SELECT statement.
80309**
80310** The column list presumably came from selectColumnNamesFromExprList().
80311** The column list has only names, not types or collations.  This
80312** routine goes through and adds the types and collations.
80313**
80314** This routine requires that all identifiers in the SELECT
80315** statement be resolved.
80316*/
80317static void selectAddColumnTypeAndCollation(
80318  Parse *pParse,        /* Parsing contexts */
80319  int nCol,             /* Number of columns */
80320  Column *aCol,         /* List of columns */
80321  Select *pSelect       /* SELECT used to determine types and collations */
80322){
80323  sqlite3 *db = pParse->db;
80324  NameContext sNC;
80325  Column *pCol;
80326  CollSeq *pColl;
80327  int i;
80328  Expr *p;
80329  struct ExprList_item *a;
80330
80331  assert( pSelect!=0 );
80332  assert( (pSelect->selFlags & SF_Resolved)!=0 );
80333  assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
80334  if( db->mallocFailed ) return;
80335  memset(&sNC, 0, sizeof(sNC));
80336  sNC.pSrcList = pSelect->pSrc;
80337  a = pSelect->pEList->a;
80338  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
80339    p = a[i].pExpr;
80340    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
80341    pCol->affinity = sqlite3ExprAffinity(p);
80342    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
80343    pColl = sqlite3ExprCollSeq(pParse, p);
80344    if( pColl ){
80345      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
80346    }
80347  }
80348}
80349
80350/*
80351** Given a SELECT statement, generate a Table structure that describes
80352** the result set of that SELECT.
80353*/
80354SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
80355  Table *pTab;
80356  sqlite3 *db = pParse->db;
80357  int savedFlags;
80358
80359  savedFlags = db->flags;
80360  db->flags &= ~SQLITE_FullColNames;
80361  db->flags |= SQLITE_ShortColNames;
80362  sqlite3SelectPrep(pParse, pSelect, 0);
80363  if( pParse->nErr ) return 0;
80364  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
80365  db->flags = savedFlags;
80366  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
80367  if( pTab==0 ){
80368    return 0;
80369  }
80370  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
80371  ** is disabled, so we might as well hard-code pTab->dbMem to NULL. */
80372  assert( db->lookaside.bEnabled==0 );
80373  pTab->dbMem = 0;
80374  pTab->nRef = 1;
80375  pTab->zName = 0;
80376  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
80377  selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
80378  pTab->iPKey = -1;
80379  if( db->mallocFailed ){
80380    sqlite3DeleteTable(pTab);
80381    return 0;
80382  }
80383  return pTab;
80384}
80385
80386/*
80387** Get a VDBE for the given parser context.  Create a new one if necessary.
80388** If an error occurs, return NULL and leave a message in pParse.
80389*/
80390SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
80391  Vdbe *v = pParse->pVdbe;
80392  if( v==0 ){
80393    v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
80394#ifndef SQLITE_OMIT_TRACE
80395    if( v ){
80396      sqlite3VdbeAddOp0(v, OP_Trace);
80397    }
80398#endif
80399  }
80400  return v;
80401}
80402
80403
80404/*
80405** Compute the iLimit and iOffset fields of the SELECT based on the
80406** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
80407** that appear in the original SQL statement after the LIMIT and OFFSET
80408** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
80409** are the integer memory register numbers for counters used to compute
80410** the limit and offset.  If there is no limit and/or offset, then
80411** iLimit and iOffset are negative.
80412**
80413** This routine changes the values of iLimit and iOffset only if
80414** a limit or offset is defined by pLimit and pOffset.  iLimit and
80415** iOffset should have been preset to appropriate default values
80416** (usually but not always -1) prior to calling this routine.
80417** Only if pLimit!=0 or pOffset!=0 do the limit registers get
80418** redefined.  The UNION ALL operator uses this property to force
80419** the reuse of the same limit and offset registers across multiple
80420** SELECT statements.
80421*/
80422static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
80423  Vdbe *v = 0;
80424  int iLimit = 0;
80425  int iOffset;
80426  int addr1, n;
80427  if( p->iLimit ) return;
80428
80429  /*
80430  ** "LIMIT -1" always shows all rows.  There is some
80431  ** contraversy about what the correct behavior should be.
80432  ** The current implementation interprets "LIMIT 0" to mean
80433  ** no rows.
80434  */
80435  sqlite3ExprCacheClear(pParse);
80436  assert( p->pOffset==0 || p->pLimit!=0 );
80437  if( p->pLimit ){
80438    p->iLimit = iLimit = ++pParse->nMem;
80439    v = sqlite3GetVdbe(pParse);
80440    if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
80441    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
80442      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
80443      VdbeComment((v, "LIMIT counter"));
80444      if( n==0 ){
80445        sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
80446      }
80447    }else{
80448      sqlite3ExprCode(pParse, p->pLimit, iLimit);
80449      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
80450      VdbeComment((v, "LIMIT counter"));
80451      sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
80452    }
80453    if( p->pOffset ){
80454      p->iOffset = iOffset = ++pParse->nMem;
80455      pParse->nMem++;   /* Allocate an extra register for limit+offset */
80456      sqlite3ExprCode(pParse, p->pOffset, iOffset);
80457      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
80458      VdbeComment((v, "OFFSET counter"));
80459      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
80460      sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
80461      sqlite3VdbeJumpHere(v, addr1);
80462      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
80463      VdbeComment((v, "LIMIT+OFFSET"));
80464      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
80465      sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
80466      sqlite3VdbeJumpHere(v, addr1);
80467    }
80468  }
80469}
80470
80471#ifndef SQLITE_OMIT_COMPOUND_SELECT
80472/*
80473** Return the appropriate collating sequence for the iCol-th column of
80474** the result set for the compound-select statement "p".  Return NULL if
80475** the column has no default collating sequence.
80476**
80477** The collating sequence for the compound select is taken from the
80478** left-most term of the select that has a collating sequence.
80479*/
80480static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
80481  CollSeq *pRet;
80482  if( p->pPrior ){
80483    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
80484  }else{
80485    pRet = 0;
80486  }
80487  assert( iCol>=0 );
80488  if( pRet==0 && iCol<p->pEList->nExpr ){
80489    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
80490  }
80491  return pRet;
80492}
80493#endif /* SQLITE_OMIT_COMPOUND_SELECT */
80494
80495/* Forward reference */
80496static int multiSelectOrderBy(
80497  Parse *pParse,        /* Parsing context */
80498  Select *p,            /* The right-most of SELECTs to be coded */
80499  SelectDest *pDest     /* What to do with query results */
80500);
80501
80502
80503#ifndef SQLITE_OMIT_COMPOUND_SELECT
80504/*
80505** This routine is called to process a compound query form from
80506** two or more separate queries using UNION, UNION ALL, EXCEPT, or
80507** INTERSECT
80508**
80509** "p" points to the right-most of the two queries.  the query on the
80510** left is p->pPrior.  The left query could also be a compound query
80511** in which case this routine will be called recursively.
80512**
80513** The results of the total query are to be written into a destination
80514** of type eDest with parameter iParm.
80515**
80516** Example 1:  Consider a three-way compound SQL statement.
80517**
80518**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
80519**
80520** This statement is parsed up as follows:
80521**
80522**     SELECT c FROM t3
80523**      |
80524**      `----->  SELECT b FROM t2
80525**                |
80526**                `------>  SELECT a FROM t1
80527**
80528** The arrows in the diagram above represent the Select.pPrior pointer.
80529** So if this routine is called with p equal to the t3 query, then
80530** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
80531**
80532** Notice that because of the way SQLite parses compound SELECTs, the
80533** individual selects always group from left to right.
80534*/
80535static int multiSelect(
80536  Parse *pParse,        /* Parsing context */
80537  Select *p,            /* The right-most of SELECTs to be coded */
80538  SelectDest *pDest     /* What to do with query results */
80539){
80540  int rc = SQLITE_OK;   /* Success code from a subroutine */
80541  Select *pPrior;       /* Another SELECT immediately to our left */
80542  Vdbe *v;              /* Generate code to this VDBE */
80543  SelectDest dest;      /* Alternative data destination */
80544  Select *pDelete = 0;  /* Chain of simple selects to delete */
80545  sqlite3 *db;          /* Database connection */
80546
80547  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
80548  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
80549  */
80550  assert( p && p->pPrior );  /* Calling function guarantees this much */
80551  db = pParse->db;
80552  pPrior = p->pPrior;
80553  assert( pPrior->pRightmost!=pPrior );
80554  assert( pPrior->pRightmost==p->pRightmost );
80555  dest = *pDest;
80556  if( pPrior->pOrderBy ){
80557    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
80558      selectOpName(p->op));
80559    rc = 1;
80560    goto multi_select_end;
80561  }
80562  if( pPrior->pLimit ){
80563    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
80564      selectOpName(p->op));
80565    rc = 1;
80566    goto multi_select_end;
80567  }
80568
80569  v = sqlite3GetVdbe(pParse);
80570  assert( v!=0 );  /* The VDBE already created by calling function */
80571
80572  /* Create the destination temporary table if necessary
80573  */
80574  if( dest.eDest==SRT_EphemTab ){
80575    assert( p->pEList );
80576    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
80577    dest.eDest = SRT_Table;
80578  }
80579
80580  /* Make sure all SELECTs in the statement have the same number of elements
80581  ** in their result sets.
80582  */
80583  assert( p->pEList && pPrior->pEList );
80584  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
80585    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
80586      " do not have the same number of result columns", selectOpName(p->op));
80587    rc = 1;
80588    goto multi_select_end;
80589  }
80590
80591  /* Compound SELECTs that have an ORDER BY clause are handled separately.
80592  */
80593  if( p->pOrderBy ){
80594    return multiSelectOrderBy(pParse, p, pDest);
80595  }
80596
80597  /* Generate code for the left and right SELECT statements.
80598  */
80599  switch( p->op ){
80600    case TK_ALL: {
80601      int addr = 0;
80602      assert( !pPrior->pLimit );
80603      pPrior->pLimit = p->pLimit;
80604      pPrior->pOffset = p->pOffset;
80605      rc = sqlite3Select(pParse, pPrior, &dest);
80606      p->pLimit = 0;
80607      p->pOffset = 0;
80608      if( rc ){
80609        goto multi_select_end;
80610      }
80611      p->pPrior = 0;
80612      p->iLimit = pPrior->iLimit;
80613      p->iOffset = pPrior->iOffset;
80614      if( p->iLimit ){
80615        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
80616        VdbeComment((v, "Jump ahead if LIMIT reached"));
80617      }
80618      rc = sqlite3Select(pParse, p, &dest);
80619      testcase( rc!=SQLITE_OK );
80620      pDelete = p->pPrior;
80621      p->pPrior = pPrior;
80622      if( addr ){
80623        sqlite3VdbeJumpHere(v, addr);
80624      }
80625      break;
80626    }
80627    case TK_EXCEPT:
80628    case TK_UNION: {
80629      int unionTab;    /* Cursor number of the temporary table holding result */
80630      u8 op = 0;       /* One of the SRT_ operations to apply to self */
80631      int priorOp;     /* The SRT_ operation to apply to prior selects */
80632      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
80633      int addr;
80634      SelectDest uniondest;
80635
80636      testcase( p->op==TK_EXCEPT );
80637      testcase( p->op==TK_UNION );
80638      priorOp = SRT_Union;
80639      if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
80640        /* We can reuse a temporary table generated by a SELECT to our
80641        ** right.
80642        */
80643        assert( p->pRightmost!=p );  /* Can only happen for leftward elements
80644                                     ** of a 3-way or more compound */
80645        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
80646        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
80647        unionTab = dest.iParm;
80648      }else{
80649        /* We will need to create our own temporary table to hold the
80650        ** intermediate results.
80651        */
80652        unionTab = pParse->nTab++;
80653        assert( p->pOrderBy==0 );
80654        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
80655        assert( p->addrOpenEphm[0] == -1 );
80656        p->addrOpenEphm[0] = addr;
80657        p->pRightmost->selFlags |= SF_UsesEphemeral;
80658        assert( p->pEList );
80659      }
80660
80661      /* Code the SELECT statements to our left
80662      */
80663      assert( !pPrior->pOrderBy );
80664      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
80665      rc = sqlite3Select(pParse, pPrior, &uniondest);
80666      if( rc ){
80667        goto multi_select_end;
80668      }
80669
80670      /* Code the current SELECT statement
80671      */
80672      if( p->op==TK_EXCEPT ){
80673        op = SRT_Except;
80674      }else{
80675        assert( p->op==TK_UNION );
80676        op = SRT_Union;
80677      }
80678      p->pPrior = 0;
80679      pLimit = p->pLimit;
80680      p->pLimit = 0;
80681      pOffset = p->pOffset;
80682      p->pOffset = 0;
80683      uniondest.eDest = op;
80684      rc = sqlite3Select(pParse, p, &uniondest);
80685      testcase( rc!=SQLITE_OK );
80686      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
80687      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
80688      sqlite3ExprListDelete(db, p->pOrderBy);
80689      pDelete = p->pPrior;
80690      p->pPrior = pPrior;
80691      p->pOrderBy = 0;
80692      sqlite3ExprDelete(db, p->pLimit);
80693      p->pLimit = pLimit;
80694      p->pOffset = pOffset;
80695      p->iLimit = 0;
80696      p->iOffset = 0;
80697
80698      /* Convert the data in the temporary table into whatever form
80699      ** it is that we currently need.
80700      */
80701      assert( unionTab==dest.iParm || dest.eDest!=priorOp );
80702      if( dest.eDest!=priorOp ){
80703        int iCont, iBreak, iStart;
80704        assert( p->pEList );
80705        if( dest.eDest==SRT_Output ){
80706          Select *pFirst = p;
80707          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
80708          generateColumnNames(pParse, 0, pFirst->pEList);
80709        }
80710        iBreak = sqlite3VdbeMakeLabel(v);
80711        iCont = sqlite3VdbeMakeLabel(v);
80712        computeLimitRegisters(pParse, p, iBreak);
80713        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
80714        iStart = sqlite3VdbeCurrentAddr(v);
80715        selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
80716                        0, -1, &dest, iCont, iBreak);
80717        sqlite3VdbeResolveLabel(v, iCont);
80718        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
80719        sqlite3VdbeResolveLabel(v, iBreak);
80720        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
80721      }
80722      break;
80723    }
80724    default: assert( p->op==TK_INTERSECT ); {
80725      int tab1, tab2;
80726      int iCont, iBreak, iStart;
80727      Expr *pLimit, *pOffset;
80728      int addr;
80729      SelectDest intersectdest;
80730      int r1;
80731
80732      /* INTERSECT is different from the others since it requires
80733      ** two temporary tables.  Hence it has its own case.  Begin
80734      ** by allocating the tables we will need.
80735      */
80736      tab1 = pParse->nTab++;
80737      tab2 = pParse->nTab++;
80738      assert( p->pOrderBy==0 );
80739
80740      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
80741      assert( p->addrOpenEphm[0] == -1 );
80742      p->addrOpenEphm[0] = addr;
80743      p->pRightmost->selFlags |= SF_UsesEphemeral;
80744      assert( p->pEList );
80745
80746      /* Code the SELECTs to our left into temporary table "tab1".
80747      */
80748      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
80749      rc = sqlite3Select(pParse, pPrior, &intersectdest);
80750      if( rc ){
80751        goto multi_select_end;
80752      }
80753
80754      /* Code the current SELECT into temporary table "tab2"
80755      */
80756      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
80757      assert( p->addrOpenEphm[1] == -1 );
80758      p->addrOpenEphm[1] = addr;
80759      p->pPrior = 0;
80760      pLimit = p->pLimit;
80761      p->pLimit = 0;
80762      pOffset = p->pOffset;
80763      p->pOffset = 0;
80764      intersectdest.iParm = tab2;
80765      rc = sqlite3Select(pParse, p, &intersectdest);
80766      testcase( rc!=SQLITE_OK );
80767      pDelete = p->pPrior;
80768      p->pPrior = pPrior;
80769      sqlite3ExprDelete(db, p->pLimit);
80770      p->pLimit = pLimit;
80771      p->pOffset = pOffset;
80772
80773      /* Generate code to take the intersection of the two temporary
80774      ** tables.
80775      */
80776      assert( p->pEList );
80777      if( dest.eDest==SRT_Output ){
80778        Select *pFirst = p;
80779        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
80780        generateColumnNames(pParse, 0, pFirst->pEList);
80781      }
80782      iBreak = sqlite3VdbeMakeLabel(v);
80783      iCont = sqlite3VdbeMakeLabel(v);
80784      computeLimitRegisters(pParse, p, iBreak);
80785      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
80786      r1 = sqlite3GetTempReg(pParse);
80787      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
80788      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
80789      sqlite3ReleaseTempReg(pParse, r1);
80790      selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
80791                      0, -1, &dest, iCont, iBreak);
80792      sqlite3VdbeResolveLabel(v, iCont);
80793      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
80794      sqlite3VdbeResolveLabel(v, iBreak);
80795      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
80796      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
80797      break;
80798    }
80799  }
80800
80801  /* Compute collating sequences used by
80802  ** temporary tables needed to implement the compound select.
80803  ** Attach the KeyInfo structure to all temporary tables.
80804  **
80805  ** This section is run by the right-most SELECT statement only.
80806  ** SELECT statements to the left always skip this part.  The right-most
80807  ** SELECT might also skip this part if it has no ORDER BY clause and
80808  ** no temp tables are required.
80809  */
80810  if( p->selFlags & SF_UsesEphemeral ){
80811    int i;                        /* Loop counter */
80812    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
80813    Select *pLoop;                /* For looping through SELECT statements */
80814    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
80815    int nCol;                     /* Number of columns in result set */
80816
80817    assert( p->pRightmost==p );
80818    nCol = p->pEList->nExpr;
80819    pKeyInfo = sqlite3DbMallocZero(db,
80820                       sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
80821    if( !pKeyInfo ){
80822      rc = SQLITE_NOMEM;
80823      goto multi_select_end;
80824    }
80825
80826    pKeyInfo->enc = ENC(db);
80827    pKeyInfo->nField = (u16)nCol;
80828
80829    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
80830      *apColl = multiSelectCollSeq(pParse, p, i);
80831      if( 0==*apColl ){
80832        *apColl = db->pDfltColl;
80833      }
80834    }
80835
80836    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
80837      for(i=0; i<2; i++){
80838        int addr = pLoop->addrOpenEphm[i];
80839        if( addr<0 ){
80840          /* If [0] is unused then [1] is also unused.  So we can
80841          ** always safely abort as soon as the first unused slot is found */
80842          assert( pLoop->addrOpenEphm[1]<0 );
80843          break;
80844        }
80845        sqlite3VdbeChangeP2(v, addr, nCol);
80846        sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
80847        pLoop->addrOpenEphm[i] = -1;
80848      }
80849    }
80850    sqlite3DbFree(db, pKeyInfo);
80851  }
80852
80853multi_select_end:
80854  pDest->iMem = dest.iMem;
80855  pDest->nMem = dest.nMem;
80856  sqlite3SelectDelete(db, pDelete);
80857  return rc;
80858}
80859#endif /* SQLITE_OMIT_COMPOUND_SELECT */
80860
80861/*
80862** Code an output subroutine for a coroutine implementation of a
80863** SELECT statment.
80864**
80865** The data to be output is contained in pIn->iMem.  There are
80866** pIn->nMem columns to be output.  pDest is where the output should
80867** be sent.
80868**
80869** regReturn is the number of the register holding the subroutine
80870** return address.
80871**
80872** If regPrev>0 then it is a the first register in a vector that
80873** records the previous output.  mem[regPrev] is a flag that is false
80874** if there has been no previous output.  If regPrev>0 then code is
80875** generated to suppress duplicates.  pKeyInfo is used for comparing
80876** keys.
80877**
80878** If the LIMIT found in p->iLimit is reached, jump immediately to
80879** iBreak.
80880*/
80881static int generateOutputSubroutine(
80882  Parse *pParse,          /* Parsing context */
80883  Select *p,              /* The SELECT statement */
80884  SelectDest *pIn,        /* Coroutine supplying data */
80885  SelectDest *pDest,      /* Where to send the data */
80886  int regReturn,          /* The return address register */
80887  int regPrev,            /* Previous result register.  No uniqueness if 0 */
80888  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
80889  int p4type,             /* The p4 type for pKeyInfo */
80890  int iBreak              /* Jump here if we hit the LIMIT */
80891){
80892  Vdbe *v = pParse->pVdbe;
80893  int iContinue;
80894  int addr;
80895
80896  addr = sqlite3VdbeCurrentAddr(v);
80897  iContinue = sqlite3VdbeMakeLabel(v);
80898
80899  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
80900  */
80901  if( regPrev ){
80902    int j1, j2;
80903    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
80904    j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
80905                              (char*)pKeyInfo, p4type);
80906    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
80907    sqlite3VdbeJumpHere(v, j1);
80908    sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
80909    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
80910  }
80911  if( pParse->db->mallocFailed ) return 0;
80912
80913  /* Suppress the the first OFFSET entries if there is an OFFSET clause
80914  */
80915  codeOffset(v, p, iContinue);
80916
80917  switch( pDest->eDest ){
80918    /* Store the result as data using a unique key.
80919    */
80920    case SRT_Table:
80921    case SRT_EphemTab: {
80922      int r1 = sqlite3GetTempReg(pParse);
80923      int r2 = sqlite3GetTempReg(pParse);
80924      testcase( pDest->eDest==SRT_Table );
80925      testcase( pDest->eDest==SRT_EphemTab );
80926      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
80927      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
80928      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
80929      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80930      sqlite3ReleaseTempReg(pParse, r2);
80931      sqlite3ReleaseTempReg(pParse, r1);
80932      break;
80933    }
80934
80935#ifndef SQLITE_OMIT_SUBQUERY
80936    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
80937    ** then there should be a single item on the stack.  Write this
80938    ** item into the set table with bogus data.
80939    */
80940    case SRT_Set: {
80941      int r1;
80942      assert( pIn->nMem==1 );
80943      p->affinity =
80944         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
80945      r1 = sqlite3GetTempReg(pParse);
80946      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
80947      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
80948      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
80949      sqlite3ReleaseTempReg(pParse, r1);
80950      break;
80951    }
80952
80953#if 0  /* Never occurs on an ORDER BY query */
80954    /* If any row exist in the result set, record that fact and abort.
80955    */
80956    case SRT_Exists: {
80957      sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
80958      /* The LIMIT clause will terminate the loop for us */
80959      break;
80960    }
80961#endif
80962
80963    /* If this is a scalar select that is part of an expression, then
80964    ** store the results in the appropriate memory cell and break out
80965    ** of the scan loop.
80966    */
80967    case SRT_Mem: {
80968      assert( pIn->nMem==1 );
80969      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
80970      /* The LIMIT clause will jump out of the loop for us */
80971      break;
80972    }
80973#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
80974
80975    /* The results are stored in a sequence of registers
80976    ** starting at pDest->iMem.  Then the co-routine yields.
80977    */
80978    case SRT_Coroutine: {
80979      if( pDest->iMem==0 ){
80980        pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
80981        pDest->nMem = pIn->nMem;
80982      }
80983      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
80984      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
80985      break;
80986    }
80987
80988    /* If none of the above, then the result destination must be
80989    ** SRT_Output.  This routine is never called with any other
80990    ** destination other than the ones handled above or SRT_Output.
80991    **
80992    ** For SRT_Output, results are stored in a sequence of registers.
80993    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
80994    ** return the next row of result.
80995    */
80996    default: {
80997      assert( pDest->eDest==SRT_Output );
80998      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
80999      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
81000      break;
81001    }
81002  }
81003
81004  /* Jump to the end of the loop if the LIMIT is reached.
81005  */
81006  if( p->iLimit ){
81007    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
81008  }
81009
81010  /* Generate the subroutine return
81011  */
81012  sqlite3VdbeResolveLabel(v, iContinue);
81013  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
81014
81015  return addr;
81016}
81017
81018/*
81019** Alternative compound select code generator for cases when there
81020** is an ORDER BY clause.
81021**
81022** We assume a query of the following form:
81023**
81024**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
81025**
81026** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
81027** is to code both <selectA> and <selectB> with the ORDER BY clause as
81028** co-routines.  Then run the co-routines in parallel and merge the results
81029** into the output.  In addition to the two coroutines (called selectA and
81030** selectB) there are 7 subroutines:
81031**
81032**    outA:    Move the output of the selectA coroutine into the output
81033**             of the compound query.
81034**
81035**    outB:    Move the output of the selectB coroutine into the output
81036**             of the compound query.  (Only generated for UNION and
81037**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
81038**             appears only in B.)
81039**
81040**    AltB:    Called when there is data from both coroutines and A<B.
81041**
81042**    AeqB:    Called when there is data from both coroutines and A==B.
81043**
81044**    AgtB:    Called when there is data from both coroutines and A>B.
81045**
81046**    EofA:    Called when data is exhausted from selectA.
81047**
81048**    EofB:    Called when data is exhausted from selectB.
81049**
81050** The implementation of the latter five subroutines depend on which
81051** <operator> is used:
81052**
81053**
81054**             UNION ALL         UNION            EXCEPT          INTERSECT
81055**          -------------  -----------------  --------------  -----------------
81056**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
81057**
81058**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
81059**
81060**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
81061**
81062**   EofA:   outB, nextB      outB, nextB          halt             halt
81063**
81064**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
81065**
81066** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
81067** causes an immediate jump to EofA and an EOF on B following nextB causes
81068** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
81069** following nextX causes a jump to the end of the select processing.
81070**
81071** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
81072** within the output subroutine.  The regPrev register set holds the previously
81073** output value.  A comparison is made against this value and the output
81074** is skipped if the next results would be the same as the previous.
81075**
81076** The implementation plan is to implement the two coroutines and seven
81077** subroutines first, then put the control logic at the bottom.  Like this:
81078**
81079**          goto Init
81080**     coA: coroutine for left query (A)
81081**     coB: coroutine for right query (B)
81082**    outA: output one row of A
81083**    outB: output one row of B (UNION and UNION ALL only)
81084**    EofA: ...
81085**    EofB: ...
81086**    AltB: ...
81087**    AeqB: ...
81088**    AgtB: ...
81089**    Init: initialize coroutine registers
81090**          yield coA
81091**          if eof(A) goto EofA
81092**          yield coB
81093**          if eof(B) goto EofB
81094**    Cmpr: Compare A, B
81095**          Jump AltB, AeqB, AgtB
81096**     End: ...
81097**
81098** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
81099** actually called using Gosub and they do not Return.  EofA and EofB loop
81100** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
81101** and AgtB jump to either L2 or to one of EofA or EofB.
81102*/
81103#ifndef SQLITE_OMIT_COMPOUND_SELECT
81104static int multiSelectOrderBy(
81105  Parse *pParse,        /* Parsing context */
81106  Select *p,            /* The right-most of SELECTs to be coded */
81107  SelectDest *pDest     /* What to do with query results */
81108){
81109  int i, j;             /* Loop counters */
81110  Select *pPrior;       /* Another SELECT immediately to our left */
81111  Vdbe *v;              /* Generate code to this VDBE */
81112  SelectDest destA;     /* Destination for coroutine A */
81113  SelectDest destB;     /* Destination for coroutine B */
81114  int regAddrA;         /* Address register for select-A coroutine */
81115  int regEofA;          /* Flag to indicate when select-A is complete */
81116  int regAddrB;         /* Address register for select-B coroutine */
81117  int regEofB;          /* Flag to indicate when select-B is complete */
81118  int addrSelectA;      /* Address of the select-A coroutine */
81119  int addrSelectB;      /* Address of the select-B coroutine */
81120  int regOutA;          /* Address register for the output-A subroutine */
81121  int regOutB;          /* Address register for the output-B subroutine */
81122  int addrOutA;         /* Address of the output-A subroutine */
81123  int addrOutB = 0;     /* Address of the output-B subroutine */
81124  int addrEofA;         /* Address of the select-A-exhausted subroutine */
81125  int addrEofB;         /* Address of the select-B-exhausted subroutine */
81126  int addrAltB;         /* Address of the A<B subroutine */
81127  int addrAeqB;         /* Address of the A==B subroutine */
81128  int addrAgtB;         /* Address of the A>B subroutine */
81129  int regLimitA;        /* Limit register for select-A */
81130  int regLimitB;        /* Limit register for select-A */
81131  int regPrev;          /* A range of registers to hold previous output */
81132  int savedLimit;       /* Saved value of p->iLimit */
81133  int savedOffset;      /* Saved value of p->iOffset */
81134  int labelCmpr;        /* Label for the start of the merge algorithm */
81135  int labelEnd;         /* Label for the end of the overall SELECT stmt */
81136  int j1;               /* Jump instructions that get retargetted */
81137  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
81138  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
81139  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
81140  sqlite3 *db;          /* Database connection */
81141  ExprList *pOrderBy;   /* The ORDER BY clause */
81142  int nOrderBy;         /* Number of terms in the ORDER BY clause */
81143  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
81144
81145  assert( p->pOrderBy!=0 );
81146  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
81147  db = pParse->db;
81148  v = pParse->pVdbe;
81149  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
81150  labelEnd = sqlite3VdbeMakeLabel(v);
81151  labelCmpr = sqlite3VdbeMakeLabel(v);
81152
81153
81154  /* Patch up the ORDER BY clause
81155  */
81156  op = p->op;
81157  pPrior = p->pPrior;
81158  assert( pPrior->pOrderBy==0 );
81159  pOrderBy = p->pOrderBy;
81160  assert( pOrderBy );
81161  nOrderBy = pOrderBy->nExpr;
81162
81163  /* For operators other than UNION ALL we have to make sure that
81164  ** the ORDER BY clause covers every term of the result set.  Add
81165  ** terms to the ORDER BY clause as necessary.
81166  */
81167  if( op!=TK_ALL ){
81168    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
81169      struct ExprList_item *pItem;
81170      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
81171        assert( pItem->iCol>0 );
81172        if( pItem->iCol==i ) break;
81173      }
81174      if( j==nOrderBy ){
81175        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
81176        if( pNew==0 ) return SQLITE_NOMEM;
81177        pNew->flags |= EP_IntValue;
81178        pNew->u.iValue = i;
81179        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
81180        pOrderBy->a[nOrderBy++].iCol = (u16)i;
81181      }
81182    }
81183  }
81184
81185  /* Compute the comparison permutation and keyinfo that is used with
81186  ** the permutation used to determine if the next
81187  ** row of results comes from selectA or selectB.  Also add explicit
81188  ** collations to the ORDER BY clause terms so that when the subqueries
81189  ** to the right and the left are evaluated, they use the correct
81190  ** collation.
81191  */
81192  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
81193  if( aPermute ){
81194    struct ExprList_item *pItem;
81195    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
81196      assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
81197      aPermute[i] = pItem->iCol - 1;
81198    }
81199    pKeyMerge =
81200      sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
81201    if( pKeyMerge ){
81202      pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
81203      pKeyMerge->nField = (u16)nOrderBy;
81204      pKeyMerge->enc = ENC(db);
81205      for(i=0; i<nOrderBy; i++){
81206        CollSeq *pColl;
81207        Expr *pTerm = pOrderBy->a[i].pExpr;
81208        if( pTerm->flags & EP_ExpCollate ){
81209          pColl = pTerm->pColl;
81210        }else{
81211          pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
81212          pTerm->flags |= EP_ExpCollate;
81213          pTerm->pColl = pColl;
81214        }
81215        pKeyMerge->aColl[i] = pColl;
81216        pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
81217      }
81218    }
81219  }else{
81220    pKeyMerge = 0;
81221  }
81222
81223  /* Reattach the ORDER BY clause to the query.
81224  */
81225  p->pOrderBy = pOrderBy;
81226  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
81227
81228  /* Allocate a range of temporary registers and the KeyInfo needed
81229  ** for the logic that removes duplicate result rows when the
81230  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
81231  */
81232  if( op==TK_ALL ){
81233    regPrev = 0;
81234  }else{
81235    int nExpr = p->pEList->nExpr;
81236    assert( nOrderBy>=nExpr || db->mallocFailed );
81237    regPrev = sqlite3GetTempRange(pParse, nExpr+1);
81238    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
81239    pKeyDup = sqlite3DbMallocZero(db,
81240                  sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
81241    if( pKeyDup ){
81242      pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
81243      pKeyDup->nField = (u16)nExpr;
81244      pKeyDup->enc = ENC(db);
81245      for(i=0; i<nExpr; i++){
81246        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
81247        pKeyDup->aSortOrder[i] = 0;
81248      }
81249    }
81250  }
81251
81252  /* Separate the left and the right query from one another
81253  */
81254  p->pPrior = 0;
81255  pPrior->pRightmost = 0;
81256  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
81257  if( pPrior->pPrior==0 ){
81258    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
81259  }
81260
81261  /* Compute the limit registers */
81262  computeLimitRegisters(pParse, p, labelEnd);
81263  if( p->iLimit && op==TK_ALL ){
81264    regLimitA = ++pParse->nMem;
81265    regLimitB = ++pParse->nMem;
81266    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
81267                                  regLimitA);
81268    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
81269  }else{
81270    regLimitA = regLimitB = 0;
81271  }
81272  sqlite3ExprDelete(db, p->pLimit);
81273  p->pLimit = 0;
81274  sqlite3ExprDelete(db, p->pOffset);
81275  p->pOffset = 0;
81276
81277  regAddrA = ++pParse->nMem;
81278  regEofA = ++pParse->nMem;
81279  regAddrB = ++pParse->nMem;
81280  regEofB = ++pParse->nMem;
81281  regOutA = ++pParse->nMem;
81282  regOutB = ++pParse->nMem;
81283  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
81284  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
81285
81286  /* Jump past the various subroutines and coroutines to the main
81287  ** merge loop
81288  */
81289  j1 = sqlite3VdbeAddOp0(v, OP_Goto);
81290  addrSelectA = sqlite3VdbeCurrentAddr(v);
81291
81292
81293  /* Generate a coroutine to evaluate the SELECT statement to the
81294  ** left of the compound operator - the "A" select.
81295  */
81296  VdbeNoopComment((v, "Begin coroutine for left SELECT"));
81297  pPrior->iLimit = regLimitA;
81298  sqlite3Select(pParse, pPrior, &destA);
81299  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
81300  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81301  VdbeNoopComment((v, "End coroutine for left SELECT"));
81302
81303  /* Generate a coroutine to evaluate the SELECT statement on
81304  ** the right - the "B" select
81305  */
81306  addrSelectB = sqlite3VdbeCurrentAddr(v);
81307  VdbeNoopComment((v, "Begin coroutine for right SELECT"));
81308  savedLimit = p->iLimit;
81309  savedOffset = p->iOffset;
81310  p->iLimit = regLimitB;
81311  p->iOffset = 0;
81312  sqlite3Select(pParse, p, &destB);
81313  p->iLimit = savedLimit;
81314  p->iOffset = savedOffset;
81315  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
81316  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
81317  VdbeNoopComment((v, "End coroutine for right SELECT"));
81318
81319  /* Generate a subroutine that outputs the current row of the A
81320  ** select as the next output row of the compound select.
81321  */
81322  VdbeNoopComment((v, "Output routine for A"));
81323  addrOutA = generateOutputSubroutine(pParse,
81324                 p, &destA, pDest, regOutA,
81325                 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
81326
81327  /* Generate a subroutine that outputs the current row of the B
81328  ** select as the next output row of the compound select.
81329  */
81330  if( op==TK_ALL || op==TK_UNION ){
81331    VdbeNoopComment((v, "Output routine for B"));
81332    addrOutB = generateOutputSubroutine(pParse,
81333                 p, &destB, pDest, regOutB,
81334                 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
81335  }
81336
81337  /* Generate a subroutine to run when the results from select A
81338  ** are exhausted and only data in select B remains.
81339  */
81340  VdbeNoopComment((v, "eof-A subroutine"));
81341  if( op==TK_EXCEPT || op==TK_INTERSECT ){
81342    addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
81343  }else{
81344    addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
81345    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
81346    sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
81347    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
81348  }
81349
81350  /* Generate a subroutine to run when the results from select B
81351  ** are exhausted and only data in select A remains.
81352  */
81353  if( op==TK_INTERSECT ){
81354    addrEofB = addrEofA;
81355  }else{
81356    VdbeNoopComment((v, "eof-B subroutine"));
81357    addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
81358    sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
81359    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81360    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
81361  }
81362
81363  /* Generate code to handle the case of A<B
81364  */
81365  VdbeNoopComment((v, "A-lt-B subroutine"));
81366  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
81367  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81368  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
81369  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
81370
81371  /* Generate code to handle the case of A==B
81372  */
81373  if( op==TK_ALL ){
81374    addrAeqB = addrAltB;
81375  }else if( op==TK_INTERSECT ){
81376    addrAeqB = addrAltB;
81377    addrAltB++;
81378  }else{
81379    VdbeNoopComment((v, "A-eq-B subroutine"));
81380    addrAeqB =
81381    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81382    sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
81383    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
81384  }
81385
81386  /* Generate code to handle the case of A>B
81387  */
81388  VdbeNoopComment((v, "A-gt-B subroutine"));
81389  addrAgtB = sqlite3VdbeCurrentAddr(v);
81390  if( op==TK_ALL || op==TK_UNION ){
81391    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
81392  }
81393  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
81394  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
81395  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
81396
81397  /* This code runs once to initialize everything.
81398  */
81399  sqlite3VdbeJumpHere(v, j1);
81400  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
81401  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
81402  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
81403  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
81404  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
81405  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
81406
81407  /* Implement the main merge loop
81408  */
81409  sqlite3VdbeResolveLabel(v, labelCmpr);
81410  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
81411  sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
81412                         (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
81413  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
81414
81415  /* Release temporary registers
81416  */
81417  if( regPrev ){
81418    sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
81419  }
81420
81421  /* Jump to the this point in order to terminate the query.
81422  */
81423  sqlite3VdbeResolveLabel(v, labelEnd);
81424
81425  /* Set the number of output columns
81426  */
81427  if( pDest->eDest==SRT_Output ){
81428    Select *pFirst = pPrior;
81429    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
81430    generateColumnNames(pParse, 0, pFirst->pEList);
81431  }
81432
81433  /* Reassembly the compound query so that it will be freed correctly
81434  ** by the calling function */
81435  if( p->pPrior ){
81436    sqlite3SelectDelete(db, p->pPrior);
81437  }
81438  p->pPrior = pPrior;
81439
81440  /*** TBD:  Insert subroutine calls to close cursors on incomplete
81441  **** subqueries ****/
81442  return SQLITE_OK;
81443}
81444#endif
81445
81446#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
81447/* Forward Declarations */
81448static void substExprList(sqlite3*, ExprList*, int, ExprList*);
81449static void substSelect(sqlite3*, Select *, int, ExprList *);
81450
81451/*
81452** Scan through the expression pExpr.  Replace every reference to
81453** a column in table number iTable with a copy of the iColumn-th
81454** entry in pEList.  (But leave references to the ROWID column
81455** unchanged.)
81456**
81457** This routine is part of the flattening procedure.  A subquery
81458** whose result set is defined by pEList appears as entry in the
81459** FROM clause of a SELECT such that the VDBE cursor assigned to that
81460** FORM clause entry is iTable.  This routine make the necessary
81461** changes to pExpr so that it refers directly to the source table
81462** of the subquery rather the result set of the subquery.
81463*/
81464static Expr *substExpr(
81465  sqlite3 *db,        /* Report malloc errors to this connection */
81466  Expr *pExpr,        /* Expr in which substitution occurs */
81467  int iTable,         /* Table to be substituted */
81468  ExprList *pEList    /* Substitute expressions */
81469){
81470  if( pExpr==0 ) return 0;
81471  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
81472    if( pExpr->iColumn<0 ){
81473      pExpr->op = TK_NULL;
81474    }else{
81475      Expr *pNew;
81476      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
81477      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
81478      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
81479      if( pNew && pExpr->pColl ){
81480        pNew->pColl = pExpr->pColl;
81481      }
81482      sqlite3ExprDelete(db, pExpr);
81483      pExpr = pNew;
81484    }
81485  }else{
81486    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
81487    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
81488    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
81489      substSelect(db, pExpr->x.pSelect, iTable, pEList);
81490    }else{
81491      substExprList(db, pExpr->x.pList, iTable, pEList);
81492    }
81493  }
81494  return pExpr;
81495}
81496static void substExprList(
81497  sqlite3 *db,         /* Report malloc errors here */
81498  ExprList *pList,     /* List to scan and in which to make substitutes */
81499  int iTable,          /* Table to be substituted */
81500  ExprList *pEList     /* Substitute values */
81501){
81502  int i;
81503  if( pList==0 ) return;
81504  for(i=0; i<pList->nExpr; i++){
81505    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
81506  }
81507}
81508static void substSelect(
81509  sqlite3 *db,         /* Report malloc errors here */
81510  Select *p,           /* SELECT statement in which to make substitutions */
81511  int iTable,          /* Table to be replaced */
81512  ExprList *pEList     /* Substitute values */
81513){
81514  SrcList *pSrc;
81515  struct SrcList_item *pItem;
81516  int i;
81517  if( !p ) return;
81518  substExprList(db, p->pEList, iTable, pEList);
81519  substExprList(db, p->pGroupBy, iTable, pEList);
81520  substExprList(db, p->pOrderBy, iTable, pEList);
81521  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
81522  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
81523  substSelect(db, p->pPrior, iTable, pEList);
81524  pSrc = p->pSrc;
81525  assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
81526  if( ALWAYS(pSrc) ){
81527    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
81528      substSelect(db, pItem->pSelect, iTable, pEList);
81529    }
81530  }
81531}
81532#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
81533
81534#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
81535/*
81536** This routine attempts to flatten subqueries in order to speed
81537** execution.  It returns 1 if it makes changes and 0 if no flattening
81538** occurs.
81539**
81540** To understand the concept of flattening, consider the following
81541** query:
81542**
81543**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
81544**
81545** The default way of implementing this query is to execute the
81546** subquery first and store the results in a temporary table, then
81547** run the outer query on that temporary table.  This requires two
81548** passes over the data.  Furthermore, because the temporary table
81549** has no indices, the WHERE clause on the outer query cannot be
81550** optimized.
81551**
81552** This routine attempts to rewrite queries such as the above into
81553** a single flat select, like this:
81554**
81555**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
81556**
81557** The code generated for this simpification gives the same result
81558** but only has to scan the data once.  And because indices might
81559** exist on the table t1, a complete scan of the data might be
81560** avoided.
81561**
81562** Flattening is only attempted if all of the following are true:
81563**
81564**   (1)  The subquery and the outer query do not both use aggregates.
81565**
81566**   (2)  The subquery is not an aggregate or the outer query is not a join.
81567**
81568**   (3)  The subquery is not the right operand of a left outer join
81569**        (Originally ticket #306.  Strenghtened by ticket #3300)
81570**
81571**   (4)  The subquery is not DISTINCT or the outer query is not a join.
81572**
81573**   (5)  The subquery is not DISTINCT or the outer query does not use
81574**        aggregates.
81575**
81576**   (6)  The subquery does not use aggregates or the outer query is not
81577**        DISTINCT.
81578**
81579**   (7)  The subquery has a FROM clause.
81580**
81581**   (8)  The subquery does not use LIMIT or the outer query is not a join.
81582**
81583**   (9)  The subquery does not use LIMIT or the outer query does not use
81584**        aggregates.
81585**
81586**  (10)  The subquery does not use aggregates or the outer query does not
81587**        use LIMIT.
81588**
81589**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
81590**
81591**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
81592**        a separate restriction deriving from ticket #350.
81593**
81594**  (13)  The subquery and outer query do not both use LIMIT
81595**
81596**  (14)  The subquery does not use OFFSET
81597**
81598**  (15)  The outer query is not part of a compound select or the
81599**        subquery does not have both an ORDER BY and a LIMIT clause.
81600**        (See ticket #2339)
81601**
81602**  (16)  The outer query is not an aggregate or the subquery does
81603**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
81604**        until we introduced the group_concat() function.
81605**
81606**  (17)  The sub-query is not a compound select, or it is a UNION ALL
81607**        compound clause made up entirely of non-aggregate queries, and
81608**        the parent query:
81609**
81610**          * is not itself part of a compound select,
81611**          * is not an aggregate or DISTINCT query, and
81612**          * has no other tables or sub-selects in the FROM clause.
81613**
81614**        The parent and sub-query may contain WHERE clauses. Subject to
81615**        rules (11), (13) and (14), they may also contain ORDER BY,
81616**        LIMIT and OFFSET clauses.
81617**
81618**  (18)  If the sub-query is a compound select, then all terms of the
81619**        ORDER by clause of the parent must be simple references to
81620**        columns of the sub-query.
81621**
81622**  (19)  The subquery does not use LIMIT or the outer query does not
81623**        have a WHERE clause.
81624**
81625**  (20)  If the sub-query is a compound select, then it must not use
81626**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
81627**        somewhat by saying that the terms of the ORDER BY clause must
81628**        appear as unmodified result columns in the outer query.  But
81629**        have other optimizations in mind to deal with that case.
81630**
81631** In this routine, the "p" parameter is a pointer to the outer query.
81632** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
81633** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
81634**
81635** If flattening is not attempted, this routine is a no-op and returns 0.
81636** If flattening is attempted this routine returns 1.
81637**
81638** All of the expression analysis must occur on both the outer query and
81639** the subquery before this routine runs.
81640*/
81641static int flattenSubquery(
81642  Parse *pParse,       /* Parsing context */
81643  Select *p,           /* The parent or outer SELECT statement */
81644  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
81645  int isAgg,           /* True if outer SELECT uses aggregate functions */
81646  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
81647){
81648  const char *zSavedAuthContext = pParse->zAuthContext;
81649  Select *pParent;
81650  Select *pSub;       /* The inner query or "subquery" */
81651  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
81652  SrcList *pSrc;      /* The FROM clause of the outer query */
81653  SrcList *pSubSrc;   /* The FROM clause of the subquery */
81654  ExprList *pList;    /* The result set of the outer query */
81655  int iParent;        /* VDBE cursor number of the pSub result set temp table */
81656  int i;              /* Loop counter */
81657  Expr *pWhere;                    /* The WHERE clause */
81658  struct SrcList_item *pSubitem;   /* The subquery */
81659  sqlite3 *db = pParse->db;
81660
81661  /* Check to see if flattening is permitted.  Return 0 if not.
81662  */
81663  assert( p!=0 );
81664  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
81665  if( db->flags & SQLITE_QueryFlattener ) return 0;
81666  pSrc = p->pSrc;
81667  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
81668  pSubitem = &pSrc->a[iFrom];
81669  iParent = pSubitem->iCursor;
81670  pSub = pSubitem->pSelect;
81671  assert( pSub!=0 );
81672  if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
81673  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
81674  pSubSrc = pSub->pSrc;
81675  assert( pSubSrc );
81676  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
81677  ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
81678  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
81679  ** became arbitrary expressions, we were forced to add restrictions (13)
81680  ** and (14). */
81681  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
81682  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
81683  if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
81684    return 0;                                            /* Restriction (15) */
81685  }
81686  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
81687  if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit)
81688         && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
81689     return 0;
81690  }
81691  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
81692     return 0;         /* Restriction (6)  */
81693  }
81694  if( p->pOrderBy && pSub->pOrderBy ){
81695     return 0;                                           /* Restriction (11) */
81696  }
81697  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
81698  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
81699
81700  /* OBSOLETE COMMENT 1:
81701  ** Restriction 3:  If the subquery is a join, make sure the subquery is
81702  ** not used as the right operand of an outer join.  Examples of why this
81703  ** is not allowed:
81704  **
81705  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
81706  **
81707  ** If we flatten the above, we would get
81708  **
81709  **         (t1 LEFT OUTER JOIN t2) JOIN t3
81710  **
81711  ** which is not at all the same thing.
81712  **
81713  ** OBSOLETE COMMENT 2:
81714  ** Restriction 12:  If the subquery is the right operand of a left outer
81715  ** join, make sure the subquery has no WHERE clause.
81716  ** An examples of why this is not allowed:
81717  **
81718  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
81719  **
81720  ** If we flatten the above, we would get
81721  **
81722  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
81723  **
81724  ** But the t2.x>0 test will always fail on a NULL row of t2, which
81725  ** effectively converts the OUTER JOIN into an INNER JOIN.
81726  **
81727  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
81728  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
81729  ** is fraught with danger.  Best to avoid the whole thing.  If the
81730  ** subquery is the right term of a LEFT JOIN, then do not flatten.
81731  */
81732  if( (pSubitem->jointype & JT_OUTER)!=0 ){
81733    return 0;
81734  }
81735
81736  /* Restriction 17: If the sub-query is a compound SELECT, then it must
81737  ** use only the UNION ALL operator. And none of the simple select queries
81738  ** that make up the compound SELECT are allowed to be aggregate or distinct
81739  ** queries.
81740  */
81741  if( pSub->pPrior ){
81742    if( pSub->pOrderBy ){
81743      return 0;  /* Restriction 20 */
81744    }
81745    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
81746      return 0;
81747    }
81748    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
81749      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
81750      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
81751      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
81752       || (pSub1->pPrior && pSub1->op!=TK_ALL)
81753       || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
81754      ){
81755        return 0;
81756      }
81757    }
81758
81759    /* Restriction 18. */
81760    if( p->pOrderBy ){
81761      int ii;
81762      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
81763        if( p->pOrderBy->a[ii].iCol==0 ) return 0;
81764      }
81765    }
81766  }
81767
81768  /***** If we reach this point, flattening is permitted. *****/
81769
81770  /* Authorize the subquery */
81771  pParse->zAuthContext = pSubitem->zName;
81772  sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
81773  pParse->zAuthContext = zSavedAuthContext;
81774
81775  /* If the sub-query is a compound SELECT statement, then (by restrictions
81776  ** 17 and 18 above) it must be a UNION ALL and the parent query must
81777  ** be of the form:
81778  **
81779  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
81780  **
81781  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
81782  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
81783  ** OFFSET clauses and joins them to the left-hand-side of the original
81784  ** using UNION ALL operators. In this case N is the number of simple
81785  ** select statements in the compound sub-query.
81786  **
81787  ** Example:
81788  **
81789  **     SELECT a+1 FROM (
81790  **        SELECT x FROM tab
81791  **        UNION ALL
81792  **        SELECT y FROM tab
81793  **        UNION ALL
81794  **        SELECT abs(z*2) FROM tab2
81795  **     ) WHERE a!=5 ORDER BY 1
81796  **
81797  ** Transformed into:
81798  **
81799  **     SELECT x+1 FROM tab WHERE x+1!=5
81800  **     UNION ALL
81801  **     SELECT y+1 FROM tab WHERE y+1!=5
81802  **     UNION ALL
81803  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
81804  **     ORDER BY 1
81805  **
81806  ** We call this the "compound-subquery flattening".
81807  */
81808  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
81809    Select *pNew;
81810    ExprList *pOrderBy = p->pOrderBy;
81811    Expr *pLimit = p->pLimit;
81812    Select *pPrior = p->pPrior;
81813    p->pOrderBy = 0;
81814    p->pSrc = 0;
81815    p->pPrior = 0;
81816    p->pLimit = 0;
81817    pNew = sqlite3SelectDup(db, p, 0);
81818    p->pLimit = pLimit;
81819    p->pOrderBy = pOrderBy;
81820    p->pSrc = pSrc;
81821    p->op = TK_ALL;
81822    p->pRightmost = 0;
81823    if( pNew==0 ){
81824      pNew = pPrior;
81825    }else{
81826      pNew->pPrior = pPrior;
81827      pNew->pRightmost = 0;
81828    }
81829    p->pPrior = pNew;
81830    if( db->mallocFailed ) return 1;
81831  }
81832
81833  /* Begin flattening the iFrom-th entry of the FROM clause
81834  ** in the outer query.
81835  */
81836  pSub = pSub1 = pSubitem->pSelect;
81837
81838  /* Delete the transient table structure associated with the
81839  ** subquery
81840  */
81841  sqlite3DbFree(db, pSubitem->zDatabase);
81842  sqlite3DbFree(db, pSubitem->zName);
81843  sqlite3DbFree(db, pSubitem->zAlias);
81844  pSubitem->zDatabase = 0;
81845  pSubitem->zName = 0;
81846  pSubitem->zAlias = 0;
81847  pSubitem->pSelect = 0;
81848
81849  /* Defer deleting the Table object associated with the
81850  ** subquery until code generation is
81851  ** complete, since there may still exist Expr.pTab entries that
81852  ** refer to the subquery even after flattening.  Ticket #3346.
81853  **
81854  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
81855  */
81856  if( ALWAYS(pSubitem->pTab!=0) ){
81857    Table *pTabToDel = pSubitem->pTab;
81858    if( pTabToDel->nRef==1 ){
81859      Parse *pToplevel = sqlite3ParseToplevel(pParse);
81860      pTabToDel->pNextZombie = pToplevel->pZombieTab;
81861      pToplevel->pZombieTab = pTabToDel;
81862    }else{
81863      pTabToDel->nRef--;
81864    }
81865    pSubitem->pTab = 0;
81866  }
81867
81868  /* The following loop runs once for each term in a compound-subquery
81869  ** flattening (as described above).  If we are doing a different kind
81870  ** of flattening - a flattening other than a compound-subquery flattening -
81871  ** then this loop only runs once.
81872  **
81873  ** This loop moves all of the FROM elements of the subquery into the
81874  ** the FROM clause of the outer query.  Before doing this, remember
81875  ** the cursor number for the original outer query FROM element in
81876  ** iParent.  The iParent cursor will never be used.  Subsequent code
81877  ** will scan expressions looking for iParent references and replace
81878  ** those references with expressions that resolve to the subquery FROM
81879  ** elements we are now copying in.
81880  */
81881  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
81882    int nSubSrc;
81883    u8 jointype = 0;
81884    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
81885    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
81886    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
81887
81888    if( pSrc ){
81889      assert( pParent==p );  /* First time through the loop */
81890      jointype = pSubitem->jointype;
81891    }else{
81892      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
81893      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
81894      if( pSrc==0 ){
81895        assert( db->mallocFailed );
81896        break;
81897      }
81898    }
81899
81900    /* The subquery uses a single slot of the FROM clause of the outer
81901    ** query.  If the subquery has more than one element in its FROM clause,
81902    ** then expand the outer query to make space for it to hold all elements
81903    ** of the subquery.
81904    **
81905    ** Example:
81906    **
81907    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
81908    **
81909    ** The outer query has 3 slots in its FROM clause.  One slot of the
81910    ** outer query (the middle slot) is used by the subquery.  The next
81911    ** block of code will expand the out query to 4 slots.  The middle
81912    ** slot is expanded to two slots in order to make space for the
81913    ** two elements in the FROM clause of the subquery.
81914    */
81915    if( nSubSrc>1 ){
81916      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
81917      if( db->mallocFailed ){
81918        break;
81919      }
81920    }
81921
81922    /* Transfer the FROM clause terms from the subquery into the
81923    ** outer query.
81924    */
81925    for(i=0; i<nSubSrc; i++){
81926      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
81927      pSrc->a[i+iFrom] = pSubSrc->a[i];
81928      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
81929    }
81930    pSrc->a[iFrom].jointype = jointype;
81931
81932    /* Now begin substituting subquery result set expressions for
81933    ** references to the iParent in the outer query.
81934    **
81935    ** Example:
81936    **
81937    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
81938    **   \                     \_____________ subquery __________/          /
81939    **    \_____________________ outer query ______________________________/
81940    **
81941    ** We look at every expression in the outer query and every place we see
81942    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
81943    */
81944    pList = pParent->pEList;
81945    for(i=0; i<pList->nExpr; i++){
81946      if( pList->a[i].zName==0 ){
81947        const char *zSpan = pList->a[i].zSpan;
81948        if( ALWAYS(zSpan) ){
81949          pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
81950        }
81951      }
81952    }
81953    substExprList(db, pParent->pEList, iParent, pSub->pEList);
81954    if( isAgg ){
81955      substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
81956      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
81957    }
81958    if( pSub->pOrderBy ){
81959      assert( pParent->pOrderBy==0 );
81960      pParent->pOrderBy = pSub->pOrderBy;
81961      pSub->pOrderBy = 0;
81962    }else if( pParent->pOrderBy ){
81963      substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
81964    }
81965    if( pSub->pWhere ){
81966      pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
81967    }else{
81968      pWhere = 0;
81969    }
81970    if( subqueryIsAgg ){
81971      assert( pParent->pHaving==0 );
81972      pParent->pHaving = pParent->pWhere;
81973      pParent->pWhere = pWhere;
81974      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
81975      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
81976                                  sqlite3ExprDup(db, pSub->pHaving, 0));
81977      assert( pParent->pGroupBy==0 );
81978      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
81979    }else{
81980      pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
81981      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
81982    }
81983
81984    /* The flattened query is distinct if either the inner or the
81985    ** outer query is distinct.
81986    */
81987    pParent->selFlags |= pSub->selFlags & SF_Distinct;
81988
81989    /*
81990    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
81991    **
81992    ** One is tempted to try to add a and b to combine the limits.  But this
81993    ** does not work if either limit is negative.
81994    */
81995    if( pSub->pLimit ){
81996      pParent->pLimit = pSub->pLimit;
81997      pSub->pLimit = 0;
81998    }
81999  }
82000
82001  /* Finially, delete what is left of the subquery and return
82002  ** success.
82003  */
82004  sqlite3SelectDelete(db, pSub1);
82005
82006  return 1;
82007}
82008#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
82009
82010/*
82011** Analyze the SELECT statement passed as an argument to see if it
82012** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
82013** it is, or 0 otherwise. At present, a query is considered to be
82014** a min()/max() query if:
82015**
82016**   1. There is a single object in the FROM clause.
82017**
82018**   2. There is a single expression in the result set, and it is
82019**      either min(x) or max(x), where x is a column reference.
82020*/
82021static u8 minMaxQuery(Select *p){
82022  Expr *pExpr;
82023  ExprList *pEList = p->pEList;
82024
82025  if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
82026  pExpr = pEList->a[0].pExpr;
82027  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
82028  if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
82029  pEList = pExpr->x.pList;
82030  if( pEList==0 || pEList->nExpr!=1 ) return 0;
82031  if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
82032  assert( !ExprHasProperty(pExpr, EP_IntValue) );
82033  if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
82034    return WHERE_ORDERBY_MIN;
82035  }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
82036    return WHERE_ORDERBY_MAX;
82037  }
82038  return WHERE_ORDERBY_NORMAL;
82039}
82040
82041/*
82042** The select statement passed as the first argument is an aggregate query.
82043** The second argment is the associated aggregate-info object. This
82044** function tests if the SELECT is of the form:
82045**
82046**   SELECT count(*) FROM <tbl>
82047**
82048** where table is a database table, not a sub-select or view. If the query
82049** does match this pattern, then a pointer to the Table object representing
82050** <tbl> is returned. Otherwise, 0 is returned.
82051*/
82052static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
82053  Table *pTab;
82054  Expr *pExpr;
82055
82056  assert( !p->pGroupBy );
82057
82058  if( p->pWhere || p->pEList->nExpr!=1
82059   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
82060  ){
82061    return 0;
82062  }
82063  pTab = p->pSrc->a[0].pTab;
82064  pExpr = p->pEList->a[0].pExpr;
82065  assert( pTab && !pTab->pSelect && pExpr );
82066
82067  if( IsVirtual(pTab) ) return 0;
82068  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
82069  if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
82070  if( pExpr->flags&EP_Distinct ) return 0;
82071
82072  return pTab;
82073}
82074
82075/*
82076** If the source-list item passed as an argument was augmented with an
82077** INDEXED BY clause, then try to locate the specified index. If there
82078** was such a clause and the named index cannot be found, return
82079** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
82080** pFrom->pIndex and return SQLITE_OK.
82081*/
82082SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
82083  if( pFrom->pTab && pFrom->zIndex ){
82084    Table *pTab = pFrom->pTab;
82085    char *zIndex = pFrom->zIndex;
82086    Index *pIdx;
82087    for(pIdx=pTab->pIndex;
82088        pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
82089        pIdx=pIdx->pNext
82090    );
82091    if( !pIdx ){
82092      sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
82093      return SQLITE_ERROR;
82094    }
82095    pFrom->pIndex = pIdx;
82096  }
82097  return SQLITE_OK;
82098}
82099
82100/*
82101** This routine is a Walker callback for "expanding" a SELECT statement.
82102** "Expanding" means to do the following:
82103**
82104**    (1)  Make sure VDBE cursor numbers have been assigned to every
82105**         element of the FROM clause.
82106**
82107**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
82108**         defines FROM clause.  When views appear in the FROM clause,
82109**         fill pTabList->a[].pSelect with a copy of the SELECT statement
82110**         that implements the view.  A copy is made of the view's SELECT
82111**         statement so that we can freely modify or delete that statement
82112**         without worrying about messing up the presistent representation
82113**         of the view.
82114**
82115**    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
82116**         on joins and the ON and USING clause of joins.
82117**
82118**    (4)  Scan the list of columns in the result set (pEList) looking
82119**         for instances of the "*" operator or the TABLE.* operator.
82120**         If found, expand each "*" to be every column in every table
82121**         and TABLE.* to be every column in TABLE.
82122**
82123*/
82124static int selectExpander(Walker *pWalker, Select *p){
82125  Parse *pParse = pWalker->pParse;
82126  int i, j, k;
82127  SrcList *pTabList;
82128  ExprList *pEList;
82129  struct SrcList_item *pFrom;
82130  sqlite3 *db = pParse->db;
82131
82132  if( db->mallocFailed  ){
82133    return WRC_Abort;
82134  }
82135  if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
82136    return WRC_Prune;
82137  }
82138  p->selFlags |= SF_Expanded;
82139  pTabList = p->pSrc;
82140  pEList = p->pEList;
82141
82142  /* Make sure cursor numbers have been assigned to all entries in
82143  ** the FROM clause of the SELECT statement.
82144  */
82145  sqlite3SrcListAssignCursors(pParse, pTabList);
82146
82147  /* Look up every table named in the FROM clause of the select.  If
82148  ** an entry of the FROM clause is a subquery instead of a table or view,
82149  ** then create a transient table structure to describe the subquery.
82150  */
82151  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
82152    Table *pTab;
82153    if( pFrom->pTab!=0 ){
82154      /* This statement has already been prepared.  There is no need
82155      ** to go further. */
82156      assert( i==0 );
82157      return WRC_Prune;
82158    }
82159    if( pFrom->zName==0 ){
82160#ifndef SQLITE_OMIT_SUBQUERY
82161      Select *pSel = pFrom->pSelect;
82162      /* A sub-query in the FROM clause of a SELECT */
82163      assert( pSel!=0 );
82164      assert( pFrom->pTab==0 );
82165      sqlite3WalkSelect(pWalker, pSel);
82166      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
82167      if( pTab==0 ) return WRC_Abort;
82168      pTab->dbMem = db->lookaside.bEnabled ? db : 0;
82169      pTab->nRef = 1;
82170      pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
82171      while( pSel->pPrior ){ pSel = pSel->pPrior; }
82172      selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
82173      pTab->iPKey = -1;
82174      pTab->tabFlags |= TF_Ephemeral;
82175#endif
82176    }else{
82177      /* An ordinary table or view name in the FROM clause */
82178      assert( pFrom->pTab==0 );
82179      pFrom->pTab = pTab =
82180        sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
82181      if( pTab==0 ) return WRC_Abort;
82182      pTab->nRef++;
82183#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
82184      if( pTab->pSelect || IsVirtual(pTab) ){
82185        /* We reach here if the named table is a really a view */
82186        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
82187        assert( pFrom->pSelect==0 );
82188        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
82189        sqlite3WalkSelect(pWalker, pFrom->pSelect);
82190      }
82191#endif
82192    }
82193
82194    /* Locate the index named by the INDEXED BY clause, if any. */
82195    if( sqlite3IndexedByLookup(pParse, pFrom) ){
82196      return WRC_Abort;
82197    }
82198  }
82199
82200  /* Process NATURAL keywords, and ON and USING clauses of joins.
82201  */
82202  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
82203    return WRC_Abort;
82204  }
82205
82206  /* For every "*" that occurs in the column list, insert the names of
82207  ** all columns in all tables.  And for every TABLE.* insert the names
82208  ** of all columns in TABLE.  The parser inserted a special expression
82209  ** with the TK_ALL operator for each "*" that it found in the column list.
82210  ** The following code just has to locate the TK_ALL expressions and expand
82211  ** each one to the list of all columns in all tables.
82212  **
82213  ** The first loop just checks to see if there are any "*" operators
82214  ** that need expanding.
82215  */
82216  for(k=0; k<pEList->nExpr; k++){
82217    Expr *pE = pEList->a[k].pExpr;
82218    if( pE->op==TK_ALL ) break;
82219    assert( pE->op!=TK_DOT || pE->pRight!=0 );
82220    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
82221    if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
82222  }
82223  if( k<pEList->nExpr ){
82224    /*
82225    ** If we get here it means the result set contains one or more "*"
82226    ** operators that need to be expanded.  Loop through each expression
82227    ** in the result set and expand them one by one.
82228    */
82229    struct ExprList_item *a = pEList->a;
82230    ExprList *pNew = 0;
82231    int flags = pParse->db->flags;
82232    int longNames = (flags & SQLITE_FullColNames)!=0
82233                      && (flags & SQLITE_ShortColNames)==0;
82234
82235    for(k=0; k<pEList->nExpr; k++){
82236      Expr *pE = a[k].pExpr;
82237      assert( pE->op!=TK_DOT || pE->pRight!=0 );
82238      if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
82239        /* This particular expression does not need to be expanded.
82240        */
82241        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
82242        if( pNew ){
82243          pNew->a[pNew->nExpr-1].zName = a[k].zName;
82244          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
82245          a[k].zName = 0;
82246          a[k].zSpan = 0;
82247        }
82248        a[k].pExpr = 0;
82249      }else{
82250        /* This expression is a "*" or a "TABLE.*" and needs to be
82251        ** expanded. */
82252        int tableSeen = 0;      /* Set to 1 when TABLE matches */
82253        char *zTName;            /* text of name of TABLE */
82254        if( pE->op==TK_DOT ){
82255          assert( pE->pLeft!=0 );
82256          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
82257          zTName = pE->pLeft->u.zToken;
82258        }else{
82259          zTName = 0;
82260        }
82261        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
82262          Table *pTab = pFrom->pTab;
82263          char *zTabName = pFrom->zAlias;
82264          if( zTabName==0 ){
82265            zTabName = pTab->zName;
82266          }
82267          if( db->mallocFailed ) break;
82268          if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
82269            continue;
82270          }
82271          tableSeen = 1;
82272          for(j=0; j<pTab->nCol; j++){
82273            Expr *pExpr, *pRight;
82274            char *zName = pTab->aCol[j].zName;
82275            char *zColname;  /* The computed column name */
82276            char *zToFree;   /* Malloced string that needs to be freed */
82277            Token sColname;  /* Computed column name as a token */
82278
82279            /* If a column is marked as 'hidden' (currently only possible
82280            ** for virtual tables), do not include it in the expanded
82281            ** result-set list.
82282            */
82283            if( IsHiddenColumn(&pTab->aCol[j]) ){
82284              assert(IsVirtual(pTab));
82285              continue;
82286            }
82287
82288            if( i>0 && zTName==0 ){
82289              if( (pFrom->jointype & JT_NATURAL)!=0
82290                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
82291              ){
82292                /* In a NATURAL join, omit the join columns from the
82293                ** table to the right of the join */
82294                continue;
82295              }
82296              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
82297                /* In a join with a USING clause, omit columns in the
82298                ** using clause from the table on the right. */
82299                continue;
82300              }
82301            }
82302            pRight = sqlite3Expr(db, TK_ID, zName);
82303            zColname = zName;
82304            zToFree = 0;
82305            if( longNames || pTabList->nSrc>1 ){
82306              Expr *pLeft;
82307              pLeft = sqlite3Expr(db, TK_ID, zTabName);
82308              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
82309              if( longNames ){
82310                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
82311                zToFree = zColname;
82312              }
82313            }else{
82314              pExpr = pRight;
82315            }
82316            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
82317            sColname.z = zColname;
82318            sColname.n = sqlite3Strlen30(zColname);
82319            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
82320            sqlite3DbFree(db, zToFree);
82321          }
82322        }
82323        if( !tableSeen ){
82324          if( zTName ){
82325            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
82326          }else{
82327            sqlite3ErrorMsg(pParse, "no tables specified");
82328          }
82329        }
82330      }
82331    }
82332    sqlite3ExprListDelete(db, pEList);
82333    p->pEList = pNew;
82334  }
82335#if SQLITE_MAX_COLUMN
82336  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
82337    sqlite3ErrorMsg(pParse, "too many columns in result set");
82338  }
82339#endif
82340  return WRC_Continue;
82341}
82342
82343/*
82344** No-op routine for the parse-tree walker.
82345**
82346** When this routine is the Walker.xExprCallback then expression trees
82347** are walked without any actions being taken at each node.  Presumably,
82348** when this routine is used for Walker.xExprCallback then
82349** Walker.xSelectCallback is set to do something useful for every
82350** subquery in the parser tree.
82351*/
82352static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
82353  UNUSED_PARAMETER2(NotUsed, NotUsed2);
82354  return WRC_Continue;
82355}
82356
82357/*
82358** This routine "expands" a SELECT statement and all of its subqueries.
82359** For additional information on what it means to "expand" a SELECT
82360** statement, see the comment on the selectExpand worker callback above.
82361**
82362** Expanding a SELECT statement is the first step in processing a
82363** SELECT statement.  The SELECT statement must be expanded before
82364** name resolution is performed.
82365**
82366** If anything goes wrong, an error message is written into pParse.
82367** The calling function can detect the problem by looking at pParse->nErr
82368** and/or pParse->db->mallocFailed.
82369*/
82370static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
82371  Walker w;
82372  w.xSelectCallback = selectExpander;
82373  w.xExprCallback = exprWalkNoop;
82374  w.pParse = pParse;
82375  sqlite3WalkSelect(&w, pSelect);
82376}
82377
82378
82379#ifndef SQLITE_OMIT_SUBQUERY
82380/*
82381** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
82382** interface.
82383**
82384** For each FROM-clause subquery, add Column.zType and Column.zColl
82385** information to the Table structure that represents the result set
82386** of that subquery.
82387**
82388** The Table structure that represents the result set was constructed
82389** by selectExpander() but the type and collation information was omitted
82390** at that point because identifiers had not yet been resolved.  This
82391** routine is called after identifier resolution.
82392*/
82393static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
82394  Parse *pParse;
82395  int i;
82396  SrcList *pTabList;
82397  struct SrcList_item *pFrom;
82398
82399  assert( p->selFlags & SF_Resolved );
82400  assert( (p->selFlags & SF_HasTypeInfo)==0 );
82401  p->selFlags |= SF_HasTypeInfo;
82402  pParse = pWalker->pParse;
82403  pTabList = p->pSrc;
82404  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
82405    Table *pTab = pFrom->pTab;
82406    if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
82407      /* A sub-query in the FROM clause of a SELECT */
82408      Select *pSel = pFrom->pSelect;
82409      assert( pSel );
82410      while( pSel->pPrior ) pSel = pSel->pPrior;
82411      selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
82412    }
82413  }
82414  return WRC_Continue;
82415}
82416#endif
82417
82418
82419/*
82420** This routine adds datatype and collating sequence information to
82421** the Table structures of all FROM-clause subqueries in a
82422** SELECT statement.
82423**
82424** Use this routine after name resolution.
82425*/
82426static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
82427#ifndef SQLITE_OMIT_SUBQUERY
82428  Walker w;
82429  w.xSelectCallback = selectAddSubqueryTypeInfo;
82430  w.xExprCallback = exprWalkNoop;
82431  w.pParse = pParse;
82432  sqlite3WalkSelect(&w, pSelect);
82433#endif
82434}
82435
82436
82437/*
82438** This routine sets of a SELECT statement for processing.  The
82439** following is accomplished:
82440**
82441**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
82442**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
82443**     *  ON and USING clauses are shifted into WHERE statements
82444**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
82445**     *  Identifiers in expression are matched to tables.
82446**
82447** This routine acts recursively on all subqueries within the SELECT.
82448*/
82449SQLITE_PRIVATE void sqlite3SelectPrep(
82450  Parse *pParse,         /* The parser context */
82451  Select *p,             /* The SELECT statement being coded. */
82452  NameContext *pOuterNC  /* Name context for container */
82453){
82454  sqlite3 *db;
82455  if( NEVER(p==0) ) return;
82456  db = pParse->db;
82457  if( p->selFlags & SF_HasTypeInfo ) return;
82458  sqlite3SelectExpand(pParse, p);
82459  if( pParse->nErr || db->mallocFailed ) return;
82460  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
82461  if( pParse->nErr || db->mallocFailed ) return;
82462  sqlite3SelectAddTypeInfo(pParse, p);
82463}
82464
82465/*
82466** Reset the aggregate accumulator.
82467**
82468** The aggregate accumulator is a set of memory cells that hold
82469** intermediate results while calculating an aggregate.  This
82470** routine simply stores NULLs in all of those memory cells.
82471*/
82472static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
82473  Vdbe *v = pParse->pVdbe;
82474  int i;
82475  struct AggInfo_func *pFunc;
82476  if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
82477    return;
82478  }
82479  for(i=0; i<pAggInfo->nColumn; i++){
82480    sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
82481  }
82482  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
82483    sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
82484    if( pFunc->iDistinct>=0 ){
82485      Expr *pE = pFunc->pExpr;
82486      assert( !ExprHasProperty(pE, EP_xIsSelect) );
82487      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
82488        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
82489           "argument");
82490        pFunc->iDistinct = -1;
82491      }else{
82492        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
82493        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
82494                          (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82495      }
82496    }
82497  }
82498}
82499
82500/*
82501** Invoke the OP_AggFinalize opcode for every aggregate function
82502** in the AggInfo structure.
82503*/
82504static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
82505  Vdbe *v = pParse->pVdbe;
82506  int i;
82507  struct AggInfo_func *pF;
82508  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
82509    ExprList *pList = pF->pExpr->x.pList;
82510    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
82511    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
82512                      (void*)pF->pFunc, P4_FUNCDEF);
82513  }
82514}
82515
82516/*
82517** Update the accumulator memory cells for an aggregate based on
82518** the current cursor position.
82519*/
82520static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
82521  Vdbe *v = pParse->pVdbe;
82522  int i;
82523  struct AggInfo_func *pF;
82524  struct AggInfo_col *pC;
82525
82526  pAggInfo->directMode = 1;
82527  sqlite3ExprCacheClear(pParse);
82528  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
82529    int nArg;
82530    int addrNext = 0;
82531    int regAgg;
82532    ExprList *pList = pF->pExpr->x.pList;
82533    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
82534    if( pList ){
82535      nArg = pList->nExpr;
82536      regAgg = sqlite3GetTempRange(pParse, nArg);
82537      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
82538    }else{
82539      nArg = 0;
82540      regAgg = 0;
82541    }
82542    if( pF->iDistinct>=0 ){
82543      addrNext = sqlite3VdbeMakeLabel(v);
82544      assert( nArg==1 );
82545      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
82546    }
82547    if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
82548      CollSeq *pColl = 0;
82549      struct ExprList_item *pItem;
82550      int j;
82551      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
82552      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
82553        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
82554      }
82555      if( !pColl ){
82556        pColl = pParse->db->pDfltColl;
82557      }
82558      sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
82559    }
82560    sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
82561                      (void*)pF->pFunc, P4_FUNCDEF);
82562    sqlite3VdbeChangeP5(v, (u8)nArg);
82563    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
82564    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
82565    if( addrNext ){
82566      sqlite3VdbeResolveLabel(v, addrNext);
82567      sqlite3ExprCacheClear(pParse);
82568    }
82569  }
82570  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
82571    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
82572  }
82573  pAggInfo->directMode = 0;
82574  sqlite3ExprCacheClear(pParse);
82575}
82576
82577/*
82578** Generate code for the SELECT statement given in the p argument.
82579**
82580** The results are distributed in various ways depending on the
82581** contents of the SelectDest structure pointed to by argument pDest
82582** as follows:
82583**
82584**     pDest->eDest    Result
82585**     ------------    -------------------------------------------
82586**     SRT_Output      Generate a row of output (using the OP_ResultRow
82587**                     opcode) for each row in the result set.
82588**
82589**     SRT_Mem         Only valid if the result is a single column.
82590**                     Store the first column of the first result row
82591**                     in register pDest->iParm then abandon the rest
82592**                     of the query.  This destination implies "LIMIT 1".
82593**
82594**     SRT_Set         The result must be a single column.  Store each
82595**                     row of result as the key in table pDest->iParm.
82596**                     Apply the affinity pDest->affinity before storing
82597**                     results.  Used to implement "IN (SELECT ...)".
82598**
82599**     SRT_Union       Store results as a key in a temporary table pDest->iParm.
82600**
82601**     SRT_Except      Remove results from the temporary table pDest->iParm.
82602**
82603**     SRT_Table       Store results in temporary table pDest->iParm.
82604**                     This is like SRT_EphemTab except that the table
82605**                     is assumed to already be open.
82606**
82607**     SRT_EphemTab    Create an temporary table pDest->iParm and store
82608**                     the result there. The cursor is left open after
82609**                     returning.  This is like SRT_Table except that
82610**                     this destination uses OP_OpenEphemeral to create
82611**                     the table first.
82612**
82613**     SRT_Coroutine   Generate a co-routine that returns a new row of
82614**                     results each time it is invoked.  The entry point
82615**                     of the co-routine is stored in register pDest->iParm.
82616**
82617**     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
82618**                     set is not empty.
82619**
82620**     SRT_Discard     Throw the results away.  This is used by SELECT
82621**                     statements within triggers whose only purpose is
82622**                     the side-effects of functions.
82623**
82624** This routine returns the number of errors.  If any errors are
82625** encountered, then an appropriate error message is left in
82626** pParse->zErrMsg.
82627**
82628** This routine does NOT free the Select structure passed in.  The
82629** calling function needs to do that.
82630*/
82631SQLITE_PRIVATE int sqlite3Select(
82632  Parse *pParse,         /* The parser context */
82633  Select *p,             /* The SELECT statement being coded. */
82634  SelectDest *pDest      /* What to do with the query results */
82635){
82636  int i, j;              /* Loop counters */
82637  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
82638  Vdbe *v;               /* The virtual machine under construction */
82639  int isAgg;             /* True for select lists like "count(*)" */
82640  ExprList *pEList;      /* List of columns to extract. */
82641  SrcList *pTabList;     /* List of tables to select from */
82642  Expr *pWhere;          /* The WHERE clause.  May be NULL */
82643  ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
82644  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
82645  Expr *pHaving;         /* The HAVING clause.  May be NULL */
82646  int isDistinct;        /* True if the DISTINCT keyword is present */
82647  int distinct;          /* Table to use for the distinct set */
82648  int rc = 1;            /* Value to return from this function */
82649  int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
82650  AggInfo sAggInfo;      /* Information used by aggregate queries */
82651  int iEnd;              /* Address of the end of the query */
82652  sqlite3 *db;           /* The database connection */
82653
82654  db = pParse->db;
82655  if( p==0 || db->mallocFailed || pParse->nErr ){
82656    return 1;
82657  }
82658  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
82659  memset(&sAggInfo, 0, sizeof(sAggInfo));
82660
82661  if( IgnorableOrderby(pDest) ){
82662    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
82663           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
82664    /* If ORDER BY makes no difference in the output then neither does
82665    ** DISTINCT so it can be removed too. */
82666    sqlite3ExprListDelete(db, p->pOrderBy);
82667    p->pOrderBy = 0;
82668    p->selFlags &= ~SF_Distinct;
82669  }
82670  sqlite3SelectPrep(pParse, p, 0);
82671  pOrderBy = p->pOrderBy;
82672  pTabList = p->pSrc;
82673  pEList = p->pEList;
82674  if( pParse->nErr || db->mallocFailed ){
82675    goto select_end;
82676  }
82677  isAgg = (p->selFlags & SF_Aggregate)!=0;
82678  assert( pEList!=0 );
82679
82680  /* Begin generating code.
82681  */
82682  v = sqlite3GetVdbe(pParse);
82683  if( v==0 ) goto select_end;
82684
82685  /* Generate code for all sub-queries in the FROM clause
82686  */
82687#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
82688  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
82689    struct SrcList_item *pItem = &pTabList->a[i];
82690    SelectDest dest;
82691    Select *pSub = pItem->pSelect;
82692    int isAggSub;
82693
82694    if( pSub==0 || pItem->isPopulated ) continue;
82695
82696    /* Increment Parse.nHeight by the height of the largest expression
82697    ** tree refered to by this, the parent select. The child select
82698    ** may contain expression trees of at most
82699    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
82700    ** more conservative than necessary, but much easier than enforcing
82701    ** an exact limit.
82702    */
82703    pParse->nHeight += sqlite3SelectExprHeight(p);
82704
82705    /* Check to see if the subquery can be absorbed into the parent. */
82706    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
82707    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
82708      if( isAggSub ){
82709        isAgg = 1;
82710        p->selFlags |= SF_Aggregate;
82711      }
82712      i = -1;
82713    }else{
82714      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
82715      assert( pItem->isPopulated==0 );
82716      sqlite3Select(pParse, pSub, &dest);
82717      pItem->isPopulated = 1;
82718    }
82719    if( /*pParse->nErr ||*/ db->mallocFailed ){
82720      goto select_end;
82721    }
82722    pParse->nHeight -= sqlite3SelectExprHeight(p);
82723    pTabList = p->pSrc;
82724    if( !IgnorableOrderby(pDest) ){
82725      pOrderBy = p->pOrderBy;
82726    }
82727  }
82728  pEList = p->pEList;
82729#endif
82730  pWhere = p->pWhere;
82731  pGroupBy = p->pGroupBy;
82732  pHaving = p->pHaving;
82733  isDistinct = (p->selFlags & SF_Distinct)!=0;
82734
82735#ifndef SQLITE_OMIT_COMPOUND_SELECT
82736  /* If there is are a sequence of queries, do the earlier ones first.
82737  */
82738  if( p->pPrior ){
82739    if( p->pRightmost==0 ){
82740      Select *pLoop, *pRight = 0;
82741      int cnt = 0;
82742      int mxSelect;
82743      for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
82744        pLoop->pRightmost = p;
82745        pLoop->pNext = pRight;
82746        pRight = pLoop;
82747      }
82748      mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
82749      if( mxSelect && cnt>mxSelect ){
82750        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
82751        return 1;
82752      }
82753    }
82754    return multiSelect(pParse, p, pDest);
82755  }
82756#endif
82757
82758  /* If writing to memory or generating a set
82759  ** only a single column may be output.
82760  */
82761#ifndef SQLITE_OMIT_SUBQUERY
82762  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
82763    goto select_end;
82764  }
82765#endif
82766
82767  /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
82768  ** GROUP BY might use an index, DISTINCT never does.
82769  */
82770  assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
82771  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
82772    p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
82773    pGroupBy = p->pGroupBy;
82774    p->selFlags &= ~SF_Distinct;
82775    isDistinct = 0;
82776  }
82777
82778  /* If there is an ORDER BY clause, then this sorting
82779  ** index might end up being unused if the data can be
82780  ** extracted in pre-sorted order.  If that is the case, then the
82781  ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
82782  ** we figure out that the sorting index is not needed.  The addrSortIndex
82783  ** variable is used to facilitate that change.
82784  */
82785  if( pOrderBy ){
82786    KeyInfo *pKeyInfo;
82787    pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
82788    pOrderBy->iECursor = pParse->nTab++;
82789    p->addrOpenEphm[2] = addrSortIndex =
82790      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
82791                           pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
82792                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82793  }else{
82794    addrSortIndex = -1;
82795  }
82796
82797  /* If the output is destined for a temporary table, open that table.
82798  */
82799  if( pDest->eDest==SRT_EphemTab ){
82800    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
82801  }
82802
82803  /* Set the limiter.
82804  */
82805  iEnd = sqlite3VdbeMakeLabel(v);
82806  computeLimitRegisters(pParse, p, iEnd);
82807
82808  /* Open a virtual index to use for the distinct set.
82809  */
82810  if( isDistinct ){
82811    KeyInfo *pKeyInfo;
82812    assert( isAgg || pGroupBy );
82813    distinct = pParse->nTab++;
82814    pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
82815    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
82816                        (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82817  }else{
82818    distinct = -1;
82819  }
82820
82821  /* Aggregate and non-aggregate queries are handled differently */
82822  if( !isAgg && pGroupBy==0 ){
82823    /* This case is for non-aggregate queries
82824    ** Begin the database scan
82825    */
82826    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
82827    if( pWInfo==0 ) goto select_end;
82828
82829    /* If sorting index that was created by a prior OP_OpenEphemeral
82830    ** instruction ended up not being needed, then change the OP_OpenEphemeral
82831    ** into an OP_Noop.
82832    */
82833    if( addrSortIndex>=0 && pOrderBy==0 ){
82834      sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
82835      p->addrOpenEphm[2] = -1;
82836    }
82837
82838    /* Use the standard inner loop
82839    */
82840    assert(!isDistinct);
82841    selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
82842                    pWInfo->iContinue, pWInfo->iBreak);
82843
82844    /* End the database scan loop.
82845    */
82846    sqlite3WhereEnd(pWInfo);
82847  }else{
82848    /* This is the processing for aggregate queries */
82849    NameContext sNC;    /* Name context for processing aggregate information */
82850    int iAMem;          /* First Mem address for storing current GROUP BY */
82851    int iBMem;          /* First Mem address for previous GROUP BY */
82852    int iUseFlag;       /* Mem address holding flag indicating that at least
82853                        ** one row of the input to the aggregator has been
82854                        ** processed */
82855    int iAbortFlag;     /* Mem address which causes query abort if positive */
82856    int groupBySort;    /* Rows come from source in GROUP BY order */
82857    int addrEnd;        /* End of processing for this SELECT */
82858
82859    /* Remove any and all aliases between the result set and the
82860    ** GROUP BY clause.
82861    */
82862    if( pGroupBy ){
82863      int k;                        /* Loop counter */
82864      struct ExprList_item *pItem;  /* For looping over expression in a list */
82865
82866      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
82867        pItem->iAlias = 0;
82868      }
82869      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
82870        pItem->iAlias = 0;
82871      }
82872    }
82873
82874
82875    /* Create a label to jump to when we want to abort the query */
82876    addrEnd = sqlite3VdbeMakeLabel(v);
82877
82878    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
82879    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
82880    ** SELECT statement.
82881    */
82882    memset(&sNC, 0, sizeof(sNC));
82883    sNC.pParse = pParse;
82884    sNC.pSrcList = pTabList;
82885    sNC.pAggInfo = &sAggInfo;
82886    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
82887    sAggInfo.pGroupBy = pGroupBy;
82888    sqlite3ExprAnalyzeAggList(&sNC, pEList);
82889    sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
82890    if( pHaving ){
82891      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
82892    }
82893    sAggInfo.nAccumulator = sAggInfo.nColumn;
82894    for(i=0; i<sAggInfo.nFunc; i++){
82895      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
82896      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
82897    }
82898    if( db->mallocFailed ) goto select_end;
82899
82900    /* Processing for aggregates with GROUP BY is very different and
82901    ** much more complex than aggregates without a GROUP BY.
82902    */
82903    if( pGroupBy ){
82904      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
82905      int j1;             /* A-vs-B comparision jump */
82906      int addrOutputRow;  /* Start of subroutine that outputs a result row */
82907      int regOutputRow;   /* Return address register for output subroutine */
82908      int addrSetAbort;   /* Set the abort flag and return */
82909      int addrTopOfLoop;  /* Top of the input loop */
82910      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
82911      int addrReset;      /* Subroutine for resetting the accumulator */
82912      int regReset;       /* Return address register for reset subroutine */
82913
82914      /* If there is a GROUP BY clause we might need a sorting index to
82915      ** implement it.  Allocate that sorting index now.  If it turns out
82916      ** that we do not need it after all, the OpenEphemeral instruction
82917      ** will be converted into a Noop.
82918      */
82919      sAggInfo.sortingIdx = pParse->nTab++;
82920      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
82921      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
82922          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
82923          0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82924
82925      /* Initialize memory locations used by GROUP BY aggregate processing
82926      */
82927      iUseFlag = ++pParse->nMem;
82928      iAbortFlag = ++pParse->nMem;
82929      regOutputRow = ++pParse->nMem;
82930      addrOutputRow = sqlite3VdbeMakeLabel(v);
82931      regReset = ++pParse->nMem;
82932      addrReset = sqlite3VdbeMakeLabel(v);
82933      iAMem = pParse->nMem + 1;
82934      pParse->nMem += pGroupBy->nExpr;
82935      iBMem = pParse->nMem + 1;
82936      pParse->nMem += pGroupBy->nExpr;
82937      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
82938      VdbeComment((v, "clear abort flag"));
82939      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
82940      VdbeComment((v, "indicate accumulator empty"));
82941
82942      /* Begin a loop that will extract all source rows in GROUP BY order.
82943      ** This might involve two separate loops with an OP_Sort in between, or
82944      ** it might be a single loop that uses an index to extract information
82945      ** in the right order to begin with.
82946      */
82947      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
82948      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
82949      if( pWInfo==0 ) goto select_end;
82950      if( pGroupBy==0 ){
82951        /* The optimizer is able to deliver rows in group by order so
82952        ** we do not have to sort.  The OP_OpenEphemeral table will be
82953        ** cancelled later because we still need to use the pKeyInfo
82954        */
82955        pGroupBy = p->pGroupBy;
82956        groupBySort = 0;
82957      }else{
82958        /* Rows are coming out in undetermined order.  We have to push
82959        ** each row into a sorting index, terminate the first loop,
82960        ** then loop over the sorting index in order to get the output
82961        ** in sorted order
82962        */
82963        int regBase;
82964        int regRecord;
82965        int nCol;
82966        int nGroupBy;
82967
82968        groupBySort = 1;
82969        nGroupBy = pGroupBy->nExpr;
82970        nCol = nGroupBy + 1;
82971        j = nGroupBy+1;
82972        for(i=0; i<sAggInfo.nColumn; i++){
82973          if( sAggInfo.aCol[i].iSorterColumn>=j ){
82974            nCol++;
82975            j++;
82976          }
82977        }
82978        regBase = sqlite3GetTempRange(pParse, nCol);
82979        sqlite3ExprCacheClear(pParse);
82980        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
82981        sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
82982        j = nGroupBy+1;
82983        for(i=0; i<sAggInfo.nColumn; i++){
82984          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
82985          if( pCol->iSorterColumn>=j ){
82986            int r1 = j + regBase;
82987            int r2;
82988
82989            r2 = sqlite3ExprCodeGetColumn(pParse,
82990                               pCol->pTab, pCol->iColumn, pCol->iTable, r1);
82991            if( r1!=r2 ){
82992              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
82993            }
82994            j++;
82995          }
82996        }
82997        regRecord = sqlite3GetTempReg(pParse);
82998        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
82999        sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
83000        sqlite3ReleaseTempReg(pParse, regRecord);
83001        sqlite3ReleaseTempRange(pParse, regBase, nCol);
83002        sqlite3WhereEnd(pWInfo);
83003        sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
83004        VdbeComment((v, "GROUP BY sort"));
83005        sAggInfo.useSortingIdx = 1;
83006        sqlite3ExprCacheClear(pParse);
83007      }
83008
83009      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
83010      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
83011      ** Then compare the current GROUP BY terms against the GROUP BY terms
83012      ** from the previous row currently stored in a0, a1, a2...
83013      */
83014      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
83015      sqlite3ExprCacheClear(pParse);
83016      for(j=0; j<pGroupBy->nExpr; j++){
83017        if( groupBySort ){
83018          sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
83019        }else{
83020          sAggInfo.directMode = 1;
83021          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
83022        }
83023      }
83024      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
83025                          (char*)pKeyInfo, P4_KEYINFO);
83026      j1 = sqlite3VdbeCurrentAddr(v);
83027      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
83028
83029      /* Generate code that runs whenever the GROUP BY changes.
83030      ** Changes in the GROUP BY are detected by the previous code
83031      ** block.  If there were no changes, this block is skipped.
83032      **
83033      ** This code copies current group by terms in b0,b1,b2,...
83034      ** over to a0,a1,a2.  It then calls the output subroutine
83035      ** and resets the aggregate accumulator registers in preparation
83036      ** for the next GROUP BY batch.
83037      */
83038      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
83039      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
83040      VdbeComment((v, "output one row"));
83041      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
83042      VdbeComment((v, "check abort flag"));
83043      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
83044      VdbeComment((v, "reset accumulator"));
83045
83046      /* Update the aggregate accumulators based on the content of
83047      ** the current row
83048      */
83049      sqlite3VdbeJumpHere(v, j1);
83050      updateAccumulator(pParse, &sAggInfo);
83051      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
83052      VdbeComment((v, "indicate data in accumulator"));
83053
83054      /* End of the loop
83055      */
83056      if( groupBySort ){
83057        sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
83058      }else{
83059        sqlite3WhereEnd(pWInfo);
83060        sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
83061      }
83062
83063      /* Output the final row of result
83064      */
83065      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
83066      VdbeComment((v, "output final row"));
83067
83068      /* Jump over the subroutines
83069      */
83070      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
83071
83072      /* Generate a subroutine that outputs a single row of the result
83073      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
83074      ** is less than or equal to zero, the subroutine is a no-op.  If
83075      ** the processing calls for the query to abort, this subroutine
83076      ** increments the iAbortFlag memory location before returning in
83077      ** order to signal the caller to abort.
83078      */
83079      addrSetAbort = sqlite3VdbeCurrentAddr(v);
83080      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
83081      VdbeComment((v, "set abort flag"));
83082      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
83083      sqlite3VdbeResolveLabel(v, addrOutputRow);
83084      addrOutputRow = sqlite3VdbeCurrentAddr(v);
83085      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
83086      VdbeComment((v, "Groupby result generator entry point"));
83087      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
83088      finalizeAggFunctions(pParse, &sAggInfo);
83089      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
83090      selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
83091                      distinct, pDest,
83092                      addrOutputRow+1, addrSetAbort);
83093      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
83094      VdbeComment((v, "end groupby result generator"));
83095
83096      /* Generate a subroutine that will reset the group-by accumulator
83097      */
83098      sqlite3VdbeResolveLabel(v, addrReset);
83099      resetAccumulator(pParse, &sAggInfo);
83100      sqlite3VdbeAddOp1(v, OP_Return, regReset);
83101
83102    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
83103    else {
83104      ExprList *pDel = 0;
83105#ifndef SQLITE_OMIT_BTREECOUNT
83106      Table *pTab;
83107      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
83108        /* If isSimpleCount() returns a pointer to a Table structure, then
83109        ** the SQL statement is of the form:
83110        **
83111        **   SELECT count(*) FROM <tbl>
83112        **
83113        ** where the Table structure returned represents table <tbl>.
83114        **
83115        ** This statement is so common that it is optimized specially. The
83116        ** OP_Count instruction is executed either on the intkey table that
83117        ** contains the data for table <tbl> or on one of its indexes. It
83118        ** is better to execute the op on an index, as indexes are almost
83119        ** always spread across less pages than their corresponding tables.
83120        */
83121        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
83122        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
83123        Index *pIdx;                         /* Iterator variable */
83124        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
83125        Index *pBest = 0;                    /* Best index found so far */
83126        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
83127
83128        sqlite3CodeVerifySchema(pParse, iDb);
83129        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
83130
83131        /* Search for the index that has the least amount of columns. If
83132        ** there is such an index, and it has less columns than the table
83133        ** does, then we can assume that it consumes less space on disk and
83134        ** will therefore be cheaper to scan to determine the query result.
83135        ** In this case set iRoot to the root page number of the index b-tree
83136        ** and pKeyInfo to the KeyInfo structure required to navigate the
83137        ** index.
83138        **
83139        ** In practice the KeyInfo structure will not be used. It is only
83140        ** passed to keep OP_OpenRead happy.
83141        */
83142        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83143          if( !pBest || pIdx->nColumn<pBest->nColumn ){
83144            pBest = pIdx;
83145          }
83146        }
83147        if( pBest && pBest->nColumn<pTab->nCol ){
83148          iRoot = pBest->tnum;
83149          pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
83150        }
83151
83152        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
83153        sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
83154        if( pKeyInfo ){
83155          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
83156        }
83157        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
83158        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
83159      }else
83160#endif /* SQLITE_OMIT_BTREECOUNT */
83161      {
83162        /* Check if the query is of one of the following forms:
83163        **
83164        **   SELECT min(x) FROM ...
83165        **   SELECT max(x) FROM ...
83166        **
83167        ** If it is, then ask the code in where.c to attempt to sort results
83168        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
83169        ** If where.c is able to produce results sorted in this order, then
83170        ** add vdbe code to break out of the processing loop after the
83171        ** first iteration (since the first iteration of the loop is
83172        ** guaranteed to operate on the row with the minimum or maximum
83173        ** value of x, the only row required).
83174        **
83175        ** A special flag must be passed to sqlite3WhereBegin() to slightly
83176        ** modify behaviour as follows:
83177        **
83178        **   + If the query is a "SELECT min(x)", then the loop coded by
83179        **     where.c should not iterate over any values with a NULL value
83180        **     for x.
83181        **
83182        **   + The optimizer code in where.c (the thing that decides which
83183        **     index or indices to use) should place a different priority on
83184        **     satisfying the 'ORDER BY' clause than it does in other cases.
83185        **     Refer to code and comments in where.c for details.
83186        */
83187        ExprList *pMinMax = 0;
83188        u8 flag = minMaxQuery(p);
83189        if( flag ){
83190          assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
83191          pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
83192          pDel = pMinMax;
83193          if( pMinMax && !db->mallocFailed ){
83194            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
83195            pMinMax->a[0].pExpr->op = TK_COLUMN;
83196          }
83197        }
83198
83199        /* This case runs if the aggregate has no GROUP BY clause.  The
83200        ** processing is much simpler since there is only a single row
83201        ** of output.
83202        */
83203        resetAccumulator(pParse, &sAggInfo);
83204        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
83205        if( pWInfo==0 ){
83206          sqlite3ExprListDelete(db, pDel);
83207          goto select_end;
83208        }
83209        updateAccumulator(pParse, &sAggInfo);
83210        if( !pMinMax && flag ){
83211          sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
83212          VdbeComment((v, "%s() by index",
83213                (flag==WHERE_ORDERBY_MIN?"min":"max")));
83214        }
83215        sqlite3WhereEnd(pWInfo);
83216        finalizeAggFunctions(pParse, &sAggInfo);
83217      }
83218
83219      pOrderBy = 0;
83220      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
83221      selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
83222                      pDest, addrEnd, addrEnd);
83223      sqlite3ExprListDelete(db, pDel);
83224    }
83225    sqlite3VdbeResolveLabel(v, addrEnd);
83226
83227  } /* endif aggregate query */
83228
83229  /* If there is an ORDER BY clause, then we need to sort the results
83230  ** and send them to the callback one by one.
83231  */
83232  if( pOrderBy ){
83233    generateSortTail(pParse, p, v, pEList->nExpr, pDest);
83234  }
83235
83236  /* Jump here to skip this query
83237  */
83238  sqlite3VdbeResolveLabel(v, iEnd);
83239
83240  /* The SELECT was successfully coded.   Set the return code to 0
83241  ** to indicate no errors.
83242  */
83243  rc = 0;
83244
83245  /* Control jumps to here if an error is encountered above, or upon
83246  ** successful coding of the SELECT.
83247  */
83248select_end:
83249
83250  /* Identify column names if results of the SELECT are to be output.
83251  */
83252  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
83253    generateColumnNames(pParse, pTabList, pEList);
83254  }
83255
83256  sqlite3DbFree(db, sAggInfo.aCol);
83257  sqlite3DbFree(db, sAggInfo.aFunc);
83258  return rc;
83259}
83260
83261#if defined(SQLITE_DEBUG)
83262/*
83263*******************************************************************************
83264** The following code is used for testing and debugging only.  The code
83265** that follows does not appear in normal builds.
83266**
83267** These routines are used to print out the content of all or part of a
83268** parse structures such as Select or Expr.  Such printouts are useful
83269** for helping to understand what is happening inside the code generator
83270** during the execution of complex SELECT statements.
83271**
83272** These routine are not called anywhere from within the normal
83273** code base.  Then are intended to be called from within the debugger
83274** or from temporary "printf" statements inserted for debugging.
83275*/
83276SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
83277  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
83278    sqlite3DebugPrintf("(%s", p->u.zToken);
83279  }else{
83280    sqlite3DebugPrintf("(%d", p->op);
83281  }
83282  if( p->pLeft ){
83283    sqlite3DebugPrintf(" ");
83284    sqlite3PrintExpr(p->pLeft);
83285  }
83286  if( p->pRight ){
83287    sqlite3DebugPrintf(" ");
83288    sqlite3PrintExpr(p->pRight);
83289  }
83290  sqlite3DebugPrintf(")");
83291}
83292SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
83293  int i;
83294  for(i=0; i<pList->nExpr; i++){
83295    sqlite3PrintExpr(pList->a[i].pExpr);
83296    if( i<pList->nExpr-1 ){
83297      sqlite3DebugPrintf(", ");
83298    }
83299  }
83300}
83301SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
83302  sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
83303  sqlite3PrintExprList(p->pEList);
83304  sqlite3DebugPrintf("\n");
83305  if( p->pSrc ){
83306    char *zPrefix;
83307    int i;
83308    zPrefix = "FROM";
83309    for(i=0; i<p->pSrc->nSrc; i++){
83310      struct SrcList_item *pItem = &p->pSrc->a[i];
83311      sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
83312      zPrefix = "";
83313      if( pItem->pSelect ){
83314        sqlite3DebugPrintf("(\n");
83315        sqlite3PrintSelect(pItem->pSelect, indent+10);
83316        sqlite3DebugPrintf("%*s)", indent+8, "");
83317      }else if( pItem->zName ){
83318        sqlite3DebugPrintf("%s", pItem->zName);
83319      }
83320      if( pItem->pTab ){
83321        sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
83322      }
83323      if( pItem->zAlias ){
83324        sqlite3DebugPrintf(" AS %s", pItem->zAlias);
83325      }
83326      if( i<p->pSrc->nSrc-1 ){
83327        sqlite3DebugPrintf(",");
83328      }
83329      sqlite3DebugPrintf("\n");
83330    }
83331  }
83332  if( p->pWhere ){
83333    sqlite3DebugPrintf("%*s WHERE ", indent, "");
83334    sqlite3PrintExpr(p->pWhere);
83335    sqlite3DebugPrintf("\n");
83336  }
83337  if( p->pGroupBy ){
83338    sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
83339    sqlite3PrintExprList(p->pGroupBy);
83340    sqlite3DebugPrintf("\n");
83341  }
83342  if( p->pHaving ){
83343    sqlite3DebugPrintf("%*s HAVING ", indent, "");
83344    sqlite3PrintExpr(p->pHaving);
83345    sqlite3DebugPrintf("\n");
83346  }
83347  if( p->pOrderBy ){
83348    sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
83349    sqlite3PrintExprList(p->pOrderBy);
83350    sqlite3DebugPrintf("\n");
83351  }
83352}
83353/* End of the structure debug printing code
83354*****************************************************************************/
83355#endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
83356
83357/************** End of select.c **********************************************/
83358/************** Begin file table.c *******************************************/
83359/*
83360** 2001 September 15
83361**
83362** The author disclaims copyright to this source code.  In place of
83363** a legal notice, here is a blessing:
83364**
83365**    May you do good and not evil.
83366**    May you find forgiveness for yourself and forgive others.
83367**    May you share freely, never taking more than you give.
83368**
83369*************************************************************************
83370** This file contains the sqlite3_get_table() and sqlite3_free_table()
83371** interface routines.  These are just wrappers around the main
83372** interface routine of sqlite3_exec().
83373**
83374** These routines are in a separate files so that they will not be linked
83375** if they are not used.
83376*/
83377
83378#ifndef SQLITE_OMIT_GET_TABLE
83379
83380/*
83381** This structure is used to pass data from sqlite3_get_table() through
83382** to the callback function is uses to build the result.
83383*/
83384typedef struct TabResult {
83385  char **azResult;   /* Accumulated output */
83386  char *zErrMsg;     /* Error message text, if an error occurs */
83387  int nAlloc;        /* Slots allocated for azResult[] */
83388  int nRow;          /* Number of rows in the result */
83389  int nColumn;       /* Number of columns in the result */
83390  int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
83391  int rc;            /* Return code from sqlite3_exec() */
83392} TabResult;
83393
83394/*
83395** This routine is called once for each row in the result table.  Its job
83396** is to fill in the TabResult structure appropriately, allocating new
83397** memory as necessary.
83398*/
83399static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
83400  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
83401  int need;                         /* Slots needed in p->azResult[] */
83402  int i;                            /* Loop counter */
83403  char *z;                          /* A single column of result */
83404
83405  /* Make sure there is enough space in p->azResult to hold everything
83406  ** we need to remember from this invocation of the callback.
83407  */
83408  if( p->nRow==0 && argv!=0 ){
83409    need = nCol*2;
83410  }else{
83411    need = nCol;
83412  }
83413  if( p->nData + need > p->nAlloc ){
83414    char **azNew;
83415    p->nAlloc = p->nAlloc*2 + need;
83416    azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
83417    if( azNew==0 ) goto malloc_failed;
83418    p->azResult = azNew;
83419  }
83420
83421  /* If this is the first row, then generate an extra row containing
83422  ** the names of all columns.
83423  */
83424  if( p->nRow==0 ){
83425    p->nColumn = nCol;
83426    for(i=0; i<nCol; i++){
83427      z = sqlite3_mprintf("%s", colv[i]);
83428      if( z==0 ) goto malloc_failed;
83429      p->azResult[p->nData++] = z;
83430    }
83431  }else if( p->nColumn!=nCol ){
83432    sqlite3_free(p->zErrMsg);
83433    p->zErrMsg = sqlite3_mprintf(
83434       "sqlite3_get_table() called with two or more incompatible queries"
83435    );
83436    p->rc = SQLITE_ERROR;
83437    return 1;
83438  }
83439
83440  /* Copy over the row data
83441  */
83442  if( argv!=0 ){
83443    for(i=0; i<nCol; i++){
83444      if( argv[i]==0 ){
83445        z = 0;
83446      }else{
83447        int n = sqlite3Strlen30(argv[i])+1;
83448        z = sqlite3_malloc( n );
83449        if( z==0 ) goto malloc_failed;
83450        memcpy(z, argv[i], n);
83451      }
83452      p->azResult[p->nData++] = z;
83453    }
83454    p->nRow++;
83455  }
83456  return 0;
83457
83458malloc_failed:
83459  p->rc = SQLITE_NOMEM;
83460  return 1;
83461}
83462
83463/*
83464** Query the database.  But instead of invoking a callback for each row,
83465** malloc() for space to hold the result and return the entire results
83466** at the conclusion of the call.
83467**
83468** The result that is written to ***pazResult is held in memory obtained
83469** from malloc().  But the caller cannot free this memory directly.
83470** Instead, the entire table should be passed to sqlite3_free_table() when
83471** the calling procedure is finished using it.
83472*/
83473SQLITE_API int sqlite3_get_table(
83474  sqlite3 *db,                /* The database on which the SQL executes */
83475  const char *zSql,           /* The SQL to be executed */
83476  char ***pazResult,          /* Write the result table here */
83477  int *pnRow,                 /* Write the number of rows in the result here */
83478  int *pnColumn,              /* Write the number of columns of result here */
83479  char **pzErrMsg             /* Write error messages here */
83480){
83481  int rc;
83482  TabResult res;
83483
83484  *pazResult = 0;
83485  if( pnColumn ) *pnColumn = 0;
83486  if( pnRow ) *pnRow = 0;
83487  if( pzErrMsg ) *pzErrMsg = 0;
83488  res.zErrMsg = 0;
83489  res.nRow = 0;
83490  res.nColumn = 0;
83491  res.nData = 1;
83492  res.nAlloc = 20;
83493  res.rc = SQLITE_OK;
83494  res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
83495  if( res.azResult==0 ){
83496     db->errCode = SQLITE_NOMEM;
83497     return SQLITE_NOMEM;
83498  }
83499  res.azResult[0] = 0;
83500  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
83501  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
83502  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
83503  if( (rc&0xff)==SQLITE_ABORT ){
83504    sqlite3_free_table(&res.azResult[1]);
83505    if( res.zErrMsg ){
83506      if( pzErrMsg ){
83507        sqlite3_free(*pzErrMsg);
83508        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
83509      }
83510      sqlite3_free(res.zErrMsg);
83511    }
83512    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
83513    return res.rc;
83514  }
83515  sqlite3_free(res.zErrMsg);
83516  if( rc!=SQLITE_OK ){
83517    sqlite3_free_table(&res.azResult[1]);
83518    return rc;
83519  }
83520  if( res.nAlloc>res.nData ){
83521    char **azNew;
83522    azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
83523    if( azNew==0 ){
83524      sqlite3_free_table(&res.azResult[1]);
83525      db->errCode = SQLITE_NOMEM;
83526      return SQLITE_NOMEM;
83527    }
83528    res.azResult = azNew;
83529  }
83530  *pazResult = &res.azResult[1];
83531  if( pnColumn ) *pnColumn = res.nColumn;
83532  if( pnRow ) *pnRow = res.nRow;
83533  return rc;
83534}
83535
83536/*
83537** This routine frees the space the sqlite3_get_table() malloced.
83538*/
83539SQLITE_API void sqlite3_free_table(
83540  char **azResult            /* Result returned from from sqlite3_get_table() */
83541){
83542  if( azResult ){
83543    int i, n;
83544    azResult--;
83545    assert( azResult!=0 );
83546    n = SQLITE_PTR_TO_INT(azResult[0]);
83547    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
83548    sqlite3_free(azResult);
83549  }
83550}
83551
83552#endif /* SQLITE_OMIT_GET_TABLE */
83553
83554/************** End of table.c ***********************************************/
83555/************** Begin file trigger.c *****************************************/
83556/*
83557**
83558** The author disclaims copyright to this source code.  In place of
83559** a legal notice, here is a blessing:
83560**
83561**    May you do good and not evil.
83562**    May you find forgiveness for yourself and forgive others.
83563**    May you share freely, never taking more than you give.
83564**
83565*************************************************************************
83566** This file contains the implementation for TRIGGERs
83567*/
83568
83569#ifndef SQLITE_OMIT_TRIGGER
83570/*
83571** Delete a linked list of TriggerStep structures.
83572*/
83573SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
83574  while( pTriggerStep ){
83575    TriggerStep * pTmp = pTriggerStep;
83576    pTriggerStep = pTriggerStep->pNext;
83577
83578    sqlite3ExprDelete(db, pTmp->pWhere);
83579    sqlite3ExprListDelete(db, pTmp->pExprList);
83580    sqlite3SelectDelete(db, pTmp->pSelect);
83581    sqlite3IdListDelete(db, pTmp->pIdList);
83582
83583    sqlite3DbFree(db, pTmp);
83584  }
83585}
83586
83587/*
83588** Given table pTab, return a list of all the triggers attached to
83589** the table. The list is connected by Trigger.pNext pointers.
83590**
83591** All of the triggers on pTab that are in the same database as pTab
83592** are already attached to pTab->pTrigger.  But there might be additional
83593** triggers on pTab in the TEMP schema.  This routine prepends all
83594** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
83595** and returns the combined list.
83596**
83597** To state it another way:  This routine returns a list of all triggers
83598** that fire off of pTab.  The list will include any TEMP triggers on
83599** pTab as well as the triggers lised in pTab->pTrigger.
83600*/
83601SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
83602  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
83603  Trigger *pList = 0;                  /* List of triggers to return */
83604
83605  if( pParse->disableTriggers ){
83606    return 0;
83607  }
83608
83609  if( pTmpSchema!=pTab->pSchema ){
83610    HashElem *p;
83611    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
83612      Trigger *pTrig = (Trigger *)sqliteHashData(p);
83613      if( pTrig->pTabSchema==pTab->pSchema
83614       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
83615      ){
83616        pTrig->pNext = (pList ? pList : pTab->pTrigger);
83617        pList = pTrig;
83618      }
83619    }
83620  }
83621
83622  return (pList ? pList : pTab->pTrigger);
83623}
83624
83625/*
83626** This is called by the parser when it sees a CREATE TRIGGER statement
83627** up to the point of the BEGIN before the trigger actions.  A Trigger
83628** structure is generated based on the information available and stored
83629** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
83630** sqlite3FinishTrigger() function is called to complete the trigger
83631** construction process.
83632*/
83633SQLITE_PRIVATE void sqlite3BeginTrigger(
83634  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
83635  Token *pName1,      /* The name of the trigger */
83636  Token *pName2,      /* The name of the trigger */
83637  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
83638  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
83639  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
83640  SrcList *pTableName,/* The name of the table/view the trigger applies to */
83641  Expr *pWhen,        /* WHEN clause */
83642  int isTemp,         /* True if the TEMPORARY keyword is present */
83643  int noErr           /* Suppress errors if the trigger already exists */
83644){
83645  Trigger *pTrigger = 0;  /* The new trigger */
83646  Table *pTab;            /* Table that the trigger fires off of */
83647  char *zName = 0;        /* Name of the trigger */
83648  sqlite3 *db = pParse->db;  /* The database connection */
83649  int iDb;                /* The database to store the trigger in */
83650  Token *pName;           /* The unqualified db name */
83651  DbFixer sFix;           /* State vector for the DB fixer */
83652  int iTabDb;             /* Index of the database holding pTab */
83653
83654  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
83655  assert( pName2!=0 );
83656  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
83657  assert( op>0 && op<0xff );
83658  if( isTemp ){
83659    /* If TEMP was specified, then the trigger name may not be qualified. */
83660    if( pName2->n>0 ){
83661      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
83662      goto trigger_cleanup;
83663    }
83664    iDb = 1;
83665    pName = pName1;
83666  }else{
83667    /* Figure out the db that the the trigger will be created in */
83668    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
83669    if( iDb<0 ){
83670      goto trigger_cleanup;
83671    }
83672  }
83673
83674  /* If the trigger name was unqualified, and the table is a temp table,
83675  ** then set iDb to 1 to create the trigger in the temporary database.
83676  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
83677  ** exist, the error is caught by the block below.
83678  */
83679  if( !pTableName || db->mallocFailed ){
83680    goto trigger_cleanup;
83681  }
83682  pTab = sqlite3SrcListLookup(pParse, pTableName);
83683  if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
83684    iDb = 1;
83685  }
83686
83687  /* Ensure the table name matches database name and that the table exists */
83688  if( db->mallocFailed ) goto trigger_cleanup;
83689  assert( pTableName->nSrc==1 );
83690  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
83691      sqlite3FixSrcList(&sFix, pTableName) ){
83692    goto trigger_cleanup;
83693  }
83694  pTab = sqlite3SrcListLookup(pParse, pTableName);
83695  if( !pTab ){
83696    /* The table does not exist. */
83697    if( db->init.iDb==1 ){
83698      /* Ticket #3810.
83699      ** Normally, whenever a table is dropped, all associated triggers are
83700      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
83701      ** and the table is dropped by a different database connection, the
83702      ** trigger is not visible to the database connection that does the
83703      ** drop so the trigger cannot be dropped.  This results in an
83704      ** "orphaned trigger" - a trigger whose associated table is missing.
83705      */
83706      db->init.orphanTrigger = 1;
83707    }
83708    goto trigger_cleanup;
83709  }
83710  if( IsVirtual(pTab) ){
83711    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
83712    goto trigger_cleanup;
83713  }
83714
83715  /* Check that the trigger name is not reserved and that no trigger of the
83716  ** specified name exists */
83717  zName = sqlite3NameFromToken(db, pName);
83718  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
83719    goto trigger_cleanup;
83720  }
83721  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
83722                      zName, sqlite3Strlen30(zName)) ){
83723    if( !noErr ){
83724      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
83725    }
83726    goto trigger_cleanup;
83727  }
83728
83729  /* Do not create a trigger on a system table */
83730  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
83731    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
83732    pParse->nErr++;
83733    goto trigger_cleanup;
83734  }
83735
83736  /* INSTEAD of triggers are only for views and views only support INSTEAD
83737  ** of triggers.
83738  */
83739  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
83740    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
83741        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
83742    goto trigger_cleanup;
83743  }
83744  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
83745    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
83746        " trigger on table: %S", pTableName, 0);
83747    goto trigger_cleanup;
83748  }
83749  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83750
83751#ifndef SQLITE_OMIT_AUTHORIZATION
83752  {
83753    int code = SQLITE_CREATE_TRIGGER;
83754    const char *zDb = db->aDb[iTabDb].zName;
83755    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
83756    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
83757    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
83758      goto trigger_cleanup;
83759    }
83760    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
83761      goto trigger_cleanup;
83762    }
83763  }
83764#endif
83765
83766  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
83767  ** cannot appear on views.  So we might as well translate every
83768  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
83769  ** elsewhere.
83770  */
83771  if (tr_tm == TK_INSTEAD){
83772    tr_tm = TK_BEFORE;
83773  }
83774
83775  /* Build the Trigger object */
83776  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
83777  if( pTrigger==0 ) goto trigger_cleanup;
83778  pTrigger->zName = zName;
83779  zName = 0;
83780  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
83781  pTrigger->pSchema = db->aDb[iDb].pSchema;
83782  pTrigger->pTabSchema = pTab->pSchema;
83783  pTrigger->op = (u8)op;
83784  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
83785  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
83786  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
83787  assert( pParse->pNewTrigger==0 );
83788  pParse->pNewTrigger = pTrigger;
83789
83790trigger_cleanup:
83791  sqlite3DbFree(db, zName);
83792  sqlite3SrcListDelete(db, pTableName);
83793  sqlite3IdListDelete(db, pColumns);
83794  sqlite3ExprDelete(db, pWhen);
83795  if( !pParse->pNewTrigger ){
83796    sqlite3DeleteTrigger(db, pTrigger);
83797  }else{
83798    assert( pParse->pNewTrigger==pTrigger );
83799  }
83800}
83801
83802/*
83803** This routine is called after all of the trigger actions have been parsed
83804** in order to complete the process of building the trigger.
83805*/
83806SQLITE_PRIVATE void sqlite3FinishTrigger(
83807  Parse *pParse,          /* Parser context */
83808  TriggerStep *pStepList, /* The triggered program */
83809  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
83810){
83811  Trigger *pTrig = pParse->pNewTrigger;    /* Trigger being finished */
83812  char *zName;                             /* Name of trigger */
83813  sqlite3 *db = pParse->db;                /* The database */
83814  DbFixer sFix;
83815  int iDb;                                 /* Database containing the trigger */
83816  Token nameToken;           /* Trigger name for error reporting */
83817
83818  pTrig = pParse->pNewTrigger;
83819  pParse->pNewTrigger = 0;
83820  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
83821  zName = pTrig->zName;
83822  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
83823  pTrig->step_list = pStepList;
83824  while( pStepList ){
83825    pStepList->pTrig = pTrig;
83826    pStepList = pStepList->pNext;
83827  }
83828  nameToken.z = pTrig->zName;
83829  nameToken.n = sqlite3Strlen30(nameToken.z);
83830  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
83831          && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
83832    goto triggerfinish_cleanup;
83833  }
83834
83835  /* if we are not initializing, and this trigger is not on a TEMP table,
83836  ** build the sqlite_master entry
83837  */
83838  if( !db->init.busy ){
83839    Vdbe *v;
83840    char *z;
83841
83842    /* Make an entry in the sqlite_master table */
83843    v = sqlite3GetVdbe(pParse);
83844    if( v==0 ) goto triggerfinish_cleanup;
83845    sqlite3BeginWriteOperation(pParse, 0, iDb);
83846    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
83847    sqlite3NestedParse(pParse,
83848       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
83849       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
83850       pTrig->table, z);
83851    sqlite3DbFree(db, z);
83852    sqlite3ChangeCookie(pParse, iDb);
83853    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
83854        db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
83855    );
83856  }
83857
83858  if( db->init.busy ){
83859    Trigger *pLink = pTrig;
83860    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
83861    pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
83862    if( pTrig ){
83863      db->mallocFailed = 1;
83864    }else if( pLink->pSchema==pLink->pTabSchema ){
83865      Table *pTab;
83866      int n = sqlite3Strlen30(pLink->table);
83867      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
83868      assert( pTab!=0 );
83869      pLink->pNext = pTab->pTrigger;
83870      pTab->pTrigger = pLink;
83871    }
83872  }
83873
83874triggerfinish_cleanup:
83875  sqlite3DeleteTrigger(db, pTrig);
83876  assert( !pParse->pNewTrigger );
83877  sqlite3DeleteTriggerStep(db, pStepList);
83878}
83879
83880/*
83881** Turn a SELECT statement (that the pSelect parameter points to) into
83882** a trigger step.  Return a pointer to a TriggerStep structure.
83883**
83884** The parser calls this routine when it finds a SELECT statement in
83885** body of a TRIGGER.
83886*/
83887SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
83888  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
83889  if( pTriggerStep==0 ) {
83890    sqlite3SelectDelete(db, pSelect);
83891    return 0;
83892  }
83893  pTriggerStep->op = TK_SELECT;
83894  pTriggerStep->pSelect = pSelect;
83895  pTriggerStep->orconf = OE_Default;
83896  return pTriggerStep;
83897}
83898
83899/*
83900** Allocate space to hold a new trigger step.  The allocated space
83901** holds both the TriggerStep object and the TriggerStep.target.z string.
83902**
83903** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
83904*/
83905static TriggerStep *triggerStepAllocate(
83906  sqlite3 *db,                /* Database connection */
83907  u8 op,                      /* Trigger opcode */
83908  Token *pName                /* The target name */
83909){
83910  TriggerStep *pTriggerStep;
83911
83912  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
83913  if( pTriggerStep ){
83914    char *z = (char*)&pTriggerStep[1];
83915    memcpy(z, pName->z, pName->n);
83916    pTriggerStep->target.z = z;
83917    pTriggerStep->target.n = pName->n;
83918    pTriggerStep->op = op;
83919  }
83920  return pTriggerStep;
83921}
83922
83923/*
83924** Build a trigger step out of an INSERT statement.  Return a pointer
83925** to the new trigger step.
83926**
83927** The parser calls this routine when it sees an INSERT inside the
83928** body of a trigger.
83929*/
83930SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
83931  sqlite3 *db,        /* The database connection */
83932  Token *pTableName,  /* Name of the table into which we insert */
83933  IdList *pColumn,    /* List of columns in pTableName to insert into */
83934  ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
83935  Select *pSelect,    /* A SELECT statement that supplies values */
83936  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
83937){
83938  TriggerStep *pTriggerStep;
83939
83940  assert(pEList == 0 || pSelect == 0);
83941  assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
83942
83943  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
83944  if( pTriggerStep ){
83945    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
83946    pTriggerStep->pIdList = pColumn;
83947    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
83948    pTriggerStep->orconf = orconf;
83949  }else{
83950    sqlite3IdListDelete(db, pColumn);
83951  }
83952  sqlite3ExprListDelete(db, pEList);
83953  sqlite3SelectDelete(db, pSelect);
83954
83955  return pTriggerStep;
83956}
83957
83958/*
83959** Construct a trigger step that implements an UPDATE statement and return
83960** a pointer to that trigger step.  The parser calls this routine when it
83961** sees an UPDATE statement inside the body of a CREATE TRIGGER.
83962*/
83963SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
83964  sqlite3 *db,         /* The database connection */
83965  Token *pTableName,   /* Name of the table to be updated */
83966  ExprList *pEList,    /* The SET clause: list of column and new values */
83967  Expr *pWhere,        /* The WHERE clause */
83968  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
83969){
83970  TriggerStep *pTriggerStep;
83971
83972  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
83973  if( pTriggerStep ){
83974    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
83975    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
83976    pTriggerStep->orconf = orconf;
83977  }
83978  sqlite3ExprListDelete(db, pEList);
83979  sqlite3ExprDelete(db, pWhere);
83980  return pTriggerStep;
83981}
83982
83983/*
83984** Construct a trigger step that implements a DELETE statement and return
83985** a pointer to that trigger step.  The parser calls this routine when it
83986** sees a DELETE statement inside the body of a CREATE TRIGGER.
83987*/
83988SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
83989  sqlite3 *db,            /* Database connection */
83990  Token *pTableName,      /* The table from which rows are deleted */
83991  Expr *pWhere            /* The WHERE clause */
83992){
83993  TriggerStep *pTriggerStep;
83994
83995  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
83996  if( pTriggerStep ){
83997    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
83998    pTriggerStep->orconf = OE_Default;
83999  }
84000  sqlite3ExprDelete(db, pWhere);
84001  return pTriggerStep;
84002}
84003
84004/*
84005** Recursively delete a Trigger structure
84006*/
84007SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
84008  if( pTrigger==0 ) return;
84009  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
84010  sqlite3DbFree(db, pTrigger->zName);
84011  sqlite3DbFree(db, pTrigger->table);
84012  sqlite3ExprDelete(db, pTrigger->pWhen);
84013  sqlite3IdListDelete(db, pTrigger->pColumns);
84014  sqlite3DbFree(db, pTrigger);
84015}
84016
84017/*
84018** This function is called to drop a trigger from the database schema.
84019**
84020** This may be called directly from the parser and therefore identifies
84021** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
84022** same job as this routine except it takes a pointer to the trigger
84023** instead of the trigger name.
84024**/
84025SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
84026  Trigger *pTrigger = 0;
84027  int i;
84028  const char *zDb;
84029  const char *zName;
84030  int nName;
84031  sqlite3 *db = pParse->db;
84032
84033  if( db->mallocFailed ) goto drop_trigger_cleanup;
84034  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
84035    goto drop_trigger_cleanup;
84036  }
84037
84038  assert( pName->nSrc==1 );
84039  zDb = pName->a[0].zDatabase;
84040  zName = pName->a[0].zName;
84041  nName = sqlite3Strlen30(zName);
84042  for(i=OMIT_TEMPDB; i<db->nDb; i++){
84043    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
84044    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
84045    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
84046    if( pTrigger ) break;
84047  }
84048  if( !pTrigger ){
84049    if( !noErr ){
84050      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
84051    }
84052    goto drop_trigger_cleanup;
84053  }
84054  sqlite3DropTriggerPtr(pParse, pTrigger);
84055
84056drop_trigger_cleanup:
84057  sqlite3SrcListDelete(db, pName);
84058}
84059
84060/*
84061** Return a pointer to the Table structure for the table that a trigger
84062** is set on.
84063*/
84064static Table *tableOfTrigger(Trigger *pTrigger){
84065  int n = sqlite3Strlen30(pTrigger->table);
84066  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
84067}
84068
84069
84070/*
84071** Drop a trigger given a pointer to that trigger.
84072*/
84073SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
84074  Table   *pTable;
84075  Vdbe *v;
84076  sqlite3 *db = pParse->db;
84077  int iDb;
84078
84079  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
84080  assert( iDb>=0 && iDb<db->nDb );
84081  pTable = tableOfTrigger(pTrigger);
84082  assert( pTable );
84083  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
84084#ifndef SQLITE_OMIT_AUTHORIZATION
84085  {
84086    int code = SQLITE_DROP_TRIGGER;
84087    const char *zDb = db->aDb[iDb].zName;
84088    const char *zTab = SCHEMA_TABLE(iDb);
84089    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
84090    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
84091      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
84092      return;
84093    }
84094  }
84095#endif
84096
84097  /* Generate code to destroy the database record of the trigger.
84098  */
84099  assert( pTable!=0 );
84100  if( (v = sqlite3GetVdbe(pParse))!=0 ){
84101    int base;
84102    static const VdbeOpList dropTrigger[] = {
84103      { OP_Rewind,     0, ADDR(9),  0},
84104      { OP_String8,    0, 1,        0}, /* 1 */
84105      { OP_Column,     0, 1,        2},
84106      { OP_Ne,         2, ADDR(8),  1},
84107      { OP_String8,    0, 1,        0}, /* 4: "trigger" */
84108      { OP_Column,     0, 0,        2},
84109      { OP_Ne,         2, ADDR(8),  1},
84110      { OP_Delete,     0, 0,        0},
84111      { OP_Next,       0, ADDR(1),  0}, /* 8 */
84112    };
84113
84114    sqlite3BeginWriteOperation(pParse, 0, iDb);
84115    sqlite3OpenMasterTable(pParse, iDb);
84116    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
84117    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
84118    sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
84119    sqlite3ChangeCookie(pParse, iDb);
84120    sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
84121    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
84122    if( pParse->nMem<3 ){
84123      pParse->nMem = 3;
84124    }
84125  }
84126}
84127
84128/*
84129** Remove a trigger from the hash tables of the sqlite* pointer.
84130*/
84131SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
84132  Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
84133  Trigger *pTrigger;
84134  pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
84135  if( ALWAYS(pTrigger) ){
84136    if( pTrigger->pSchema==pTrigger->pTabSchema ){
84137      Table *pTab = tableOfTrigger(pTrigger);
84138      Trigger **pp;
84139      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
84140      *pp = (*pp)->pNext;
84141    }
84142    sqlite3DeleteTrigger(db, pTrigger);
84143    db->flags |= SQLITE_InternChanges;
84144  }
84145}
84146
84147/*
84148** pEList is the SET clause of an UPDATE statement.  Each entry
84149** in pEList is of the format <id>=<expr>.  If any of the entries
84150** in pEList have an <id> which matches an identifier in pIdList,
84151** then return TRUE.  If pIdList==NULL, then it is considered a
84152** wildcard that matches anything.  Likewise if pEList==NULL then
84153** it matches anything so always return true.  Return false only
84154** if there is no match.
84155*/
84156static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
84157  int e;
84158  if( pIdList==0 || NEVER(pEList==0) ) return 1;
84159  for(e=0; e<pEList->nExpr; e++){
84160    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
84161  }
84162  return 0;
84163}
84164
84165/*
84166** Return a list of all triggers on table pTab if there exists at least
84167** one trigger that must be fired when an operation of type 'op' is
84168** performed on the table, and, if that operation is an UPDATE, if at
84169** least one of the columns in pChanges is being modified.
84170*/
84171SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
84172  Parse *pParse,          /* Parse context */
84173  Table *pTab,            /* The table the contains the triggers */
84174  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
84175  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
84176  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
84177){
84178  int mask = 0;
84179  Trigger *pList = sqlite3TriggerList(pParse, pTab);
84180  Trigger *p;
84181  assert( pList==0 || IsVirtual(pTab)==0 );
84182  for(p=pList; p; p=p->pNext){
84183    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
84184      mask |= p->tr_tm;
84185    }
84186  }
84187  if( pMask ){
84188    *pMask = mask;
84189  }
84190  return (mask ? pList : 0);
84191}
84192
84193/*
84194** Convert the pStep->target token into a SrcList and return a pointer
84195** to that SrcList.
84196**
84197** This routine adds a specific database name, if needed, to the target when
84198** forming the SrcList.  This prevents a trigger in one database from
84199** referring to a target in another database.  An exception is when the
84200** trigger is in TEMP in which case it can refer to any other database it
84201** wants.
84202*/
84203static SrcList *targetSrcList(
84204  Parse *pParse,       /* The parsing context */
84205  TriggerStep *pStep   /* The trigger containing the target token */
84206){
84207  int iDb;             /* Index of the database to use */
84208  SrcList *pSrc;       /* SrcList to be returned */
84209
84210  pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
84211  if( pSrc ){
84212    assert( pSrc->nSrc>0 );
84213    assert( pSrc->a!=0 );
84214    iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
84215    if( iDb==0 || iDb>=2 ){
84216      sqlite3 *db = pParse->db;
84217      assert( iDb<pParse->db->nDb );
84218      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
84219    }
84220  }
84221  return pSrc;
84222}
84223
84224/*
84225** Generate VDBE code for the statements inside the body of a single
84226** trigger.
84227*/
84228static int codeTriggerProgram(
84229  Parse *pParse,            /* The parser context */
84230  TriggerStep *pStepList,   /* List of statements inside the trigger body */
84231  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
84232){
84233  TriggerStep *pStep;
84234  Vdbe *v = pParse->pVdbe;
84235  sqlite3 *db = pParse->db;
84236
84237  assert( pParse->pTriggerTab && pParse->pToplevel );
84238  assert( pStepList );
84239  assert( v!=0 );
84240  for(pStep=pStepList; pStep; pStep=pStep->pNext){
84241    /* Figure out the ON CONFLICT policy that will be used for this step
84242    ** of the trigger program. If the statement that caused this trigger
84243    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
84244    ** the ON CONFLICT policy that was specified as part of the trigger
84245    ** step statement. Example:
84246    **
84247    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
84248    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
84249    **   END;
84250    **
84251    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
84252    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
84253    */
84254    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
84255
84256    switch( pStep->op ){
84257      case TK_UPDATE: {
84258        sqlite3Update(pParse,
84259          targetSrcList(pParse, pStep),
84260          sqlite3ExprListDup(db, pStep->pExprList, 0),
84261          sqlite3ExprDup(db, pStep->pWhere, 0),
84262          pParse->eOrconf
84263        );
84264        break;
84265      }
84266      case TK_INSERT: {
84267        sqlite3Insert(pParse,
84268          targetSrcList(pParse, pStep),
84269          sqlite3ExprListDup(db, pStep->pExprList, 0),
84270          sqlite3SelectDup(db, pStep->pSelect, 0),
84271          sqlite3IdListDup(db, pStep->pIdList),
84272          pParse->eOrconf
84273        );
84274        break;
84275      }
84276      case TK_DELETE: {
84277        sqlite3DeleteFrom(pParse,
84278          targetSrcList(pParse, pStep),
84279          sqlite3ExprDup(db, pStep->pWhere, 0)
84280        );
84281        break;
84282      }
84283      default: assert( pStep->op==TK_SELECT ); {
84284        SelectDest sDest;
84285        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
84286        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
84287        sqlite3Select(pParse, pSelect, &sDest);
84288        sqlite3SelectDelete(db, pSelect);
84289        break;
84290      }
84291    }
84292    if( pStep->op!=TK_SELECT ){
84293      sqlite3VdbeAddOp0(v, OP_ResetCount);
84294    }
84295  }
84296
84297  return 0;
84298}
84299
84300#ifdef SQLITE_DEBUG
84301/*
84302** This function is used to add VdbeComment() annotations to a VDBE
84303** program. It is not used in production code, only for debugging.
84304*/
84305static const char *onErrorText(int onError){
84306  switch( onError ){
84307    case OE_Abort:    return "abort";
84308    case OE_Rollback: return "rollback";
84309    case OE_Fail:     return "fail";
84310    case OE_Replace:  return "replace";
84311    case OE_Ignore:   return "ignore";
84312    case OE_Default:  return "default";
84313  }
84314  return "n/a";
84315}
84316#endif
84317
84318/*
84319** Parse context structure pFrom has just been used to create a sub-vdbe
84320** (trigger program). If an error has occurred, transfer error information
84321** from pFrom to pTo.
84322*/
84323static void transferParseError(Parse *pTo, Parse *pFrom){
84324  assert( pFrom->zErrMsg==0 || pFrom->nErr );
84325  assert( pTo->zErrMsg==0 || pTo->nErr );
84326  if( pTo->nErr==0 ){
84327    pTo->zErrMsg = pFrom->zErrMsg;
84328    pTo->nErr = pFrom->nErr;
84329  }else{
84330    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
84331  }
84332}
84333
84334/*
84335** Create and populate a new TriggerPrg object with a sub-program
84336** implementing trigger pTrigger with ON CONFLICT policy orconf.
84337*/
84338static TriggerPrg *codeRowTrigger(
84339  Parse *pParse,       /* Current parse context */
84340  Trigger *pTrigger,   /* Trigger to code */
84341  Table *pTab,         /* The table pTrigger is attached to */
84342  int orconf           /* ON CONFLICT policy to code trigger program with */
84343){
84344  Parse *pTop = sqlite3ParseToplevel(pParse);
84345  sqlite3 *db = pParse->db;   /* Database handle */
84346  TriggerPrg *pPrg;           /* Value to return */
84347  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
84348  Vdbe *v;                    /* Temporary VM */
84349  NameContext sNC;            /* Name context for sub-vdbe */
84350  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
84351  Parse *pSubParse;           /* Parse context for sub-vdbe */
84352  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
84353
84354  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
84355
84356  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
84357  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
84358  ** list of the top-level Parse object sooner rather than later.  */
84359  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
84360  if( !pPrg ) return 0;
84361  pPrg->pNext = pTop->pTriggerPrg;
84362  pTop->pTriggerPrg = pPrg;
84363  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
84364  if( !pProgram ) return 0;
84365  pProgram->nRef = 1;
84366  pPrg->pTrigger = pTrigger;
84367  pPrg->orconf = orconf;
84368  pPrg->aColmask[0] = 0xffffffff;
84369  pPrg->aColmask[1] = 0xffffffff;
84370
84371  /* Allocate and populate a new Parse context to use for coding the
84372  ** trigger sub-program.  */
84373  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
84374  if( !pSubParse ) return 0;
84375  memset(&sNC, 0, sizeof(sNC));
84376  sNC.pParse = pSubParse;
84377  pSubParse->db = db;
84378  pSubParse->pTriggerTab = pTab;
84379  pSubParse->pToplevel = pTop;
84380  pSubParse->zAuthContext = pTrigger->zName;
84381  pSubParse->eTriggerOp = pTrigger->op;
84382
84383  v = sqlite3GetVdbe(pSubParse);
84384  if( v ){
84385    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
84386      pTrigger->zName, onErrorText(orconf),
84387      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
84388        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
84389        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
84390        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
84391      pTab->zName
84392    ));
84393#ifndef SQLITE_OMIT_TRACE
84394    sqlite3VdbeChangeP4(v, -1,
84395      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
84396    );
84397#endif
84398
84399    /* If one was specified, code the WHEN clause. If it evaluates to false
84400    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
84401    ** OP_Halt inserted at the end of the program.  */
84402    if( pTrigger->pWhen ){
84403      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
84404      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
84405       && db->mallocFailed==0
84406      ){
84407        iEndTrigger = sqlite3VdbeMakeLabel(v);
84408        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
84409      }
84410      sqlite3ExprDelete(db, pWhen);
84411    }
84412
84413    /* Code the trigger program into the sub-vdbe. */
84414    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
84415
84416    /* Insert an OP_Halt at the end of the sub-program. */
84417    if( iEndTrigger ){
84418      sqlite3VdbeResolveLabel(v, iEndTrigger);
84419    }
84420    sqlite3VdbeAddOp0(v, OP_Halt);
84421    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
84422
84423    transferParseError(pParse, pSubParse);
84424    if( db->mallocFailed==0 ){
84425      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
84426    }
84427    pProgram->nMem = pSubParse->nMem;
84428    pProgram->nCsr = pSubParse->nTab;
84429    pProgram->token = (void *)pTrigger;
84430    pPrg->aColmask[0] = pSubParse->oldmask;
84431    pPrg->aColmask[1] = pSubParse->newmask;
84432    sqlite3VdbeDelete(v);
84433  }
84434
84435  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
84436  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
84437  sqlite3StackFree(db, pSubParse);
84438
84439  return pPrg;
84440}
84441
84442/*
84443** Return a pointer to a TriggerPrg object containing the sub-program for
84444** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
84445** TriggerPrg object exists, a new object is allocated and populated before
84446** being returned.
84447*/
84448static TriggerPrg *getRowTrigger(
84449  Parse *pParse,       /* Current parse context */
84450  Trigger *pTrigger,   /* Trigger to code */
84451  Table *pTab,         /* The table trigger pTrigger is attached to */
84452  int orconf           /* ON CONFLICT algorithm. */
84453){
84454  Parse *pRoot = sqlite3ParseToplevel(pParse);
84455  TriggerPrg *pPrg;
84456
84457  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
84458
84459  /* It may be that this trigger has already been coded (or is in the
84460  ** process of being coded). If this is the case, then an entry with
84461  ** a matching TriggerPrg.pTrigger field will be present somewhere
84462  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
84463  for(pPrg=pRoot->pTriggerPrg;
84464      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
84465      pPrg=pPrg->pNext
84466  );
84467
84468  /* If an existing TriggerPrg could not be located, create a new one. */
84469  if( !pPrg ){
84470    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
84471  }
84472
84473  return pPrg;
84474}
84475
84476/*
84477** Generate code for the trigger program associated with trigger p on
84478** table pTab. The reg, orconf and ignoreJump parameters passed to this
84479** function are the same as those described in the header function for
84480** sqlite3CodeRowTrigger()
84481*/
84482SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
84483  Parse *pParse,       /* Parse context */
84484  Trigger *p,          /* Trigger to code */
84485  Table *pTab,         /* The table to code triggers from */
84486  int reg,             /* Reg array containing OLD.* and NEW.* values */
84487  int orconf,          /* ON CONFLICT policy */
84488  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
84489){
84490  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
84491  TriggerPrg *pPrg;
84492  pPrg = getRowTrigger(pParse, p, pTab, orconf);
84493  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
84494
84495  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
84496  ** is a pointer to the sub-vdbe containing the trigger program.  */
84497  if( pPrg ){
84498    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
84499    pPrg->pProgram->nRef++;
84500    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
84501    VdbeComment(
84502        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
84503
84504    /* Set the P5 operand of the OP_Program instruction to non-zero if
84505    ** recursive invocation of this trigger program is disallowed. Recursive
84506    ** invocation is disallowed if (a) the sub-program is really a trigger,
84507    ** not a foreign key action, and (b) the flag to enable recursive triggers
84508    ** is clear.  */
84509    sqlite3VdbeChangeP5(v, (u8)(p->zName && !(pParse->db->flags&SQLITE_RecTriggers)));
84510  }
84511}
84512
84513/*
84514** This is called to code the required FOR EACH ROW triggers for an operation
84515** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
84516** is given by the op paramater. The tr_tm parameter determines whether the
84517** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
84518** parameter pChanges is passed the list of columns being modified.
84519**
84520** If there are no triggers that fire at the specified time for the specified
84521** operation on pTab, this function is a no-op.
84522**
84523** The reg argument is the address of the first in an array of registers
84524** that contain the values substituted for the new.* and old.* references
84525** in the trigger program. If N is the number of columns in table pTab
84526** (a copy of pTab->nCol), then registers are populated as follows:
84527**
84528**   Register       Contains
84529**   ------------------------------------------------------
84530**   reg+0          OLD.rowid
84531**   reg+1          OLD.* value of left-most column of pTab
84532**   ...            ...
84533**   reg+N          OLD.* value of right-most column of pTab
84534**   reg+N+1        NEW.rowid
84535**   reg+N+2        OLD.* value of left-most column of pTab
84536**   ...            ...
84537**   reg+N+N+1      NEW.* value of right-most column of pTab
84538**
84539** For ON DELETE triggers, the registers containing the NEW.* values will
84540** never be accessed by the trigger program, so they are not allocated or
84541** populated by the caller (there is no data to populate them with anyway).
84542** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
84543** are never accessed, and so are not allocated by the caller. So, for an
84544** ON INSERT trigger, the value passed to this function as parameter reg
84545** is not a readable register, although registers (reg+N) through
84546** (reg+N+N+1) are.
84547**
84548** Parameter orconf is the default conflict resolution algorithm for the
84549** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
84550** is the instruction that control should jump to if a trigger program
84551** raises an IGNORE exception.
84552*/
84553SQLITE_PRIVATE void sqlite3CodeRowTrigger(
84554  Parse *pParse,       /* Parse context */
84555  Trigger *pTrigger,   /* List of triggers on table pTab */
84556  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
84557  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
84558  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
84559  Table *pTab,         /* The table to code triggers from */
84560  int reg,             /* The first in an array of registers (see above) */
84561  int orconf,          /* ON CONFLICT policy */
84562  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
84563){
84564  Trigger *p;          /* Used to iterate through pTrigger list */
84565
84566  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
84567  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
84568  assert( (op==TK_UPDATE)==(pChanges!=0) );
84569
84570  for(p=pTrigger; p; p=p->pNext){
84571
84572    /* Sanity checking:  The schema for the trigger and for the table are
84573    ** always defined.  The trigger must be in the same schema as the table
84574    ** or else it must be a TEMP trigger. */
84575    assert( p->pSchema!=0 );
84576    assert( p->pTabSchema!=0 );
84577    assert( p->pSchema==p->pTabSchema
84578         || p->pSchema==pParse->db->aDb[1].pSchema );
84579
84580    /* Determine whether we should code this trigger */
84581    if( p->op==op
84582     && p->tr_tm==tr_tm
84583     && checkColumnOverlap(p->pColumns, pChanges)
84584    ){
84585      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
84586    }
84587  }
84588}
84589
84590/*
84591** Triggers may access values stored in the old.* or new.* pseudo-table.
84592** This function returns a 32-bit bitmask indicating which columns of the
84593** old.* or new.* tables actually are used by triggers. This information
84594** may be used by the caller, for example, to avoid having to load the entire
84595** old.* record into memory when executing an UPDATE or DELETE command.
84596**
84597** Bit 0 of the returned mask is set if the left-most column of the
84598** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
84599** the second leftmost column value is required, and so on. If there
84600** are more than 32 columns in the table, and at least one of the columns
84601** with an index greater than 32 may be accessed, 0xffffffff is returned.
84602**
84603** It is not possible to determine if the old.rowid or new.rowid column is
84604** accessed by triggers. The caller must always assume that it is.
84605**
84606** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
84607** applies to the old.* table. If 1, the new.* table.
84608**
84609** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
84610** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
84611** included in the returned mask if the TRIGGER_BEFORE bit is set in the
84612** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
84613** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
84614*/
84615SQLITE_PRIVATE u32 sqlite3TriggerColmask(
84616  Parse *pParse,       /* Parse context */
84617  Trigger *pTrigger,   /* List of triggers on table pTab */
84618  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
84619  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
84620  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
84621  Table *pTab,         /* The table to code triggers from */
84622  int orconf           /* Default ON CONFLICT policy for trigger steps */
84623){
84624  const int op = pChanges ? TK_UPDATE : TK_DELETE;
84625  u32 mask = 0;
84626  Trigger *p;
84627
84628  assert( isNew==1 || isNew==0 );
84629  for(p=pTrigger; p; p=p->pNext){
84630    if( p->op==op && (tr_tm&p->tr_tm)
84631     && checkColumnOverlap(p->pColumns,pChanges)
84632    ){
84633      TriggerPrg *pPrg;
84634      pPrg = getRowTrigger(pParse, p, pTab, orconf);
84635      if( pPrg ){
84636        mask |= pPrg->aColmask[isNew];
84637      }
84638    }
84639  }
84640
84641  return mask;
84642}
84643
84644#endif /* !defined(SQLITE_OMIT_TRIGGER) */
84645
84646/************** End of trigger.c *********************************************/
84647/************** Begin file update.c ******************************************/
84648/*
84649** 2001 September 15
84650**
84651** The author disclaims copyright to this source code.  In place of
84652** a legal notice, here is a blessing:
84653**
84654**    May you do good and not evil.
84655**    May you find forgiveness for yourself and forgive others.
84656**    May you share freely, never taking more than you give.
84657**
84658*************************************************************************
84659** This file contains C code routines that are called by the parser
84660** to handle UPDATE statements.
84661*/
84662
84663#ifndef SQLITE_OMIT_VIRTUALTABLE
84664/* Forward declaration */
84665static void updateVirtualTable(
84666  Parse *pParse,       /* The parsing context */
84667  SrcList *pSrc,       /* The virtual table to be modified */
84668  Table *pTab,         /* The virtual table */
84669  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
84670  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
84671  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
84672  Expr *pWhere         /* WHERE clause of the UPDATE statement */
84673);
84674#endif /* SQLITE_OMIT_VIRTUALTABLE */
84675
84676/*
84677** The most recently coded instruction was an OP_Column to retrieve the
84678** i-th column of table pTab. This routine sets the P4 parameter of the
84679** OP_Column to the default value, if any.
84680**
84681** The default value of a column is specified by a DEFAULT clause in the
84682** column definition. This was either supplied by the user when the table
84683** was created, or added later to the table definition by an ALTER TABLE
84684** command. If the latter, then the row-records in the table btree on disk
84685** may not contain a value for the column and the default value, taken
84686** from the P4 parameter of the OP_Column instruction, is returned instead.
84687** If the former, then all row-records are guaranteed to include a value
84688** for the column and the P4 value is not required.
84689**
84690** Column definitions created by an ALTER TABLE command may only have
84691** literal default values specified: a number, null or a string. (If a more
84692** complicated default expression value was provided, it is evaluated
84693** when the ALTER TABLE is executed and one of the literal values written
84694** into the sqlite_master table.)
84695**
84696** Therefore, the P4 parameter is only required if the default value for
84697** the column is a literal number, string or null. The sqlite3ValueFromExpr()
84698** function is capable of transforming these types of expressions into
84699** sqlite3_value objects.
84700**
84701** If parameter iReg is not negative, code an OP_RealAffinity instruction
84702** on register iReg. This is used when an equivalent integer value is
84703** stored in place of an 8-byte floating point value in order to save
84704** space.
84705*/
84706SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
84707  assert( pTab!=0 );
84708  if( !pTab->pSelect ){
84709    sqlite3_value *pValue;
84710    u8 enc = ENC(sqlite3VdbeDb(v));
84711    Column *pCol = &pTab->aCol[i];
84712    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
84713    assert( i<pTab->nCol );
84714    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
84715                         pCol->affinity, &pValue);
84716    if( pValue ){
84717      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
84718    }
84719#ifndef SQLITE_OMIT_FLOATING_POINT
84720    if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
84721      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
84722    }
84723#endif
84724  }
84725}
84726
84727/*
84728** Process an UPDATE statement.
84729**
84730**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
84731**          \_______/ \________/     \______/       \________________/
84732*            onError   pTabList      pChanges             pWhere
84733*/
84734SQLITE_PRIVATE void sqlite3Update(
84735  Parse *pParse,         /* The parser context */
84736  SrcList *pTabList,     /* The table in which we should change things */
84737  ExprList *pChanges,    /* Things to be changed */
84738  Expr *pWhere,          /* The WHERE clause.  May be null */
84739  int onError            /* How to handle constraint errors */
84740){
84741  int i, j;              /* Loop counters */
84742  Table *pTab;           /* The table to be updated */
84743  int addr = 0;          /* VDBE instruction address of the start of the loop */
84744  WhereInfo *pWInfo;     /* Information about the WHERE clause */
84745  Vdbe *v;               /* The virtual database engine */
84746  Index *pIdx;           /* For looping over indices */
84747  int nIdx;              /* Number of indices that need updating */
84748  int iCur;              /* VDBE Cursor number of pTab */
84749  sqlite3 *db;           /* The database structure */
84750  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
84751  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
84752                         ** an expression for the i-th column of the table.
84753                         ** aXRef[i]==-1 if the i-th column is not changed. */
84754  int chngRowid;         /* True if the record number is being changed */
84755  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
84756  int openAll = 0;       /* True if all indices need to be opened */
84757  AuthContext sContext;  /* The authorization context */
84758  NameContext sNC;       /* The name-context to resolve expressions in */
84759  int iDb;               /* Database containing the table being updated */
84760  int okOnePass;         /* True for one-pass algorithm without the FIFO */
84761  int hasFK;             /* True if foreign key processing is required */
84762
84763#ifndef SQLITE_OMIT_TRIGGER
84764  int isView;            /* True when updating a view (INSTEAD OF trigger) */
84765  Trigger *pTrigger;     /* List of triggers on pTab, if required */
84766  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
84767#endif
84768  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
84769
84770  /* Register Allocations */
84771  int regRowCount = 0;   /* A count of rows changed */
84772  int regOldRowid;       /* The old rowid */
84773  int regNewRowid;       /* The new rowid */
84774  int regNew;
84775  int regOld = 0;
84776  int regRowSet = 0;     /* Rowset of rows to be updated */
84777  int regRec;            /* Register used for new table record to insert */
84778
84779  memset(&sContext, 0, sizeof(sContext));
84780  db = pParse->db;
84781  if( pParse->nErr || db->mallocFailed ){
84782    goto update_cleanup;
84783  }
84784  assert( pTabList->nSrc==1 );
84785
84786  /* Locate the table which we want to update.
84787  */
84788  pTab = sqlite3SrcListLookup(pParse, pTabList);
84789  if( pTab==0 ) goto update_cleanup;
84790  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84791
84792  /* Figure out if we have any triggers and if the table being
84793  ** updated is a view.
84794  */
84795#ifndef SQLITE_OMIT_TRIGGER
84796  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
84797  isView = pTab->pSelect!=0;
84798  assert( pTrigger || tmask==0 );
84799#else
84800# define pTrigger 0
84801# define isView 0
84802# define tmask 0
84803#endif
84804#ifdef SQLITE_OMIT_VIEW
84805# undef isView
84806# define isView 0
84807#endif
84808
84809  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
84810    goto update_cleanup;
84811  }
84812  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
84813    goto update_cleanup;
84814  }
84815  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
84816  if( aXRef==0 ) goto update_cleanup;
84817  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
84818
84819  /* Allocate a cursors for the main database table and for all indices.
84820  ** The index cursors might not be used, but if they are used they
84821  ** need to occur right after the database cursor.  So go ahead and
84822  ** allocate enough space, just in case.
84823  */
84824  pTabList->a[0].iCursor = iCur = pParse->nTab++;
84825  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84826    pParse->nTab++;
84827  }
84828
84829  /* Initialize the name-context */
84830  memset(&sNC, 0, sizeof(sNC));
84831  sNC.pParse = pParse;
84832  sNC.pSrcList = pTabList;
84833
84834  /* Resolve the column names in all the expressions of the
84835  ** of the UPDATE statement.  Also find the column index
84836  ** for each column to be updated in the pChanges array.  For each
84837  ** column to be updated, make sure we have authorization to change
84838  ** that column.
84839  */
84840  chngRowid = 0;
84841  for(i=0; i<pChanges->nExpr; i++){
84842    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
84843      goto update_cleanup;
84844    }
84845    for(j=0; j<pTab->nCol; j++){
84846      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
84847        if( j==pTab->iPKey ){
84848          chngRowid = 1;
84849          pRowidExpr = pChanges->a[i].pExpr;
84850        }
84851        aXRef[j] = i;
84852        break;
84853      }
84854    }
84855    if( j>=pTab->nCol ){
84856      if( sqlite3IsRowid(pChanges->a[i].zName) ){
84857        chngRowid = 1;
84858        pRowidExpr = pChanges->a[i].pExpr;
84859      }else{
84860        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
84861        goto update_cleanup;
84862      }
84863    }
84864#ifndef SQLITE_OMIT_AUTHORIZATION
84865    {
84866      int rc;
84867      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
84868                           pTab->aCol[j].zName, db->aDb[iDb].zName);
84869      if( rc==SQLITE_DENY ){
84870        goto update_cleanup;
84871      }else if( rc==SQLITE_IGNORE ){
84872        aXRef[j] = -1;
84873      }
84874    }
84875#endif
84876  }
84877
84878  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
84879
84880  /* Allocate memory for the array aRegIdx[].  There is one entry in the
84881  ** array for each index associated with table being updated.  Fill in
84882  ** the value with a register number for indices that are to be used
84883  ** and with zero for unused indices.
84884  */
84885  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
84886  if( nIdx>0 ){
84887    aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
84888    if( aRegIdx==0 ) goto update_cleanup;
84889  }
84890  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
84891    int reg;
84892    if( chngRowid ){
84893      reg = ++pParse->nMem;
84894    }else{
84895      reg = 0;
84896      for(i=0; i<pIdx->nColumn; i++){
84897        if( aXRef[pIdx->aiColumn[i]]>=0 ){
84898          reg = ++pParse->nMem;
84899          break;
84900        }
84901      }
84902    }
84903    aRegIdx[j] = reg;
84904  }
84905
84906  /* Begin generating code. */
84907  v = sqlite3GetVdbe(pParse);
84908  if( v==0 ) goto update_cleanup;
84909  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
84910  sqlite3BeginWriteOperation(pParse, 1, iDb);
84911
84912#ifndef SQLITE_OMIT_VIRTUALTABLE
84913  /* Virtual tables must be handled separately */
84914  if( IsVirtual(pTab) ){
84915    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
84916                       pWhere);
84917    pWhere = 0;
84918    pTabList = 0;
84919    goto update_cleanup;
84920  }
84921#endif
84922
84923  /* Allocate required registers. */
84924  regOldRowid = regNewRowid = ++pParse->nMem;
84925  if( pTrigger || hasFK ){
84926    regOld = pParse->nMem + 1;
84927    pParse->nMem += pTab->nCol;
84928  }
84929  if( chngRowid || pTrigger || hasFK ){
84930    regNewRowid = ++pParse->nMem;
84931  }
84932  regNew = pParse->nMem + 1;
84933  pParse->nMem += pTab->nCol;
84934  regRec = ++pParse->nMem;
84935
84936  /* Start the view context. */
84937  if( isView ){
84938    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
84939  }
84940
84941  /* If we are trying to update a view, realize that view into
84942  ** a ephemeral table.
84943  */
84944#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
84945  if( isView ){
84946    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
84947  }
84948#endif
84949
84950  /* Resolve the column names in all the expressions in the
84951  ** WHERE clause.
84952  */
84953  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
84954    goto update_cleanup;
84955  }
84956
84957  /* Begin the database scan
84958  */
84959  sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
84960  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
84961  if( pWInfo==0 ) goto update_cleanup;
84962  okOnePass = pWInfo->okOnePass;
84963
84964  /* Remember the rowid of every item to be updated.
84965  */
84966  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
84967  if( !okOnePass ){
84968    regRowSet = ++pParse->nMem;
84969    sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
84970  }
84971
84972  /* End the database scan loop.
84973  */
84974  sqlite3WhereEnd(pWInfo);
84975
84976  /* Initialize the count of updated rows
84977  */
84978  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
84979    regRowCount = ++pParse->nMem;
84980    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
84981  }
84982
84983  if( !isView ){
84984    /*
84985    ** Open every index that needs updating.  Note that if any
84986    ** index could potentially invoke a REPLACE conflict resolution
84987    ** action, then we need to open all indices because we might need
84988    ** to be deleting some records.
84989    */
84990    if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
84991    if( onError==OE_Replace ){
84992      openAll = 1;
84993    }else{
84994      openAll = 0;
84995      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84996        if( pIdx->onError==OE_Replace ){
84997          openAll = 1;
84998          break;
84999        }
85000      }
85001    }
85002    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
85003      if( openAll || aRegIdx[i]>0 ){
85004        KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
85005        sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
85006                       (char*)pKey, P4_KEYINFO_HANDOFF);
85007        assert( pParse->nTab>iCur+i+1 );
85008      }
85009    }
85010  }
85011
85012  /* Top of the update loop */
85013  if( okOnePass ){
85014    int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
85015    addr = sqlite3VdbeAddOp0(v, OP_Goto);
85016    sqlite3VdbeJumpHere(v, a1);
85017  }else{
85018    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
85019  }
85020
85021  /* Make cursor iCur point to the record that is being updated. If
85022  ** this record does not exist for some reason (deleted by a trigger,
85023  ** for example, then jump to the next iteration of the RowSet loop.  */
85024  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
85025
85026  /* If the record number will change, set register regNewRowid to
85027  ** contain the new value. If the record number is not being modified,
85028  ** then regNewRowid is the same register as regOldRowid, which is
85029  ** already populated.  */
85030  assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
85031  if( chngRowid ){
85032    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
85033    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
85034  }
85035
85036  /* If there are triggers on this table, populate an array of registers
85037  ** with the required old.* column data.  */
85038  if( hasFK || pTrigger ){
85039    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
85040    oldmask |= sqlite3TriggerColmask(pParse,
85041        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
85042    );
85043    for(i=0; i<pTab->nCol; i++){
85044      if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
85045        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regOld+i);
85046        sqlite3ColumnDefault(v, pTab, i, regOld+i);
85047      }else{
85048        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
85049      }
85050    }
85051    if( chngRowid==0 ){
85052      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
85053    }
85054  }
85055
85056  /* Populate the array of registers beginning at regNew with the new
85057  ** row data. This array is used to check constaints, create the new
85058  ** table and index records, and as the values for any new.* references
85059  ** made by triggers.
85060  **
85061  ** If there are one or more BEFORE triggers, then do not populate the
85062  ** registers associated with columns that are (a) not modified by
85063  ** this UPDATE statement and (b) not accessed by new.* references. The
85064  ** values for registers not modified by the UPDATE must be reloaded from
85065  ** the database after the BEFORE triggers are fired anyway (as the trigger
85066  ** may have modified them). So not loading those that are not going to
85067  ** be used eliminates some redundant opcodes.
85068  */
85069  newmask = sqlite3TriggerColmask(
85070      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
85071  );
85072  for(i=0; i<pTab->nCol; i++){
85073    if( i==pTab->iPKey ){
85074      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
85075    }else{
85076      j = aXRef[i];
85077      if( j>=0 ){
85078        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
85079      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
85080        /* This branch loads the value of a column that will not be changed
85081        ** into a register. This is done if there are no BEFORE triggers, or
85082        ** if there are one or more BEFORE triggers that use this value via
85083        ** a new.* reference in a trigger program.
85084        */
85085        testcase( i==31 );
85086        testcase( i==32 );
85087        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
85088        sqlite3ColumnDefault(v, pTab, i, regNew+i);
85089      }
85090    }
85091  }
85092
85093  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
85094  ** verified. One could argue that this is wrong.
85095  */
85096  if( tmask&TRIGGER_BEFORE ){
85097    sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
85098    sqlite3TableAffinityStr(v, pTab);
85099    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
85100        TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
85101
85102    /* The row-trigger may have deleted the row being updated. In this
85103    ** case, jump to the next row. No updates or AFTER triggers are
85104    ** required. This behaviour - what happens when the row being updated
85105    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
85106    ** documentation.
85107    */
85108    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
85109
85110    /* If it did not delete it, the row-trigger may still have modified
85111    ** some of the columns of the row being updated. Load the values for
85112    ** all columns not modified by the update statement into their
85113    ** registers in case this has happened.
85114    */
85115    for(i=0; i<pTab->nCol; i++){
85116      if( aXRef[i]<0 && i!=pTab->iPKey ){
85117        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
85118        sqlite3ColumnDefault(v, pTab, i, regNew+i);
85119      }
85120    }
85121  }
85122
85123  if( !isView ){
85124    int j1;                       /* Address of jump instruction */
85125
85126    /* Do constraint checks. */
85127    sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
85128        aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
85129
85130    /* Do FK constraint checks. */
85131    if( hasFK ){
85132      sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
85133    }
85134
85135    /* Delete the index entries associated with the current record.  */
85136    j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
85137    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
85138
85139    /* If changing the record number, delete the old record.  */
85140    if( hasFK || chngRowid ){
85141      sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
85142    }
85143    sqlite3VdbeJumpHere(v, j1);
85144
85145    if( hasFK ){
85146      sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
85147    }
85148
85149    /* Insert the new index entries and the new record. */
85150    sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
85151
85152    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
85153    ** handle rows (possibly in other tables) that refer via a foreign key
85154    ** to the row just updated. */
85155    if( hasFK ){
85156      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
85157    }
85158  }
85159
85160  /* Increment the row counter
85161  */
85162  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
85163    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
85164  }
85165
85166  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
85167      TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
85168
85169  /* Repeat the above with the next record to be updated, until
85170  ** all record selected by the WHERE clause have been updated.
85171  */
85172  sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
85173  sqlite3VdbeJumpHere(v, addr);
85174
85175  /* Close all tables */
85176  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
85177    if( openAll || aRegIdx[i]>0 ){
85178      sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
85179    }
85180  }
85181  sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
85182
85183  /* Update the sqlite_sequence table by storing the content of the
85184  ** maximum rowid counter values recorded while inserting into
85185  ** autoincrement tables.
85186  */
85187  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85188    sqlite3AutoincrementEnd(pParse);
85189  }
85190
85191  /*
85192  ** Return the number of rows that were changed. If this routine is
85193  ** generating code because of a call to sqlite3NestedParse(), do not
85194  ** invoke the callback function.
85195  */
85196  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
85197    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
85198    sqlite3VdbeSetNumCols(v, 1);
85199    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
85200  }
85201
85202update_cleanup:
85203  sqlite3AuthContextPop(&sContext);
85204  sqlite3DbFree(db, aRegIdx);
85205  sqlite3DbFree(db, aXRef);
85206  sqlite3SrcListDelete(db, pTabList);
85207  sqlite3ExprListDelete(db, pChanges);
85208  sqlite3ExprDelete(db, pWhere);
85209  return;
85210}
85211/* Make sure "isView" and other macros defined above are undefined. Otherwise
85212** thely may interfere with compilation of other functions in this file
85213** (or in another file, if this file becomes part of the amalgamation).  */
85214#ifdef isView
85215 #undef isView
85216#endif
85217#ifdef pTrigger
85218 #undef pTrigger
85219#endif
85220
85221#ifndef SQLITE_OMIT_VIRTUALTABLE
85222/*
85223** Generate code for an UPDATE of a virtual table.
85224**
85225** The strategy is that we create an ephemerial table that contains
85226** for each row to be changed:
85227**
85228**   (A)  The original rowid of that row.
85229**   (B)  The revised rowid for the row. (note1)
85230**   (C)  The content of every column in the row.
85231**
85232** Then we loop over this ephemeral table and for each row in
85233** the ephermeral table call VUpdate.
85234**
85235** When finished, drop the ephemeral table.
85236**
85237** (note1) Actually, if we know in advance that (A) is always the same
85238** as (B) we only store (A), then duplicate (A) when pulling
85239** it out of the ephemeral table before calling VUpdate.
85240*/
85241static void updateVirtualTable(
85242  Parse *pParse,       /* The parsing context */
85243  SrcList *pSrc,       /* The virtual table to be modified */
85244  Table *pTab,         /* The virtual table */
85245  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
85246  Expr *pRowid,        /* Expression used to recompute the rowid */
85247  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
85248  Expr *pWhere         /* WHERE clause of the UPDATE statement */
85249){
85250  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
85251  ExprList *pEList = 0;     /* The result set of the SELECT statement */
85252  Select *pSelect = 0;      /* The SELECT statement */
85253  Expr *pExpr;              /* Temporary expression */
85254  int ephemTab;             /* Table holding the result of the SELECT */
85255  int i;                    /* Loop counter */
85256  int addr;                 /* Address of top of loop */
85257  int iReg;                 /* First register in set passed to OP_VUpdate */
85258  sqlite3 *db = pParse->db; /* Database connection */
85259  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
85260  SelectDest dest;
85261
85262  /* Construct the SELECT statement that will find the new values for
85263  ** all updated rows.
85264  */
85265  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
85266  if( pRowid ){
85267    pEList = sqlite3ExprListAppend(pParse, pEList,
85268                                   sqlite3ExprDup(db, pRowid, 0));
85269  }
85270  assert( pTab->iPKey<0 );
85271  for(i=0; i<pTab->nCol; i++){
85272    if( aXRef[i]>=0 ){
85273      pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
85274    }else{
85275      pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
85276    }
85277    pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
85278  }
85279  pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
85280
85281  /* Create the ephemeral table into which the update results will
85282  ** be stored.
85283  */
85284  assert( v );
85285  ephemTab = pParse->nTab++;
85286  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
85287
85288  /* fill the ephemeral table
85289  */
85290  sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
85291  sqlite3Select(pParse, pSelect, &dest);
85292
85293  /* Generate code to scan the ephemeral table and call VUpdate. */
85294  iReg = ++pParse->nMem;
85295  pParse->nMem += pTab->nCol+1;
85296  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
85297  sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
85298  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
85299  for(i=0; i<pTab->nCol; i++){
85300    sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
85301  }
85302  sqlite3VtabMakeWritable(pParse, pTab);
85303  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
85304  sqlite3MayAbort(pParse);
85305  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
85306  sqlite3VdbeJumpHere(v, addr);
85307  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
85308
85309  /* Cleanup */
85310  sqlite3SelectDelete(db, pSelect);
85311}
85312#endif /* SQLITE_OMIT_VIRTUALTABLE */
85313
85314/************** End of update.c **********************************************/
85315/************** Begin file vacuum.c ******************************************/
85316/*
85317** 2003 April 6
85318**
85319** The author disclaims copyright to this source code.  In place of
85320** a legal notice, here is a blessing:
85321**
85322**    May you do good and not evil.
85323**    May you find forgiveness for yourself and forgive others.
85324**    May you share freely, never taking more than you give.
85325**
85326*************************************************************************
85327** This file contains code used to implement the VACUUM command.
85328**
85329** Most of the code in this file may be omitted by defining the
85330** SQLITE_OMIT_VACUUM macro.
85331*/
85332
85333#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
85334/*
85335** Execute zSql on database db. Return an error code.
85336*/
85337static int execSql(sqlite3 *db, const char *zSql){
85338  sqlite3_stmt *pStmt;
85339  VVA_ONLY( int rc; )
85340  if( !zSql ){
85341    return SQLITE_NOMEM;
85342  }
85343  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
85344    return sqlite3_errcode(db);
85345  }
85346  VVA_ONLY( rc = ) sqlite3_step(pStmt);
85347  assert( rc!=SQLITE_ROW );
85348  return sqlite3_finalize(pStmt);
85349}
85350
85351/*
85352** Execute zSql on database db. The statement returns exactly
85353** one column. Execute this as SQL on the same database.
85354*/
85355static int execExecSql(sqlite3 *db, const char *zSql){
85356  sqlite3_stmt *pStmt;
85357  int rc;
85358
85359  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
85360  if( rc!=SQLITE_OK ) return rc;
85361
85362  while( SQLITE_ROW==sqlite3_step(pStmt) ){
85363    rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
85364    if( rc!=SQLITE_OK ){
85365      sqlite3_finalize(pStmt);
85366      return rc;
85367    }
85368  }
85369
85370  return sqlite3_finalize(pStmt);
85371}
85372
85373/*
85374** The non-standard VACUUM command is used to clean up the database,
85375** collapse free space, etc.  It is modelled after the VACUUM command
85376** in PostgreSQL.
85377**
85378** In version 1.0.x of SQLite, the VACUUM command would call
85379** gdbm_reorganize() on all the database tables.  But beginning
85380** with 2.0.0, SQLite no longer uses GDBM so this command has
85381** become a no-op.
85382*/
85383SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
85384  Vdbe *v = sqlite3GetVdbe(pParse);
85385  if( v ){
85386    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
85387  }
85388  return;
85389}
85390
85391/*
85392** This routine implements the OP_Vacuum opcode of the VDBE.
85393*/
85394SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
85395  int rc = SQLITE_OK;     /* Return code from service routines */
85396  Btree *pMain;           /* The database being vacuumed */
85397  Btree *pTemp;           /* The temporary database we vacuum into */
85398  char *zSql = 0;         /* SQL statements */
85399  int saved_flags;        /* Saved value of the db->flags */
85400  int saved_nChange;      /* Saved value of db->nChange */
85401  int saved_nTotalChange; /* Saved value of db->nTotalChange */
85402  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
85403  Db *pDb = 0;            /* Database to detach at end of vacuum */
85404  int isMemDb;            /* True if vacuuming a :memory: database */
85405  int nRes;
85406
85407  if( !db->autoCommit ){
85408    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
85409    return SQLITE_ERROR;
85410  }
85411
85412  /* Save the current value of the database flags so that it can be
85413  ** restored before returning. Then set the writable-schema flag, and
85414  ** disable CHECK and foreign key constraints.  */
85415  saved_flags = db->flags;
85416  saved_nChange = db->nChange;
85417  saved_nTotalChange = db->nTotalChange;
85418  saved_xTrace = db->xTrace;
85419  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
85420  db->flags &= ~SQLITE_ForeignKeys;
85421  db->xTrace = 0;
85422
85423  pMain = db->aDb[0].pBt;
85424  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
85425
85426  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
85427  ** can be set to 'off' for this file, as it is not recovered if a crash
85428  ** occurs anyway. The integrity of the database is maintained by a
85429  ** (possibly synchronous) transaction opened on the main database before
85430  ** sqlite3BtreeCopyFile() is called.
85431  **
85432  ** An optimisation would be to use a non-journaled pager.
85433  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
85434  ** that actually made the VACUUM run slower.  Very little journalling
85435  ** actually occurs when doing a vacuum since the vacuum_db is initially
85436  ** empty.  Only the journal header is written.  Apparently it takes more
85437  ** time to parse and run the PRAGMA to turn journalling off than it does
85438  ** to write the journal header file.
85439  */
85440  zSql = "ATTACH '' AS vacuum_db;";
85441  rc = execSql(db, zSql);
85442  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85443  pDb = &db->aDb[db->nDb-1];
85444  assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
85445  pTemp = db->aDb[db->nDb-1].pBt;
85446
85447  /* The call to execSql() to attach the temp database has left the file
85448  ** locked (as there was more than one active statement when the transaction
85449  ** to read the schema was concluded. Unlock it here so that this doesn't
85450  ** cause problems for the call to BtreeSetPageSize() below.  */
85451  sqlite3BtreeCommit(pTemp);
85452
85453  nRes = sqlite3BtreeGetReserve(pMain);
85454
85455  /* A VACUUM cannot change the pagesize of an encrypted database. */
85456#ifdef SQLITE_HAS_CODEC
85457  if( db->nextPagesize ){
85458    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
85459    int nKey;
85460    char *zKey;
85461    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
85462    if( nKey ) db->nextPagesize = 0;
85463  }
85464#endif
85465
85466  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
85467   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
85468   || NEVER(db->mallocFailed)
85469  ){
85470    rc = SQLITE_NOMEM;
85471    goto end_of_vacuum;
85472  }
85473  rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
85474  if( rc!=SQLITE_OK ){
85475    goto end_of_vacuum;
85476  }
85477
85478#ifndef SQLITE_OMIT_AUTOVACUUM
85479  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
85480                                           sqlite3BtreeGetAutoVacuum(pMain));
85481#endif
85482
85483  /* Begin a transaction */
85484  rc = execSql(db, "BEGIN EXCLUSIVE;");
85485  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85486
85487  /* Query the schema of the main database. Create a mirror schema
85488  ** in the temporary database.
85489  */
85490  rc = execExecSql(db,
85491      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
85492      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
85493      "   AND rootpage>0"
85494  );
85495  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85496  rc = execExecSql(db,
85497      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
85498      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
85499  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85500  rc = execExecSql(db,
85501      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
85502      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
85503  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85504
85505  /* Loop through the tables in the main database. For each, do
85506  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
85507  ** the contents to the temporary database.
85508  */
85509  rc = execExecSql(db,
85510      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
85511      "|| ' SELECT * FROM main.' || quote(name) || ';'"
85512      "FROM main.sqlite_master "
85513      "WHERE type = 'table' AND name!='sqlite_sequence' "
85514      "  AND rootpage>0"
85515
85516  );
85517  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85518
85519  /* Copy over the sequence table
85520  */
85521  rc = execExecSql(db,
85522      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
85523      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
85524  );
85525  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85526  rc = execExecSql(db,
85527      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
85528      "|| ' SELECT * FROM main.' || quote(name) || ';' "
85529      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
85530  );
85531  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85532
85533
85534  /* Copy the triggers, views, and virtual tables from the main database
85535  ** over to the temporary database.  None of these objects has any
85536  ** associated storage, so all we have to do is copy their entries
85537  ** from the SQLITE_MASTER table.
85538  */
85539  rc = execSql(db,
85540      "INSERT INTO vacuum_db.sqlite_master "
85541      "  SELECT type, name, tbl_name, rootpage, sql"
85542      "    FROM main.sqlite_master"
85543      "   WHERE type='view' OR type='trigger'"
85544      "      OR (type='table' AND rootpage=0)"
85545  );
85546  if( rc ) goto end_of_vacuum;
85547
85548  /* At this point, unless the main db was completely empty, there is now a
85549  ** transaction open on the vacuum database, but not on the main database.
85550  ** Open a btree level transaction on the main database. This allows a
85551  ** call to sqlite3BtreeCopyFile(). The main database btree level
85552  ** transaction is then committed, so the SQL level never knows it was
85553  ** opened for writing. This way, the SQL transaction used to create the
85554  ** temporary database never needs to be committed.
85555  */
85556  {
85557    u32 meta;
85558    int i;
85559
85560    /* This array determines which meta meta values are preserved in the
85561    ** vacuum.  Even entries are the meta value number and odd entries
85562    ** are an increment to apply to the meta value after the vacuum.
85563    ** The increment is used to increase the schema cookie so that other
85564    ** connections to the same database will know to reread the schema.
85565    */
85566    static const unsigned char aCopy[] = {
85567       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
85568       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
85569       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
85570       BTREE_USER_VERSION,       0,  /* Preserve the user version */
85571    };
85572
85573    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
85574    assert( 1==sqlite3BtreeIsInTrans(pMain) );
85575
85576    /* Copy Btree meta values */
85577    for(i=0; i<ArraySize(aCopy); i+=2){
85578      /* GetMeta() and UpdateMeta() cannot fail in this context because
85579      ** we already have page 1 loaded into cache and marked dirty. */
85580      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
85581      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
85582      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
85583    }
85584
85585    rc = sqlite3BtreeCopyFile(pMain, pTemp);
85586    if( rc!=SQLITE_OK ) goto end_of_vacuum;
85587    rc = sqlite3BtreeCommit(pTemp);
85588    if( rc!=SQLITE_OK ) goto end_of_vacuum;
85589#ifndef SQLITE_OMIT_AUTOVACUUM
85590    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
85591#endif
85592  }
85593
85594  assert( rc==SQLITE_OK );
85595  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
85596
85597end_of_vacuum:
85598  /* Restore the original value of db->flags */
85599  db->flags = saved_flags;
85600  db->nChange = saved_nChange;
85601  db->nTotalChange = saved_nTotalChange;
85602  db->xTrace = saved_xTrace;
85603
85604  /* Currently there is an SQL level transaction open on the vacuum
85605  ** database. No locks are held on any other files (since the main file
85606  ** was committed at the btree level). So it safe to end the transaction
85607  ** by manually setting the autoCommit flag to true and detaching the
85608  ** vacuum database. The vacuum_db journal file is deleted when the pager
85609  ** is closed by the DETACH.
85610  */
85611  db->autoCommit = 1;
85612
85613  if( pDb ){
85614    sqlite3BtreeClose(pDb->pBt);
85615    pDb->pBt = 0;
85616    pDb->pSchema = 0;
85617  }
85618
85619  sqlite3ResetInternalSchema(db, 0);
85620
85621  return rc;
85622}
85623#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
85624
85625/************** End of vacuum.c **********************************************/
85626/************** Begin file vtab.c ********************************************/
85627/*
85628** 2006 June 10
85629**
85630** The author disclaims copyright to this source code.  In place of
85631** a legal notice, here is a blessing:
85632**
85633**    May you do good and not evil.
85634**    May you find forgiveness for yourself and forgive others.
85635**    May you share freely, never taking more than you give.
85636**
85637*************************************************************************
85638** This file contains code used to help implement virtual tables.
85639*/
85640#ifndef SQLITE_OMIT_VIRTUALTABLE
85641
85642/*
85643** The actual function that does the work of creating a new module.
85644** This function implements the sqlite3_create_module() and
85645** sqlite3_create_module_v2() interfaces.
85646*/
85647static int createModule(
85648  sqlite3 *db,                    /* Database in which module is registered */
85649  const char *zName,              /* Name assigned to this module */
85650  const sqlite3_module *pModule,  /* The definition of the module */
85651  void *pAux,                     /* Context pointer for xCreate/xConnect */
85652  void (*xDestroy)(void *)        /* Module destructor function */
85653){
85654  int rc, nName;
85655  Module *pMod;
85656
85657  sqlite3_mutex_enter(db->mutex);
85658  nName = sqlite3Strlen30(zName);
85659  pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
85660  if( pMod ){
85661    Module *pDel;
85662    char *zCopy = (char *)(&pMod[1]);
85663    memcpy(zCopy, zName, nName+1);
85664    pMod->zName = zCopy;
85665    pMod->pModule = pModule;
85666    pMod->pAux = pAux;
85667    pMod->xDestroy = xDestroy;
85668    pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
85669    if( pDel && pDel->xDestroy ){
85670      pDel->xDestroy(pDel->pAux);
85671    }
85672    sqlite3DbFree(db, pDel);
85673    if( pDel==pMod ){
85674      db->mallocFailed = 1;
85675    }
85676    sqlite3ResetInternalSchema(db, 0);
85677  }else if( xDestroy ){
85678    xDestroy(pAux);
85679  }
85680  rc = sqlite3ApiExit(db, SQLITE_OK);
85681  sqlite3_mutex_leave(db->mutex);
85682  return rc;
85683}
85684
85685
85686/*
85687** External API function used to create a new virtual-table module.
85688*/
85689SQLITE_API int sqlite3_create_module(
85690  sqlite3 *db,                    /* Database in which module is registered */
85691  const char *zName,              /* Name assigned to this module */
85692  const sqlite3_module *pModule,  /* The definition of the module */
85693  void *pAux                      /* Context pointer for xCreate/xConnect */
85694){
85695  return createModule(db, zName, pModule, pAux, 0);
85696}
85697
85698/*
85699** External API function used to create a new virtual-table module.
85700*/
85701SQLITE_API int sqlite3_create_module_v2(
85702  sqlite3 *db,                    /* Database in which module is registered */
85703  const char *zName,              /* Name assigned to this module */
85704  const sqlite3_module *pModule,  /* The definition of the module */
85705  void *pAux,                     /* Context pointer for xCreate/xConnect */
85706  void (*xDestroy)(void *)        /* Module destructor function */
85707){
85708  return createModule(db, zName, pModule, pAux, xDestroy);
85709}
85710
85711/*
85712** Lock the virtual table so that it cannot be disconnected.
85713** Locks nest.  Every lock should have a corresponding unlock.
85714** If an unlock is omitted, resources leaks will occur.
85715**
85716** If a disconnect is attempted while a virtual table is locked,
85717** the disconnect is deferred until all locks have been removed.
85718*/
85719SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
85720  pVTab->nRef++;
85721}
85722
85723
85724/*
85725** pTab is a pointer to a Table structure representing a virtual-table.
85726** Return a pointer to the VTable object used by connection db to access
85727** this virtual-table, if one has been created, or NULL otherwise.
85728*/
85729SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
85730  VTable *pVtab;
85731  assert( IsVirtual(pTab) );
85732  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
85733  return pVtab;
85734}
85735
85736/*
85737** Decrement the ref-count on a virtual table object. When the ref-count
85738** reaches zero, call the xDisconnect() method to delete the object.
85739*/
85740SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
85741  sqlite3 *db = pVTab->db;
85742
85743  assert( db );
85744  assert( pVTab->nRef>0 );
85745  assert( sqlite3SafetyCheckOk(db) );
85746
85747  pVTab->nRef--;
85748  if( pVTab->nRef==0 ){
85749    sqlite3_vtab *p = pVTab->pVtab;
85750    if( p ){
85751#ifdef SQLITE_DEBUG
85752      if( pVTab->db->magic==SQLITE_MAGIC_BUSY ){
85753        (void)sqlite3SafetyOff(db);
85754        p->pModule->xDisconnect(p);
85755        (void)sqlite3SafetyOn(db);
85756      } else
85757#endif
85758      {
85759        p->pModule->xDisconnect(p);
85760      }
85761    }
85762    sqlite3DbFree(db, pVTab);
85763  }
85764}
85765
85766/*
85767** Table p is a virtual table. This function moves all elements in the
85768** p->pVTable list to the sqlite3.pDisconnect lists of their associated
85769** database connections to be disconnected at the next opportunity.
85770** Except, if argument db is not NULL, then the entry associated with
85771** connection db is left in the p->pVTable list.
85772*/
85773static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
85774  VTable *pRet = 0;
85775  VTable *pVTable = p->pVTable;
85776  p->pVTable = 0;
85777
85778  /* Assert that the mutex (if any) associated with the BtShared database
85779  ** that contains table p is held by the caller. See header comments
85780  ** above function sqlite3VtabUnlockList() for an explanation of why
85781  ** this makes it safe to access the sqlite3.pDisconnect list of any
85782  ** database connection that may have an entry in the p->pVTable list.  */
85783  assert( db==0 ||
85784    sqlite3BtreeHoldsMutex(db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].pBt)
85785  );
85786
85787  while( pVTable ){
85788    sqlite3 *db2 = pVTable->db;
85789    VTable *pNext = pVTable->pNext;
85790    assert( db2 );
85791    if( db2==db ){
85792      pRet = pVTable;
85793      p->pVTable = pRet;
85794      pRet->pNext = 0;
85795    }else{
85796      pVTable->pNext = db2->pDisconnect;
85797      db2->pDisconnect = pVTable;
85798    }
85799    pVTable = pNext;
85800  }
85801
85802  assert( !db || pRet );
85803  return pRet;
85804}
85805
85806
85807/*
85808** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
85809**
85810** This function may only be called when the mutexes associated with all
85811** shared b-tree databases opened using connection db are held by the
85812** caller. This is done to protect the sqlite3.pDisconnect list. The
85813** sqlite3.pDisconnect list is accessed only as follows:
85814**
85815**   1) By this function. In this case, all BtShared mutexes and the mutex
85816**      associated with the database handle itself must be held.
85817**
85818**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
85819**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
85820**      associated with the database the virtual table is stored in is held
85821**      or, if the virtual table is stored in a non-sharable database, then
85822**      the database handle mutex is held.
85823**
85824** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
85825** by multiple threads. It is thread-safe.
85826*/
85827SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
85828  VTable *p = db->pDisconnect;
85829  db->pDisconnect = 0;
85830
85831  assert( sqlite3BtreeHoldsAllMutexes(db) );
85832  assert( sqlite3_mutex_held(db->mutex) );
85833
85834  if( p ){
85835    sqlite3ExpirePreparedStatements(db);
85836    do {
85837      VTable *pNext = p->pNext;
85838      sqlite3VtabUnlock(p);
85839      p = pNext;
85840    }while( p );
85841  }
85842}
85843
85844/*
85845** Clear any and all virtual-table information from the Table record.
85846** This routine is called, for example, just before deleting the Table
85847** record.
85848**
85849** Since it is a virtual-table, the Table structure contains a pointer
85850** to the head of a linked list of VTable structures. Each VTable
85851** structure is associated with a single sqlite3* user of the schema.
85852** The reference count of the VTable structure associated with database
85853** connection db is decremented immediately (which may lead to the
85854** structure being xDisconnected and free). Any other VTable structures
85855** in the list are moved to the sqlite3.pDisconnect list of the associated
85856** database connection.
85857*/
85858SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
85859  vtabDisconnectAll(0, p);
85860  if( p->azModuleArg ){
85861    int i;
85862    for(i=0; i<p->nModuleArg; i++){
85863      sqlite3DbFree(p->dbMem, p->azModuleArg[i]);
85864    }
85865    sqlite3DbFree(p->dbMem, p->azModuleArg);
85866  }
85867}
85868
85869/*
85870** Add a new module argument to pTable->azModuleArg[].
85871** The string is not copied - the pointer is stored.  The
85872** string will be freed automatically when the table is
85873** deleted.
85874*/
85875static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
85876  int i = pTable->nModuleArg++;
85877  int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
85878  char **azModuleArg;
85879  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
85880  if( azModuleArg==0 ){
85881    int j;
85882    for(j=0; j<i; j++){
85883      sqlite3DbFree(db, pTable->azModuleArg[j]);
85884    }
85885    sqlite3DbFree(db, zArg);
85886    sqlite3DbFree(db, pTable->azModuleArg);
85887    pTable->nModuleArg = 0;
85888  }else{
85889    azModuleArg[i] = zArg;
85890    azModuleArg[i+1] = 0;
85891  }
85892  pTable->azModuleArg = azModuleArg;
85893}
85894
85895/*
85896** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
85897** statement.  The module name has been parsed, but the optional list
85898** of parameters that follow the module name are still pending.
85899*/
85900SQLITE_PRIVATE void sqlite3VtabBeginParse(
85901  Parse *pParse,        /* Parsing context */
85902  Token *pName1,        /* Name of new table, or database name */
85903  Token *pName2,        /* Name of new table or NULL */
85904  Token *pModuleName    /* Name of the module for the virtual table */
85905){
85906  int iDb;              /* The database the table is being created in */
85907  Table *pTable;        /* The new virtual table */
85908  sqlite3 *db;          /* Database connection */
85909
85910  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
85911  pTable = pParse->pNewTable;
85912  if( pTable==0 ) return;
85913  assert( 0==pTable->pIndex );
85914
85915  db = pParse->db;
85916  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
85917  assert( iDb>=0 );
85918
85919  pTable->tabFlags |= TF_Virtual;
85920  pTable->nModuleArg = 0;
85921  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
85922  addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
85923  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
85924  pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
85925
85926#ifndef SQLITE_OMIT_AUTHORIZATION
85927  /* Creating a virtual table invokes the authorization callback twice.
85928  ** The first invocation, to obtain permission to INSERT a row into the
85929  ** sqlite_master table, has already been made by sqlite3StartTable().
85930  ** The second call, to obtain permission to create the table, is made now.
85931  */
85932  if( pTable->azModuleArg ){
85933    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
85934            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
85935  }
85936#endif
85937}
85938
85939/*
85940** This routine takes the module argument that has been accumulating
85941** in pParse->zArg[] and appends it to the list of arguments on the
85942** virtual table currently under construction in pParse->pTable.
85943*/
85944static void addArgumentToVtab(Parse *pParse){
85945  if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
85946    const char *z = (const char*)pParse->sArg.z;
85947    int n = pParse->sArg.n;
85948    sqlite3 *db = pParse->db;
85949    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
85950  }
85951}
85952
85953/*
85954** The parser calls this routine after the CREATE VIRTUAL TABLE statement
85955** has been completely parsed.
85956*/
85957SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
85958  Table *pTab = pParse->pNewTable;  /* The table being constructed */
85959  sqlite3 *db = pParse->db;         /* The database connection */
85960
85961  if( pTab==0 ) return;
85962  addArgumentToVtab(pParse);
85963  pParse->sArg.z = 0;
85964  if( pTab->nModuleArg<1 ) return;
85965
85966  /* If the CREATE VIRTUAL TABLE statement is being entered for the
85967  ** first time (in other words if the virtual table is actually being
85968  ** created now instead of just being read out of sqlite_master) then
85969  ** do additional initialization work and store the statement text
85970  ** in the sqlite_master table.
85971  */
85972  if( !db->init.busy ){
85973    char *zStmt;
85974    char *zWhere;
85975    int iDb;
85976    Vdbe *v;
85977
85978    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
85979    if( pEnd ){
85980      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
85981    }
85982    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
85983
85984    /* A slot for the record has already been allocated in the
85985    ** SQLITE_MASTER table.  We just need to update that slot with all
85986    ** the information we've collected.
85987    **
85988    ** The VM register number pParse->regRowid holds the rowid of an
85989    ** entry in the sqlite_master table tht was created for this vtab
85990    ** by sqlite3StartTable().
85991    */
85992    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
85993    sqlite3NestedParse(pParse,
85994      "UPDATE %Q.%s "
85995         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
85996       "WHERE rowid=#%d",
85997      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
85998      pTab->zName,
85999      pTab->zName,
86000      zStmt,
86001      pParse->regRowid
86002    );
86003    sqlite3DbFree(db, zStmt);
86004    v = sqlite3GetVdbe(pParse);
86005    sqlite3ChangeCookie(pParse, iDb);
86006
86007    sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
86008    zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
86009    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
86010    sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
86011                         pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
86012  }
86013
86014  /* If we are rereading the sqlite_master table create the in-memory
86015  ** record of the table. The xConnect() method is not called until
86016  ** the first time the virtual table is used in an SQL statement. This
86017  ** allows a schema that contains virtual tables to be loaded before
86018  ** the required virtual table implementations are registered.  */
86019  else {
86020    Table *pOld;
86021    Schema *pSchema = pTab->pSchema;
86022    const char *zName = pTab->zName;
86023    int nName = sqlite3Strlen30(zName);
86024    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
86025    if( pOld ){
86026      db->mallocFailed = 1;
86027      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
86028      return;
86029    }
86030    pSchema->db = pParse->db;
86031    pParse->pNewTable = 0;
86032  }
86033}
86034
86035/*
86036** The parser calls this routine when it sees the first token
86037** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
86038*/
86039SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
86040  addArgumentToVtab(pParse);
86041  pParse->sArg.z = 0;
86042  pParse->sArg.n = 0;
86043}
86044
86045/*
86046** The parser calls this routine for each token after the first token
86047** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
86048*/
86049SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
86050  Token *pArg = &pParse->sArg;
86051  if( pArg->z==0 ){
86052    pArg->z = p->z;
86053    pArg->n = p->n;
86054  }else{
86055    assert(pArg->z < p->z);
86056    pArg->n = (int)(&p->z[p->n] - pArg->z);
86057  }
86058}
86059
86060/*
86061** Invoke a virtual table constructor (either xCreate or xConnect). The
86062** pointer to the function to invoke is passed as the fourth parameter
86063** to this procedure.
86064*/
86065static int vtabCallConstructor(
86066  sqlite3 *db,
86067  Table *pTab,
86068  Module *pMod,
86069  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
86070  char **pzErr
86071){
86072  VTable *pVTable;
86073  int rc;
86074  const char *const*azArg = (const char *const*)pTab->azModuleArg;
86075  int nArg = pTab->nModuleArg;
86076  char *zErr = 0;
86077  char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
86078
86079  if( !zModuleName ){
86080    return SQLITE_NOMEM;
86081  }
86082
86083  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
86084  if( !pVTable ){
86085    sqlite3DbFree(db, zModuleName);
86086    return SQLITE_NOMEM;
86087  }
86088  pVTable->db = db;
86089  pVTable->pMod = pMod;
86090
86091  assert( !db->pVTab );
86092  assert( xConstruct );
86093  db->pVTab = pTab;
86094
86095  /* Invoke the virtual table constructor */
86096  (void)sqlite3SafetyOff(db);
86097  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
86098  (void)sqlite3SafetyOn(db);
86099  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
86100
86101  if( SQLITE_OK!=rc ){
86102    if( zErr==0 ){
86103      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
86104    }else {
86105      *pzErr = sqlite3MPrintf(db, "%s", zErr);
86106      sqlite3DbFree(db, zErr);
86107    }
86108    sqlite3DbFree(db, pVTable);
86109  }else if( ALWAYS(pVTable->pVtab) ){
86110    /* Justification of ALWAYS():  A correct vtab constructor must allocate
86111    ** the sqlite3_vtab object if successful.  */
86112    pVTable->pVtab->pModule = pMod->pModule;
86113    pVTable->nRef = 1;
86114    if( db->pVTab ){
86115      const char *zFormat = "vtable constructor did not declare schema: %s";
86116      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
86117      sqlite3VtabUnlock(pVTable);
86118      rc = SQLITE_ERROR;
86119    }else{
86120      int iCol;
86121      /* If everything went according to plan, link the new VTable structure
86122      ** into the linked list headed by pTab->pVTable. Then loop through the
86123      ** columns of the table to see if any of them contain the token "hidden".
86124      ** If so, set the Column.isHidden flag and remove the token from
86125      ** the type string.  */
86126      pVTable->pNext = pTab->pVTable;
86127      pTab->pVTable = pVTable;
86128
86129      for(iCol=0; iCol<pTab->nCol; iCol++){
86130        char *zType = pTab->aCol[iCol].zType;
86131        int nType;
86132        int i = 0;
86133        if( !zType ) continue;
86134        nType = sqlite3Strlen30(zType);
86135        if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
86136          for(i=0; i<nType; i++){
86137            if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
86138             && (zType[i+7]=='\0' || zType[i+7]==' ')
86139            ){
86140              i++;
86141              break;
86142            }
86143          }
86144        }
86145        if( i<nType ){
86146          int j;
86147          int nDel = 6 + (zType[i+6] ? 1 : 0);
86148          for(j=i; (j+nDel)<=nType; j++){
86149            zType[j] = zType[j+nDel];
86150          }
86151          if( zType[i]=='\0' && i>0 ){
86152            assert(zType[i-1]==' ');
86153            zType[i-1] = '\0';
86154          }
86155          pTab->aCol[iCol].isHidden = 1;
86156        }
86157      }
86158    }
86159  }
86160
86161  sqlite3DbFree(db, zModuleName);
86162  db->pVTab = 0;
86163  return rc;
86164}
86165
86166/*
86167** This function is invoked by the parser to call the xConnect() method
86168** of the virtual table pTab. If an error occurs, an error code is returned
86169** and an error left in pParse.
86170**
86171** This call is a no-op if table pTab is not a virtual table.
86172*/
86173SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
86174  sqlite3 *db = pParse->db;
86175  const char *zMod;
86176  Module *pMod;
86177  int rc;
86178
86179  assert( pTab );
86180  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
86181    return SQLITE_OK;
86182  }
86183
86184  /* Locate the required virtual table module */
86185  zMod = pTab->azModuleArg[0];
86186  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
86187
86188  if( !pMod ){
86189    const char *zModule = pTab->azModuleArg[0];
86190    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
86191    rc = SQLITE_ERROR;
86192  }else{
86193    char *zErr = 0;
86194    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
86195    if( rc!=SQLITE_OK ){
86196      sqlite3ErrorMsg(pParse, "%s", zErr);
86197    }
86198    sqlite3DbFree(db, zErr);
86199  }
86200
86201  return rc;
86202}
86203
86204/*
86205** Add the virtual table pVTab to the array sqlite3.aVTrans[].
86206*/
86207static int addToVTrans(sqlite3 *db, VTable *pVTab){
86208  const int ARRAY_INCR = 5;
86209
86210  /* Grow the sqlite3.aVTrans array if required */
86211  if( (db->nVTrans%ARRAY_INCR)==0 ){
86212    VTable **aVTrans;
86213    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
86214    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
86215    if( !aVTrans ){
86216      return SQLITE_NOMEM;
86217    }
86218    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
86219    db->aVTrans = aVTrans;
86220  }
86221
86222  /* Add pVtab to the end of sqlite3.aVTrans */
86223  db->aVTrans[db->nVTrans++] = pVTab;
86224  sqlite3VtabLock(pVTab);
86225  return SQLITE_OK;
86226}
86227
86228/*
86229** This function is invoked by the vdbe to call the xCreate method
86230** of the virtual table named zTab in database iDb.
86231**
86232** If an error occurs, *pzErr is set to point an an English language
86233** description of the error and an SQLITE_XXX error code is returned.
86234** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
86235*/
86236SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
86237  int rc = SQLITE_OK;
86238  Table *pTab;
86239  Module *pMod;
86240  const char *zMod;
86241
86242  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
86243  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
86244
86245  /* Locate the required virtual table module */
86246  zMod = pTab->azModuleArg[0];
86247  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
86248
86249  /* If the module has been registered and includes a Create method,
86250  ** invoke it now. If the module has not been registered, return an
86251  ** error. Otherwise, do nothing.
86252  */
86253  if( !pMod ){
86254    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
86255    rc = SQLITE_ERROR;
86256  }else{
86257    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
86258  }
86259
86260  /* Justification of ALWAYS():  The xConstructor method is required to
86261  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
86262  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
86263      rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
86264  }
86265
86266  return rc;
86267}
86268
86269/*
86270** This function is used to set the schema of a virtual table.  It is only
86271** valid to call this function from within the xCreate() or xConnect() of a
86272** virtual table module.
86273*/
86274SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
86275  Parse *pParse;
86276
86277  int rc = SQLITE_OK;
86278  Table *pTab;
86279  char *zErr = 0;
86280
86281  sqlite3_mutex_enter(db->mutex);
86282  pTab = db->pVTab;
86283  if( !pTab ){
86284    sqlite3Error(db, SQLITE_MISUSE, 0);
86285    sqlite3_mutex_leave(db->mutex);
86286    return SQLITE_MISUSE;
86287  }
86288  assert( (pTab->tabFlags & TF_Virtual)!=0 );
86289
86290  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
86291  if( pParse==0 ){
86292    rc = SQLITE_NOMEM;
86293  }else{
86294    pParse->declareVtab = 1;
86295    pParse->db = db;
86296
86297    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
86298     && pParse->pNewTable
86299     && !db->mallocFailed
86300     && !pParse->pNewTable->pSelect
86301     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
86302    ){
86303      if( !pTab->aCol ){
86304        pTab->aCol = pParse->pNewTable->aCol;
86305        pTab->nCol = pParse->pNewTable->nCol;
86306        pParse->pNewTable->nCol = 0;
86307        pParse->pNewTable->aCol = 0;
86308      }
86309      db->pVTab = 0;
86310    }else{
86311      sqlite3Error(db, SQLITE_ERROR, zErr);
86312      sqlite3DbFree(db, zErr);
86313      rc = SQLITE_ERROR;
86314    }
86315    pParse->declareVtab = 0;
86316
86317    if( pParse->pVdbe ){
86318      sqlite3VdbeFinalize(pParse->pVdbe);
86319    }
86320    sqlite3DeleteTable(pParse->pNewTable);
86321    sqlite3StackFree(db, pParse);
86322  }
86323
86324  assert( (rc&0xff)==rc );
86325  rc = sqlite3ApiExit(db, rc);
86326  sqlite3_mutex_leave(db->mutex);
86327  return rc;
86328}
86329
86330/*
86331** This function is invoked by the vdbe to call the xDestroy method
86332** of the virtual table named zTab in database iDb. This occurs
86333** when a DROP TABLE is mentioned.
86334**
86335** This call is a no-op if zTab is not a virtual table.
86336*/
86337SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
86338  int rc = SQLITE_OK;
86339  Table *pTab;
86340
86341  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
86342  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
86343    VTable *p = vtabDisconnectAll(db, pTab);
86344
86345    rc = sqlite3SafetyOff(db);
86346    assert( rc==SQLITE_OK );
86347    rc = p->pMod->pModule->xDestroy(p->pVtab);
86348    (void)sqlite3SafetyOn(db);
86349
86350    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
86351    if( rc==SQLITE_OK ){
86352      assert( pTab->pVTable==p && p->pNext==0 );
86353      p->pVtab = 0;
86354      pTab->pVTable = 0;
86355      sqlite3VtabUnlock(p);
86356    }
86357  }
86358
86359  return rc;
86360}
86361
86362/*
86363** This function invokes either the xRollback or xCommit method
86364** of each of the virtual tables in the sqlite3.aVTrans array. The method
86365** called is identified by the second argument, "offset", which is
86366** the offset of the method to call in the sqlite3_module structure.
86367**
86368** The array is cleared after invoking the callbacks.
86369*/
86370static void callFinaliser(sqlite3 *db, int offset){
86371  int i;
86372  if( db->aVTrans ){
86373    for(i=0; i<db->nVTrans; i++){
86374      VTable *pVTab = db->aVTrans[i];
86375      sqlite3_vtab *p = pVTab->pVtab;
86376      if( p ){
86377        int (*x)(sqlite3_vtab *);
86378        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
86379        if( x ) x(p);
86380      }
86381      sqlite3VtabUnlock(pVTab);
86382    }
86383    sqlite3DbFree(db, db->aVTrans);
86384    db->nVTrans = 0;
86385    db->aVTrans = 0;
86386  }
86387}
86388
86389/*
86390** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
86391** array. Return the error code for the first error that occurs, or
86392** SQLITE_OK if all xSync operations are successful.
86393**
86394** Set *pzErrmsg to point to a buffer that should be released using
86395** sqlite3DbFree() containing an error message, if one is available.
86396*/
86397SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
86398  int i;
86399  int rc = SQLITE_OK;
86400  int rcsafety;
86401  VTable **aVTrans = db->aVTrans;
86402
86403  rc = sqlite3SafetyOff(db);
86404  db->aVTrans = 0;
86405  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
86406    int (*x)(sqlite3_vtab *);
86407    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
86408    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
86409      rc = x(pVtab);
86410      sqlite3DbFree(db, *pzErrmsg);
86411      *pzErrmsg = pVtab->zErrMsg;
86412      pVtab->zErrMsg = 0;
86413    }
86414  }
86415  db->aVTrans = aVTrans;
86416  rcsafety = sqlite3SafetyOn(db);
86417
86418  if( rc==SQLITE_OK ){
86419    rc = rcsafety;
86420  }
86421  return rc;
86422}
86423
86424/*
86425** Invoke the xRollback method of all virtual tables in the
86426** sqlite3.aVTrans array. Then clear the array itself.
86427*/
86428SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
86429  callFinaliser(db, offsetof(sqlite3_module,xRollback));
86430  return SQLITE_OK;
86431}
86432
86433/*
86434** Invoke the xCommit method of all virtual tables in the
86435** sqlite3.aVTrans array. Then clear the array itself.
86436*/
86437SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
86438  callFinaliser(db, offsetof(sqlite3_module,xCommit));
86439  return SQLITE_OK;
86440}
86441
86442/*
86443** If the virtual table pVtab supports the transaction interface
86444** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
86445** not currently open, invoke the xBegin method now.
86446**
86447** If the xBegin call is successful, place the sqlite3_vtab pointer
86448** in the sqlite3.aVTrans array.
86449*/
86450SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
86451  int rc = SQLITE_OK;
86452  const sqlite3_module *pModule;
86453
86454  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
86455  ** than zero, then this function is being called from within a
86456  ** virtual module xSync() callback. It is illegal to write to
86457  ** virtual module tables in this case, so return SQLITE_LOCKED.
86458  */
86459  if( sqlite3VtabInSync(db) ){
86460    return SQLITE_LOCKED;
86461  }
86462  if( !pVTab ){
86463    return SQLITE_OK;
86464  }
86465  pModule = pVTab->pVtab->pModule;
86466
86467  if( pModule->xBegin ){
86468    int i;
86469
86470
86471    /* If pVtab is already in the aVTrans array, return early */
86472    for(i=0; i<db->nVTrans; i++){
86473      if( db->aVTrans[i]==pVTab ){
86474        return SQLITE_OK;
86475      }
86476    }
86477
86478    /* Invoke the xBegin method */
86479    rc = pModule->xBegin(pVTab->pVtab);
86480    if( rc==SQLITE_OK ){
86481      rc = addToVTrans(db, pVTab);
86482    }
86483  }
86484  return rc;
86485}
86486
86487/*
86488** The first parameter (pDef) is a function implementation.  The
86489** second parameter (pExpr) is the first argument to this function.
86490** If pExpr is a column in a virtual table, then let the virtual
86491** table implementation have an opportunity to overload the function.
86492**
86493** This routine is used to allow virtual table implementations to
86494** overload MATCH, LIKE, GLOB, and REGEXP operators.
86495**
86496** Return either the pDef argument (indicating no change) or a
86497** new FuncDef structure that is marked as ephemeral using the
86498** SQLITE_FUNC_EPHEM flag.
86499*/
86500SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
86501  sqlite3 *db,    /* Database connection for reporting malloc problems */
86502  FuncDef *pDef,  /* Function to possibly overload */
86503  int nArg,       /* Number of arguments to the function */
86504  Expr *pExpr     /* First argument to the function */
86505){
86506  Table *pTab;
86507  sqlite3_vtab *pVtab;
86508  sqlite3_module *pMod;
86509  void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
86510  void *pArg = 0;
86511  FuncDef *pNew;
86512  int rc = 0;
86513  char *zLowerName;
86514  unsigned char *z;
86515
86516
86517  /* Check to see the left operand is a column in a virtual table */
86518  if( NEVER(pExpr==0) ) return pDef;
86519  if( pExpr->op!=TK_COLUMN ) return pDef;
86520  pTab = pExpr->pTab;
86521  if( NEVER(pTab==0) ) return pDef;
86522  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
86523  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
86524  assert( pVtab!=0 );
86525  assert( pVtab->pModule!=0 );
86526  pMod = (sqlite3_module *)pVtab->pModule;
86527  if( pMod->xFindFunction==0 ) return pDef;
86528
86529  /* Call the xFindFunction method on the virtual table implementation
86530  ** to see if the implementation wants to overload this function
86531  */
86532  zLowerName = sqlite3DbStrDup(db, pDef->zName);
86533  if( zLowerName ){
86534    for(z=(unsigned char*)zLowerName; *z; z++){
86535      *z = sqlite3UpperToLower[*z];
86536    }
86537    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
86538    sqlite3DbFree(db, zLowerName);
86539  }
86540  if( rc==0 ){
86541    return pDef;
86542  }
86543
86544  /* Create a new ephemeral function definition for the overloaded
86545  ** function */
86546  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
86547                             + sqlite3Strlen30(pDef->zName) + 1);
86548  if( pNew==0 ){
86549    return pDef;
86550  }
86551  *pNew = *pDef;
86552  pNew->zName = (char *)&pNew[1];
86553  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
86554  pNew->xFunc = xFunc;
86555  pNew->pUserData = pArg;
86556  pNew->flags |= SQLITE_FUNC_EPHEM;
86557  return pNew;
86558}
86559
86560/*
86561** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
86562** array so that an OP_VBegin will get generated for it.  Add pTab to the
86563** array if it is missing.  If pTab is already in the array, this routine
86564** is a no-op.
86565*/
86566SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
86567  Parse *pToplevel = sqlite3ParseToplevel(pParse);
86568  int i, n;
86569  Table **apVtabLock;
86570
86571  assert( IsVirtual(pTab) );
86572  for(i=0; i<pToplevel->nVtabLock; i++){
86573    if( pTab==pToplevel->apVtabLock[i] ) return;
86574  }
86575  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
86576  apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
86577  if( apVtabLock ){
86578    pToplevel->apVtabLock = apVtabLock;
86579    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
86580  }else{
86581    pToplevel->db->mallocFailed = 1;
86582  }
86583}
86584
86585#endif /* SQLITE_OMIT_VIRTUALTABLE */
86586
86587/************** End of vtab.c ************************************************/
86588/************** Begin file where.c *******************************************/
86589/*
86590** 2001 September 15
86591**
86592** The author disclaims copyright to this source code.  In place of
86593** a legal notice, here is a blessing:
86594**
86595**    May you do good and not evil.
86596**    May you find forgiveness for yourself and forgive others.
86597**    May you share freely, never taking more than you give.
86598**
86599*************************************************************************
86600** This module contains C code that generates VDBE code used to process
86601** the WHERE clause of SQL statements.  This module is responsible for
86602** generating the code that loops through a table looking for applicable
86603** rows.  Indices are selected and used to speed the search when doing
86604** so is applicable.  Because this module is responsible for selecting
86605** indices, you might also think of this module as the "query optimizer".
86606*/
86607
86608/*
86609** Trace output macros
86610*/
86611#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
86612SQLITE_PRIVATE int sqlite3WhereTrace = 0;
86613#endif
86614#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
86615# define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
86616#else
86617# define WHERETRACE(X)
86618#endif
86619
86620/* Forward reference
86621*/
86622typedef struct WhereClause WhereClause;
86623typedef struct WhereMaskSet WhereMaskSet;
86624typedef struct WhereOrInfo WhereOrInfo;
86625typedef struct WhereAndInfo WhereAndInfo;
86626typedef struct WhereCost WhereCost;
86627
86628/*
86629** The query generator uses an array of instances of this structure to
86630** help it analyze the subexpressions of the WHERE clause.  Each WHERE
86631** clause subexpression is separated from the others by AND operators,
86632** usually, or sometimes subexpressions separated by OR.
86633**
86634** All WhereTerms are collected into a single WhereClause structure.
86635** The following identity holds:
86636**
86637**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
86638**
86639** When a term is of the form:
86640**
86641**              X <op> <expr>
86642**
86643** where X is a column name and <op> is one of certain operators,
86644** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
86645** cursor number and column number for X.  WhereTerm.eOperator records
86646** the <op> using a bitmask encoding defined by WO_xxx below.  The
86647** use of a bitmask encoding for the operator allows us to search
86648** quickly for terms that match any of several different operators.
86649**
86650** A WhereTerm might also be two or more subterms connected by OR:
86651**
86652**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
86653**
86654** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
86655** and the WhereTerm.u.pOrInfo field points to auxiliary information that
86656** is collected about the
86657**
86658** If a term in the WHERE clause does not match either of the two previous
86659** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
86660** to the original subexpression content and wtFlags is set up appropriately
86661** but no other fields in the WhereTerm object are meaningful.
86662**
86663** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
86664** but they do so indirectly.  A single WhereMaskSet structure translates
86665** cursor number into bits and the translated bit is stored in the prereq
86666** fields.  The translation is used in order to maximize the number of
86667** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
86668** spread out over the non-negative integers.  For example, the cursor
86669** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
86670** translates these sparse cursor numbers into consecutive integers
86671** beginning with 0 in order to make the best possible use of the available
86672** bits in the Bitmask.  So, in the example above, the cursor numbers
86673** would be mapped into integers 0 through 7.
86674**
86675** The number of terms in a join is limited by the number of bits
86676** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
86677** is only able to process joins with 64 or fewer tables.
86678*/
86679typedef struct WhereTerm WhereTerm;
86680struct WhereTerm {
86681  Expr *pExpr;            /* Pointer to the subexpression that is this term */
86682  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
86683  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
86684  union {
86685    int leftColumn;         /* Column number of X in "X <op> <expr>" */
86686    WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
86687    WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
86688  } u;
86689  u16 eOperator;          /* A WO_xx value describing <op> */
86690  u8 wtFlags;             /* TERM_xxx bit flags.  See below */
86691  u8 nChild;              /* Number of children that must disable us */
86692  WhereClause *pWC;       /* The clause this term is part of */
86693  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
86694  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
86695};
86696
86697/*
86698** Allowed values of WhereTerm.wtFlags
86699*/
86700#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
86701#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
86702#define TERM_CODED      0x04   /* This term is already coded */
86703#define TERM_COPIED     0x08   /* Has a child */
86704#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
86705#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
86706#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
86707
86708/*
86709** An instance of the following structure holds all information about a
86710** WHERE clause.  Mostly this is a container for one or more WhereTerms.
86711*/
86712struct WhereClause {
86713  Parse *pParse;           /* The parser context */
86714  WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
86715  Bitmask vmask;           /* Bitmask identifying virtual table cursors */
86716  u8 op;                   /* Split operator.  TK_AND or TK_OR */
86717  int nTerm;               /* Number of terms */
86718  int nSlot;               /* Number of entries in a[] */
86719  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
86720#if defined(SQLITE_SMALL_STACK)
86721  WhereTerm aStatic[1];    /* Initial static space for a[] */
86722#else
86723  WhereTerm aStatic[8];    /* Initial static space for a[] */
86724#endif
86725};
86726
86727/*
86728** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
86729** a dynamically allocated instance of the following structure.
86730*/
86731struct WhereOrInfo {
86732  WhereClause wc;          /* Decomposition into subterms */
86733  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
86734};
86735
86736/*
86737** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
86738** a dynamically allocated instance of the following structure.
86739*/
86740struct WhereAndInfo {
86741  WhereClause wc;          /* The subexpression broken out */
86742};
86743
86744/*
86745** An instance of the following structure keeps track of a mapping
86746** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
86747**
86748** The VDBE cursor numbers are small integers contained in
86749** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
86750** clause, the cursor numbers might not begin with 0 and they might
86751** contain gaps in the numbering sequence.  But we want to make maximum
86752** use of the bits in our bitmasks.  This structure provides a mapping
86753** from the sparse cursor numbers into consecutive integers beginning
86754** with 0.
86755**
86756** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
86757** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
86758**
86759** For example, if the WHERE clause expression used these VDBE
86760** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
86761** would map those cursor numbers into bits 0 through 5.
86762**
86763** Note that the mapping is not necessarily ordered.  In the example
86764** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
86765** 57->5, 73->4.  Or one of 719 other combinations might be used. It
86766** does not really matter.  What is important is that sparse cursor
86767** numbers all get mapped into bit numbers that begin with 0 and contain
86768** no gaps.
86769*/
86770struct WhereMaskSet {
86771  int n;                        /* Number of assigned cursor values */
86772  int ix[BMS];                  /* Cursor assigned to each bit */
86773};
86774
86775/*
86776** A WhereCost object records a lookup strategy and the estimated
86777** cost of pursuing that strategy.
86778*/
86779struct WhereCost {
86780  WherePlan plan;    /* The lookup strategy */
86781  double rCost;      /* Overall cost of pursuing this search strategy */
86782  double nRow;       /* Estimated number of output rows */
86783  Bitmask used;      /* Bitmask of cursors used by this plan */
86784};
86785
86786/*
86787** Bitmasks for the operators that indices are able to exploit.  An
86788** OR-ed combination of these values can be used when searching for
86789** terms in the where clause.
86790*/
86791#define WO_IN     0x001
86792#define WO_EQ     0x002
86793#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
86794#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
86795#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
86796#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
86797#define WO_MATCH  0x040
86798#define WO_ISNULL 0x080
86799#define WO_OR     0x100       /* Two or more OR-connected terms */
86800#define WO_AND    0x200       /* Two or more AND-connected terms */
86801
86802#define WO_ALL    0xfff       /* Mask of all possible WO_* values */
86803#define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
86804
86805/*
86806** Value for wsFlags returned by bestIndex() and stored in
86807** WhereLevel.wsFlags.  These flags determine which search
86808** strategies are appropriate.
86809**
86810** The least significant 12 bits is reserved as a mask for WO_ values above.
86811** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
86812** But if the table is the right table of a left join, WhereLevel.wsFlags
86813** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
86814** the "op" parameter to findTerm when we are resolving equality constraints.
86815** ISNULL constraints will then not be used on the right table of a left
86816** join.  Tickets #2177 and #2189.
86817*/
86818#define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
86819#define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
86820#define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
86821#define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
86822#define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
86823#define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
86824#define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
86825#define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
86826#define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
86827#define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
86828#define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
86829#define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
86830#define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
86831#define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
86832#define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
86833#define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
86834
86835/*
86836** Initialize a preallocated WhereClause structure.
86837*/
86838static void whereClauseInit(
86839  WhereClause *pWC,        /* The WhereClause to be initialized */
86840  Parse *pParse,           /* The parsing context */
86841  WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
86842){
86843  pWC->pParse = pParse;
86844  pWC->pMaskSet = pMaskSet;
86845  pWC->nTerm = 0;
86846  pWC->nSlot = ArraySize(pWC->aStatic);
86847  pWC->a = pWC->aStatic;
86848  pWC->vmask = 0;
86849}
86850
86851/* Forward reference */
86852static void whereClauseClear(WhereClause*);
86853
86854/*
86855** Deallocate all memory associated with a WhereOrInfo object.
86856*/
86857static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
86858  whereClauseClear(&p->wc);
86859  sqlite3DbFree(db, p);
86860}
86861
86862/*
86863** Deallocate all memory associated with a WhereAndInfo object.
86864*/
86865static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
86866  whereClauseClear(&p->wc);
86867  sqlite3DbFree(db, p);
86868}
86869
86870/*
86871** Deallocate a WhereClause structure.  The WhereClause structure
86872** itself is not freed.  This routine is the inverse of whereClauseInit().
86873*/
86874static void whereClauseClear(WhereClause *pWC){
86875  int i;
86876  WhereTerm *a;
86877  sqlite3 *db = pWC->pParse->db;
86878  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
86879    if( a->wtFlags & TERM_DYNAMIC ){
86880      sqlite3ExprDelete(db, a->pExpr);
86881    }
86882    if( a->wtFlags & TERM_ORINFO ){
86883      whereOrInfoDelete(db, a->u.pOrInfo);
86884    }else if( a->wtFlags & TERM_ANDINFO ){
86885      whereAndInfoDelete(db, a->u.pAndInfo);
86886    }
86887  }
86888  if( pWC->a!=pWC->aStatic ){
86889    sqlite3DbFree(db, pWC->a);
86890  }
86891}
86892
86893/*
86894** Add a single new WhereTerm entry to the WhereClause object pWC.
86895** The new WhereTerm object is constructed from Expr p and with wtFlags.
86896** The index in pWC->a[] of the new WhereTerm is returned on success.
86897** 0 is returned if the new WhereTerm could not be added due to a memory
86898** allocation error.  The memory allocation failure will be recorded in
86899** the db->mallocFailed flag so that higher-level functions can detect it.
86900**
86901** This routine will increase the size of the pWC->a[] array as necessary.
86902**
86903** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
86904** for freeing the expression p is assumed by the WhereClause object pWC.
86905** This is true even if this routine fails to allocate a new WhereTerm.
86906**
86907** WARNING:  This routine might reallocate the space used to store
86908** WhereTerms.  All pointers to WhereTerms should be invalidated after
86909** calling this routine.  Such pointers may be reinitialized by referencing
86910** the pWC->a[] array.
86911*/
86912static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
86913  WhereTerm *pTerm;
86914  int idx;
86915  if( pWC->nTerm>=pWC->nSlot ){
86916    WhereTerm *pOld = pWC->a;
86917    sqlite3 *db = pWC->pParse->db;
86918    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
86919    if( pWC->a==0 ){
86920      if( wtFlags & TERM_DYNAMIC ){
86921        sqlite3ExprDelete(db, p);
86922      }
86923      pWC->a = pOld;
86924      return 0;
86925    }
86926    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
86927    if( pOld!=pWC->aStatic ){
86928      sqlite3DbFree(db, pOld);
86929    }
86930    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
86931  }
86932  pTerm = &pWC->a[idx = pWC->nTerm++];
86933  pTerm->pExpr = p;
86934  pTerm->wtFlags = wtFlags;
86935  pTerm->pWC = pWC;
86936  pTerm->iParent = -1;
86937  return idx;
86938}
86939
86940/*
86941** This routine identifies subexpressions in the WHERE clause where
86942** each subexpression is separated by the AND operator or some other
86943** operator specified in the op parameter.  The WhereClause structure
86944** is filled with pointers to subexpressions.  For example:
86945**
86946**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
86947**           \________/     \_______________/     \________________/
86948**            slot[0]            slot[1]               slot[2]
86949**
86950** The original WHERE clause in pExpr is unaltered.  All this routine
86951** does is make slot[] entries point to substructure within pExpr.
86952**
86953** In the previous sentence and in the diagram, "slot[]" refers to
86954** the WhereClause.a[] array.  The slot[] array grows as needed to contain
86955** all terms of the WHERE clause.
86956*/
86957static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
86958  pWC->op = (u8)op;
86959  if( pExpr==0 ) return;
86960  if( pExpr->op!=op ){
86961    whereClauseInsert(pWC, pExpr, 0);
86962  }else{
86963    whereSplit(pWC, pExpr->pLeft, op);
86964    whereSplit(pWC, pExpr->pRight, op);
86965  }
86966}
86967
86968/*
86969** Initialize an expression mask set (a WhereMaskSet object)
86970*/
86971#define initMaskSet(P)  memset(P, 0, sizeof(*P))
86972
86973/*
86974** Return the bitmask for the given cursor number.  Return 0 if
86975** iCursor is not in the set.
86976*/
86977static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
86978  int i;
86979  assert( pMaskSet->n<=sizeof(Bitmask)*8 );
86980  for(i=0; i<pMaskSet->n; i++){
86981    if( pMaskSet->ix[i]==iCursor ){
86982      return ((Bitmask)1)<<i;
86983    }
86984  }
86985  return 0;
86986}
86987
86988/*
86989** Create a new mask for cursor iCursor.
86990**
86991** There is one cursor per table in the FROM clause.  The number of
86992** tables in the FROM clause is limited by a test early in the
86993** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
86994** array will never overflow.
86995*/
86996static void createMask(WhereMaskSet *pMaskSet, int iCursor){
86997  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
86998  pMaskSet->ix[pMaskSet->n++] = iCursor;
86999}
87000
87001/*
87002** This routine walks (recursively) an expression tree and generates
87003** a bitmask indicating which tables are used in that expression
87004** tree.
87005**
87006** In order for this routine to work, the calling function must have
87007** previously invoked sqlite3ResolveExprNames() on the expression.  See
87008** the header comment on that routine for additional information.
87009** The sqlite3ResolveExprNames() routines looks for column names and
87010** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
87011** the VDBE cursor number of the table.  This routine just has to
87012** translate the cursor numbers into bitmask values and OR all
87013** the bitmasks together.
87014*/
87015static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
87016static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
87017static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
87018  Bitmask mask = 0;
87019  if( p==0 ) return 0;
87020  if( p->op==TK_COLUMN ){
87021    mask = getMask(pMaskSet, p->iTable);
87022    return mask;
87023  }
87024  mask = exprTableUsage(pMaskSet, p->pRight);
87025  mask |= exprTableUsage(pMaskSet, p->pLeft);
87026  if( ExprHasProperty(p, EP_xIsSelect) ){
87027    mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
87028  }else{
87029    mask |= exprListTableUsage(pMaskSet, p->x.pList);
87030  }
87031  return mask;
87032}
87033static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
87034  int i;
87035  Bitmask mask = 0;
87036  if( pList ){
87037    for(i=0; i<pList->nExpr; i++){
87038      mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
87039    }
87040  }
87041  return mask;
87042}
87043static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
87044  Bitmask mask = 0;
87045  while( pS ){
87046    mask |= exprListTableUsage(pMaskSet, pS->pEList);
87047    mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
87048    mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
87049    mask |= exprTableUsage(pMaskSet, pS->pWhere);
87050    mask |= exprTableUsage(pMaskSet, pS->pHaving);
87051    pS = pS->pPrior;
87052  }
87053  return mask;
87054}
87055
87056/*
87057** Return TRUE if the given operator is one of the operators that is
87058** allowed for an indexable WHERE clause term.  The allowed operators are
87059** "=", "<", ">", "<=", ">=", and "IN".
87060*/
87061static int allowedOp(int op){
87062  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
87063  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
87064  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
87065  assert( TK_GE==TK_EQ+4 );
87066  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
87067}
87068
87069/*
87070** Swap two objects of type TYPE.
87071*/
87072#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
87073
87074/*
87075** Commute a comparison operator.  Expressions of the form "X op Y"
87076** are converted into "Y op X".
87077**
87078** If a collation sequence is associated with either the left or right
87079** side of the comparison, it remains associated with the same side after
87080** the commutation. So "Y collate NOCASE op X" becomes
87081** "X collate NOCASE op Y". This is because any collation sequence on
87082** the left hand side of a comparison overrides any collation sequence
87083** attached to the right. For the same reason the EP_ExpCollate flag
87084** is not commuted.
87085*/
87086static void exprCommute(Parse *pParse, Expr *pExpr){
87087  u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
87088  u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
87089  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
87090  pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
87091  pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
87092  SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
87093  pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
87094  pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
87095  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
87096  if( pExpr->op>=TK_GT ){
87097    assert( TK_LT==TK_GT+2 );
87098    assert( TK_GE==TK_LE+2 );
87099    assert( TK_GT>TK_EQ );
87100    assert( TK_GT<TK_LE );
87101    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
87102    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
87103  }
87104}
87105
87106/*
87107** Translate from TK_xx operator to WO_xx bitmask.
87108*/
87109static u16 operatorMask(int op){
87110  u16 c;
87111  assert( allowedOp(op) );
87112  if( op==TK_IN ){
87113    c = WO_IN;
87114  }else if( op==TK_ISNULL ){
87115    c = WO_ISNULL;
87116  }else{
87117    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
87118    c = (u16)(WO_EQ<<(op-TK_EQ));
87119  }
87120  assert( op!=TK_ISNULL || c==WO_ISNULL );
87121  assert( op!=TK_IN || c==WO_IN );
87122  assert( op!=TK_EQ || c==WO_EQ );
87123  assert( op!=TK_LT || c==WO_LT );
87124  assert( op!=TK_LE || c==WO_LE );
87125  assert( op!=TK_GT || c==WO_GT );
87126  assert( op!=TK_GE || c==WO_GE );
87127  return c;
87128}
87129
87130/*
87131** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
87132** where X is a reference to the iColumn of table iCur and <op> is one of
87133** the WO_xx operator codes specified by the op parameter.
87134** Return a pointer to the term.  Return 0 if not found.
87135*/
87136static WhereTerm *findTerm(
87137  WhereClause *pWC,     /* The WHERE clause to be searched */
87138  int iCur,             /* Cursor number of LHS */
87139  int iColumn,          /* Column number of LHS */
87140  Bitmask notReady,     /* RHS must not overlap with this mask */
87141  u32 op,               /* Mask of WO_xx values describing operator */
87142  Index *pIdx           /* Must be compatible with this index, if not NULL */
87143){
87144  WhereTerm *pTerm;
87145  int k;
87146  assert( iCur>=0 );
87147  op &= WO_ALL;
87148  for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
87149    if( pTerm->leftCursor==iCur
87150       && (pTerm->prereqRight & notReady)==0
87151       && pTerm->u.leftColumn==iColumn
87152       && (pTerm->eOperator & op)!=0
87153    ){
87154      if( pIdx && pTerm->eOperator!=WO_ISNULL ){
87155        Expr *pX = pTerm->pExpr;
87156        CollSeq *pColl;
87157        char idxaff;
87158        int j;
87159        Parse *pParse = pWC->pParse;
87160
87161        idxaff = pIdx->pTable->aCol[iColumn].affinity;
87162        if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
87163
87164        /* Figure out the collation sequence required from an index for
87165        ** it to be useful for optimising expression pX. Store this
87166        ** value in variable pColl.
87167        */
87168        assert(pX->pLeft);
87169        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
87170        assert(pColl || pParse->nErr);
87171
87172        for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
87173          if( NEVER(j>=pIdx->nColumn) ) return 0;
87174        }
87175        if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
87176      }
87177      return pTerm;
87178    }
87179  }
87180  return 0;
87181}
87182
87183/* Forward reference */
87184static void exprAnalyze(SrcList*, WhereClause*, int);
87185
87186/*
87187** Call exprAnalyze on all terms in a WHERE clause.
87188**
87189**
87190*/
87191static void exprAnalyzeAll(
87192  SrcList *pTabList,       /* the FROM clause */
87193  WhereClause *pWC         /* the WHERE clause to be analyzed */
87194){
87195  int i;
87196  for(i=pWC->nTerm-1; i>=0; i--){
87197    exprAnalyze(pTabList, pWC, i);
87198  }
87199}
87200
87201#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
87202/*
87203** Check to see if the given expression is a LIKE or GLOB operator that
87204** can be optimized using inequality constraints.  Return TRUE if it is
87205** so and false if not.
87206**
87207** In order for the operator to be optimizible, the RHS must be a string
87208** literal that does not begin with a wildcard.
87209*/
87210static int isLikeOrGlob(
87211  Parse *pParse,    /* Parsing and code generating context */
87212  Expr *pExpr,      /* Test this expression */
87213  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
87214  int *pisComplete, /* True if the only wildcard is % in the last character */
87215  int *pnoCase      /* True if uppercase is equivalent to lowercase */
87216){
87217  const char *z = 0;         /* String on RHS of LIKE operator */
87218  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
87219  ExprList *pList;           /* List of operands to the LIKE operator */
87220  int c;                     /* One character in z[] */
87221  int cnt;                   /* Number of non-wildcard prefix characters */
87222  char wc[3];                /* Wildcard characters */
87223  CollSeq *pColl;            /* Collating sequence for LHS */
87224  sqlite3 *db = pParse->db;  /* Database connection */
87225  sqlite3_value *pVal = 0;
87226  int op;                    /* Opcode of pRight */
87227
87228  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
87229    return 0;
87230  }
87231#ifdef SQLITE_EBCDIC
87232  if( *pnoCase ) return 0;
87233#endif
87234  pList = pExpr->x.pList;
87235  pLeft = pList->a[1].pExpr;
87236  if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
87237    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
87238    ** be the name of an indexed column with TEXT affinity. */
87239    return 0;
87240  }
87241  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
87242  pColl = sqlite3ExprCollSeq(pParse, pLeft);
87243  assert( pColl!=0 );  /* Every non-IPK column has a collating sequence */
87244  if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
87245      (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
87246    /* IMP: R-09003-32046 For the GLOB operator, the column must use the
87247    ** default BINARY collating sequence.
87248    ** IMP: R-41408-28306 For the LIKE operator, if case_sensitive_like mode
87249    ** is enabled then the column must use the default BINARY collating
87250    ** sequence, or if case_sensitive_like mode is disabled then the column
87251    ** must use the built-in NOCASE collating sequence.
87252    */
87253    return 0;
87254  }
87255
87256  pRight = pList->a[0].pExpr;
87257  op = pRight->op;
87258  if( op==TK_REGISTER ){
87259    op = pRight->op2;
87260  }
87261  if( op==TK_VARIABLE ){
87262    Vdbe *pReprepare = pParse->pReprepare;
87263    pVal = sqlite3VdbeGetValue(pReprepare, pRight->iColumn, SQLITE_AFF_NONE);
87264    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
87265      z = (char *)sqlite3_value_text(pVal);
87266    }
87267    sqlite3VdbeSetVarmask(pParse->pVdbe, pRight->iColumn);
87268    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
87269  }else if( op==TK_STRING ){
87270    z = pRight->u.zToken;
87271  }
87272  if( z ){
87273    cnt = 0;
87274    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
87275      cnt++;
87276    }
87277    if( cnt!=0 && c!=0 && 255!=(u8)z[cnt-1] ){
87278      Expr *pPrefix;
87279      *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
87280      pPrefix = sqlite3Expr(db, TK_STRING, z);
87281      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
87282      *ppPrefix = pPrefix;
87283      if( op==TK_VARIABLE ){
87284        Vdbe *v = pParse->pVdbe;
87285        sqlite3VdbeSetVarmask(v, pRight->iColumn);
87286        if( *pisComplete && pRight->u.zToken[1] ){
87287          /* If the rhs of the LIKE expression is a variable, and the current
87288          ** value of the variable means there is no need to invoke the LIKE
87289          ** function, then no OP_Variable will be added to the program.
87290          ** This causes problems for the sqlite3_bind_parameter_name()
87291          ** API. To workaround them, add a dummy OP_Variable here.
87292          */
87293          int r1 = sqlite3GetTempReg(pParse);
87294          sqlite3ExprCodeTarget(pParse, pRight, r1);
87295          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
87296          sqlite3ReleaseTempReg(pParse, r1);
87297        }
87298      }
87299    }else{
87300      z = 0;
87301    }
87302  }
87303
87304  sqlite3ValueFree(pVal);
87305  return (z!=0);
87306}
87307#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
87308
87309
87310#ifndef SQLITE_OMIT_VIRTUALTABLE
87311/*
87312** Check to see if the given expression is of the form
87313**
87314**         column MATCH expr
87315**
87316** If it is then return TRUE.  If not, return FALSE.
87317*/
87318static int isMatchOfColumn(
87319  Expr *pExpr      /* Test this expression */
87320){
87321  ExprList *pList;
87322
87323  if( pExpr->op!=TK_FUNCTION ){
87324    return 0;
87325  }
87326  if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
87327    return 0;
87328  }
87329  pList = pExpr->x.pList;
87330  if( pList->nExpr!=2 ){
87331    return 0;
87332  }
87333  if( pList->a[1].pExpr->op != TK_COLUMN ){
87334    return 0;
87335  }
87336  return 1;
87337}
87338#endif /* SQLITE_OMIT_VIRTUALTABLE */
87339
87340/*
87341** If the pBase expression originated in the ON or USING clause of
87342** a join, then transfer the appropriate markings over to derived.
87343*/
87344static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
87345  pDerived->flags |= pBase->flags & EP_FromJoin;
87346  pDerived->iRightJoinTable = pBase->iRightJoinTable;
87347}
87348
87349#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
87350/*
87351** Analyze a term that consists of two or more OR-connected
87352** subterms.  So in:
87353**
87354**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
87355**                          ^^^^^^^^^^^^^^^^^^^^
87356**
87357** This routine analyzes terms such as the middle term in the above example.
87358** A WhereOrTerm object is computed and attached to the term under
87359** analysis, regardless of the outcome of the analysis.  Hence:
87360**
87361**     WhereTerm.wtFlags   |=  TERM_ORINFO
87362**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
87363**
87364** The term being analyzed must have two or more of OR-connected subterms.
87365** A single subterm might be a set of AND-connected sub-subterms.
87366** Examples of terms under analysis:
87367**
87368**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
87369**     (B)     x=expr1 OR expr2=x OR x=expr3
87370**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
87371**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
87372**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
87373**
87374** CASE 1:
87375**
87376** If all subterms are of the form T.C=expr for some single column of C
87377** a single table T (as shown in example B above) then create a new virtual
87378** term that is an equivalent IN expression.  In other words, if the term
87379** being analyzed is:
87380**
87381**      x = expr1  OR  expr2 = x  OR  x = expr3
87382**
87383** then create a new virtual term like this:
87384**
87385**      x IN (expr1,expr2,expr3)
87386**
87387** CASE 2:
87388**
87389** If all subterms are indexable by a single table T, then set
87390**
87391**     WhereTerm.eOperator              =  WO_OR
87392**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
87393**
87394** A subterm is "indexable" if it is of the form
87395** "T.C <op> <expr>" where C is any column of table T and
87396** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
87397** A subterm is also indexable if it is an AND of two or more
87398** subsubterms at least one of which is indexable.  Indexable AND
87399** subterms have their eOperator set to WO_AND and they have
87400** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
87401**
87402** From another point of view, "indexable" means that the subterm could
87403** potentially be used with an index if an appropriate index exists.
87404** This analysis does not consider whether or not the index exists; that
87405** is something the bestIndex() routine will determine.  This analysis
87406** only looks at whether subterms appropriate for indexing exist.
87407**
87408** All examples A through E above all satisfy case 2.  But if a term
87409** also statisfies case 1 (such as B) we know that the optimizer will
87410** always prefer case 1, so in that case we pretend that case 2 is not
87411** satisfied.
87412**
87413** It might be the case that multiple tables are indexable.  For example,
87414** (E) above is indexable on tables P, Q, and R.
87415**
87416** Terms that satisfy case 2 are candidates for lookup by using
87417** separate indices to find rowids for each subterm and composing
87418** the union of all rowids using a RowSet object.  This is similar
87419** to "bitmap indices" in other database engines.
87420**
87421** OTHERWISE:
87422**
87423** If neither case 1 nor case 2 apply, then leave the eOperator set to
87424** zero.  This term is not useful for search.
87425*/
87426static void exprAnalyzeOrTerm(
87427  SrcList *pSrc,            /* the FROM clause */
87428  WhereClause *pWC,         /* the complete WHERE clause */
87429  int idxTerm               /* Index of the OR-term to be analyzed */
87430){
87431  Parse *pParse = pWC->pParse;            /* Parser context */
87432  sqlite3 *db = pParse->db;               /* Database connection */
87433  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
87434  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
87435  WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
87436  int i;                                  /* Loop counters */
87437  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
87438  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
87439  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
87440  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
87441  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
87442
87443  /*
87444  ** Break the OR clause into its separate subterms.  The subterms are
87445  ** stored in a WhereClause structure containing within the WhereOrInfo
87446  ** object that is attached to the original OR clause term.
87447  */
87448  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
87449  assert( pExpr->op==TK_OR );
87450  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
87451  if( pOrInfo==0 ) return;
87452  pTerm->wtFlags |= TERM_ORINFO;
87453  pOrWc = &pOrInfo->wc;
87454  whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
87455  whereSplit(pOrWc, pExpr, TK_OR);
87456  exprAnalyzeAll(pSrc, pOrWc);
87457  if( db->mallocFailed ) return;
87458  assert( pOrWc->nTerm>=2 );
87459
87460  /*
87461  ** Compute the set of tables that might satisfy cases 1 or 2.
87462  */
87463  indexable = ~(Bitmask)0;
87464  chngToIN = ~(pWC->vmask);
87465  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
87466    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
87467      WhereAndInfo *pAndInfo;
87468      assert( pOrTerm->eOperator==0 );
87469      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
87470      chngToIN = 0;
87471      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
87472      if( pAndInfo ){
87473        WhereClause *pAndWC;
87474        WhereTerm *pAndTerm;
87475        int j;
87476        Bitmask b = 0;
87477        pOrTerm->u.pAndInfo = pAndInfo;
87478        pOrTerm->wtFlags |= TERM_ANDINFO;
87479        pOrTerm->eOperator = WO_AND;
87480        pAndWC = &pAndInfo->wc;
87481        whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
87482        whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
87483        exprAnalyzeAll(pSrc, pAndWC);
87484        testcase( db->mallocFailed );
87485        if( !db->mallocFailed ){
87486          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
87487            assert( pAndTerm->pExpr );
87488            if( allowedOp(pAndTerm->pExpr->op) ){
87489              b |= getMask(pMaskSet, pAndTerm->leftCursor);
87490            }
87491          }
87492        }
87493        indexable &= b;
87494      }
87495    }else if( pOrTerm->wtFlags & TERM_COPIED ){
87496      /* Skip this term for now.  We revisit it when we process the
87497      ** corresponding TERM_VIRTUAL term */
87498    }else{
87499      Bitmask b;
87500      b = getMask(pMaskSet, pOrTerm->leftCursor);
87501      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
87502        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
87503        b |= getMask(pMaskSet, pOther->leftCursor);
87504      }
87505      indexable &= b;
87506      if( pOrTerm->eOperator!=WO_EQ ){
87507        chngToIN = 0;
87508      }else{
87509        chngToIN &= b;
87510      }
87511    }
87512  }
87513
87514  /*
87515  ** Record the set of tables that satisfy case 2.  The set might be
87516  ** empty.
87517  */
87518  pOrInfo->indexable = indexable;
87519  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
87520
87521  /*
87522  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
87523  ** we have to do some additional checking to see if case 1 really
87524  ** is satisfied.
87525  **
87526  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
87527  ** that there is no possibility of transforming the OR clause into an
87528  ** IN operator because one or more terms in the OR clause contain
87529  ** something other than == on a column in the single table.  The 1-bit
87530  ** case means that every term of the OR clause is of the form
87531  ** "table.column=expr" for some single table.  The one bit that is set
87532  ** will correspond to the common table.  We still need to check to make
87533  ** sure the same column is used on all terms.  The 2-bit case is when
87534  ** the all terms are of the form "table1.column=table2.column".  It
87535  ** might be possible to form an IN operator with either table1.column
87536  ** or table2.column as the LHS if either is common to every term of
87537  ** the OR clause.
87538  **
87539  ** Note that terms of the form "table.column1=table.column2" (the
87540  ** same table on both sizes of the ==) cannot be optimized.
87541  */
87542  if( chngToIN ){
87543    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
87544    int iColumn = -1;         /* Column index on lhs of IN operator */
87545    int iCursor = -1;         /* Table cursor common to all terms */
87546    int j = 0;                /* Loop counter */
87547
87548    /* Search for a table and column that appears on one side or the
87549    ** other of the == operator in every subterm.  That table and column
87550    ** will be recorded in iCursor and iColumn.  There might not be any
87551    ** such table and column.  Set okToChngToIN if an appropriate table
87552    ** and column is found but leave okToChngToIN false if not found.
87553    */
87554    for(j=0; j<2 && !okToChngToIN; j++){
87555      pOrTerm = pOrWc->a;
87556      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
87557        assert( pOrTerm->eOperator==WO_EQ );
87558        pOrTerm->wtFlags &= ~TERM_OR_OK;
87559        if( pOrTerm->leftCursor==iCursor ){
87560          /* This is the 2-bit case and we are on the second iteration and
87561          ** current term is from the first iteration.  So skip this term. */
87562          assert( j==1 );
87563          continue;
87564        }
87565        if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
87566          /* This term must be of the form t1.a==t2.b where t2 is in the
87567          ** chngToIN set but t1 is not.  This term will be either preceeded
87568          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
87569          ** and use its inversion. */
87570          testcase( pOrTerm->wtFlags & TERM_COPIED );
87571          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
87572          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
87573          continue;
87574        }
87575        iColumn = pOrTerm->u.leftColumn;
87576        iCursor = pOrTerm->leftCursor;
87577        break;
87578      }
87579      if( i<0 ){
87580        /* No candidate table+column was found.  This can only occur
87581        ** on the second iteration */
87582        assert( j==1 );
87583        assert( (chngToIN&(chngToIN-1))==0 );
87584        assert( chngToIN==getMask(pMaskSet, iCursor) );
87585        break;
87586      }
87587      testcase( j==1 );
87588
87589      /* We have found a candidate table and column.  Check to see if that
87590      ** table and column is common to every term in the OR clause */
87591      okToChngToIN = 1;
87592      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
87593        assert( pOrTerm->eOperator==WO_EQ );
87594        if( pOrTerm->leftCursor!=iCursor ){
87595          pOrTerm->wtFlags &= ~TERM_OR_OK;
87596        }else if( pOrTerm->u.leftColumn!=iColumn ){
87597          okToChngToIN = 0;
87598        }else{
87599          int affLeft, affRight;
87600          /* If the right-hand side is also a column, then the affinities
87601          ** of both right and left sides must be such that no type
87602          ** conversions are required on the right.  (Ticket #2249)
87603          */
87604          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
87605          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
87606          if( affRight!=0 && affRight!=affLeft ){
87607            okToChngToIN = 0;
87608          }else{
87609            pOrTerm->wtFlags |= TERM_OR_OK;
87610          }
87611        }
87612      }
87613    }
87614
87615    /* At this point, okToChngToIN is true if original pTerm satisfies
87616    ** case 1.  In that case, construct a new virtual term that is
87617    ** pTerm converted into an IN operator.
87618    */
87619    if( okToChngToIN ){
87620      Expr *pDup;            /* A transient duplicate expression */
87621      ExprList *pList = 0;   /* The RHS of the IN operator */
87622      Expr *pLeft = 0;       /* The LHS of the IN operator */
87623      Expr *pNew;            /* The complete IN operator */
87624
87625      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
87626        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
87627        assert( pOrTerm->eOperator==WO_EQ );
87628        assert( pOrTerm->leftCursor==iCursor );
87629        assert( pOrTerm->u.leftColumn==iColumn );
87630        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
87631        pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
87632        pLeft = pOrTerm->pExpr->pLeft;
87633      }
87634      assert( pLeft!=0 );
87635      pDup = sqlite3ExprDup(db, pLeft, 0);
87636      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
87637      if( pNew ){
87638        int idxNew;
87639        transferJoinMarkings(pNew, pExpr);
87640        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
87641        pNew->x.pList = pList;
87642        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
87643        testcase( idxNew==0 );
87644        exprAnalyze(pSrc, pWC, idxNew);
87645        pTerm = &pWC->a[idxTerm];
87646        pWC->a[idxNew].iParent = idxTerm;
87647        pTerm->nChild = 1;
87648      }else{
87649        sqlite3ExprListDelete(db, pList);
87650      }
87651      pTerm->eOperator = 0;  /* case 1 trumps case 2 */
87652    }
87653  }
87654}
87655#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
87656
87657
87658/*
87659** The input to this routine is an WhereTerm structure with only the
87660** "pExpr" field filled in.  The job of this routine is to analyze the
87661** subexpression and populate all the other fields of the WhereTerm
87662** structure.
87663**
87664** If the expression is of the form "<expr> <op> X" it gets commuted
87665** to the standard form of "X <op> <expr>".
87666**
87667** If the expression is of the form "X <op> Y" where both X and Y are
87668** columns, then the original expression is unchanged and a new virtual
87669** term of the form "Y <op> X" is added to the WHERE clause and
87670** analyzed separately.  The original term is marked with TERM_COPIED
87671** and the new term is marked with TERM_DYNAMIC (because it's pExpr
87672** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
87673** is a commuted copy of a prior term.)  The original term has nChild=1
87674** and the copy has idxParent set to the index of the original term.
87675*/
87676static void exprAnalyze(
87677  SrcList *pSrc,            /* the FROM clause */
87678  WhereClause *pWC,         /* the WHERE clause */
87679  int idxTerm               /* Index of the term to be analyzed */
87680){
87681  WhereTerm *pTerm;                /* The term to be analyzed */
87682  WhereMaskSet *pMaskSet;          /* Set of table index masks */
87683  Expr *pExpr;                     /* The expression to be analyzed */
87684  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
87685  Bitmask prereqAll;               /* Prerequesites of pExpr */
87686  Bitmask extraRight = 0;          /* */
87687  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
87688  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
87689  int noCase = 0;                  /* LIKE/GLOB distinguishes case */
87690  int op;                          /* Top-level operator.  pExpr->op */
87691  Parse *pParse = pWC->pParse;     /* Parsing context */
87692  sqlite3 *db = pParse->db;        /* Database connection */
87693
87694  if( db->mallocFailed ){
87695    return;
87696  }
87697  pTerm = &pWC->a[idxTerm];
87698  pMaskSet = pWC->pMaskSet;
87699  pExpr = pTerm->pExpr;
87700  prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
87701  op = pExpr->op;
87702  if( op==TK_IN ){
87703    assert( pExpr->pRight==0 );
87704    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
87705      pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
87706    }else{
87707      pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
87708    }
87709  }else if( op==TK_ISNULL ){
87710    pTerm->prereqRight = 0;
87711  }else{
87712    pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
87713  }
87714  prereqAll = exprTableUsage(pMaskSet, pExpr);
87715  if( ExprHasProperty(pExpr, EP_FromJoin) ){
87716    Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
87717    prereqAll |= x;
87718    extraRight = x-1;  /* ON clause terms may not be used with an index
87719                       ** on left table of a LEFT JOIN.  Ticket #3015 */
87720  }
87721  pTerm->prereqAll = prereqAll;
87722  pTerm->leftCursor = -1;
87723  pTerm->iParent = -1;
87724  pTerm->eOperator = 0;
87725  if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
87726    Expr *pLeft = pExpr->pLeft;
87727    Expr *pRight = pExpr->pRight;
87728    if( pLeft->op==TK_COLUMN ){
87729      pTerm->leftCursor = pLeft->iTable;
87730      pTerm->u.leftColumn = pLeft->iColumn;
87731      pTerm->eOperator = operatorMask(op);
87732    }
87733    if( pRight && pRight->op==TK_COLUMN ){
87734      WhereTerm *pNew;
87735      Expr *pDup;
87736      if( pTerm->leftCursor>=0 ){
87737        int idxNew;
87738        pDup = sqlite3ExprDup(db, pExpr, 0);
87739        if( db->mallocFailed ){
87740          sqlite3ExprDelete(db, pDup);
87741          return;
87742        }
87743        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
87744        if( idxNew==0 ) return;
87745        pNew = &pWC->a[idxNew];
87746        pNew->iParent = idxTerm;
87747        pTerm = &pWC->a[idxTerm];
87748        pTerm->nChild = 1;
87749        pTerm->wtFlags |= TERM_COPIED;
87750      }else{
87751        pDup = pExpr;
87752        pNew = pTerm;
87753      }
87754      exprCommute(pParse, pDup);
87755      pLeft = pDup->pLeft;
87756      pNew->leftCursor = pLeft->iTable;
87757      pNew->u.leftColumn = pLeft->iColumn;
87758      pNew->prereqRight = prereqLeft;
87759      pNew->prereqAll = prereqAll;
87760      pNew->eOperator = operatorMask(pDup->op);
87761    }
87762  }
87763
87764#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
87765  /* If a term is the BETWEEN operator, create two new virtual terms
87766  ** that define the range that the BETWEEN implements.  For example:
87767  **
87768  **      a BETWEEN b AND c
87769  **
87770  ** is converted into:
87771  **
87772  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
87773  **
87774  ** The two new terms are added onto the end of the WhereClause object.
87775  ** The new terms are "dynamic" and are children of the original BETWEEN
87776  ** term.  That means that if the BETWEEN term is coded, the children are
87777  ** skipped.  Or, if the children are satisfied by an index, the original
87778  ** BETWEEN term is skipped.
87779  */
87780  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
87781    ExprList *pList = pExpr->x.pList;
87782    int i;
87783    static const u8 ops[] = {TK_GE, TK_LE};
87784    assert( pList!=0 );
87785    assert( pList->nExpr==2 );
87786    for(i=0; i<2; i++){
87787      Expr *pNewExpr;
87788      int idxNew;
87789      pNewExpr = sqlite3PExpr(pParse, ops[i],
87790                             sqlite3ExprDup(db, pExpr->pLeft, 0),
87791                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
87792      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
87793      testcase( idxNew==0 );
87794      exprAnalyze(pSrc, pWC, idxNew);
87795      pTerm = &pWC->a[idxTerm];
87796      pWC->a[idxNew].iParent = idxTerm;
87797    }
87798    pTerm->nChild = 2;
87799  }
87800#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
87801
87802#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
87803  /* Analyze a term that is composed of two or more subterms connected by
87804  ** an OR operator.
87805  */
87806  else if( pExpr->op==TK_OR ){
87807    assert( pWC->op==TK_AND );
87808    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
87809    pTerm = &pWC->a[idxTerm];
87810  }
87811#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
87812
87813#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
87814  /* Add constraints to reduce the search space on a LIKE or GLOB
87815  ** operator.
87816  **
87817  ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
87818  **
87819  **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
87820  **
87821  ** The last character of the prefix "abc" is incremented to form the
87822  ** termination condition "abd".
87823  */
87824  if( pWC->op==TK_AND
87825   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
87826  ){
87827    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
87828    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
87829    Expr *pNewExpr1;
87830    Expr *pNewExpr2;
87831    int idxNew1;
87832    int idxNew2;
87833
87834    pLeft = pExpr->x.pList->a[1].pExpr;
87835    pStr2 = sqlite3ExprDup(db, pStr1, 0);
87836    if( !db->mallocFailed ){
87837      u8 c, *pC;       /* Last character before the first wildcard */
87838      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
87839      c = *pC;
87840      if( noCase ){
87841        /* The point is to increment the last character before the first
87842        ** wildcard.  But if we increment '@', that will push it into the
87843        ** alphabetic range where case conversions will mess up the
87844        ** inequality.  To avoid this, make sure to also run the full
87845        ** LIKE on all candidate expressions by clearing the isComplete flag
87846        */
87847        if( c=='A'-1 ) isComplete = 0;
87848
87849        c = sqlite3UpperToLower[c];
87850      }
87851      *pC = c + 1;
87852    }
87853    pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft,0),pStr1,0);
87854    idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
87855    testcase( idxNew1==0 );
87856    exprAnalyze(pSrc, pWC, idxNew1);
87857    pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft,0),pStr2,0);
87858    idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
87859    testcase( idxNew2==0 );
87860    exprAnalyze(pSrc, pWC, idxNew2);
87861    pTerm = &pWC->a[idxTerm];
87862    if( isComplete ){
87863      pWC->a[idxNew1].iParent = idxTerm;
87864      pWC->a[idxNew2].iParent = idxTerm;
87865      pTerm->nChild = 2;
87866    }
87867  }
87868#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
87869
87870#ifndef SQLITE_OMIT_VIRTUALTABLE
87871  /* Add a WO_MATCH auxiliary term to the constraint set if the
87872  ** current expression is of the form:  column MATCH expr.
87873  ** This information is used by the xBestIndex methods of
87874  ** virtual tables.  The native query optimizer does not attempt
87875  ** to do anything with MATCH functions.
87876  */
87877  if( isMatchOfColumn(pExpr) ){
87878    int idxNew;
87879    Expr *pRight, *pLeft;
87880    WhereTerm *pNewTerm;
87881    Bitmask prereqColumn, prereqExpr;
87882
87883    pRight = pExpr->x.pList->a[0].pExpr;
87884    pLeft = pExpr->x.pList->a[1].pExpr;
87885    prereqExpr = exprTableUsage(pMaskSet, pRight);
87886    prereqColumn = exprTableUsage(pMaskSet, pLeft);
87887    if( (prereqExpr & prereqColumn)==0 ){
87888      Expr *pNewExpr;
87889      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
87890                              0, sqlite3ExprDup(db, pRight, 0), 0);
87891      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
87892      testcase( idxNew==0 );
87893      pNewTerm = &pWC->a[idxNew];
87894      pNewTerm->prereqRight = prereqExpr;
87895      pNewTerm->leftCursor = pLeft->iTable;
87896      pNewTerm->u.leftColumn = pLeft->iColumn;
87897      pNewTerm->eOperator = WO_MATCH;
87898      pNewTerm->iParent = idxTerm;
87899      pTerm = &pWC->a[idxTerm];
87900      pTerm->nChild = 1;
87901      pTerm->wtFlags |= TERM_COPIED;
87902      pNewTerm->prereqAll = pTerm->prereqAll;
87903    }
87904  }
87905#endif /* SQLITE_OMIT_VIRTUALTABLE */
87906
87907  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
87908  ** an index for tables to the left of the join.
87909  */
87910  pTerm->prereqRight |= extraRight;
87911}
87912
87913/*
87914** Return TRUE if any of the expressions in pList->a[iFirst...] contain
87915** a reference to any table other than the iBase table.
87916*/
87917static int referencesOtherTables(
87918  ExprList *pList,          /* Search expressions in ths list */
87919  WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
87920  int iFirst,               /* Be searching with the iFirst-th expression */
87921  int iBase                 /* Ignore references to this table */
87922){
87923  Bitmask allowed = ~getMask(pMaskSet, iBase);
87924  while( iFirst<pList->nExpr ){
87925    if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
87926      return 1;
87927    }
87928  }
87929  return 0;
87930}
87931
87932
87933/*
87934** This routine decides if pIdx can be used to satisfy the ORDER BY
87935** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
87936** ORDER BY clause, this routine returns 0.
87937**
87938** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
87939** left-most table in the FROM clause of that same SELECT statement and
87940** the table has a cursor number of "base".  pIdx is an index on pTab.
87941**
87942** nEqCol is the number of columns of pIdx that are used as equality
87943** constraints.  Any of these columns may be missing from the ORDER BY
87944** clause and the match can still be a success.
87945**
87946** All terms of the ORDER BY that match against the index must be either
87947** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
87948** index do not need to satisfy this constraint.)  The *pbRev value is
87949** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
87950** the ORDER BY clause is all ASC.
87951*/
87952static int isSortingIndex(
87953  Parse *pParse,          /* Parsing context */
87954  WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
87955  Index *pIdx,            /* The index we are testing */
87956  int base,               /* Cursor number for the table to be sorted */
87957  ExprList *pOrderBy,     /* The ORDER BY clause */
87958  int nEqCol,             /* Number of index columns with == constraints */
87959  int *pbRev              /* Set to 1 if ORDER BY is DESC */
87960){
87961  int i, j;                       /* Loop counters */
87962  int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
87963  int nTerm;                      /* Number of ORDER BY terms */
87964  struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
87965  sqlite3 *db = pParse->db;
87966
87967  assert( pOrderBy!=0 );
87968  nTerm = pOrderBy->nExpr;
87969  assert( nTerm>0 );
87970
87971  /* Argument pIdx must either point to a 'real' named index structure,
87972  ** or an index structure allocated on the stack by bestBtreeIndex() to
87973  ** represent the rowid index that is part of every table.  */
87974  assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
87975
87976  /* Match terms of the ORDER BY clause against columns of
87977  ** the index.
87978  **
87979  ** Note that indices have pIdx->nColumn regular columns plus
87980  ** one additional column containing the rowid.  The rowid column
87981  ** of the index is also allowed to match against the ORDER BY
87982  ** clause.
87983  */
87984  for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
87985    Expr *pExpr;       /* The expression of the ORDER BY pTerm */
87986    CollSeq *pColl;    /* The collating sequence of pExpr */
87987    int termSortOrder; /* Sort order for this term */
87988    int iColumn;       /* The i-th column of the index.  -1 for rowid */
87989    int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
87990    const char *zColl; /* Name of the collating sequence for i-th index term */
87991
87992    pExpr = pTerm->pExpr;
87993    if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
87994      /* Can not use an index sort on anything that is not a column in the
87995      ** left-most table of the FROM clause */
87996      break;
87997    }
87998    pColl = sqlite3ExprCollSeq(pParse, pExpr);
87999    if( !pColl ){
88000      pColl = db->pDfltColl;
88001    }
88002    if( pIdx->zName && i<pIdx->nColumn ){
88003      iColumn = pIdx->aiColumn[i];
88004      if( iColumn==pIdx->pTable->iPKey ){
88005        iColumn = -1;
88006      }
88007      iSortOrder = pIdx->aSortOrder[i];
88008      zColl = pIdx->azColl[i];
88009    }else{
88010      iColumn = -1;
88011      iSortOrder = 0;
88012      zColl = pColl->zName;
88013    }
88014    if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
88015      /* Term j of the ORDER BY clause does not match column i of the index */
88016      if( i<nEqCol ){
88017        /* If an index column that is constrained by == fails to match an
88018        ** ORDER BY term, that is OK.  Just ignore that column of the index
88019        */
88020        continue;
88021      }else if( i==pIdx->nColumn ){
88022        /* Index column i is the rowid.  All other terms match. */
88023        break;
88024      }else{
88025        /* If an index column fails to match and is not constrained by ==
88026        ** then the index cannot satisfy the ORDER BY constraint.
88027        */
88028        return 0;
88029      }
88030    }
88031    assert( pIdx->aSortOrder!=0 || iColumn==-1 );
88032    assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
88033    assert( iSortOrder==0 || iSortOrder==1 );
88034    termSortOrder = iSortOrder ^ pTerm->sortOrder;
88035    if( i>nEqCol ){
88036      if( termSortOrder!=sortOrder ){
88037        /* Indices can only be used if all ORDER BY terms past the
88038        ** equality constraints are all either DESC or ASC. */
88039        return 0;
88040      }
88041    }else{
88042      sortOrder = termSortOrder;
88043    }
88044    j++;
88045    pTerm++;
88046    if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
88047      /* If the indexed column is the primary key and everything matches
88048      ** so far and none of the ORDER BY terms to the right reference other
88049      ** tables in the join, then we are assured that the index can be used
88050      ** to sort because the primary key is unique and so none of the other
88051      ** columns will make any difference
88052      */
88053      j = nTerm;
88054    }
88055  }
88056
88057  *pbRev = sortOrder!=0;
88058  if( j>=nTerm ){
88059    /* All terms of the ORDER BY clause are covered by this index so
88060    ** this index can be used for sorting. */
88061    return 1;
88062  }
88063  if( pIdx->onError!=OE_None && i==pIdx->nColumn
88064      && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
88065    /* All terms of this index match some prefix of the ORDER BY clause
88066    ** and the index is UNIQUE and no terms on the tail of the ORDER BY
88067    ** clause reference other tables in a join.  If this is all true then
88068    ** the order by clause is superfluous. */
88069    return 1;
88070  }
88071  return 0;
88072}
88073
88074/*
88075** Prepare a crude estimate of the logarithm of the input value.
88076** The results need not be exact.  This is only used for estimating
88077** the total cost of performing operations with O(logN) or O(NlogN)
88078** complexity.  Because N is just a guess, it is no great tragedy if
88079** logN is a little off.
88080*/
88081static double estLog(double N){
88082  double logN = 1;
88083  double x = 10;
88084  while( N>x ){
88085    logN += 1;
88086    x *= 10;
88087  }
88088  return logN;
88089}
88090
88091/*
88092** Two routines for printing the content of an sqlite3_index_info
88093** structure.  Used for testing and debugging only.  If neither
88094** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
88095** are no-ops.
88096*/
88097#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
88098static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
88099  int i;
88100  if( !sqlite3WhereTrace ) return;
88101  for(i=0; i<p->nConstraint; i++){
88102    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
88103       i,
88104       p->aConstraint[i].iColumn,
88105       p->aConstraint[i].iTermOffset,
88106       p->aConstraint[i].op,
88107       p->aConstraint[i].usable);
88108  }
88109  for(i=0; i<p->nOrderBy; i++){
88110    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
88111       i,
88112       p->aOrderBy[i].iColumn,
88113       p->aOrderBy[i].desc);
88114  }
88115}
88116static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
88117  int i;
88118  if( !sqlite3WhereTrace ) return;
88119  for(i=0; i<p->nConstraint; i++){
88120    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
88121       i,
88122       p->aConstraintUsage[i].argvIndex,
88123       p->aConstraintUsage[i].omit);
88124  }
88125  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
88126  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
88127  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
88128  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
88129}
88130#else
88131#define TRACE_IDX_INPUTS(A)
88132#define TRACE_IDX_OUTPUTS(A)
88133#endif
88134
88135/*
88136** Required because bestIndex() is called by bestOrClauseIndex()
88137*/
88138static void bestIndex(
88139    Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*);
88140
88141/*
88142** This routine attempts to find an scanning strategy that can be used
88143** to optimize an 'OR' expression that is part of a WHERE clause.
88144**
88145** The table associated with FROM clause term pSrc may be either a
88146** regular B-Tree table or a virtual table.
88147*/
88148static void bestOrClauseIndex(
88149  Parse *pParse,              /* The parsing context */
88150  WhereClause *pWC,           /* The WHERE clause */
88151  struct SrcList_item *pSrc,  /* The FROM clause term to search */
88152  Bitmask notReady,           /* Mask of cursors that are not available */
88153  ExprList *pOrderBy,         /* The ORDER BY clause */
88154  WhereCost *pCost            /* Lowest cost query plan */
88155){
88156#ifndef SQLITE_OMIT_OR_OPTIMIZATION
88157  const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
88158  const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
88159  WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
88160  WhereTerm *pTerm;                 /* A single term of the WHERE clause */
88161
88162  /* Search the WHERE clause terms for a usable WO_OR term. */
88163  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
88164    if( pTerm->eOperator==WO_OR
88165     && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
88166     && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
88167    ){
88168      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
88169      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
88170      WhereTerm *pOrTerm;
88171      int flags = WHERE_MULTI_OR;
88172      double rTotal = 0;
88173      double nRow = 0;
88174      Bitmask used = 0;
88175
88176      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
88177        WhereCost sTermCost;
88178        WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
88179          (pOrTerm - pOrWC->a), (pTerm - pWC->a)
88180        ));
88181        if( pOrTerm->eOperator==WO_AND ){
88182          WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
88183          bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
88184        }else if( pOrTerm->leftCursor==iCur ){
88185          WhereClause tempWC;
88186          tempWC.pParse = pWC->pParse;
88187          tempWC.pMaskSet = pWC->pMaskSet;
88188          tempWC.op = TK_AND;
88189          tempWC.a = pOrTerm;
88190          tempWC.nTerm = 1;
88191          bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
88192        }else{
88193          continue;
88194        }
88195        rTotal += sTermCost.rCost;
88196        nRow += sTermCost.nRow;
88197        used |= sTermCost.used;
88198        if( rTotal>=pCost->rCost ) break;
88199      }
88200
88201      /* If there is an ORDER BY clause, increase the scan cost to account
88202      ** for the cost of the sort. */
88203      if( pOrderBy!=0 ){
88204        rTotal += nRow*estLog(nRow);
88205        WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
88206      }
88207
88208      /* If the cost of scanning using this OR term for optimization is
88209      ** less than the current cost stored in pCost, replace the contents
88210      ** of pCost. */
88211      WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
88212      if( rTotal<pCost->rCost ){
88213        pCost->rCost = rTotal;
88214        pCost->nRow = nRow;
88215        pCost->used = used;
88216        pCost->plan.wsFlags = flags;
88217        pCost->plan.u.pTerm = pTerm;
88218      }
88219    }
88220  }
88221#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
88222}
88223
88224#ifndef SQLITE_OMIT_VIRTUALTABLE
88225/*
88226** Allocate and populate an sqlite3_index_info structure. It is the
88227** responsibility of the caller to eventually release the structure
88228** by passing the pointer returned by this function to sqlite3_free().
88229*/
88230static sqlite3_index_info *allocateIndexInfo(
88231  Parse *pParse,
88232  WhereClause *pWC,
88233  struct SrcList_item *pSrc,
88234  ExprList *pOrderBy
88235){
88236  int i, j;
88237  int nTerm;
88238  struct sqlite3_index_constraint *pIdxCons;
88239  struct sqlite3_index_orderby *pIdxOrderBy;
88240  struct sqlite3_index_constraint_usage *pUsage;
88241  WhereTerm *pTerm;
88242  int nOrderBy;
88243  sqlite3_index_info *pIdxInfo;
88244
88245  WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
88246
88247  /* Count the number of possible WHERE clause constraints referring
88248  ** to this virtual table */
88249  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
88250    if( pTerm->leftCursor != pSrc->iCursor ) continue;
88251    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
88252    testcase( pTerm->eOperator==WO_IN );
88253    testcase( pTerm->eOperator==WO_ISNULL );
88254    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
88255    nTerm++;
88256  }
88257
88258  /* If the ORDER BY clause contains only columns in the current
88259  ** virtual table then allocate space for the aOrderBy part of
88260  ** the sqlite3_index_info structure.
88261  */
88262  nOrderBy = 0;
88263  if( pOrderBy ){
88264    for(i=0; i<pOrderBy->nExpr; i++){
88265      Expr *pExpr = pOrderBy->a[i].pExpr;
88266      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
88267    }
88268    if( i==pOrderBy->nExpr ){
88269      nOrderBy = pOrderBy->nExpr;
88270    }
88271  }
88272
88273  /* Allocate the sqlite3_index_info structure
88274  */
88275  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
88276                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
88277                           + sizeof(*pIdxOrderBy)*nOrderBy );
88278  if( pIdxInfo==0 ){
88279    sqlite3ErrorMsg(pParse, "out of memory");
88280    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
88281    return 0;
88282  }
88283
88284  /* Initialize the structure.  The sqlite3_index_info structure contains
88285  ** many fields that are declared "const" to prevent xBestIndex from
88286  ** changing them.  We have to do some funky casting in order to
88287  ** initialize those fields.
88288  */
88289  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
88290  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
88291  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
88292  *(int*)&pIdxInfo->nConstraint = nTerm;
88293  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
88294  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
88295  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
88296  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
88297                                                                   pUsage;
88298
88299  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
88300    if( pTerm->leftCursor != pSrc->iCursor ) continue;
88301    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
88302    testcase( pTerm->eOperator==WO_IN );
88303    testcase( pTerm->eOperator==WO_ISNULL );
88304    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
88305    pIdxCons[j].iColumn = pTerm->u.leftColumn;
88306    pIdxCons[j].iTermOffset = i;
88307    pIdxCons[j].op = (u8)pTerm->eOperator;
88308    /* The direct assignment in the previous line is possible only because
88309    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
88310    ** following asserts verify this fact. */
88311    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
88312    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
88313    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
88314    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
88315    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
88316    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
88317    assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
88318    j++;
88319  }
88320  for(i=0; i<nOrderBy; i++){
88321    Expr *pExpr = pOrderBy->a[i].pExpr;
88322    pIdxOrderBy[i].iColumn = pExpr->iColumn;
88323    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
88324  }
88325
88326  return pIdxInfo;
88327}
88328
88329/*
88330** The table object reference passed as the second argument to this function
88331** must represent a virtual table. This function invokes the xBestIndex()
88332** method of the virtual table with the sqlite3_index_info pointer passed
88333** as the argument.
88334**
88335** If an error occurs, pParse is populated with an error message and a
88336** non-zero value is returned. Otherwise, 0 is returned and the output
88337** part of the sqlite3_index_info structure is left populated.
88338**
88339** Whether or not an error is returned, it is the responsibility of the
88340** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
88341** that this is required.
88342*/
88343static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
88344  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
88345  int i;
88346  int rc;
88347
88348  (void)sqlite3SafetyOff(pParse->db);
88349  WHERETRACE(("xBestIndex for %s\n", pTab->zName));
88350  TRACE_IDX_INPUTS(p);
88351  rc = pVtab->pModule->xBestIndex(pVtab, p);
88352  TRACE_IDX_OUTPUTS(p);
88353  (void)sqlite3SafetyOn(pParse->db);
88354
88355  if( rc!=SQLITE_OK ){
88356    if( rc==SQLITE_NOMEM ){
88357      pParse->db->mallocFailed = 1;
88358    }else if( !pVtab->zErrMsg ){
88359      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
88360    }else{
88361      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
88362    }
88363  }
88364  sqlite3DbFree(pParse->db, pVtab->zErrMsg);
88365  pVtab->zErrMsg = 0;
88366
88367  for(i=0; i<p->nConstraint; i++){
88368    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
88369      sqlite3ErrorMsg(pParse,
88370          "table %s: xBestIndex returned an invalid plan", pTab->zName);
88371    }
88372  }
88373
88374  return pParse->nErr;
88375}
88376
88377
88378/*
88379** Compute the best index for a virtual table.
88380**
88381** The best index is computed by the xBestIndex method of the virtual
88382** table module.  This routine is really just a wrapper that sets up
88383** the sqlite3_index_info structure that is used to communicate with
88384** xBestIndex.
88385**
88386** In a join, this routine might be called multiple times for the
88387** same virtual table.  The sqlite3_index_info structure is created
88388** and initialized on the first invocation and reused on all subsequent
88389** invocations.  The sqlite3_index_info structure is also used when
88390** code is generated to access the virtual table.  The whereInfoDelete()
88391** routine takes care of freeing the sqlite3_index_info structure after
88392** everybody has finished with it.
88393*/
88394static void bestVirtualIndex(
88395  Parse *pParse,                  /* The parsing context */
88396  WhereClause *pWC,               /* The WHERE clause */
88397  struct SrcList_item *pSrc,      /* The FROM clause term to search */
88398  Bitmask notReady,               /* Mask of cursors that are not available */
88399  ExprList *pOrderBy,             /* The order by clause */
88400  WhereCost *pCost,               /* Lowest cost query plan */
88401  sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
88402){
88403  Table *pTab = pSrc->pTab;
88404  sqlite3_index_info *pIdxInfo;
88405  struct sqlite3_index_constraint *pIdxCons;
88406  struct sqlite3_index_constraint_usage *pUsage;
88407  WhereTerm *pTerm;
88408  int i, j;
88409  int nOrderBy;
88410
88411  /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
88412  ** malloc in allocateIndexInfo() fails and this function returns leaving
88413  ** wsFlags in an uninitialized state, the caller may behave unpredictably.
88414  */
88415  memset(pCost, 0, sizeof(*pCost));
88416  pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
88417
88418  /* If the sqlite3_index_info structure has not been previously
88419  ** allocated and initialized, then allocate and initialize it now.
88420  */
88421  pIdxInfo = *ppIdxInfo;
88422  if( pIdxInfo==0 ){
88423    *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
88424  }
88425  if( pIdxInfo==0 ){
88426    return;
88427  }
88428
88429  /* At this point, the sqlite3_index_info structure that pIdxInfo points
88430  ** to will have been initialized, either during the current invocation or
88431  ** during some prior invocation.  Now we just have to customize the
88432  ** details of pIdxInfo for the current invocation and pass it to
88433  ** xBestIndex.
88434  */
88435
88436  /* The module name must be defined. Also, by this point there must
88437  ** be a pointer to an sqlite3_vtab structure. Otherwise
88438  ** sqlite3ViewGetColumnNames() would have picked up the error.
88439  */
88440  assert( pTab->azModuleArg && pTab->azModuleArg[0] );
88441  assert( sqlite3GetVTable(pParse->db, pTab) );
88442
88443  /* Set the aConstraint[].usable fields and initialize all
88444  ** output variables to zero.
88445  **
88446  ** aConstraint[].usable is true for constraints where the right-hand
88447  ** side contains only references to tables to the left of the current
88448  ** table.  In other words, if the constraint is of the form:
88449  **
88450  **           column = expr
88451  **
88452  ** and we are evaluating a join, then the constraint on column is
88453  ** only valid if all tables referenced in expr occur to the left
88454  ** of the table containing column.
88455  **
88456  ** The aConstraints[] array contains entries for all constraints
88457  ** on the current table.  That way we only have to compute it once
88458  ** even though we might try to pick the best index multiple times.
88459  ** For each attempt at picking an index, the order of tables in the
88460  ** join might be different so we have to recompute the usable flag
88461  ** each time.
88462  */
88463  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
88464  pUsage = pIdxInfo->aConstraintUsage;
88465  for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
88466    j = pIdxCons->iTermOffset;
88467    pTerm = &pWC->a[j];
88468    pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
88469  }
88470  memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
88471  if( pIdxInfo->needToFreeIdxStr ){
88472    sqlite3_free(pIdxInfo->idxStr);
88473  }
88474  pIdxInfo->idxStr = 0;
88475  pIdxInfo->idxNum = 0;
88476  pIdxInfo->needToFreeIdxStr = 0;
88477  pIdxInfo->orderByConsumed = 0;
88478  /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
88479  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
88480  nOrderBy = pIdxInfo->nOrderBy;
88481  if( !pOrderBy ){
88482    pIdxInfo->nOrderBy = 0;
88483  }
88484
88485  if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
88486    return;
88487  }
88488
88489  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
88490  for(i=0; i<pIdxInfo->nConstraint; i++){
88491    if( pUsage[i].argvIndex>0 ){
88492      pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
88493    }
88494  }
88495
88496  /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
88497  ** inital value of lowestCost in this loop. If it is, then the
88498  ** (cost<lowestCost) test below will never be true.
88499  **
88500  ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
88501  ** is defined.
88502  */
88503  if( (SQLITE_BIG_DBL/((double)2))<pIdxInfo->estimatedCost ){
88504    pCost->rCost = (SQLITE_BIG_DBL/((double)2));
88505  }else{
88506    pCost->rCost = pIdxInfo->estimatedCost;
88507  }
88508  pCost->plan.u.pVtabIdx = pIdxInfo;
88509  if( pIdxInfo->orderByConsumed ){
88510    pCost->plan.wsFlags |= WHERE_ORDERBY;
88511  }
88512  pCost->plan.nEq = 0;
88513  pIdxInfo->nOrderBy = nOrderBy;
88514
88515  /* Try to find a more efficient access pattern by using multiple indexes
88516  ** to optimize an OR expression within the WHERE clause.
88517  */
88518  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
88519}
88520#endif /* SQLITE_OMIT_VIRTUALTABLE */
88521
88522/*
88523** Argument pIdx is a pointer to an index structure that has an array of
88524** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
88525** stored in Index.aSample. The domain of values stored in said column
88526** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
88527** Region 0 contains all values smaller than the first sample value. Region
88528** 1 contains values larger than or equal to the value of the first sample,
88529** but smaller than the value of the second. And so on.
88530**
88531** If successful, this function determines which of the regions value
88532** pVal lies in, sets *piRegion to the region index (a value between 0
88533** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
88534** Or, if an OOM occurs while converting text values between encodings,
88535** SQLITE_NOMEM is returned and *piRegion is undefined.
88536*/
88537#ifdef SQLITE_ENABLE_STAT2
88538static int whereRangeRegion(
88539  Parse *pParse,              /* Database connection */
88540  Index *pIdx,                /* Index to consider domain of */
88541  sqlite3_value *pVal,        /* Value to consider */
88542  int *piRegion               /* OUT: Region of domain in which value lies */
88543){
88544  if( ALWAYS(pVal) ){
88545    IndexSample *aSample = pIdx->aSample;
88546    int i = 0;
88547    int eType = sqlite3_value_type(pVal);
88548
88549    if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
88550      double r = sqlite3_value_double(pVal);
88551      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
88552        if( aSample[i].eType==SQLITE_NULL ) continue;
88553        if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
88554      }
88555    }else{
88556      sqlite3 *db = pParse->db;
88557      CollSeq *pColl;
88558      const u8 *z;
88559      int n;
88560
88561      /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
88562      assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
88563
88564      if( eType==SQLITE_BLOB ){
88565        z = (const u8 *)sqlite3_value_blob(pVal);
88566        pColl = db->pDfltColl;
88567        assert( pColl->enc==SQLITE_UTF8 );
88568      }else{
88569        pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
88570        if( pColl==0 ){
88571          sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
88572                          *pIdx->azColl);
88573          return SQLITE_ERROR;
88574        }
88575        z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
88576        if( !z ){
88577          return SQLITE_NOMEM;
88578        }
88579        assert( z && pColl && pColl->xCmp );
88580      }
88581      n = sqlite3ValueBytes(pVal, pColl->enc);
88582
88583      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
88584        int r;
88585        int eSampletype = aSample[i].eType;
88586        if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
88587        if( (eSampletype!=eType) ) break;
88588#ifndef SQLITE_OMIT_UTF16
88589        if( pColl->enc!=SQLITE_UTF8 ){
88590          int nSample;
88591          char *zSample = sqlite3Utf8to16(
88592              db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
88593          );
88594          if( !zSample ){
88595            assert( db->mallocFailed );
88596            return SQLITE_NOMEM;
88597          }
88598          r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
88599          sqlite3DbFree(db, zSample);
88600        }else
88601#endif
88602        {
88603          r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
88604        }
88605        if( r>0 ) break;
88606      }
88607    }
88608
88609    assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
88610    *piRegion = i;
88611  }
88612  return SQLITE_OK;
88613}
88614#endif   /* #ifdef SQLITE_ENABLE_STAT2 */
88615
88616/*
88617** If expression pExpr represents a literal value, set *pp to point to
88618** an sqlite3_value structure containing the same value, with affinity
88619** aff applied to it, before returning. It is the responsibility of the
88620** caller to eventually release this structure by passing it to
88621** sqlite3ValueFree().
88622**
88623** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
88624** is an SQL variable that currently has a non-NULL value bound to it,
88625** create an sqlite3_value structure containing this value, again with
88626** affinity aff applied to it, instead.
88627**
88628** If neither of the above apply, set *pp to NULL.
88629**
88630** If an error occurs, return an error code. Otherwise, SQLITE_OK.
88631*/
88632#ifdef SQLITE_ENABLE_STAT2
88633static int valueFromExpr(
88634  Parse *pParse,
88635  Expr *pExpr,
88636  u8 aff,
88637  sqlite3_value **pp
88638){
88639  /* The evalConstExpr() function will have already converted any TK_VARIABLE
88640  ** expression involved in an comparison into a TK_REGISTER. */
88641  assert( pExpr->op!=TK_VARIABLE );
88642  if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
88643    int iVar = pExpr->iColumn;
88644    sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
88645    *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
88646    return SQLITE_OK;
88647  }
88648  return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
88649}
88650#endif
88651
88652/*
88653** This function is used to estimate the number of rows that will be visited
88654** by scanning an index for a range of values. The range may have an upper
88655** bound, a lower bound, or both. The WHERE clause terms that set the upper
88656** and lower bounds are represented by pLower and pUpper respectively. For
88657** example, assuming that index p is on t1(a):
88658**
88659**   ... FROM t1 WHERE a > ? AND a < ? ...
88660**                    |_____|   |_____|
88661**                       |         |
88662**                     pLower    pUpper
88663**
88664** If either of the upper or lower bound is not present, then NULL is passed in
88665** place of the corresponding WhereTerm.
88666**
88667** The nEq parameter is passed the index of the index column subject to the
88668** range constraint. Or, equivalently, the number of equality constraints
88669** optimized by the proposed index scan. For example, assuming index p is
88670** on t1(a, b), and the SQL query is:
88671**
88672**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
88673**
88674** then nEq should be passed the value 1 (as the range restricted column,
88675** b, is the second left-most column of the index). Or, if the query is:
88676**
88677**   ... FROM t1 WHERE a > ? AND a < ? ...
88678**
88679** then nEq should be passed 0.
88680**
88681** The returned value is an integer between 1 and 100, inclusive. A return
88682** value of 1 indicates that the proposed range scan is expected to visit
88683** approximately 1/100th (1%) of the rows selected by the nEq equality
88684** constraints (if any). A return value of 100 indicates that it is expected
88685** that the range scan will visit every row (100%) selected by the equality
88686** constraints.
88687**
88688** In the absence of sqlite_stat2 ANALYZE data, each range inequality
88689** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
88690** results in a return of 33 and a range constraint (x>? AND x<?) results
88691** in a return of 11.
88692*/
88693static int whereRangeScanEst(
88694  Parse *pParse,       /* Parsing & code generating context */
88695  Index *p,            /* The index containing the range-compared column; "x" */
88696  int nEq,             /* index into p->aCol[] of the range-compared column */
88697  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
88698  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
88699  int *piEst           /* OUT: Return value */
88700){
88701  int rc = SQLITE_OK;
88702
88703#ifdef SQLITE_ENABLE_STAT2
88704
88705  if( nEq==0 && p->aSample ){
88706    sqlite3_value *pLowerVal = 0;
88707    sqlite3_value *pUpperVal = 0;
88708    int iEst;
88709    int iLower = 0;
88710    int iUpper = SQLITE_INDEX_SAMPLES;
88711    u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
88712
88713    if( pLower ){
88714      Expr *pExpr = pLower->pExpr->pRight;
88715      rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
88716    }
88717    if( rc==SQLITE_OK && pUpper ){
88718      Expr *pExpr = pUpper->pExpr->pRight;
88719      rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
88720    }
88721
88722    if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
88723      sqlite3ValueFree(pLowerVal);
88724      sqlite3ValueFree(pUpperVal);
88725      goto range_est_fallback;
88726    }else if( pLowerVal==0 ){
88727      rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
88728      if( pLower ) iLower = iUpper/2;
88729    }else if( pUpperVal==0 ){
88730      rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
88731      if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
88732    }else{
88733      rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
88734      if( rc==SQLITE_OK ){
88735        rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
88736      }
88737    }
88738
88739    iEst = iUpper - iLower;
88740    testcase( iEst==SQLITE_INDEX_SAMPLES );
88741    assert( iEst<=SQLITE_INDEX_SAMPLES );
88742    if( iEst<1 ){
88743      iEst = 1;
88744    }
88745
88746    sqlite3ValueFree(pLowerVal);
88747    sqlite3ValueFree(pUpperVal);
88748    *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
88749    return rc;
88750  }
88751range_est_fallback:
88752#else
88753  UNUSED_PARAMETER(pParse);
88754  UNUSED_PARAMETER(p);
88755  UNUSED_PARAMETER(nEq);
88756#endif
88757  assert( pLower || pUpper );
88758  if( pLower && pUpper ){
88759    *piEst = 11;
88760  }else{
88761    *piEst = 33;
88762  }
88763  return rc;
88764}
88765
88766
88767/*
88768** Find the query plan for accessing a particular table.  Write the
88769** best query plan and its cost into the WhereCost object supplied as the
88770** last parameter.
88771**
88772** The lowest cost plan wins.  The cost is an estimate of the amount of
88773** CPU and disk I/O need to process the request using the selected plan.
88774** Factors that influence cost include:
88775**
88776**    *  The estimated number of rows that will be retrieved.  (The
88777**       fewer the better.)
88778**
88779**    *  Whether or not sorting must occur.
88780**
88781**    *  Whether or not there must be separate lookups in the
88782**       index and in the main table.
88783**
88784** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
88785** the SQL statement, then this function only considers plans using the
88786** named index. If no such plan is found, then the returned cost is
88787** SQLITE_BIG_DBL. If a plan is found that uses the named index,
88788** then the cost is calculated in the usual way.
88789**
88790** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
88791** in the SELECT statement, then no indexes are considered. However, the
88792** selected plan may still take advantage of the tables built-in rowid
88793** index.
88794*/
88795static void bestBtreeIndex(
88796  Parse *pParse,              /* The parsing context */
88797  WhereClause *pWC,           /* The WHERE clause */
88798  struct SrcList_item *pSrc,  /* The FROM clause term to search */
88799  Bitmask notReady,           /* Mask of cursors that are not available */
88800  ExprList *pOrderBy,         /* The ORDER BY clause */
88801  WhereCost *pCost            /* Lowest cost query plan */
88802){
88803  int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
88804  Index *pProbe;              /* An index we are evaluating */
88805  Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
88806  int eqTermMask;             /* Current mask of valid equality operators */
88807  int idxEqTermMask;          /* Index mask of valid equality operators */
88808  Index sPk;                  /* A fake index object for the primary key */
88809  unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
88810  int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
88811  int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
88812
88813  /* Initialize the cost to a worst-case value */
88814  memset(pCost, 0, sizeof(*pCost));
88815  pCost->rCost = SQLITE_BIG_DBL;
88816
88817  /* If the pSrc table is the right table of a LEFT JOIN then we may not
88818  ** use an index to satisfy IS NULL constraints on that table.  This is
88819  ** because columns might end up being NULL if the table does not match -
88820  ** a circumstance which the index cannot help us discover.  Ticket #2177.
88821  */
88822  if( pSrc->jointype & JT_LEFT ){
88823    idxEqTermMask = WO_EQ|WO_IN;
88824  }else{
88825    idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
88826  }
88827
88828  if( pSrc->pIndex ){
88829    /* An INDEXED BY clause specifies a particular index to use */
88830    pIdx = pProbe = pSrc->pIndex;
88831    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
88832    eqTermMask = idxEqTermMask;
88833  }else{
88834    /* There is no INDEXED BY clause.  Create a fake Index object to
88835    ** represent the primary key */
88836    Index *pFirst;                /* Any other index on the table */
88837    memset(&sPk, 0, sizeof(Index));
88838    sPk.nColumn = 1;
88839    sPk.aiColumn = &aiColumnPk;
88840    sPk.aiRowEst = aiRowEstPk;
88841    aiRowEstPk[1] = 1;
88842    sPk.onError = OE_Replace;
88843    sPk.pTable = pSrc->pTab;
88844    pFirst = pSrc->pTab->pIndex;
88845    if( pSrc->notIndexed==0 ){
88846      sPk.pNext = pFirst;
88847    }
88848    /* The aiRowEstPk[0] is an estimate of the total number of rows in the
88849    ** table.  Get this information from the ANALYZE information if it is
88850    ** available.  If not available, assume the table 1 million rows in size.
88851    */
88852    if( pFirst ){
88853      assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */
88854      aiRowEstPk[0] = pFirst->aiRowEst[0];
88855    }else{
88856      aiRowEstPk[0] = 1000000;
88857    }
88858    pProbe = &sPk;
88859    wsFlagMask = ~(
88860        WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
88861    );
88862    eqTermMask = WO_EQ|WO_IN;
88863    pIdx = 0;
88864  }
88865
88866  /* Loop over all indices looking for the best one to use
88867  */
88868  for(; pProbe; pIdx=pProbe=pProbe->pNext){
88869    const unsigned int * const aiRowEst = pProbe->aiRowEst;
88870    double cost;                /* Cost of using pProbe */
88871    double nRow;                /* Estimated number of rows in result set */
88872    int rev;                    /* True to scan in reverse order */
88873    int wsFlags = 0;
88874    Bitmask used = 0;
88875
88876    /* The following variables are populated based on the properties of
88877    ** scan being evaluated. They are then used to determine the expected
88878    ** cost and number of rows returned.
88879    **
88880    **  nEq:
88881    **    Number of equality terms that can be implemented using the index.
88882    **
88883    **  nInMul:
88884    **    The "in-multiplier". This is an estimate of how many seek operations
88885    **    SQLite must perform on the index in question. For example, if the
88886    **    WHERE clause is:
88887    **
88888    **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
88889    **
88890    **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
88891    **    set to 9. Given the same schema and either of the following WHERE
88892    **    clauses:
88893    **
88894    **      WHERE a =  1
88895    **      WHERE a >= 2
88896    **
88897    **    nInMul is set to 1.
88898    **
88899    **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
88900    **    the sub-select is assumed to return 25 rows for the purposes of
88901    **    determining nInMul.
88902    **
88903    **  bInEst:
88904    **    Set to true if there was at least one "x IN (SELECT ...)" term used
88905    **    in determining the value of nInMul.
88906    **
88907    **  nBound:
88908    **    An estimate on the amount of the table that must be searched.  A
88909    **    value of 100 means the entire table is searched.  Range constraints
88910    **    might reduce this to a value less than 100 to indicate that only
88911    **    a fraction of the table needs searching.  In the absence of
88912    **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
88913    **    space to 1/3rd its original size.  So an x>? constraint reduces
88914    **    nBound to 33.  Two constraints (x>? AND x<?) reduce nBound to 11.
88915    **
88916    **  bSort:
88917    **    Boolean. True if there is an ORDER BY clause that will require an
88918    **    external sort (i.e. scanning the index being evaluated will not
88919    **    correctly order records).
88920    **
88921    **  bLookup:
88922    **    Boolean. True if for each index entry visited a lookup on the
88923    **    corresponding table b-tree is required. This is always false
88924    **    for the rowid index. For other indexes, it is true unless all the
88925    **    columns of the table used by the SELECT statement are present in
88926    **    the index (such an index is sometimes described as a covering index).
88927    **    For example, given the index on (a, b), the second of the following
88928    **    two queries requires table b-tree lookups, but the first does not.
88929    **
88930    **             SELECT a, b    FROM tbl WHERE a = 1;
88931    **             SELECT a, b, c FROM tbl WHERE a = 1;
88932    */
88933    int nEq;
88934    int bInEst = 0;
88935    int nInMul = 1;
88936    int nBound = 100;
88937    int bSort = 0;
88938    int bLookup = 0;
88939
88940    /* Determine the values of nEq and nInMul */
88941    for(nEq=0; nEq<pProbe->nColumn; nEq++){
88942      WhereTerm *pTerm;           /* A single term of the WHERE clause */
88943      int j = pProbe->aiColumn[nEq];
88944      pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
88945      if( pTerm==0 ) break;
88946      wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
88947      if( pTerm->eOperator & WO_IN ){
88948        Expr *pExpr = pTerm->pExpr;
88949        wsFlags |= WHERE_COLUMN_IN;
88950        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88951          nInMul *= 25;
88952          bInEst = 1;
88953        }else if( pExpr->x.pList ){
88954          nInMul *= pExpr->x.pList->nExpr + 1;
88955        }
88956      }else if( pTerm->eOperator & WO_ISNULL ){
88957        wsFlags |= WHERE_COLUMN_NULL;
88958      }
88959      used |= pTerm->prereqRight;
88960    }
88961
88962    /* Determine the value of nBound. */
88963    if( nEq<pProbe->nColumn ){
88964      int j = pProbe->aiColumn[nEq];
88965      if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
88966        WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
88967        WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
88968        whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &nBound);
88969        if( pTop ){
88970          wsFlags |= WHERE_TOP_LIMIT;
88971          used |= pTop->prereqRight;
88972        }
88973        if( pBtm ){
88974          wsFlags |= WHERE_BTM_LIMIT;
88975          used |= pBtm->prereqRight;
88976        }
88977        wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
88978      }
88979    }else if( pProbe->onError!=OE_None ){
88980      testcase( wsFlags & WHERE_COLUMN_IN );
88981      testcase( wsFlags & WHERE_COLUMN_NULL );
88982      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
88983        wsFlags |= WHERE_UNIQUE;
88984      }
88985    }
88986
88987    /* If there is an ORDER BY clause and the index being considered will
88988    ** naturally scan rows in the required order, set the appropriate flags
88989    ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
88990    ** will scan rows in a different order, set the bSort variable.  */
88991    if( pOrderBy ){
88992      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
88993        && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
88994      ){
88995        wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
88996        wsFlags |= (rev ? WHERE_REVERSE : 0);
88997      }else{
88998        bSort = 1;
88999      }
89000    }
89001
89002    /* If currently calculating the cost of using an index (not the IPK
89003    ** index), determine if all required column data may be obtained without
89004    ** seeking to entries in the main table (i.e. if the index is a covering
89005    ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
89006    ** wsFlags. Otherwise, set the bLookup variable to true.  */
89007    if( pIdx && wsFlags ){
89008      Bitmask m = pSrc->colUsed;
89009      int j;
89010      for(j=0; j<pIdx->nColumn; j++){
89011        int x = pIdx->aiColumn[j];
89012        if( x<BMS-1 ){
89013          m &= ~(((Bitmask)1)<<x);
89014        }
89015      }
89016      if( m==0 ){
89017        wsFlags |= WHERE_IDX_ONLY;
89018      }else{
89019        bLookup = 1;
89020      }
89021    }
89022
89023    /**** Begin adding up the cost of using this index (Needs improvements)
89024    **
89025    ** Estimate the number of rows of output.  For an IN operator,
89026    ** do not let the estimate exceed half the rows in the table.
89027    */
89028    nRow = (double)(aiRowEst[nEq] * nInMul);
89029    if( bInEst && nRow*2>aiRowEst[0] ){
89030      nRow = aiRowEst[0]/2;
89031      nInMul = (int)(nRow / aiRowEst[nEq]);
89032    }
89033
89034    /* Assume constant cost to access a row and logarithmic cost to
89035    ** do a binary search.  Hence, the initial cost is the number of output
89036    ** rows plus log2(table-size) times the number of binary searches.
89037    */
89038    cost = nRow + nInMul*estLog(aiRowEst[0]);
89039
89040    /* Adjust the number of rows and the cost downward to reflect rows
89041    ** that are excluded by range constraints.
89042    */
89043    nRow = (nRow * (double)nBound) / (double)100;
89044    cost = (cost * (double)nBound) / (double)100;
89045
89046    /* Add in the estimated cost of sorting the result
89047    */
89048    if( bSort ){
89049      cost += cost*estLog(cost);
89050    }
89051
89052    /* If all information can be taken directly from the index, we avoid
89053    ** doing table lookups.  This reduces the cost by half.  (Not really -
89054    ** this needs to be fixed.)
89055    */
89056    if( pIdx && bLookup==0 ){
89057      cost /= (double)2;
89058    }
89059    /**** Cost of using this index has now been computed ****/
89060
89061    WHERETRACE((
89062      "tbl=%s idx=%s nEq=%d nInMul=%d nBound=%d bSort=%d bLookup=%d"
89063      " wsFlags=%d   (nRow=%.2f cost=%.2f)\n",
89064      pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
89065      nEq, nInMul, nBound, bSort, bLookup, wsFlags, nRow, cost
89066    ));
89067
89068    /* If this index is the best we have seen so far, then record this
89069    ** index and its cost in the pCost structure.
89070    */
89071    if( (!pIdx || wsFlags) && cost<pCost->rCost ){
89072      pCost->rCost = cost;
89073      pCost->nRow = nRow;
89074      pCost->used = used;
89075      pCost->plan.wsFlags = (wsFlags&wsFlagMask);
89076      pCost->plan.nEq = nEq;
89077      pCost->plan.u.pIdx = pIdx;
89078    }
89079
89080    /* If there was an INDEXED BY clause, then only that one index is
89081    ** considered. */
89082    if( pSrc->pIndex ) break;
89083
89084    /* Reset masks for the next index in the loop */
89085    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
89086    eqTermMask = idxEqTermMask;
89087  }
89088
89089  /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
89090  ** is set, then reverse the order that the index will be scanned
89091  ** in. This is used for application testing, to help find cases
89092  ** where application behaviour depends on the (undefined) order that
89093  ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
89094  if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
89095    pCost->plan.wsFlags |= WHERE_REVERSE;
89096  }
89097
89098  assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
89099  assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
89100  assert( pSrc->pIndex==0
89101       || pCost->plan.u.pIdx==0
89102       || pCost->plan.u.pIdx==pSrc->pIndex
89103  );
89104
89105  WHERETRACE(("best index is: %s\n",
89106    (pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
89107  ));
89108
89109  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
89110  pCost->plan.wsFlags |= eqTermMask;
89111}
89112
89113/*
89114** Find the query plan for accessing table pSrc->pTab. Write the
89115** best query plan and its cost into the WhereCost object supplied
89116** as the last parameter. This function may calculate the cost of
89117** both real and virtual table scans.
89118*/
89119static void bestIndex(
89120  Parse *pParse,              /* The parsing context */
89121  WhereClause *pWC,           /* The WHERE clause */
89122  struct SrcList_item *pSrc,  /* The FROM clause term to search */
89123  Bitmask notReady,           /* Mask of cursors that are not available */
89124  ExprList *pOrderBy,         /* The ORDER BY clause */
89125  WhereCost *pCost            /* Lowest cost query plan */
89126){
89127#ifndef SQLITE_OMIT_VIRTUALTABLE
89128  if( IsVirtual(pSrc->pTab) ){
89129    sqlite3_index_info *p = 0;
89130    bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p);
89131    if( p->needToFreeIdxStr ){
89132      sqlite3_free(p->idxStr);
89133    }
89134    sqlite3DbFree(pParse->db, p);
89135  }else
89136#endif
89137  {
89138    bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
89139  }
89140}
89141
89142/*
89143** Disable a term in the WHERE clause.  Except, do not disable the term
89144** if it controls a LEFT OUTER JOIN and it did not originate in the ON
89145** or USING clause of that join.
89146**
89147** Consider the term t2.z='ok' in the following queries:
89148**
89149**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
89150**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
89151**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
89152**
89153** The t2.z='ok' is disabled in the in (2) because it originates
89154** in the ON clause.  The term is disabled in (3) because it is not part
89155** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
89156**
89157** Disabling a term causes that term to not be tested in the inner loop
89158** of the join.  Disabling is an optimization.  When terms are satisfied
89159** by indices, we disable them to prevent redundant tests in the inner
89160** loop.  We would get the correct results if nothing were ever disabled,
89161** but joins might run a little slower.  The trick is to disable as much
89162** as we can without disabling too much.  If we disabled in (1), we'd get
89163** the wrong answer.  See ticket #813.
89164*/
89165static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
89166  if( pTerm
89167      && ALWAYS((pTerm->wtFlags & TERM_CODED)==0)
89168      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
89169  ){
89170    pTerm->wtFlags |= TERM_CODED;
89171    if( pTerm->iParent>=0 ){
89172      WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
89173      if( (--pOther->nChild)==0 ){
89174        disableTerm(pLevel, pOther);
89175      }
89176    }
89177  }
89178}
89179
89180/*
89181** Code an OP_Affinity opcode to apply the column affinity string zAff
89182** to the n registers starting at base.
89183**
89184** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
89185** beginning and end of zAff are ignored.  If all entries in zAff are
89186** SQLITE_AFF_NONE, then no code gets generated.
89187**
89188** This routine makes its own copy of zAff so that the caller is free
89189** to modify zAff after this routine returns.
89190*/
89191static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
89192  Vdbe *v = pParse->pVdbe;
89193  if( zAff==0 ){
89194    assert( pParse->db->mallocFailed );
89195    return;
89196  }
89197  assert( v!=0 );
89198
89199  /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
89200  ** and end of the affinity string.
89201  */
89202  while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
89203    n--;
89204    base++;
89205    zAff++;
89206  }
89207  while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
89208    n--;
89209  }
89210
89211  /* Code the OP_Affinity opcode if there is anything left to do. */
89212  if( n>0 ){
89213    sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
89214    sqlite3VdbeChangeP4(v, -1, zAff, n);
89215    sqlite3ExprCacheAffinityChange(pParse, base, n);
89216  }
89217}
89218
89219
89220/*
89221** Generate code for a single equality term of the WHERE clause.  An equality
89222** term can be either X=expr or X IN (...).   pTerm is the term to be
89223** coded.
89224**
89225** The current value for the constraint is left in register iReg.
89226**
89227** For a constraint of the form X=expr, the expression is evaluated and its
89228** result is left on the stack.  For constraints of the form X IN (...)
89229** this routine sets up a loop that will iterate over all values of X.
89230*/
89231static int codeEqualityTerm(
89232  Parse *pParse,      /* The parsing context */
89233  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
89234  WhereLevel *pLevel, /* When level of the FROM clause we are working on */
89235  int iTarget         /* Attempt to leave results in this register */
89236){
89237  Expr *pX = pTerm->pExpr;
89238  Vdbe *v = pParse->pVdbe;
89239  int iReg;                  /* Register holding results */
89240
89241  assert( iTarget>0 );
89242  if( pX->op==TK_EQ ){
89243    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
89244  }else if( pX->op==TK_ISNULL ){
89245    iReg = iTarget;
89246    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
89247#ifndef SQLITE_OMIT_SUBQUERY
89248  }else{
89249    int eType;
89250    int iTab;
89251    struct InLoop *pIn;
89252
89253    assert( pX->op==TK_IN );
89254    iReg = iTarget;
89255    eType = sqlite3FindInIndex(pParse, pX, 0);
89256    iTab = pX->iTable;
89257    sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
89258    assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
89259    if( pLevel->u.in.nIn==0 ){
89260      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
89261    }
89262    pLevel->u.in.nIn++;
89263    pLevel->u.in.aInLoop =
89264       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
89265                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
89266    pIn = pLevel->u.in.aInLoop;
89267    if( pIn ){
89268      pIn += pLevel->u.in.nIn - 1;
89269      pIn->iCur = iTab;
89270      if( eType==IN_INDEX_ROWID ){
89271        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
89272      }else{
89273        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
89274      }
89275      sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
89276    }else{
89277      pLevel->u.in.nIn = 0;
89278    }
89279#endif
89280  }
89281  disableTerm(pLevel, pTerm);
89282  return iReg;
89283}
89284
89285/*
89286** Generate code that will evaluate all == and IN constraints for an
89287** index.
89288**
89289** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
89290** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
89291** The index has as many as three equality constraints, but in this
89292** example, the third "c" value is an inequality.  So only two
89293** constraints are coded.  This routine will generate code to evaluate
89294** a==5 and b IN (1,2,3).  The current values for a and b will be stored
89295** in consecutive registers and the index of the first register is returned.
89296**
89297** In the example above nEq==2.  But this subroutine works for any value
89298** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
89299** The only thing it does is allocate the pLevel->iMem memory cell and
89300** compute the affinity string.
89301**
89302** This routine always allocates at least one memory cell and returns
89303** the index of that memory cell. The code that
89304** calls this routine will use that memory cell to store the termination
89305** key value of the loop.  If one or more IN operators appear, then
89306** this routine allocates an additional nEq memory cells for internal
89307** use.
89308**
89309** Before returning, *pzAff is set to point to a buffer containing a
89310** copy of the column affinity string of the index allocated using
89311** sqlite3DbMalloc(). Except, entries in the copy of the string associated
89312** with equality constraints that use NONE affinity are set to
89313** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
89314**
89315**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
89316**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
89317**
89318** In the example above, the index on t1(a) has TEXT affinity. But since
89319** the right hand side of the equality constraint (t2.b) has NONE affinity,
89320** no conversion should be attempted before using a t2.b value as part of
89321** a key to search the index. Hence the first byte in the returned affinity
89322** string in this example would be set to SQLITE_AFF_NONE.
89323*/
89324static int codeAllEqualityTerms(
89325  Parse *pParse,        /* Parsing context */
89326  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
89327  WhereClause *pWC,     /* The WHERE clause */
89328  Bitmask notReady,     /* Which parts of FROM have not yet been coded */
89329  int nExtraReg,        /* Number of extra registers to allocate */
89330  char **pzAff          /* OUT: Set to point to affinity string */
89331){
89332  int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
89333  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
89334  Index *pIdx;                  /* The index being used for this loop */
89335  int iCur = pLevel->iTabCur;   /* The cursor of the table */
89336  WhereTerm *pTerm;             /* A single constraint term */
89337  int j;                        /* Loop counter */
89338  int regBase;                  /* Base register */
89339  int nReg;                     /* Number of registers to allocate */
89340  char *zAff;                   /* Affinity string to return */
89341
89342  /* This module is only called on query plans that use an index. */
89343  assert( pLevel->plan.wsFlags & WHERE_INDEXED );
89344  pIdx = pLevel->plan.u.pIdx;
89345
89346  /* Figure out how many memory cells we will need then allocate them.
89347  */
89348  regBase = pParse->nMem + 1;
89349  nReg = pLevel->plan.nEq + nExtraReg;
89350  pParse->nMem += nReg;
89351
89352  zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
89353  if( !zAff ){
89354    pParse->db->mallocFailed = 1;
89355  }
89356
89357  /* Evaluate the equality constraints
89358  */
89359  assert( pIdx->nColumn>=nEq );
89360  for(j=0; j<nEq; j++){
89361    int r1;
89362    int k = pIdx->aiColumn[j];
89363    pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
89364    if( NEVER(pTerm==0) ) break;
89365    assert( (pTerm->wtFlags & TERM_CODED)==0 );
89366    r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
89367    if( r1!=regBase+j ){
89368      if( nReg==1 ){
89369        sqlite3ReleaseTempReg(pParse, regBase);
89370        regBase = r1;
89371      }else{
89372        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
89373      }
89374    }
89375    testcase( pTerm->eOperator & WO_ISNULL );
89376    testcase( pTerm->eOperator & WO_IN );
89377    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
89378      Expr *pRight = pTerm->pExpr->pRight;
89379      sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
89380      if( zAff ){
89381        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
89382          zAff[j] = SQLITE_AFF_NONE;
89383        }
89384        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
89385          zAff[j] = SQLITE_AFF_NONE;
89386        }
89387      }
89388    }
89389  }
89390  *pzAff = zAff;
89391  return regBase;
89392}
89393
89394/*
89395** Generate code for the start of the iLevel-th loop in the WHERE clause
89396** implementation described by pWInfo.
89397*/
89398static Bitmask codeOneLoopStart(
89399  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
89400  int iLevel,          /* Which level of pWInfo->a[] should be coded */
89401  u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
89402  Bitmask notReady     /* Which tables are currently available */
89403){
89404  int j, k;            /* Loop counters */
89405  int iCur;            /* The VDBE cursor for the table */
89406  int addrNxt;         /* Where to jump to continue with the next IN case */
89407  int omitTable;       /* True if we use the index only */
89408  int bRev;            /* True if we need to scan in reverse order */
89409  WhereLevel *pLevel;  /* The where level to be coded */
89410  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
89411  WhereTerm *pTerm;               /* A WHERE clause term */
89412  Parse *pParse;                  /* Parsing context */
89413  Vdbe *v;                        /* The prepared stmt under constructions */
89414  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
89415  int addrBrk;                    /* Jump here to break out of the loop */
89416  int addrCont;                   /* Jump here to continue with next cycle */
89417  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
89418  int iReleaseReg = 0;      /* Temp register to free before returning */
89419
89420  pParse = pWInfo->pParse;
89421  v = pParse->pVdbe;
89422  pWC = pWInfo->pWC;
89423  pLevel = &pWInfo->a[iLevel];
89424  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
89425  iCur = pTabItem->iCursor;
89426  bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
89427  omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
89428           && (wctrlFlags & WHERE_FORCE_TABLE)==0;
89429
89430  /* Create labels for the "break" and "continue" instructions
89431  ** for the current loop.  Jump to addrBrk to break out of a loop.
89432  ** Jump to cont to go immediately to the next iteration of the
89433  ** loop.
89434  **
89435  ** When there is an IN operator, we also have a "addrNxt" label that
89436  ** means to continue with the next IN value combination.  When
89437  ** there are no IN operators in the constraints, the "addrNxt" label
89438  ** is the same as "addrBrk".
89439  */
89440  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
89441  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
89442
89443  /* If this is the right table of a LEFT OUTER JOIN, allocate and
89444  ** initialize a memory cell that records if this table matches any
89445  ** row of the left table of the join.
89446  */
89447  if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
89448    pLevel->iLeftJoin = ++pParse->nMem;
89449    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
89450    VdbeComment((v, "init LEFT JOIN no-match flag"));
89451  }
89452
89453#ifndef SQLITE_OMIT_VIRTUALTABLE
89454  if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
89455    /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
89456    **          to access the data.
89457    */
89458    int iReg;   /* P3 Value for OP_VFilter */
89459    sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
89460    int nConstraint = pVtabIdx->nConstraint;
89461    struct sqlite3_index_constraint_usage *aUsage =
89462                                                pVtabIdx->aConstraintUsage;
89463    const struct sqlite3_index_constraint *aConstraint =
89464                                                pVtabIdx->aConstraint;
89465
89466    sqlite3ExprCachePush(pParse);
89467    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
89468    for(j=1; j<=nConstraint; j++){
89469      for(k=0; k<nConstraint; k++){
89470        if( aUsage[k].argvIndex==j ){
89471          int iTerm = aConstraint[k].iTermOffset;
89472          sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
89473          break;
89474        }
89475      }
89476      if( k==nConstraint ) break;
89477    }
89478    sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
89479    sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
89480    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
89481                      pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
89482    pVtabIdx->needToFreeIdxStr = 0;
89483    for(j=0; j<nConstraint; j++){
89484      if( aUsage[j].omit ){
89485        int iTerm = aConstraint[j].iTermOffset;
89486        disableTerm(pLevel, &pWC->a[iTerm]);
89487      }
89488    }
89489    pLevel->op = OP_VNext;
89490    pLevel->p1 = iCur;
89491    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
89492    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
89493    sqlite3ExprCachePop(pParse, 1);
89494  }else
89495#endif /* SQLITE_OMIT_VIRTUALTABLE */
89496
89497  if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
89498    /* Case 1:  We can directly reference a single row using an
89499    **          equality comparison against the ROWID field.  Or
89500    **          we reference multiple rows using a "rowid IN (...)"
89501    **          construct.
89502    */
89503    iReleaseReg = sqlite3GetTempReg(pParse);
89504    pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
89505    assert( pTerm!=0 );
89506    assert( pTerm->pExpr!=0 );
89507    assert( pTerm->leftCursor==iCur );
89508    assert( omitTable==0 );
89509    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
89510    addrNxt = pLevel->addrNxt;
89511    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
89512    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
89513    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
89514    VdbeComment((v, "pk"));
89515    pLevel->op = OP_Noop;
89516  }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
89517    /* Case 2:  We have an inequality comparison against the ROWID field.
89518    */
89519    int testOp = OP_Noop;
89520    int start;
89521    int memEndValue = 0;
89522    WhereTerm *pStart, *pEnd;
89523
89524    assert( omitTable==0 );
89525    pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
89526    pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
89527    if( bRev ){
89528      pTerm = pStart;
89529      pStart = pEnd;
89530      pEnd = pTerm;
89531    }
89532    if( pStart ){
89533      Expr *pX;             /* The expression that defines the start bound */
89534      int r1, rTemp;        /* Registers for holding the start boundary */
89535
89536      /* The following constant maps TK_xx codes into corresponding
89537      ** seek opcodes.  It depends on a particular ordering of TK_xx
89538      */
89539      const u8 aMoveOp[] = {
89540           /* TK_GT */  OP_SeekGt,
89541           /* TK_LE */  OP_SeekLe,
89542           /* TK_LT */  OP_SeekLt,
89543           /* TK_GE */  OP_SeekGe
89544      };
89545      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
89546      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
89547      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
89548
89549      pX = pStart->pExpr;
89550      assert( pX!=0 );
89551      assert( pStart->leftCursor==iCur );
89552      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
89553      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
89554      VdbeComment((v, "pk"));
89555      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
89556      sqlite3ReleaseTempReg(pParse, rTemp);
89557      disableTerm(pLevel, pStart);
89558    }else{
89559      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
89560    }
89561    if( pEnd ){
89562      Expr *pX;
89563      pX = pEnd->pExpr;
89564      assert( pX!=0 );
89565      assert( pEnd->leftCursor==iCur );
89566      memEndValue = ++pParse->nMem;
89567      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
89568      if( pX->op==TK_LT || pX->op==TK_GT ){
89569        testOp = bRev ? OP_Le : OP_Ge;
89570      }else{
89571        testOp = bRev ? OP_Lt : OP_Gt;
89572      }
89573      disableTerm(pLevel, pEnd);
89574    }
89575    start = sqlite3VdbeCurrentAddr(v);
89576    pLevel->op = bRev ? OP_Prev : OP_Next;
89577    pLevel->p1 = iCur;
89578    pLevel->p2 = start;
89579    pLevel->p5 = (pStart==0 && pEnd==0) ?1:0;
89580    if( testOp!=OP_Noop ){
89581      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
89582      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
89583      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
89584      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
89585      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
89586    }
89587  }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
89588    /* Case 3: A scan using an index.
89589    **
89590    **         The WHERE clause may contain zero or more equality
89591    **         terms ("==" or "IN" operators) that refer to the N
89592    **         left-most columns of the index. It may also contain
89593    **         inequality constraints (>, <, >= or <=) on the indexed
89594    **         column that immediately follows the N equalities. Only
89595    **         the right-most column can be an inequality - the rest must
89596    **         use the "==" and "IN" operators. For example, if the
89597    **         index is on (x,y,z), then the following clauses are all
89598    **         optimized:
89599    **
89600    **            x=5
89601    **            x=5 AND y=10
89602    **            x=5 AND y<10
89603    **            x=5 AND y>5 AND y<10
89604    **            x=5 AND y=5 AND z<=10
89605    **
89606    **         The z<10 term of the following cannot be used, only
89607    **         the x=5 term:
89608    **
89609    **            x=5 AND z<10
89610    **
89611    **         N may be zero if there are inequality constraints.
89612    **         If there are no inequality constraints, then N is at
89613    **         least one.
89614    **
89615    **         This case is also used when there are no WHERE clause
89616    **         constraints but an index is selected anyway, in order
89617    **         to force the output order to conform to an ORDER BY.
89618    */
89619    int aStartOp[] = {
89620      0,
89621      0,
89622      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
89623      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
89624      OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
89625      OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
89626      OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
89627      OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
89628    };
89629    int aEndOp[] = {
89630      OP_Noop,             /* 0: (!end_constraints) */
89631      OP_IdxGE,            /* 1: (end_constraints && !bRev) */
89632      OP_IdxLT             /* 2: (end_constraints && bRev) */
89633    };
89634    int nEq = pLevel->plan.nEq;
89635    int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
89636    int regBase;                 /* Base register holding constraint values */
89637    int r1;                      /* Temp register */
89638    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
89639    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
89640    int startEq;                 /* True if range start uses ==, >= or <= */
89641    int endEq;                   /* True if range end uses ==, >= or <= */
89642    int start_constraints;       /* Start of range is constrained */
89643    int nConstraint;             /* Number of constraint terms */
89644    Index *pIdx;         /* The index we will be using */
89645    int iIdxCur;         /* The VDBE cursor for the index */
89646    int nExtraReg = 0;   /* Number of extra registers needed */
89647    int op;              /* Instruction opcode */
89648    char *zAff;
89649
89650    pIdx = pLevel->plan.u.pIdx;
89651    iIdxCur = pLevel->iIdxCur;
89652    k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
89653
89654    /* If this loop satisfies a sort order (pOrderBy) request that
89655    ** was passed to this function to implement a "SELECT min(x) ..."
89656    ** query, then the caller will only allow the loop to run for
89657    ** a single iteration. This means that the first row returned
89658    ** should not have a NULL value stored in 'x'. If column 'x' is
89659    ** the first one after the nEq equality constraints in the index,
89660    ** this requires some special handling.
89661    */
89662    if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
89663     && (pLevel->plan.wsFlags&WHERE_ORDERBY)
89664     && (pIdx->nColumn>nEq)
89665    ){
89666      /* assert( pOrderBy->nExpr==1 ); */
89667      /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
89668      isMinQuery = 1;
89669      nExtraReg = 1;
89670    }
89671
89672    /* Find any inequality constraint terms for the start and end
89673    ** of the range.
89674    */
89675    if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
89676      pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
89677      nExtraReg = 1;
89678    }
89679    if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
89680      pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
89681      nExtraReg = 1;
89682    }
89683
89684    /* Generate code to evaluate all constraint terms using == or IN
89685    ** and store the values of those terms in an array of registers
89686    ** starting at regBase.
89687    */
89688    regBase = codeAllEqualityTerms(
89689        pParse, pLevel, pWC, notReady, nExtraReg, &zAff
89690    );
89691    addrNxt = pLevel->addrNxt;
89692
89693    /* If we are doing a reverse order scan on an ascending index, or
89694    ** a forward order scan on a descending index, interchange the
89695    ** start and end terms (pRangeStart and pRangeEnd).
89696    */
89697    if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
89698      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
89699    }
89700
89701    testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
89702    testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
89703    testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
89704    testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
89705    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
89706    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
89707    start_constraints = pRangeStart || nEq>0;
89708
89709    /* Seek the index cursor to the start of the range. */
89710    nConstraint = nEq;
89711    if( pRangeStart ){
89712      Expr *pRight = pRangeStart->pExpr->pRight;
89713      sqlite3ExprCode(pParse, pRight, regBase+nEq);
89714      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
89715      if( zAff ){
89716        if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
89717          /* Since the comparison is to be performed with no conversions
89718          ** applied to the operands, set the affinity to apply to pRight to
89719          ** SQLITE_AFF_NONE.  */
89720          zAff[nConstraint] = SQLITE_AFF_NONE;
89721        }
89722        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
89723          zAff[nConstraint] = SQLITE_AFF_NONE;
89724        }
89725      }
89726      nConstraint++;
89727    }else if( isMinQuery ){
89728      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
89729      nConstraint++;
89730      startEq = 0;
89731      start_constraints = 1;
89732    }
89733    codeApplyAffinity(pParse, regBase, nConstraint, zAff);
89734    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
89735    assert( op!=0 );
89736    testcase( op==OP_Rewind );
89737    testcase( op==OP_Last );
89738    testcase( op==OP_SeekGt );
89739    testcase( op==OP_SeekGe );
89740    testcase( op==OP_SeekLe );
89741    testcase( op==OP_SeekLt );
89742    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
89743
89744    /* Load the value for the inequality constraint at the end of the
89745    ** range (if any).
89746    */
89747    nConstraint = nEq;
89748    if( pRangeEnd ){
89749      Expr *pRight = pRangeEnd->pExpr->pRight;
89750      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
89751      sqlite3ExprCode(pParse, pRight, regBase+nEq);
89752      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
89753      if( zAff ){
89754        if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
89755          /* Since the comparison is to be performed with no conversions
89756          ** applied to the operands, set the affinity to apply to pRight to
89757          ** SQLITE_AFF_NONE.  */
89758          zAff[nConstraint] = SQLITE_AFF_NONE;
89759        }
89760        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
89761          zAff[nConstraint] = SQLITE_AFF_NONE;
89762        }
89763      }
89764      codeApplyAffinity(pParse, regBase, nEq+1, zAff);
89765      nConstraint++;
89766    }
89767    sqlite3DbFree(pParse->db, zAff);
89768
89769    /* Top of the loop body */
89770    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
89771
89772    /* Check if the index cursor is past the end of the range. */
89773    op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
89774    testcase( op==OP_Noop );
89775    testcase( op==OP_IdxGE );
89776    testcase( op==OP_IdxLT );
89777    if( op!=OP_Noop ){
89778      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
89779      sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
89780    }
89781
89782    /* If there are inequality constraints, check that the value
89783    ** of the table column that the inequality contrains is not NULL.
89784    ** If it is, jump to the next iteration of the loop.
89785    */
89786    r1 = sqlite3GetTempReg(pParse);
89787    testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
89788    testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
89789    if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
89790      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
89791      sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
89792    }
89793    sqlite3ReleaseTempReg(pParse, r1);
89794
89795    /* Seek the table cursor, if required */
89796    disableTerm(pLevel, pRangeStart);
89797    disableTerm(pLevel, pRangeEnd);
89798    if( !omitTable ){
89799      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
89800      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
89801      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
89802      sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
89803    }
89804
89805    /* Record the instruction used to terminate the loop. Disable
89806    ** WHERE clause terms made redundant by the index range scan.
89807    */
89808    pLevel->op = bRev ? OP_Prev : OP_Next;
89809    pLevel->p1 = iIdxCur;
89810  }else
89811
89812#ifndef SQLITE_OMIT_OR_OPTIMIZATION
89813  if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
89814    /* Case 4:  Two or more separately indexed terms connected by OR
89815    **
89816    ** Example:
89817    **
89818    **   CREATE TABLE t1(a,b,c,d);
89819    **   CREATE INDEX i1 ON t1(a);
89820    **   CREATE INDEX i2 ON t1(b);
89821    **   CREATE INDEX i3 ON t1(c);
89822    **
89823    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
89824    **
89825    ** In the example, there are three indexed terms connected by OR.
89826    ** The top of the loop looks like this:
89827    **
89828    **          Null       1                # Zero the rowset in reg 1
89829    **
89830    ** Then, for each indexed term, the following. The arguments to
89831    ** RowSetTest are such that the rowid of the current row is inserted
89832    ** into the RowSet. If it is already present, control skips the
89833    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
89834    **
89835    **        sqlite3WhereBegin(<term>)
89836    **          RowSetTest                  # Insert rowid into rowset
89837    **          Gosub      2 A
89838    **        sqlite3WhereEnd()
89839    **
89840    ** Following the above, code to terminate the loop. Label A, the target
89841    ** of the Gosub above, jumps to the instruction right after the Goto.
89842    **
89843    **          Null       1                # Zero the rowset in reg 1
89844    **          Goto       B                # The loop is finished.
89845    **
89846    **       A: <loop body>                 # Return data, whatever.
89847    **
89848    **          Return     2                # Jump back to the Gosub
89849    **
89850    **       B: <after the loop>
89851    **
89852    */
89853    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
89854    WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
89855    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
89856
89857    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
89858    int regRowset = 0;                        /* Register for RowSet object */
89859    int regRowid = 0;                         /* Register holding rowid */
89860    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
89861    int iRetInit;                             /* Address of regReturn init */
89862    int untestedTerms = 0;             /* Some terms not completely tested */
89863    int ii;
89864
89865    pTerm = pLevel->plan.u.pTerm;
89866    assert( pTerm!=0 );
89867    assert( pTerm->eOperator==WO_OR );
89868    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
89869    pOrWc = &pTerm->u.pOrInfo->wc;
89870    pFinal = &pOrWc->a[pOrWc->nTerm-1];
89871    pLevel->op = OP_Return;
89872    pLevel->p1 = regReturn;
89873
89874    /* Set up a new SrcList ni pOrTab containing the table being scanned
89875    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
89876    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
89877    */
89878    if( pWInfo->nLevel>1 ){
89879      int nNotReady;                 /* The number of notReady tables */
89880      struct SrcList_item *origSrc;     /* Original list of tables */
89881      nNotReady = pWInfo->nLevel - iLevel - 1;
89882      pOrTab = sqlite3StackAllocRaw(pParse->db,
89883                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
89884      if( pOrTab==0 ) return notReady;
89885      pOrTab->nAlloc = (i16)(nNotReady + 1);
89886      pOrTab->nSrc = pOrTab->nAlloc;
89887      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
89888      origSrc = pWInfo->pTabList->a;
89889      for(k=1; k<=nNotReady; k++){
89890        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
89891      }
89892    }else{
89893      pOrTab = pWInfo->pTabList;
89894    }
89895
89896    /* Initialize the rowset register to contain NULL. An SQL NULL is
89897    ** equivalent to an empty rowset.
89898    **
89899    ** Also initialize regReturn to contain the address of the instruction
89900    ** immediately following the OP_Return at the bottom of the loop. This
89901    ** is required in a few obscure LEFT JOIN cases where control jumps
89902    ** over the top of the loop into the body of it. In this case the
89903    ** correct response for the end-of-loop code (the OP_Return) is to
89904    ** fall through to the next instruction, just as an OP_Next does if
89905    ** called on an uninitialized cursor.
89906    */
89907    if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
89908      regRowset = ++pParse->nMem;
89909      regRowid = ++pParse->nMem;
89910      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
89911    }
89912    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
89913
89914    for(ii=0; ii<pOrWc->nTerm; ii++){
89915      WhereTerm *pOrTerm = &pOrWc->a[ii];
89916      if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
89917        WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
89918        /* Loop through table entries that match term pOrTerm. */
89919        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
89920                        WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
89921                        WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
89922        if( pSubWInfo ){
89923          if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
89924            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
89925            int r;
89926            r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
89927                                         regRowid);
89928            sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
89929                                 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
89930          }
89931          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
89932
89933          /* The pSubWInfo->untestedTerms flag means that this OR term
89934          ** contained one or more AND term from a notReady table.  The
89935          ** terms from the notReady table could not be tested and will
89936          ** need to be tested later.
89937          */
89938          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
89939
89940          /* Finish the loop through table entries that match term pOrTerm. */
89941          sqlite3WhereEnd(pSubWInfo);
89942        }
89943      }
89944    }
89945    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
89946    sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
89947    sqlite3VdbeResolveLabel(v, iLoopBody);
89948
89949    if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
89950    if( !untestedTerms ) disableTerm(pLevel, pTerm);
89951  }else
89952#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
89953
89954  {
89955    /* Case 5:  There is no usable index.  We must do a complete
89956    **          scan of the entire table.
89957    */
89958    static const u8 aStep[] = { OP_Next, OP_Prev };
89959    static const u8 aStart[] = { OP_Rewind, OP_Last };
89960    assert( bRev==0 || bRev==1 );
89961    assert( omitTable==0 );
89962    pLevel->op = aStep[bRev];
89963    pLevel->p1 = iCur;
89964    pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
89965    pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
89966  }
89967  notReady &= ~getMask(pWC->pMaskSet, iCur);
89968
89969  /* Insert code to test every subexpression that can be completely
89970  ** computed using the current set of tables.
89971  */
89972  k = 0;
89973  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
89974    Expr *pE;
89975    testcase( pTerm->wtFlags & TERM_VIRTUAL );
89976    testcase( pTerm->wtFlags & TERM_CODED );
89977    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
89978    if( (pTerm->prereqAll & notReady)!=0 ){
89979      testcase( pWInfo->untestedTerms==0
89980               && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
89981      pWInfo->untestedTerms = 1;
89982      continue;
89983    }
89984    pE = pTerm->pExpr;
89985    assert( pE!=0 );
89986    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
89987      continue;
89988    }
89989    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
89990    k = 1;
89991    pTerm->wtFlags |= TERM_CODED;
89992  }
89993
89994  /* For a LEFT OUTER JOIN, generate code that will record the fact that
89995  ** at least one row of the right table has matched the left table.
89996  */
89997  if( pLevel->iLeftJoin ){
89998    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
89999    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
90000    VdbeComment((v, "record LEFT JOIN hit"));
90001    sqlite3ExprCacheClear(pParse);
90002    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
90003      testcase( pTerm->wtFlags & TERM_VIRTUAL );
90004      testcase( pTerm->wtFlags & TERM_CODED );
90005      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
90006      if( (pTerm->prereqAll & notReady)!=0 ){
90007        assert( pWInfo->untestedTerms );
90008        continue;
90009      }
90010      assert( pTerm->pExpr );
90011      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
90012      pTerm->wtFlags |= TERM_CODED;
90013    }
90014  }
90015  sqlite3ReleaseTempReg(pParse, iReleaseReg);
90016
90017  return notReady;
90018}
90019
90020#if defined(SQLITE_TEST)
90021/*
90022** The following variable holds a text description of query plan generated
90023** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
90024** overwrites the previous.  This information is used for testing and
90025** analysis only.
90026*/
90027SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
90028static int nQPlan = 0;              /* Next free slow in _query_plan[] */
90029
90030#endif /* SQLITE_TEST */
90031
90032
90033/*
90034** Free a WhereInfo structure
90035*/
90036static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
90037  if( pWInfo ){
90038    int i;
90039    for(i=0; i<pWInfo->nLevel; i++){
90040      sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
90041      if( pInfo ){
90042        /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
90043        if( pInfo->needToFreeIdxStr ){
90044          sqlite3_free(pInfo->idxStr);
90045        }
90046        sqlite3DbFree(db, pInfo);
90047      }
90048    }
90049    whereClauseClear(pWInfo->pWC);
90050    sqlite3DbFree(db, pWInfo);
90051  }
90052}
90053
90054
90055/*
90056** Generate the beginning of the loop used for WHERE clause processing.
90057** The return value is a pointer to an opaque structure that contains
90058** information needed to terminate the loop.  Later, the calling routine
90059** should invoke sqlite3WhereEnd() with the return value of this function
90060** in order to complete the WHERE clause processing.
90061**
90062** If an error occurs, this routine returns NULL.
90063**
90064** The basic idea is to do a nested loop, one loop for each table in
90065** the FROM clause of a select.  (INSERT and UPDATE statements are the
90066** same as a SELECT with only a single table in the FROM clause.)  For
90067** example, if the SQL is this:
90068**
90069**       SELECT * FROM t1, t2, t3 WHERE ...;
90070**
90071** Then the code generated is conceptually like the following:
90072**
90073**      foreach row1 in t1 do       \    Code generated
90074**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
90075**          foreach row3 in t3 do   /
90076**            ...
90077**          end                     \    Code generated
90078**        end                        |-- by sqlite3WhereEnd()
90079**      end                         /
90080**
90081** Note that the loops might not be nested in the order in which they
90082** appear in the FROM clause if a different order is better able to make
90083** use of indices.  Note also that when the IN operator appears in
90084** the WHERE clause, it might result in additional nested loops for
90085** scanning through all values on the right-hand side of the IN.
90086**
90087** There are Btree cursors associated with each table.  t1 uses cursor
90088** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
90089** And so forth.  This routine generates code to open those VDBE cursors
90090** and sqlite3WhereEnd() generates the code to close them.
90091**
90092** The code that sqlite3WhereBegin() generates leaves the cursors named
90093** in pTabList pointing at their appropriate entries.  The [...] code
90094** can use OP_Column and OP_Rowid opcodes on these cursors to extract
90095** data from the various tables of the loop.
90096**
90097** If the WHERE clause is empty, the foreach loops must each scan their
90098** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
90099** the tables have indices and there are terms in the WHERE clause that
90100** refer to those indices, a complete table scan can be avoided and the
90101** code will run much faster.  Most of the work of this routine is checking
90102** to see if there are indices that can be used to speed up the loop.
90103**
90104** Terms of the WHERE clause are also used to limit which rows actually
90105** make it to the "..." in the middle of the loop.  After each "foreach",
90106** terms of the WHERE clause that use only terms in that loop and outer
90107** loops are evaluated and if false a jump is made around all subsequent
90108** inner loops (or around the "..." if the test occurs within the inner-
90109** most loop)
90110**
90111** OUTER JOINS
90112**
90113** An outer join of tables t1 and t2 is conceptally coded as follows:
90114**
90115**    foreach row1 in t1 do
90116**      flag = 0
90117**      foreach row2 in t2 do
90118**        start:
90119**          ...
90120**          flag = 1
90121**      end
90122**      if flag==0 then
90123**        move the row2 cursor to a null row
90124**        goto start
90125**      fi
90126**    end
90127**
90128** ORDER BY CLAUSE PROCESSING
90129**
90130** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
90131** if there is one.  If there is no ORDER BY clause or if this routine
90132** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
90133**
90134** If an index can be used so that the natural output order of the table
90135** scan is correct for the ORDER BY clause, then that index is used and
90136** *ppOrderBy is set to NULL.  This is an optimization that prevents an
90137** unnecessary sort of the result set if an index appropriate for the
90138** ORDER BY clause already exists.
90139**
90140** If the where clause loops cannot be arranged to provide the correct
90141** output order, then the *ppOrderBy is unchanged.
90142*/
90143SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
90144  Parse *pParse,        /* The parser context */
90145  SrcList *pTabList,    /* A list of all tables to be scanned */
90146  Expr *pWhere,         /* The WHERE clause */
90147  ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
90148  u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
90149){
90150  int i;                     /* Loop counter */
90151  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
90152  int nTabList;              /* Number of elements in pTabList */
90153  WhereInfo *pWInfo;         /* Will become the return value of this function */
90154  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
90155  Bitmask notReady;          /* Cursors that are not yet positioned */
90156  WhereMaskSet *pMaskSet;    /* The expression mask set */
90157  WhereClause *pWC;               /* Decomposition of the WHERE clause */
90158  struct SrcList_item *pTabItem;  /* A single entry from pTabList */
90159  WhereLevel *pLevel;             /* A single level in the pWInfo list */
90160  int iFrom;                      /* First unused FROM clause element */
90161  int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
90162  sqlite3 *db;               /* Database connection */
90163
90164  /* The number of tables in the FROM clause is limited by the number of
90165  ** bits in a Bitmask
90166  */
90167  if( pTabList->nSrc>BMS ){
90168    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
90169    return 0;
90170  }
90171
90172  /* This function normally generates a nested loop for all tables in
90173  ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
90174  ** only generate code for the first table in pTabList and assume that
90175  ** any cursors associated with subsequent tables are uninitialized.
90176  */
90177  nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
90178
90179  /* Allocate and initialize the WhereInfo structure that will become the
90180  ** return value. A single allocation is used to store the WhereInfo
90181  ** struct, the contents of WhereInfo.a[], the WhereClause structure
90182  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
90183  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
90184  ** some architectures. Hence the ROUND8() below.
90185  */
90186  db = pParse->db;
90187  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
90188  pWInfo = sqlite3DbMallocZero(db,
90189      nByteWInfo +
90190      sizeof(WhereClause) +
90191      sizeof(WhereMaskSet)
90192  );
90193  if( db->mallocFailed ){
90194    goto whereBeginError;
90195  }
90196  pWInfo->nLevel = nTabList;
90197  pWInfo->pParse = pParse;
90198  pWInfo->pTabList = pTabList;
90199  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
90200  pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
90201  pWInfo->wctrlFlags = wctrlFlags;
90202  pMaskSet = (WhereMaskSet*)&pWC[1];
90203
90204  /* Split the WHERE clause into separate subexpressions where each
90205  ** subexpression is separated by an AND operator.
90206  */
90207  initMaskSet(pMaskSet);
90208  whereClauseInit(pWC, pParse, pMaskSet);
90209  sqlite3ExprCodeConstants(pParse, pWhere);
90210  whereSplit(pWC, pWhere, TK_AND);
90211
90212  /* Special case: a WHERE clause that is constant.  Evaluate the
90213  ** expression and either jump over all of the code or fall thru.
90214  */
90215  if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
90216    sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
90217    pWhere = 0;
90218  }
90219
90220  /* Assign a bit from the bitmask to every term in the FROM clause.
90221  **
90222  ** When assigning bitmask values to FROM clause cursors, it must be
90223  ** the case that if X is the bitmask for the N-th FROM clause term then
90224  ** the bitmask for all FROM clause terms to the left of the N-th term
90225  ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
90226  ** its Expr.iRightJoinTable value to find the bitmask of the right table
90227  ** of the join.  Subtracting one from the right table bitmask gives a
90228  ** bitmask for all tables to the left of the join.  Knowing the bitmask
90229  ** for all tables to the left of a left join is important.  Ticket #3015.
90230  **
90231  ** Configure the WhereClause.vmask variable so that bits that correspond
90232  ** to virtual table cursors are set. This is used to selectively disable
90233  ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
90234  ** with virtual tables.
90235  **
90236  ** Note that bitmasks are created for all pTabList->nSrc tables in
90237  ** pTabList, not just the first nTabList tables.  nTabList is normally
90238  ** equal to pTabList->nSrc but might be shortened to 1 if the
90239  ** WHERE_ONETABLE_ONLY flag is set.
90240  */
90241  assert( pWC->vmask==0 && pMaskSet->n==0 );
90242  for(i=0; i<pTabList->nSrc; i++){
90243    createMask(pMaskSet, pTabList->a[i].iCursor);
90244#ifndef SQLITE_OMIT_VIRTUALTABLE
90245    if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
90246      pWC->vmask |= ((Bitmask)1 << i);
90247    }
90248#endif
90249  }
90250#ifndef NDEBUG
90251  {
90252    Bitmask toTheLeft = 0;
90253    for(i=0; i<pTabList->nSrc; i++){
90254      Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
90255      assert( (m-1)==toTheLeft );
90256      toTheLeft |= m;
90257    }
90258  }
90259#endif
90260
90261  /* Analyze all of the subexpressions.  Note that exprAnalyze() might
90262  ** add new virtual terms onto the end of the WHERE clause.  We do not
90263  ** want to analyze these virtual terms, so start analyzing at the end
90264  ** and work forward so that the added virtual terms are never processed.
90265  */
90266  exprAnalyzeAll(pTabList, pWC);
90267  if( db->mallocFailed ){
90268    goto whereBeginError;
90269  }
90270
90271  /* Chose the best index to use for each table in the FROM clause.
90272  **
90273  ** This loop fills in the following fields:
90274  **
90275  **   pWInfo->a[].pIdx      The index to use for this level of the loop.
90276  **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
90277  **   pWInfo->a[].nEq       The number of == and IN constraints
90278  **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
90279  **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
90280  **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
90281  **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
90282  **
90283  ** This loop also figures out the nesting order of tables in the FROM
90284  ** clause.
90285  */
90286  notReady = ~(Bitmask)0;
90287  pTabItem = pTabList->a;
90288  pLevel = pWInfo->a;
90289  andFlags = ~0;
90290  WHERETRACE(("*** Optimizer Start ***\n"));
90291  for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
90292    WhereCost bestPlan;         /* Most efficient plan seen so far */
90293    Index *pIdx;                /* Index for FROM table at pTabItem */
90294    int j;                      /* For looping over FROM tables */
90295    int bestJ = -1;             /* The value of j */
90296    Bitmask m;                  /* Bitmask value for j or bestJ */
90297    int isOptimal;              /* Iterator for optimal/non-optimal search */
90298
90299    memset(&bestPlan, 0, sizeof(bestPlan));
90300    bestPlan.rCost = SQLITE_BIG_DBL;
90301
90302    /* Loop through the remaining entries in the FROM clause to find the
90303    ** next nested loop. The FROM clause entries may be iterated through
90304    ** either once or twice.
90305    **
90306    ** The first iteration, which is always performed, searches for the
90307    ** FROM clause entry that permits the lowest-cost, "optimal" scan. In
90308    ** this context an optimal scan is one that uses the same strategy
90309    ** for the given FROM clause entry as would be selected if the entry
90310    ** were used as the innermost nested loop.  In other words, a table
90311    ** is chosen such that the cost of running that table cannot be reduced
90312    ** by waiting for other tables to run first.
90313    **
90314    ** The second iteration is only performed if no optimal scan strategies
90315    ** were found by the first. This iteration is used to search for the
90316    ** lowest cost scan overall.
90317    **
90318    ** Previous versions of SQLite performed only the second iteration -
90319    ** the next outermost loop was always that with the lowest overall
90320    ** cost. However, this meant that SQLite could select the wrong plan
90321    ** for scripts such as the following:
90322    **
90323    **   CREATE TABLE t1(a, b);
90324    **   CREATE TABLE t2(c, d);
90325    **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
90326    **
90327    ** The best strategy is to iterate through table t1 first. However it
90328    ** is not possible to determine this with a simple greedy algorithm.
90329    ** However, since the cost of a linear scan through table t2 is the same
90330    ** as the cost of a linear scan through table t1, a simple greedy
90331    ** algorithm may choose to use t2 for the outer loop, which is a much
90332    ** costlier approach.
90333    */
90334    for(isOptimal=1; isOptimal>=0 && bestJ<0; isOptimal--){
90335      Bitmask mask = (isOptimal ? 0 : notReady);
90336      assert( (nTabList-iFrom)>1 || isOptimal );
90337      for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
90338        int doNotReorder;    /* True if this table should not be reordered */
90339        WhereCost sCost;     /* Cost information from best[Virtual]Index() */
90340        ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
90341
90342        doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
90343        if( j!=iFrom && doNotReorder ) break;
90344        m = getMask(pMaskSet, pTabItem->iCursor);
90345        if( (m & notReady)==0 ){
90346          if( j==iFrom ) iFrom++;
90347          continue;
90348        }
90349        pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
90350
90351        assert( pTabItem->pTab );
90352#ifndef SQLITE_OMIT_VIRTUALTABLE
90353        if( IsVirtual(pTabItem->pTab) ){
90354          sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
90355          bestVirtualIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost, pp);
90356        }else
90357#endif
90358        {
90359          bestBtreeIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost);
90360        }
90361        assert( isOptimal || (sCost.used&notReady)==0 );
90362
90363        if( (sCost.used&notReady)==0
90364         && (j==iFrom || sCost.rCost<bestPlan.rCost)
90365        ){
90366          bestPlan = sCost;
90367          bestJ = j;
90368        }
90369        if( doNotReorder ) break;
90370      }
90371    }
90372    assert( bestJ>=0 );
90373    assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
90374    WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
90375           pLevel-pWInfo->a));
90376    if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
90377      *ppOrderBy = 0;
90378    }
90379    andFlags &= bestPlan.plan.wsFlags;
90380    pLevel->plan = bestPlan.plan;
90381    if( bestPlan.plan.wsFlags & WHERE_INDEXED ){
90382      pLevel->iIdxCur = pParse->nTab++;
90383    }else{
90384      pLevel->iIdxCur = -1;
90385    }
90386    notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
90387    pLevel->iFrom = (u8)bestJ;
90388
90389    /* Check that if the table scanned by this loop iteration had an
90390    ** INDEXED BY clause attached to it, that the named index is being
90391    ** used for the scan. If not, then query compilation has failed.
90392    ** Return an error.
90393    */
90394    pIdx = pTabList->a[bestJ].pIndex;
90395    if( pIdx ){
90396      if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
90397        sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
90398        goto whereBeginError;
90399      }else{
90400        /* If an INDEXED BY clause is used, the bestIndex() function is
90401        ** guaranteed to find the index specified in the INDEXED BY clause
90402        ** if it find an index at all. */
90403        assert( bestPlan.plan.u.pIdx==pIdx );
90404      }
90405    }
90406  }
90407  WHERETRACE(("*** Optimizer Finished ***\n"));
90408  if( pParse->nErr || db->mallocFailed ){
90409    goto whereBeginError;
90410  }
90411
90412  /* If the total query only selects a single row, then the ORDER BY
90413  ** clause is irrelevant.
90414  */
90415  if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
90416    *ppOrderBy = 0;
90417  }
90418
90419  /* If the caller is an UPDATE or DELETE statement that is requesting
90420  ** to use a one-pass algorithm, determine if this is appropriate.
90421  ** The one-pass algorithm only works if the WHERE clause constraints
90422  ** the statement to update a single row.
90423  */
90424  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
90425  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
90426    pWInfo->okOnePass = 1;
90427    pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
90428  }
90429
90430  /* Open all tables in the pTabList and any indices selected for
90431  ** searching those tables.
90432  */
90433  sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
90434  for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
90435    Table *pTab;     /* Table to open */
90436    int iDb;         /* Index of database containing table/index */
90437
90438#ifndef SQLITE_OMIT_EXPLAIN
90439    if( pParse->explain==2 ){
90440      char *zMsg;
90441      struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
90442      zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
90443      if( pItem->zAlias ){
90444        zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
90445      }
90446      if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90447        zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
90448           zMsg, pLevel->plan.u.pIdx->zName);
90449      }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
90450        zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
90451      }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
90452        zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
90453      }
90454#ifndef SQLITE_OMIT_VIRTUALTABLE
90455      else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
90456        sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
90457        zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
90458                    pVtabIdx->idxNum, pVtabIdx->idxStr);
90459      }
90460#endif
90461      if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
90462        zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
90463      }
90464      sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
90465    }
90466#endif /* SQLITE_OMIT_EXPLAIN */
90467    pTabItem = &pTabList->a[pLevel->iFrom];
90468    pTab = pTabItem->pTab;
90469    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
90470    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
90471#ifndef SQLITE_OMIT_VIRTUALTABLE
90472    if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
90473      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
90474      int iCur = pTabItem->iCursor;
90475      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
90476    }else
90477#endif
90478    if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
90479         && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
90480      int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
90481      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
90482      if( !pWInfo->okOnePass && pTab->nCol<BMS ){
90483        Bitmask b = pTabItem->colUsed;
90484        int n = 0;
90485        for(; b; b=b>>1, n++){}
90486        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
90487                            SQLITE_INT_TO_PTR(n), P4_INT32);
90488        assert( n<=pTab->nCol );
90489      }
90490    }else{
90491      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
90492    }
90493    pLevel->iTabCur = pTabItem->iCursor;
90494    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90495      Index *pIx = pLevel->plan.u.pIdx;
90496      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
90497      int iIdxCur = pLevel->iIdxCur;
90498      assert( pIx->pSchema==pTab->pSchema );
90499      assert( iIdxCur>=0 );
90500      sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
90501                        (char*)pKey, P4_KEYINFO_HANDOFF);
90502      VdbeComment((v, "%s", pIx->zName));
90503    }
90504    sqlite3CodeVerifySchema(pParse, iDb);
90505  }
90506  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
90507
90508  /* Generate the code to do the search.  Each iteration of the for
90509  ** loop below generates code for a single nested loop of the VM
90510  ** program.
90511  */
90512  notReady = ~(Bitmask)0;
90513  for(i=0; i<nTabList; i++){
90514    notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
90515    pWInfo->iContinue = pWInfo->a[i].addrCont;
90516  }
90517
90518#ifdef SQLITE_TEST  /* For testing and debugging use only */
90519  /* Record in the query plan information about the current table
90520  ** and the index used to access it (if any).  If the table itself
90521  ** is not used, its name is just '{}'.  If no index is used
90522  ** the index is listed as "{}".  If the primary key is used the
90523  ** index name is '*'.
90524  */
90525  for(i=0; i<nTabList; i++){
90526    char *z;
90527    int n;
90528    pLevel = &pWInfo->a[i];
90529    pTabItem = &pTabList->a[pLevel->iFrom];
90530    z = pTabItem->zAlias;
90531    if( z==0 ) z = pTabItem->pTab->zName;
90532    n = sqlite3Strlen30(z);
90533    if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
90534      if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
90535        memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
90536        nQPlan += 2;
90537      }else{
90538        memcpy(&sqlite3_query_plan[nQPlan], z, n);
90539        nQPlan += n;
90540      }
90541      sqlite3_query_plan[nQPlan++] = ' ';
90542    }
90543    testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
90544    testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
90545    if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
90546      memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
90547      nQPlan += 2;
90548    }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90549      n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
90550      if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
90551        memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
90552        nQPlan += n;
90553        sqlite3_query_plan[nQPlan++] = ' ';
90554      }
90555    }else{
90556      memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
90557      nQPlan += 3;
90558    }
90559  }
90560  while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
90561    sqlite3_query_plan[--nQPlan] = 0;
90562  }
90563  sqlite3_query_plan[nQPlan] = 0;
90564  nQPlan = 0;
90565#endif /* SQLITE_TEST // Testing and debugging use only */
90566
90567  /* Record the continuation address in the WhereInfo structure.  Then
90568  ** clean up and return.
90569  */
90570  return pWInfo;
90571
90572  /* Jump here if malloc fails */
90573whereBeginError:
90574  whereInfoFree(db, pWInfo);
90575  return 0;
90576}
90577
90578/*
90579** Generate the end of the WHERE loop.  See comments on
90580** sqlite3WhereBegin() for additional information.
90581*/
90582SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
90583  Parse *pParse = pWInfo->pParse;
90584  Vdbe *v = pParse->pVdbe;
90585  int i;
90586  WhereLevel *pLevel;
90587  SrcList *pTabList = pWInfo->pTabList;
90588  sqlite3 *db = pParse->db;
90589
90590  /* Generate loop termination code.
90591  */
90592  sqlite3ExprCacheClear(pParse);
90593  for(i=pWInfo->nLevel-1; i>=0; i--){
90594    pLevel = &pWInfo->a[i];
90595    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
90596    if( pLevel->op!=OP_Noop ){
90597      sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
90598      sqlite3VdbeChangeP5(v, pLevel->p5);
90599    }
90600    if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
90601      struct InLoop *pIn;
90602      int j;
90603      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
90604      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
90605        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
90606        sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
90607        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
90608      }
90609      sqlite3DbFree(db, pLevel->u.in.aInLoop);
90610    }
90611    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
90612    if( pLevel->iLeftJoin ){
90613      int addr;
90614      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
90615      assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
90616           || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
90617      if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
90618        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
90619      }
90620      if( pLevel->iIdxCur>=0 ){
90621        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
90622      }
90623      if( pLevel->op==OP_Return ){
90624        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
90625      }else{
90626        sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
90627      }
90628      sqlite3VdbeJumpHere(v, addr);
90629    }
90630  }
90631
90632  /* The "break" point is here, just past the end of the outer loop.
90633  ** Set it.
90634  */
90635  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
90636
90637  /* Close all of the cursors that were opened by sqlite3WhereBegin.
90638  */
90639  assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
90640  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
90641    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
90642    Table *pTab = pTabItem->pTab;
90643    assert( pTab!=0 );
90644    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
90645    if( (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0 ){
90646      if( !pWInfo->okOnePass && (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
90647        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
90648      }
90649      if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90650        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
90651      }
90652    }
90653
90654    /* If this scan uses an index, make code substitutions to read data
90655    ** from the index in preference to the table. Sometimes, this means
90656    ** the table need never be read from. This is a performance boost,
90657    ** as the vdbe level waits until the table is read before actually
90658    ** seeking the table cursor to the record corresponding to the current
90659    ** position in the index.
90660    **
90661    ** Calls to the code generator in between sqlite3WhereBegin and
90662    ** sqlite3WhereEnd will have created code that references the table
90663    ** directly.  This loop scans all that code looking for opcodes
90664    ** that reference the table and converts them into opcodes that
90665    ** reference the index.
90666    */
90667    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
90668      int k, j, last;
90669      VdbeOp *pOp;
90670      Index *pIdx = pLevel->plan.u.pIdx;
90671
90672      assert( pIdx!=0 );
90673      pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
90674      last = sqlite3VdbeCurrentAddr(v);
90675      for(k=pWInfo->iTop; k<last; k++, pOp++){
90676        if( pOp->p1!=pLevel->iTabCur ) continue;
90677        if( pOp->opcode==OP_Column ){
90678          for(j=0; j<pIdx->nColumn; j++){
90679            if( pOp->p2==pIdx->aiColumn[j] ){
90680              pOp->p2 = j;
90681              pOp->p1 = pLevel->iIdxCur;
90682              break;
90683            }
90684          }
90685          assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
90686               || j<pIdx->nColumn );
90687        }else if( pOp->opcode==OP_Rowid ){
90688          pOp->p1 = pLevel->iIdxCur;
90689          pOp->opcode = OP_IdxRowid;
90690        }
90691      }
90692    }
90693  }
90694
90695  /* Final cleanup
90696  */
90697  whereInfoFree(db, pWInfo);
90698  return;
90699}
90700
90701/************** End of where.c ***********************************************/
90702/************** Begin file parse.c *******************************************/
90703/* Driver template for the LEMON parser generator.
90704** The author disclaims copyright to this source code.
90705**
90706** This version of "lempar.c" is modified, slightly, for use by SQLite.
90707** The only modifications are the addition of a couple of NEVER()
90708** macros to disable tests that are needed in the case of a general
90709** LALR(1) grammar but which are always false in the
90710** specific grammar used by SQLite.
90711*/
90712/* First off, code is included that follows the "include" declaration
90713** in the input grammar file. */
90714
90715
90716/*
90717** Disable all error recovery processing in the parser push-down
90718** automaton.
90719*/
90720#define YYNOERRORRECOVERY 1
90721
90722/*
90723** Make yytestcase() the same as testcase()
90724*/
90725#define yytestcase(X) testcase(X)
90726
90727/*
90728** An instance of this structure holds information about the
90729** LIMIT clause of a SELECT statement.
90730*/
90731struct LimitVal {
90732  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
90733  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
90734};
90735
90736/*
90737** An instance of this structure is used to store the LIKE,
90738** GLOB, NOT LIKE, and NOT GLOB operators.
90739*/
90740struct LikeOp {
90741  Token eOperator;  /* "like" or "glob" or "regexp" */
90742  int not;         /* True if the NOT keyword is present */
90743};
90744
90745/*
90746** An instance of the following structure describes the event of a
90747** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
90748** TK_DELETE, or TK_INSTEAD.  If the event is of the form
90749**
90750**      UPDATE ON (a,b,c)
90751**
90752** Then the "b" IdList records the list "a,b,c".
90753*/
90754struct TrigEvent { int a; IdList * b; };
90755
90756/*
90757** An instance of this structure holds the ATTACH key and the key type.
90758*/
90759struct AttachKey { int type;  Token key; };
90760
90761
90762  /* This is a utility routine used to set the ExprSpan.zStart and
90763  ** ExprSpan.zEnd values of pOut so that the span covers the complete
90764  ** range of text beginning with pStart and going to the end of pEnd.
90765  */
90766  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
90767    pOut->zStart = pStart->z;
90768    pOut->zEnd = &pEnd->z[pEnd->n];
90769  }
90770
90771  /* Construct a new Expr object from a single identifier.  Use the
90772  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
90773  ** that created the expression.
90774  */
90775  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
90776    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
90777    pOut->zStart = pValue->z;
90778    pOut->zEnd = &pValue->z[pValue->n];
90779  }
90780
90781  /* This routine constructs a binary expression node out of two ExprSpan
90782  ** objects and uses the result to populate a new ExprSpan object.
90783  */
90784  static void spanBinaryExpr(
90785    ExprSpan *pOut,     /* Write the result here */
90786    Parse *pParse,      /* The parsing context.  Errors accumulate here */
90787    int op,             /* The binary operation */
90788    ExprSpan *pLeft,    /* The left operand */
90789    ExprSpan *pRight    /* The right operand */
90790  ){
90791    pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
90792    pOut->zStart = pLeft->zStart;
90793    pOut->zEnd = pRight->zEnd;
90794  }
90795
90796  /* Construct an expression node for a unary postfix operator
90797  */
90798  static void spanUnaryPostfix(
90799    ExprSpan *pOut,        /* Write the new expression node here */
90800    Parse *pParse,         /* Parsing context to record errors */
90801    int op,                /* The operator */
90802    ExprSpan *pOperand,    /* The operand */
90803    Token *pPostOp         /* The operand token for setting the span */
90804  ){
90805    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
90806    pOut->zStart = pOperand->zStart;
90807    pOut->zEnd = &pPostOp->z[pPostOp->n];
90808  }
90809
90810  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
90811  ** unary TK_ISNULL or TK_NOTNULL expression. */
90812  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
90813    sqlite3 *db = pParse->db;
90814    if( db->mallocFailed==0 && pY->op==TK_NULL ){
90815      pA->op = (u8)op;
90816      sqlite3ExprDelete(db, pA->pRight);
90817      pA->pRight = 0;
90818    }
90819  }
90820
90821  /* Construct an expression node for a unary prefix operator
90822  */
90823  static void spanUnaryPrefix(
90824    ExprSpan *pOut,        /* Write the new expression node here */
90825    Parse *pParse,         /* Parsing context to record errors */
90826    int op,                /* The operator */
90827    ExprSpan *pOperand,    /* The operand */
90828    Token *pPreOp         /* The operand token for setting the span */
90829  ){
90830    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
90831    pOut->zStart = pPreOp->z;
90832    pOut->zEnd = pOperand->zEnd;
90833  }
90834/* Next is all token values, in a form suitable for use by makeheaders.
90835** This section will be null unless lemon is run with the -m switch.
90836*/
90837/*
90838** These constants (all generated automatically by the parser generator)
90839** specify the various kinds of tokens (terminals) that the parser
90840** understands.
90841**
90842** Each symbol here is a terminal symbol in the grammar.
90843*/
90844/* Make sure the INTERFACE macro is defined.
90845*/
90846#ifndef INTERFACE
90847# define INTERFACE 1
90848#endif
90849/* The next thing included is series of defines which control
90850** various aspects of the generated parser.
90851**    YYCODETYPE         is the data type used for storing terminal
90852**                       and nonterminal numbers.  "unsigned char" is
90853**                       used if there are fewer than 250 terminals
90854**                       and nonterminals.  "int" is used otherwise.
90855**    YYNOCODE           is a number of type YYCODETYPE which corresponds
90856**                       to no legal terminal or nonterminal number.  This
90857**                       number is used to fill in empty slots of the hash
90858**                       table.
90859**    YYFALLBACK         If defined, this indicates that one or more tokens
90860**                       have fall-back values which should be used if the
90861**                       original value of the token will not parse.
90862**    YYACTIONTYPE       is the data type used for storing terminal
90863**                       and nonterminal numbers.  "unsigned char" is
90864**                       used if there are fewer than 250 rules and
90865**                       states combined.  "int" is used otherwise.
90866**    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
90867**                       directly to the parser from the tokenizer.
90868**    YYMINORTYPE        is the data type used for all minor tokens.
90869**                       This is typically a union of many types, one of
90870**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
90871**                       for base tokens is called "yy0".
90872**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
90873**                       zero the stack is dynamically sized using realloc()
90874**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
90875**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
90876**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
90877**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
90878**    YYNSTATE           the combined number of states.
90879**    YYNRULE            the number of rules in the grammar
90880**    YYERRORSYMBOL      is the code number of the error symbol.  If not
90881**                       defined, then do no error processing.
90882*/
90883#define YYCODETYPE unsigned char
90884#define YYNOCODE 254
90885#define YYACTIONTYPE unsigned short int
90886#define YYWILDCARD 67
90887#define sqlite3ParserTOKENTYPE Token
90888typedef union {
90889  int yyinit;
90890  sqlite3ParserTOKENTYPE yy0;
90891  Select* yy3;
90892  ExprList* yy14;
90893  SrcList* yy65;
90894  struct LikeOp yy96;
90895  Expr* yy132;
90896  u8 yy186;
90897  int yy328;
90898  ExprSpan yy346;
90899  struct TrigEvent yy378;
90900  IdList* yy408;
90901  struct {int value; int mask;} yy429;
90902  TriggerStep* yy473;
90903  struct LimitVal yy476;
90904} YYMINORTYPE;
90905#ifndef YYSTACKDEPTH
90906#define YYSTACKDEPTH 100
90907#endif
90908#define sqlite3ParserARG_SDECL Parse *pParse;
90909#define sqlite3ParserARG_PDECL ,Parse *pParse
90910#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
90911#define sqlite3ParserARG_STORE yypParser->pParse = pParse
90912#define YYNSTATE 631
90913#define YYNRULE 330
90914#define YYFALLBACK 1
90915#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
90916#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
90917#define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
90918
90919/* The yyzerominor constant is used to initialize instances of
90920** YYMINORTYPE objects to zero. */
90921static const YYMINORTYPE yyzerominor = { 0 };
90922
90923/* Define the yytestcase() macro to be a no-op if is not already defined
90924** otherwise.
90925**
90926** Applications can choose to define yytestcase() in the %include section
90927** to a macro that can assist in verifying code coverage.  For production
90928** code the yytestcase() macro should be turned off.  But it is useful
90929** for testing.
90930*/
90931#ifndef yytestcase
90932# define yytestcase(X)
90933#endif
90934
90935
90936/* Next are the tables used to determine what action to take based on the
90937** current state and lookahead token.  These tables are used to implement
90938** functions that take a state number and lookahead value and return an
90939** action integer.
90940**
90941** Suppose the action integer is N.  Then the action is determined as
90942** follows
90943**
90944**   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
90945**                                      token onto the stack and goto state N.
90946**
90947**   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
90948**
90949**   N == YYNSTATE+YYNRULE              A syntax error has occurred.
90950**
90951**   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
90952**
90953**   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
90954**                                      slots in the yy_action[] table.
90955**
90956** The action table is constructed as a single large table named yy_action[].
90957** Given state S and lookahead X, the action is computed as
90958**
90959**      yy_action[ yy_shift_ofst[S] + X ]
90960**
90961** If the index value yy_shift_ofst[S]+X is out of range or if the value
90962** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
90963** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
90964** and that yy_default[S] should be used instead.
90965**
90966** The formula above is for computing the action when the lookahead is
90967** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
90968** a reduce action) then the yy_reduce_ofst[] array is used in place of
90969** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
90970** YY_SHIFT_USE_DFLT.
90971**
90972** The following are the tables generated in this section:
90973**
90974**  yy_action[]        A single table containing all actions.
90975**  yy_lookahead[]     A table containing the lookahead for each entry in
90976**                     yy_action.  Used to detect hash collisions.
90977**  yy_shift_ofst[]    For each state, the offset into yy_action for
90978**                     shifting terminals.
90979**  yy_reduce_ofst[]   For each state, the offset into yy_action for
90980**                     shifting non-terminals after a reduce.
90981**  yy_default[]       Default action for each state.
90982*/
90983#define YY_ACTTAB_COUNT (1543)
90984static const YYACTIONTYPE yy_action[] = {
90985 /*     0 */   313,   49,  556,   46,  147,  172,  628,  598,   55,   55,
90986 /*    10 */    55,   55,  302,   53,   53,   53,   53,   52,   52,   51,
90987 /*    20 */    51,   51,   50,  238,  603,   66,  624,  623,  604,  598,
90988 /*    30 */   591,  585,   48,   53,   53,   53,   53,   52,   52,   51,
90989 /*    40 */    51,   51,   50,  238,   51,   51,   51,   50,  238,   56,
90990 /*    50 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
90991 /*    60 */    55,   55,  609,   53,   53,   53,   53,   52,   52,   51,
90992 /*    70 */    51,   51,   50,  238,  313,  598,  672,  330,  411,  217,
90993 /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
90994 /*    90 */    50,  238,  330,  414,  621,  620,  166,  598,  673,  382,
90995 /*   100 */   379,  378,  602,   73,  591,  585,  307,  424,  166,   58,
90996 /*   110 */   377,  382,  379,  378,  516,  515,  624,  623,  254,  200,
90997 /*   120 */   199,  198,  377,   56,   57,   47,  583,  582,  584,  584,
90998 /*   130 */    54,   54,   55,   55,   55,   55,  581,   53,   53,   53,
90999 /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  270,
91000 /*   150 */   226,  422,  283,  133,  177,  139,  284,  385,  279,  384,
91001 /*   160 */   169,  197,  251,  282,  253,  226,  411,  275,  440,  167,
91002 /*   170 */   139,  284,  385,  279,  384,  169,  571,  236,  591,  585,
91003 /*   180 */   240,  414,  275,  622,  621,  620,  674,  437,  441,  442,
91004 /*   190 */   602,   88,  352,  266,  439,  268,  438,   56,   57,   47,
91005 /*   200 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
91006 /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
91007 /*   220 */    50,  238,  313,  471,   52,   52,   51,   51,   51,   50,
91008 /*   230 */   238,  234,  166,  491,  567,  382,  379,  378,    1,  440,
91009 /*   240 */   252,  176,  624,  623,  608,   67,  377,  513,  622,  443,
91010 /*   250 */   237,  577,  591,  585,  622,  172,  466,  598,  554,  441,
91011 /*   260 */   340,  409,  526,  580,  580,  349,  596,  553,  194,  482,
91012 /*   270 */   175,   56,   57,   47,  583,  582,  584,  584,   54,   54,
91013 /*   280 */    55,   55,   55,   55,  562,   53,   53,   53,   53,   52,
91014 /*   290 */    52,   51,   51,   51,   50,  238,  313,  594,  594,  594,
91015 /*   300 */   561,  578,  469,   65,  259,  351,  258,  411,  624,  623,
91016 /*   310 */   621,  620,  332,  576,  575,  240,  560,  568,  520,  411,
91017 /*   320 */   341,  237,  414,  624,  623,  598,  591,  585,  542,  519,
91018 /*   330 */   171,  602,   95,   68,  414,  624,  623,  624,  623,   38,
91019 /*   340 */   877,  506,  507,  602,   88,   56,   57,   47,  583,  582,
91020 /*   350 */   584,  584,   54,   54,   55,   55,   55,   55,  532,   53,
91021 /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
91022 /*   370 */   313,  411,  579,  398,  531,  237,  621,  620,  388,  625,
91023 /*   380 */   500,  206,  167,  396,  233,  312,  414,  387,  569,  492,
91024 /*   390 */   216,  621,  620,  566,  622,  602,   74,  533,  210,  491,
91025 /*   400 */   591,  585,  548,  621,  620,  621,  620,  300,  598,  466,
91026 /*   410 */   481,   67,  603,   35,  622,  601,  604,  547,    6,   56,
91027 /*   420 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
91028 /*   430 */    55,   55,  601,   53,   53,   53,   53,   52,   52,   51,
91029 /*   440 */    51,   51,   50,  238,  313,  411,  184,  409,  528,  580,
91030 /*   450 */   580,  551,  962,  186,  419,    2,  353,  259,  351,  258,
91031 /*   460 */   414,  409,  411,  580,  580,   44,  411,  544,  240,  602,
91032 /*   470 */    94,  190,    7,   62,  591,  585,  598,  414,  350,  607,
91033 /*   480 */   493,  414,  409,  317,  580,  580,  602,   95,  496,  565,
91034 /*   490 */   602,   80,  203,   56,   57,   47,  583,  582,  584,  584,
91035 /*   500 */    54,   54,   55,   55,   55,   55,  535,   53,   53,   53,
91036 /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  202,
91037 /*   520 */   564,  293,  511,   49,  562,   46,  147,  411,  394,  183,
91038 /*   530 */   563,  549,  505,  549,  174,  409,  322,  580,  580,   39,
91039 /*   540 */   561,   37,  414,  624,  623,  192,  473,  383,  591,  585,
91040 /*   550 */   474,  602,   80,  601,  504,  544,  560,  364,  402,  210,
91041 /*   560 */   421,  952,  361,  952,  365,  201,  144,   56,   57,   47,
91042 /*   570 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
91043 /*   580 */   559,   53,   53,   53,   53,   52,   52,   51,   51,   51,
91044 /*   590 */    50,  238,  313,  601,  232,  264,  272,  321,  374,  484,
91045 /*   600 */   510,  146,  342,  146,  328,  425,  485,  407,  576,  575,
91046 /*   610 */   622,  621,  620,   49,  168,   46,  147,  353,  546,  491,
91047 /*   620 */   204,  240,  591,  585,  421,  951,  549,  951,  549,  168,
91048 /*   630 */   429,   67,  390,  343,  622,  434,  307,  423,  338,  360,
91049 /*   640 */   391,   56,   57,   47,  583,  582,  584,  584,   54,   54,
91050 /*   650 */    55,   55,   55,   55,  601,   53,   53,   53,   53,   52,
91051 /*   660 */    52,   51,   51,   51,   50,  238,  313,   34,  318,  425,
91052 /*   670 */   237,   21,  359,  273,  411,  167,  411,  276,  411,  540,
91053 /*   680 */   411,  422,   13,  318,  619,  618,  617,  622,  275,  414,
91054 /*   690 */   336,  414,  622,  414,  622,  414,  591,  585,  602,   69,
91055 /*   700 */   602,   97,  602,  100,  602,   98,  631,  629,  334,  475,
91056 /*   710 */   475,  367,  319,  148,  327,   56,   57,   47,  583,  582,
91057 /*   720 */   584,  584,   54,   54,   55,   55,   55,   55,  411,   53,
91058 /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
91059 /*   740 */   313,  411,  331,  414,  411,   49,  276,   46,  147,  569,
91060 /*   750 */   406,  216,  602,  106,  573,  573,  414,  354,  524,  414,
91061 /*   760 */   411,  622,  411,  224,    4,  602,  104,  605,  602,  108,
91062 /*   770 */   591,  585,  622,   20,  375,  414,  167,  414,  215,  144,
91063 /*   780 */   470,  239,  167,  225,  602,  109,  602,  134,   18,   56,
91064 /*   790 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
91065 /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
91066 /*   810 */    51,   51,   50,  238,  313,  411,  276,  414,   12,  459,
91067 /*   820 */   276,  171,  411,   16,  223,  189,  602,  135,  354,  170,
91068 /*   830 */   414,  622,  630,    2,  411,  622,  540,  414,  143,  602,
91069 /*   840 */    61,  359,  132,  622,  591,  585,  602,  105,  458,  414,
91070 /*   850 */    23,  622,  446,  326,   23,  538,  622,  325,  602,  103,
91071 /*   860 */   427,  530,  309,   56,   57,   47,  583,  582,  584,  584,
91072 /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
91073 /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
91074 /*   890 */   264,  414,  411,  276,  359,  219,  157,  214,  357,  366,
91075 /*   900 */   602,   96,  522,  521,  414,  622,  358,  414,  622,  622,
91076 /*   910 */   411,  613,  612,  602,  102,  142,  602,   77,  591,  585,
91077 /*   920 */   529,  540,  231,  426,  308,  414,  622,  622,  468,  521,
91078 /*   930 */   324,  601,  257,  263,  602,   99,  622,   56,   45,   47,
91079 /*   940 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
91080 /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
91081 /*   960 */    50,  238,  313,  264,  264,  414,  411,  213,  209,  544,
91082 /*   970 */   544,  207,  611,   28,  602,  138,   50,  238,  622,  622,
91083 /*   980 */   381,  414,  503,  140,  323,  222,  274,  622,  590,  589,
91084 /*   990 */   602,  137,  591,  585,  629,  334,  606,   30,  622,  571,
91085 /*  1000 */   236,  601,  601,  130,  496,  601,  453,  451,  288,  286,
91086 /*  1010 */   587,  586,   57,   47,  583,  582,  584,  584,   54,   54,
91087 /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
91088 /*  1030 */    52,   51,   51,   51,   50,  238,  313,  588,  411,  414,
91089 /*  1040 */   411,  264,  410,  129,  595,  400,   27,  376,  602,  136,
91090 /*  1050 */   128,  165,  479,  414,  282,  414,  622,  622,  411,  622,
91091 /*  1060 */   622,  411,  602,   76,  602,   93,  591,  585,  188,  372,
91092 /*  1070 */   368,  125,  476,  414,  261,  160,  414,  171,  124,  472,
91093 /*  1080 */   123,   15,  602,   92,  450,  602,   75,   47,  583,  582,
91094 /*  1090 */   584,  584,   54,   54,   55,   55,   55,   55,  464,   53,
91095 /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
91096 /*  1110 */    43,  405,  264,    3,  558,  264,  545,  415,  623,  159,
91097 /*  1120 */   541,  158,  539,  278,   25,  461,  121,  622,  408,  622,
91098 /*  1130 */   622,  622,   24,   43,  405,  622,    3,  622,  622,  120,
91099 /*  1140 */   415,  623,   11,  456,  411,  156,  452,  403,  509,  277,
91100 /*  1150 */   118,  408,  489,  113,  205,  449,  271,  567,  221,  414,
91101 /*  1160 */   269,  267,  155,  622,  622,  111,  411,  622,  602,   95,
91102 /*  1170 */   403,  622,  411,  110,   10,  622,  622,   40,   41,  534,
91103 /*  1180 */   567,  414,   64,  264,   42,  413,  412,  414,  601,  596,
91104 /*  1190 */   602,   91,  445,  436,  150,  435,  602,   90,  622,  265,
91105 /*  1200 */    40,   41,  337,  242,  411,  191,  333,   42,  413,  412,
91106 /*  1210 */   398,  420,  596,  316,  622,  399,  260,  107,  230,  414,
91107 /*  1220 */   594,  594,  594,  593,  592,   14,  220,  411,  602,  101,
91108 /*  1230 */   240,  622,   43,  405,  362,    3,  149,  315,  626,  415,
91109 /*  1240 */   623,  127,  414,  594,  594,  594,  593,  592,   14,  622,
91110 /*  1250 */   408,  602,   89,  411,  181,   33,  405,  463,    3,  411,
91111 /*  1260 */   264,  462,  415,  623,  616,  615,  614,  355,  414,  403,
91112 /*  1270 */   417,  416,  622,  408,  414,  622,  622,  602,   87,  567,
91113 /*  1280 */   418,  627,  622,  602,   86,    8,  241,  180,  126,  255,
91114 /*  1290 */   600,  178,  403,  240,  208,  455,  395,  294,  444,   40,
91115 /*  1300 */    41,  297,  567,  248,  622,  296,   42,  413,  412,  247,
91116 /*  1310 */   622,  596,  244,  622,   30,   60,   31,  243,  430,  624,
91117 /*  1320 */   623,  292,   40,   41,  622,  295,  145,  622,  601,   42,
91118 /*  1330 */   413,  412,  622,  622,  596,  393,  622,  397,  599,   59,
91119 /*  1340 */   235,  622,  594,  594,  594,  593,  592,   14,  218,  291,
91120 /*  1350 */   622,   36,  344,  305,  304,  303,  179,  301,  411,  567,
91121 /*  1360 */   454,  557,  173,  185,  622,  594,  594,  594,  593,  592,
91122 /*  1370 */    14,  411,   29,  414,  151,  289,  246,  523,  411,  196,
91123 /*  1380 */   195,  335,  602,   85,  411,  245,  414,  526,  392,  543,
91124 /*  1390 */   411,  596,  287,  414,  285,  602,   72,  537,  153,  414,
91125 /*  1400 */   466,  411,  602,   71,  154,  414,  411,  152,  602,   84,
91126 /*  1410 */   386,  536,  329,  411,  602,   83,  414,  518,  280,  411,
91127 /*  1420 */   513,  414,  594,  594,  594,  602,   82,  517,  414,  311,
91128 /*  1430 */   602,   81,  411,  514,  414,  512,  131,  602,   70,  229,
91129 /*  1440 */   228,  227,  494,  602,   17,  411,  488,  414,  259,  346,
91130 /*  1450 */   249,  389,  487,  486,  314,  164,  602,   79,  310,  240,
91131 /*  1460 */   414,  373,  480,  163,  262,  371,  414,  162,  369,  602,
91132 /*  1470 */    78,  212,  478,   26,  477,  602,    9,  161,  467,  363,
91133 /*  1480 */   141,  122,  339,  187,  119,  457,  348,  117,  347,  116,
91134 /*  1490 */   115,  114,  448,  112,  182,  320,   22,  433,   19,  432,
91135 /*  1500 */   431,   63,  428,  610,  193,  298,  597,  574,  572,  404,
91136 /*  1510 */   555,  552,  290,  281,  510,  499,  498,  497,  495,  380,
91137 /*  1520 */   356,  460,  256,  250,  345,  447,  306,    5,  570,  550,
91138 /*  1530 */   299,  211,  370,  401,  550,  508,  502,  501,  490,  527,
91139 /*  1540 */   525,  483,  238,
91140};
91141static const YYCODETYPE yy_lookahead[] = {
91142 /*     0 */    19,  222,  223,  224,  225,   24,    1,   26,   77,   78,
91143 /*    10 */    79,   80,   15,   82,   83,   84,   85,   86,   87,   88,
91144 /*    20 */    89,   90,   91,   92,  113,   22,   26,   27,  117,   26,
91145 /*    30 */    49,   50,   81,   82,   83,   84,   85,   86,   87,   88,
91146 /*    40 */    89,   90,   91,   92,   88,   89,   90,   91,   92,   68,
91147 /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
91148 /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
91149 /*    70 */    89,   90,   91,   92,   19,   94,  118,   19,  150,   22,
91150 /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91151 /*    90 */    91,   92,   19,  165,   94,   95,   96,   94,  118,   99,
91152 /*   100 */   100,  101,  174,  175,   49,   50,   22,   23,   96,   54,
91153 /*   110 */   110,   99,  100,  101,    7,    8,   26,   27,   16,  105,
91154 /*   120 */   106,  107,  110,   68,   69,   70,   71,   72,   73,   74,
91155 /*   130 */    75,   76,   77,   78,   79,   80,  113,   82,   83,   84,
91156 /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   16,
91157 /*   150 */    92,   67,   98,   24,   96,   97,   98,   99,  100,  101,
91158 /*   160 */   102,   25,   60,  109,   62,   92,  150,  109,  150,   25,
91159 /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
91160 /*   180 */   116,  165,  109,  165,   94,   95,  118,   97,  170,  171,
91161 /*   190 */   174,  175,  128,   60,  104,   62,  106,   68,   69,   70,
91162 /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
91163 /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91164 /*   220 */    91,   92,   19,   21,   86,   87,   88,   89,   90,   91,
91165 /*   230 */    92,  215,   96,  150,   66,   99,  100,  101,   22,  150,
91166 /*   240 */   138,  118,   26,   27,  161,  162,  110,  103,  165,  231,
91167 /*   250 */   232,   23,   49,   50,  165,   24,   57,   26,   32,  170,
91168 /*   260 */   171,  112,   94,  114,  115,   63,   98,   41,  185,  186,
91169 /*   270 */   118,   68,   69,   70,   71,   72,   73,   74,   75,   76,
91170 /*   280 */    77,   78,   79,   80,   12,   82,   83,   84,   85,   86,
91171 /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
91172 /*   300 */    28,   23,  100,   25,  105,  106,  107,  150,   26,   27,
91173 /*   310 */    94,   95,  169,  170,  171,  116,   44,   23,   46,  150,
91174 /*   320 */   231,  232,  165,   26,   27,   94,   49,   50,   23,   57,
91175 /*   330 */    25,  174,  175,   22,  165,   26,   27,   26,   27,  136,
91176 /*   340 */   138,   97,   98,  174,  175,   68,   69,   70,   71,   72,
91177 /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
91178 /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
91179 /*   370 */    19,  150,   23,  216,   23,  232,   94,   95,  221,  150,
91180 /*   380 */    23,  160,   25,  214,  215,  163,  165,   88,  166,  167,
91181 /*   390 */   168,   94,   95,   23,  165,  174,  175,   88,  160,  150,
91182 /*   400 */    49,   50,  120,   94,   95,   94,   95,  158,   26,   57,
91183 /*   410 */   161,  162,  113,  136,  165,  194,  117,  120,   22,   68,
91184 /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
91185 /*   430 */    79,   80,  194,   82,   83,   84,   85,   86,   87,   88,
91186 /*   440 */    89,   90,   91,   92,   19,  150,   23,  112,   23,  114,
91187 /*   450 */   115,   25,  142,  143,  144,  145,  218,  105,  106,  107,
91188 /*   460 */   165,  112,  150,  114,  115,   22,  150,  166,  116,  174,
91189 /*   470 */   175,   22,   76,  235,   49,   50,   94,  165,  240,  172,
91190 /*   480 */   173,  165,  112,  155,  114,  115,  174,  175,  181,   11,
91191 /*   490 */   174,  175,   22,   68,   69,   70,   71,   72,   73,   74,
91192 /*   500 */    75,   76,   77,   78,   79,   80,  205,   82,   83,   84,
91193 /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  160,
91194 /*   520 */    23,  226,   23,  222,   12,  224,  225,  150,  216,   23,
91195 /*   530 */    23,   25,   36,   25,   25,  112,  220,  114,  115,  135,
91196 /*   540 */    28,  137,  165,   26,   27,  119,   30,   51,   49,   50,
91197 /*   550 */    34,  174,  175,  194,   58,  166,   44,  229,   46,  160,
91198 /*   560 */    22,   23,  234,   25,   48,  206,  207,   68,   69,   70,
91199 /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
91200 /*   580 */    23,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91201 /*   590 */    91,   92,   19,  194,  205,  150,   23,  220,   19,  181,
91202 /*   600 */   182,   95,   97,   95,  108,   67,  188,  169,  170,  171,
91203 /*   610 */   165,   94,   95,  222,   50,  224,  225,  218,  120,  150,
91204 /*   620 */   160,  116,   49,   50,   22,   23,  120,   25,  120,   50,
91205 /*   630 */   161,  162,   19,  128,  165,  244,   22,   23,  193,  240,
91206 /*   640 */    27,   68,   69,   70,   71,   72,   73,   74,   75,   76,
91207 /*   650 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
91208 /*   660 */    87,   88,   89,   90,   91,   92,   19,   25,  104,   67,
91209 /*   670 */   232,   24,  150,   23,  150,   25,  150,  150,  150,  150,
91210 /*   680 */   150,   67,   25,  104,    7,    8,    9,  165,  109,  165,
91211 /*   690 */   245,  165,  165,  165,  165,  165,   49,   50,  174,  175,
91212 /*   700 */   174,  175,  174,  175,  174,  175,    0,    1,    2,  105,
91213 /*   710 */   106,  107,  248,  249,  187,   68,   69,   70,   71,   72,
91214 /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
91215 /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
91216 /*   740 */    19,  150,  213,  165,  150,  222,  150,  224,  225,  166,
91217 /*   750 */   167,  168,  174,  175,  129,  130,  165,  150,  165,  165,
91218 /*   760 */   150,  165,  150,  241,   35,  174,  175,  174,  174,  175,
91219 /*   770 */    49,   50,  165,   52,   23,  165,   25,  165,  206,  207,
91220 /*   780 */    23,  197,   25,  187,  174,  175,  174,  175,  204,   68,
91221 /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
91222 /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
91223 /*   810 */    89,   90,   91,   92,   19,  150,  150,  165,   35,   23,
91224 /*   820 */   150,   25,  150,   22,  217,   24,  174,  175,  150,   35,
91225 /*   830 */   165,  165,  144,  145,  150,  165,  150,  165,  118,  174,
91226 /*   840 */   175,  150,   22,  165,   49,   50,  174,  175,   23,  165,
91227 /*   850 */    25,  165,   23,  187,   25,   27,  165,  187,  174,  175,
91228 /*   860 */    23,   23,   25,   68,   69,   70,   71,   72,   73,   74,
91229 /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
91230 /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
91231 /*   890 */   150,  165,  150,  150,  150,  217,   25,  160,   19,  213,
91232 /*   900 */   174,  175,  190,  191,  165,  165,   27,  165,  165,  165,
91233 /*   910 */   150,  150,  150,  174,  175,   39,  174,  175,   49,   50,
91234 /*   920 */    23,  150,   52,  250,  251,  165,  165,  165,  190,  191,
91235 /*   930 */   187,  194,  241,  193,  174,  175,  165,   68,   69,   70,
91236 /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
91237 /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91238 /*   960 */    91,   92,   19,  150,  150,  165,  150,  160,  160,  166,
91239 /*   970 */   166,  160,  150,   22,  174,  175,   91,   92,  165,  165,
91240 /*   980 */    52,  165,   29,  150,  213,  241,   23,  165,   49,   50,
91241 /*   990 */   174,  175,   49,   50,    1,    2,  173,  126,  165,   86,
91242 /*  1000 */    87,  194,  194,   22,  181,  194,  193,  193,  205,  205,
91243 /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
91244 /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
91245 /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
91246 /*  1040 */   150,  150,  150,   22,  150,  150,   22,   52,  174,  175,
91247 /*  1050 */    22,  102,   20,  165,  109,  165,  165,  165,  150,  165,
91248 /*  1060 */   165,  150,  174,  175,  174,  175,   49,   50,   24,   19,
91249 /*  1070 */    43,  104,   59,  165,  138,  104,  165,   25,   53,   53,
91250 /*  1080 */    22,    5,  174,  175,  193,  174,  175,   70,   71,   72,
91251 /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,    1,   82,
91252 /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
91253 /*  1110 */    19,   20,  150,   22,  150,  150,  150,   26,   27,  118,
91254 /*  1120 */   150,   35,  150,  150,   76,   27,  108,  165,   37,  165,
91255 /*  1130 */   165,  165,   76,   19,   20,  165,   22,  165,  165,  127,
91256 /*  1140 */    26,   27,   22,    1,  150,   16,   20,   56,  150,  150,
91257 /*  1150 */   119,   37,  150,  119,  160,  193,  150,   66,  193,  165,
91258 /*  1160 */   150,  150,  121,  165,  165,  108,  150,  165,  174,  175,
91259 /*  1170 */    56,  165,  150,  127,   22,  165,  165,   86,   87,   88,
91260 /*  1180 */    66,  165,   16,  150,   93,   94,   95,  165,  194,   98,
91261 /*  1190 */   174,  175,  128,   23,   15,   23,  174,  175,  165,  150,
91262 /*  1200 */    86,   87,   65,  140,  150,   22,    3,   93,   94,   95,
91263 /*  1210 */   216,    4,   98,  252,  165,  221,  150,  164,  180,  165,
91264 /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
91265 /*  1230 */   116,  165,   19,   20,  150,   22,  249,  252,  149,   26,
91266 /*  1240 */    27,  180,  165,  129,  130,  131,  132,  133,  134,  165,
91267 /*  1250 */    37,  174,  175,  150,    6,   19,   20,  150,   22,  150,
91268 /*  1260 */   150,  150,   26,   27,  149,  149,   13,  150,  165,   56,
91269 /*  1270 */   149,  159,  165,   37,  165,  165,  165,  174,  175,   66,
91270 /*  1280 */   146,  147,  165,  174,  175,   25,  152,  151,  154,  150,
91271 /*  1290 */   194,  151,   56,  116,  160,  150,  123,  202,  150,   86,
91272 /*  1300 */    87,  199,   66,  193,  165,  200,   93,   94,   95,  150,
91273 /*  1310 */   165,   98,  150,  165,  126,   22,  124,  150,  150,   26,
91274 /*  1320 */    27,  150,   86,   87,  165,  201,  150,  165,  194,   93,
91275 /*  1330 */    94,   95,  165,  165,   98,  150,  165,  122,  203,  125,
91276 /*  1340 */   227,  165,  129,  130,  131,  132,  133,  134,    5,  150,
91277 /*  1350 */   165,  135,  218,   10,   11,   12,   13,   14,  150,   66,
91278 /*  1360 */    17,  157,  118,  157,  165,  129,  130,  131,  132,  133,
91279 /*  1370 */   134,  150,  104,  165,   31,  210,   33,  176,  150,   86,
91280 /*  1380 */    87,  247,  174,  175,  150,   42,  165,   94,  121,  211,
91281 /*  1390 */   150,   98,  210,  165,  210,  174,  175,  211,   55,  165,
91282 /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
91283 /*  1410 */   104,  211,   47,  150,  174,  175,  165,  176,  176,  150,
91284 /*  1420 */   103,  165,  129,  130,  131,  174,  175,  184,  165,  179,
91285 /*  1430 */   174,  175,  150,  178,  165,  176,   22,  174,  175,  230,
91286 /*  1440 */    92,  230,  184,  174,  175,  150,  176,  165,  105,  106,
91287 /*  1450 */   107,  150,  176,  176,  111,  156,  174,  175,  179,  116,
91288 /*  1460 */   165,   18,  157,  156,  238,  157,  165,  156,   45,  174,
91289 /*  1470 */   175,  157,  157,  135,  239,  174,  175,  156,  189,  157,
91290 /*  1480 */    68,  189,  139,  219,   22,  199,  157,  192,   18,  192,
91291 /*  1490 */   192,  192,  199,  189,  219,  157,  243,   40,  243,  157,
91292 /*  1500 */   157,  246,   38,  153,  196,  198,  166,  233,  233,  228,
91293 /*  1510 */   177,  177,  209,  177,  182,  177,  166,  177,  166,  178,
91294 /*  1520 */   242,  199,  242,  209,  209,  199,  148,  196,  166,  208,
91295 /*  1530 */   195,  236,  237,  191,  208,  183,  183,  183,  186,  174,
91296 /*  1540 */   174,  186,   92,
91297};
91298#define YY_SHIFT_USE_DFLT (-90)
91299#define YY_SHIFT_COUNT (418)
91300#define YY_SHIFT_MIN   (-89)
91301#define YY_SHIFT_MAX   (1470)
91302static const short yy_shift_ofst[] = {
91303 /*     0 */   993, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
91304 /*    10 */  1213, 1213, 1213, 1213, 1213,  352,  517,  721, 1091, 1213,
91305 /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
91306 /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
91307 /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
91308 /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
91309 /*    60 */  1213,  -49,  199,  517,  517,  913,  913,  382, 1177,   55,
91310 /*    70 */   647,  573,  499,  425,  351,  277,  203,  129,  795,  795,
91311 /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
91312 /*    90 */   795,  795,  795,  795,  795,  795,  869,  795,  943, 1017,
91313 /*   100 */  1017,  -69,  -69,  -69,  -69,   -1,   -1,   58,  138,  -44,
91314 /*   110 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91315 /*   120 */   517,  517,  517,  517,  517,  517,  202,  579,  517,  517,
91316 /*   130 */   517,  517,  517,  382,  885, 1450,  -90,  -90,  -90, 1293,
91317 /*   140 */    73,  272,  272,  309,  311,  297,  282,  216,  602,  538,
91318 /*   150 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91319 /*   160 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91320 /*   170 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91321 /*   180 */   517,  517,  505,  231,  231,  231,  706,   64, 1177, 1177,
91322 /*   190 */  1177,  -90,  -90,  -90,  136,  168,  168,   12,  496,  496,
91323 /*   200 */   496,  506,  423,  512,  370,  349,  335,  149,  149,  149,
91324 /*   210 */   149,  604,  516,  149,  149,  508,    3,  299,  677,  871,
91325 /*   220 */   613,  613,  879,  871,  879,  144,  382,  226,  382,  226,
91326 /*   230 */   564,  226,  613,  226,  226,  404,  625,  625,  382,  426,
91327 /*   240 */   -89,  801, 1464, 1244, 1244, 1457, 1457, 1244, 1462, 1412,
91328 /*   250 */  1188, 1470, 1470, 1470, 1470, 1244, 1188, 1462, 1412, 1412,
91329 /*   260 */  1244, 1443, 1338, 1423, 1244, 1244, 1443, 1244, 1443, 1244,
91330 /*   270 */  1443, 1414, 1306, 1306, 1306, 1365, 1348, 1348, 1414, 1306,
91331 /*   280 */  1317, 1306, 1365, 1306, 1306, 1267, 1268, 1267, 1268, 1267,
91332 /*   290 */  1268, 1244, 1244, 1216, 1214, 1215, 1192, 1173, 1188, 1177,
91333 /*   300 */  1260, 1253, 1253, 1248, 1248, 1248, 1248,  -90,  -90,  -90,
91334 /*   310 */   -90,  -90,  -90,  939,  102,  614,   84,  133,   14,  837,
91335 /*   320 */   396,  829,  825,  796,  757,  751,  650,  357,  244,  107,
91336 /*   330 */    54,  305,  278, 1207, 1203, 1183, 1063, 1179, 1137, 1166,
91337 /*   340 */  1172, 1170, 1064, 1152, 1046, 1057, 1034, 1126, 1041, 1129,
91338 /*   350 */  1142, 1031, 1120, 1012, 1056, 1048, 1018, 1098, 1086, 1001,
91339 /*   360 */  1097, 1076, 1058,  971,  936, 1026, 1052, 1025, 1013, 1027,
91340 /*   370 */   967, 1044, 1032, 1050,  945,  949, 1028,  995, 1024, 1021,
91341 /*   380 */   963,  981,  928,  953,  951,  870,  876,  897,  838,  720,
91342 /*   390 */   828,  794,  820,  498,  642,  783,  657,  729,  642,  557,
91343 /*   400 */   507,  509,  497,  470,  478,  449,  294,  228,  443,   23,
91344 /*   410 */   152,  123,   68,  -20,  -42,   57,   39,   -3,    5,
91345};
91346#define YY_REDUCE_USE_DFLT (-222)
91347#define YY_REDUCE_COUNT (312)
91348#define YY_REDUCE_MIN   (-221)
91349#define YY_REDUCE_MAX   (1378)
91350static const short yy_reduce_ofst[] = {
91351 /*     0 */   310,  994, 1134,  221,  169,  157,   89,   18,   83,  301,
91352 /*    10 */   377,  316,  312,   16,  295,  238,  249,  391, 1301, 1295,
91353 /*    20 */  1282, 1269, 1263, 1256, 1251, 1240, 1234, 1228, 1221, 1208,
91354 /*    30 */  1109, 1103, 1077, 1054, 1022, 1016,  911,  908,  890,  888,
91355 /*    40 */   874,  816,  800,  760,  742,  739,  726,  684,  672,  665,
91356 /*    50 */   652,  612,  610,  594,  591,  578,  530,  528,  526,  524,
91357 /*    60 */   -72, -221,  399,  469,  445,  438,  143,  222,  359,  523,
91358 /*    70 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
91359 /*    80 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
91360 /*    90 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
91361 /*   100 */   523,  523,  523,  523,  523,  523,  523,  307,  523,  523,
91362 /*   110 */  1110,  678, 1033,  965,  962,  891,  814,  813,  744,  771,
91363 /*   120 */   691,  607,  522,  743,  686,  740,  328,  418,  670,  666,
91364 /*   130 */   596,  527,  529,  583,  523,  523,  523,  523,  523,  593,
91365 /*   140 */   823,  738,  712,  892, 1199, 1185, 1176, 1171,  673,  673,
91366 /*   150 */  1168, 1167, 1162, 1159, 1148, 1145, 1139, 1117, 1111, 1107,
91367 /*   160 */  1084, 1066, 1049, 1011, 1010, 1006, 1002,  999,  998,  973,
91368 /*   170 */   972,  970,  966,  964,  895,  894,  892,  833,  822,  762,
91369 /*   180 */   761,  229,  811,  804,  803,  389,  688,  808,  807,  737,
91370 /*   190 */   460,  464,  572,  584, 1355, 1366, 1365, 1352, 1354, 1353,
91371 /*   200 */  1352, 1326, 1335, 1342, 1335, 1335, 1335, 1335, 1335, 1335,
91372 /*   210 */  1335, 1295, 1295, 1335, 1335, 1321, 1362, 1331, 1378, 1326,
91373 /*   220 */  1315, 1314, 1280, 1322, 1278, 1341, 1352, 1340, 1350, 1338,
91374 /*   230 */  1332, 1336, 1303, 1334, 1333, 1281, 1275, 1274, 1340, 1307,
91375 /*   240 */  1308, 1350, 1255, 1343, 1342, 1255, 1253, 1338, 1275, 1304,
91376 /*   250 */  1293, 1299, 1298, 1297, 1295, 1329, 1286, 1264, 1292, 1289,
91377 /*   260 */  1322, 1321, 1235, 1226, 1315, 1314, 1311, 1308, 1307, 1305,
91378 /*   270 */  1299, 1279, 1277, 1276, 1270, 1258, 1211, 1209, 1250, 1259,
91379 /*   280 */  1255, 1242, 1243, 1241, 1201, 1200, 1184, 1186, 1182, 1178,
91380 /*   290 */  1165, 1206, 1204, 1113, 1135, 1095, 1124, 1105, 1102, 1096,
91381 /*   300 */  1112, 1140, 1136, 1121, 1116, 1115, 1089,  985,  961,  987,
91382 /*   310 */  1061, 1038, 1053,
91383};
91384static const YYACTIONTYPE yy_default[] = {
91385 /*     0 */   636,  872,  961,  961,  961,  872,  901,  901,  961,  760,
91386 /*    10 */   961,  961,  961,  961,  870,  961,  961,  935,  961,  961,
91387 /*    20 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91388 /*    30 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91389 /*    40 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91390 /*    50 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91391 /*    60 */   961,  844,  961,  961,  961,  901,  901,  675,  764,  795,
91392 /*    70 */   961,  961,  961,  961,  961,  961,  961,  961,  934,  936,
91393 /*    80 */   810,  809,  803,  802,  914,  775,  800,  793,  786,  797,
91394 /*    90 */   873,  866,  867,  865,  869,  874,  961,  796,  832,  850,
91395 /*   100 */   831,  849,  856,  848,  834,  843,  833,  667,  835,  836,
91396 /*   110 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91397 /*   120 */   961,  961,  961,  961,  961,  961,  662,  729,  961,  961,
91398 /*   130 */   961,  961,  961,  961,  837,  838,  853,  852,  851,  961,
91399 /*   140 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91400 /*   150 */   961,  941,  939,  961,  885,  961,  961,  961,  961,  961,
91401 /*   160 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91402 /*   170 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91403 /*   180 */   961,  642,  961,  760,  760,  760,  636,  961,  961,  961,
91404 /*   190 */   961,  953,  764,  754,  720,  961,  961,  961,  961,  961,
91405 /*   200 */   961,  961,  961,  961,  961,  961,  961,  805,  743,  924,
91406 /*   210 */   926,  961,  907,  741,  664,  762,  677,  752,  644,  799,
91407 /*   220 */   777,  777,  919,  799,  919,  701,  961,  789,  961,  789,
91408 /*   230 */   698,  789,  777,  789,  789,  868,  961,  961,  961,  761,
91409 /*   240 */   752,  961,  946,  768,  768,  938,  938,  768,  811,  733,
91410 /*   250 */   799,  740,  740,  740,  740,  768,  799,  811,  733,  733,
91411 /*   260 */   768,  659,  913,  911,  768,  768,  659,  768,  659,  768,
91412 /*   270 */   659,  878,  731,  731,  731,  716,  882,  882,  878,  731,
91413 /*   280 */   701,  731,  716,  731,  731,  781,  776,  781,  776,  781,
91414 /*   290 */   776,  768,  768,  961,  794,  782,  792,  790,  799,  961,
91415 /*   300 */   719,  652,  652,  641,  641,  641,  641,  958,  958,  953,
91416 /*   310 */   703,  703,  685,  961,  961,  961,  961,  961,  961,  961,
91417 /*   320 */   887,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91418 /*   330 */   961,  961,  961,  961,  637,  948,  961,  961,  945,  961,
91419 /*   340 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91420 /*   350 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  917,
91421 /*   360 */   961,  961,  961,  961,  961,  961,  910,  909,  961,  961,
91422 /*   370 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91423 /*   380 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91424 /*   390 */   961,  961,  961,  961,  791,  961,  783,  961,  871,  961,
91425 /*   400 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  746,
91426 /*   410 */   820,  961,  819,  823,  818,  669,  961,  650,  961,  633,
91427 /*   420 */   638,  957,  960,  959,  956,  955,  954,  949,  947,  944,
91428 /*   430 */   943,  942,  940,  937,  933,  891,  889,  896,  895,  894,
91429 /*   440 */   893,  892,  890,  888,  886,  806,  804,  801,  798,  932,
91430 /*   450 */   884,  742,  739,  738,  658,  950,  916,  925,  923,  812,
91431 /*   460 */   922,  921,  920,  918,  915,  902,  808,  807,  734,  876,
91432 /*   470 */   875,  661,  906,  905,  904,  908,  912,  903,  770,  660,
91433 /*   480 */   657,  666,  723,  722,  730,  728,  727,  726,  725,  724,
91434 /*   490 */   721,  668,  676,  687,  715,  700,  699,  881,  883,  880,
91435 /*   500 */   879,  708,  707,  713,  712,  711,  710,  709,  706,  705,
91436 /*   510 */   704,  697,  696,  702,  695,  718,  717,  714,  694,  737,
91437 /*   520 */   736,  735,  732,  693,  692,  691,  823,  690,  689,  829,
91438 /*   530 */   828,  816,  860,  757,  756,  755,  767,  766,  779,  778,
91439 /*   540 */   814,  813,  780,  765,  759,  758,  774,  773,  772,  771,
91440 /*   550 */   763,  753,  785,  788,  787,  784,  845,  862,  769,  859,
91441 /*   560 */   931,  930,  929,  928,  927,  864,  863,  830,  827,  680,
91442 /*   570 */   681,  900,  898,  899,  897,  683,  682,  679,  678,  861,
91443 /*   580 */   748,  747,  857,  854,  846,  841,  858,  855,  847,  842,
91444 /*   590 */   840,  839,  825,  824,  822,  821,  817,  826,  671,  749,
91445 /*   600 */   745,  744,  815,  751,  750,  688,  686,  684,  665,  663,
91446 /*   610 */   656,  654,  653,  655,  651,  649,  648,  647,  646,  645,
91447 /*   620 */   674,  673,  672,  670,  669,  643,  640,  639,  635,  634,
91448 /*   630 */   632,
91449};
91450
91451/* The next table maps tokens into fallback tokens.  If a construct
91452** like the following:
91453**
91454**      %fallback ID X Y Z.
91455**
91456** appears in the grammar, then ID becomes a fallback token for X, Y,
91457** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
91458** but it does not parse, the type of the token is changed to ID and
91459** the parse is retried before an error is thrown.
91460*/
91461#ifdef YYFALLBACK
91462static const YYCODETYPE yyFallback[] = {
91463    0,  /*          $ => nothing */
91464    0,  /*       SEMI => nothing */
91465   26,  /*    EXPLAIN => ID */
91466   26,  /*      QUERY => ID */
91467   26,  /*       PLAN => ID */
91468   26,  /*      BEGIN => ID */
91469    0,  /* TRANSACTION => nothing */
91470   26,  /*   DEFERRED => ID */
91471   26,  /*  IMMEDIATE => ID */
91472   26,  /*  EXCLUSIVE => ID */
91473    0,  /*     COMMIT => nothing */
91474   26,  /*        END => ID */
91475   26,  /*   ROLLBACK => ID */
91476   26,  /*  SAVEPOINT => ID */
91477   26,  /*    RELEASE => ID */
91478    0,  /*         TO => nothing */
91479    0,  /*      TABLE => nothing */
91480    0,  /*     CREATE => nothing */
91481   26,  /*         IF => ID */
91482    0,  /*        NOT => nothing */
91483    0,  /*     EXISTS => nothing */
91484   26,  /*       TEMP => ID */
91485    0,  /*         LP => nothing */
91486    0,  /*         RP => nothing */
91487    0,  /*         AS => nothing */
91488    0,  /*      COMMA => nothing */
91489    0,  /*         ID => nothing */
91490    0,  /*    INDEXED => nothing */
91491   26,  /*      ABORT => ID */
91492   26,  /*     ACTION => ID */
91493   26,  /*      AFTER => ID */
91494   26,  /*    ANALYZE => ID */
91495   26,  /*        ASC => ID */
91496   26,  /*     ATTACH => ID */
91497   26,  /*     BEFORE => ID */
91498   26,  /*         BY => ID */
91499   26,  /*    CASCADE => ID */
91500   26,  /*       CAST => ID */
91501   26,  /*   COLUMNKW => ID */
91502   26,  /*   CONFLICT => ID */
91503   26,  /*   DATABASE => ID */
91504   26,  /*       DESC => ID */
91505   26,  /*     DETACH => ID */
91506   26,  /*       EACH => ID */
91507   26,  /*       FAIL => ID */
91508   26,  /*        FOR => ID */
91509   26,  /*     IGNORE => ID */
91510   26,  /*  INITIALLY => ID */
91511   26,  /*    INSTEAD => ID */
91512   26,  /*    LIKE_KW => ID */
91513   26,  /*      MATCH => ID */
91514   26,  /*         NO => ID */
91515   26,  /*        KEY => ID */
91516   26,  /*         OF => ID */
91517   26,  /*     OFFSET => ID */
91518   26,  /*     PRAGMA => ID */
91519   26,  /*      RAISE => ID */
91520   26,  /*    REPLACE => ID */
91521   26,  /*   RESTRICT => ID */
91522   26,  /*        ROW => ID */
91523   26,  /*    TRIGGER => ID */
91524   26,  /*     VACUUM => ID */
91525   26,  /*       VIEW => ID */
91526   26,  /*    VIRTUAL => ID */
91527   26,  /*    REINDEX => ID */
91528   26,  /*     RENAME => ID */
91529   26,  /*   CTIME_KW => ID */
91530};
91531#endif /* YYFALLBACK */
91532
91533/* The following structure represents a single element of the
91534** parser's stack.  Information stored includes:
91535**
91536**   +  The state number for the parser at this level of the stack.
91537**
91538**   +  The value of the token stored at this level of the stack.
91539**      (In other words, the "major" token.)
91540**
91541**   +  The semantic value stored at this level of the stack.  This is
91542**      the information used by the action routines in the grammar.
91543**      It is sometimes called the "minor" token.
91544*/
91545struct yyStackEntry {
91546  YYACTIONTYPE stateno;  /* The state-number */
91547  YYCODETYPE major;      /* The major token value.  This is the code
91548                         ** number for the token at this stack level */
91549  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
91550                         ** is the value of the token  */
91551};
91552typedef struct yyStackEntry yyStackEntry;
91553
91554/* The state of the parser is completely contained in an instance of
91555** the following structure */
91556struct yyParser {
91557  int yyidx;                    /* Index of top element in stack */
91558#ifdef YYTRACKMAXSTACKDEPTH
91559  int yyidxMax;                 /* Maximum value of yyidx */
91560#endif
91561  int yyerrcnt;                 /* Shifts left before out of the error */
91562  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
91563#if YYSTACKDEPTH<=0
91564  int yystksz;                  /* Current side of the stack */
91565  yyStackEntry *yystack;        /* The parser's stack */
91566#else
91567  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
91568#endif
91569};
91570typedef struct yyParser yyParser;
91571
91572#ifndef NDEBUG
91573static FILE *yyTraceFILE = 0;
91574static char *yyTracePrompt = 0;
91575#endif /* NDEBUG */
91576
91577#ifndef NDEBUG
91578/*
91579** Turn parser tracing on by giving a stream to which to write the trace
91580** and a prompt to preface each trace message.  Tracing is turned off
91581** by making either argument NULL
91582**
91583** Inputs:
91584** <ul>
91585** <li> A FILE* to which trace output should be written.
91586**      If NULL, then tracing is turned off.
91587** <li> A prefix string written at the beginning of every
91588**      line of trace output.  If NULL, then tracing is
91589**      turned off.
91590** </ul>
91591**
91592** Outputs:
91593** None.
91594*/
91595SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
91596  yyTraceFILE = TraceFILE;
91597  yyTracePrompt = zTracePrompt;
91598  if( yyTraceFILE==0 ) yyTracePrompt = 0;
91599  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
91600}
91601#endif /* NDEBUG */
91602
91603#ifndef NDEBUG
91604/* For tracing shifts, the names of all terminals and nonterminals
91605** are required.  The following table supplies these names */
91606static const char *const yyTokenName[] = {
91607  "$",             "SEMI",          "EXPLAIN",       "QUERY",
91608  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
91609  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
91610  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
91611  "TABLE",         "CREATE",        "IF",            "NOT",
91612  "EXISTS",        "TEMP",          "LP",            "RP",
91613  "AS",            "COMMA",         "ID",            "INDEXED",
91614  "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
91615  "ASC",           "ATTACH",        "BEFORE",        "BY",
91616  "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
91617  "DATABASE",      "DESC",          "DETACH",        "EACH",
91618  "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
91619  "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
91620  "KEY",           "OF",            "OFFSET",        "PRAGMA",
91621  "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
91622  "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
91623  "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
91624  "OR",            "AND",           "IS",            "BETWEEN",
91625  "IN",            "ISNULL",        "NOTNULL",       "NE",
91626  "EQ",            "GT",            "LE",            "LT",
91627  "GE",            "ESCAPE",        "BITAND",        "BITOR",
91628  "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
91629  "STAR",          "SLASH",         "REM",           "CONCAT",
91630  "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
91631  "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
91632  "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
91633  "ON",            "INSERT",        "DELETE",        "UPDATE",
91634  "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
91635  "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
91636  "SELECT",        "DISTINCT",      "DOT",           "FROM",
91637  "JOIN",          "USING",         "ORDER",         "GROUP",
91638  "HAVING",        "LIMIT",         "WHERE",         "INTO",
91639  "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
91640  "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
91641  "THEN",          "ELSE",          "INDEX",         "ALTER",
91642  "ADD",           "error",         "input",         "cmdlist",
91643  "ecmd",          "explain",       "cmdx",          "cmd",
91644  "transtype",     "trans_opt",     "nm",            "savepoint_opt",
91645  "create_table",  "create_table_args",  "createkw",      "temp",
91646  "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
91647  "select",        "column",        "columnid",      "type",
91648  "carglist",      "id",            "ids",           "typetoken",
91649  "typename",      "signed",        "plus_num",      "minus_num",
91650  "carg",          "ccons",         "term",          "expr",
91651  "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
91652  "refargs",       "defer_subclause",  "refarg",        "refact",
91653  "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",
91654  "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
91655  "ifexists",      "fullname",      "oneselect",     "multiselect_op",
91656  "distinct",      "selcollist",    "from",          "where_opt",
91657  "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
91658  "sclp",          "as",            "seltablist",    "stl_prefix",
91659  "joinop",        "indexed_opt",   "on_opt",        "using_opt",
91660  "joinop2",       "inscollist",    "sortlist",      "sortitem",
91661  "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
91662  "itemlist",      "exprlist",      "likeop",        "escape",
91663  "between_op",    "in_op",         "case_operand",  "case_exprlist",
91664  "case_else",     "uniqueflag",    "collate",       "nmnum",
91665  "plus_opt",      "number",        "trigger_decl",  "trigger_cmd_list",
91666  "trigger_time",  "trigger_event",  "foreach_clause",  "when_clause",
91667  "trigger_cmd",   "trnm",          "tridxby",       "database_kw_opt",
91668  "key_opt",       "add_column_fullname",  "kwcolumn_opt",  "create_vtab",
91669  "vtabarglist",   "vtabarg",       "vtabargtoken",  "lp",
91670  "anylist",
91671};
91672#endif /* NDEBUG */
91673
91674#ifndef NDEBUG
91675/* For tracing reduce actions, the names of all rules are required.
91676*/
91677static const char *const yyRuleName[] = {
91678 /*   0 */ "input ::= cmdlist",
91679 /*   1 */ "cmdlist ::= cmdlist ecmd",
91680 /*   2 */ "cmdlist ::= ecmd",
91681 /*   3 */ "ecmd ::= SEMI",
91682 /*   4 */ "ecmd ::= explain cmdx SEMI",
91683 /*   5 */ "explain ::=",
91684 /*   6 */ "explain ::= EXPLAIN",
91685 /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
91686 /*   8 */ "cmdx ::= cmd",
91687 /*   9 */ "cmd ::= BEGIN transtype trans_opt",
91688 /*  10 */ "trans_opt ::=",
91689 /*  11 */ "trans_opt ::= TRANSACTION",
91690 /*  12 */ "trans_opt ::= TRANSACTION nm",
91691 /*  13 */ "transtype ::=",
91692 /*  14 */ "transtype ::= DEFERRED",
91693 /*  15 */ "transtype ::= IMMEDIATE",
91694 /*  16 */ "transtype ::= EXCLUSIVE",
91695 /*  17 */ "cmd ::= COMMIT trans_opt",
91696 /*  18 */ "cmd ::= END trans_opt",
91697 /*  19 */ "cmd ::= ROLLBACK trans_opt",
91698 /*  20 */ "savepoint_opt ::= SAVEPOINT",
91699 /*  21 */ "savepoint_opt ::=",
91700 /*  22 */ "cmd ::= SAVEPOINT nm",
91701 /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
91702 /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
91703 /*  25 */ "cmd ::= create_table create_table_args",
91704 /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
91705 /*  27 */ "createkw ::= CREATE",
91706 /*  28 */ "ifnotexists ::=",
91707 /*  29 */ "ifnotexists ::= IF NOT EXISTS",
91708 /*  30 */ "temp ::= TEMP",
91709 /*  31 */ "temp ::=",
91710 /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
91711 /*  33 */ "create_table_args ::= AS select",
91712 /*  34 */ "columnlist ::= columnlist COMMA column",
91713 /*  35 */ "columnlist ::= column",
91714 /*  36 */ "column ::= columnid type carglist",
91715 /*  37 */ "columnid ::= nm",
91716 /*  38 */ "id ::= ID",
91717 /*  39 */ "id ::= INDEXED",
91718 /*  40 */ "ids ::= ID|STRING",
91719 /*  41 */ "nm ::= id",
91720 /*  42 */ "nm ::= STRING",
91721 /*  43 */ "nm ::= JOIN_KW",
91722 /*  44 */ "type ::=",
91723 /*  45 */ "type ::= typetoken",
91724 /*  46 */ "typetoken ::= typename",
91725 /*  47 */ "typetoken ::= typename LP signed RP",
91726 /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
91727 /*  49 */ "typename ::= ids",
91728 /*  50 */ "typename ::= typename ids",
91729 /*  51 */ "signed ::= plus_num",
91730 /*  52 */ "signed ::= minus_num",
91731 /*  53 */ "carglist ::= carglist carg",
91732 /*  54 */ "carglist ::=",
91733 /*  55 */ "carg ::= CONSTRAINT nm ccons",
91734 /*  56 */ "carg ::= ccons",
91735 /*  57 */ "ccons ::= DEFAULT term",
91736 /*  58 */ "ccons ::= DEFAULT LP expr RP",
91737 /*  59 */ "ccons ::= DEFAULT PLUS term",
91738 /*  60 */ "ccons ::= DEFAULT MINUS term",
91739 /*  61 */ "ccons ::= DEFAULT id",
91740 /*  62 */ "ccons ::= NULL onconf",
91741 /*  63 */ "ccons ::= NOT NULL onconf",
91742 /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
91743 /*  65 */ "ccons ::= UNIQUE onconf",
91744 /*  66 */ "ccons ::= CHECK LP expr RP",
91745 /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
91746 /*  68 */ "ccons ::= defer_subclause",
91747 /*  69 */ "ccons ::= COLLATE ids",
91748 /*  70 */ "autoinc ::=",
91749 /*  71 */ "autoinc ::= AUTOINCR",
91750 /*  72 */ "refargs ::=",
91751 /*  73 */ "refargs ::= refargs refarg",
91752 /*  74 */ "refarg ::= MATCH nm",
91753 /*  75 */ "refarg ::= ON INSERT refact",
91754 /*  76 */ "refarg ::= ON DELETE refact",
91755 /*  77 */ "refarg ::= ON UPDATE refact",
91756 /*  78 */ "refact ::= SET NULL",
91757 /*  79 */ "refact ::= SET DEFAULT",
91758 /*  80 */ "refact ::= CASCADE",
91759 /*  81 */ "refact ::= RESTRICT",
91760 /*  82 */ "refact ::= NO ACTION",
91761 /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
91762 /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
91763 /*  85 */ "init_deferred_pred_opt ::=",
91764 /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
91765 /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
91766 /*  88 */ "conslist_opt ::=",
91767 /*  89 */ "conslist_opt ::= COMMA conslist",
91768 /*  90 */ "conslist ::= conslist COMMA tcons",
91769 /*  91 */ "conslist ::= conslist tcons",
91770 /*  92 */ "conslist ::= tcons",
91771 /*  93 */ "tcons ::= CONSTRAINT nm",
91772 /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
91773 /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
91774 /*  96 */ "tcons ::= CHECK LP expr RP onconf",
91775 /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
91776 /*  98 */ "defer_subclause_opt ::=",
91777 /*  99 */ "defer_subclause_opt ::= defer_subclause",
91778 /* 100 */ "onconf ::=",
91779 /* 101 */ "onconf ::= ON CONFLICT resolvetype",
91780 /* 102 */ "orconf ::=",
91781 /* 103 */ "orconf ::= OR resolvetype",
91782 /* 104 */ "resolvetype ::= raisetype",
91783 /* 105 */ "resolvetype ::= IGNORE",
91784 /* 106 */ "resolvetype ::= REPLACE",
91785 /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
91786 /* 108 */ "ifexists ::= IF EXISTS",
91787 /* 109 */ "ifexists ::=",
91788 /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
91789 /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
91790 /* 112 */ "cmd ::= select",
91791 /* 113 */ "select ::= oneselect",
91792 /* 114 */ "select ::= select multiselect_op oneselect",
91793 /* 115 */ "multiselect_op ::= UNION",
91794 /* 116 */ "multiselect_op ::= UNION ALL",
91795 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
91796 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
91797 /* 119 */ "distinct ::= DISTINCT",
91798 /* 120 */ "distinct ::= ALL",
91799 /* 121 */ "distinct ::=",
91800 /* 122 */ "sclp ::= selcollist COMMA",
91801 /* 123 */ "sclp ::=",
91802 /* 124 */ "selcollist ::= sclp expr as",
91803 /* 125 */ "selcollist ::= sclp STAR",
91804 /* 126 */ "selcollist ::= sclp nm DOT STAR",
91805 /* 127 */ "as ::= AS nm",
91806 /* 128 */ "as ::= ids",
91807 /* 129 */ "as ::=",
91808 /* 130 */ "from ::=",
91809 /* 131 */ "from ::= FROM seltablist",
91810 /* 132 */ "stl_prefix ::= seltablist joinop",
91811 /* 133 */ "stl_prefix ::=",
91812 /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
91813 /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
91814 /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
91815 /* 137 */ "dbnm ::=",
91816 /* 138 */ "dbnm ::= DOT nm",
91817 /* 139 */ "fullname ::= nm dbnm",
91818 /* 140 */ "joinop ::= COMMA|JOIN",
91819 /* 141 */ "joinop ::= JOIN_KW JOIN",
91820 /* 142 */ "joinop ::= JOIN_KW nm JOIN",
91821 /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
91822 /* 144 */ "on_opt ::= ON expr",
91823 /* 145 */ "on_opt ::=",
91824 /* 146 */ "indexed_opt ::=",
91825 /* 147 */ "indexed_opt ::= INDEXED BY nm",
91826 /* 148 */ "indexed_opt ::= NOT INDEXED",
91827 /* 149 */ "using_opt ::= USING LP inscollist RP",
91828 /* 150 */ "using_opt ::=",
91829 /* 151 */ "orderby_opt ::=",
91830 /* 152 */ "orderby_opt ::= ORDER BY sortlist",
91831 /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
91832 /* 154 */ "sortlist ::= sortitem sortorder",
91833 /* 155 */ "sortitem ::= expr",
91834 /* 156 */ "sortorder ::= ASC",
91835 /* 157 */ "sortorder ::= DESC",
91836 /* 158 */ "sortorder ::=",
91837 /* 159 */ "groupby_opt ::=",
91838 /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
91839 /* 161 */ "having_opt ::=",
91840 /* 162 */ "having_opt ::= HAVING expr",
91841 /* 163 */ "limit_opt ::=",
91842 /* 164 */ "limit_opt ::= LIMIT expr",
91843 /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
91844 /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
91845 /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
91846 /* 168 */ "where_opt ::=",
91847 /* 169 */ "where_opt ::= WHERE expr",
91848 /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
91849 /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
91850 /* 172 */ "setlist ::= nm EQ expr",
91851 /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
91852 /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
91853 /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
91854 /* 176 */ "insert_cmd ::= INSERT orconf",
91855 /* 177 */ "insert_cmd ::= REPLACE",
91856 /* 178 */ "itemlist ::= itemlist COMMA expr",
91857 /* 179 */ "itemlist ::= expr",
91858 /* 180 */ "inscollist_opt ::=",
91859 /* 181 */ "inscollist_opt ::= LP inscollist RP",
91860 /* 182 */ "inscollist ::= inscollist COMMA nm",
91861 /* 183 */ "inscollist ::= nm",
91862 /* 184 */ "expr ::= term",
91863 /* 185 */ "expr ::= LP expr RP",
91864 /* 186 */ "term ::= NULL",
91865 /* 187 */ "expr ::= id",
91866 /* 188 */ "expr ::= JOIN_KW",
91867 /* 189 */ "expr ::= nm DOT nm",
91868 /* 190 */ "expr ::= nm DOT nm DOT nm",
91869 /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
91870 /* 192 */ "term ::= STRING",
91871 /* 193 */ "expr ::= REGISTER",
91872 /* 194 */ "expr ::= VARIABLE",
91873 /* 195 */ "expr ::= expr COLLATE ids",
91874 /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
91875 /* 197 */ "expr ::= ID LP distinct exprlist RP",
91876 /* 198 */ "expr ::= ID LP STAR RP",
91877 /* 199 */ "term ::= CTIME_KW",
91878 /* 200 */ "expr ::= expr AND expr",
91879 /* 201 */ "expr ::= expr OR expr",
91880 /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
91881 /* 203 */ "expr ::= expr EQ|NE expr",
91882 /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
91883 /* 205 */ "expr ::= expr PLUS|MINUS expr",
91884 /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
91885 /* 207 */ "expr ::= expr CONCAT expr",
91886 /* 208 */ "likeop ::= LIKE_KW",
91887 /* 209 */ "likeop ::= NOT LIKE_KW",
91888 /* 210 */ "likeop ::= MATCH",
91889 /* 211 */ "likeop ::= NOT MATCH",
91890 /* 212 */ "escape ::= ESCAPE expr",
91891 /* 213 */ "escape ::=",
91892 /* 214 */ "expr ::= expr likeop expr escape",
91893 /* 215 */ "expr ::= expr ISNULL|NOTNULL",
91894 /* 216 */ "expr ::= expr NOT NULL",
91895 /* 217 */ "expr ::= expr IS expr",
91896 /* 218 */ "expr ::= expr IS NOT expr",
91897 /* 219 */ "expr ::= NOT expr",
91898 /* 220 */ "expr ::= BITNOT expr",
91899 /* 221 */ "expr ::= MINUS expr",
91900 /* 222 */ "expr ::= PLUS expr",
91901 /* 223 */ "between_op ::= BETWEEN",
91902 /* 224 */ "between_op ::= NOT BETWEEN",
91903 /* 225 */ "expr ::= expr between_op expr AND expr",
91904 /* 226 */ "in_op ::= IN",
91905 /* 227 */ "in_op ::= NOT IN",
91906 /* 228 */ "expr ::= expr in_op LP exprlist RP",
91907 /* 229 */ "expr ::= LP select RP",
91908 /* 230 */ "expr ::= expr in_op LP select RP",
91909 /* 231 */ "expr ::= expr in_op nm dbnm",
91910 /* 232 */ "expr ::= EXISTS LP select RP",
91911 /* 233 */ "expr ::= CASE case_operand case_exprlist case_else END",
91912 /* 234 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
91913 /* 235 */ "case_exprlist ::= WHEN expr THEN expr",
91914 /* 236 */ "case_else ::= ELSE expr",
91915 /* 237 */ "case_else ::=",
91916 /* 238 */ "case_operand ::= expr",
91917 /* 239 */ "case_operand ::=",
91918 /* 240 */ "exprlist ::= nexprlist",
91919 /* 241 */ "exprlist ::=",
91920 /* 242 */ "nexprlist ::= nexprlist COMMA expr",
91921 /* 243 */ "nexprlist ::= expr",
91922 /* 244 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
91923 /* 245 */ "uniqueflag ::= UNIQUE",
91924 /* 246 */ "uniqueflag ::=",
91925 /* 247 */ "idxlist_opt ::=",
91926 /* 248 */ "idxlist_opt ::= LP idxlist RP",
91927 /* 249 */ "idxlist ::= idxlist COMMA nm collate sortorder",
91928 /* 250 */ "idxlist ::= nm collate sortorder",
91929 /* 251 */ "collate ::=",
91930 /* 252 */ "collate ::= COLLATE ids",
91931 /* 253 */ "cmd ::= DROP INDEX ifexists fullname",
91932 /* 254 */ "cmd ::= VACUUM",
91933 /* 255 */ "cmd ::= VACUUM nm",
91934 /* 256 */ "cmd ::= PRAGMA nm dbnm",
91935 /* 257 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
91936 /* 258 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
91937 /* 259 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
91938 /* 260 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
91939 /* 261 */ "nmnum ::= plus_num",
91940 /* 262 */ "nmnum ::= nm",
91941 /* 263 */ "nmnum ::= ON",
91942 /* 264 */ "nmnum ::= DELETE",
91943 /* 265 */ "nmnum ::= DEFAULT",
91944 /* 266 */ "plus_num ::= plus_opt number",
91945 /* 267 */ "minus_num ::= MINUS number",
91946 /* 268 */ "number ::= INTEGER|FLOAT",
91947 /* 269 */ "plus_opt ::= PLUS",
91948 /* 270 */ "plus_opt ::=",
91949 /* 271 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
91950 /* 272 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
91951 /* 273 */ "trigger_time ::= BEFORE",
91952 /* 274 */ "trigger_time ::= AFTER",
91953 /* 275 */ "trigger_time ::= INSTEAD OF",
91954 /* 276 */ "trigger_time ::=",
91955 /* 277 */ "trigger_event ::= DELETE|INSERT",
91956 /* 278 */ "trigger_event ::= UPDATE",
91957 /* 279 */ "trigger_event ::= UPDATE OF inscollist",
91958 /* 280 */ "foreach_clause ::=",
91959 /* 281 */ "foreach_clause ::= FOR EACH ROW",
91960 /* 282 */ "when_clause ::=",
91961 /* 283 */ "when_clause ::= WHEN expr",
91962 /* 284 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
91963 /* 285 */ "trigger_cmd_list ::= trigger_cmd SEMI",
91964 /* 286 */ "trnm ::= nm",
91965 /* 287 */ "trnm ::= nm DOT nm",
91966 /* 288 */ "tridxby ::=",
91967 /* 289 */ "tridxby ::= INDEXED BY nm",
91968 /* 290 */ "tridxby ::= NOT INDEXED",
91969 /* 291 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
91970 /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
91971 /* 293 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
91972 /* 294 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
91973 /* 295 */ "trigger_cmd ::= select",
91974 /* 296 */ "expr ::= RAISE LP IGNORE RP",
91975 /* 297 */ "expr ::= RAISE LP raisetype COMMA nm RP",
91976 /* 298 */ "raisetype ::= ROLLBACK",
91977 /* 299 */ "raisetype ::= ABORT",
91978 /* 300 */ "raisetype ::= FAIL",
91979 /* 301 */ "cmd ::= DROP TRIGGER ifexists fullname",
91980 /* 302 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
91981 /* 303 */ "cmd ::= DETACH database_kw_opt expr",
91982 /* 304 */ "key_opt ::=",
91983 /* 305 */ "key_opt ::= KEY expr",
91984 /* 306 */ "database_kw_opt ::= DATABASE",
91985 /* 307 */ "database_kw_opt ::=",
91986 /* 308 */ "cmd ::= REINDEX",
91987 /* 309 */ "cmd ::= REINDEX nm dbnm",
91988 /* 310 */ "cmd ::= ANALYZE",
91989 /* 311 */ "cmd ::= ANALYZE nm dbnm",
91990 /* 312 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
91991 /* 313 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
91992 /* 314 */ "add_column_fullname ::= fullname",
91993 /* 315 */ "kwcolumn_opt ::=",
91994 /* 316 */ "kwcolumn_opt ::= COLUMNKW",
91995 /* 317 */ "cmd ::= create_vtab",
91996 /* 318 */ "cmd ::= create_vtab LP vtabarglist RP",
91997 /* 319 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
91998 /* 320 */ "vtabarglist ::= vtabarg",
91999 /* 321 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
92000 /* 322 */ "vtabarg ::=",
92001 /* 323 */ "vtabarg ::= vtabarg vtabargtoken",
92002 /* 324 */ "vtabargtoken ::= ANY",
92003 /* 325 */ "vtabargtoken ::= lp anylist RP",
92004 /* 326 */ "lp ::= LP",
92005 /* 327 */ "anylist ::=",
92006 /* 328 */ "anylist ::= anylist LP anylist RP",
92007 /* 329 */ "anylist ::= anylist ANY",
92008};
92009#endif /* NDEBUG */
92010
92011
92012#if YYSTACKDEPTH<=0
92013/*
92014** Try to increase the size of the parser stack.
92015*/
92016static void yyGrowStack(yyParser *p){
92017  int newSize;
92018  yyStackEntry *pNew;
92019
92020  newSize = p->yystksz*2 + 100;
92021  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
92022  if( pNew ){
92023    p->yystack = pNew;
92024    p->yystksz = newSize;
92025#ifndef NDEBUG
92026    if( yyTraceFILE ){
92027      fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
92028              yyTracePrompt, p->yystksz);
92029    }
92030#endif
92031  }
92032}
92033#endif
92034
92035/*
92036** This function allocates a new parser.
92037** The only argument is a pointer to a function which works like
92038** malloc.
92039**
92040** Inputs:
92041** A pointer to the function used to allocate memory.
92042**
92043** Outputs:
92044** A pointer to a parser.  This pointer is used in subsequent calls
92045** to sqlite3Parser and sqlite3ParserFree.
92046*/
92047SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
92048  yyParser *pParser;
92049  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
92050  if( pParser ){
92051    pParser->yyidx = -1;
92052#ifdef YYTRACKMAXSTACKDEPTH
92053    pParser->yyidxMax = 0;
92054#endif
92055#if YYSTACKDEPTH<=0
92056    pParser->yystack = NULL;
92057    pParser->yystksz = 0;
92058    yyGrowStack(pParser);
92059#endif
92060  }
92061  return pParser;
92062}
92063
92064/* The following function deletes the value associated with a
92065** symbol.  The symbol can be either a terminal or nonterminal.
92066** "yymajor" is the symbol code, and "yypminor" is a pointer to
92067** the value.
92068*/
92069static void yy_destructor(
92070  yyParser *yypParser,    /* The parser */
92071  YYCODETYPE yymajor,     /* Type code for object to destroy */
92072  YYMINORTYPE *yypminor   /* The object to be destroyed */
92073){
92074  sqlite3ParserARG_FETCH;
92075  switch( yymajor ){
92076    /* Here is inserted the actions which take place when a
92077    ** terminal or non-terminal is destroyed.  This can happen
92078    ** when the symbol is popped from the stack during a
92079    ** reduce or during error processing or when a parser is
92080    ** being destroyed before it is finished parsing.
92081    **
92082    ** Note: during a reduce, the only symbols destroyed are those
92083    ** which appear on the RHS of the rule, but which are not used
92084    ** inside the C code.
92085    */
92086    case 160: /* select */
92087    case 194: /* oneselect */
92088{
92089sqlite3SelectDelete(pParse->db, (yypminor->yy3));
92090}
92091      break;
92092    case 174: /* term */
92093    case 175: /* expr */
92094    case 223: /* escape */
92095{
92096sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
92097}
92098      break;
92099    case 179: /* idxlist_opt */
92100    case 187: /* idxlist */
92101    case 197: /* selcollist */
92102    case 200: /* groupby_opt */
92103    case 202: /* orderby_opt */
92104    case 204: /* sclp */
92105    case 214: /* sortlist */
92106    case 216: /* nexprlist */
92107    case 217: /* setlist */
92108    case 220: /* itemlist */
92109    case 221: /* exprlist */
92110    case 227: /* case_exprlist */
92111{
92112sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
92113}
92114      break;
92115    case 193: /* fullname */
92116    case 198: /* from */
92117    case 206: /* seltablist */
92118    case 207: /* stl_prefix */
92119{
92120sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
92121}
92122      break;
92123    case 199: /* where_opt */
92124    case 201: /* having_opt */
92125    case 210: /* on_opt */
92126    case 215: /* sortitem */
92127    case 226: /* case_operand */
92128    case 228: /* case_else */
92129    case 239: /* when_clause */
92130    case 244: /* key_opt */
92131{
92132sqlite3ExprDelete(pParse->db, (yypminor->yy132));
92133}
92134      break;
92135    case 211: /* using_opt */
92136    case 213: /* inscollist */
92137    case 219: /* inscollist_opt */
92138{
92139sqlite3IdListDelete(pParse->db, (yypminor->yy408));
92140}
92141      break;
92142    case 235: /* trigger_cmd_list */
92143    case 240: /* trigger_cmd */
92144{
92145sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
92146}
92147      break;
92148    case 237: /* trigger_event */
92149{
92150sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
92151}
92152      break;
92153    default:  break;   /* If no destructor action specified: do nothing */
92154  }
92155}
92156
92157/*
92158** Pop the parser's stack once.
92159**
92160** If there is a destructor routine associated with the token which
92161** is popped from the stack, then call it.
92162**
92163** Return the major token number for the symbol popped.
92164*/
92165static int yy_pop_parser_stack(yyParser *pParser){
92166  YYCODETYPE yymajor;
92167  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
92168
92169  /* There is no mechanism by which the parser stack can be popped below
92170  ** empty in SQLite.  */
92171  if( NEVER(pParser->yyidx<0) ) return 0;
92172#ifndef NDEBUG
92173  if( yyTraceFILE && pParser->yyidx>=0 ){
92174    fprintf(yyTraceFILE,"%sPopping %s\n",
92175      yyTracePrompt,
92176      yyTokenName[yytos->major]);
92177  }
92178#endif
92179  yymajor = yytos->major;
92180  yy_destructor(pParser, yymajor, &yytos->minor);
92181  pParser->yyidx--;
92182  return yymajor;
92183}
92184
92185/*
92186** Deallocate and destroy a parser.  Destructors are all called for
92187** all stack elements before shutting the parser down.
92188**
92189** Inputs:
92190** <ul>
92191** <li>  A pointer to the parser.  This should be a pointer
92192**       obtained from sqlite3ParserAlloc.
92193** <li>  A pointer to a function used to reclaim memory obtained
92194**       from malloc.
92195** </ul>
92196*/
92197SQLITE_PRIVATE void sqlite3ParserFree(
92198  void *p,                    /* The parser to be deleted */
92199  void (*freeProc)(void*)     /* Function used to reclaim memory */
92200){
92201  yyParser *pParser = (yyParser*)p;
92202  /* In SQLite, we never try to destroy a parser that was not successfully
92203  ** created in the first place. */
92204  if( NEVER(pParser==0) ) return;
92205  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
92206#if YYSTACKDEPTH<=0
92207  free(pParser->yystack);
92208#endif
92209  (*freeProc)((void*)pParser);
92210}
92211
92212/*
92213** Return the peak depth of the stack for a parser.
92214*/
92215#ifdef YYTRACKMAXSTACKDEPTH
92216SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
92217  yyParser *pParser = (yyParser*)p;
92218  return pParser->yyidxMax;
92219}
92220#endif
92221
92222/*
92223** Find the appropriate action for a parser given the terminal
92224** look-ahead token iLookAhead.
92225**
92226** If the look-ahead token is YYNOCODE, then check to see if the action is
92227** independent of the look-ahead.  If it is, return the action, otherwise
92228** return YY_NO_ACTION.
92229*/
92230static int yy_find_shift_action(
92231  yyParser *pParser,        /* The parser */
92232  YYCODETYPE iLookAhead     /* The look-ahead token */
92233){
92234  int i;
92235  int stateno = pParser->yystack[pParser->yyidx].stateno;
92236
92237  if( stateno>YY_SHIFT_COUNT
92238   || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
92239    return yy_default[stateno];
92240  }
92241  assert( iLookAhead!=YYNOCODE );
92242  i += iLookAhead;
92243  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
92244    if( iLookAhead>0 ){
92245#ifdef YYFALLBACK
92246      YYCODETYPE iFallback;            /* Fallback token */
92247      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
92248             && (iFallback = yyFallback[iLookAhead])!=0 ){
92249#ifndef NDEBUG
92250        if( yyTraceFILE ){
92251          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
92252             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
92253        }
92254#endif
92255        return yy_find_shift_action(pParser, iFallback);
92256      }
92257#endif
92258#ifdef YYWILDCARD
92259      {
92260        int j = i - iLookAhead + YYWILDCARD;
92261        if(
92262#if YY_SHIFT_MIN+YYWILDCARD<0
92263          j>=0 &&
92264#endif
92265#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
92266          j<YY_ACTTAB_COUNT &&
92267#endif
92268          yy_lookahead[j]==YYWILDCARD
92269        ){
92270#ifndef NDEBUG
92271          if( yyTraceFILE ){
92272            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
92273               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
92274          }
92275#endif /* NDEBUG */
92276          return yy_action[j];
92277        }
92278      }
92279#endif /* YYWILDCARD */
92280    }
92281    return yy_default[stateno];
92282  }else{
92283    return yy_action[i];
92284  }
92285}
92286
92287/*
92288** Find the appropriate action for a parser given the non-terminal
92289** look-ahead token iLookAhead.
92290**
92291** If the look-ahead token is YYNOCODE, then check to see if the action is
92292** independent of the look-ahead.  If it is, return the action, otherwise
92293** return YY_NO_ACTION.
92294*/
92295static int yy_find_reduce_action(
92296  int stateno,              /* Current state number */
92297  YYCODETYPE iLookAhead     /* The look-ahead token */
92298){
92299  int i;
92300#ifdef YYERRORSYMBOL
92301  if( stateno>YY_REDUCE_COUNT ){
92302    return yy_default[stateno];
92303  }
92304#else
92305  assert( stateno<=YY_REDUCE_COUNT );
92306#endif
92307  i = yy_reduce_ofst[stateno];
92308  assert( i!=YY_REDUCE_USE_DFLT );
92309  assert( iLookAhead!=YYNOCODE );
92310  i += iLookAhead;
92311#ifdef YYERRORSYMBOL
92312  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
92313    return yy_default[stateno];
92314  }
92315#else
92316  assert( i>=0 && i<YY_ACTTAB_COUNT );
92317  assert( yy_lookahead[i]==iLookAhead );
92318#endif
92319  return yy_action[i];
92320}
92321
92322/*
92323** The following routine is called if the stack overflows.
92324*/
92325static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
92326   sqlite3ParserARG_FETCH;
92327   yypParser->yyidx--;
92328#ifndef NDEBUG
92329   if( yyTraceFILE ){
92330     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
92331   }
92332#endif
92333   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
92334   /* Here code is inserted which will execute if the parser
92335   ** stack every overflows */
92336
92337  UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
92338  sqlite3ErrorMsg(pParse, "parser stack overflow");
92339  pParse->parseError = 1;
92340   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
92341}
92342
92343/*
92344** Perform a shift action.
92345*/
92346static void yy_shift(
92347  yyParser *yypParser,          /* The parser to be shifted */
92348  int yyNewState,               /* The new state to shift in */
92349  int yyMajor,                  /* The major token to shift in */
92350  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
92351){
92352  yyStackEntry *yytos;
92353  yypParser->yyidx++;
92354#ifdef YYTRACKMAXSTACKDEPTH
92355  if( yypParser->yyidx>yypParser->yyidxMax ){
92356    yypParser->yyidxMax = yypParser->yyidx;
92357  }
92358#endif
92359#if YYSTACKDEPTH>0
92360  if( yypParser->yyidx>=YYSTACKDEPTH ){
92361    yyStackOverflow(yypParser, yypMinor);
92362    return;
92363  }
92364#else
92365  if( yypParser->yyidx>=yypParser->yystksz ){
92366    yyGrowStack(yypParser);
92367    if( yypParser->yyidx>=yypParser->yystksz ){
92368      yyStackOverflow(yypParser, yypMinor);
92369      return;
92370    }
92371  }
92372#endif
92373  yytos = &yypParser->yystack[yypParser->yyidx];
92374  yytos->stateno = (YYACTIONTYPE)yyNewState;
92375  yytos->major = (YYCODETYPE)yyMajor;
92376  yytos->minor = *yypMinor;
92377#ifndef NDEBUG
92378  if( yyTraceFILE && yypParser->yyidx>0 ){
92379    int i;
92380    fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
92381    fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
92382    for(i=1; i<=yypParser->yyidx; i++)
92383      fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
92384    fprintf(yyTraceFILE,"\n");
92385  }
92386#endif
92387}
92388
92389/* The following table contains information about every rule that
92390** is used during the reduce.
92391*/
92392static const struct {
92393  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
92394  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
92395} yyRuleInfo[] = {
92396  { 142, 1 },
92397  { 143, 2 },
92398  { 143, 1 },
92399  { 144, 1 },
92400  { 144, 3 },
92401  { 145, 0 },
92402  { 145, 1 },
92403  { 145, 3 },
92404  { 146, 1 },
92405  { 147, 3 },
92406  { 149, 0 },
92407  { 149, 1 },
92408  { 149, 2 },
92409  { 148, 0 },
92410  { 148, 1 },
92411  { 148, 1 },
92412  { 148, 1 },
92413  { 147, 2 },
92414  { 147, 2 },
92415  { 147, 2 },
92416  { 151, 1 },
92417  { 151, 0 },
92418  { 147, 2 },
92419  { 147, 3 },
92420  { 147, 5 },
92421  { 147, 2 },
92422  { 152, 6 },
92423  { 154, 1 },
92424  { 156, 0 },
92425  { 156, 3 },
92426  { 155, 1 },
92427  { 155, 0 },
92428  { 153, 4 },
92429  { 153, 2 },
92430  { 158, 3 },
92431  { 158, 1 },
92432  { 161, 3 },
92433  { 162, 1 },
92434  { 165, 1 },
92435  { 165, 1 },
92436  { 166, 1 },
92437  { 150, 1 },
92438  { 150, 1 },
92439  { 150, 1 },
92440  { 163, 0 },
92441  { 163, 1 },
92442  { 167, 1 },
92443  { 167, 4 },
92444  { 167, 6 },
92445  { 168, 1 },
92446  { 168, 2 },
92447  { 169, 1 },
92448  { 169, 1 },
92449  { 164, 2 },
92450  { 164, 0 },
92451  { 172, 3 },
92452  { 172, 1 },
92453  { 173, 2 },
92454  { 173, 4 },
92455  { 173, 3 },
92456  { 173, 3 },
92457  { 173, 2 },
92458  { 173, 2 },
92459  { 173, 3 },
92460  { 173, 5 },
92461  { 173, 2 },
92462  { 173, 4 },
92463  { 173, 4 },
92464  { 173, 1 },
92465  { 173, 2 },
92466  { 178, 0 },
92467  { 178, 1 },
92468  { 180, 0 },
92469  { 180, 2 },
92470  { 182, 2 },
92471  { 182, 3 },
92472  { 182, 3 },
92473  { 182, 3 },
92474  { 183, 2 },
92475  { 183, 2 },
92476  { 183, 1 },
92477  { 183, 1 },
92478  { 183, 2 },
92479  { 181, 3 },
92480  { 181, 2 },
92481  { 184, 0 },
92482  { 184, 2 },
92483  { 184, 2 },
92484  { 159, 0 },
92485  { 159, 2 },
92486  { 185, 3 },
92487  { 185, 2 },
92488  { 185, 1 },
92489  { 186, 2 },
92490  { 186, 7 },
92491  { 186, 5 },
92492  { 186, 5 },
92493  { 186, 10 },
92494  { 188, 0 },
92495  { 188, 1 },
92496  { 176, 0 },
92497  { 176, 3 },
92498  { 189, 0 },
92499  { 189, 2 },
92500  { 190, 1 },
92501  { 190, 1 },
92502  { 190, 1 },
92503  { 147, 4 },
92504  { 192, 2 },
92505  { 192, 0 },
92506  { 147, 8 },
92507  { 147, 4 },
92508  { 147, 1 },
92509  { 160, 1 },
92510  { 160, 3 },
92511  { 195, 1 },
92512  { 195, 2 },
92513  { 195, 1 },
92514  { 194, 9 },
92515  { 196, 1 },
92516  { 196, 1 },
92517  { 196, 0 },
92518  { 204, 2 },
92519  { 204, 0 },
92520  { 197, 3 },
92521  { 197, 2 },
92522  { 197, 4 },
92523  { 205, 2 },
92524  { 205, 1 },
92525  { 205, 0 },
92526  { 198, 0 },
92527  { 198, 2 },
92528  { 207, 2 },
92529  { 207, 0 },
92530  { 206, 7 },
92531  { 206, 7 },
92532  { 206, 7 },
92533  { 157, 0 },
92534  { 157, 2 },
92535  { 193, 2 },
92536  { 208, 1 },
92537  { 208, 2 },
92538  { 208, 3 },
92539  { 208, 4 },
92540  { 210, 2 },
92541  { 210, 0 },
92542  { 209, 0 },
92543  { 209, 3 },
92544  { 209, 2 },
92545  { 211, 4 },
92546  { 211, 0 },
92547  { 202, 0 },
92548  { 202, 3 },
92549  { 214, 4 },
92550  { 214, 2 },
92551  { 215, 1 },
92552  { 177, 1 },
92553  { 177, 1 },
92554  { 177, 0 },
92555  { 200, 0 },
92556  { 200, 3 },
92557  { 201, 0 },
92558  { 201, 2 },
92559  { 203, 0 },
92560  { 203, 2 },
92561  { 203, 4 },
92562  { 203, 4 },
92563  { 147, 5 },
92564  { 199, 0 },
92565  { 199, 2 },
92566  { 147, 7 },
92567  { 217, 5 },
92568  { 217, 3 },
92569  { 147, 8 },
92570  { 147, 5 },
92571  { 147, 6 },
92572  { 218, 2 },
92573  { 218, 1 },
92574  { 220, 3 },
92575  { 220, 1 },
92576  { 219, 0 },
92577  { 219, 3 },
92578  { 213, 3 },
92579  { 213, 1 },
92580  { 175, 1 },
92581  { 175, 3 },
92582  { 174, 1 },
92583  { 175, 1 },
92584  { 175, 1 },
92585  { 175, 3 },
92586  { 175, 5 },
92587  { 174, 1 },
92588  { 174, 1 },
92589  { 175, 1 },
92590  { 175, 1 },
92591  { 175, 3 },
92592  { 175, 6 },
92593  { 175, 5 },
92594  { 175, 4 },
92595  { 174, 1 },
92596  { 175, 3 },
92597  { 175, 3 },
92598  { 175, 3 },
92599  { 175, 3 },
92600  { 175, 3 },
92601  { 175, 3 },
92602  { 175, 3 },
92603  { 175, 3 },
92604  { 222, 1 },
92605  { 222, 2 },
92606  { 222, 1 },
92607  { 222, 2 },
92608  { 223, 2 },
92609  { 223, 0 },
92610  { 175, 4 },
92611  { 175, 2 },
92612  { 175, 3 },
92613  { 175, 3 },
92614  { 175, 4 },
92615  { 175, 2 },
92616  { 175, 2 },
92617  { 175, 2 },
92618  { 175, 2 },
92619  { 224, 1 },
92620  { 224, 2 },
92621  { 175, 5 },
92622  { 225, 1 },
92623  { 225, 2 },
92624  { 175, 5 },
92625  { 175, 3 },
92626  { 175, 5 },
92627  { 175, 4 },
92628  { 175, 4 },
92629  { 175, 5 },
92630  { 227, 5 },
92631  { 227, 4 },
92632  { 228, 2 },
92633  { 228, 0 },
92634  { 226, 1 },
92635  { 226, 0 },
92636  { 221, 1 },
92637  { 221, 0 },
92638  { 216, 3 },
92639  { 216, 1 },
92640  { 147, 11 },
92641  { 229, 1 },
92642  { 229, 0 },
92643  { 179, 0 },
92644  { 179, 3 },
92645  { 187, 5 },
92646  { 187, 3 },
92647  { 230, 0 },
92648  { 230, 2 },
92649  { 147, 4 },
92650  { 147, 1 },
92651  { 147, 2 },
92652  { 147, 3 },
92653  { 147, 5 },
92654  { 147, 6 },
92655  { 147, 5 },
92656  { 147, 6 },
92657  { 231, 1 },
92658  { 231, 1 },
92659  { 231, 1 },
92660  { 231, 1 },
92661  { 231, 1 },
92662  { 170, 2 },
92663  { 171, 2 },
92664  { 233, 1 },
92665  { 232, 1 },
92666  { 232, 0 },
92667  { 147, 5 },
92668  { 234, 11 },
92669  { 236, 1 },
92670  { 236, 1 },
92671  { 236, 2 },
92672  { 236, 0 },
92673  { 237, 1 },
92674  { 237, 1 },
92675  { 237, 3 },
92676  { 238, 0 },
92677  { 238, 3 },
92678  { 239, 0 },
92679  { 239, 2 },
92680  { 235, 3 },
92681  { 235, 2 },
92682  { 241, 1 },
92683  { 241, 3 },
92684  { 242, 0 },
92685  { 242, 3 },
92686  { 242, 2 },
92687  { 240, 7 },
92688  { 240, 8 },
92689  { 240, 5 },
92690  { 240, 5 },
92691  { 240, 1 },
92692  { 175, 4 },
92693  { 175, 6 },
92694  { 191, 1 },
92695  { 191, 1 },
92696  { 191, 1 },
92697  { 147, 4 },
92698  { 147, 6 },
92699  { 147, 3 },
92700  { 244, 0 },
92701  { 244, 2 },
92702  { 243, 1 },
92703  { 243, 0 },
92704  { 147, 1 },
92705  { 147, 3 },
92706  { 147, 1 },
92707  { 147, 3 },
92708  { 147, 6 },
92709  { 147, 6 },
92710  { 245, 1 },
92711  { 246, 0 },
92712  { 246, 1 },
92713  { 147, 1 },
92714  { 147, 4 },
92715  { 247, 7 },
92716  { 248, 1 },
92717  { 248, 3 },
92718  { 249, 0 },
92719  { 249, 2 },
92720  { 250, 1 },
92721  { 250, 3 },
92722  { 251, 1 },
92723  { 252, 0 },
92724  { 252, 4 },
92725  { 252, 2 },
92726};
92727
92728static void yy_accept(yyParser*);  /* Forward Declaration */
92729
92730/*
92731** Perform a reduce action and the shift that must immediately
92732** follow the reduce.
92733*/
92734static void yy_reduce(
92735  yyParser *yypParser,         /* The parser */
92736  int yyruleno                 /* Number of the rule by which to reduce */
92737){
92738  int yygoto;                     /* The next state */
92739  int yyact;                      /* The next action */
92740  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
92741  yyStackEntry *yymsp;            /* The top of the parser's stack */
92742  int yysize;                     /* Amount to pop the stack */
92743  sqlite3ParserARG_FETCH;
92744  yymsp = &yypParser->yystack[yypParser->yyidx];
92745#ifndef NDEBUG
92746  if( yyTraceFILE && yyruleno>=0
92747        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
92748    fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
92749      yyRuleName[yyruleno]);
92750  }
92751#endif /* NDEBUG */
92752
92753  /* Silence complaints from purify about yygotominor being uninitialized
92754  ** in some cases when it is copied into the stack after the following
92755  ** switch.  yygotominor is uninitialized when a rule reduces that does
92756  ** not set the value of its left-hand side nonterminal.  Leaving the
92757  ** value of the nonterminal uninitialized is utterly harmless as long
92758  ** as the value is never used.  So really the only thing this code
92759  ** accomplishes is to quieten purify.
92760  **
92761  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
92762  ** without this code, their parser segfaults.  I'm not sure what there
92763  ** parser is doing to make this happen.  This is the second bug report
92764  ** from wireshark this week.  Clearly they are stressing Lemon in ways
92765  ** that it has not been previously stressed...  (SQLite ticket #2172)
92766  */
92767  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
92768  yygotominor = yyzerominor;
92769
92770
92771  switch( yyruleno ){
92772  /* Beginning here are the reduction cases.  A typical example
92773  ** follows:
92774  **   case 0:
92775  **  #line <lineno> <grammarfile>
92776  **     { ... }           // User supplied code
92777  **  #line <lineno> <thisfile>
92778  **     break;
92779  */
92780      case 5: /* explain ::= */
92781{ sqlite3BeginParse(pParse, 0); }
92782        break;
92783      case 6: /* explain ::= EXPLAIN */
92784{ sqlite3BeginParse(pParse, 1); }
92785        break;
92786      case 7: /* explain ::= EXPLAIN QUERY PLAN */
92787{ sqlite3BeginParse(pParse, 2); }
92788        break;
92789      case 8: /* cmdx ::= cmd */
92790{ sqlite3FinishCoding(pParse); }
92791        break;
92792      case 9: /* cmd ::= BEGIN transtype trans_opt */
92793{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
92794        break;
92795      case 13: /* transtype ::= */
92796{yygotominor.yy328 = (pParse->db->flags&SQLITE_BeginImmediate) ? TK_IMMEDIATE : TK_DEFERRED;}/* Android Change */
92797        break;
92798      case 14: /* transtype ::= DEFERRED */
92799      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
92800      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
92801      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
92802      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
92803{yygotominor.yy328 = yymsp[0].major;}
92804        break;
92805      case 17: /* cmd ::= COMMIT trans_opt */
92806      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
92807{sqlite3CommitTransaction(pParse);}
92808        break;
92809      case 19: /* cmd ::= ROLLBACK trans_opt */
92810{sqlite3RollbackTransaction(pParse);}
92811        break;
92812      case 22: /* cmd ::= SAVEPOINT nm */
92813{
92814  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
92815}
92816        break;
92817      case 23: /* cmd ::= RELEASE savepoint_opt nm */
92818{
92819  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
92820}
92821        break;
92822      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
92823{
92824  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
92825}
92826        break;
92827      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
92828{
92829   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
92830}
92831        break;
92832      case 27: /* createkw ::= CREATE */
92833{
92834  pParse->db->lookaside.bEnabled = 0;
92835  yygotominor.yy0 = yymsp[0].minor.yy0;
92836}
92837        break;
92838      case 28: /* ifnotexists ::= */
92839      case 31: /* temp ::= */ yytestcase(yyruleno==31);
92840      case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
92841      case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
92842      case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
92843      case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
92844      case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
92845      case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
92846      case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
92847      case 121: /* distinct ::= */ yytestcase(yyruleno==121);
92848      case 223: /* between_op ::= BETWEEN */ yytestcase(yyruleno==223);
92849      case 226: /* in_op ::= IN */ yytestcase(yyruleno==226);
92850{yygotominor.yy328 = 0;}
92851        break;
92852      case 29: /* ifnotexists ::= IF NOT EXISTS */
92853      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
92854      case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
92855      case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
92856      case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
92857      case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
92858      case 224: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==224);
92859      case 227: /* in_op ::= NOT IN */ yytestcase(yyruleno==227);
92860{yygotominor.yy328 = 1;}
92861        break;
92862      case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
92863{
92864  sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
92865}
92866        break;
92867      case 33: /* create_table_args ::= AS select */
92868{
92869  sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy3);
92870  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
92871}
92872        break;
92873      case 36: /* column ::= columnid type carglist */
92874{
92875  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
92876  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
92877}
92878        break;
92879      case 37: /* columnid ::= nm */
92880{
92881  sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
92882  yygotominor.yy0 = yymsp[0].minor.yy0;
92883}
92884        break;
92885      case 38: /* id ::= ID */
92886      case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
92887      case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
92888      case 41: /* nm ::= id */ yytestcase(yyruleno==41);
92889      case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
92890      case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
92891      case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
92892      case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
92893      case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
92894      case 128: /* as ::= ids */ yytestcase(yyruleno==128);
92895      case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
92896      case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
92897      case 252: /* collate ::= COLLATE ids */ yytestcase(yyruleno==252);
92898      case 261: /* nmnum ::= plus_num */ yytestcase(yyruleno==261);
92899      case 262: /* nmnum ::= nm */ yytestcase(yyruleno==262);
92900      case 263: /* nmnum ::= ON */ yytestcase(yyruleno==263);
92901      case 264: /* nmnum ::= DELETE */ yytestcase(yyruleno==264);
92902      case 265: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==265);
92903      case 266: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==266);
92904      case 267: /* minus_num ::= MINUS number */ yytestcase(yyruleno==267);
92905      case 268: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==268);
92906      case 286: /* trnm ::= nm */ yytestcase(yyruleno==286);
92907{yygotominor.yy0 = yymsp[0].minor.yy0;}
92908        break;
92909      case 45: /* type ::= typetoken */
92910{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
92911        break;
92912      case 47: /* typetoken ::= typename LP signed RP */
92913{
92914  yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
92915  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
92916}
92917        break;
92918      case 48: /* typetoken ::= typename LP signed COMMA signed RP */
92919{
92920  yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
92921  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
92922}
92923        break;
92924      case 50: /* typename ::= typename ids */
92925{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);}
92926        break;
92927      case 57: /* ccons ::= DEFAULT term */
92928      case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
92929{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
92930        break;
92931      case 58: /* ccons ::= DEFAULT LP expr RP */
92932{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
92933        break;
92934      case 60: /* ccons ::= DEFAULT MINUS term */
92935{
92936  ExprSpan v;
92937  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
92938  v.zStart = yymsp[-1].minor.yy0.z;
92939  v.zEnd = yymsp[0].minor.yy346.zEnd;
92940  sqlite3AddDefaultValue(pParse,&v);
92941}
92942        break;
92943      case 61: /* ccons ::= DEFAULT id */
92944{
92945  ExprSpan v;
92946  spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
92947  sqlite3AddDefaultValue(pParse,&v);
92948}
92949        break;
92950      case 63: /* ccons ::= NOT NULL onconf */
92951{sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
92952        break;
92953      case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
92954{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
92955        break;
92956      case 65: /* ccons ::= UNIQUE onconf */
92957{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
92958        break;
92959      case 66: /* ccons ::= CHECK LP expr RP */
92960{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
92961        break;
92962      case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
92963{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
92964        break;
92965      case 68: /* ccons ::= defer_subclause */
92966{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
92967        break;
92968      case 69: /* ccons ::= COLLATE ids */
92969{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
92970        break;
92971      case 72: /* refargs ::= */
92972{ yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
92973        break;
92974      case 73: /* refargs ::= refargs refarg */
92975{ yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
92976        break;
92977      case 74: /* refarg ::= MATCH nm */
92978      case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
92979{ yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
92980        break;
92981      case 76: /* refarg ::= ON DELETE refact */
92982{ yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
92983        break;
92984      case 77: /* refarg ::= ON UPDATE refact */
92985{ yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
92986        break;
92987      case 78: /* refact ::= SET NULL */
92988{ yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
92989        break;
92990      case 79: /* refact ::= SET DEFAULT */
92991{ yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
92992        break;
92993      case 80: /* refact ::= CASCADE */
92994{ yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
92995        break;
92996      case 81: /* refact ::= RESTRICT */
92997{ yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
92998        break;
92999      case 82: /* refact ::= NO ACTION */
93000{ yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
93001        break;
93002      case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
93003      case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
93004      case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
93005      case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
93006{yygotominor.yy328 = yymsp[0].minor.yy328;}
93007        break;
93008      case 88: /* conslist_opt ::= */
93009{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
93010        break;
93011      case 89: /* conslist_opt ::= COMMA conslist */
93012{yygotominor.yy0 = yymsp[-1].minor.yy0;}
93013        break;
93014      case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
93015{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
93016        break;
93017      case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
93018{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
93019        break;
93020      case 96: /* tcons ::= CHECK LP expr RP onconf */
93021{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
93022        break;
93023      case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
93024{
93025    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
93026    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
93027}
93028        break;
93029      case 100: /* onconf ::= */
93030{yygotominor.yy328 = OE_Default;}
93031        break;
93032      case 102: /* orconf ::= */
93033{yygotominor.yy186 = OE_Default;}
93034        break;
93035      case 103: /* orconf ::= OR resolvetype */
93036{yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
93037        break;
93038      case 105: /* resolvetype ::= IGNORE */
93039{yygotominor.yy328 = OE_Ignore;}
93040        break;
93041      case 106: /* resolvetype ::= REPLACE */
93042{yygotominor.yy328 = OE_Replace;}
93043        break;
93044      case 107: /* cmd ::= DROP TABLE ifexists fullname */
93045{
93046  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
93047}
93048        break;
93049      case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
93050{
93051  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);
93052}
93053        break;
93054      case 111: /* cmd ::= DROP VIEW ifexists fullname */
93055{
93056  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
93057}
93058        break;
93059      case 112: /* cmd ::= select */
93060{
93061  SelectDest dest = {SRT_Output, 0, 0, 0, 0};
93062  sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
93063  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
93064}
93065        break;
93066      case 113: /* select ::= oneselect */
93067{yygotominor.yy3 = yymsp[0].minor.yy3;}
93068        break;
93069      case 114: /* select ::= select multiselect_op oneselect */
93070{
93071  if( yymsp[0].minor.yy3 ){
93072    yymsp[0].minor.yy3->op = (u8)yymsp[-1].minor.yy328;
93073    yymsp[0].minor.yy3->pPrior = yymsp[-2].minor.yy3;
93074  }else{
93075    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
93076  }
93077  yygotominor.yy3 = yymsp[0].minor.yy3;
93078}
93079        break;
93080      case 116: /* multiselect_op ::= UNION ALL */
93081{yygotominor.yy328 = TK_ALL;}
93082        break;
93083      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
93084{
93085  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);
93086}
93087        break;
93088      case 122: /* sclp ::= selcollist COMMA */
93089      case 248: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==248);
93090{yygotominor.yy14 = yymsp[-1].minor.yy14;}
93091        break;
93092      case 123: /* sclp ::= */
93093      case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
93094      case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
93095      case 241: /* exprlist ::= */ yytestcase(yyruleno==241);
93096      case 247: /* idxlist_opt ::= */ yytestcase(yyruleno==247);
93097{yygotominor.yy14 = 0;}
93098        break;
93099      case 124: /* selcollist ::= sclp expr as */
93100{
93101   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
93102   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
93103   sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
93104}
93105        break;
93106      case 125: /* selcollist ::= sclp STAR */
93107{
93108  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
93109  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
93110}
93111        break;
93112      case 126: /* selcollist ::= sclp nm DOT STAR */
93113{
93114  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
93115  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
93116  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
93117  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
93118}
93119        break;
93120      case 129: /* as ::= */
93121{yygotominor.yy0.n = 0;}
93122        break;
93123      case 130: /* from ::= */
93124{yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
93125        break;
93126      case 131: /* from ::= FROM seltablist */
93127{
93128  yygotominor.yy65 = yymsp[0].minor.yy65;
93129  sqlite3SrcListShiftJoinType(yygotominor.yy65);
93130}
93131        break;
93132      case 132: /* stl_prefix ::= seltablist joinop */
93133{
93134   yygotominor.yy65 = yymsp[-1].minor.yy65;
93135   if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
93136}
93137        break;
93138      case 133: /* stl_prefix ::= */
93139{yygotominor.yy65 = 0;}
93140        break;
93141      case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
93142{
93143  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);
93144  sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
93145}
93146        break;
93147      case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
93148{
93149    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);
93150  }
93151        break;
93152      case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
93153{
93154    if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
93155      yygotominor.yy65 = yymsp[-4].minor.yy65;
93156    }else{
93157      Select *pSubquery;
93158      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
93159      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,0,0,0);
93160      yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
93161    }
93162  }
93163        break;
93164      case 137: /* dbnm ::= */
93165      case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
93166{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
93167        break;
93168      case 139: /* fullname ::= nm dbnm */
93169{yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
93170        break;
93171      case 140: /* joinop ::= COMMA|JOIN */
93172{ yygotominor.yy328 = JT_INNER; }
93173        break;
93174      case 141: /* joinop ::= JOIN_KW JOIN */
93175{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
93176        break;
93177      case 142: /* joinop ::= JOIN_KW nm JOIN */
93178{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
93179        break;
93180      case 143: /* joinop ::= JOIN_KW nm nm JOIN */
93181{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
93182        break;
93183      case 144: /* on_opt ::= ON expr */
93184      case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
93185      case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
93186      case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
93187      case 236: /* case_else ::= ELSE expr */ yytestcase(yyruleno==236);
93188      case 238: /* case_operand ::= expr */ yytestcase(yyruleno==238);
93189{yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
93190        break;
93191      case 145: /* on_opt ::= */
93192      case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
93193      case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
93194      case 237: /* case_else ::= */ yytestcase(yyruleno==237);
93195      case 239: /* case_operand ::= */ yytestcase(yyruleno==239);
93196{yygotominor.yy132 = 0;}
93197        break;
93198      case 148: /* indexed_opt ::= NOT INDEXED */
93199{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
93200        break;
93201      case 149: /* using_opt ::= USING LP inscollist RP */
93202      case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
93203{yygotominor.yy408 = yymsp[-1].minor.yy408;}
93204        break;
93205      case 150: /* using_opt ::= */
93206      case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
93207{yygotominor.yy408 = 0;}
93208        break;
93209      case 152: /* orderby_opt ::= ORDER BY sortlist */
93210      case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
93211      case 240: /* exprlist ::= nexprlist */ yytestcase(yyruleno==240);
93212{yygotominor.yy14 = yymsp[0].minor.yy14;}
93213        break;
93214      case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
93215{
93216  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy132);
93217  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
93218}
93219        break;
93220      case 154: /* sortlist ::= sortitem sortorder */
93221{
93222  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy132);
93223  if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
93224}
93225        break;
93226      case 156: /* sortorder ::= ASC */
93227      case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
93228{yygotominor.yy328 = SQLITE_SO_ASC;}
93229        break;
93230      case 157: /* sortorder ::= DESC */
93231{yygotominor.yy328 = SQLITE_SO_DESC;}
93232        break;
93233      case 163: /* limit_opt ::= */
93234{yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
93235        break;
93236      case 164: /* limit_opt ::= LIMIT expr */
93237{yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
93238        break;
93239      case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
93240{yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
93241        break;
93242      case 166: /* limit_opt ::= LIMIT expr COMMA expr */
93243{yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
93244        break;
93245      case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
93246{
93247  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
93248  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
93249}
93250        break;
93251      case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
93252{
93253  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
93254  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
93255  sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
93256}
93257        break;
93258      case 171: /* setlist ::= setlist COMMA nm EQ expr */
93259{
93260  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
93261  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
93262}
93263        break;
93264      case 172: /* setlist ::= nm EQ expr */
93265{
93266  yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
93267  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
93268}
93269        break;
93270      case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
93271{sqlite3Insert(pParse, yymsp[-5].minor.yy65, yymsp[-1].minor.yy14, 0, yymsp[-4].minor.yy408, yymsp[-7].minor.yy186);}
93272        break;
93273      case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
93274{sqlite3Insert(pParse, yymsp[-2].minor.yy65, 0, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);}
93275        break;
93276      case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
93277{sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);}
93278        break;
93279      case 176: /* insert_cmd ::= INSERT orconf */
93280{yygotominor.yy186 = yymsp[0].minor.yy186;}
93281        break;
93282      case 177: /* insert_cmd ::= REPLACE */
93283{yygotominor.yy186 = OE_Replace;}
93284        break;
93285      case 178: /* itemlist ::= itemlist COMMA expr */
93286      case 242: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==242);
93287{yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
93288        break;
93289      case 179: /* itemlist ::= expr */
93290      case 243: /* nexprlist ::= expr */ yytestcase(yyruleno==243);
93291{yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
93292        break;
93293      case 182: /* inscollist ::= inscollist COMMA nm */
93294{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
93295        break;
93296      case 183: /* inscollist ::= nm */
93297{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
93298        break;
93299      case 184: /* expr ::= term */
93300      case 212: /* escape ::= ESCAPE expr */ yytestcase(yyruleno==212);
93301{yygotominor.yy346 = yymsp[0].minor.yy346;}
93302        break;
93303      case 185: /* expr ::= LP expr RP */
93304{yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
93305        break;
93306      case 186: /* term ::= NULL */
93307      case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
93308      case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
93309{spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
93310        break;
93311      case 187: /* expr ::= id */
93312      case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
93313{spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
93314        break;
93315      case 189: /* expr ::= nm DOT nm */
93316{
93317  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
93318  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
93319  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
93320  spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
93321}
93322        break;
93323      case 190: /* expr ::= nm DOT nm DOT nm */
93324{
93325  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
93326  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
93327  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
93328  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
93329  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
93330  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
93331}
93332        break;
93333      case 193: /* expr ::= REGISTER */
93334{
93335  /* When doing a nested parse, one can include terms in an expression
93336  ** that look like this:   #1 #2 ...  These terms refer to registers
93337  ** in the virtual machine.  #N is the N-th register. */
93338  if( pParse->nested==0 ){
93339    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
93340    yygotominor.yy346.pExpr = 0;
93341  }else{
93342    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
93343    if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
93344  }
93345  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
93346}
93347        break;
93348      case 194: /* expr ::= VARIABLE */
93349{
93350  spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
93351  sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
93352  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
93353}
93354        break;
93355      case 195: /* expr ::= expr COLLATE ids */
93356{
93357  yygotominor.yy346.pExpr = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
93358  yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
93359  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93360}
93361        break;
93362      case 196: /* expr ::= CAST LP expr AS typetoken RP */
93363{
93364  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
93365  spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
93366}
93367        break;
93368      case 197: /* expr ::= ID LP distinct exprlist RP */
93369{
93370  if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
93371    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
93372  }
93373  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
93374  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
93375  if( yymsp[-2].minor.yy328 && yygotominor.yy346.pExpr ){
93376    yygotominor.yy346.pExpr->flags |= EP_Distinct;
93377  }
93378}
93379        break;
93380      case 198: /* expr ::= ID LP STAR RP */
93381{
93382  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
93383  spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
93384}
93385        break;
93386      case 199: /* term ::= CTIME_KW */
93387{
93388  /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
93389  ** treated as functions that return constants */
93390  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
93391  if( yygotominor.yy346.pExpr ){
93392    yygotominor.yy346.pExpr->op = TK_CONST_FUNC;
93393  }
93394  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
93395}
93396        break;
93397      case 200: /* expr ::= expr AND expr */
93398      case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
93399      case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
93400      case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
93401      case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
93402      case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
93403      case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
93404      case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
93405{spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
93406        break;
93407      case 208: /* likeop ::= LIKE_KW */
93408      case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
93409{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 0;}
93410        break;
93411      case 209: /* likeop ::= NOT LIKE_KW */
93412      case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
93413{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 1;}
93414        break;
93415      case 213: /* escape ::= */
93416{memset(&yygotominor.yy346,0,sizeof(yygotominor.yy346));}
93417        break;
93418      case 214: /* expr ::= expr likeop expr escape */
93419{
93420  ExprList *pList;
93421  pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy346.pExpr);
93422  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy346.pExpr);
93423  if( yymsp[0].minor.yy346.pExpr ){
93424    pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
93425  }
93426  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy96.eOperator);
93427  if( yymsp[-2].minor.yy96.not ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93428  yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
93429  yygotominor.yy346.zEnd = yymsp[-1].minor.yy346.zEnd;
93430  if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
93431}
93432        break;
93433      case 215: /* expr ::= expr ISNULL|NOTNULL */
93434{spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
93435        break;
93436      case 216: /* expr ::= expr NOT NULL */
93437{spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
93438        break;
93439      case 217: /* expr ::= expr IS expr */
93440{
93441  spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
93442  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
93443}
93444        break;
93445      case 218: /* expr ::= expr IS NOT expr */
93446{
93447  spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
93448  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
93449}
93450        break;
93451      case 219: /* expr ::= NOT expr */
93452      case 220: /* expr ::= BITNOT expr */ yytestcase(yyruleno==220);
93453{spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
93454        break;
93455      case 221: /* expr ::= MINUS expr */
93456{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
93457        break;
93458      case 222: /* expr ::= PLUS expr */
93459{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
93460        break;
93461      case 225: /* expr ::= expr between_op expr AND expr */
93462{
93463  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
93464  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
93465  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
93466  if( yygotominor.yy346.pExpr ){
93467    yygotominor.yy346.pExpr->x.pList = pList;
93468  }else{
93469    sqlite3ExprListDelete(pParse->db, pList);
93470  }
93471  if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93472  yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
93473  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
93474}
93475        break;
93476      case 228: /* expr ::= expr in_op LP exprlist RP */
93477{
93478    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
93479    if( yygotominor.yy346.pExpr ){
93480      yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
93481      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93482    }else{
93483      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
93484    }
93485    if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93486    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
93487    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93488  }
93489        break;
93490      case 229: /* expr ::= LP select RP */
93491{
93492    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
93493    if( yygotominor.yy346.pExpr ){
93494      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
93495      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
93496      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93497    }else{
93498      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
93499    }
93500    yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
93501    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93502  }
93503        break;
93504      case 230: /* expr ::= expr in_op LP select RP */
93505{
93506    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
93507    if( yygotominor.yy346.pExpr ){
93508      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
93509      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
93510      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93511    }else{
93512      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
93513    }
93514    if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93515    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
93516    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93517  }
93518        break;
93519      case 231: /* expr ::= expr in_op nm dbnm */
93520{
93521    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
93522    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
93523    if( yygotominor.yy346.pExpr ){
93524      yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
93525      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
93526      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93527    }else{
93528      sqlite3SrcListDelete(pParse->db, pSrc);
93529    }
93530    if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93531    yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
93532    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];
93533  }
93534        break;
93535      case 232: /* expr ::= EXISTS LP select RP */
93536{
93537    Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
93538    if( p ){
93539      p->x.pSelect = yymsp[-1].minor.yy3;
93540      ExprSetProperty(p, EP_xIsSelect);
93541      sqlite3ExprSetHeight(pParse, p);
93542    }else{
93543      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
93544    }
93545    yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
93546    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93547  }
93548        break;
93549      case 233: /* expr ::= CASE case_operand case_exprlist case_else END */
93550{
93551  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, yymsp[-1].minor.yy132, 0);
93552  if( yygotominor.yy346.pExpr ){
93553    yygotominor.yy346.pExpr->x.pList = yymsp[-2].minor.yy14;
93554    sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93555  }else{
93556    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
93557  }
93558  yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
93559  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93560}
93561        break;
93562      case 234: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
93563{
93564  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
93565  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
93566}
93567        break;
93568      case 235: /* case_exprlist ::= WHEN expr THEN expr */
93569{
93570  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
93571  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
93572}
93573        break;
93574      case 244: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
93575{
93576  sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
93577                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy14, yymsp[-9].minor.yy328,
93578                      &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy328);
93579}
93580        break;
93581      case 245: /* uniqueflag ::= UNIQUE */
93582      case 299: /* raisetype ::= ABORT */ yytestcase(yyruleno==299);
93583{yygotominor.yy328 = OE_Abort;}
93584        break;
93585      case 246: /* uniqueflag ::= */
93586{yygotominor.yy328 = OE_None;}
93587        break;
93588      case 249: /* idxlist ::= idxlist COMMA nm collate sortorder */
93589{
93590  Expr *p = 0;
93591  if( yymsp[-1].minor.yy0.n>0 ){
93592    p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
93593    sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
93594  }
93595  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
93596  sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
93597  sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
93598  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
93599}
93600        break;
93601      case 250: /* idxlist ::= nm collate sortorder */
93602{
93603  Expr *p = 0;
93604  if( yymsp[-1].minor.yy0.n>0 ){
93605    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
93606    sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
93607  }
93608  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
93609  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
93610  sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
93611  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
93612}
93613        break;
93614      case 251: /* collate ::= */
93615{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
93616        break;
93617      case 253: /* cmd ::= DROP INDEX ifexists fullname */
93618{sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
93619        break;
93620      case 254: /* cmd ::= VACUUM */
93621      case 255: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==255);
93622{sqlite3Vacuum(pParse);}
93623        break;
93624      case 256: /* cmd ::= PRAGMA nm dbnm */
93625{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
93626        break;
93627      case 257: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
93628{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
93629        break;
93630      case 258: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
93631{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
93632        break;
93633      case 259: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
93634{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
93635        break;
93636      case 260: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
93637{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
93638        break;
93639      case 271: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
93640{
93641  Token all;
93642  all.z = yymsp[-3].minor.yy0.z;
93643  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
93644  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
93645}
93646        break;
93647      case 272: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
93648{
93649  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);
93650  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
93651}
93652        break;
93653      case 273: /* trigger_time ::= BEFORE */
93654      case 276: /* trigger_time ::= */ yytestcase(yyruleno==276);
93655{ yygotominor.yy328 = TK_BEFORE; }
93656        break;
93657      case 274: /* trigger_time ::= AFTER */
93658{ yygotominor.yy328 = TK_AFTER;  }
93659        break;
93660      case 275: /* trigger_time ::= INSTEAD OF */
93661{ yygotominor.yy328 = TK_INSTEAD;}
93662        break;
93663      case 277: /* trigger_event ::= DELETE|INSERT */
93664      case 278: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==278);
93665{yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
93666        break;
93667      case 279: /* trigger_event ::= UPDATE OF inscollist */
93668{yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
93669        break;
93670      case 282: /* when_clause ::= */
93671      case 304: /* key_opt ::= */ yytestcase(yyruleno==304);
93672{ yygotominor.yy132 = 0; }
93673        break;
93674      case 283: /* when_clause ::= WHEN expr */
93675      case 305: /* key_opt ::= KEY expr */ yytestcase(yyruleno==305);
93676{ yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
93677        break;
93678      case 284: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
93679{
93680  assert( yymsp[-2].minor.yy473!=0 );
93681  yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
93682  yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
93683  yygotominor.yy473 = yymsp[-2].minor.yy473;
93684}
93685        break;
93686      case 285: /* trigger_cmd_list ::= trigger_cmd SEMI */
93687{
93688  assert( yymsp[-1].minor.yy473!=0 );
93689  yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
93690  yygotominor.yy473 = yymsp[-1].minor.yy473;
93691}
93692        break;
93693      case 287: /* trnm ::= nm DOT nm */
93694{
93695  yygotominor.yy0 = yymsp[0].minor.yy0;
93696  sqlite3ErrorMsg(pParse,
93697        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
93698        "statements within triggers");
93699}
93700        break;
93701      case 289: /* tridxby ::= INDEXED BY nm */
93702{
93703  sqlite3ErrorMsg(pParse,
93704        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
93705        "within triggers");
93706}
93707        break;
93708      case 290: /* tridxby ::= NOT INDEXED */
93709{
93710  sqlite3ErrorMsg(pParse,
93711        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
93712        "within triggers");
93713}
93714        break;
93715      case 291: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
93716{ yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
93717        break;
93718      case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
93719{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy408, yymsp[-1].minor.yy14, 0, yymsp[-7].minor.yy186);}
93720        break;
93721      case 293: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
93722{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, 0, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
93723        break;
93724      case 294: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
93725{yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
93726        break;
93727      case 295: /* trigger_cmd ::= select */
93728{yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
93729        break;
93730      case 296: /* expr ::= RAISE LP IGNORE RP */
93731{
93732  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
93733  if( yygotominor.yy346.pExpr ){
93734    yygotominor.yy346.pExpr->affinity = OE_Ignore;
93735  }
93736  yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
93737  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93738}
93739        break;
93740      case 297: /* expr ::= RAISE LP raisetype COMMA nm RP */
93741{
93742  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
93743  if( yygotominor.yy346.pExpr ) {
93744    yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
93745  }
93746  yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
93747  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93748}
93749        break;
93750      case 298: /* raisetype ::= ROLLBACK */
93751{yygotominor.yy328 = OE_Rollback;}
93752        break;
93753      case 300: /* raisetype ::= FAIL */
93754{yygotominor.yy328 = OE_Fail;}
93755        break;
93756      case 301: /* cmd ::= DROP TRIGGER ifexists fullname */
93757{
93758  sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
93759}
93760        break;
93761      case 302: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
93762{
93763  sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
93764}
93765        break;
93766      case 303: /* cmd ::= DETACH database_kw_opt expr */
93767{
93768  sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
93769}
93770        break;
93771      case 308: /* cmd ::= REINDEX */
93772{sqlite3Reindex(pParse, 0, 0);}
93773        break;
93774      case 309: /* cmd ::= REINDEX nm dbnm */
93775{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
93776        break;
93777      case 310: /* cmd ::= ANALYZE */
93778{sqlite3Analyze(pParse, 0, 0);}
93779        break;
93780      case 311: /* cmd ::= ANALYZE nm dbnm */
93781{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
93782        break;
93783      case 312: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
93784{
93785  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
93786}
93787        break;
93788      case 313: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
93789{
93790  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
93791}
93792        break;
93793      case 314: /* add_column_fullname ::= fullname */
93794{
93795  pParse->db->lookaside.bEnabled = 0;
93796  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
93797}
93798        break;
93799      case 317: /* cmd ::= create_vtab */
93800{sqlite3VtabFinishParse(pParse,0);}
93801        break;
93802      case 318: /* cmd ::= create_vtab LP vtabarglist RP */
93803{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
93804        break;
93805      case 319: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
93806{
93807    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
93808}
93809        break;
93810      case 322: /* vtabarg ::= */
93811{sqlite3VtabArgInit(pParse);}
93812        break;
93813      case 324: /* vtabargtoken ::= ANY */
93814      case 325: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==325);
93815      case 326: /* lp ::= LP */ yytestcase(yyruleno==326);
93816{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
93817        break;
93818      default:
93819      /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
93820      /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
93821      /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
93822      /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
93823      /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
93824      /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
93825      /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
93826      /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
93827      /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
93828      /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
93829      /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
93830      /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
93831      /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
93832      /* (44) type ::= */ yytestcase(yyruleno==44);
93833      /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
93834      /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
93835      /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
93836      /* (54) carglist ::= */ yytestcase(yyruleno==54);
93837      /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
93838      /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
93839      /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
93840      /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
93841      /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
93842      /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
93843      /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
93844      /* (269) plus_opt ::= PLUS */ yytestcase(yyruleno==269);
93845      /* (270) plus_opt ::= */ yytestcase(yyruleno==270);
93846      /* (280) foreach_clause ::= */ yytestcase(yyruleno==280);
93847      /* (281) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==281);
93848      /* (288) tridxby ::= */ yytestcase(yyruleno==288);
93849      /* (306) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==306);
93850      /* (307) database_kw_opt ::= */ yytestcase(yyruleno==307);
93851      /* (315) kwcolumn_opt ::= */ yytestcase(yyruleno==315);
93852      /* (316) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==316);
93853      /* (320) vtabarglist ::= vtabarg */ yytestcase(yyruleno==320);
93854      /* (321) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==321);
93855      /* (323) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==323);
93856      /* (327) anylist ::= */ yytestcase(yyruleno==327);
93857      /* (328) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==328);
93858      /* (329) anylist ::= anylist ANY */ yytestcase(yyruleno==329);
93859        break;
93860  };
93861  yygoto = yyRuleInfo[yyruleno].lhs;
93862  yysize = yyRuleInfo[yyruleno].nrhs;
93863  yypParser->yyidx -= yysize;
93864  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
93865  if( yyact < YYNSTATE ){
93866#ifdef NDEBUG
93867    /* If we are not debugging and the reduce action popped at least
93868    ** one element off the stack, then we can push the new element back
93869    ** onto the stack here, and skip the stack overflow test in yy_shift().
93870    ** That gives a significant speed improvement. */
93871    if( yysize ){
93872      yypParser->yyidx++;
93873      yymsp -= yysize-1;
93874      yymsp->stateno = (YYACTIONTYPE)yyact;
93875      yymsp->major = (YYCODETYPE)yygoto;
93876      yymsp->minor = yygotominor;
93877    }else
93878#endif
93879    {
93880      yy_shift(yypParser,yyact,yygoto,&yygotominor);
93881    }
93882  }else{
93883    assert( yyact == YYNSTATE + YYNRULE + 1 );
93884    yy_accept(yypParser);
93885  }
93886}
93887
93888/*
93889** The following code executes when the parse fails
93890*/
93891#ifndef YYNOERRORRECOVERY
93892static void yy_parse_failed(
93893  yyParser *yypParser           /* The parser */
93894){
93895  sqlite3ParserARG_FETCH;
93896#ifndef NDEBUG
93897  if( yyTraceFILE ){
93898    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
93899  }
93900#endif
93901  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
93902  /* Here code is inserted which will be executed whenever the
93903  ** parser fails */
93904  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
93905}
93906#endif /* YYNOERRORRECOVERY */
93907
93908/*
93909** The following code executes when a syntax error first occurs.
93910*/
93911static void yy_syntax_error(
93912  yyParser *yypParser,           /* The parser */
93913  int yymajor,                   /* The major type of the error token */
93914  YYMINORTYPE yyminor            /* The minor type of the error token */
93915){
93916  sqlite3ParserARG_FETCH;
93917#define TOKEN (yyminor.yy0)
93918
93919  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
93920  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
93921  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
93922  pParse->parseError = 1;
93923  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
93924}
93925
93926/*
93927** The following is executed when the parser accepts
93928*/
93929static void yy_accept(
93930  yyParser *yypParser           /* The parser */
93931){
93932  sqlite3ParserARG_FETCH;
93933#ifndef NDEBUG
93934  if( yyTraceFILE ){
93935    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
93936  }
93937#endif
93938  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
93939  /* Here code is inserted which will be executed whenever the
93940  ** parser accepts */
93941  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
93942}
93943
93944/* The main parser program.
93945** The first argument is a pointer to a structure obtained from
93946** "sqlite3ParserAlloc" which describes the current state of the parser.
93947** The second argument is the major token number.  The third is
93948** the minor token.  The fourth optional argument is whatever the
93949** user wants (and specified in the grammar) and is available for
93950** use by the action routines.
93951**
93952** Inputs:
93953** <ul>
93954** <li> A pointer to the parser (an opaque structure.)
93955** <li> The major token number.
93956** <li> The minor token number.
93957** <li> An option argument of a grammar-specified type.
93958** </ul>
93959**
93960** Outputs:
93961** None.
93962*/
93963SQLITE_PRIVATE void sqlite3Parser(
93964  void *yyp,                   /* The parser */
93965  int yymajor,                 /* The major token code number */
93966  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
93967  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
93968){
93969  YYMINORTYPE yyminorunion;
93970  int yyact;            /* The parser action. */
93971  int yyendofinput;     /* True if we are at the end of input */
93972#ifdef YYERRORSYMBOL
93973  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
93974#endif
93975  yyParser *yypParser;  /* The parser */
93976
93977  /* (re)initialize the parser, if necessary */
93978  yypParser = (yyParser*)yyp;
93979  if( yypParser->yyidx<0 ){
93980#if YYSTACKDEPTH<=0
93981    if( yypParser->yystksz <=0 ){
93982      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
93983      yyminorunion = yyzerominor;
93984      yyStackOverflow(yypParser, &yyminorunion);
93985      return;
93986    }
93987#endif
93988    yypParser->yyidx = 0;
93989    yypParser->yyerrcnt = -1;
93990    yypParser->yystack[0].stateno = 0;
93991    yypParser->yystack[0].major = 0;
93992  }
93993  yyminorunion.yy0 = yyminor;
93994  yyendofinput = (yymajor==0);
93995  sqlite3ParserARG_STORE;
93996
93997#ifndef NDEBUG
93998  if( yyTraceFILE ){
93999    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
94000  }
94001#endif
94002
94003  do{
94004    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
94005    if( yyact<YYNSTATE ){
94006      assert( !yyendofinput );  /* Impossible to shift the $ token */
94007      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
94008      yypParser->yyerrcnt--;
94009      yymajor = YYNOCODE;
94010    }else if( yyact < YYNSTATE + YYNRULE ){
94011      yy_reduce(yypParser,yyact-YYNSTATE);
94012    }else{
94013      assert( yyact == YY_ERROR_ACTION );
94014#ifdef YYERRORSYMBOL
94015      int yymx;
94016#endif
94017#ifndef NDEBUG
94018      if( yyTraceFILE ){
94019        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
94020      }
94021#endif
94022#ifdef YYERRORSYMBOL
94023      /* A syntax error has occurred.
94024      ** The response to an error depends upon whether or not the
94025      ** grammar defines an error token "ERROR".
94026      **
94027      ** This is what we do if the grammar does define ERROR:
94028      **
94029      **  * Call the %syntax_error function.
94030      **
94031      **  * Begin popping the stack until we enter a state where
94032      **    it is legal to shift the error symbol, then shift
94033      **    the error symbol.
94034      **
94035      **  * Set the error count to three.
94036      **
94037      **  * Begin accepting and shifting new tokens.  No new error
94038      **    processing will occur until three tokens have been
94039      **    shifted successfully.
94040      **
94041      */
94042      if( yypParser->yyerrcnt<0 ){
94043        yy_syntax_error(yypParser,yymajor,yyminorunion);
94044      }
94045      yymx = yypParser->yystack[yypParser->yyidx].major;
94046      if( yymx==YYERRORSYMBOL || yyerrorhit ){
94047#ifndef NDEBUG
94048        if( yyTraceFILE ){
94049          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
94050             yyTracePrompt,yyTokenName[yymajor]);
94051        }
94052#endif
94053        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
94054        yymajor = YYNOCODE;
94055      }else{
94056         while(
94057          yypParser->yyidx >= 0 &&
94058          yymx != YYERRORSYMBOL &&
94059          (yyact = yy_find_reduce_action(
94060                        yypParser->yystack[yypParser->yyidx].stateno,
94061                        YYERRORSYMBOL)) >= YYNSTATE
94062        ){
94063          yy_pop_parser_stack(yypParser);
94064        }
94065        if( yypParser->yyidx < 0 || yymajor==0 ){
94066          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
94067          yy_parse_failed(yypParser);
94068          yymajor = YYNOCODE;
94069        }else if( yymx!=YYERRORSYMBOL ){
94070          YYMINORTYPE u2;
94071          u2.YYERRSYMDT = 0;
94072          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
94073        }
94074      }
94075      yypParser->yyerrcnt = 3;
94076      yyerrorhit = 1;
94077#elif defined(YYNOERRORRECOVERY)
94078      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
94079      ** do any kind of error recovery.  Instead, simply invoke the syntax
94080      ** error routine and continue going as if nothing had happened.
94081      **
94082      ** Applications can set this macro (for example inside %include) if
94083      ** they intend to abandon the parse upon the first syntax error seen.
94084      */
94085      yy_syntax_error(yypParser,yymajor,yyminorunion);
94086      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
94087      yymajor = YYNOCODE;
94088
94089#else  /* YYERRORSYMBOL is not defined */
94090      /* This is what we do if the grammar does not define ERROR:
94091      **
94092      **  * Report an error message, and throw away the input token.
94093      **
94094      **  * If the input token is $, then fail the parse.
94095      **
94096      ** As before, subsequent error messages are suppressed until
94097      ** three input tokens have been successfully shifted.
94098      */
94099      if( yypParser->yyerrcnt<=0 ){
94100        yy_syntax_error(yypParser,yymajor,yyminorunion);
94101      }
94102      yypParser->yyerrcnt = 3;
94103      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
94104      if( yyendofinput ){
94105        yy_parse_failed(yypParser);
94106      }
94107      yymajor = YYNOCODE;
94108#endif
94109    }
94110  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
94111  return;
94112}
94113
94114/************** End of parse.c ***********************************************/
94115/************** Begin file tokenize.c ****************************************/
94116/*
94117** 2001 September 15
94118**
94119** The author disclaims copyright to this source code.  In place of
94120** a legal notice, here is a blessing:
94121**
94122**    May you do good and not evil.
94123**    May you find forgiveness for yourself and forgive others.
94124**    May you share freely, never taking more than you give.
94125**
94126*************************************************************************
94127** An tokenizer for SQL
94128**
94129** This file contains C code that splits an SQL input string up into
94130** individual tokens and sends those tokens one-by-one over to the
94131** parser for analysis.
94132*/
94133
94134/*
94135** The charMap() macro maps alphabetic characters into their
94136** lower-case ASCII equivalent.  On ASCII machines, this is just
94137** an upper-to-lower case map.  On EBCDIC machines we also need
94138** to adjust the encoding.  Only alphabetic characters and underscores
94139** need to be translated.
94140*/
94141#ifdef SQLITE_ASCII
94142# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
94143#endif
94144#ifdef SQLITE_EBCDIC
94145# define charMap(X) ebcdicToAscii[(unsigned char)X]
94146const unsigned char ebcdicToAscii[] = {
94147/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
94148   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
94149   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
94150   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
94151   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
94152   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
94153   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
94154   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
94155   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
94156   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
94157   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
94158   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
94159   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
94160   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
94161   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
94162   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
94163   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
94164};
94165#endif
94166
94167/*
94168** The sqlite3KeywordCode function looks up an identifier to determine if
94169** it is a keyword.  If it is a keyword, the token code of that keyword is
94170** returned.  If the input is not a keyword, TK_ID is returned.
94171**
94172** The implementation of this routine was generated by a program,
94173** mkkeywordhash.h, located in the tool subdirectory of the distribution.
94174** The output of the mkkeywordhash.c program is written into a file
94175** named keywordhash.h and then included into this source file by
94176** the #include below.
94177*/
94178/************** Include keywordhash.h in the middle of tokenize.c ************/
94179/************** Begin file keywordhash.h *************************************/
94180/***** This file contains automatically generated code ******
94181**
94182** The code in this file has been automatically generated by
94183**
94184**   sqlite/tool/mkkeywordhash.c
94185**
94186** The code in this file implements a function that determines whether
94187** or not a given identifier is really an SQL keyword.  The same thing
94188** might be implemented more directly using a hand-written hash table.
94189** But by using this automatically generated code, the size of the code
94190** is substantially reduced.  This is important for embedded applications
94191** on platforms with limited memory.
94192*/
94193/* Hash score: 175 */
94194static int keywordCode(const char *z, int n){
94195  /* zText[] encodes 811 bytes of keywords in 541 bytes */
94196  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
94197  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
94198  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
94199  /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
94200  /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
94201  /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
94202  /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
94203  /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
94204  /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
94205  /*   INITIALLY                                                          */
94206  static const char zText[540] = {
94207    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
94208    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
94209    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
94210    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
94211    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
94212    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
94213    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
94214    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
94215    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
94216    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
94217    'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
94218    'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
94219    'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
94220    'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
94221    'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
94222    'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
94223    'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
94224    'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
94225    'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
94226    'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
94227    'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
94228    'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
94229    'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
94230    'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
94231    'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
94232    'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
94233    'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
94234    'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
94235    'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
94236    'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
94237  };
94238  static const unsigned char aHash[127] = {
94239      72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
94240      42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
94241     118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
94242       0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
94243       0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
94244      92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
94245      96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
94246      39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
94247      58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
94248      29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
94249  };
94250  static const unsigned char aNext[121] = {
94251       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
94252       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
94253       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
94254       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
94255       0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
94256      62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
94257      61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
94258       0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
94259     103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
94260      35,  64,   0,   0,
94261  };
94262  static const unsigned char aLen[121] = {
94263       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
94264       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
94265      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
94266       4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
94267       5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
94268       7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
94269       7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
94270       6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
94271       4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
94272       6,   4,   9,   3,
94273  };
94274  static const unsigned short int aOffset[121] = {
94275       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
94276      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
94277      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
94278     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
94279     203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
94280     248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
94281     326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
94282     387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
94283     462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
94284     521, 527, 531, 536,
94285  };
94286  static const unsigned char aCode[121] = {
94287    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
94288    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
94289    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
94290    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
94291    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
94292    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
94293    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
94294    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
94295    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
94296    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
94297    TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
94298    TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
94299    TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
94300    TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
94301    TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
94302    TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
94303    TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
94304    TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
94305    TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
94306    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
94307    TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
94308    TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
94309    TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
94310    TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
94311    TK_ALL,
94312  };
94313  int h, i;
94314  if( n<2 ) return TK_ID;
94315  h = ((charMap(z[0])*4) ^
94316      (charMap(z[n-1])*3) ^
94317      n) % 127;
94318  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
94319    if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
94320      testcase( i==0 ); /* REINDEX */
94321      testcase( i==1 ); /* INDEXED */
94322      testcase( i==2 ); /* INDEX */
94323      testcase( i==3 ); /* DESC */
94324      testcase( i==4 ); /* ESCAPE */
94325      testcase( i==5 ); /* EACH */
94326      testcase( i==6 ); /* CHECK */
94327      testcase( i==7 ); /* KEY */
94328      testcase( i==8 ); /* BEFORE */
94329      testcase( i==9 ); /* FOREIGN */
94330      testcase( i==10 ); /* FOR */
94331      testcase( i==11 ); /* IGNORE */
94332      testcase( i==12 ); /* REGEXP */
94333      testcase( i==13 ); /* EXPLAIN */
94334      testcase( i==14 ); /* INSTEAD */
94335      testcase( i==15 ); /* ADD */
94336      testcase( i==16 ); /* DATABASE */
94337      testcase( i==17 ); /* AS */
94338      testcase( i==18 ); /* SELECT */
94339      testcase( i==19 ); /* TABLE */
94340      testcase( i==20 ); /* LEFT */
94341      testcase( i==21 ); /* THEN */
94342      testcase( i==22 ); /* END */
94343      testcase( i==23 ); /* DEFERRABLE */
94344      testcase( i==24 ); /* ELSE */
94345      testcase( i==25 ); /* EXCEPT */
94346      testcase( i==26 ); /* TRANSACTION */
94347      testcase( i==27 ); /* ACTION */
94348      testcase( i==28 ); /* ON */
94349      testcase( i==29 ); /* NATURAL */
94350      testcase( i==30 ); /* ALTER */
94351      testcase( i==31 ); /* RAISE */
94352      testcase( i==32 ); /* EXCLUSIVE */
94353      testcase( i==33 ); /* EXISTS */
94354      testcase( i==34 ); /* SAVEPOINT */
94355      testcase( i==35 ); /* INTERSECT */
94356      testcase( i==36 ); /* TRIGGER */
94357      testcase( i==37 ); /* REFERENCES */
94358      testcase( i==38 ); /* CONSTRAINT */
94359      testcase( i==39 ); /* INTO */
94360      testcase( i==40 ); /* OFFSET */
94361      testcase( i==41 ); /* OF */
94362      testcase( i==42 ); /* SET */
94363      testcase( i==43 ); /* TEMPORARY */
94364      testcase( i==44 ); /* TEMP */
94365      testcase( i==45 ); /* OR */
94366      testcase( i==46 ); /* UNIQUE */
94367      testcase( i==47 ); /* QUERY */
94368      testcase( i==48 ); /* ATTACH */
94369      testcase( i==49 ); /* HAVING */
94370      testcase( i==50 ); /* GROUP */
94371      testcase( i==51 ); /* UPDATE */
94372      testcase( i==52 ); /* BEGIN */
94373      testcase( i==53 ); /* INNER */
94374      testcase( i==54 ); /* RELEASE */
94375      testcase( i==55 ); /* BETWEEN */
94376      testcase( i==56 ); /* NOTNULL */
94377      testcase( i==57 ); /* NOT */
94378      testcase( i==58 ); /* NO */
94379      testcase( i==59 ); /* NULL */
94380      testcase( i==60 ); /* LIKE */
94381      testcase( i==61 ); /* CASCADE */
94382      testcase( i==62 ); /* ASC */
94383      testcase( i==63 ); /* DELETE */
94384      testcase( i==64 ); /* CASE */
94385      testcase( i==65 ); /* COLLATE */
94386      testcase( i==66 ); /* CREATE */
94387      testcase( i==67 ); /* CURRENT_DATE */
94388      testcase( i==68 ); /* DETACH */
94389      testcase( i==69 ); /* IMMEDIATE */
94390      testcase( i==70 ); /* JOIN */
94391      testcase( i==71 ); /* INSERT */
94392      testcase( i==72 ); /* MATCH */
94393      testcase( i==73 ); /* PLAN */
94394      testcase( i==74 ); /* ANALYZE */
94395      testcase( i==75 ); /* PRAGMA */
94396      testcase( i==76 ); /* ABORT */
94397      testcase( i==77 ); /* VALUES */
94398      testcase( i==78 ); /* VIRTUAL */
94399      testcase( i==79 ); /* LIMIT */
94400      testcase( i==80 ); /* WHEN */
94401      testcase( i==81 ); /* WHERE */
94402      testcase( i==82 ); /* RENAME */
94403      testcase( i==83 ); /* AFTER */
94404      testcase( i==84 ); /* REPLACE */
94405      testcase( i==85 ); /* AND */
94406      testcase( i==86 ); /* DEFAULT */
94407      testcase( i==87 ); /* AUTOINCREMENT */
94408      testcase( i==88 ); /* TO */
94409      testcase( i==89 ); /* IN */
94410      testcase( i==90 ); /* CAST */
94411      testcase( i==91 ); /* COLUMN */
94412      testcase( i==92 ); /* COMMIT */
94413      testcase( i==93 ); /* CONFLICT */
94414      testcase( i==94 ); /* CROSS */
94415      testcase( i==95 ); /* CURRENT_TIMESTAMP */
94416      testcase( i==96 ); /* CURRENT_TIME */
94417      testcase( i==97 ); /* PRIMARY */
94418      testcase( i==98 ); /* DEFERRED */
94419      testcase( i==99 ); /* DISTINCT */
94420      testcase( i==100 ); /* IS */
94421      testcase( i==101 ); /* DROP */
94422      testcase( i==102 ); /* FAIL */
94423      testcase( i==103 ); /* FROM */
94424      testcase( i==104 ); /* FULL */
94425      testcase( i==105 ); /* GLOB */
94426      testcase( i==106 ); /* BY */
94427      testcase( i==107 ); /* IF */
94428      testcase( i==108 ); /* ISNULL */
94429      testcase( i==109 ); /* ORDER */
94430      testcase( i==110 ); /* RESTRICT */
94431      testcase( i==111 ); /* OUTER */
94432      testcase( i==112 ); /* RIGHT */
94433      testcase( i==113 ); /* ROLLBACK */
94434      testcase( i==114 ); /* ROW */
94435      testcase( i==115 ); /* UNION */
94436      testcase( i==116 ); /* USING */
94437      testcase( i==117 ); /* VACUUM */
94438      testcase( i==118 ); /* VIEW */
94439      testcase( i==119 ); /* INITIALLY */
94440      testcase( i==120 ); /* ALL */
94441      return aCode[i];
94442    }
94443  }
94444  return TK_ID;
94445}
94446SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
94447  return keywordCode((char*)z, n);
94448}
94449#define SQLITE_N_KEYWORD 121
94450
94451/************** End of keywordhash.h *****************************************/
94452/************** Continuing where we left off in tokenize.c *******************/
94453
94454
94455/*
94456** If X is a character that can be used in an identifier then
94457** IdChar(X) will be true.  Otherwise it is false.
94458**
94459** For ASCII, any character with the high-order bit set is
94460** allowed in an identifier.  For 7-bit characters,
94461** sqlite3IsIdChar[X] must be 1.
94462**
94463** For EBCDIC, the rules are more complex but have the same
94464** end result.
94465**
94466** Ticket #1066.  the SQL standard does not allow '$' in the
94467** middle of identfiers.  But many SQL implementations do.
94468** SQLite will allow '$' in identifiers for compatibility.
94469** But the feature is undocumented.
94470*/
94471#ifdef SQLITE_ASCII
94472#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
94473#endif
94474#ifdef SQLITE_EBCDIC
94475SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
94476/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
94477    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
94478    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
94479    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
94480    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
94481    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
94482    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
94483    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
94484    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
94485    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
94486    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
94487    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
94488    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
94489};
94490#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
94491#endif
94492
94493
94494/*
94495** Return the length of the token that begins at z[0].
94496** Store the token type in *tokenType before returning.
94497*/
94498SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
94499  int i, c;
94500  switch( *z ){
94501    case ' ': case '\t': case '\n': case '\f': case '\r': {
94502      testcase( z[0]==' ' );
94503      testcase( z[0]=='\t' );
94504      testcase( z[0]=='\n' );
94505      testcase( z[0]=='\f' );
94506      testcase( z[0]=='\r' );
94507      for(i=1; sqlite3Isspace(z[i]); i++){}
94508      *tokenType = TK_SPACE;
94509      return i;
94510    }
94511    case '-': {
94512      if( z[1]=='-' ){
94513        /* IMP: R-15891-05542 -- syntax diagram for comments */
94514        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
94515        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
94516        return i;
94517      }
94518      *tokenType = TK_MINUS;
94519      return 1;
94520    }
94521    case '(': {
94522      *tokenType = TK_LP;
94523      return 1;
94524    }
94525    case ')': {
94526      *tokenType = TK_RP;
94527      return 1;
94528    }
94529    case ';': {
94530      *tokenType = TK_SEMI;
94531      return 1;
94532    }
94533    case '+': {
94534      *tokenType = TK_PLUS;
94535      return 1;
94536    }
94537    case '*': {
94538      *tokenType = TK_STAR;
94539      return 1;
94540    }
94541    case '/': {
94542      if( z[1]!='*' || z[2]==0 ){
94543        *tokenType = TK_SLASH;
94544        return 1;
94545      }
94546      /* IMP: R-15891-05542 -- syntax diagram for comments */
94547      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
94548      if( c ) i++;
94549      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
94550      return i;
94551    }
94552    case '%': {
94553      *tokenType = TK_REM;
94554      return 1;
94555    }
94556    case '=': {
94557      *tokenType = TK_EQ;
94558      return 1 + (z[1]=='=');
94559    }
94560    case '<': {
94561      if( (c=z[1])=='=' ){
94562        *tokenType = TK_LE;
94563        return 2;
94564      }else if( c=='>' ){
94565        *tokenType = TK_NE;
94566        return 2;
94567      }else if( c=='<' ){
94568        *tokenType = TK_LSHIFT;
94569        return 2;
94570      }else{
94571        *tokenType = TK_LT;
94572        return 1;
94573      }
94574    }
94575    case '>': {
94576      if( (c=z[1])=='=' ){
94577        *tokenType = TK_GE;
94578        return 2;
94579      }else if( c=='>' ){
94580        *tokenType = TK_RSHIFT;
94581        return 2;
94582      }else{
94583        *tokenType = TK_GT;
94584        return 1;
94585      }
94586    }
94587    case '!': {
94588      if( z[1]!='=' ){
94589        *tokenType = TK_ILLEGAL;
94590        return 2;
94591      }else{
94592        *tokenType = TK_NE;
94593        return 2;
94594      }
94595    }
94596    case '|': {
94597      if( z[1]!='|' ){
94598        *tokenType = TK_BITOR;
94599        return 1;
94600      }else{
94601        *tokenType = TK_CONCAT;
94602        return 2;
94603      }
94604    }
94605    case ',': {
94606      *tokenType = TK_COMMA;
94607      return 1;
94608    }
94609    case '&': {
94610      *tokenType = TK_BITAND;
94611      return 1;
94612    }
94613    case '~': {
94614      *tokenType = TK_BITNOT;
94615      return 1;
94616    }
94617    case '`':
94618    case '\'':
94619    case '"': {
94620      int delim = z[0];
94621      testcase( delim=='`' );
94622      testcase( delim=='\'' );
94623      testcase( delim=='"' );
94624      for(i=1; (c=z[i])!=0; i++){
94625        if( c==delim ){
94626          if( z[i+1]==delim ){
94627            i++;
94628          }else{
94629            break;
94630          }
94631        }
94632      }
94633      if( c=='\'' ){
94634        *tokenType = TK_STRING;
94635        return i+1;
94636      }else if( c!=0 ){
94637        *tokenType = TK_ID;
94638        return i+1;
94639      }else{
94640        *tokenType = TK_ILLEGAL;
94641        return i;
94642      }
94643    }
94644    case '.': {
94645#ifndef SQLITE_OMIT_FLOATING_POINT
94646      if( !sqlite3Isdigit(z[1]) )
94647#endif
94648      {
94649        *tokenType = TK_DOT;
94650        return 1;
94651      }
94652      /* If the next character is a digit, this is a floating point
94653      ** number that begins with ".".  Fall thru into the next case */
94654    }
94655    case '0': case '1': case '2': case '3': case '4':
94656    case '5': case '6': case '7': case '8': case '9': {
94657      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
94658      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
94659      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
94660      testcase( z[0]=='9' );
94661      *tokenType = TK_INTEGER;
94662      for(i=0; sqlite3Isdigit(z[i]); i++){}
94663#ifndef SQLITE_OMIT_FLOATING_POINT
94664      if( z[i]=='.' ){
94665        i++;
94666        while( sqlite3Isdigit(z[i]) ){ i++; }
94667        *tokenType = TK_FLOAT;
94668      }
94669      if( (z[i]=='e' || z[i]=='E') &&
94670           ( sqlite3Isdigit(z[i+1])
94671            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
94672           )
94673      ){
94674        i += 2;
94675        while( sqlite3Isdigit(z[i]) ){ i++; }
94676        *tokenType = TK_FLOAT;
94677      }
94678#endif
94679      while( IdChar(z[i]) ){
94680        *tokenType = TK_ILLEGAL;
94681        i++;
94682      }
94683      return i;
94684    }
94685    case '[': {
94686      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
94687      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
94688      return i;
94689    }
94690    case '?': {
94691      *tokenType = TK_VARIABLE;
94692      for(i=1; sqlite3Isdigit(z[i]); i++){}
94693      return i;
94694    }
94695    case '#': {
94696      for(i=1; sqlite3Isdigit(z[i]); i++){}
94697      if( i>1 ){
94698        /* Parameters of the form #NNN (where NNN is a number) are used
94699        ** internally by sqlite3NestedParse.  */
94700        *tokenType = TK_REGISTER;
94701        return i;
94702      }
94703      /* Fall through into the next case if the '#' is not followed by
94704      ** a digit. Try to match #AAAA where AAAA is a parameter name. */
94705    }
94706#ifndef SQLITE_OMIT_TCL_VARIABLE
94707    case '$':
94708#endif
94709    case '@':  /* For compatibility with MS SQL Server */
94710    case ':': {
94711      int n = 0;
94712      testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
94713      *tokenType = TK_VARIABLE;
94714      for(i=1; (c=z[i])!=0; i++){
94715        if( IdChar(c) ){
94716          n++;
94717#ifndef SQLITE_OMIT_TCL_VARIABLE
94718        }else if( c=='(' && n>0 ){
94719          do{
94720            i++;
94721          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
94722          if( c==')' ){
94723            i++;
94724          }else{
94725            *tokenType = TK_ILLEGAL;
94726          }
94727          break;
94728        }else if( c==':' && z[i+1]==':' ){
94729          i++;
94730#endif
94731        }else{
94732          break;
94733        }
94734      }
94735      if( n==0 ) *tokenType = TK_ILLEGAL;
94736      return i;
94737    }
94738#ifndef SQLITE_OMIT_BLOB_LITERAL
94739    case 'x': case 'X': {
94740      testcase( z[0]=='x' ); testcase( z[0]=='X' );
94741      if( z[1]=='\'' ){
94742        *tokenType = TK_BLOB;
94743        for(i=2; (c=z[i])!=0 && c!='\''; i++){
94744          if( !sqlite3Isxdigit(c) ){
94745            *tokenType = TK_ILLEGAL;
94746          }
94747        }
94748        if( i%2 || !c ) *tokenType = TK_ILLEGAL;
94749        if( c ) i++;
94750        return i;
94751      }
94752      /* Otherwise fall through to the next case */
94753    }
94754#endif
94755    default: {
94756      if( !IdChar(*z) ){
94757        break;
94758      }
94759      for(i=1; IdChar(z[i]); i++){}
94760      *tokenType = keywordCode((char*)z, i);
94761      return i;
94762    }
94763  }
94764  *tokenType = TK_ILLEGAL;
94765  return 1;
94766}
94767
94768/*
94769** Run the parser on the given SQL string.  The parser structure is
94770** passed in.  An SQLITE_ status code is returned.  If an error occurs
94771** then an and attempt is made to write an error message into
94772** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
94773** error message.
94774*/
94775SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
94776  int nErr = 0;                   /* Number of errors encountered */
94777  int i;                          /* Loop counter */
94778  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
94779  int tokenType;                  /* type of the next token */
94780  int lastTokenParsed = -1;       /* type of the previous token */
94781  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
94782  sqlite3 *db = pParse->db;       /* The database connection */
94783  int mxSqlLen;                   /* Max length of an SQL string */
94784
94785
94786  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
94787  if( db->activeVdbeCnt==0 ){
94788    db->u1.isInterrupted = 0;
94789  }
94790  pParse->rc = SQLITE_OK;
94791  pParse->zTail = zSql;
94792  i = 0;
94793  assert( pzErrMsg!=0 );
94794  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
94795  if( pEngine==0 ){
94796    db->mallocFailed = 1;
94797    return SQLITE_NOMEM;
94798  }
94799  assert( pParse->pNewTable==0 );
94800  assert( pParse->pNewTrigger==0 );
94801  assert( pParse->nVar==0 );
94802  assert( pParse->nVarExpr==0 );
94803  assert( pParse->nVarExprAlloc==0 );
94804  assert( pParse->apVarExpr==0 );
94805  enableLookaside = db->lookaside.bEnabled;
94806  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
94807  while( !db->mallocFailed && zSql[i]!=0 ){
94808    assert( i>=0 );
94809    pParse->sLastToken.z = &zSql[i];
94810    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
94811    i += pParse->sLastToken.n;
94812    if( i>mxSqlLen ){
94813      pParse->rc = SQLITE_TOOBIG;
94814      break;
94815    }
94816    switch( tokenType ){
94817      case TK_SPACE: {
94818        if( db->u1.isInterrupted ){
94819          sqlite3ErrorMsg(pParse, "interrupt");
94820          pParse->rc = SQLITE_INTERRUPT;
94821          goto abort_parse;
94822        }
94823        break;
94824      }
94825      case TK_ILLEGAL: {
94826        sqlite3DbFree(db, *pzErrMsg);
94827        *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
94828                        &pParse->sLastToken);
94829        nErr++;
94830        goto abort_parse;
94831      }
94832      case TK_SEMI: {
94833        pParse->zTail = &zSql[i];
94834        /* Fall thru into the default case */
94835      }
94836      default: {
94837        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
94838        lastTokenParsed = tokenType;
94839        if( pParse->rc!=SQLITE_OK ){
94840          goto abort_parse;
94841        }
94842        break;
94843      }
94844    }
94845  }
94846abort_parse:
94847  if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
94848    if( lastTokenParsed!=TK_SEMI ){
94849      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
94850      pParse->zTail = &zSql[i];
94851    }
94852    sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
94853  }
94854#ifdef YYTRACKMAXSTACKDEPTH
94855  sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
94856      sqlite3ParserStackPeak(pEngine)
94857  );
94858#endif /* YYDEBUG */
94859  sqlite3ParserFree(pEngine, sqlite3_free);
94860  db->lookaside.bEnabled = enableLookaside;
94861  if( db->mallocFailed ){
94862    pParse->rc = SQLITE_NOMEM;
94863  }
94864  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
94865    sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
94866  }
94867  assert( pzErrMsg!=0 );
94868  if( pParse->zErrMsg ){
94869    *pzErrMsg = pParse->zErrMsg;
94870    pParse->zErrMsg = 0;
94871    nErr++;
94872  }
94873  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
94874    sqlite3VdbeDelete(pParse->pVdbe);
94875    pParse->pVdbe = 0;
94876  }
94877#ifndef SQLITE_OMIT_SHARED_CACHE
94878  if( pParse->nested==0 ){
94879    sqlite3DbFree(db, pParse->aTableLock);
94880    pParse->aTableLock = 0;
94881    pParse->nTableLock = 0;
94882  }
94883#endif
94884#ifndef SQLITE_OMIT_VIRTUALTABLE
94885  sqlite3DbFree(db, pParse->apVtabLock);
94886#endif
94887
94888  if( !IN_DECLARE_VTAB ){
94889    /* If the pParse->declareVtab flag is set, do not delete any table
94890    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
94891    ** will take responsibility for freeing the Table structure.
94892    */
94893    sqlite3DeleteTable(pParse->pNewTable);
94894  }
94895
94896  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
94897  sqlite3DbFree(db, pParse->apVarExpr);
94898  sqlite3DbFree(db, pParse->aAlias);
94899  while( pParse->pAinc ){
94900    AutoincInfo *p = pParse->pAinc;
94901    pParse->pAinc = p->pNext;
94902    sqlite3DbFree(db, p);
94903  }
94904  while( pParse->pZombieTab ){
94905    Table *p = pParse->pZombieTab;
94906    pParse->pZombieTab = p->pNextZombie;
94907    sqlite3DeleteTable(p);
94908  }
94909  if( nErr>0 && pParse->rc==SQLITE_OK ){
94910    pParse->rc = SQLITE_ERROR;
94911  }
94912  return nErr;
94913}
94914
94915/************** End of tokenize.c ********************************************/
94916/************** Begin file complete.c ****************************************/
94917/*
94918** 2001 September 15
94919**
94920** The author disclaims copyright to this source code.  In place of
94921** a legal notice, here is a blessing:
94922**
94923**    May you do good and not evil.
94924**    May you find forgiveness for yourself and forgive others.
94925**    May you share freely, never taking more than you give.
94926**
94927*************************************************************************
94928** An tokenizer for SQL
94929**
94930** This file contains C code that implements the sqlite3_complete() API.
94931** This code used to be part of the tokenizer.c source file.  But by
94932** separating it out, the code will be automatically omitted from
94933** static links that do not use it.
94934*/
94935#ifndef SQLITE_OMIT_COMPLETE
94936
94937/*
94938** This is defined in tokenize.c.  We just have to import the definition.
94939*/
94940#ifndef SQLITE_AMALGAMATION
94941#ifdef SQLITE_ASCII
94942#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
94943#endif
94944#ifdef SQLITE_EBCDIC
94945SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
94946#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
94947#endif
94948#endif /* SQLITE_AMALGAMATION */
94949
94950
94951/*
94952** Token types used by the sqlite3_complete() routine.  See the header
94953** comments on that procedure for additional information.
94954*/
94955#define tkSEMI    0
94956#define tkWS      1
94957#define tkOTHER   2
94958#ifndef SQLITE_OMIT_TRIGGER
94959#define tkEXPLAIN 3
94960#define tkCREATE  4
94961#define tkTEMP    5
94962#define tkTRIGGER 6
94963#define tkEND     7
94964#endif
94965
94966/*
94967** Return TRUE if the given SQL string ends in a semicolon.
94968**
94969** Special handling is require for CREATE TRIGGER statements.
94970** Whenever the CREATE TRIGGER keywords are seen, the statement
94971** must end with ";END;".
94972**
94973** This implementation uses a state machine with 8 states:
94974**
94975**   (0) INVALID   We have not yet seen a non-whitespace character.
94976**
94977**   (1) START     At the beginning or end of an SQL statement.  This routine
94978**                 returns 1 if it ends in the START state and 0 if it ends
94979**                 in any other state.
94980**
94981**   (2) NORMAL    We are in the middle of statement which ends with a single
94982**                 semicolon.
94983**
94984**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
94985**                 a statement.
94986**
94987**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
94988**                 statement, possibly preceeded by EXPLAIN and/or followed by
94989**                 TEMP or TEMPORARY
94990**
94991**   (5) TRIGGER   We are in the middle of a trigger definition that must be
94992**                 ended by a semicolon, the keyword END, and another semicolon.
94993**
94994**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
94995**                 the end of a trigger definition.
94996**
94997**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
94998**                 of a trigger difinition.
94999**
95000** Transitions between states above are determined by tokens extracted
95001** from the input.  The following tokens are significant:
95002**
95003**   (0) tkSEMI      A semicolon.
95004**   (1) tkWS        Whitespace.
95005**   (2) tkOTHER     Any other SQL token.
95006**   (3) tkEXPLAIN   The "explain" keyword.
95007**   (4) tkCREATE    The "create" keyword.
95008**   (5) tkTEMP      The "temp" or "temporary" keyword.
95009**   (6) tkTRIGGER   The "trigger" keyword.
95010**   (7) tkEND       The "end" keyword.
95011**
95012** Whitespace never causes a state transition and is always ignored.
95013** This means that a SQL string of all whitespace is invalid.
95014**
95015** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
95016** to recognize the end of a trigger can be omitted.  All we have to do
95017** is look for a semicolon that is not part of an string or comment.
95018*/
95019SQLITE_API int sqlite3_complete(const char *zSql){
95020  u8 state = 0;   /* Current state, using numbers defined in header comment */
95021  u8 token;       /* Value of the next token */
95022
95023#ifndef SQLITE_OMIT_TRIGGER
95024  /* A complex statement machine used to detect the end of a CREATE TRIGGER
95025  ** statement.  This is the normal case.
95026  */
95027  static const u8 trans[8][8] = {
95028                     /* Token:                                                */
95029     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
95030     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
95031     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
95032     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
95033     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
95034     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
95035     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
95036     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
95037     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
95038  };
95039#else
95040  /* If triggers are not supported by this compile then the statement machine
95041  ** used to detect the end of a statement is much simplier
95042  */
95043  static const u8 trans[3][3] = {
95044                     /* Token:           */
95045     /* State:       **  SEMI  WS  OTHER */
95046     /* 0 INVALID: */ {    1,  0,     2, },
95047     /* 1   START: */ {    1,  1,     2, },
95048     /* 2  NORMAL: */ {    1,  2,     2, },
95049  };
95050#endif /* SQLITE_OMIT_TRIGGER */
95051
95052  while( *zSql ){
95053    switch( *zSql ){
95054      case ';': {  /* A semicolon */
95055        token = tkSEMI;
95056        break;
95057      }
95058      case ' ':
95059      case '\r':
95060      case '\t':
95061      case '\n':
95062      case '\f': {  /* White space is ignored */
95063        token = tkWS;
95064        break;
95065      }
95066      case '/': {   /* C-style comments */
95067        if( zSql[1]!='*' ){
95068          token = tkOTHER;
95069          break;
95070        }
95071        zSql += 2;
95072        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
95073        if( zSql[0]==0 ) return 0;
95074        zSql++;
95075        token = tkWS;
95076        break;
95077      }
95078      case '-': {   /* SQL-style comments from "--" to end of line */
95079        if( zSql[1]!='-' ){
95080          token = tkOTHER;
95081          break;
95082        }
95083        while( *zSql && *zSql!='\n' ){ zSql++; }
95084        if( *zSql==0 ) return state==1;
95085        token = tkWS;
95086        break;
95087      }
95088      case '[': {   /* Microsoft-style identifiers in [...] */
95089        zSql++;
95090        while( *zSql && *zSql!=']' ){ zSql++; }
95091        if( *zSql==0 ) return 0;
95092        token = tkOTHER;
95093        break;
95094      }
95095      case '`':     /* Grave-accent quoted symbols used by MySQL */
95096      case '"':     /* single- and double-quoted strings */
95097      case '\'': {
95098        int c = *zSql;
95099        zSql++;
95100        while( *zSql && *zSql!=c ){ zSql++; }
95101        if( *zSql==0 ) return 0;
95102        token = tkOTHER;
95103        break;
95104      }
95105      default: {
95106#ifdef SQLITE_EBCDIC
95107        unsigned char c;
95108#endif
95109        if( IdChar((u8)*zSql) ){
95110          /* Keywords and unquoted identifiers */
95111          int nId;
95112          for(nId=1; IdChar(zSql[nId]); nId++){}
95113#ifdef SQLITE_OMIT_TRIGGER
95114          token = tkOTHER;
95115#else
95116          switch( *zSql ){
95117            case 'c': case 'C': {
95118              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
95119                token = tkCREATE;
95120              }else{
95121                token = tkOTHER;
95122              }
95123              break;
95124            }
95125            case 't': case 'T': {
95126              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
95127                token = tkTRIGGER;
95128              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
95129                token = tkTEMP;
95130              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
95131                token = tkTEMP;
95132              }else{
95133                token = tkOTHER;
95134              }
95135              break;
95136            }
95137            case 'e':  case 'E': {
95138              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
95139                token = tkEND;
95140              }else
95141#ifndef SQLITE_OMIT_EXPLAIN
95142              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
95143                token = tkEXPLAIN;
95144              }else
95145#endif
95146              {
95147                token = tkOTHER;
95148              }
95149              break;
95150            }
95151            default: {
95152              token = tkOTHER;
95153              break;
95154            }
95155          }
95156#endif /* SQLITE_OMIT_TRIGGER */
95157          zSql += nId-1;
95158        }else{
95159          /* Operators and special symbols */
95160          token = tkOTHER;
95161        }
95162        break;
95163      }
95164    }
95165    state = trans[state][token];
95166    zSql++;
95167  }
95168  return state==1;
95169}
95170
95171#ifndef SQLITE_OMIT_UTF16
95172/*
95173** This routine is the same as the sqlite3_complete() routine described
95174** above, except that the parameter is required to be UTF-16 encoded, not
95175** UTF-8.
95176*/
95177SQLITE_API int sqlite3_complete16(const void *zSql){
95178  sqlite3_value *pVal;
95179  char const *zSql8;
95180  int rc = SQLITE_NOMEM;
95181
95182#ifndef SQLITE_OMIT_AUTOINIT
95183  rc = sqlite3_initialize();
95184  if( rc ) return rc;
95185#endif
95186  pVal = sqlite3ValueNew(0);
95187  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
95188  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
95189  if( zSql8 ){
95190    rc = sqlite3_complete(zSql8);
95191  }else{
95192    rc = SQLITE_NOMEM;
95193  }
95194  sqlite3ValueFree(pVal);
95195  return sqlite3ApiExit(0, rc);
95196}
95197#endif /* SQLITE_OMIT_UTF16 */
95198#endif /* SQLITE_OMIT_COMPLETE */
95199
95200/************** End of complete.c ********************************************/
95201/************** Begin file main.c ********************************************/
95202/*
95203** 2001 September 15
95204**
95205** The author disclaims copyright to this source code.  In place of
95206** a legal notice, here is a blessing:
95207**
95208**    May you do good and not evil.
95209**    May you find forgiveness for yourself and forgive others.
95210**    May you share freely, never taking more than you give.
95211**
95212*************************************************************************
95213** Main file for the SQLite library.  The routines in this file
95214** implement the programmer interface to the library.  Routines in
95215** other files are for internal use by SQLite and should not be
95216** accessed by users of the library.
95217*/
95218
95219#ifdef SQLITE_ENABLE_FTS3
95220/************** Include fts3.h in the middle of main.c ***********************/
95221/************** Begin file fts3.h ********************************************/
95222/*
95223** 2006 Oct 10
95224**
95225** The author disclaims copyright to this source code.  In place of
95226** a legal notice, here is a blessing:
95227**
95228**    May you do good and not evil.
95229**    May you find forgiveness for yourself and forgive others.
95230**    May you share freely, never taking more than you give.
95231**
95232******************************************************************************
95233**
95234** This header file is used by programs that want to link against the
95235** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
95236*/
95237
95238#if 0
95239extern "C" {
95240#endif  /* __cplusplus */
95241
95242SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
95243
95244#if 0
95245}  /* extern "C" */
95246#endif  /* __cplusplus */
95247
95248/************** End of fts3.h ************************************************/
95249/************** Continuing where we left off in main.c ***********************/
95250#endif
95251#ifdef SQLITE_ENABLE_RTREE
95252/************** Include rtree.h in the middle of main.c **********************/
95253/************** Begin file rtree.h *******************************************/
95254/*
95255** 2008 May 26
95256**
95257** The author disclaims copyright to this source code.  In place of
95258** a legal notice, here is a blessing:
95259**
95260**    May you do good and not evil.
95261**    May you find forgiveness for yourself and forgive others.
95262**    May you share freely, never taking more than you give.
95263**
95264******************************************************************************
95265**
95266** This header file is used by programs that want to link against the
95267** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
95268*/
95269
95270#if 0
95271extern "C" {
95272#endif  /* __cplusplus */
95273
95274SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
95275
95276#if 0
95277}  /* extern "C" */
95278#endif  /* __cplusplus */
95279
95280/************** End of rtree.h ***********************************************/
95281/************** Continuing where we left off in main.c ***********************/
95282#endif
95283#ifdef SQLITE_ENABLE_ICU
95284/************** Include sqliteicu.h in the middle of main.c ******************/
95285/************** Begin file sqliteicu.h ***************************************/
95286/*
95287** 2008 May 26
95288**
95289** The author disclaims copyright to this source code.  In place of
95290** a legal notice, here is a blessing:
95291**
95292**    May you do good and not evil.
95293**    May you find forgiveness for yourself and forgive others.
95294**    May you share freely, never taking more than you give.
95295**
95296******************************************************************************
95297**
95298** This header file is used by programs that want to link against the
95299** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
95300*/
95301
95302#if 0
95303extern "C" {
95304#endif  /* __cplusplus */
95305
95306SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
95307
95308#if 0
95309}  /* extern "C" */
95310#endif  /* __cplusplus */
95311
95312
95313/************** End of sqliteicu.h *******************************************/
95314/************** Continuing where we left off in main.c ***********************/
95315#endif
95316
95317/*
95318** The version of the library
95319*/
95320#ifndef SQLITE_AMALGAMATION
95321SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
95322#endif
95323SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
95324SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
95325SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
95326SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
95327
95328#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
95329/*
95330** If the following function pointer is not NULL and if
95331** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
95332** I/O active are written using this function.  These messages
95333** are intended for debugging activity only.
95334*/
95335SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
95336#endif
95337
95338/*
95339** If the following global variable points to a string which is the
95340** name of a directory, then that directory will be used to store
95341** temporary files.
95342**
95343** See also the "PRAGMA temp_store_directory" SQL command.
95344*/
95345SQLITE_API char *sqlite3_temp_directory = 0;
95346
95347/*
95348** Initialize SQLite.
95349**
95350** This routine must be called to initialize the memory allocation,
95351** VFS, and mutex subsystems prior to doing any serious work with
95352** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
95353** this routine will be called automatically by key routines such as
95354** sqlite3_open().
95355**
95356** This routine is a no-op except on its very first call for the process,
95357** or for the first call after a call to sqlite3_shutdown.
95358**
95359** The first thread to call this routine runs the initialization to
95360** completion.  If subsequent threads call this routine before the first
95361** thread has finished the initialization process, then the subsequent
95362** threads must block until the first thread finishes with the initialization.
95363**
95364** The first thread might call this routine recursively.  Recursive
95365** calls to this routine should not block, of course.  Otherwise the
95366** initialization process would never complete.
95367**
95368** Let X be the first thread to enter this routine.  Let Y be some other
95369** thread.  Then while the initial invocation of this routine by X is
95370** incomplete, it is required that:
95371**
95372**    *  Calls to this routine from Y must block until the outer-most
95373**       call by X completes.
95374**
95375**    *  Recursive calls to this routine from thread X return immediately
95376**       without blocking.
95377*/
95378SQLITE_API int sqlite3_initialize(void){
95379  sqlite3_mutex *pMaster;                      /* The main static mutex */
95380  int rc;                                      /* Result code */
95381
95382#ifdef SQLITE_OMIT_WSD
95383  rc = sqlite3_wsd_init(4096, 24);
95384  if( rc!=SQLITE_OK ){
95385    return rc;
95386  }
95387#endif
95388
95389  /* If SQLite is already completely initialized, then this call
95390  ** to sqlite3_initialize() should be a no-op.  But the initialization
95391  ** must be complete.  So isInit must not be set until the very end
95392  ** of this routine.
95393  */
95394  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
95395
95396  /* Make sure the mutex subsystem is initialized.  If unable to
95397  ** initialize the mutex subsystem, return early with the error.
95398  ** If the system is so sick that we are unable to allocate a mutex,
95399  ** there is not much SQLite is going to be able to do.
95400  **
95401  ** The mutex subsystem must take care of serializing its own
95402  ** initialization.
95403  */
95404  rc = sqlite3MutexInit();
95405  if( rc ) return rc;
95406
95407  /* Initialize the malloc() system and the recursive pInitMutex mutex.
95408  ** This operation is protected by the STATIC_MASTER mutex.  Note that
95409  ** MutexAlloc() is called for a static mutex prior to initializing the
95410  ** malloc subsystem - this implies that the allocation of a static
95411  ** mutex must not require support from the malloc subsystem.
95412  */
95413  pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
95414  sqlite3_mutex_enter(pMaster);
95415  sqlite3GlobalConfig.isMutexInit = 1;
95416  if( !sqlite3GlobalConfig.isMallocInit ){
95417    rc = sqlite3MallocInit();
95418  }
95419  if( rc==SQLITE_OK ){
95420    sqlite3GlobalConfig.isMallocInit = 1;
95421    if( !sqlite3GlobalConfig.pInitMutex ){
95422      sqlite3GlobalConfig.pInitMutex =
95423           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
95424      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
95425        rc = SQLITE_NOMEM;
95426      }
95427    }
95428  }
95429  if( rc==SQLITE_OK ){
95430    sqlite3GlobalConfig.nRefInitMutex++;
95431  }
95432  sqlite3_mutex_leave(pMaster);
95433
95434  /* If rc is not SQLITE_OK at this point, then either the malloc
95435  ** subsystem could not be initialized or the system failed to allocate
95436  ** the pInitMutex mutex. Return an error in either case.  */
95437  if( rc!=SQLITE_OK ){
95438    return rc;
95439  }
95440
95441  /* Do the rest of the initialization under the recursive mutex so
95442  ** that we will be able to handle recursive calls into
95443  ** sqlite3_initialize().  The recursive calls normally come through
95444  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
95445  ** recursive calls might also be possible.
95446  */
95447  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
95448  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
95449    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
95450    sqlite3GlobalConfig.inProgress = 1;
95451    memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
95452    sqlite3RegisterGlobalFunctions();
95453    if( sqlite3GlobalConfig.isPCacheInit==0 ){
95454      rc = sqlite3PcacheInitialize();
95455    }
95456    if( rc==SQLITE_OK ){
95457      sqlite3GlobalConfig.isPCacheInit = 1;
95458      rc = sqlite3OsInit();
95459    }
95460    if( rc==SQLITE_OK ){
95461      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
95462          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
95463      sqlite3GlobalConfig.isInit = 1;
95464    }
95465    sqlite3GlobalConfig.inProgress = 0;
95466  }
95467  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
95468
95469  /* Go back under the static mutex and clean up the recursive
95470  ** mutex to prevent a resource leak.
95471  */
95472  sqlite3_mutex_enter(pMaster);
95473  sqlite3GlobalConfig.nRefInitMutex--;
95474  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
95475    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
95476    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
95477    sqlite3GlobalConfig.pInitMutex = 0;
95478  }
95479  sqlite3_mutex_leave(pMaster);
95480
95481  /* The following is just a sanity check to make sure SQLite has
95482  ** been compiled correctly.  It is important to run this code, but
95483  ** we don't want to run it too often and soak up CPU cycles for no
95484  ** reason.  So we run it once during initialization.
95485  */
95486#ifndef NDEBUG
95487#ifndef SQLITE_OMIT_FLOATING_POINT
95488  /* This section of code's only "output" is via assert() statements. */
95489  if ( rc==SQLITE_OK ){
95490    u64 x = (((u64)1)<<63)-1;
95491    double y;
95492    assert(sizeof(x)==8);
95493    assert(sizeof(x)==sizeof(y));
95494    memcpy(&y, &x, 8);
95495    assert( sqlite3IsNaN(y) );
95496  }
95497#endif
95498#endif
95499
95500  return rc;
95501}
95502
95503/*
95504** Undo the effects of sqlite3_initialize().  Must not be called while
95505** there are outstanding database connections or memory allocations or
95506** while any part of SQLite is otherwise in use in any thread.  This
95507** routine is not threadsafe.  But it is safe to invoke this routine
95508** on when SQLite is already shut down.  If SQLite is already shut down
95509** when this routine is invoked, then this routine is a harmless no-op.
95510*/
95511SQLITE_API int sqlite3_shutdown(void){
95512  if( sqlite3GlobalConfig.isInit ){
95513    sqlite3_os_end();
95514    sqlite3_reset_auto_extension();
95515    sqlite3GlobalConfig.isInit = 0;
95516  }
95517  if( sqlite3GlobalConfig.isPCacheInit ){
95518    sqlite3PcacheShutdown();
95519    sqlite3GlobalConfig.isPCacheInit = 0;
95520  }
95521  if( sqlite3GlobalConfig.isMallocInit ){
95522    sqlite3MallocEnd();
95523    sqlite3GlobalConfig.isMallocInit = 0;
95524  }
95525  if( sqlite3GlobalConfig.isMutexInit ){
95526    sqlite3MutexEnd();
95527    sqlite3GlobalConfig.isMutexInit = 0;
95528  }
95529
95530  return SQLITE_OK;
95531}
95532
95533/*
95534** This API allows applications to modify the global configuration of
95535** the SQLite library at run-time.
95536**
95537** This routine should only be called when there are no outstanding
95538** database connections or memory allocations.  This routine is not
95539** threadsafe.  Failure to heed these warnings can lead to unpredictable
95540** behavior.
95541*/
95542SQLITE_API int sqlite3_config(int op, ...){
95543  va_list ap;
95544  int rc = SQLITE_OK;
95545
95546  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
95547  ** the SQLite library is in use. */
95548  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE;
95549
95550  va_start(ap, op);
95551  switch( op ){
95552
95553    /* Mutex configuration options are only available in a threadsafe
95554    ** compile.
95555    */
95556#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
95557    case SQLITE_CONFIG_SINGLETHREAD: {
95558      /* Disable all mutexing */
95559      sqlite3GlobalConfig.bCoreMutex = 0;
95560      sqlite3GlobalConfig.bFullMutex = 0;
95561      break;
95562    }
95563    case SQLITE_CONFIG_MULTITHREAD: {
95564      /* Disable mutexing of database connections */
95565      /* Enable mutexing of core data structures */
95566      sqlite3GlobalConfig.bCoreMutex = 1;
95567      sqlite3GlobalConfig.bFullMutex = 0;
95568      break;
95569    }
95570    case SQLITE_CONFIG_SERIALIZED: {
95571      /* Enable all mutexing */
95572      sqlite3GlobalConfig.bCoreMutex = 1;
95573      sqlite3GlobalConfig.bFullMutex = 1;
95574      break;
95575    }
95576    case SQLITE_CONFIG_MUTEX: {
95577      /* Specify an alternative mutex implementation */
95578      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
95579      break;
95580    }
95581    case SQLITE_CONFIG_GETMUTEX: {
95582      /* Retrieve the current mutex implementation */
95583      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
95584      break;
95585    }
95586#endif
95587
95588
95589    case SQLITE_CONFIG_MALLOC: {
95590      /* Specify an alternative malloc implementation */
95591      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
95592      break;
95593    }
95594    case SQLITE_CONFIG_GETMALLOC: {
95595      /* Retrieve the current malloc() implementation */
95596      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
95597      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
95598      break;
95599    }
95600    case SQLITE_CONFIG_MEMSTATUS: {
95601      /* Enable or disable the malloc status collection */
95602      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
95603      break;
95604    }
95605    case SQLITE_CONFIG_SCRATCH: {
95606      /* Designate a buffer for scratch memory space */
95607      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
95608      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
95609      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
95610      break;
95611    }
95612    case SQLITE_CONFIG_PAGECACHE: {
95613      /* Designate a buffer for page cache memory space */
95614      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
95615      sqlite3GlobalConfig.szPage = va_arg(ap, int);
95616      sqlite3GlobalConfig.nPage = va_arg(ap, int);
95617      break;
95618    }
95619
95620    case SQLITE_CONFIG_PCACHE: {
95621      /* Specify an alternative page cache implementation */
95622      sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
95623      break;
95624    }
95625
95626    case SQLITE_CONFIG_GETPCACHE: {
95627      if( sqlite3GlobalConfig.pcache.xInit==0 ){
95628        sqlite3PCacheSetDefault();
95629      }
95630      *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
95631      break;
95632    }
95633
95634#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
95635    case SQLITE_CONFIG_HEAP: {
95636      /* Designate a buffer for heap memory space */
95637      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
95638      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
95639      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
95640
95641      if( sqlite3GlobalConfig.pHeap==0 ){
95642        /* If the heap pointer is NULL, then restore the malloc implementation
95643        ** back to NULL pointers too.  This will cause the malloc to go
95644        ** back to its default implementation when sqlite3_initialize() is
95645        ** run.
95646        */
95647        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
95648      }else{
95649        /* The heap pointer is not NULL, then install one of the
95650        ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
95651        ** ENABLE_MEMSYS5 is defined, return an error.
95652        */
95653#ifdef SQLITE_ENABLE_MEMSYS3
95654        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
95655#endif
95656#ifdef SQLITE_ENABLE_MEMSYS5
95657        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
95658#endif
95659      }
95660      break;
95661    }
95662#endif
95663
95664    case SQLITE_CONFIG_LOOKASIDE: {
95665      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
95666      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
95667      break;
95668    }
95669
95670    default: {
95671      rc = SQLITE_ERROR;
95672      break;
95673    }
95674  }
95675  va_end(ap);
95676  return rc;
95677}
95678
95679/*
95680** Set up the lookaside buffers for a database connection.
95681** Return SQLITE_OK on success.
95682** If lookaside is already active, return SQLITE_BUSY.
95683**
95684** The sz parameter is the number of bytes in each lookaside slot.
95685** The cnt parameter is the number of slots.  If pStart is NULL the
95686** space for the lookaside memory is obtained from sqlite3_malloc().
95687** If pStart is not NULL then it is sz*cnt bytes of memory to use for
95688** the lookaside memory.
95689*/
95690static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
95691  void *pStart;
95692  if( db->lookaside.nOut ){
95693    return SQLITE_BUSY;
95694  }
95695  /* Free any existing lookaside buffer for this handle before
95696  ** allocating a new one so we don't have to have space for
95697  ** both at the same time.
95698  */
95699  if( db->lookaside.bMalloced ){
95700    sqlite3_free(db->lookaside.pStart);
95701  }
95702  /* The size of a lookaside slot needs to be larger than a pointer
95703  ** to be useful.
95704  */
95705  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
95706  if( cnt<0 ) cnt = 0;
95707  if( sz==0 || cnt==0 ){
95708    sz = 0;
95709    pStart = 0;
95710  }else if( pBuf==0 ){
95711    sz = ROUND8(sz);
95712    sqlite3BeginBenignMalloc();
95713    pStart = sqlite3Malloc( sz*cnt );
95714    sqlite3EndBenignMalloc();
95715  }else{
95716    sz = ROUNDDOWN8(sz);
95717    pStart = pBuf;
95718  }
95719  db->lookaside.pStart = pStart;
95720  db->lookaside.pFree = 0;
95721  db->lookaside.sz = (u16)sz;
95722  if( pStart ){
95723    int i;
95724    LookasideSlot *p;
95725    assert( sz > (int)sizeof(LookasideSlot*) );
95726    p = (LookasideSlot*)pStart;
95727    for(i=cnt-1; i>=0; i--){
95728      p->pNext = db->lookaside.pFree;
95729      db->lookaside.pFree = p;
95730      p = (LookasideSlot*)&((u8*)p)[sz];
95731    }
95732    db->lookaside.pEnd = p;
95733    db->lookaside.bEnabled = 1;
95734    db->lookaside.bMalloced = pBuf==0 ?1:0;
95735  }else{
95736    db->lookaside.pEnd = 0;
95737    db->lookaside.bEnabled = 0;
95738    db->lookaside.bMalloced = 0;
95739  }
95740  return SQLITE_OK;
95741}
95742
95743/*
95744** Return the mutex associated with a database connection.
95745*/
95746SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
95747  return db->mutex;
95748}
95749
95750/*
95751** Configuration settings for an individual database connection
95752*/
95753SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
95754  va_list ap;
95755  int rc;
95756  va_start(ap, op);
95757  switch( op ){
95758    case SQLITE_DBCONFIG_LOOKASIDE: {
95759      void *pBuf = va_arg(ap, void*);
95760      int sz = va_arg(ap, int);
95761      int cnt = va_arg(ap, int);
95762      rc = setupLookaside(db, pBuf, sz, cnt);
95763      break;
95764    }
95765    default: {
95766      rc = SQLITE_ERROR;
95767      break;
95768    }
95769  }
95770  va_end(ap);
95771  return rc;
95772}
95773
95774
95775/*
95776** Return true if the buffer z[0..n-1] contains all spaces.
95777*/
95778static int allSpaces(const char *z, int n){
95779  while( n>0 && z[n-1]==' ' ){ n--; }
95780  return n==0;
95781}
95782
95783/*
95784** This is the default collating function named "BINARY" which is always
95785** available.
95786**
95787** If the padFlag argument is not NULL then space padding at the end
95788** of strings is ignored.  This implements the RTRIM collation.
95789*/
95790static int binCollFunc(
95791  void *padFlag,
95792  int nKey1, const void *pKey1,
95793  int nKey2, const void *pKey2
95794){
95795  int rc, n;
95796  n = nKey1<nKey2 ? nKey1 : nKey2;
95797  rc = memcmp(pKey1, pKey2, n);
95798  if( rc==0 ){
95799    if( padFlag
95800     && allSpaces(((char*)pKey1)+n, nKey1-n)
95801     && allSpaces(((char*)pKey2)+n, nKey2-n)
95802    ){
95803      /* Leave rc unchanged at 0 */
95804    }else{
95805      rc = nKey1 - nKey2;
95806    }
95807  }
95808  return rc;
95809}
95810
95811/*
95812** Another built-in collating sequence: NOCASE.
95813**
95814** This collating sequence is intended to be used for "case independant
95815** comparison". SQLite's knowledge of upper and lower case equivalents
95816** extends only to the 26 characters used in the English language.
95817**
95818** At the moment there is only a UTF-8 implementation.
95819*/
95820static int nocaseCollatingFunc(
95821  void *NotUsed,
95822  int nKey1, const void *pKey1,
95823  int nKey2, const void *pKey2
95824){
95825  int r = sqlite3StrNICmp(
95826      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
95827  UNUSED_PARAMETER(NotUsed);
95828  if( 0==r ){
95829    r = nKey1-nKey2;
95830  }
95831  return r;
95832}
95833
95834/*
95835** Return the ROWID of the most recent insert
95836*/
95837SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
95838  return db->lastRowid;
95839}
95840
95841/*
95842** Return the number of changes in the most recent call to sqlite3_exec().
95843*/
95844SQLITE_API int sqlite3_changes(sqlite3 *db){
95845  return db->nChange;
95846}
95847
95848/*
95849** Return the number of changes since the database handle was opened.
95850*/
95851SQLITE_API int sqlite3_total_changes(sqlite3 *db){
95852  return db->nTotalChange;
95853}
95854
95855/*
95856** Close all open savepoints. This function only manipulates fields of the
95857** database handle object, it does not close any savepoints that may be open
95858** at the b-tree/pager level.
95859*/
95860SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
95861  while( db->pSavepoint ){
95862    Savepoint *pTmp = db->pSavepoint;
95863    db->pSavepoint = pTmp->pNext;
95864    sqlite3DbFree(db, pTmp);
95865  }
95866  db->nSavepoint = 0;
95867  db->nStatement = 0;
95868  db->isTransactionSavepoint = 0;
95869}
95870
95871/*
95872** Close an existing SQLite database
95873*/
95874SQLITE_API int sqlite3_close(sqlite3 *db){
95875  HashElem *i;
95876  int j;
95877
95878  if( !db ){
95879    return SQLITE_OK;
95880  }
95881  if( !sqlite3SafetyCheckSickOrOk(db) ){
95882    return SQLITE_MISUSE;
95883  }
95884  sqlite3_mutex_enter(db->mutex);
95885
95886  sqlite3ResetInternalSchema(db, 0);
95887
95888  /* If a transaction is open, the ResetInternalSchema() call above
95889  ** will not have called the xDisconnect() method on any virtual
95890  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
95891  ** call will do so. We need to do this before the check for active
95892  ** SQL statements below, as the v-table implementation may be storing
95893  ** some prepared statements internally.
95894  */
95895  sqlite3VtabRollback(db);
95896
95897  /* If there are any outstanding VMs, return SQLITE_BUSY. */
95898  if( db->pVdbe ){
95899    // Begin Android Change
95900    // print the first unfinalized statement in the error message, to help the developer
95901    // figure out what the unfinalized statement is.
95902    char *msgPrefix = "unable to close due to unfinalised statements: ";
95903    int len = strlen(msgPrefix) + strlen(db->pVdbe->zSql) + 1;
95904    char *buff =(char*)sqlite3_malloc(len);
95905    strncat(buff, msgPrefix, strlen(msgPrefix));
95906    strncat(buff, db->pVdbe->zSql, strlen(db->pVdbe->zSql));
95907    buff[len-1] = NULL; // null terminate the string, just in case. paranoid, eh? :)
95908    sqlite3Error(db, SQLITE_BUSY, buff);
95909    sqlite3_free(buff);
95910    // End Android Change
95911    sqlite3_mutex_leave(db->mutex);
95912    return SQLITE_BUSY;
95913  }
95914  assert( sqlite3SafetyCheckSickOrOk(db) );
95915
95916  for(j=0; j<db->nDb; j++){
95917    Btree *pBt = db->aDb[j].pBt;
95918    if( pBt && sqlite3BtreeIsInBackup(pBt) ){
95919      sqlite3Error(db, SQLITE_BUSY,
95920          "unable to close due to unfinished backup operation");
95921      sqlite3_mutex_leave(db->mutex);
95922      return SQLITE_BUSY;
95923    }
95924  }
95925
95926  /* Free any outstanding Savepoint structures. */
95927  sqlite3CloseSavepoints(db);
95928
95929  for(j=0; j<db->nDb; j++){
95930    struct Db *pDb = &db->aDb[j];
95931    if( pDb->pBt ){
95932      sqlite3BtreeClose(pDb->pBt);
95933      pDb->pBt = 0;
95934      if( j!=1 ){
95935        pDb->pSchema = 0;
95936      }
95937    }
95938  }
95939  sqlite3ResetInternalSchema(db, 0);
95940
95941  /* Tell the code in notify.c that the connection no longer holds any
95942  ** locks and does not require any further unlock-notify callbacks.
95943  */
95944  sqlite3ConnectionClosed(db);
95945
95946  assert( db->nDb<=2 );
95947  assert( db->aDb==db->aDbStatic );
95948  for(j=0; j<ArraySize(db->aFunc.a); j++){
95949    FuncDef *pNext, *pHash, *p;
95950    for(p=db->aFunc.a[j]; p; p=pHash){
95951      pHash = p->pHash;
95952      while( p ){
95953        pNext = p->pNext;
95954        sqlite3DbFree(db, p);
95955        p = pNext;
95956      }
95957    }
95958  }
95959  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
95960    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
95961    /* Invoke any destructors registered for collation sequence user data. */
95962    for(j=0; j<3; j++){
95963      if( pColl[j].xDel ){
95964        pColl[j].xDel(pColl[j].pUser);
95965      }
95966    }
95967    sqlite3DbFree(db, pColl);
95968  }
95969  sqlite3HashClear(&db->aCollSeq);
95970#ifndef SQLITE_OMIT_VIRTUALTABLE
95971  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
95972    Module *pMod = (Module *)sqliteHashData(i);
95973    if( pMod->xDestroy ){
95974      pMod->xDestroy(pMod->pAux);
95975    }
95976    sqlite3DbFree(db, pMod);
95977  }
95978  sqlite3HashClear(&db->aModule);
95979#endif
95980
95981  sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
95982  if( db->pErr ){
95983    sqlite3ValueFree(db->pErr);
95984  }
95985  sqlite3CloseExtensions(db);
95986
95987  db->magic = SQLITE_MAGIC_ERROR;
95988
95989  /* The temp-database schema is allocated differently from the other schema
95990  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
95991  ** So it needs to be freed here. Todo: Why not roll the temp schema into
95992  ** the same sqliteMalloc() as the one that allocates the database
95993  ** structure?
95994  */
95995  sqlite3DbFree(db, db->aDb[1].pSchema);
95996  sqlite3_mutex_leave(db->mutex);
95997  db->magic = SQLITE_MAGIC_CLOSED;
95998  sqlite3_mutex_free(db->mutex);
95999  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
96000  if( db->lookaside.bMalloced ){
96001    sqlite3_free(db->lookaside.pStart);
96002  }
96003  sqlite3_free(db);
96004  return SQLITE_OK;
96005}
96006
96007/*
96008** Rollback all database files.
96009*/
96010SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
96011  int i;
96012  int inTrans = 0;
96013  assert( sqlite3_mutex_held(db->mutex) );
96014  sqlite3BeginBenignMalloc();
96015  for(i=0; i<db->nDb; i++){
96016    if( db->aDb[i].pBt ){
96017      if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
96018        inTrans = 1;
96019      }
96020      sqlite3BtreeRollback(db->aDb[i].pBt);
96021      db->aDb[i].inTrans = 0;
96022    }
96023  }
96024  sqlite3VtabRollback(db);
96025  sqlite3EndBenignMalloc();
96026
96027  if( db->flags&SQLITE_InternChanges ){
96028    sqlite3ExpirePreparedStatements(db);
96029    sqlite3ResetInternalSchema(db, 0);
96030  }
96031
96032  /* Any deferred constraint violations have now been resolved. */
96033  db->nDeferredCons = 0;
96034
96035  /* If one has been configured, invoke the rollback-hook callback */
96036  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
96037    db->xRollbackCallback(db->pRollbackArg);
96038  }
96039}
96040
96041/*
96042** Return a static string that describes the kind of error specified in the
96043** argument.
96044*/
96045SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
96046  static const char* const aMsg[] = {
96047    /* SQLITE_OK          */ "not an error",
96048    /* SQLITE_ERROR       */ "SQL logic error or missing database",
96049    /* SQLITE_INTERNAL    */ 0,
96050    /* SQLITE_PERM        */ "access permission denied",
96051    /* SQLITE_ABORT       */ "callback requested query abort",
96052    /* SQLITE_BUSY        */ "database is locked",
96053    /* SQLITE_LOCKED      */ "database table is locked",
96054    /* SQLITE_NOMEM       */ "out of memory",
96055    /* SQLITE_READONLY    */ "attempt to write a readonly database",
96056    /* SQLITE_INTERRUPT   */ "interrupted",
96057    /* SQLITE_IOERR       */ "disk I/O error",
96058    /* SQLITE_CORRUPT     */ "database disk image is malformed",
96059    /* SQLITE_NOTFOUND    */ 0,
96060    /* SQLITE_FULL        */ "database or disk is full",
96061    /* SQLITE_CANTOPEN    */ "unable to open database file",
96062    /* SQLITE_PROTOCOL    */ 0,
96063    /* SQLITE_EMPTY       */ "table contains no data",
96064    /* SQLITE_SCHEMA      */ "database schema has changed",
96065    /* SQLITE_TOOBIG      */ "string or blob too big",
96066    /* SQLITE_CONSTRAINT  */ "constraint failed",
96067    /* SQLITE_MISMATCH    */ "datatype mismatch",
96068    /* SQLITE_MISUSE      */ "library routine called out of sequence",
96069    /* SQLITE_NOLFS       */ "large file support is disabled",
96070    /* SQLITE_AUTH        */ "authorization denied",
96071    /* SQLITE_FORMAT      */ "auxiliary database format error",
96072    /* SQLITE_RANGE       */ "bind or column index out of range",
96073    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
96074  };
96075  rc &= 0xff;
96076  if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
96077    return aMsg[rc];
96078  }else{
96079    return "unknown error";
96080  }
96081}
96082
96083/*
96084** This routine implements a busy callback that sleeps and tries
96085** again until a timeout value is reached.  The timeout value is
96086** an integer number of milliseconds passed in as the first
96087** argument.
96088*/
96089static int sqliteDefaultBusyCallback(
96090 void *ptr,               /* Database connection */
96091 int count                /* Number of times table has been busy */
96092){
96093#if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
96094  static const u8 delays[] =
96095     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
96096  static const u8 totals[] =
96097     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
96098# define NDELAY (sizeof(delays)/sizeof(delays[0]))
96099  sqlite3 *db = (sqlite3 *)ptr;
96100  int timeout = db->busyTimeout;
96101  int delay, prior;
96102
96103  assert( count>=0 );
96104  if( count < NDELAY ){
96105    delay = delays[count];
96106    prior = totals[count];
96107  }else{
96108    delay = delays[NDELAY-1];
96109    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
96110  }
96111  if( prior + delay > timeout ){
96112    delay = timeout - prior;
96113    if( delay<=0 ) return 0;
96114  }
96115  sqlite3OsSleep(db->pVfs, delay*1000);
96116  return 1;
96117#else
96118  sqlite3 *db = (sqlite3 *)ptr;
96119  int timeout = ((sqlite3 *)ptr)->busyTimeout;
96120  if( (count+1)*1000 > timeout ){
96121    return 0;
96122  }
96123  sqlite3OsSleep(db->pVfs, 1000000);
96124  return 1;
96125#endif
96126}
96127
96128/*
96129** Invoke the given busy handler.
96130**
96131** This routine is called when an operation failed with a lock.
96132** If this routine returns non-zero, the lock is retried.  If it
96133** returns 0, the operation aborts with an SQLITE_BUSY error.
96134*/
96135SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
96136  int rc;
96137  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
96138  rc = p->xFunc(p->pArg, p->nBusy);
96139  if( rc==0 ){
96140    p->nBusy = -1;
96141  }else{
96142    p->nBusy++;
96143  }
96144  return rc;
96145}
96146
96147/*
96148** This routine sets the busy callback for an Sqlite database to the
96149** given callback function with the given argument.
96150*/
96151SQLITE_API int sqlite3_busy_handler(
96152  sqlite3 *db,
96153  int (*xBusy)(void*,int),
96154  void *pArg
96155){
96156  sqlite3_mutex_enter(db->mutex);
96157  db->busyHandler.xFunc = xBusy;
96158  db->busyHandler.pArg = pArg;
96159  db->busyHandler.nBusy = 0;
96160  sqlite3_mutex_leave(db->mutex);
96161  return SQLITE_OK;
96162}
96163
96164#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
96165/*
96166** This routine sets the progress callback for an Sqlite database to the
96167** given callback function with the given argument. The progress callback will
96168** be invoked every nOps opcodes.
96169*/
96170SQLITE_API void sqlite3_progress_handler(
96171  sqlite3 *db,
96172  int nOps,
96173  int (*xProgress)(void*),
96174  void *pArg
96175){
96176  sqlite3_mutex_enter(db->mutex);
96177  if( nOps>0 ){
96178    db->xProgress = xProgress;
96179    db->nProgressOps = nOps;
96180    db->pProgressArg = pArg;
96181  }else{
96182    db->xProgress = 0;
96183    db->nProgressOps = 0;
96184    db->pProgressArg = 0;
96185  }
96186  sqlite3_mutex_leave(db->mutex);
96187}
96188#endif
96189
96190
96191/*
96192** This routine installs a default busy handler that waits for the
96193** specified number of milliseconds before returning 0.
96194*/
96195SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
96196  if( ms>0 ){
96197    db->busyTimeout = ms;
96198    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
96199  }else{
96200    sqlite3_busy_handler(db, 0, 0);
96201  }
96202  return SQLITE_OK;
96203}
96204
96205/*
96206** Cause any pending operation to stop at its earliest opportunity.
96207*/
96208SQLITE_API void sqlite3_interrupt(sqlite3 *db){
96209  db->u1.isInterrupted = 1;
96210}
96211
96212
96213/*
96214** This function is exactly the same as sqlite3_create_function(), except
96215** that it is designed to be called by internal code. The difference is
96216** that if a malloc() fails in sqlite3_create_function(), an error code
96217** is returned and the mallocFailed flag cleared.
96218*/
96219SQLITE_PRIVATE int sqlite3CreateFunc(
96220  sqlite3 *db,
96221  const char *zFunctionName,
96222  int nArg,
96223  int enc,
96224  void *pUserData,
96225  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
96226  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
96227  void (*xFinal)(sqlite3_context*)
96228){
96229  FuncDef *p;
96230  int nName;
96231
96232  assert( sqlite3_mutex_held(db->mutex) );
96233  if( zFunctionName==0 ||
96234      (xFunc && (xFinal || xStep)) ||
96235      (!xFunc && (xFinal && !xStep)) ||
96236      (!xFunc && (!xFinal && xStep)) ||
96237      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
96238      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
96239    return SQLITE_MISUSE;
96240  }
96241
96242#ifndef SQLITE_OMIT_UTF16
96243  /* If SQLITE_UTF16 is specified as the encoding type, transform this
96244  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
96245  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
96246  **
96247  ** If SQLITE_ANY is specified, add three versions of the function
96248  ** to the hash table.
96249  */
96250  if( enc==SQLITE_UTF16 ){
96251    enc = SQLITE_UTF16NATIVE;
96252  }else if( enc==SQLITE_ANY ){
96253    int rc;
96254    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
96255         pUserData, xFunc, xStep, xFinal);
96256    if( rc==SQLITE_OK ){
96257      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
96258          pUserData, xFunc, xStep, xFinal);
96259    }
96260    if( rc!=SQLITE_OK ){
96261      return rc;
96262    }
96263    enc = SQLITE_UTF16BE;
96264  }
96265#else
96266  enc = SQLITE_UTF8;
96267#endif
96268
96269  /* Check if an existing function is being overridden or deleted. If so,
96270  ** and there are active VMs, then return SQLITE_BUSY. If a function
96271  ** is being overridden/deleted but there are no active VMs, allow the
96272  ** operation to continue but invalidate all precompiled statements.
96273  */
96274  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
96275  if( p && p->iPrefEnc==enc && p->nArg==nArg ){
96276    if( db->activeVdbeCnt ){
96277      sqlite3Error(db, SQLITE_BUSY,
96278        "unable to delete/modify user-function due to active statements");
96279      assert( !db->mallocFailed );
96280      return SQLITE_BUSY;
96281    }else{
96282      sqlite3ExpirePreparedStatements(db);
96283    }
96284  }
96285
96286  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
96287  assert(p || db->mallocFailed);
96288  if( !p ){
96289    return SQLITE_NOMEM;
96290  }
96291  p->flags = 0;
96292  p->xFunc = xFunc;
96293  p->xStep = xStep;
96294  p->xFinalize = xFinal;
96295  p->pUserData = pUserData;
96296  p->nArg = (u16)nArg;
96297  return SQLITE_OK;
96298}
96299
96300/*
96301** Create new user functions.
96302*/
96303SQLITE_API int sqlite3_create_function(
96304  sqlite3 *db,
96305  const char *zFunctionName,
96306  int nArg,
96307  int enc,
96308  void *p,
96309  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
96310  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
96311  void (*xFinal)(sqlite3_context*)
96312){
96313  int rc;
96314  sqlite3_mutex_enter(db->mutex);
96315  rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
96316  rc = sqlite3ApiExit(db, rc);
96317  sqlite3_mutex_leave(db->mutex);
96318  return rc;
96319}
96320
96321#ifndef SQLITE_OMIT_UTF16
96322SQLITE_API int sqlite3_create_function16(
96323  sqlite3 *db,
96324  const void *zFunctionName,
96325  int nArg,
96326  int eTextRep,
96327  void *p,
96328  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
96329  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
96330  void (*xFinal)(sqlite3_context*)
96331){
96332  int rc;
96333  char *zFunc8;
96334  sqlite3_mutex_enter(db->mutex);
96335  assert( !db->mallocFailed );
96336  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
96337  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
96338  sqlite3DbFree(db, zFunc8);
96339  rc = sqlite3ApiExit(db, rc);
96340  sqlite3_mutex_leave(db->mutex);
96341  return rc;
96342}
96343#endif
96344
96345
96346/*
96347** Declare that a function has been overloaded by a virtual table.
96348**
96349** If the function already exists as a regular global function, then
96350** this routine is a no-op.  If the function does not exist, then create
96351** a new one that always throws a run-time error.
96352**
96353** When virtual tables intend to provide an overloaded function, they
96354** should call this routine to make sure the global function exists.
96355** A global function must exist in order for name resolution to work
96356** properly.
96357*/
96358SQLITE_API int sqlite3_overload_function(
96359  sqlite3 *db,
96360  const char *zName,
96361  int nArg
96362){
96363  int nName = sqlite3Strlen30(zName);
96364  int rc;
96365  sqlite3_mutex_enter(db->mutex);
96366  if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
96367    sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
96368                      0, sqlite3InvalidFunction, 0, 0);
96369  }
96370  rc = sqlite3ApiExit(db, SQLITE_OK);
96371  sqlite3_mutex_leave(db->mutex);
96372  return rc;
96373}
96374
96375#ifndef SQLITE_OMIT_TRACE
96376/*
96377** Register a trace function.  The pArg from the previously registered trace
96378** is returned.
96379**
96380** A NULL trace function means that no tracing is executes.  A non-NULL
96381** trace is a pointer to a function that is invoked at the start of each
96382** SQL statement.
96383*/
96384SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
96385  void *pOld;
96386  sqlite3_mutex_enter(db->mutex);
96387  pOld = db->pTraceArg;
96388  db->xTrace = xTrace;
96389  db->pTraceArg = pArg;
96390  sqlite3_mutex_leave(db->mutex);
96391  return pOld;
96392}
96393/*
96394** Register a profile function.  The pArg from the previously registered
96395** profile function is returned.
96396**
96397** A NULL profile function means that no profiling is executes.  A non-NULL
96398** profile is a pointer to a function that is invoked at the conclusion of
96399** each SQL statement that is run.
96400*/
96401SQLITE_API void *sqlite3_profile(
96402  sqlite3 *db,
96403  void (*xProfile)(void*,const char*,sqlite_uint64),
96404  void *pArg
96405){
96406  void *pOld;
96407  sqlite3_mutex_enter(db->mutex);
96408  pOld = db->pProfileArg;
96409  db->xProfile = xProfile;
96410  db->pProfileArg = pArg;
96411  sqlite3_mutex_leave(db->mutex);
96412  return pOld;
96413}
96414#endif /* SQLITE_OMIT_TRACE */
96415
96416/*** EXPERIMENTAL ***
96417**
96418** Register a function to be invoked when a transaction comments.
96419** If the invoked function returns non-zero, then the commit becomes a
96420** rollback.
96421*/
96422SQLITE_API void *sqlite3_commit_hook(
96423  sqlite3 *db,              /* Attach the hook to this database */
96424  int (*xCallback)(void*),  /* Function to invoke on each commit */
96425  void *pArg                /* Argument to the function */
96426){
96427  void *pOld;
96428  sqlite3_mutex_enter(db->mutex);
96429  pOld = db->pCommitArg;
96430  db->xCommitCallback = xCallback;
96431  db->pCommitArg = pArg;
96432  sqlite3_mutex_leave(db->mutex);
96433  return pOld;
96434}
96435
96436/*
96437** Register a callback to be invoked each time a row is updated,
96438** inserted or deleted using this database connection.
96439*/
96440SQLITE_API void *sqlite3_update_hook(
96441  sqlite3 *db,              /* Attach the hook to this database */
96442  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
96443  void *pArg                /* Argument to the function */
96444){
96445  void *pRet;
96446  sqlite3_mutex_enter(db->mutex);
96447  pRet = db->pUpdateArg;
96448  db->xUpdateCallback = xCallback;
96449  db->pUpdateArg = pArg;
96450  sqlite3_mutex_leave(db->mutex);
96451  return pRet;
96452}
96453
96454/*
96455** Register a callback to be invoked each time a transaction is rolled
96456** back by this database connection.
96457*/
96458SQLITE_API void *sqlite3_rollback_hook(
96459  sqlite3 *db,              /* Attach the hook to this database */
96460  void (*xCallback)(void*), /* Callback function */
96461  void *pArg                /* Argument to the function */
96462){
96463  void *pRet;
96464  sqlite3_mutex_enter(db->mutex);
96465  pRet = db->pRollbackArg;
96466  db->xRollbackCallback = xCallback;
96467  db->pRollbackArg = pArg;
96468  sqlite3_mutex_leave(db->mutex);
96469  return pRet;
96470}
96471
96472/*
96473** This function returns true if main-memory should be used instead of
96474** a temporary file for transient pager files and statement journals.
96475** The value returned depends on the value of db->temp_store (runtime
96476** parameter) and the compile time value of SQLITE_TEMP_STORE. The
96477** following table describes the relationship between these two values
96478** and this functions return value.
96479**
96480**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
96481**   -----------------     --------------     ------------------------------
96482**   0                     any                file      (return 0)
96483**   1                     1                  file      (return 0)
96484**   1                     2                  memory    (return 1)
96485**   1                     0                  file      (return 0)
96486**   2                     1                  file      (return 0)
96487**   2                     2                  memory    (return 1)
96488**   2                     0                  memory    (return 1)
96489**   3                     any                memory    (return 1)
96490*/
96491SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
96492#if SQLITE_TEMP_STORE==1
96493  return ( db->temp_store==2 );
96494#endif
96495#if SQLITE_TEMP_STORE==2
96496  return ( db->temp_store!=1 );
96497#endif
96498#if SQLITE_TEMP_STORE==3
96499  return 1;
96500#endif
96501#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
96502  return 0;
96503#endif
96504}
96505
96506/*
96507** This routine is called to create a connection to a database BTree
96508** driver.  If zFilename is the name of a file, then that file is
96509** opened and used.  If zFilename is the magic name ":memory:" then
96510** the database is stored in memory (and is thus forgotten as soon as
96511** the connection is closed.)  If zFilename is NULL then the database
96512** is a "virtual" database for transient use only and is deleted as
96513** soon as the connection is closed.
96514**
96515** A virtual database can be either a disk file (that is automatically
96516** deleted when the file is closed) or it an be held entirely in memory.
96517** The sqlite3TempInMemory() function is used to determine which.
96518*/
96519SQLITE_PRIVATE int sqlite3BtreeFactory(
96520  sqlite3 *db,              /* Main database when opening aux otherwise 0 */
96521  const char *zFilename,    /* Name of the file containing the BTree database */
96522  int omitJournal,          /* if TRUE then do not journal this file */
96523  int nCache,               /* How many pages in the page cache */
96524  int vfsFlags,             /* Flags passed through to vfsOpen */
96525  Btree **ppBtree           /* Pointer to new Btree object written here */
96526){
96527  int btFlags = 0;
96528  int rc;
96529
96530  assert( sqlite3_mutex_held(db->mutex) );
96531  assert( ppBtree != 0);
96532  if( omitJournal ){
96533    btFlags |= BTREE_OMIT_JOURNAL;
96534  }
96535  if( db->flags & SQLITE_NoReadlock ){
96536    btFlags |= BTREE_NO_READLOCK;
96537  }
96538#ifndef SQLITE_OMIT_MEMORYDB
96539  if( zFilename==0 && sqlite3TempInMemory(db) ){
96540    zFilename = ":memory:";
96541  }
96542#endif
96543
96544  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
96545    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
96546  }
96547  rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
96548
96549  /* If the B-Tree was successfully opened, set the pager-cache size to the
96550  ** default value. Except, if the call to BtreeOpen() returned a handle
96551  ** open on an existing shared pager-cache, do not change the pager-cache
96552  ** size.
96553  */
96554  if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
96555    sqlite3BtreeSetCacheSize(*ppBtree, nCache);
96556  }
96557  return rc;
96558}
96559
96560/*
96561** Return UTF-8 encoded English language explanation of the most recent
96562** error.
96563*/
96564SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
96565  const char *z;
96566  if( !db ){
96567    return sqlite3ErrStr(SQLITE_NOMEM);
96568  }
96569  if( !sqlite3SafetyCheckSickOrOk(db) ){
96570    return sqlite3ErrStr(SQLITE_MISUSE);
96571  }
96572  sqlite3_mutex_enter(db->mutex);
96573  if( db->mallocFailed ){
96574    z = sqlite3ErrStr(SQLITE_NOMEM);
96575  }else{
96576    z = (char*)sqlite3_value_text(db->pErr);
96577    assert( !db->mallocFailed );
96578    if( z==0 ){
96579      z = sqlite3ErrStr(db->errCode);
96580    }
96581  }
96582  sqlite3_mutex_leave(db->mutex);
96583  return z;
96584}
96585
96586#ifndef SQLITE_OMIT_UTF16
96587/*
96588** Return UTF-16 encoded English language explanation of the most recent
96589** error.
96590*/
96591SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
96592  static const u16 outOfMem[] = {
96593    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
96594  };
96595  static const u16 misuse[] = {
96596    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
96597    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
96598    'c', 'a', 'l', 'l', 'e', 'd', ' ',
96599    'o', 'u', 't', ' ',
96600    'o', 'f', ' ',
96601    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
96602  };
96603
96604  const void *z;
96605  if( !db ){
96606    return (void *)outOfMem;
96607  }
96608  if( !sqlite3SafetyCheckSickOrOk(db) ){
96609    return (void *)misuse;
96610  }
96611  sqlite3_mutex_enter(db->mutex);
96612  if( db->mallocFailed ){
96613    z = (void *)outOfMem;
96614  }else{
96615    z = sqlite3_value_text16(db->pErr);
96616    if( z==0 ){
96617      sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
96618           SQLITE_UTF8, SQLITE_STATIC);
96619      z = sqlite3_value_text16(db->pErr);
96620    }
96621    /* A malloc() may have failed within the call to sqlite3_value_text16()
96622    ** above. If this is the case, then the db->mallocFailed flag needs to
96623    ** be cleared before returning. Do this directly, instead of via
96624    ** sqlite3ApiExit(), to avoid setting the database handle error message.
96625    */
96626    db->mallocFailed = 0;
96627  }
96628  sqlite3_mutex_leave(db->mutex);
96629  return z;
96630}
96631#endif /* SQLITE_OMIT_UTF16 */
96632
96633/*
96634** Return the most recent error code generated by an SQLite routine. If NULL is
96635** passed to this function, we assume a malloc() failed during sqlite3_open().
96636*/
96637SQLITE_API int sqlite3_errcode(sqlite3 *db){
96638  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
96639    return SQLITE_MISUSE;
96640  }
96641  if( !db || db->mallocFailed ){
96642    return SQLITE_NOMEM;
96643  }
96644  return db->errCode & db->errMask;
96645}
96646SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
96647  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
96648    return SQLITE_MISUSE;
96649  }
96650  if( !db || db->mallocFailed ){
96651    return SQLITE_NOMEM;
96652  }
96653  return db->errCode;
96654}
96655
96656/*
96657** Create a new collating function for database "db".  The name is zName
96658** and the encoding is enc.
96659*/
96660static int createCollation(
96661  sqlite3* db,
96662  const char *zName,
96663  u8 enc,
96664  u8 collType,
96665  void* pCtx,
96666  int(*xCompare)(void*,int,const void*,int,const void*),
96667  void(*xDel)(void*)
96668){
96669  CollSeq *pColl;
96670  int enc2;
96671  int nName = sqlite3Strlen30(zName);
96672
96673  assert( sqlite3_mutex_held(db->mutex) );
96674
96675  /* If SQLITE_UTF16 is specified as the encoding type, transform this
96676  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
96677  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
96678  */
96679  enc2 = enc;
96680  testcase( enc2==SQLITE_UTF16 );
96681  testcase( enc2==SQLITE_UTF16_ALIGNED );
96682  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
96683    enc2 = SQLITE_UTF16NATIVE;
96684  }
96685  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
96686    return SQLITE_MISUSE;
96687  }
96688
96689  /* Check if this call is removing or replacing an existing collation
96690  ** sequence. If so, and there are active VMs, return busy. If there
96691  ** are no active VMs, invalidate any pre-compiled statements.
96692  */
96693  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
96694  if( pColl && pColl->xCmp ){
96695    if( db->activeVdbeCnt ){
96696      sqlite3Error(db, SQLITE_BUSY,
96697        "unable to delete/modify collation sequence due to active statements");
96698      return SQLITE_BUSY;
96699    }
96700    sqlite3ExpirePreparedStatements(db);
96701
96702    /* If collation sequence pColl was created directly by a call to
96703    ** sqlite3_create_collation, and not generated by synthCollSeq(),
96704    ** then any copies made by synthCollSeq() need to be invalidated.
96705    ** Also, collation destructor - CollSeq.xDel() - function may need
96706    ** to be called.
96707    */
96708    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
96709      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
96710      int j;
96711      for(j=0; j<3; j++){
96712        CollSeq *p = &aColl[j];
96713        if( p->enc==pColl->enc ){
96714          if( p->xDel ){
96715            p->xDel(p->pUser);
96716          }
96717          p->xCmp = 0;
96718        }
96719      }
96720    }
96721  }
96722
96723  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
96724  if( pColl ){
96725    pColl->xCmp = xCompare;
96726    pColl->pUser = pCtx;
96727    pColl->xDel = xDel;
96728    pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
96729    pColl->type = collType;
96730  }
96731  sqlite3Error(db, SQLITE_OK, 0);
96732  return SQLITE_OK;
96733}
96734
96735
96736/*
96737** This array defines hard upper bounds on limit values.  The
96738** initializer must be kept in sync with the SQLITE_LIMIT_*
96739** #defines in sqlite3.h.
96740*/
96741static const int aHardLimit[] = {
96742  SQLITE_MAX_LENGTH,
96743  SQLITE_MAX_SQL_LENGTH,
96744  SQLITE_MAX_COLUMN,
96745  SQLITE_MAX_EXPR_DEPTH,
96746  SQLITE_MAX_COMPOUND_SELECT,
96747  SQLITE_MAX_VDBE_OP,
96748  SQLITE_MAX_FUNCTION_ARG,
96749  SQLITE_MAX_ATTACHED,
96750  SQLITE_MAX_LIKE_PATTERN_LENGTH,
96751  SQLITE_MAX_VARIABLE_NUMBER,
96752  SQLITE_MAX_TRIGGER_DEPTH,
96753};
96754
96755/*
96756** Make sure the hard limits are set to reasonable values
96757*/
96758#if SQLITE_MAX_LENGTH<100
96759# error SQLITE_MAX_LENGTH must be at least 100
96760#endif
96761#if SQLITE_MAX_SQL_LENGTH<100
96762# error SQLITE_MAX_SQL_LENGTH must be at least 100
96763#endif
96764#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
96765# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
96766#endif
96767#if SQLITE_MAX_COMPOUND_SELECT<2
96768# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
96769#endif
96770#if SQLITE_MAX_VDBE_OP<40
96771# error SQLITE_MAX_VDBE_OP must be at least 40
96772#endif
96773#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
96774# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
96775#endif
96776#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
96777# error SQLITE_MAX_ATTACHED must be between 0 and 30
96778#endif
96779#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
96780# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
96781#endif
96782#if SQLITE_MAX_COLUMN>32767
96783# error SQLITE_MAX_COLUMN must not exceed 32767
96784#endif
96785#if SQLITE_MAX_TRIGGER_DEPTH<1
96786# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
96787#endif
96788
96789
96790/*
96791** Change the value of a limit.  Report the old value.
96792** If an invalid limit index is supplied, report -1.
96793** Make no changes but still report the old value if the
96794** new limit is negative.
96795**
96796** A new lower limit does not shrink existing constructs.
96797** It merely prevents new constructs that exceed the limit
96798** from forming.
96799*/
96800SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
96801  int oldLimit;
96802  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
96803    return -1;
96804  }
96805  oldLimit = db->aLimit[limitId];
96806  if( newLimit>=0 ){
96807    if( newLimit>aHardLimit[limitId] ){
96808      newLimit = aHardLimit[limitId];
96809    }
96810    db->aLimit[limitId] = newLimit;
96811  }
96812  return oldLimit;
96813}
96814
96815/*
96816** This routine does the work of opening a database on behalf of
96817** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
96818** is UTF-8 encoded.
96819*/
96820static int openDatabase(
96821  const char *zFilename, /* Database filename UTF-8 encoded */
96822  sqlite3 **ppDb,        /* OUT: Returned database handle */
96823  unsigned flags,        /* Operational flags */
96824  const char *zVfs       /* Name of the VFS to use */
96825){
96826  sqlite3 *db;
96827  int rc;
96828  int isThreadsafe;
96829
96830  *ppDb = 0;
96831#ifndef SQLITE_OMIT_AUTOINIT
96832  rc = sqlite3_initialize();
96833  if( rc ) return rc;
96834#endif
96835
96836  if( sqlite3GlobalConfig.bCoreMutex==0 ){
96837    isThreadsafe = 0;
96838  }else if( flags & SQLITE_OPEN_NOMUTEX ){
96839    isThreadsafe = 0;
96840  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
96841    isThreadsafe = 1;
96842  }else{
96843    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
96844  }
96845  if( flags & SQLITE_OPEN_PRIVATECACHE ){
96846    flags &= ~SQLITE_OPEN_SHAREDCACHE;
96847  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
96848    flags |= SQLITE_OPEN_SHAREDCACHE;
96849  }
96850
96851  /* Remove harmful bits from the flags parameter
96852  **
96853  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
96854  ** dealt with in the previous code block.  Besides these, the only
96855  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
96856  ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE.  Silently mask
96857  ** off all other flags.
96858  */
96859  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
96860               SQLITE_OPEN_EXCLUSIVE |
96861               SQLITE_OPEN_MAIN_DB |
96862               SQLITE_OPEN_TEMP_DB |
96863               SQLITE_OPEN_TRANSIENT_DB |
96864               SQLITE_OPEN_MAIN_JOURNAL |
96865               SQLITE_OPEN_TEMP_JOURNAL |
96866               SQLITE_OPEN_SUBJOURNAL |
96867               SQLITE_OPEN_MASTER_JOURNAL |
96868               SQLITE_OPEN_NOMUTEX |
96869               SQLITE_OPEN_FULLMUTEX
96870             );
96871
96872  /* Allocate the sqlite data structure */
96873  db = sqlite3MallocZero( sizeof(sqlite3) );
96874  if( db==0 ) goto opendb_out;
96875  if( isThreadsafe ){
96876    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
96877    if( db->mutex==0 ){
96878      sqlite3_free(db);
96879      db = 0;
96880      goto opendb_out;
96881    }
96882  }
96883  sqlite3_mutex_enter(db->mutex);
96884  db->errMask = 0xff;
96885  db->nDb = 2;
96886  db->magic = SQLITE_MAGIC_BUSY;
96887  db->aDb = db->aDbStatic;
96888
96889  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
96890  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
96891  db->autoCommit = 1;
96892  db->nextAutovac = -1;
96893  db->nextPagesize = 0;
96894  db->flags |= SQLITE_ShortColNames
96895#if SQLITE_DEFAULT_FILE_FORMAT<4
96896                 | SQLITE_LegacyFileFmt
96897#endif
96898#ifdef SQLITE_ENABLE_LOAD_EXTENSION
96899                 | SQLITE_LoadExtension
96900#endif
96901#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
96902                 | SQLITE_RecTriggers
96903#endif
96904      ;
96905  sqlite3HashInit(&db->aCollSeq);
96906#ifndef SQLITE_OMIT_VIRTUALTABLE
96907  sqlite3HashInit(&db->aModule);
96908#endif
96909
96910  db->pVfs = sqlite3_vfs_find(zVfs);
96911  if( !db->pVfs ){
96912    rc = SQLITE_ERROR;
96913    sqlite3Error(db, rc, "no such vfs: %s", zVfs);
96914    goto opendb_out;
96915  }
96916
96917  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
96918  ** and UTF-16, so add a version for each to avoid any unnecessary
96919  ** conversions. The only error that can occur here is a malloc() failure.
96920  */
96921  createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
96922                  binCollFunc, 0);
96923  createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
96924                  binCollFunc, 0);
96925  createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
96926                  binCollFunc, 0);
96927  createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
96928                  binCollFunc, 0);
96929  if( db->mallocFailed ){
96930    goto opendb_out;
96931  }
96932  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
96933  assert( db->pDfltColl!=0 );
96934
96935  /* Also add a UTF-8 case-insensitive collation sequence. */
96936  createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
96937                  nocaseCollatingFunc, 0);
96938
96939  /* Open the backend database driver */
96940  db->openFlags = flags;
96941  rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
96942                           flags | SQLITE_OPEN_MAIN_DB,
96943                           &db->aDb[0].pBt);
96944  if( rc!=SQLITE_OK ){
96945    if( rc==SQLITE_IOERR_NOMEM ){
96946      rc = SQLITE_NOMEM;
96947    }
96948    sqlite3Error(db, rc, 0);
96949    goto opendb_out;
96950  }
96951  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
96952  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
96953
96954
96955  /* The default safety_level for the main database is 'full'; for the temp
96956  ** database it is 'NONE'. This matches the pager layer defaults.
96957  */
96958  db->aDb[0].zName = "main";
96959  db->aDb[0].safety_level = 3;
96960  db->aDb[1].zName = "temp";
96961  db->aDb[1].safety_level = 1;
96962
96963  db->magic = SQLITE_MAGIC_OPEN;
96964  if( db->mallocFailed ){
96965    goto opendb_out;
96966  }
96967
96968  /* Register all built-in functions, but do not attempt to read the
96969  ** database schema yet. This is delayed until the first time the database
96970  ** is accessed.
96971  */
96972  sqlite3Error(db, SQLITE_OK, 0);
96973  sqlite3RegisterBuiltinFunctions(db);
96974
96975  /* Load automatic extensions - extensions that have been registered
96976  ** using the sqlite3_automatic_extension() API.
96977  */
96978  sqlite3AutoLoadExtensions(db);
96979  rc = sqlite3_errcode(db);
96980  if( rc!=SQLITE_OK ){
96981    goto opendb_out;
96982  }
96983
96984#ifdef SQLITE_ENABLE_FTS1
96985  if( !db->mallocFailed ){
96986    extern int sqlite3Fts1Init(sqlite3*);
96987    rc = sqlite3Fts1Init(db);
96988  }
96989#endif
96990
96991#ifdef SQLITE_ENABLE_FTS2
96992  if( !db->mallocFailed && rc==SQLITE_OK ){
96993    extern int sqlite3Fts2Init(sqlite3*);
96994    rc = sqlite3Fts2Init(db);
96995  }
96996#endif
96997
96998#ifdef SQLITE_ENABLE_FTS3
96999  if( !db->mallocFailed && rc==SQLITE_OK ){
97000    rc = sqlite3Fts3Init(db);
97001  }
97002#endif
97003
97004#ifdef SQLITE_ENABLE_ICU
97005  if( !db->mallocFailed && rc==SQLITE_OK ){
97006    rc = sqlite3IcuInit(db);
97007  }
97008#endif
97009
97010#ifdef SQLITE_ENABLE_RTREE
97011  if( !db->mallocFailed && rc==SQLITE_OK){
97012    rc = sqlite3RtreeInit(db);
97013  }
97014#endif
97015
97016  sqlite3Error(db, rc, 0);
97017
97018  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
97019  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
97020  ** mode.  Doing nothing at all also makes NORMAL the default.
97021  */
97022#ifdef SQLITE_DEFAULT_LOCKING_MODE
97023  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
97024  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
97025                          SQLITE_DEFAULT_LOCKING_MODE);
97026#endif
97027
97028  /* Enable the lookaside-malloc subsystem */
97029  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
97030                        sqlite3GlobalConfig.nLookaside);
97031
97032opendb_out:
97033  if( db ){
97034    assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
97035    sqlite3_mutex_leave(db->mutex);
97036  }
97037  rc = sqlite3_errcode(db);
97038  if( rc==SQLITE_NOMEM ){
97039    sqlite3_close(db);
97040    db = 0;
97041  }else if( rc!=SQLITE_OK ){
97042    db->magic = SQLITE_MAGIC_SICK;
97043  }
97044  *ppDb = db;
97045  return sqlite3ApiExit(0, rc);
97046}
97047
97048/*
97049** Open a new database handle.
97050*/
97051SQLITE_API int sqlite3_open(
97052  const char *zFilename,
97053  sqlite3 **ppDb
97054){
97055  return openDatabase(zFilename, ppDb,
97056                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
97057}
97058SQLITE_API int sqlite3_open_v2(
97059  const char *filename,   /* Database filename (UTF-8) */
97060  sqlite3 **ppDb,         /* OUT: SQLite db handle */
97061  int flags,              /* Flags */
97062  const char *zVfs        /* Name of VFS module to use */
97063){
97064  return openDatabase(filename, ppDb, flags, zVfs);
97065}
97066
97067#ifndef SQLITE_OMIT_UTF16
97068/*
97069** Open a new database handle.
97070*/
97071SQLITE_API int sqlite3_open16(
97072  const void *zFilename,
97073  sqlite3 **ppDb
97074){
97075  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
97076  sqlite3_value *pVal;
97077  int rc;
97078
97079  assert( zFilename );
97080  assert( ppDb );
97081  *ppDb = 0;
97082#ifndef SQLITE_OMIT_AUTOINIT
97083  rc = sqlite3_initialize();
97084  if( rc ) return rc;
97085#endif
97086  pVal = sqlite3ValueNew(0);
97087  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
97088  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
97089  if( zFilename8 ){
97090    rc = openDatabase(zFilename8, ppDb,
97091                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
97092    assert( *ppDb || rc==SQLITE_NOMEM );
97093    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
97094      ENC(*ppDb) = SQLITE_UTF16NATIVE;
97095    }
97096  }else{
97097    rc = SQLITE_NOMEM;
97098  }
97099  sqlite3ValueFree(pVal);
97100
97101  return sqlite3ApiExit(0, rc);
97102}
97103#endif /* SQLITE_OMIT_UTF16 */
97104
97105/*
97106** Register a new collation sequence with the database handle db.
97107*/
97108SQLITE_API int sqlite3_create_collation(
97109  sqlite3* db,
97110  const char *zName,
97111  int enc,
97112  void* pCtx,
97113  int(*xCompare)(void*,int,const void*,int,const void*)
97114){
97115  int rc;
97116  sqlite3_mutex_enter(db->mutex);
97117  assert( !db->mallocFailed );
97118  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
97119  rc = sqlite3ApiExit(db, rc);
97120  sqlite3_mutex_leave(db->mutex);
97121  return rc;
97122}
97123
97124/*
97125** Register a new collation sequence with the database handle db.
97126*/
97127SQLITE_API int sqlite3_create_collation_v2(
97128  sqlite3* db,
97129  const char *zName,
97130  int enc,
97131  void* pCtx,
97132  int(*xCompare)(void*,int,const void*,int,const void*),
97133  void(*xDel)(void*)
97134){
97135  int rc;
97136  sqlite3_mutex_enter(db->mutex);
97137  assert( !db->mallocFailed );
97138  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
97139  rc = sqlite3ApiExit(db, rc);
97140  sqlite3_mutex_leave(db->mutex);
97141  return rc;
97142}
97143
97144#ifndef SQLITE_OMIT_UTF16
97145/*
97146** Register a new collation sequence with the database handle db.
97147*/
97148SQLITE_API int sqlite3_create_collation16(
97149  sqlite3* db,
97150  const void *zName,
97151  int enc,
97152  void* pCtx,
97153  int(*xCompare)(void*,int,const void*,int,const void*)
97154){
97155  int rc = SQLITE_OK;
97156  char *zName8;
97157  sqlite3_mutex_enter(db->mutex);
97158  assert( !db->mallocFailed );
97159  zName8 = sqlite3Utf16to8(db, zName, -1);
97160  if( zName8 ){
97161    rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
97162    sqlite3DbFree(db, zName8);
97163  }
97164  rc = sqlite3ApiExit(db, rc);
97165  sqlite3_mutex_leave(db->mutex);
97166  return rc;
97167}
97168#endif /* SQLITE_OMIT_UTF16 */
97169
97170/*
97171** Register a collation sequence factory callback with the database handle
97172** db. Replace any previously installed collation sequence factory.
97173*/
97174SQLITE_API int sqlite3_collation_needed(
97175  sqlite3 *db,
97176  void *pCollNeededArg,
97177  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
97178){
97179  sqlite3_mutex_enter(db->mutex);
97180  db->xCollNeeded = xCollNeeded;
97181  db->xCollNeeded16 = 0;
97182  db->pCollNeededArg = pCollNeededArg;
97183  sqlite3_mutex_leave(db->mutex);
97184  return SQLITE_OK;
97185}
97186
97187#ifndef SQLITE_OMIT_UTF16
97188/*
97189** Register a collation sequence factory callback with the database handle
97190** db. Replace any previously installed collation sequence factory.
97191*/
97192SQLITE_API int sqlite3_collation_needed16(
97193  sqlite3 *db,
97194  void *pCollNeededArg,
97195  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
97196){
97197  sqlite3_mutex_enter(db->mutex);
97198  db->xCollNeeded = 0;
97199  db->xCollNeeded16 = xCollNeeded16;
97200  db->pCollNeededArg = pCollNeededArg;
97201  sqlite3_mutex_leave(db->mutex);
97202  return SQLITE_OK;
97203}
97204#endif /* SQLITE_OMIT_UTF16 */
97205
97206#ifndef SQLITE_OMIT_GLOBALRECOVER
97207#ifndef SQLITE_OMIT_DEPRECATED
97208/*
97209** This function is now an anachronism. It used to be used to recover from a
97210** malloc() failure, but SQLite now does this automatically.
97211*/
97212SQLITE_API int sqlite3_global_recover(void){
97213  return SQLITE_OK;
97214}
97215#endif
97216#endif
97217
97218/*
97219** Test to see whether or not the database connection is in autocommit
97220** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
97221** by default.  Autocommit is disabled by a BEGIN statement and reenabled
97222** by the next COMMIT or ROLLBACK.
97223**
97224******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
97225*/
97226SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
97227  return db->autoCommit;
97228}
97229
97230#ifdef SQLITE_DEBUG
97231/*
97232** The following routine is subtituted for constant SQLITE_CORRUPT in
97233** debugging builds.  This provides a way to set a breakpoint for when
97234** corruption is first detected.
97235*/
97236/* Begin Android Delete
97237SQLITE_PRIVATE int sqlite3Corrupt(void){
97238  return SQLITE_CORRUPT;
97239}
97240*/
97241#endif
97242
97243#ifndef SQLITE_OMIT_DEPRECATED
97244/*
97245** This is a convenience routine that makes sure that all thread-specific
97246** data for this thread has been deallocated.
97247**
97248** SQLite no longer uses thread-specific data so this routine is now a
97249** no-op.  It is retained for historical compatibility.
97250*/
97251SQLITE_API void sqlite3_thread_cleanup(void){
97252}
97253#endif
97254
97255/*
97256** Return meta information about a specific column of a database table.
97257** See comment in sqlite3.h (sqlite.h.in) for details.
97258*/
97259#ifdef SQLITE_ENABLE_COLUMN_METADATA
97260SQLITE_API int sqlite3_table_column_metadata(
97261  sqlite3 *db,                /* Connection handle */
97262  const char *zDbName,        /* Database name or NULL */
97263  const char *zTableName,     /* Table name */
97264  const char *zColumnName,    /* Column name */
97265  char const **pzDataType,    /* OUTPUT: Declared data type */
97266  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
97267  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
97268  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
97269  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
97270){
97271  int rc;
97272  char *zErrMsg = 0;
97273  Table *pTab = 0;
97274  Column *pCol = 0;
97275  int iCol;
97276
97277  char const *zDataType = 0;
97278  char const *zCollSeq = 0;
97279  int notnull = 0;
97280  int primarykey = 0;
97281  int autoinc = 0;
97282
97283  /* Ensure the database schema has been loaded */
97284  sqlite3_mutex_enter(db->mutex);
97285  (void)sqlite3SafetyOn(db);
97286  sqlite3BtreeEnterAll(db);
97287  rc = sqlite3Init(db, &zErrMsg);
97288  if( SQLITE_OK!=rc ){
97289    goto error_out;
97290  }
97291
97292  /* Locate the table in question */
97293  pTab = sqlite3FindTable(db, zTableName, zDbName);
97294  if( !pTab || pTab->pSelect ){
97295    pTab = 0;
97296    goto error_out;
97297  }
97298
97299  /* Find the column for which info is requested */
97300  if( sqlite3IsRowid(zColumnName) ){
97301    iCol = pTab->iPKey;
97302    if( iCol>=0 ){
97303      pCol = &pTab->aCol[iCol];
97304    }
97305  }else{
97306    for(iCol=0; iCol<pTab->nCol; iCol++){
97307      pCol = &pTab->aCol[iCol];
97308      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
97309        break;
97310      }
97311    }
97312    if( iCol==pTab->nCol ){
97313      pTab = 0;
97314      goto error_out;
97315    }
97316  }
97317
97318  /* The following block stores the meta information that will be returned
97319  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
97320  ** and autoinc. At this point there are two possibilities:
97321  **
97322  **     1. The specified column name was rowid", "oid" or "_rowid_"
97323  **        and there is no explicitly declared IPK column.
97324  **
97325  **     2. The table is not a view and the column name identified an
97326  **        explicitly declared column. Copy meta information from *pCol.
97327  */
97328  if( pCol ){
97329    zDataType = pCol->zType;
97330    zCollSeq = pCol->zColl;
97331    notnull = pCol->notNull!=0;
97332    primarykey  = pCol->isPrimKey!=0;
97333    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
97334  }else{
97335    zDataType = "INTEGER";
97336    primarykey = 1;
97337  }
97338  if( !zCollSeq ){
97339    zCollSeq = "BINARY";
97340  }
97341
97342error_out:
97343  sqlite3BtreeLeaveAll(db);
97344  (void)sqlite3SafetyOff(db);
97345
97346  /* Whether the function call succeeded or failed, set the output parameters
97347  ** to whatever their local counterparts contain. If an error did occur,
97348  ** this has the effect of zeroing all output parameters.
97349  */
97350  if( pzDataType ) *pzDataType = zDataType;
97351  if( pzCollSeq ) *pzCollSeq = zCollSeq;
97352  if( pNotNull ) *pNotNull = notnull;
97353  if( pPrimaryKey ) *pPrimaryKey = primarykey;
97354  if( pAutoinc ) *pAutoinc = autoinc;
97355
97356  if( SQLITE_OK==rc && !pTab ){
97357    sqlite3DbFree(db, zErrMsg);
97358    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
97359        zColumnName);
97360    rc = SQLITE_ERROR;
97361  }
97362  sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
97363  sqlite3DbFree(db, zErrMsg);
97364  rc = sqlite3ApiExit(db, rc);
97365  sqlite3_mutex_leave(db->mutex);
97366  return rc;
97367}
97368#endif
97369
97370/*
97371** Sleep for a little while.  Return the amount of time slept.
97372*/
97373SQLITE_API int sqlite3_sleep(int ms){
97374  sqlite3_vfs *pVfs;
97375  int rc;
97376  pVfs = sqlite3_vfs_find(0);
97377  if( pVfs==0 ) return 0;
97378
97379  /* This function works in milliseconds, but the underlying OsSleep()
97380  ** API uses microseconds. Hence the 1000's.
97381  */
97382  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
97383  return rc;
97384}
97385
97386/*
97387** Enable or disable the extended result codes.
97388*/
97389SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
97390  sqlite3_mutex_enter(db->mutex);
97391  db->errMask = onoff ? 0xffffffff : 0xff;
97392  sqlite3_mutex_leave(db->mutex);
97393  return SQLITE_OK;
97394}
97395
97396/*
97397** Invoke the xFileControl method on a particular database.
97398*/
97399SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
97400  int rc = SQLITE_ERROR;
97401  int iDb;
97402  sqlite3_mutex_enter(db->mutex);
97403  if( zDbName==0 ){
97404    iDb = 0;
97405  }else{
97406    for(iDb=0; iDb<db->nDb; iDb++){
97407      if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
97408    }
97409  }
97410  if( iDb<db->nDb ){
97411    Btree *pBtree = db->aDb[iDb].pBt;
97412    if( pBtree ){
97413      Pager *pPager;
97414      sqlite3_file *fd;
97415      sqlite3BtreeEnter(pBtree);
97416      pPager = sqlite3BtreePager(pBtree);
97417      assert( pPager!=0 );
97418      fd = sqlite3PagerFile(pPager);
97419      assert( fd!=0 );
97420      if( fd->pMethods ){
97421        rc = sqlite3OsFileControl(fd, op, pArg);
97422      }
97423      sqlite3BtreeLeave(pBtree);
97424    }
97425  }
97426  sqlite3_mutex_leave(db->mutex);
97427  return rc;
97428}
97429
97430/*
97431** Interface to the testing logic.
97432*/
97433SQLITE_API int sqlite3_test_control(int op, ...){
97434  int rc = 0;
97435#ifndef SQLITE_OMIT_BUILTIN_TEST
97436  va_list ap;
97437  va_start(ap, op);
97438  switch( op ){
97439
97440    /*
97441    ** Save the current state of the PRNG.
97442    */
97443    case SQLITE_TESTCTRL_PRNG_SAVE: {
97444      sqlite3PrngSaveState();
97445      break;
97446    }
97447
97448    /*
97449    ** Restore the state of the PRNG to the last state saved using
97450    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
97451    ** this verb acts like PRNG_RESET.
97452    */
97453    case SQLITE_TESTCTRL_PRNG_RESTORE: {
97454      sqlite3PrngRestoreState();
97455      break;
97456    }
97457
97458    /*
97459    ** Reset the PRNG back to its uninitialized state.  The next call
97460    ** to sqlite3_randomness() will reseed the PRNG using a single call
97461    ** to the xRandomness method of the default VFS.
97462    */
97463    case SQLITE_TESTCTRL_PRNG_RESET: {
97464      sqlite3PrngResetState();
97465      break;
97466    }
97467
97468    /*
97469    **  sqlite3_test_control(BITVEC_TEST, size, program)
97470    **
97471    ** Run a test against a Bitvec object of size.  The program argument
97472    ** is an array of integers that defines the test.  Return -1 on a
97473    ** memory allocation error, 0 on success, or non-zero for an error.
97474    ** See the sqlite3BitvecBuiltinTest() for additional information.
97475    */
97476    case SQLITE_TESTCTRL_BITVEC_TEST: {
97477      int sz = va_arg(ap, int);
97478      int *aProg = va_arg(ap, int*);
97479      rc = sqlite3BitvecBuiltinTest(sz, aProg);
97480      break;
97481    }
97482
97483    /*
97484    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
97485    **
97486    ** Register hooks to call to indicate which malloc() failures
97487    ** are benign.
97488    */
97489    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
97490      typedef void (*void_function)(void);
97491      void_function xBenignBegin;
97492      void_function xBenignEnd;
97493      xBenignBegin = va_arg(ap, void_function);
97494      xBenignEnd = va_arg(ap, void_function);
97495      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
97496      break;
97497    }
97498
97499    /*
97500    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
97501    **
97502    ** Set the PENDING byte to the value in the argument, if X>0.
97503    ** Make no changes if X==0.  Return the value of the pending byte
97504    ** as it existing before this routine was called.
97505    **
97506    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
97507    ** an incompatible database file format.  Changing the PENDING byte
97508    ** while any database connection is open results in undefined and
97509    ** dileterious behavior.
97510    */
97511    case SQLITE_TESTCTRL_PENDING_BYTE: {
97512      unsigned int newVal = va_arg(ap, unsigned int);
97513      rc = sqlite3PendingByte;
97514      if( newVal ) sqlite3PendingByte = newVal;
97515      break;
97516    }
97517
97518    /*
97519    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
97520    **
97521    ** This action provides a run-time test to see whether or not
97522    ** assert() was enabled at compile-time.  If X is true and assert()
97523    ** is enabled, then the return value is true.  If X is true and
97524    ** assert() is disabled, then the return value is zero.  If X is
97525    ** false and assert() is enabled, then the assertion fires and the
97526    ** process aborts.  If X is false and assert() is disabled, then the
97527    ** return value is zero.
97528    */
97529    case SQLITE_TESTCTRL_ASSERT: {
97530      volatile int x = 0;
97531      assert( (x = va_arg(ap,int))!=0 );
97532      rc = x;
97533      break;
97534    }
97535
97536
97537    /*
97538    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
97539    **
97540    ** This action provides a run-time test to see how the ALWAYS and
97541    ** NEVER macros were defined at compile-time.
97542    **
97543    ** The return value is ALWAYS(X).
97544    **
97545    ** The recommended test is X==2.  If the return value is 2, that means
97546    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
97547    ** default setting.  If the return value is 1, then ALWAYS() is either
97548    ** hard-coded to true or else it asserts if its argument is false.
97549    ** The first behavior (hard-coded to true) is the case if
97550    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
97551    ** behavior (assert if the argument to ALWAYS() is false) is the case if
97552    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
97553    **
97554    ** The run-time test procedure might look something like this:
97555    **
97556    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
97557    **      // ALWAYS() and NEVER() are no-op pass-through macros
97558    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
97559    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
97560    **    }else{
97561    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
97562    **    }
97563    */
97564    case SQLITE_TESTCTRL_ALWAYS: {
97565      int x = va_arg(ap,int);
97566      rc = ALWAYS(x);
97567      break;
97568    }
97569
97570    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
97571    **
97572    ** Set the nReserve size to N for the main database on the database
97573    ** connection db.
97574    */
97575    case SQLITE_TESTCTRL_RESERVE: {
97576      sqlite3 *db = va_arg(ap, sqlite3*);
97577      int x = va_arg(ap,int);
97578      sqlite3_mutex_enter(db->mutex);
97579      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
97580      sqlite3_mutex_leave(db->mutex);
97581      break;
97582    }
97583
97584    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
97585    **
97586    ** Enable or disable various optimizations for testing purposes.  The
97587    ** argument N is a bitmask of optimizations to be disabled.  For normal
97588    ** operation N should be 0.  The idea is that a test program (like the
97589    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
97590    ** with various optimizations disabled to verify that the same answer
97591    ** is obtained in every case.
97592    */
97593    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
97594      sqlite3 *db = va_arg(ap, sqlite3*);
97595      int x = va_arg(ap,int);
97596      db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
97597      break;
97598    }
97599
97600#ifdef SQLITE_N_KEYWORD
97601    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
97602    **
97603    ** If zWord is a keyword recognized by the parser, then return the
97604    ** number of keywords.  Or if zWord is not a keyword, return 0.
97605    **
97606    ** This test feature is only available in the amalgamation since
97607    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
97608    ** is built using separate source files.
97609    */
97610    case SQLITE_TESTCTRL_ISKEYWORD: {
97611      const char *zWord = va_arg(ap, const char*);
97612      int n = sqlite3Strlen30(zWord);
97613      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
97614      break;
97615    }
97616#endif
97617
97618  }
97619  va_end(ap);
97620#endif /* SQLITE_OMIT_BUILTIN_TEST */
97621  return rc;
97622}
97623
97624/************** End of main.c ************************************************/
97625/************** Begin file notify.c ******************************************/
97626/*
97627** 2009 March 3
97628**
97629** The author disclaims copyright to this source code.  In place of
97630** a legal notice, here is a blessing:
97631**
97632**    May you do good and not evil.
97633**    May you find forgiveness for yourself and forgive others.
97634**    May you share freely, never taking more than you give.
97635**
97636*************************************************************************
97637**
97638** This file contains the implementation of the sqlite3_unlock_notify()
97639** API method and its associated functionality.
97640*/
97641
97642/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
97643#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
97644
97645/*
97646** Public interfaces:
97647**
97648**   sqlite3ConnectionBlocked()
97649**   sqlite3ConnectionUnlocked()
97650**   sqlite3ConnectionClosed()
97651**   sqlite3_unlock_notify()
97652*/
97653
97654#define assertMutexHeld() \
97655  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
97656
97657/*
97658** Head of a linked list of all sqlite3 objects created by this process
97659** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
97660** is not NULL. This variable may only accessed while the STATIC_MASTER
97661** mutex is held.
97662*/
97663static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
97664
97665#ifndef NDEBUG
97666/*
97667** This function is a complex assert() that verifies the following
97668** properties of the blocked connections list:
97669**
97670**   1) Each entry in the list has a non-NULL value for either
97671**      pUnlockConnection or pBlockingConnection, or both.
97672**
97673**   2) All entries in the list that share a common value for
97674**      xUnlockNotify are grouped together.
97675**
97676**   3) If the argument db is not NULL, then none of the entries in the
97677**      blocked connections list have pUnlockConnection or pBlockingConnection
97678**      set to db. This is used when closing connection db.
97679*/
97680static void checkListProperties(sqlite3 *db){
97681  sqlite3 *p;
97682  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
97683    int seen = 0;
97684    sqlite3 *p2;
97685
97686    /* Verify property (1) */
97687    assert( p->pUnlockConnection || p->pBlockingConnection );
97688
97689    /* Verify property (2) */
97690    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
97691      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
97692      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
97693      assert( db==0 || p->pUnlockConnection!=db );
97694      assert( db==0 || p->pBlockingConnection!=db );
97695    }
97696  }
97697}
97698#else
97699# define checkListProperties(x)
97700#endif
97701
97702/*
97703** Remove connection db from the blocked connections list. If connection
97704** db is not currently a part of the list, this function is a no-op.
97705*/
97706static void removeFromBlockedList(sqlite3 *db){
97707  sqlite3 **pp;
97708  assertMutexHeld();
97709  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
97710    if( *pp==db ){
97711      *pp = (*pp)->pNextBlocked;
97712      break;
97713    }
97714  }
97715}
97716
97717/*
97718** Add connection db to the blocked connections list. It is assumed
97719** that it is not already a part of the list.
97720*/
97721static void addToBlockedList(sqlite3 *db){
97722  sqlite3 **pp;
97723  assertMutexHeld();
97724  for(
97725    pp=&sqlite3BlockedList;
97726    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
97727    pp=&(*pp)->pNextBlocked
97728  );
97729  db->pNextBlocked = *pp;
97730  *pp = db;
97731}
97732
97733/*
97734** Obtain the STATIC_MASTER mutex.
97735*/
97736static void enterMutex(void){
97737  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
97738  checkListProperties(0);
97739}
97740
97741/*
97742** Release the STATIC_MASTER mutex.
97743*/
97744static void leaveMutex(void){
97745  assertMutexHeld();
97746  checkListProperties(0);
97747  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
97748}
97749
97750/*
97751** Register an unlock-notify callback.
97752**
97753** This is called after connection "db" has attempted some operation
97754** but has received an SQLITE_LOCKED error because another connection
97755** (call it pOther) in the same process was busy using the same shared
97756** cache.  pOther is found by looking at db->pBlockingConnection.
97757**
97758** If there is no blocking connection, the callback is invoked immediately,
97759** before this routine returns.
97760**
97761** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
97762** a deadlock.
97763**
97764** Otherwise, make arrangements to invoke xNotify when pOther drops
97765** its locks.
97766**
97767** Each call to this routine overrides any prior callbacks registered
97768** on the same "db".  If xNotify==0 then any prior callbacks are immediately
97769** cancelled.
97770*/
97771SQLITE_API int sqlite3_unlock_notify(
97772  sqlite3 *db,
97773  void (*xNotify)(void **, int),
97774  void *pArg
97775){
97776  int rc = SQLITE_OK;
97777
97778  sqlite3_mutex_enter(db->mutex);
97779  enterMutex();
97780
97781  if( xNotify==0 ){
97782    removeFromBlockedList(db);
97783    db->pUnlockConnection = 0;
97784    db->xUnlockNotify = 0;
97785    db->pUnlockArg = 0;
97786  }else if( 0==db->pBlockingConnection ){
97787    /* The blocking transaction has been concluded. Or there never was a
97788    ** blocking transaction. In either case, invoke the notify callback
97789    ** immediately.
97790    */
97791    xNotify(&pArg, 1);
97792  }else{
97793    sqlite3 *p;
97794
97795    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
97796    if( p ){
97797      rc = SQLITE_LOCKED;              /* Deadlock detected. */
97798    }else{
97799      db->pUnlockConnection = db->pBlockingConnection;
97800      db->xUnlockNotify = xNotify;
97801      db->pUnlockArg = pArg;
97802      removeFromBlockedList(db);
97803      addToBlockedList(db);
97804    }
97805  }
97806
97807  leaveMutex();
97808  assert( !db->mallocFailed );
97809  sqlite3Error(db, rc, (rc?"database is deadlocked":0));
97810  sqlite3_mutex_leave(db->mutex);
97811  return rc;
97812}
97813
97814/*
97815** This function is called while stepping or preparing a statement
97816** associated with connection db. The operation will return SQLITE_LOCKED
97817** to the user because it requires a lock that will not be available
97818** until connection pBlocker concludes its current transaction.
97819*/
97820SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
97821  enterMutex();
97822  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
97823    addToBlockedList(db);
97824  }
97825  db->pBlockingConnection = pBlocker;
97826  leaveMutex();
97827}
97828
97829/*
97830** This function is called when
97831** the transaction opened by database db has just finished. Locks held
97832** by database connection db have been released.
97833**
97834** This function loops through each entry in the blocked connections
97835** list and does the following:
97836**
97837**   1) If the sqlite3.pBlockingConnection member of a list entry is
97838**      set to db, then set pBlockingConnection=0.
97839**
97840**   2) If the sqlite3.pUnlockConnection member of a list entry is
97841**      set to db, then invoke the configured unlock-notify callback and
97842**      set pUnlockConnection=0.
97843**
97844**   3) If the two steps above mean that pBlockingConnection==0 and
97845**      pUnlockConnection==0, remove the entry from the blocked connections
97846**      list.
97847*/
97848SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
97849  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
97850  int nArg = 0;                            /* Number of entries in aArg[] */
97851  sqlite3 **pp;                            /* Iterator variable */
97852  void **aArg;               /* Arguments to the unlock callback */
97853  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
97854  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
97855
97856  aArg = aStatic;
97857  enterMutex();         /* Enter STATIC_MASTER mutex */
97858
97859  /* This loop runs once for each entry in the blocked-connections list. */
97860  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
97861    sqlite3 *p = *pp;
97862
97863    /* Step 1. */
97864    if( p->pBlockingConnection==db ){
97865      p->pBlockingConnection = 0;
97866    }
97867
97868    /* Step 2. */
97869    if( p->pUnlockConnection==db ){
97870      assert( p->xUnlockNotify );
97871      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
97872        xUnlockNotify(aArg, nArg);
97873        nArg = 0;
97874      }
97875
97876      sqlite3BeginBenignMalloc();
97877      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
97878      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
97879      if( (!aDyn && nArg==(int)ArraySize(aStatic))
97880       || (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*)))
97881      ){
97882        /* The aArg[] array needs to grow. */
97883        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
97884        if( pNew ){
97885          memcpy(pNew, aArg, nArg*sizeof(void *));
97886          sqlite3_free(aDyn);
97887          aDyn = aArg = pNew;
97888        }else{
97889          /* This occurs when the array of context pointers that need to
97890          ** be passed to the unlock-notify callback is larger than the
97891          ** aStatic[] array allocated on the stack and the attempt to
97892          ** allocate a larger array from the heap has failed.
97893          **
97894          ** This is a difficult situation to handle. Returning an error
97895          ** code to the caller is insufficient, as even if an error code
97896          ** is returned the transaction on connection db will still be
97897          ** closed and the unlock-notify callbacks on blocked connections
97898          ** will go unissued. This might cause the application to wait
97899          ** indefinitely for an unlock-notify callback that will never
97900          ** arrive.
97901          **
97902          ** Instead, invoke the unlock-notify callback with the context
97903          ** array already accumulated. We can then clear the array and
97904          ** begin accumulating any further context pointers without
97905          ** requiring any dynamic allocation. This is sub-optimal because
97906          ** it means that instead of one callback with a large array of
97907          ** context pointers the application will receive two or more
97908          ** callbacks with smaller arrays of context pointers, which will
97909          ** reduce the applications ability to prioritize multiple
97910          ** connections. But it is the best that can be done under the
97911          ** circumstances.
97912          */
97913          xUnlockNotify(aArg, nArg);
97914          nArg = 0;
97915        }
97916      }
97917      sqlite3EndBenignMalloc();
97918
97919      aArg[nArg++] = p->pUnlockArg;
97920      xUnlockNotify = p->xUnlockNotify;
97921      p->pUnlockConnection = 0;
97922      p->xUnlockNotify = 0;
97923      p->pUnlockArg = 0;
97924    }
97925
97926    /* Step 3. */
97927    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
97928      /* Remove connection p from the blocked connections list. */
97929      *pp = p->pNextBlocked;
97930      p->pNextBlocked = 0;
97931    }else{
97932      pp = &p->pNextBlocked;
97933    }
97934  }
97935
97936  if( nArg!=0 ){
97937    xUnlockNotify(aArg, nArg);
97938  }
97939  sqlite3_free(aDyn);
97940  leaveMutex();         /* Leave STATIC_MASTER mutex */
97941}
97942
97943/*
97944** This is called when the database connection passed as an argument is
97945** being closed. The connection is removed from the blocked list.
97946*/
97947SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
97948  sqlite3ConnectionUnlocked(db);
97949  enterMutex();
97950  removeFromBlockedList(db);
97951  checkListProperties(db);
97952  leaveMutex();
97953}
97954#endif
97955
97956/************** End of notify.c **********************************************/
97957/************** Begin file fts3.c ********************************************/
97958/*
97959** 2006 Oct 10
97960**
97961** The author disclaims copyright to this source code.  In place of
97962** a legal notice, here is a blessing:
97963**
97964**    May you do good and not evil.
97965**    May you find forgiveness for yourself and forgive others.
97966**    May you share freely, never taking more than you give.
97967**
97968******************************************************************************
97969**
97970** This is an SQLite module implementing full-text search.
97971*/
97972
97973/*
97974** The code in this file is only compiled if:
97975**
97976**     * The FTS3 module is being built as an extension
97977**       (in which case SQLITE_CORE is not defined), or
97978**
97979**     * The FTS3 module is being built into the core of
97980**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
97981*/
97982
97983/* TODO(shess) Consider exporting this comment to an HTML file or the
97984** wiki.
97985*/
97986/* The full-text index is stored in a series of b+tree (-like)
97987** structures called segments which map terms to doclists.  The
97988** structures are like b+trees in layout, but are constructed from the
97989** bottom up in optimal fashion and are not updatable.  Since trees
97990** are built from the bottom up, things will be described from the
97991** bottom up.
97992**
97993**
97994**** Varints ****
97995** The basic unit of encoding is a variable-length integer called a
97996** varint.  We encode variable-length integers in little-endian order
97997** using seven bits * per byte as follows:
97998**
97999** KEY:
98000**         A = 0xxxxxxx    7 bits of data and one flag bit
98001**         B = 1xxxxxxx    7 bits of data and one flag bit
98002**
98003**  7 bits - A
98004** 14 bits - BA
98005** 21 bits - BBA
98006** and so on.
98007**
98008** This is identical to how sqlite encodes varints (see util.c).
98009**
98010**
98011**** Document lists ****
98012** A doclist (document list) holds a docid-sorted list of hits for a
98013** given term.  Doclists hold docids, and can optionally associate
98014** token positions and offsets with docids.
98015**
98016** A DL_POSITIONS_OFFSETS doclist is stored like this:
98017**
98018** array {
98019**   varint docid;
98020**   array {                (position list for column 0)
98021**     varint position;     (delta from previous position plus POS_BASE)
98022**     varint startOffset;  (delta from previous startOffset)
98023**     varint endOffset;    (delta from startOffset)
98024**   }
98025**   array {
98026**     varint POS_COLUMN;   (marks start of position list for new column)
98027**     varint column;       (index of new column)
98028**     array {
98029**       varint position;   (delta from previous position plus POS_BASE)
98030**       varint startOffset;(delta from previous startOffset)
98031**       varint endOffset;  (delta from startOffset)
98032**     }
98033**   }
98034**   varint POS_END;        (marks end of positions for this document.
98035** }
98036**
98037** Here, array { X } means zero or more occurrences of X, adjacent in
98038** memory.  A "position" is an index of a token in the token stream
98039** generated by the tokenizer, while an "offset" is a byte offset,
98040** both based at 0.  Note that POS_END and POS_COLUMN occur in the
98041** same logical place as the position element, and act as sentinals
98042** ending a position list array.
98043**
98044** A DL_POSITIONS doclist omits the startOffset and endOffset
98045** information.  A DL_DOCIDS doclist omits both the position and
98046** offset information, becoming an array of varint-encoded docids.
98047**
98048** On-disk data is stored as type DL_DEFAULT, so we don't serialize
98049** the type.  Due to how deletion is implemented in the segmentation
98050** system, on-disk doclists MUST store at least positions.
98051**
98052**
98053**** Segment leaf nodes ****
98054** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
98055** nodes are written using LeafWriter, and read using LeafReader (to
98056** iterate through a single leaf node's data) and LeavesReader (to
98057** iterate through a segment's entire leaf layer).  Leaf nodes have
98058** the format:
98059**
98060** varint iHeight;             (height from leaf level, always 0)
98061** varint nTerm;               (length of first term)
98062** char pTerm[nTerm];          (content of first term)
98063** varint nDoclist;            (length of term's associated doclist)
98064** char pDoclist[nDoclist];    (content of doclist)
98065** array {
98066**                             (further terms are delta-encoded)
98067**   varint nPrefix;           (length of prefix shared with previous term)
98068**   varint nSuffix;           (length of unshared suffix)
98069**   char pTermSuffix[nSuffix];(unshared suffix of next term)
98070**   varint nDoclist;          (length of term's associated doclist)
98071**   char pDoclist[nDoclist];  (content of doclist)
98072** }
98073**
98074** Here, array { X } means zero or more occurrences of X, adjacent in
98075** memory.
98076**
98077** Leaf nodes are broken into blocks which are stored contiguously in
98078** the %_segments table in sorted order.  This means that when the end
98079** of a node is reached, the next term is in the node with the next
98080** greater node id.
98081**
98082** New data is spilled to a new leaf node when the current node
98083** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
98084** larger than STANDALONE_MIN (default 1024) is placed in a standalone
98085** node (a leaf node with a single term and doclist).  The goal of
98086** these settings is to pack together groups of small doclists while
98087** making it efficient to directly access large doclists.  The
98088** assumption is that large doclists represent terms which are more
98089** likely to be query targets.
98090**
98091** TODO(shess) It may be useful for blocking decisions to be more
98092** dynamic.  For instance, it may make more sense to have a 2.5k leaf
98093** node rather than splitting into 2k and .5k nodes.  My intuition is
98094** that this might extend through 2x or 4x the pagesize.
98095**
98096**
98097**** Segment interior nodes ****
98098** Segment interior nodes store blockids for subtree nodes and terms
98099** to describe what data is stored by the each subtree.  Interior
98100** nodes are written using InteriorWriter, and read using
98101** InteriorReader.  InteriorWriters are created as needed when
98102** SegmentWriter creates new leaf nodes, or when an interior node
98103** itself grows too big and must be split.  The format of interior
98104** nodes:
98105**
98106** varint iHeight;           (height from leaf level, always >0)
98107** varint iBlockid;          (block id of node's leftmost subtree)
98108** optional {
98109**   varint nTerm;           (length of first term)
98110**   char pTerm[nTerm];      (content of first term)
98111**   array {
98112**                                (further terms are delta-encoded)
98113**     varint nPrefix;            (length of shared prefix with previous term)
98114**     varint nSuffix;            (length of unshared suffix)
98115**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
98116**   }
98117** }
98118**
98119** Here, optional { X } means an optional element, while array { X }
98120** means zero or more occurrences of X, adjacent in memory.
98121**
98122** An interior node encodes n terms separating n+1 subtrees.  The
98123** subtree blocks are contiguous, so only the first subtree's blockid
98124** is encoded.  The subtree at iBlockid will contain all terms less
98125** than the first term encoded (or all terms if no term is encoded).
98126** Otherwise, for terms greater than or equal to pTerm[i] but less
98127** than pTerm[i+1], the subtree for that term will be rooted at
98128** iBlockid+i.  Interior nodes only store enough term data to
98129** distinguish adjacent children (if the rightmost term of the left
98130** child is "something", and the leftmost term of the right child is
98131** "wicked", only "w" is stored).
98132**
98133** New data is spilled to a new interior node at the same height when
98134** the current node exceeds INTERIOR_MAX bytes (default 2048).
98135** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
98136** interior nodes and making the tree too skinny.  The interior nodes
98137** at a given height are naturally tracked by interior nodes at
98138** height+1, and so on.
98139**
98140**
98141**** Segment directory ****
98142** The segment directory in table %_segdir stores meta-information for
98143** merging and deleting segments, and also the root node of the
98144** segment's tree.
98145**
98146** The root node is the top node of the segment's tree after encoding
98147** the entire segment, restricted to ROOT_MAX bytes (default 1024).
98148** This could be either a leaf node or an interior node.  If the top
98149** node requires more than ROOT_MAX bytes, it is flushed to %_segments
98150** and a new root interior node is generated (which should always fit
98151** within ROOT_MAX because it only needs space for 2 varints, the
98152** height and the blockid of the previous root).
98153**
98154** The meta-information in the segment directory is:
98155**   level               - segment level (see below)
98156**   idx                 - index within level
98157**                       - (level,idx uniquely identify a segment)
98158**   start_block         - first leaf node
98159**   leaves_end_block    - last leaf node
98160**   end_block           - last block (including interior nodes)
98161**   root                - contents of root node
98162**
98163** If the root node is a leaf node, then start_block,
98164** leaves_end_block, and end_block are all 0.
98165**
98166**
98167**** Segment merging ****
98168** To amortize update costs, segments are grouped into levels and
98169** merged in batches.  Each increase in level represents exponentially
98170** more documents.
98171**
98172** New documents (actually, document updates) are tokenized and
98173** written individually (using LeafWriter) to a level 0 segment, with
98174** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
98175** level 0 segments are merged into a single level 1 segment.  Level 1
98176** is populated like level 0, and eventually MERGE_COUNT level 1
98177** segments are merged to a single level 2 segment (representing
98178** MERGE_COUNT^2 updates), and so on.
98179**
98180** A segment merge traverses all segments at a given level in
98181** parallel, performing a straightforward sorted merge.  Since segment
98182** leaf nodes are written in to the %_segments table in order, this
98183** merge traverses the underlying sqlite disk structures efficiently.
98184** After the merge, all segment blocks from the merged level are
98185** deleted.
98186**
98187** MERGE_COUNT controls how often we merge segments.  16 seems to be
98188** somewhat of a sweet spot for insertion performance.  32 and 64 show
98189** very similar performance numbers to 16 on insertion, though they're
98190** a tiny bit slower (perhaps due to more overhead in merge-time
98191** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
98192** 16, 2 about 66% slower than 16.
98193**
98194** At query time, high MERGE_COUNT increases the number of segments
98195** which need to be scanned and merged.  For instance, with 100k docs
98196** inserted:
98197**
98198**    MERGE_COUNT   segments
98199**       16           25
98200**        8           12
98201**        4           10
98202**        2            6
98203**
98204** This appears to have only a moderate impact on queries for very
98205** frequent terms (which are somewhat dominated by segment merge
98206** costs), and infrequent and non-existent terms still seem to be fast
98207** even with many segments.
98208**
98209** TODO(shess) That said, it would be nice to have a better query-side
98210** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
98211** optimizations to things like doclist merging will swing the sweet
98212** spot around.
98213**
98214**
98215**
98216**** Handling of deletions and updates ****
98217** Since we're using a segmented structure, with no docid-oriented
98218** index into the term index, we clearly cannot simply update the term
98219** index when a document is deleted or updated.  For deletions, we
98220** write an empty doclist (varint(docid) varint(POS_END)), for updates
98221** we simply write the new doclist.  Segment merges overwrite older
98222** data for a particular docid with newer data, so deletes or updates
98223** will eventually overtake the earlier data and knock it out.  The
98224** query logic likewise merges doclists so that newer data knocks out
98225** older data.
98226**
98227** TODO(shess) Provide a VACUUM type operation to clear out all
98228** deletions and duplications.  This would basically be a forced merge
98229** into a single segment.
98230*/
98231
98232#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
98233
98234#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
98235# define SQLITE_CORE 1
98236#endif
98237
98238/************** Include fts3Int.h in the middle of fts3.c ********************/
98239/************** Begin file fts3Int.h *****************************************/
98240/*
98241** 2009 Nov 12
98242**
98243** The author disclaims copyright to this source code.  In place of
98244** a legal notice, here is a blessing:
98245**
98246**    May you do good and not evil.
98247**    May you find forgiveness for yourself and forgive others.
98248**    May you share freely, never taking more than you give.
98249**
98250******************************************************************************
98251**
98252*/
98253
98254#ifndef _FTSINT_H
98255#define _FTSINT_H
98256
98257#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
98258# define NDEBUG 1
98259#endif
98260
98261/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
98262/************** Begin file fts3_tokenizer.h **********************************/
98263/*
98264** 2006 July 10
98265**
98266** The author disclaims copyright to this source code.
98267**
98268*************************************************************************
98269** Defines the interface to tokenizers used by fulltext-search.  There
98270** are three basic components:
98271**
98272** sqlite3_tokenizer_module is a singleton defining the tokenizer
98273** interface functions.  This is essentially the class structure for
98274** tokenizers.
98275**
98276** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
98277** including customization information defined at creation time.
98278**
98279** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
98280** tokens from a particular input.
98281*/
98282#ifndef _FTS3_TOKENIZER_H_
98283#define _FTS3_TOKENIZER_H_
98284
98285/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
98286** If tokenizers are to be allowed to call sqlite3_*() functions, then
98287** we will need a way to register the API consistently.
98288*/
98289
98290/*
98291** Structures used by the tokenizer interface. When a new tokenizer
98292** implementation is registered, the caller provides a pointer to
98293** an sqlite3_tokenizer_module containing pointers to the callback
98294** functions that make up an implementation.
98295**
98296** When an fts3 table is created, it passes any arguments passed to
98297** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
98298** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
98299** implementation. The xCreate() function in turn returns an
98300** sqlite3_tokenizer structure representing the specific tokenizer to
98301** be used for the fts3 table (customized by the tokenizer clause arguments).
98302**
98303** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
98304** method is called. It returns an sqlite3_tokenizer_cursor object
98305** that may be used to tokenize a specific input buffer based on
98306** the tokenization rules supplied by a specific sqlite3_tokenizer
98307** object.
98308*/
98309typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
98310typedef struct sqlite3_tokenizer sqlite3_tokenizer;
98311typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
98312
98313struct sqlite3_tokenizer_module {
98314
98315  /*
98316  ** Structure version. Should always be set to 0.
98317  */
98318  int iVersion;
98319
98320  /*
98321  ** Create a new tokenizer. The values in the argv[] array are the
98322  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
98323  ** TABLE statement that created the fts3 table. For example, if
98324  ** the following SQL is executed:
98325  **
98326  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
98327  **
98328  ** then argc is set to 2, and the argv[] array contains pointers
98329  ** to the strings "arg1" and "arg2".
98330  **
98331  ** This method should return either SQLITE_OK (0), or an SQLite error
98332  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
98333  ** to point at the newly created tokenizer structure. The generic
98334  ** sqlite3_tokenizer.pModule variable should not be initialised by
98335  ** this callback. The caller will do so.
98336  */
98337  int (*xCreate)(
98338    int argc,                           /* Size of argv array */
98339    const char *const*argv,             /* Tokenizer argument strings */
98340    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
98341  );
98342
98343  /*
98344  ** Destroy an existing tokenizer. The fts3 module calls this method
98345  ** exactly once for each successful call to xCreate().
98346  */
98347  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
98348
98349  /*
98350  ** Create a tokenizer cursor to tokenize an input buffer. The caller
98351  ** is responsible for ensuring that the input buffer remains valid
98352  ** until the cursor is closed (using the xClose() method).
98353  */
98354  int (*xOpen)(
98355    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
98356    const char *pInput, int nBytes,      /* Input buffer */
98357    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
98358  );
98359
98360  /*
98361  ** Destroy an existing tokenizer cursor. The fts3 module calls this
98362  ** method exactly once for each successful call to xOpen().
98363  */
98364  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
98365
98366  /*
98367  ** Retrieve the next token from the tokenizer cursor pCursor. This
98368  ** method should either return SQLITE_OK and set the values of the
98369  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
98370  ** the end of the buffer has been reached, or an SQLite error code.
98371  **
98372  ** *ppToken should be set to point at a buffer containing the
98373  ** normalized version of the token (i.e. after any case-folding and/or
98374  ** stemming has been performed). *pnBytes should be set to the length
98375  ** of this buffer in bytes. The input text that generated the token is
98376  ** identified by the byte offsets returned in *piStartOffset and
98377  ** *piEndOffset. *piStartOffset should be set to the index of the first
98378  ** byte of the token in the input buffer. *piEndOffset should be set
98379  ** to the index of the first byte just past the end of the token in
98380  ** the input buffer.
98381  **
98382  ** The buffer *ppToken is set to point at is managed by the tokenizer
98383  ** implementation. It is only required to be valid until the next call
98384  ** to xNext() or xClose().
98385  */
98386  /* TODO(shess) current implementation requires pInput to be
98387  ** nul-terminated.  This should either be fixed, or pInput/nBytes
98388  ** should be converted to zInput.
98389  */
98390  int (*xNext)(
98391    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
98392    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
98393    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
98394    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
98395    int *piPosition      /* OUT: Number of tokens returned before this one */
98396  );
98397};
98398
98399struct sqlite3_tokenizer {
98400  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
98401  /* Tokenizer implementations will typically add additional fields */
98402};
98403
98404struct sqlite3_tokenizer_cursor {
98405  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
98406  /* Tokenizer implementations will typically add additional fields */
98407};
98408
98409int fts3_global_term_cnt(int iTerm, int iCol);
98410int fts3_term_cnt(int iTerm, int iCol);
98411
98412
98413#endif /* _FTS3_TOKENIZER_H_ */
98414
98415/************** End of fts3_tokenizer.h **************************************/
98416/************** Continuing where we left off in fts3Int.h ********************/
98417/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
98418/************** Begin file fts3_hash.h ***************************************/
98419/*
98420** 2001 September 22
98421**
98422** The author disclaims copyright to this source code.  In place of
98423** a legal notice, here is a blessing:
98424**
98425**    May you do good and not evil.
98426**    May you find forgiveness for yourself and forgive others.
98427**    May you share freely, never taking more than you give.
98428**
98429*************************************************************************
98430** This is the header file for the generic hash-table implemenation
98431** used in SQLite.  We've modified it slightly to serve as a standalone
98432** hash table implementation for the full-text indexing module.
98433**
98434*/
98435#ifndef _FTS3_HASH_H_
98436#define _FTS3_HASH_H_
98437
98438/* Forward declarations of structures. */
98439typedef struct Fts3Hash Fts3Hash;
98440typedef struct Fts3HashElem Fts3HashElem;
98441
98442/* A complete hash table is an instance of the following structure.
98443** The internals of this structure are intended to be opaque -- client
98444** code should not attempt to access or modify the fields of this structure
98445** directly.  Change this structure only by using the routines below.
98446** However, many of the "procedures" and "functions" for modifying and
98447** accessing this structure are really macros, so we can't really make
98448** this structure opaque.
98449*/
98450struct Fts3Hash {
98451  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
98452  char copyKey;           /* True if copy of key made on insert */
98453  int count;              /* Number of entries in this table */
98454  Fts3HashElem *first;    /* The first element of the array */
98455  int htsize;             /* Number of buckets in the hash table */
98456  struct _fts3ht {        /* the hash table */
98457    int count;               /* Number of entries with this hash */
98458    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
98459  } *ht;
98460};
98461
98462/* Each element in the hash table is an instance of the following
98463** structure.  All elements are stored on a single doubly-linked list.
98464**
98465** Again, this structure is intended to be opaque, but it can't really
98466** be opaque because it is used by macros.
98467*/
98468struct Fts3HashElem {
98469  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
98470  void *data;                /* Data associated with this element */
98471  void *pKey; int nKey;      /* Key associated with this element */
98472};
98473
98474/*
98475** There are 2 different modes of operation for a hash table:
98476**
98477**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
98478**                           (including the null-terminator, if any).  Case
98479**                           is respected in comparisons.
98480**
98481**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
98482**                           memcmp() is used to compare keys.
98483**
98484** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
98485*/
98486#define FTS3_HASH_STRING    1
98487#define FTS3_HASH_BINARY    2
98488
98489/*
98490** Access routines.  To delete, insert a NULL pointer.
98491*/
98492SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
98493SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
98494SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
98495SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
98496SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
98497
98498/*
98499** Shorthand for the functions above
98500*/
98501#define fts3HashInit     sqlite3Fts3HashInit
98502#define fts3HashInsert   sqlite3Fts3HashInsert
98503#define fts3HashFind     sqlite3Fts3HashFind
98504#define fts3HashClear    sqlite3Fts3HashClear
98505#define fts3HashFindElem sqlite3Fts3HashFindElem
98506
98507/*
98508** Macros for looping over all elements of a hash table.  The idiom is
98509** like this:
98510**
98511**   Fts3Hash h;
98512**   Fts3HashElem *p;
98513**   ...
98514**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
98515**     SomeStructure *pData = fts3HashData(p);
98516**     // do something with pData
98517**   }
98518*/
98519#define fts3HashFirst(H)  ((H)->first)
98520#define fts3HashNext(E)   ((E)->next)
98521#define fts3HashData(E)   ((E)->data)
98522#define fts3HashKey(E)    ((E)->pKey)
98523#define fts3HashKeysize(E) ((E)->nKey)
98524
98525/*
98526** Number of entries in a hash table
98527*/
98528#define fts3HashCount(H)  ((H)->count)
98529
98530#endif /* _FTS3_HASH_H_ */
98531
98532/************** End of fts3_hash.h *******************************************/
98533/************** Continuing where we left off in fts3Int.h ********************/
98534
98535/*
98536** This constant controls how often segments are merged. Once there are
98537** FTS3_MERGE_COUNT segments of level N, they are merged into a single
98538** segment of level N+1.
98539*/
98540#define FTS3_MERGE_COUNT 16
98541
98542/*
98543** This is the maximum amount of data (in bytes) to store in the
98544** Fts3Table.pendingTerms hash table. Normally, the hash table is
98545** populated as documents are inserted/updated/deleted in a transaction
98546** and used to create a new segment when the transaction is committed.
98547** However if this limit is reached midway through a transaction, a new
98548** segment is created and the hash table cleared immediately.
98549*/
98550#define FTS3_MAX_PENDING_DATA (1*1024*1024)
98551
98552/*
98553** Macro to return the number of elements in an array. SQLite has a
98554** similar macro called ArraySize(). Use a different name to avoid
98555** a collision when building an amalgamation with built-in FTS3.
98556*/
98557#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
98558
98559/*
98560** Maximum length of a varint encoded integer. The varint format is different
98561** from that used by SQLite, so the maximum length is 10, not 9.
98562*/
98563#define FTS3_VARINT_MAX 10
98564
98565/*
98566** This section provides definitions to allow the
98567** FTS3 extension to be compiled outside of the
98568** amalgamation.
98569*/
98570#ifndef SQLITE_AMALGAMATION
98571/*
98572** Macros indicating that conditional expressions are always true or
98573** false.
98574*/
98575# define ALWAYS(x) (x)
98576# define NEVER(X)  (x)
98577/*
98578** Internal types used by SQLite.
98579*/
98580typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
98581typedef short int i16;            /* 2-byte (or larger) signed integer */
98582typedef unsigned int u32;         /* 4-byte unsigned integer */
98583typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
98584/*
98585** Macro used to suppress compiler warnings for unused parameters.
98586*/
98587#define UNUSED_PARAMETER(x) (void)(x)
98588#endif
98589
98590typedef struct Fts3Table Fts3Table;
98591typedef struct Fts3Cursor Fts3Cursor;
98592typedef struct Fts3Expr Fts3Expr;
98593typedef struct Fts3Phrase Fts3Phrase;
98594typedef struct Fts3SegReader Fts3SegReader;
98595typedef struct Fts3SegFilter Fts3SegFilter;
98596
98597/*
98598** A connection to a fulltext index is an instance of the following
98599** structure. The xCreate and xConnect methods create an instance
98600** of this structure and xDestroy and xDisconnect free that instance.
98601** All other methods receive a pointer to the structure as one of their
98602** arguments.
98603*/
98604struct Fts3Table {
98605  sqlite3_vtab base;              /* Base class used by SQLite core */
98606  sqlite3 *db;                    /* The database connection */
98607  const char *zDb;                /* logical database name */
98608  const char *zName;              /* virtual table name */
98609  int nColumn;                    /* number of named columns in virtual table */
98610  char **azColumn;                /* column names.  malloced */
98611  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
98612
98613  /* Precompiled statements used by the implementation. Each of these
98614  ** statements is run and reset within a single virtual table API call.
98615  */
98616  sqlite3_stmt *aStmt[18];
98617
98618  /* Pointer to string containing the SQL:
98619  **
98620  ** "SELECT block FROM %_segments WHERE blockid BETWEEN ? AND ?
98621  **    ORDER BY blockid"
98622  */
98623  char *zSelectLeaves;
98624  int nLeavesStmt;                /* Valid statements in aLeavesStmt */
98625  int nLeavesTotal;               /* Total number of prepared leaves stmts */
98626  int nLeavesAlloc;               /* Allocated size of aLeavesStmt */
98627  sqlite3_stmt **aLeavesStmt;     /* Array of prepared zSelectLeaves stmts */
98628
98629  int nNodeSize;                  /* Soft limit for node size */
98630
98631  /* The following hash table is used to buffer pending index updates during
98632  ** transactions. Variable nPendingData estimates the memory size of the
98633  ** pending data, including hash table overhead, but not malloc overhead.
98634  ** When nPendingData exceeds nMaxPendingData, the buffer is flushed
98635  ** automatically. Variable iPrevDocid is the docid of the most recently
98636  ** inserted record.
98637  */
98638  int nMaxPendingData;
98639  int nPendingData;
98640  sqlite_int64 iPrevDocid;
98641  Fts3Hash pendingTerms;
98642};
98643
98644/*
98645** When the core wants to read from the virtual table, it creates a
98646** virtual table cursor (an instance of the following structure) using
98647** the xOpen method. Cursors are destroyed using the xClose method.
98648*/
98649struct Fts3Cursor {
98650  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
98651  i16 eSearch;                    /* Search strategy (see below) */
98652  u8 isEof;                       /* True if at End Of Results */
98653  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
98654  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
98655  Fts3Expr *pExpr;                /* Parsed MATCH query string */
98656  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
98657  char *pNextId;                  /* Pointer into the body of aDoclist */
98658  char *aDoclist;                 /* List of docids for full-text queries */
98659  int nDoclist;                   /* Size of buffer at aDoclist */
98660  int isMatchinfoOk;              /* True when aMatchinfo[] matches iPrevId */
98661  u32 *aMatchinfo;
98662};
98663
98664/*
98665** The Fts3Cursor.eSearch member is always set to one of the following.
98666** Actualy, Fts3Cursor.eSearch can be greater than or equal to
98667** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
98668** of the column to be searched.  For example, in
98669**
98670**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
98671**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
98672**
98673** Because the LHS of the MATCH operator is 2nd column "b",
98674** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
98675** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
98676** indicating that all columns should be searched,
98677** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
98678*/
98679#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
98680#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
98681#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
98682
98683/*
98684** A "phrase" is a sequence of one or more tokens that must match in
98685** sequence.  A single token is the base case and the most common case.
98686** For a sequence of tokens contained in "...", nToken will be the number
98687** of tokens in the string.
98688*/
98689struct Fts3Phrase {
98690  int nToken;                /* Number of tokens in the phrase */
98691  int iColumn;               /* Index of column this phrase must match */
98692  int isNot;                 /* Phrase prefixed by unary not (-) operator */
98693  struct PhraseToken {
98694    char *z;                 /* Text of the token */
98695    int n;                   /* Number of bytes in buffer pointed to by z */
98696    int isPrefix;            /* True if token ends in with a "*" character */
98697  } aToken[1];               /* One entry for each token in the phrase */
98698};
98699
98700/*
98701** A tree of these objects forms the RHS of a MATCH operator.
98702**
98703** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
98704** is true, then aDoclist points to a malloced buffer, size nDoclist bytes,
98705** containing the results of the NEAR or phrase query in FTS3 doclist
98706** format. As usual, the initial "Length" field found in doclists stored
98707** on disk is omitted from this buffer.
98708**
98709** Variable pCurrent always points to the start of a docid field within
98710** aDoclist. Since the doclist is usually scanned in docid order, this can
98711** be used to accelerate seeking to the required docid within the doclist.
98712*/
98713struct Fts3Expr {
98714  int eType;                 /* One of the FTSQUERY_XXX values defined below */
98715  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
98716  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
98717  Fts3Expr *pLeft;           /* Left operand */
98718  Fts3Expr *pRight;          /* Right operand */
98719  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
98720
98721  int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
98722  char *aDoclist;            /* Buffer containing doclist */
98723  int nDoclist;              /* Size of aDoclist in bytes */
98724
98725  sqlite3_int64 iCurrent;
98726  char *pCurrent;
98727};
98728
98729/*
98730** Candidate values for Fts3Query.eType. Note that the order of the first
98731** four values is in order of precedence when parsing expressions. For
98732** example, the following:
98733**
98734**   "a OR b AND c NOT d NEAR e"
98735**
98736** is equivalent to:
98737**
98738**   "a OR (b AND (c NOT (d NEAR e)))"
98739*/
98740#define FTSQUERY_NEAR   1
98741#define FTSQUERY_NOT    2
98742#define FTSQUERY_AND    3
98743#define FTSQUERY_OR     4
98744#define FTSQUERY_PHRASE 5
98745
98746
98747/* fts3_init.c */
98748SQLITE_PRIVATE int sqlite3Fts3DeleteVtab(int, sqlite3_vtab *);
98749SQLITE_PRIVATE int sqlite3Fts3InitVtab(int, sqlite3*, void*, int, const char*const*,
98750                        sqlite3_vtab **, char **);
98751
98752/* fts3_write.c */
98753SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
98754SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
98755SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
98756SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
98757SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(Fts3Table *,int, sqlite3_int64,
98758  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
98759SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
98760SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *, Fts3SegReader *);
98761SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
98762  Fts3Table *, Fts3SegReader **, int, Fts3SegFilter *,
98763  int (*)(Fts3Table *, void *, char *, int, char *, int),  void *
98764);
98765SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char const**, int*);
98766SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
98767
98768/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
98769#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
98770#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
98771#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
98772#define FTS3_SEGMENT_PREFIX        0x00000008
98773
98774/* Type passed as 4th argument to SegmentReaderIterate() */
98775struct Fts3SegFilter {
98776  const char *zTerm;
98777  int nTerm;
98778  int iCol;
98779  int flags;
98780};
98781
98782/* fts3.c */
98783SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
98784SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
98785SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
98786SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
98787SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
98788
98789SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
98790SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *, Fts3Expr *);
98791
98792/* fts3_tokenizer.c */
98793SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
98794SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
98795SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash,
98796  const char *, sqlite3_tokenizer **, const char **, char **
98797);
98798
98799/* fts3_snippet.c */
98800SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
98801SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context*, Fts3Cursor*,
98802  const char *, const char *, const char *
98803);
98804SQLITE_PRIVATE void sqlite3Fts3Snippet2(sqlite3_context *, Fts3Cursor *, const char *,
98805  const char *, const char *, int, int
98806);
98807SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *);
98808
98809/* fts3_expr.c */
98810SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *,
98811  char **, int, int, const char *, int, Fts3Expr **
98812);
98813SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
98814#ifdef SQLITE_TEST
98815SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
98816#endif
98817
98818#endif /* _FTSINT_H */
98819
98820/************** End of fts3Int.h *********************************************/
98821/************** Continuing where we left off in fts3.c ***********************/
98822
98823
98824#ifndef SQLITE_CORE
98825  SQLITE_EXTENSION_INIT1
98826#endif
98827
98828/*
98829** Write a 64-bit variable-length integer to memory starting at p[0].
98830** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
98831** The number of bytes written is returned.
98832*/
98833SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
98834  unsigned char *q = (unsigned char *) p;
98835  sqlite_uint64 vu = v;
98836  do{
98837    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
98838    vu >>= 7;
98839  }while( vu!=0 );
98840  q[-1] &= 0x7f;  /* turn off high bit in final byte */
98841  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
98842  return (int) (q - (unsigned char *)p);
98843}
98844
98845/*
98846** Read a 64-bit variable-length integer from memory starting at p[0].
98847** Return the number of bytes read, or 0 on error.
98848** The value is stored in *v.
98849*/
98850SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
98851  const unsigned char *q = (const unsigned char *) p;
98852  sqlite_uint64 x = 0, y = 1;
98853  while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
98854    x += y * (*q++ & 0x7f);
98855    y <<= 7;
98856  }
98857  x += y * (*q++);
98858  *v = (sqlite_int64) x;
98859  return (int) (q - (unsigned char *)p);
98860}
98861
98862/*
98863** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
98864** 32-bit integer before it is returned.
98865*/
98866SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
98867 sqlite_int64 i;
98868 int ret = sqlite3Fts3GetVarint(p, &i);
98869 *pi = (int) i;
98870 return ret;
98871}
98872
98873/*
98874** Return the number of bytes required to store the value passed as the
98875** first argument in varint form.
98876*/
98877SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
98878  int i = 0;
98879  do{
98880    i++;
98881    v >>= 7;
98882  }while( v!=0 );
98883  return i;
98884}
98885
98886/*
98887** Convert an SQL-style quoted string into a normal string by removing
98888** the quote characters.  The conversion is done in-place.  If the
98889** input does not begin with a quote character, then this routine
98890** is a no-op.
98891**
98892** Examples:
98893**
98894**     "abc"   becomes   abc
98895**     'xyz'   becomes   xyz
98896**     [pqr]   becomes   pqr
98897**     `mno`   becomes   mno
98898**
98899*/
98900SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
98901  char quote;                     /* Quote character (if any ) */
98902
98903  quote = z[0];
98904  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
98905    int iIn = 1;                  /* Index of next byte to read from input */
98906    int iOut = 0;                 /* Index of next byte to write to output */
98907
98908    /* If the first byte was a '[', then the close-quote character is a ']' */
98909    if( quote=='[' ) quote = ']';
98910
98911    while( ALWAYS(z[iIn]) ){
98912      if( z[iIn]==quote ){
98913        if( z[iIn+1]!=quote ) break;
98914        z[iOut++] = quote;
98915        iIn += 2;
98916      }else{
98917        z[iOut++] = z[iIn++];
98918      }
98919    }
98920    z[iOut] = '\0';
98921  }
98922}
98923
98924static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
98925  sqlite3_int64 iVal;
98926  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
98927  *pVal += iVal;
98928}
98929
98930static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
98931  if( *pp>=pEnd ){
98932    *pp = 0;
98933  }else{
98934    fts3GetDeltaVarint(pp, pVal);
98935  }
98936}
98937
98938/*
98939** The xDisconnect() virtual table method.
98940*/
98941static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
98942  Fts3Table *p = (Fts3Table *)pVtab;
98943  int i;
98944
98945  assert( p->nPendingData==0 );
98946
98947  /* Free any prepared statements held */
98948  for(i=0; i<SizeofArray(p->aStmt); i++){
98949    sqlite3_finalize(p->aStmt[i]);
98950  }
98951  for(i=0; i<p->nLeavesStmt; i++){
98952    sqlite3_finalize(p->aLeavesStmt[i]);
98953  }
98954  sqlite3_free(p->zSelectLeaves);
98955  sqlite3_free(p->aLeavesStmt);
98956
98957  /* Invoke the tokenizer destructor to free the tokenizer. */
98958  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
98959
98960  sqlite3_free(p);
98961  return SQLITE_OK;
98962}
98963
98964/*
98965** The xDestroy() virtual table method.
98966*/
98967static int fts3DestroyMethod(sqlite3_vtab *pVtab){
98968  int rc;                         /* Return code */
98969  Fts3Table *p = (Fts3Table *)pVtab;
98970
98971  /* Create a script to drop the underlying three storage tables. */
98972  char *zSql = sqlite3_mprintf(
98973      "DROP TABLE IF EXISTS %Q.'%q_content';"
98974      "DROP TABLE IF EXISTS %Q.'%q_segments';"
98975      "DROP TABLE IF EXISTS %Q.'%q_segdir';",
98976      p->zDb, p->zName, p->zDb, p->zName, p->zDb, p->zName
98977  );
98978
98979  /* If malloc has failed, set rc to SQLITE_NOMEM. Otherwise, try to
98980  ** execute the SQL script created above.
98981  */
98982  if( zSql ){
98983    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
98984    sqlite3_free(zSql);
98985  }else{
98986    rc = SQLITE_NOMEM;
98987  }
98988
98989  /* If everything has worked, invoke fts3DisconnectMethod() to free the
98990  ** memory associated with the Fts3Table structure and return SQLITE_OK.
98991  ** Otherwise, return an SQLite error code.
98992  */
98993  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
98994}
98995
98996
98997/*
98998** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
98999** passed as the first argument. This is done as part of the xConnect()
99000** and xCreate() methods.
99001*/
99002static int fts3DeclareVtab(Fts3Table *p){
99003  int i;                          /* Iterator variable */
99004  int rc;                         /* Return code */
99005  char *zSql;                     /* SQL statement passed to declare_vtab() */
99006  char *zCols;                    /* List of user defined columns */
99007
99008  /* Create a list of user columns for the virtual table */
99009  zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
99010  for(i=1; zCols && i<p->nColumn; i++){
99011    zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
99012  }
99013
99014  /* Create the whole "CREATE TABLE" statement to pass to SQLite */
99015  zSql = sqlite3_mprintf(
99016      "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
99017  );
99018
99019  if( !zCols || !zSql ){
99020    rc = SQLITE_NOMEM;
99021  }else{
99022    rc = sqlite3_declare_vtab(p->db, zSql);
99023  }
99024
99025  sqlite3_free(zSql);
99026  sqlite3_free(zCols);
99027  return rc;
99028}
99029
99030/*
99031** Create the backing store tables (%_content, %_segments and %_segdir)
99032** required by the FTS3 table passed as the only argument. This is done
99033** as part of the vtab xCreate() method.
99034*/
99035static int fts3CreateTables(Fts3Table *p){
99036  int rc;                         /* Return code */
99037  int i;                          /* Iterator variable */
99038  char *zContentCols;             /* Columns of %_content table */
99039  char *zSql;                     /* SQL script to create required tables */
99040
99041  /* Create a list of user columns for the content table */
99042  zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
99043  for(i=0; zContentCols && i<p->nColumn; i++){
99044    char *z = p->azColumn[i];
99045    zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
99046  }
99047
99048  /* Create the whole SQL script */
99049  zSql = sqlite3_mprintf(
99050      "CREATE TABLE %Q.'%q_content'(%s);"
99051      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);"
99052      "CREATE TABLE %Q.'%q_segdir'("
99053        "level INTEGER,"
99054        "idx INTEGER,"
99055        "start_block INTEGER,"
99056        "leaves_end_block INTEGER,"
99057        "end_block INTEGER,"
99058        "root BLOB,"
99059        "PRIMARY KEY(level, idx)"
99060      ");",
99061      p->zDb, p->zName, zContentCols, p->zDb, p->zName, p->zDb, p->zName
99062  );
99063
99064  /* Unless a malloc() failure has occurred, execute the SQL script to
99065  ** create the tables used to store data for this FTS3 virtual table.
99066  */
99067  if( zContentCols==0 || zSql==0 ){
99068    rc = SQLITE_NOMEM;
99069  }else{
99070    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
99071  }
99072
99073  sqlite3_free(zSql);
99074  sqlite3_free(zContentCols);
99075  return rc;
99076}
99077
99078/*
99079** This function is the implementation of both the xConnect and xCreate
99080** methods of the FTS3 virtual table.
99081**
99082** The argv[] array contains the following:
99083**
99084**   argv[0]   -> module name
99085**   argv[1]   -> database name
99086**   argv[2]   -> table name
99087**   argv[...] -> "column name" and other module argument fields.
99088*/
99089static int fts3InitVtab(
99090  int isCreate,                   /* True for xCreate, false for xConnect */
99091  sqlite3 *db,                    /* The SQLite database connection */
99092  void *pAux,                     /* Hash table containing tokenizers */
99093  int argc,                       /* Number of elements in argv array */
99094  const char * const *argv,       /* xCreate/xConnect argument array */
99095  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
99096  char **pzErr                    /* Write any error message here */
99097){
99098  Fts3Hash *pHash = (Fts3Hash *)pAux;
99099  Fts3Table *p;                   /* Pointer to allocated vtab */
99100  int rc;                         /* Return code */
99101  int i;                          /* Iterator variable */
99102  int nByte;                      /* Size of allocation used for *p */
99103  int iCol;
99104  int nString = 0;
99105  int nCol = 0;
99106  char *zCsr;
99107  int nDb;
99108  int nName;
99109
99110  const char *zTokenizer = 0;               /* Name of tokenizer to use */
99111  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
99112
99113  nDb = (int)strlen(argv[1]) + 1;
99114  nName = (int)strlen(argv[2]) + 1;
99115  for(i=3; i<argc; i++){
99116    char const *z = argv[i];
99117    rc = sqlite3Fts3InitTokenizer(pHash, z, &pTokenizer, &zTokenizer, pzErr);
99118    if( rc!=SQLITE_OK ){
99119      return rc;
99120    }
99121    if( z!=zTokenizer ){
99122      nString += (int)(strlen(z) + 1);
99123    }
99124  }
99125  nCol = argc - 3 - (zTokenizer!=0);
99126  if( zTokenizer==0 ){
99127    rc = sqlite3Fts3InitTokenizer(pHash, 0, &pTokenizer, 0, pzErr);
99128    if( rc!=SQLITE_OK ){
99129      return rc;
99130    }
99131    assert( pTokenizer );
99132  }
99133
99134  if( nCol==0 ){
99135    nCol = 1;
99136  }
99137
99138  /* Allocate and populate the Fts3Table structure. */
99139  nByte = sizeof(Fts3Table) +              /* Fts3Table */
99140          nCol * sizeof(char *) +              /* azColumn */
99141          nName +                              /* zName */
99142          nDb +                                /* zDb */
99143          nString;                             /* Space for azColumn strings */
99144  p = (Fts3Table*)sqlite3_malloc(nByte);
99145  if( p==0 ){
99146    rc = SQLITE_NOMEM;
99147    goto fts3_init_out;
99148  }
99149  memset(p, 0, nByte);
99150
99151  p->db = db;
99152  p->nColumn = nCol;
99153  p->nPendingData = 0;
99154  p->azColumn = (char **)&p[1];
99155  p->pTokenizer = pTokenizer;
99156  p->nNodeSize = 1000;
99157  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
99158  zCsr = (char *)&p->azColumn[nCol];
99159
99160  fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
99161
99162  /* Fill in the zName and zDb fields of the vtab structure. */
99163  p->zName = zCsr;
99164  memcpy(zCsr, argv[2], nName);
99165  zCsr += nName;
99166  p->zDb = zCsr;
99167  memcpy(zCsr, argv[1], nDb);
99168  zCsr += nDb;
99169
99170  /* Fill in the azColumn array */
99171  iCol = 0;
99172  for(i=3; i<argc; i++){
99173    if( argv[i]!=zTokenizer ){
99174      char *z;
99175      int n;
99176      z = (char *)sqlite3Fts3NextToken(argv[i], &n);
99177      memcpy(zCsr, z, n);
99178      zCsr[n] = '\0';
99179      sqlite3Fts3Dequote(zCsr);
99180      p->azColumn[iCol++] = zCsr;
99181      zCsr += n+1;
99182      assert( zCsr <= &((char *)p)[nByte] );
99183    }
99184  }
99185  if( iCol==0 ){
99186    assert( nCol==1 );
99187    p->azColumn[0] = "content";
99188  }
99189
99190  /* If this is an xCreate call, create the underlying tables in the
99191  ** database. TODO: For xConnect(), it could verify that said tables exist.
99192  */
99193  if( isCreate ){
99194    rc = fts3CreateTables(p);
99195    if( rc!=SQLITE_OK ) goto fts3_init_out;
99196  }
99197
99198  rc = fts3DeclareVtab(p);
99199  if( rc!=SQLITE_OK ) goto fts3_init_out;
99200
99201  *ppVTab = &p->base;
99202
99203fts3_init_out:
99204  assert( p || (pTokenizer && rc!=SQLITE_OK) );
99205  if( rc!=SQLITE_OK ){
99206    if( p ){
99207      fts3DisconnectMethod((sqlite3_vtab *)p);
99208    }else{
99209      pTokenizer->pModule->xDestroy(pTokenizer);
99210    }
99211  }
99212  return rc;
99213}
99214
99215/*
99216** The xConnect() and xCreate() methods for the virtual table. All the
99217** work is done in function fts3InitVtab().
99218*/
99219static int fts3ConnectMethod(
99220  sqlite3 *db,                    /* Database connection */
99221  void *pAux,                     /* Pointer to tokenizer hash table */
99222  int argc,                       /* Number of elements in argv array */
99223  const char * const *argv,       /* xCreate/xConnect argument array */
99224  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
99225  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
99226){
99227  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
99228}
99229static int fts3CreateMethod(
99230  sqlite3 *db,                    /* Database connection */
99231  void *pAux,                     /* Pointer to tokenizer hash table */
99232  int argc,                       /* Number of elements in argv array */
99233  const char * const *argv,       /* xCreate/xConnect argument array */
99234  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
99235  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
99236){
99237  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
99238}
99239
99240/*
99241** Implementation of the xBestIndex method for FTS3 tables. There
99242** are three possible strategies, in order of preference:
99243**
99244**   1. Direct lookup by rowid or docid.
99245**   2. Full-text search using a MATCH operator on a non-docid column.
99246**   3. Linear scan of %_content table.
99247*/
99248static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
99249  Fts3Table *p = (Fts3Table *)pVTab;
99250  int i;                          /* Iterator variable */
99251  int iCons = -1;                 /* Index of constraint to use */
99252
99253  /* By default use a full table scan. This is an expensive option,
99254  ** so search through the constraints to see if a more efficient
99255  ** strategy is possible.
99256  */
99257  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
99258  pInfo->estimatedCost = 500000;
99259  for(i=0; i<pInfo->nConstraint; i++){
99260    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
99261    if( pCons->usable==0 ) continue;
99262
99263    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
99264    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
99265     && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
99266    ){
99267      pInfo->idxNum = FTS3_DOCID_SEARCH;
99268      pInfo->estimatedCost = 1.0;
99269      iCons = i;
99270    }
99271
99272    /* A MATCH constraint. Use a full-text search.
99273    **
99274    ** If there is more than one MATCH constraint available, use the first
99275    ** one encountered. If there is both a MATCH constraint and a direct
99276    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
99277    ** though the rowid/docid lookup is faster than a MATCH query, selecting
99278    ** it would lead to an "unable to use function MATCH in the requested
99279    ** context" error.
99280    */
99281    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
99282     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
99283    ){
99284      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
99285      pInfo->estimatedCost = 2.0;
99286      iCons = i;
99287      break;
99288    }
99289  }
99290
99291  if( iCons>=0 ){
99292    pInfo->aConstraintUsage[iCons].argvIndex = 1;
99293    pInfo->aConstraintUsage[iCons].omit = 1;
99294  }
99295  return SQLITE_OK;
99296}
99297
99298/*
99299** Implementation of xOpen method.
99300*/
99301static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
99302  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
99303
99304  UNUSED_PARAMETER(pVTab);
99305
99306  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
99307  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
99308  ** if the allocation fails, return SQLITE_NOMEM.
99309  */
99310  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
99311  if( !pCsr ){
99312    return SQLITE_NOMEM;
99313  }
99314  memset(pCsr, 0, sizeof(Fts3Cursor));
99315  return SQLITE_OK;
99316}
99317
99318/****************************************************************/
99319/****************************************************************/
99320/****************************************************************/
99321/****************************************************************/
99322
99323
99324/*
99325** Close the cursor.  For additional information see the documentation
99326** on the xClose method of the virtual table interface.
99327*/
99328static int fulltextClose(sqlite3_vtab_cursor *pCursor){
99329  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
99330  sqlite3_finalize(pCsr->pStmt);
99331  sqlite3Fts3ExprFree(pCsr->pExpr);
99332  sqlite3_free(pCsr->aDoclist);
99333  sqlite3_free(pCsr->aMatchinfo);
99334  sqlite3_free(pCsr);
99335  return SQLITE_OK;
99336}
99337
99338static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
99339  if( pCsr->isRequireSeek ){
99340    pCsr->isRequireSeek = 0;
99341    sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
99342    if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
99343      return SQLITE_OK;
99344    }else{
99345      int rc = sqlite3_reset(pCsr->pStmt);
99346      if( rc==SQLITE_OK ){
99347        /* If no row was found and no error has occured, then the %_content
99348        ** table is missing a row that is present in the full-text index.
99349        ** The data structures are corrupt.
99350        */
99351        rc = SQLITE_CORRUPT;
99352      }
99353      pCsr->isEof = 1;
99354      if( pContext ){
99355        sqlite3_result_error_code(pContext, rc);
99356      }
99357      return rc;
99358    }
99359  }else{
99360    return SQLITE_OK;
99361  }
99362}
99363
99364static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
99365  int rc = SQLITE_OK;             /* Return code */
99366  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
99367
99368  if( pCsr->aDoclist==0 ){
99369    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
99370      pCsr->isEof = 1;
99371      rc = sqlite3_reset(pCsr->pStmt);
99372    }
99373  }else if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
99374    pCsr->isEof = 1;
99375  }else{
99376    sqlite3_reset(pCsr->pStmt);
99377    fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
99378    pCsr->isRequireSeek = 1;
99379    pCsr->isMatchinfoOk = 1;
99380  }
99381  return rc;
99382}
99383
99384
99385/*
99386** The buffer pointed to by argument zNode (size nNode bytes) contains the
99387** root node of a b-tree segment. The segment is guaranteed to be at least
99388** one level high (i.e. the root node is not also a leaf). If successful,
99389** this function locates the leaf node of the segment that may contain the
99390** term specified by arguments zTerm and nTerm and writes its block number
99391** to *piLeaf.
99392**
99393** It is possible that the returned leaf node does not contain the specified
99394** term. However, if the segment does contain said term, it is stored on
99395** the identified leaf node. Because this function only inspects interior
99396** segment nodes (and never loads leaf nodes into memory), it is not possible
99397** to be sure.
99398**
99399** If an error occurs, an error code other than SQLITE_OK is returned.
99400*/
99401static int fts3SelectLeaf(
99402  Fts3Table *p,                   /* Virtual table handle */
99403  const char *zTerm,              /* Term to select leaves for */
99404  int nTerm,                      /* Size of term zTerm in bytes */
99405  const char *zNode,              /* Buffer containing segment interior node */
99406  int nNode,                      /* Size of buffer at zNode */
99407  sqlite3_int64 *piLeaf           /* Selected leaf node */
99408){
99409  int rc = SQLITE_OK;             /* Return code */
99410  const char *zCsr = zNode;       /* Cursor to iterate through node */
99411  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
99412  char *zBuffer = 0;              /* Buffer to load terms into */
99413  int nAlloc = 0;                 /* Size of allocated buffer */
99414
99415  while( 1 ){
99416    int isFirstTerm = 1;          /* True when processing first term on page */
99417    int iHeight;                  /* Height of this node in tree */
99418    sqlite3_int64 iChild;         /* Block id of child node to descend to */
99419    int nBlock;                   /* Size of child node in bytes */
99420
99421    zCsr += sqlite3Fts3GetVarint32(zCsr, &iHeight);
99422    zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
99423
99424    while( zCsr<zEnd ){
99425      int cmp;                    /* memcmp() result */
99426      int nSuffix;                /* Size of term suffix */
99427      int nPrefix = 0;            /* Size of term prefix */
99428      int nBuffer;                /* Total term size */
99429
99430      /* Load the next term on the node into zBuffer */
99431      if( !isFirstTerm ){
99432        zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
99433      }
99434      isFirstTerm = 0;
99435      zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
99436      if( nPrefix+nSuffix>nAlloc ){
99437        char *zNew;
99438        nAlloc = (nPrefix+nSuffix) * 2;
99439        zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
99440        if( !zNew ){
99441          sqlite3_free(zBuffer);
99442          return SQLITE_NOMEM;
99443        }
99444        zBuffer = zNew;
99445      }
99446      memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
99447      nBuffer = nPrefix + nSuffix;
99448      zCsr += nSuffix;
99449
99450      /* Compare the term we are searching for with the term just loaded from
99451      ** the interior node. If the specified term is greater than or equal
99452      ** to the term from the interior node, then all terms on the sub-tree
99453      ** headed by node iChild are smaller than zTerm. No need to search
99454      ** iChild.
99455      **
99456      ** If the interior node term is larger than the specified term, then
99457      ** the tree headed by iChild may contain the specified term.
99458      */
99459      cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
99460      if( cmp<0 || (cmp==0 && nBuffer>nTerm) ) break;
99461      iChild++;
99462    };
99463
99464    /* If (iHeight==1), the children of this interior node are leaves. The
99465    ** specified term may be present on leaf node iChild.
99466    */
99467    if( iHeight==1 ){
99468      *piLeaf = iChild;
99469      break;
99470    }
99471
99472    /* Descend to interior node iChild. */
99473    rc = sqlite3Fts3ReadBlock(p, iChild, &zCsr, &nBlock);
99474    if( rc!=SQLITE_OK ) break;
99475    zEnd = &zCsr[nBlock];
99476  }
99477  sqlite3_free(zBuffer);
99478  return rc;
99479}
99480
99481/*
99482** This function is used to create delta-encoded serialized lists of FTS3
99483** varints. Each call to this function appends a single varint to a list.
99484*/
99485static void fts3PutDeltaVarint(
99486  char **pp,                      /* IN/OUT: Output pointer */
99487  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
99488  sqlite3_int64 iVal              /* Write this value to the list */
99489){
99490  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
99491  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
99492  *piPrev = iVal;
99493}
99494
99495/*
99496** When this function is called, *ppPoslist is assumed to point to the
99497** start of a position-list.
99498*/
99499static void fts3PoslistCopy(char **pp, char **ppPoslist){
99500  char *pEnd = *ppPoslist;
99501  char c = 0;
99502
99503  /* The end of a position list is marked by a zero encoded as an FTS3
99504  ** varint. A single 0x00 byte. Except, if the 0x00 byte is preceded by
99505  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
99506  ** of some other, multi-byte, value.
99507  **
99508  ** The following block moves pEnd to point to the first byte that is not
99509  ** immediately preceded by a byte with the 0x80 bit set. Then increments
99510  ** pEnd once more so that it points to the byte immediately following the
99511  ** last byte in the position-list.
99512  */
99513  while( *pEnd | c ) c = *pEnd++ & 0x80;
99514  pEnd++;
99515
99516  if( pp ){
99517    int n = (int)(pEnd - *ppPoslist);
99518    char *p = *pp;
99519    memcpy(p, *ppPoslist, n);
99520    p += n;
99521    *pp = p;
99522  }
99523  *ppPoslist = pEnd;
99524}
99525
99526static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
99527  char *pEnd = *ppPoslist;
99528  char c = 0;
99529
99530  /* A column-list is terminated by either a 0x01 or 0x00. */
99531  while( 0xFE & (*pEnd | c) ) c = *pEnd++ & 0x80;
99532  if( pp ){
99533    int n = (int)(pEnd - *ppPoslist);
99534    char *p = *pp;
99535    memcpy(p, *ppPoslist, n);
99536    p += n;
99537    *pp = p;
99538  }
99539  *ppPoslist = pEnd;
99540}
99541
99542/*
99543** Value used to signify the end of an offset-list. This is safe because
99544** it is not possible to have a document with 2^31 terms.
99545*/
99546#define OFFSET_LIST_END 0x7fffffff
99547
99548/*
99549** This function is used to help parse offset-lists. When this function is
99550** called, *pp may point to the start of the next varint in the offset-list
99551** being parsed, or it may point to 1 byte past the end of the offset-list
99552** (in which case **pp will be 0x00 or 0x01).
99553**
99554** If *pp points past the end of the current offset list, set *pi to
99555** OFFSET_LIST_END and return. Otherwise, read the next varint from *pp,
99556** increment the current value of *pi by the value read, and set *pp to
99557** point to the next value before returning.
99558*/
99559static void fts3ReadNextPos(
99560  char **pp,                      /* IN/OUT: Pointer into offset-list buffer */
99561  sqlite3_int64 *pi               /* IN/OUT: Value read from offset-list */
99562){
99563  if( **pp&0xFE ){
99564    fts3GetDeltaVarint(pp, pi);
99565    *pi -= 2;
99566  }else{
99567    *pi = OFFSET_LIST_END;
99568  }
99569}
99570
99571/*
99572** If parameter iCol is not 0, write an 0x01 byte followed by the value of
99573** iCol encoded as a varint to *pp.
99574**
99575** Set *pp to point to the byte just after the last byte written before
99576** returning (do not modify it if iCol==0). Return the total number of bytes
99577** written (0 if iCol==0).
99578*/
99579static int fts3PutColNumber(char **pp, int iCol){
99580  int n = 0;                      /* Number of bytes written */
99581  if( iCol ){
99582    char *p = *pp;                /* Output pointer */
99583    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
99584    *p = 0x01;
99585    *pp = &p[n];
99586  }
99587  return n;
99588}
99589
99590/*
99591**
99592*/
99593static void fts3PoslistMerge(
99594  char **pp,                      /* Output buffer */
99595  char **pp1,                     /* Left input list */
99596  char **pp2                      /* Right input list */
99597){
99598  char *p = *pp;
99599  char *p1 = *pp1;
99600  char *p2 = *pp2;
99601
99602  while( *p1 || *p2 ){
99603    int iCol1;
99604    int iCol2;
99605
99606    if( *p1==0x01 ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
99607    else if( *p1==0x00 ) iCol1 = OFFSET_LIST_END;
99608    else iCol1 = 0;
99609
99610    if( *p2==0x01 ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
99611    else if( *p2==0x00 ) iCol2 = OFFSET_LIST_END;
99612    else iCol2 = 0;
99613
99614    if( iCol1==iCol2 ){
99615      sqlite3_int64 i1 = 0;
99616      sqlite3_int64 i2 = 0;
99617      sqlite3_int64 iPrev = 0;
99618      int n = fts3PutColNumber(&p, iCol1);
99619      p1 += n;
99620      p2 += n;
99621
99622      /* At this point, both p1 and p2 point to the start of offset-lists.
99623      ** An offset-list is a list of non-negative delta-encoded varints, each
99624      ** incremented by 2 before being stored. Each list is terminated by a 0
99625      ** or 1 value (0x00 or 0x01). The following block merges the two lists
99626      ** and writes the results to buffer p. p is left pointing to the byte
99627      ** after the list written. No terminator (0x00 or 0x01) is written to
99628      ** the output.
99629      */
99630      fts3GetDeltaVarint(&p1, &i1);
99631      fts3GetDeltaVarint(&p2, &i2);
99632      do {
99633        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
99634        iPrev -= 2;
99635        if( i1==i2 ){
99636          fts3ReadNextPos(&p1, &i1);
99637          fts3ReadNextPos(&p2, &i2);
99638        }else if( i1<i2 ){
99639          fts3ReadNextPos(&p1, &i1);
99640        }else{
99641          fts3ReadNextPos(&p2, &i2);
99642        }
99643      }while( i1!=OFFSET_LIST_END || i2!=OFFSET_LIST_END );
99644    }else if( iCol1<iCol2 ){
99645      p1 += fts3PutColNumber(&p, iCol1);
99646      fts3ColumnlistCopy(&p, &p1);
99647    }else{
99648      p2 += fts3PutColNumber(&p, iCol2);
99649      fts3ColumnlistCopy(&p, &p2);
99650    }
99651  }
99652
99653  *p++ = '\0';
99654  *pp = p;
99655  *pp1 = p1 + 1;
99656  *pp2 = p2 + 1;
99657}
99658
99659/*
99660** nToken==1 searches for adjacent positions.
99661*/
99662static int fts3PoslistPhraseMerge(
99663  char **pp,                      /* Output buffer */
99664  int nToken,                     /* Maximum difference in token positions */
99665  int isSaveLeft,                 /* Save the left position */
99666  char **pp1,                     /* Left input list */
99667  char **pp2                      /* Right input list */
99668){
99669  char *p = (pp ? *pp : 0);
99670  char *p1 = *pp1;
99671  char *p2 = *pp2;
99672
99673  int iCol1 = 0;
99674  int iCol2 = 0;
99675  assert( *p1!=0 && *p2!=0 );
99676  if( *p1==0x01 ){
99677    p1++;
99678    p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
99679  }
99680  if( *p2==0x01 ){
99681    p2++;
99682    p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
99683  }
99684
99685  while( 1 ){
99686    if( iCol1==iCol2 ){
99687      char *pSave = p;
99688      sqlite3_int64 iPrev = 0;
99689      sqlite3_int64 iPos1 = 0;
99690      sqlite3_int64 iPos2 = 0;
99691
99692      if( pp && iCol1 ){
99693        *p++ = 0x01;
99694        p += sqlite3Fts3PutVarint(p, iCol1);
99695      }
99696
99697      assert( *p1!=0x00 && *p2!=0x00 && *p1!=0x01 && *p2!=0x01 );
99698      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
99699      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
99700
99701      while( 1 ){
99702        if( iPos2>iPos1 && iPos2<=iPos1+nToken ){
99703          sqlite3_int64 iSave;
99704          if( !pp ){
99705            fts3PoslistCopy(0, &p2);
99706            fts3PoslistCopy(0, &p1);
99707            *pp1 = p1;
99708            *pp2 = p2;
99709            return 1;
99710          }
99711          iSave = isSaveLeft ? iPos1 : iPos2;
99712          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
99713          pSave = 0;
99714        }
99715        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
99716          if( (*p2&0xFE)==0 ) break;
99717          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
99718        }else{
99719          if( (*p1&0xFE)==0 ) break;
99720          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
99721        }
99722      }
99723
99724      if( pSave ){
99725        assert( pp && p );
99726        p = pSave;
99727      }
99728
99729      fts3ColumnlistCopy(0, &p1);
99730      fts3ColumnlistCopy(0, &p2);
99731      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
99732      if( 0==*p1 || 0==*p2 ) break;
99733
99734      p1++;
99735      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
99736      p2++;
99737      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
99738    }
99739
99740    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
99741    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
99742    ** end of the position list, or the 0x01 that precedes the next
99743    ** column-number in the position list.
99744    */
99745    else if( iCol1<iCol2 ){
99746      fts3ColumnlistCopy(0, &p1);
99747      if( 0==*p1 ) break;
99748      p1++;
99749      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
99750    }else{
99751      fts3ColumnlistCopy(0, &p2);
99752      if( 0==*p2 ) break;
99753      p2++;
99754      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
99755    }
99756  }
99757
99758  fts3PoslistCopy(0, &p2);
99759  fts3PoslistCopy(0, &p1);
99760  *pp1 = p1;
99761  *pp2 = p2;
99762  if( !pp || *pp==p ){
99763    return 0;
99764  }
99765  *p++ = 0x00;
99766  *pp = p;
99767  return 1;
99768}
99769
99770/*
99771** Merge two position-lists as required by the NEAR operator.
99772*/
99773static int fts3PoslistNearMerge(
99774  char **pp,                      /* Output buffer */
99775  char *aTmp,                     /* Temporary buffer space */
99776  int nRight,                     /* Maximum difference in token positions */
99777  int nLeft,                      /* Maximum difference in token positions */
99778  char **pp1,                     /* IN/OUT: Left input list */
99779  char **pp2                      /* IN/OUT: Right input list */
99780){
99781  char *p1 = *pp1;
99782  char *p2 = *pp2;
99783
99784  if( !pp ){
99785    if( fts3PoslistPhraseMerge(0, nRight, 0, pp1, pp2) ) return 1;
99786    *pp1 = p1;
99787    *pp2 = p2;
99788    return fts3PoslistPhraseMerge(0, nLeft, 0, pp2, pp1);
99789  }else{
99790    char *pTmp1 = aTmp;
99791    char *pTmp2;
99792    char *aTmp2;
99793    int res = 1;
99794
99795    fts3PoslistPhraseMerge(&pTmp1, nRight, 0, pp1, pp2);
99796    aTmp2 = pTmp2 = pTmp1;
99797    *pp1 = p1;
99798    *pp2 = p2;
99799    fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, pp2, pp1);
99800    if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
99801      fts3PoslistMerge(pp, &aTmp, &aTmp2);
99802    }else if( pTmp1!=aTmp ){
99803      fts3PoslistCopy(pp, &aTmp);
99804    }else if( pTmp2!=aTmp2 ){
99805      fts3PoslistCopy(pp, &aTmp2);
99806    }else{
99807      res = 0;
99808    }
99809
99810    return res;
99811  }
99812}
99813
99814/*
99815** Values that may be used as the first parameter to fts3DoclistMerge().
99816*/
99817#define MERGE_NOT        2        /* D + D -> D */
99818#define MERGE_AND        3        /* D + D -> D */
99819#define MERGE_OR         4        /* D + D -> D */
99820#define MERGE_POS_OR     5        /* P + P -> P */
99821#define MERGE_PHRASE     6        /* P + P -> D */
99822#define MERGE_POS_PHRASE 7        /* P + P -> P */
99823#define MERGE_NEAR       8        /* P + P -> D */
99824#define MERGE_POS_NEAR   9        /* P + P -> P */
99825
99826/*
99827** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
99828** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
99829** which is guaranteed to be large enough to hold the results. The number
99830** of bytes written to aBuffer is stored in *pnBuffer before returning.
99831**
99832** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
99833** occurs while allocating a temporary buffer as part of the merge operation,
99834** SQLITE_NOMEM is returned.
99835*/
99836static int fts3DoclistMerge(
99837  int mergetype,                  /* One of the MERGE_XXX constants */
99838  int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
99839  int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
99840  char *aBuffer,                  /* Pre-allocated output buffer */
99841  int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
99842  char *a1,                       /* Buffer containing first doclist */
99843  int n1,                         /* Size of buffer a1 */
99844  char *a2,                       /* Buffer containing second doclist */
99845  int n2                          /* Size of buffer a2 */
99846){
99847  sqlite3_int64 i1 = 0;
99848  sqlite3_int64 i2 = 0;
99849  sqlite3_int64 iPrev = 0;
99850
99851  char *p = aBuffer;
99852  char *p1 = a1;
99853  char *p2 = a2;
99854  char *pEnd1 = &a1[n1];
99855  char *pEnd2 = &a2[n2];
99856
99857  assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR
99858       || mergetype==MERGE_AND    || mergetype==MERGE_NOT
99859       || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
99860       || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
99861  );
99862
99863  if( !aBuffer ){
99864    *pnBuffer = 0;
99865    return SQLITE_NOMEM;
99866  }
99867
99868  /* Read the first docid from each doclist */
99869  fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99870  fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99871
99872  switch( mergetype ){
99873    case MERGE_OR:
99874    case MERGE_POS_OR:
99875      while( p1 || p2 ){
99876        if( p2 && p1 && i1==i2 ){
99877          fts3PutDeltaVarint(&p, &iPrev, i1);
99878          if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
99879          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99880          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99881        }else if( !p2 || (p1 && i1<i2) ){
99882          fts3PutDeltaVarint(&p, &iPrev, i1);
99883          if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
99884          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99885        }else{
99886          fts3PutDeltaVarint(&p, &iPrev, i2);
99887          if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
99888          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99889        }
99890      }
99891      break;
99892
99893    case MERGE_AND:
99894      while( p1 && p2 ){
99895        if( i1==i2 ){
99896          fts3PutDeltaVarint(&p, &iPrev, i1);
99897          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99898          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99899        }else if( i1<i2 ){
99900          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99901        }else{
99902          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99903        }
99904      }
99905      break;
99906
99907    case MERGE_NOT:
99908      while( p1 ){
99909        if( p2 && i1==i2 ){
99910          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99911          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99912        }else if( !p2 || i1<i2 ){
99913          fts3PutDeltaVarint(&p, &iPrev, i1);
99914          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99915        }else{
99916          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99917        }
99918      }
99919      break;
99920
99921    case MERGE_POS_PHRASE:
99922    case MERGE_PHRASE: {
99923      char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
99924      while( p1 && p2 ){
99925        if( i1==i2 ){
99926          char *pSave = p;
99927          sqlite3_int64 iPrevSave = iPrev;
99928          fts3PutDeltaVarint(&p, &iPrev, i1);
99929          if( 0==fts3PoslistPhraseMerge(ppPos, 1, 0, &p1, &p2) ){
99930            p = pSave;
99931            iPrev = iPrevSave;
99932          }
99933          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99934          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99935        }else if( i1<i2 ){
99936          fts3PoslistCopy(0, &p1);
99937          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99938        }else{
99939          fts3PoslistCopy(0, &p2);
99940          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99941        }
99942      }
99943      break;
99944    }
99945
99946    default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
99947      char *aTmp = 0;
99948      char **ppPos = 0;
99949      if( mergetype==MERGE_POS_NEAR ){
99950        ppPos = &p;
99951        aTmp = sqlite3_malloc(2*(n1+n2+1));
99952        if( !aTmp ){
99953          return SQLITE_NOMEM;
99954        }
99955      }
99956
99957      while( p1 && p2 ){
99958        if( i1==i2 ){
99959          char *pSave = p;
99960          sqlite3_int64 iPrevSave = iPrev;
99961          fts3PutDeltaVarint(&p, &iPrev, i1);
99962
99963          if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
99964            iPrev = iPrevSave;
99965            p = pSave;
99966          }
99967
99968          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99969          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99970        }else if( i1<i2 ){
99971          fts3PoslistCopy(0, &p1);
99972          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99973        }else{
99974          fts3PoslistCopy(0, &p2);
99975          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99976        }
99977      }
99978      sqlite3_free(aTmp);
99979      break;
99980    }
99981  }
99982
99983  *pnBuffer = (int)(p-aBuffer);
99984  return SQLITE_OK;
99985}
99986
99987/*
99988** A pointer to an instance of this structure is used as the context
99989** argument to sqlite3Fts3SegReaderIterate()
99990*/
99991typedef struct TermSelect TermSelect;
99992struct TermSelect {
99993  int isReqPos;
99994  char *aOutput;                  /* Malloc'd output buffer */
99995  int nOutput;                    /* Size of output in bytes */
99996};
99997
99998/*
99999** This function is used as the sqlite3Fts3SegReaderIterate() callback when
100000** querying the full-text index for a doclist associated with a term or
100001** term-prefix.
100002*/
100003static int fts3TermSelectCb(
100004  Fts3Table *p,                   /* Virtual table object */
100005  void *pContext,                 /* Pointer to TermSelect structure */
100006  char *zTerm,
100007  int nTerm,
100008  char *aDoclist,
100009  int nDoclist
100010){
100011  TermSelect *pTS = (TermSelect *)pContext;
100012  int nNew = pTS->nOutput + nDoclist;
100013  char *aNew = sqlite3_malloc(nNew);
100014
100015  UNUSED_PARAMETER(p);
100016  UNUSED_PARAMETER(zTerm);
100017  UNUSED_PARAMETER(nTerm);
100018
100019  if( !aNew ){
100020    return SQLITE_NOMEM;
100021  }
100022
100023  if( pTS->nOutput==0 ){
100024    /* If this is the first term selected, copy the doclist to the output
100025    ** buffer using memcpy(). TODO: Add a way to transfer control of the
100026    ** aDoclist buffer from the caller so as to avoid the memcpy().
100027    */
100028    memcpy(aNew, aDoclist, nDoclist);
100029  }else{
100030    /* The output buffer is not empty. Merge doclist aDoclist with the
100031    ** existing output. This can only happen with prefix-searches (as
100032    ** searches for exact terms return exactly one doclist).
100033    */
100034    int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
100035    fts3DoclistMerge(mergetype, 0, 0,
100036        aNew, &nNew, pTS->aOutput, pTS->nOutput, aDoclist, nDoclist
100037    );
100038  }
100039
100040  sqlite3_free(pTS->aOutput);
100041  pTS->aOutput = aNew;
100042  pTS->nOutput = nNew;
100043
100044  return SQLITE_OK;
100045}
100046
100047/*
100048** This function retreives the doclist for the specified term (or term
100049** prefix) from the database.
100050**
100051** The returned doclist may be in one of two formats, depending on the
100052** value of parameter isReqPos. If isReqPos is zero, then the doclist is
100053** a sorted list of delta-compressed docids. If isReqPos is non-zero,
100054** then the returned list is in the same format as is stored in the
100055** database without the found length specifier at the start of on-disk
100056** doclists.
100057*/
100058static int fts3TermSelect(
100059  Fts3Table *p,                   /* Virtual table handle */
100060  int iColumn,                    /* Column to query (or -ve for all columns) */
100061  const char *zTerm,              /* Term to query for */
100062  int nTerm,                      /* Size of zTerm in bytes */
100063  int isPrefix,                   /* True for a prefix search */
100064  int isReqPos,                   /* True to include position lists in output */
100065  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
100066  char **ppOut                    /* OUT: Malloced result buffer */
100067){
100068  int i;
100069  TermSelect tsc;
100070  Fts3SegFilter filter;           /* Segment term filter configuration */
100071  Fts3SegReader **apSegment;      /* Array of segments to read data from */
100072  int nSegment = 0;               /* Size of apSegment array */
100073  int nAlloc = 16;                /* Allocated size of segment array */
100074  int rc;                         /* Return code */
100075  sqlite3_stmt *pStmt = 0;        /* SQL statement to scan %_segdir table */
100076  int iAge = 0;                   /* Used to assign ages to segments */
100077
100078  apSegment = (Fts3SegReader **)sqlite3_malloc(sizeof(Fts3SegReader*)*nAlloc);
100079  if( !apSegment ) return SQLITE_NOMEM;
100080  rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &apSegment[0]);
100081  if( rc!=SQLITE_OK ) goto finished;
100082  if( apSegment[0] ){
100083    nSegment = 1;
100084  }
100085
100086  /* Loop through the entire %_segdir table. For each segment, create a
100087  ** Fts3SegReader to iterate through the subset of the segment leaves
100088  ** that may contain a term that matches zTerm/nTerm. For non-prefix
100089  ** searches, this is always a single leaf. For prefix searches, this
100090  ** may be a contiguous block of leaves.
100091  **
100092  ** The code in this loop does not actually load any leaves into memory
100093  ** (unless the root node happens to be a leaf). It simply examines the
100094  ** b-tree structure to determine which leaves need to be inspected.
100095  */
100096  rc = sqlite3Fts3AllSegdirs(p, &pStmt);
100097  while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
100098    Fts3SegReader *pNew = 0;
100099    int nRoot = sqlite3_column_bytes(pStmt, 4);
100100    char const *zRoot = sqlite3_column_blob(pStmt, 4);
100101    if( sqlite3_column_int64(pStmt, 1)==0 ){
100102      /* The entire segment is stored on the root node (which must be a
100103      ** leaf). Do not bother inspecting any data in this case, just
100104      ** create a Fts3SegReader to scan the single leaf.
100105      */
100106      rc = sqlite3Fts3SegReaderNew(p, iAge, 0, 0, 0, zRoot, nRoot, &pNew);
100107    }else{
100108      int rc2;                    /* Return value of sqlite3Fts3ReadBlock() */
100109      sqlite3_int64 i1;           /* Blockid of leaf that may contain zTerm */
100110      rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &i1);
100111      if( rc==SQLITE_OK ){
100112        sqlite3_int64 i2 = sqlite3_column_int64(pStmt, 2);
100113        rc = sqlite3Fts3SegReaderNew(p, iAge, i1, i2, 0, 0, 0, &pNew);
100114      }
100115
100116      /* The following call to ReadBlock() serves to reset the SQL statement
100117      ** used to retrieve blocks of data from the %_segments table. If it is
100118      ** not reset here, then it may remain classified as an active statement
100119      ** by SQLite, which may lead to "DROP TABLE" or "DETACH" commands
100120      ** failing.
100121      */
100122      rc2 = sqlite3Fts3ReadBlock(p, 0, 0, 0);
100123      if( rc==SQLITE_OK ){
100124        rc = rc2;
100125      }
100126    }
100127    iAge++;
100128
100129    /* If a new Fts3SegReader was allocated, add it to the apSegment array. */
100130    assert( pNew!=0 || rc!=SQLITE_OK );
100131    if( pNew ){
100132      if( nSegment==nAlloc ){
100133        Fts3SegReader **pArray;
100134        nAlloc += 16;
100135        pArray = (Fts3SegReader **)sqlite3_realloc(
100136            apSegment, nAlloc*sizeof(Fts3SegReader *)
100137        );
100138        if( !pArray ){
100139          sqlite3Fts3SegReaderFree(p, pNew);
100140          rc = SQLITE_NOMEM;
100141          goto finished;
100142        }
100143        apSegment = pArray;
100144      }
100145      apSegment[nSegment++] = pNew;
100146    }
100147  }
100148  if( rc!=SQLITE_DONE ){
100149    assert( rc!=SQLITE_OK );
100150    goto finished;
100151  }
100152
100153  memset(&tsc, 0, sizeof(TermSelect));
100154  tsc.isReqPos = isReqPos;
100155
100156  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY
100157        | (isPrefix ? FTS3_SEGMENT_PREFIX : 0)
100158        | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
100159        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
100160  filter.iCol = iColumn;
100161  filter.zTerm = zTerm;
100162  filter.nTerm = nTerm;
100163
100164  rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment, &filter,
100165      fts3TermSelectCb, (void *)&tsc
100166  );
100167
100168  if( rc==SQLITE_OK ){
100169    *ppOut = tsc.aOutput;
100170    *pnOut = tsc.nOutput;
100171  }else{
100172    sqlite3_free(tsc.aOutput);
100173  }
100174
100175finished:
100176  sqlite3_reset(pStmt);
100177  for(i=0; i<nSegment; i++){
100178    sqlite3Fts3SegReaderFree(p, apSegment[i]);
100179  }
100180  sqlite3_free(apSegment);
100181  return rc;
100182}
100183
100184
100185/*
100186** Return a DocList corresponding to the phrase *pPhrase.
100187*/
100188static int fts3PhraseSelect(
100189  Fts3Table *p,                   /* Virtual table handle */
100190  Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
100191  int isReqPos,                   /* True if output should contain positions */
100192  char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
100193  int *pnOut                      /* OUT: Size of buffer at *paOut */
100194){
100195  char *pOut = 0;
100196  int nOut = 0;
100197  int rc = SQLITE_OK;
100198  int ii;
100199  int iCol = pPhrase->iColumn;
100200  int isTermPos = (pPhrase->nToken>1 || isReqPos);
100201
100202  for(ii=0; ii<pPhrase->nToken; ii++){
100203    struct PhraseToken *pTok = &pPhrase->aToken[ii];
100204    char *z = pTok->z;            /* Next token of the phrase */
100205    int n = pTok->n;              /* Size of z in bytes */
100206    int isPrefix = pTok->isPrefix;/* True if token is a prefix */
100207    char *pList;                  /* Pointer to token doclist */
100208    int nList;                    /* Size of buffer at pList */
100209
100210    rc = fts3TermSelect(p, iCol, z, n, isPrefix, isTermPos, &nList, &pList);
100211    if( rc!=SQLITE_OK ) break;
100212
100213    if( ii==0 ){
100214      pOut = pList;
100215      nOut = nList;
100216    }else{
100217      /* Merge the new term list and the current output. If this is the
100218      ** last term in the phrase, and positions are not required in the
100219      ** output of this function, the positions can be dropped as part
100220      ** of this merge. Either way, the result of this merge will be
100221      ** smaller than nList bytes. The code in fts3DoclistMerge() is written
100222      ** so that it is safe to use pList as the output as well as an input
100223      ** in this case.
100224      */
100225      int mergetype = MERGE_POS_PHRASE;
100226      if( ii==pPhrase->nToken-1 && !isReqPos ){
100227        mergetype = MERGE_PHRASE;
100228      }
100229      fts3DoclistMerge(mergetype, 0, 0, pList, &nOut, pOut, nOut, pList, nList);
100230      sqlite3_free(pOut);
100231      pOut = pList;
100232    }
100233    assert( nOut==0 || pOut!=0 );
100234  }
100235
100236  if( rc==SQLITE_OK ){
100237    *paOut = pOut;
100238    *pnOut = nOut;
100239  }else{
100240    sqlite3_free(pOut);
100241  }
100242  return rc;
100243}
100244
100245/*
100246** Evaluate the full-text expression pExpr against fts3 table pTab. Store
100247** the resulting doclist in *paOut and *pnOut.
100248*/
100249static int evalFts3Expr(
100250  Fts3Table *p,                   /* Virtual table handle */
100251  Fts3Expr *pExpr,                /* Parsed fts3 expression */
100252  char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
100253  int *pnOut,                     /* OUT: Size of buffer at *paOut */
100254  int isReqPos                    /* Require positions in output buffer */
100255){
100256  int rc = SQLITE_OK;             /* Return code */
100257
100258  /* Zero the output parameters. */
100259  *paOut = 0;
100260  *pnOut = 0;
100261
100262  if( pExpr ){
100263    assert( pExpr->eType==FTSQUERY_PHRASE
100264         || pExpr->eType==FTSQUERY_NEAR
100265         || isReqPos==0
100266    );
100267    if( pExpr->eType==FTSQUERY_PHRASE ){
100268      rc = fts3PhraseSelect(p, pExpr->pPhrase,
100269          isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
100270          paOut, pnOut
100271      );
100272    }else{
100273      char *aLeft;
100274      char *aRight;
100275      int nLeft;
100276      int nRight;
100277
100278      if( 0==(rc = evalFts3Expr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
100279       && 0==(rc = evalFts3Expr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
100280      ){
100281        assert( pExpr->eType==FTSQUERY_NEAR || pExpr->eType==FTSQUERY_OR
100282            || pExpr->eType==FTSQUERY_AND  || pExpr->eType==FTSQUERY_NOT
100283        );
100284        switch( pExpr->eType ){
100285          case FTSQUERY_NEAR: {
100286            Fts3Expr *pLeft;
100287            Fts3Expr *pRight;
100288            int mergetype = isReqPos ? MERGE_POS_NEAR : MERGE_NEAR;
100289            int nParam1;
100290            int nParam2;
100291            char *aBuffer;
100292
100293            if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
100294              mergetype = MERGE_POS_NEAR;
100295            }
100296            pLeft = pExpr->pLeft;
100297            while( pLeft->eType==FTSQUERY_NEAR ){
100298              pLeft=pLeft->pRight;
100299            }
100300            pRight = pExpr->pRight;
100301            assert( pRight->eType==FTSQUERY_PHRASE );
100302            assert( pLeft->eType==FTSQUERY_PHRASE );
100303
100304            nParam1 = pExpr->nNear+1;
100305            nParam2 = nParam1+pLeft->pPhrase->nToken+pRight->pPhrase->nToken-2;
100306            aBuffer = sqlite3_malloc(nLeft+nRight+1);
100307            rc = fts3DoclistMerge(mergetype, nParam1, nParam2, aBuffer,
100308                pnOut, aLeft, nLeft, aRight, nRight
100309            );
100310            if( rc!=SQLITE_OK ){
100311              sqlite3_free(aBuffer);
100312            }else{
100313              *paOut = aBuffer;
100314            }
100315            sqlite3_free(aLeft);
100316            break;
100317          }
100318
100319          case FTSQUERY_OR: {
100320            /* Allocate a buffer for the output. The maximum size is the
100321            ** sum of the sizes of the two input buffers. The +1 term is
100322            ** so that a buffer of zero bytes is never allocated - this can
100323            ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
100324            */
100325            char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
100326            rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
100327                aLeft, nLeft, aRight, nRight
100328            );
100329            *paOut = aBuffer;
100330            sqlite3_free(aLeft);
100331            break;
100332          }
100333
100334          default: {
100335            assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
100336            fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
100337                aLeft, nLeft, aRight, nRight
100338            );
100339            *paOut = aLeft;
100340            break;
100341          }
100342        }
100343      }
100344      sqlite3_free(aRight);
100345    }
100346  }
100347
100348  return rc;
100349}
100350
100351/*
100352** This is the xFilter interface for the virtual table.  See
100353** the virtual table xFilter method documentation for additional
100354** information.
100355**
100356** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
100357** the %_content table.
100358**
100359** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
100360** in the %_content table.
100361**
100362** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
100363** column on the left-hand side of the MATCH operator is column
100364** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
100365** side of the MATCH operator.
100366*/
100367/* TODO(shess) Upgrade the cursor initialization and destruction to
100368** account for fts3FilterMethod() being called multiple times on the
100369** same cursor. The current solution is very fragile. Apply fix to
100370** fts3 as appropriate.
100371*/
100372static int fts3FilterMethod(
100373  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
100374  int idxNum,                     /* Strategy index */
100375  const char *idxStr,             /* Unused */
100376  int nVal,                       /* Number of elements in apVal */
100377  sqlite3_value **apVal           /* Arguments for the indexing scheme */
100378){
100379  const char *azSql[] = {
100380    "SELECT * FROM %Q.'%q_content' WHERE docid = ?", /* non-full-table-scan */
100381    "SELECT * FROM %Q.'%q_content'",                 /* full-table-scan */
100382  };
100383  int rc;                         /* Return code */
100384  char *zSql;                     /* SQL statement used to access %_content */
100385  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
100386  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
100387
100388  UNUSED_PARAMETER(idxStr);
100389  UNUSED_PARAMETER(nVal);
100390
100391  assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
100392  assert( nVal==0 || nVal==1 );
100393  assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
100394
100395  /* In case the cursor has been used before, clear it now. */
100396  sqlite3_finalize(pCsr->pStmt);
100397  sqlite3_free(pCsr->aDoclist);
100398  sqlite3Fts3ExprFree(pCsr->pExpr);
100399  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
100400
100401  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
100402  ** statement loops through all rows of the %_content table. For a
100403  ** full-text query or docid lookup, the statement retrieves a single
100404  ** row by docid.
100405  */
100406  zSql = sqlite3_mprintf(azSql[idxNum==FTS3_FULLSCAN_SEARCH], p->zDb, p->zName);
100407  if( !zSql ){
100408    rc = SQLITE_NOMEM;
100409  }else{
100410    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
100411    sqlite3_free(zSql);
100412  }
100413  if( rc!=SQLITE_OK ) return rc;
100414  pCsr->eSearch = (i16)idxNum;
100415
100416  if( idxNum==FTS3_DOCID_SEARCH ){
100417    rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
100418  }else if( idxNum!=FTS3_FULLSCAN_SEARCH ){
100419    int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
100420    const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
100421
100422    if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
100423      return SQLITE_NOMEM;
100424    }
100425
100426    rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn,
100427        iCol, zQuery, -1, &pCsr->pExpr
100428    );
100429    if( rc!=SQLITE_OK ) return rc;
100430
100431    rc = evalFts3Expr(p, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
100432    pCsr->pNextId = pCsr->aDoclist;
100433    pCsr->iPrevId = 0;
100434  }
100435
100436  if( rc!=SQLITE_OK ) return rc;
100437  return fts3NextMethod(pCursor);
100438}
100439
100440/*
100441** This is the xEof method of the virtual table. SQLite calls this
100442** routine to find out if it has reached the end of a result set.
100443*/
100444static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
100445  return ((Fts3Cursor *)pCursor)->isEof;
100446}
100447
100448/*
100449** This is the xRowid method. The SQLite core calls this routine to
100450** retrieve the rowid for the current row of the result set. fts3
100451** exposes %_content.docid as the rowid for the virtual table. The
100452** rowid should be written to *pRowid.
100453*/
100454static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
100455  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
100456  if( pCsr->aDoclist ){
100457    *pRowid = pCsr->iPrevId;
100458  }else{
100459    *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
100460  }
100461  return SQLITE_OK;
100462}
100463
100464/*
100465** This is the xColumn method, called by SQLite to request a value from
100466** the row that the supplied cursor currently points to.
100467*/
100468static int fts3ColumnMethod(
100469  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
100470  sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
100471  int iCol                        /* Index of column to read value from */
100472){
100473  int rc;                         /* Return Code */
100474  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
100475  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
100476
100477  /* The column value supplied by SQLite must be in range. */
100478  assert( iCol>=0 && iCol<=p->nColumn+1 );
100479
100480  if( iCol==p->nColumn+1 ){
100481    /* This call is a request for the "docid" column. Since "docid" is an
100482    ** alias for "rowid", use the xRowid() method to obtain the value.
100483    */
100484    sqlite3_int64 iRowid;
100485    rc = fts3RowidMethod(pCursor, &iRowid);
100486    sqlite3_result_int64(pContext, iRowid);
100487  }else if( iCol==p->nColumn ){
100488    /* The extra column whose name is the same as the table.
100489    ** Return a blob which is a pointer to the cursor.
100490    */
100491    sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
100492    rc = SQLITE_OK;
100493  }else{
100494    rc = fts3CursorSeek(0, pCsr);
100495    if( rc==SQLITE_OK ){
100496      sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
100497    }
100498  }
100499  return rc;
100500}
100501
100502/*
100503** This function is the implementation of the xUpdate callback used by
100504** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
100505** inserted, updated or deleted.
100506*/
100507static int fts3UpdateMethod(
100508  sqlite3_vtab *pVtab,            /* Virtual table handle */
100509  int nArg,                       /* Size of argument array */
100510  sqlite3_value **apVal,          /* Array of arguments */
100511  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
100512){
100513  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
100514}
100515
100516/*
100517** Implementation of xSync() method. Flush the contents of the pending-terms
100518** hash-table to the database.
100519*/
100520static int fts3SyncMethod(sqlite3_vtab *pVtab){
100521  return sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
100522}
100523
100524/*
100525** Implementation of xBegin() method. This is a no-op.
100526*/
100527static int fts3BeginMethod(sqlite3_vtab *pVtab){
100528  UNUSED_PARAMETER(pVtab);
100529  assert( ((Fts3Table *)pVtab)->nPendingData==0 );
100530  return SQLITE_OK;
100531}
100532
100533/*
100534** Implementation of xCommit() method. This is a no-op. The contents of
100535** the pending-terms hash-table have already been flushed into the database
100536** by fts3SyncMethod().
100537*/
100538static int fts3CommitMethod(sqlite3_vtab *pVtab){
100539  UNUSED_PARAMETER(pVtab);
100540  assert( ((Fts3Table *)pVtab)->nPendingData==0 );
100541  return SQLITE_OK;
100542}
100543
100544/*
100545** Implementation of xRollback(). Discard the contents of the pending-terms
100546** hash-table. Any changes made to the database are reverted by SQLite.
100547*/
100548static int fts3RollbackMethod(sqlite3_vtab *pVtab){
100549  sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
100550  return SQLITE_OK;
100551}
100552
100553/*
100554** Load the doclist associated with expression pExpr to pExpr->aDoclist.
100555** The loaded doclist contains positions as well as the document ids.
100556** This is used by the matchinfo(), snippet() and offsets() auxillary
100557** functions.
100558*/
100559SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *pTab, Fts3Expr *pExpr){
100560  return evalFts3Expr(pTab, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
100561}
100562
100563/*
100564** After ExprLoadDoclist() (see above) has been called, this function is
100565** used to iterate through the position lists that make up the doclist
100566** stored in pExpr->aDoclist.
100567*/
100568SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
100569  Fts3Expr *pExpr,                /* Access this expressions doclist */
100570  sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
100571  int iCol                        /* Column of requested pos-list */
100572){
100573  assert( pExpr->isLoaded );
100574  if( pExpr->aDoclist ){
100575    char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
100576    char *pCsr = pExpr->pCurrent;
100577
100578    assert( pCsr );
100579    while( pCsr<pEnd ){
100580      if( pExpr->iCurrent<iDocid ){
100581        fts3PoslistCopy(0, &pCsr);
100582        fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
100583        pExpr->pCurrent = pCsr;
100584      }else{
100585        if( pExpr->iCurrent==iDocid ){
100586          int iThis = 0;
100587          if( iCol<0 ){
100588            /* If iCol is negative, return a pointer to the start of the
100589            ** position-list (instead of a pointer to the start of a list
100590            ** of offsets associated with a specific column).
100591            */
100592            return pCsr;
100593          }
100594          while( iThis<iCol ){
100595            fts3ColumnlistCopy(0, &pCsr);
100596            if( *pCsr==0x00 ) return 0;
100597            pCsr++;
100598            pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
100599          }
100600          if( iCol==iThis ) return pCsr;
100601        }
100602        return 0;
100603      }
100604    }
100605  }
100606
100607  return 0;
100608}
100609
100610/*
100611** Helper function used by the implementation of the overloaded snippet(),
100612** offsets() and optimize() SQL functions.
100613**
100614** If the value passed as the third argument is a blob of size
100615** sizeof(Fts3Cursor*), then the blob contents are copied to the
100616** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
100617** message is written to context pContext and SQLITE_ERROR returned. The
100618** string passed via zFunc is used as part of the error message.
100619*/
100620static int fts3FunctionArg(
100621  sqlite3_context *pContext,      /* SQL function call context */
100622  const char *zFunc,              /* Function name */
100623  sqlite3_value *pVal,            /* argv[0] passed to function */
100624  Fts3Cursor **ppCsr         /* OUT: Store cursor handle here */
100625){
100626  Fts3Cursor *pRet;
100627  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
100628   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
100629  ){
100630    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
100631    sqlite3_result_error(pContext, zErr, -1);
100632    sqlite3_free(zErr);
100633    return SQLITE_ERROR;
100634  }
100635  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
100636  *ppCsr = pRet;
100637  return SQLITE_OK;
100638}
100639
100640/*
100641** Implementation of the snippet() function for FTS3
100642*/
100643static void fts3SnippetFunc(
100644  sqlite3_context *pContext,      /* SQLite function call context */
100645  int nVal,                       /* Size of apVal[] array */
100646  sqlite3_value **apVal           /* Array of arguments */
100647){
100648  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100649  const char *zStart = "<b>";
100650  const char *zEnd = "</b>";
100651  const char *zEllipsis = "<b>...</b>";
100652
100653  /* There must be at least one argument passed to this function (otherwise
100654  ** the non-overloaded version would have been called instead of this one).
100655  */
100656  assert( nVal>=1 );
100657
100658  if( nVal>4 ){
100659    sqlite3_result_error(pContext,
100660        "wrong number of arguments to function snippet()", -1);
100661    return;
100662  }
100663  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
100664
100665  switch( nVal ){
100666    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
100667    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
100668    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
100669  }
100670  if( !zEllipsis || !zEnd || !zStart ){
100671    sqlite3_result_error_nomem(pContext);
100672  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
100673    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis);
100674  }
100675}
100676
100677/*
100678** Implementation of the snippet2() function for FTS3
100679*/
100680static void fts3Snippet2Func(
100681  sqlite3_context *pContext,      /* SQLite function call context */
100682  int nVal,                       /* Size of apVal[] array */
100683  sqlite3_value **apVal           /* Array of arguments */
100684){
100685  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100686  const char *zStart = "<b>";
100687  const char *zEnd = "</b>";
100688  const char *zEllipsis = "<b>...</b>";
100689  int iCol = -1;
100690  int nToken = 10;
100691
100692  /* There must be at least one argument passed to this function (otherwise
100693  ** the non-overloaded version would have been called instead of this one).
100694  */
100695  assert( nVal>=1 );
100696
100697  if( nVal>6 ){
100698    sqlite3_result_error(pContext,
100699        "wrong number of arguments to function snippet()", -1);
100700    return;
100701  }
100702  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
100703
100704  switch( nVal ){
100705    case 6: nToken = sqlite3_value_int(apVal[5]);
100706    case 5: iCol = sqlite3_value_int(apVal[4]);
100707    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
100708    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
100709    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
100710  }
100711  if( !zEllipsis || !zEnd || !zStart ){
100712    sqlite3_result_error_nomem(pContext);
100713  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
100714    sqlite3Fts3Snippet2(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
100715  }
100716}
100717
100718/*
100719** Implementation of the offsets() function for FTS3
100720*/
100721static void fts3OffsetsFunc(
100722  sqlite3_context *pContext,      /* SQLite function call context */
100723  int nVal,                       /* Size of argument array */
100724  sqlite3_value **apVal           /* Array of arguments */
100725){
100726  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100727
100728  UNUSED_PARAMETER(nVal);
100729
100730  assert( nVal==1 );
100731  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
100732  assert( pCsr );
100733  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
100734    sqlite3Fts3Offsets(pContext, pCsr);
100735  }
100736}
100737
100738/*
100739** Implementation of the special optimize() function for FTS3. This
100740** function merges all segments in the database to a single segment.
100741** Example usage is:
100742**
100743**   SELECT optimize(t) FROM t LIMIT 1;
100744**
100745** where 't' is the name of an FTS3 table.
100746*/
100747static void fts3OptimizeFunc(
100748  sqlite3_context *pContext,      /* SQLite function call context */
100749  int nVal,                       /* Size of argument array */
100750  sqlite3_value **apVal           /* Array of arguments */
100751){
100752  int rc;                         /* Return code */
100753  Fts3Table *p;                   /* Virtual table handle */
100754  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
100755
100756  UNUSED_PARAMETER(nVal);
100757
100758  assert( nVal==1 );
100759  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
100760  p = (Fts3Table *)pCursor->base.pVtab;
100761  assert( p );
100762
100763  rc = sqlite3Fts3Optimize(p);
100764
100765  switch( rc ){
100766    case SQLITE_OK:
100767      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
100768      break;
100769    case SQLITE_DONE:
100770      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
100771      break;
100772    default:
100773      sqlite3_result_error_code(pContext, rc);
100774      break;
100775  }
100776}
100777
100778/*
100779** Implementation of the matchinfo() function for FTS3
100780*/
100781static void fts3MatchinfoFunc(
100782  sqlite3_context *pContext,      /* SQLite function call context */
100783  int nVal,                       /* Size of argument array */
100784  sqlite3_value **apVal           /* Array of arguments */
100785){
100786  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100787
100788  if( nVal!=1 ){
100789    sqlite3_result_error(pContext,
100790        "wrong number of arguments to function matchinfo()", -1);
100791    return;
100792  }
100793
100794  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
100795    sqlite3Fts3Matchinfo(pContext, pCsr);
100796  }
100797}
100798
100799/*
100800** This routine implements the xFindFunction method for the FTS3
100801** virtual table.
100802*/
100803static int fts3FindFunctionMethod(
100804  sqlite3_vtab *pVtab,            /* Virtual table handle */
100805  int nArg,                       /* Number of SQL function arguments */
100806  const char *zName,              /* Name of SQL function */
100807  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
100808  void **ppArg                    /* Unused */
100809){
100810  struct Overloaded {
100811    const char *zName;
100812    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
100813  } aOverload[] = {
100814    { "snippet", fts3SnippetFunc },
100815    { "snippet2", fts3Snippet2Func },
100816    { "offsets", fts3OffsetsFunc },
100817    { "optimize", fts3OptimizeFunc },
100818    { "matchinfo", fts3MatchinfoFunc },
100819  };
100820  int i;                          /* Iterator variable */
100821
100822  UNUSED_PARAMETER(pVtab);
100823  UNUSED_PARAMETER(nArg);
100824  UNUSED_PARAMETER(ppArg);
100825
100826  for(i=0; i<SizeofArray(aOverload); i++){
100827    if( strcmp(zName, aOverload[i].zName)==0 ){
100828      *pxFunc = aOverload[i].xFunc;
100829      return 1;
100830    }
100831  }
100832
100833  /* No function of the specified name was found. Return 0. */
100834  return 0;
100835}
100836
100837/*
100838** Implementation of FTS3 xRename method. Rename an fts3 table.
100839*/
100840static int fts3RenameMethod(
100841  sqlite3_vtab *pVtab,            /* Virtual table handle */
100842  const char *zName               /* New name of table */
100843){
100844  Fts3Table *p = (Fts3Table *)pVtab;
100845  int rc = SQLITE_NOMEM;          /* Return Code */
100846  char *zSql;                     /* SQL script to run to rename tables */
100847
100848  zSql = sqlite3_mprintf(
100849    "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
100850    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
100851    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
100852    , p->zDb, p->zName, zName
100853    , p->zDb, p->zName, zName
100854    , p->zDb, p->zName, zName
100855  );
100856  if( zSql ){
100857    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
100858    sqlite3_free(zSql);
100859  }
100860  return rc;
100861}
100862
100863static const sqlite3_module fts3Module = {
100864  /* iVersion      */ 0,
100865  /* xCreate       */ fts3CreateMethod,
100866  /* xConnect      */ fts3ConnectMethod,
100867  /* xBestIndex    */ fts3BestIndexMethod,
100868  /* xDisconnect   */ fts3DisconnectMethod,
100869  /* xDestroy      */ fts3DestroyMethod,
100870  /* xOpen         */ fts3OpenMethod,
100871  /* xClose        */ fulltextClose,
100872  /* xFilter       */ fts3FilterMethod,
100873  /* xNext         */ fts3NextMethod,
100874  /* xEof          */ fts3EofMethod,
100875  /* xColumn       */ fts3ColumnMethod,
100876  /* xRowid        */ fts3RowidMethod,
100877  /* xUpdate       */ fts3UpdateMethod,
100878  /* xBegin        */ fts3BeginMethod,
100879  /* xSync         */ fts3SyncMethod,
100880  /* xCommit       */ fts3CommitMethod,
100881  /* xRollback     */ fts3RollbackMethod,
100882  /* xFindFunction */ fts3FindFunctionMethod,
100883  /* xRename */       fts3RenameMethod,
100884};
100885
100886/*
100887** This function is registered as the module destructor (called when an
100888** FTS3 enabled database connection is closed). It frees the memory
100889** allocated for the tokenizer hash table.
100890*/
100891static void hashDestroy(void *p){
100892  Fts3Hash *pHash = (Fts3Hash *)p;
100893  sqlite3Fts3HashClear(pHash);
100894  sqlite3_free(pHash);
100895}
100896
100897/*
100898** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
100899** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
100900** two forward declarations are for functions declared in these files
100901** used to retrieve the respective implementations.
100902**
100903** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
100904** to by the argument to point a the "simple" tokenizer implementation.
100905** Function ...PorterTokenizerModule() sets *pModule to point to the
100906** porter tokenizer/stemmer implementation.
100907*/
100908SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
100909SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
100910SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
100911
100912/*
100913** Initialise the fts3 extension. If this extension is built as part
100914** of the sqlite library, then this function is called directly by
100915** SQLite. If fts3 is built as a dynamically loadable extension, this
100916** function is called by the sqlite3_extension_init() entry point.
100917*/
100918SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
100919  int rc = SQLITE_OK;
100920  Fts3Hash *pHash = 0;
100921  const sqlite3_tokenizer_module *pSimple = 0;
100922  const sqlite3_tokenizer_module *pPorter = 0;
100923
100924#ifdef SQLITE_ENABLE_ICU
100925  const sqlite3_tokenizer_module *pIcu = 0;
100926  sqlite3Fts3IcuTokenizerModule(&pIcu);
100927#endif
100928
100929  sqlite3Fts3SimpleTokenizerModule(&pSimple);
100930  sqlite3Fts3PorterTokenizerModule(&pPorter);
100931
100932  /* Allocate and initialise the hash-table used to store tokenizers. */
100933  pHash = sqlite3_malloc(sizeof(Fts3Hash));
100934  if( !pHash ){
100935    rc = SQLITE_NOMEM;
100936  }else{
100937    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
100938  }
100939
100940  /* Load the built-in tokenizers into the hash table */
100941  if( rc==SQLITE_OK ){
100942    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
100943     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
100944#ifdef SQLITE_ENABLE_ICU
100945     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
100946#endif
100947    ){
100948      rc = SQLITE_NOMEM;
100949    }
100950  }
100951
100952#ifdef SQLITE_TEST
100953  if( rc==SQLITE_OK ){
100954    rc = sqlite3Fts3ExprInitTestInterface(db);
100955  }
100956#endif
100957
100958  /* Create the virtual table wrapper around the hash-table and overload
100959  ** the two scalar functions. If this is successful, register the
100960  ** module with sqlite.
100961  */
100962  if( SQLITE_OK==rc
100963   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
100964   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
100965   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet2", -1))
100966   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
100967   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", -1))
100968   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
100969  ){
100970    return sqlite3_create_module_v2(
100971        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
100972    );
100973  }
100974
100975  /* An error has occurred. Delete the hash table and return the error code. */
100976  assert( rc!=SQLITE_OK );
100977  if( pHash ){
100978    sqlite3Fts3HashClear(pHash);
100979    sqlite3_free(pHash);
100980  }
100981  return rc;
100982}
100983
100984#if !SQLITE_CORE
100985SQLITE_API int sqlite3_extension_init(
100986  sqlite3 *db,
100987  char **pzErrMsg,
100988  const sqlite3_api_routines *pApi
100989){
100990  SQLITE_EXTENSION_INIT2(pApi)
100991  return sqlite3Fts3Init(db);
100992}
100993#endif
100994
100995#endif
100996
100997/************** End of fts3.c ************************************************/
100998/************** Begin file fts3_expr.c ***************************************/
100999/*
101000** 2008 Nov 28
101001**
101002** The author disclaims copyright to this source code.  In place of
101003** a legal notice, here is a blessing:
101004**
101005**    May you do good and not evil.
101006**    May you find forgiveness for yourself and forgive others.
101007**    May you share freely, never taking more than you give.
101008**
101009******************************************************************************
101010**
101011** This module contains code that implements a parser for fts3 query strings
101012** (the right-hand argument to the MATCH operator). Because the supported
101013** syntax is relatively simple, the whole tokenizer/parser system is
101014** hand-coded.
101015*/
101016#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
101017
101018/*
101019** By default, this module parses the legacy syntax that has been
101020** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
101021** is defined, then it uses the new syntax. The differences between
101022** the new and the old syntaxes are:
101023**
101024**  a) The new syntax supports parenthesis. The old does not.
101025**
101026**  b) The new syntax supports the AND and NOT operators. The old does not.
101027**
101028**  c) The old syntax supports the "-" token qualifier. This is not
101029**     supported by the new syntax (it is replaced by the NOT operator).
101030**
101031**  d) When using the old syntax, the OR operator has a greater precedence
101032**     than an implicit AND. When using the new, both implicity and explicit
101033**     AND operators have a higher precedence than OR.
101034**
101035** If compiled with SQLITE_TEST defined, then this module exports the
101036** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
101037** to zero causes the module to use the old syntax. If it is set to
101038** non-zero the new syntax is activated. This is so both syntaxes can
101039** be tested using a single build of testfixture.
101040**
101041** The following describes the syntax supported by the fts3 MATCH
101042** operator in a similar format to that used by the lemon parser
101043** generator. This module does not use actually lemon, it uses a
101044** custom parser.
101045**
101046**   query ::= andexpr (OR andexpr)*.
101047**
101048**   andexpr ::= notexpr (AND? notexpr)*.
101049**
101050**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
101051**   notexpr ::= LP query RP.
101052**
101053**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
101054**
101055**   distance_opt ::= .
101056**   distance_opt ::= / INTEGER.
101057**
101058**   phrase ::= TOKEN.
101059**   phrase ::= COLUMN:TOKEN.
101060**   phrase ::= "TOKEN TOKEN TOKEN...".
101061*/
101062
101063#ifdef SQLITE_TEST
101064SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
101065#else
101066# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
101067#  define sqlite3_fts3_enable_parentheses 1
101068# else
101069#  define sqlite3_fts3_enable_parentheses 0
101070# endif
101071#endif
101072
101073/*
101074** Default span for NEAR operators.
101075*/
101076#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
101077
101078
101079typedef struct ParseContext ParseContext;
101080struct ParseContext {
101081  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
101082  const char **azCol;                 /* Array of column names for fts3 table */
101083  int nCol;                           /* Number of entries in azCol[] */
101084  int iDefaultCol;                    /* Default column to query */
101085  sqlite3_context *pCtx;              /* Write error message here */
101086  int nNest;                          /* Number of nested brackets */
101087};
101088
101089/*
101090** This function is equivalent to the standard isspace() function.
101091**
101092** The standard isspace() can be awkward to use safely, because although it
101093** is defined to accept an argument of type int, its behaviour when passed
101094** an integer that falls outside of the range of the unsigned char type
101095** is undefined (and sometimes, "undefined" means segfault). This wrapper
101096** is defined to accept an argument of type char, and always returns 0 for
101097** any values that fall outside of the range of the unsigned char type (i.e.
101098** negative values).
101099*/
101100static int fts3isspace(char c){
101101  return (c&0x80)==0 ? isspace(c) : 0;
101102}
101103
101104/*
101105** Extract the next token from buffer z (length n) using the tokenizer
101106** and other information (column names etc.) in pParse. Create an Fts3Expr
101107** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
101108** single token and set *ppExpr to point to it. If the end of the buffer is
101109** reached before a token is found, set *ppExpr to zero. It is the
101110** responsibility of the caller to eventually deallocate the allocated
101111** Fts3Expr structure (if any) by passing it to sqlite3_free().
101112**
101113** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
101114** fails.
101115*/
101116static int getNextToken(
101117  ParseContext *pParse,                   /* fts3 query parse context */
101118  int iCol,                               /* Value for Fts3Phrase.iColumn */
101119  const char *z, int n,                   /* Input string */
101120  Fts3Expr **ppExpr,                      /* OUT: expression */
101121  int *pnConsumed                         /* OUT: Number of bytes consumed */
101122){
101123  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
101124  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
101125  int rc;
101126  sqlite3_tokenizer_cursor *pCursor;
101127  Fts3Expr *pRet = 0;
101128  int nConsumed = 0;
101129
101130  rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
101131  if( rc==SQLITE_OK ){
101132    const char *zToken;
101133    int nToken, iStart, iEnd, iPosition;
101134    int nByte;                               /* total space to allocate */
101135
101136    pCursor->pTokenizer = pTokenizer;
101137    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
101138
101139    if( rc==SQLITE_OK ){
101140      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
101141      pRet = (Fts3Expr *)sqlite3_malloc(nByte);
101142      if( !pRet ){
101143        rc = SQLITE_NOMEM;
101144      }else{
101145        memset(pRet, 0, nByte);
101146        pRet->eType = FTSQUERY_PHRASE;
101147        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
101148        pRet->pPhrase->nToken = 1;
101149        pRet->pPhrase->iColumn = iCol;
101150        pRet->pPhrase->aToken[0].n = nToken;
101151        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
101152        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
101153
101154        if( iEnd<n && z[iEnd]=='*' ){
101155          pRet->pPhrase->aToken[0].isPrefix = 1;
101156          iEnd++;
101157        }
101158        if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
101159          pRet->pPhrase->isNot = 1;
101160        }
101161      }
101162      nConsumed = iEnd;
101163    }
101164
101165    pModule->xClose(pCursor);
101166  }
101167
101168  *pnConsumed = nConsumed;
101169  *ppExpr = pRet;
101170  return rc;
101171}
101172
101173
101174/*
101175** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
101176** then free the old allocation.
101177*/
101178static void *fts3ReallocOrFree(void *pOrig, int nNew){
101179  void *pRet = sqlite3_realloc(pOrig, nNew);
101180  if( !pRet ){
101181    sqlite3_free(pOrig);
101182  }
101183  return pRet;
101184}
101185
101186/*
101187** Buffer zInput, length nInput, contains the contents of a quoted string
101188** that appeared as part of an fts3 query expression. Neither quote character
101189** is included in the buffer. This function attempts to tokenize the entire
101190** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
101191** containing the results.
101192**
101193** If successful, SQLITE_OK is returned and *ppExpr set to point at the
101194** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
101195** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
101196** to 0.
101197*/
101198static int getNextString(
101199  ParseContext *pParse,                   /* fts3 query parse context */
101200  const char *zInput, int nInput,         /* Input string */
101201  Fts3Expr **ppExpr                       /* OUT: expression */
101202){
101203  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
101204  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
101205  int rc;
101206  Fts3Expr *p = 0;
101207  sqlite3_tokenizer_cursor *pCursor = 0;
101208  char *zTemp = 0;
101209  int nTemp = 0;
101210
101211  rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
101212  if( rc==SQLITE_OK ){
101213    int ii;
101214    pCursor->pTokenizer = pTokenizer;
101215    for(ii=0; rc==SQLITE_OK; ii++){
101216      const char *zToken;
101217      int nToken, iBegin, iEnd, iPos;
101218      rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
101219      if( rc==SQLITE_OK ){
101220        int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
101221        p = fts3ReallocOrFree(p, nByte+ii*sizeof(struct PhraseToken));
101222        zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
101223        if( !p || !zTemp ){
101224          goto no_mem;
101225        }
101226        if( ii==0 ){
101227          memset(p, 0, nByte);
101228          p->pPhrase = (Fts3Phrase *)&p[1];
101229        }
101230        p->pPhrase = (Fts3Phrase *)&p[1];
101231        p->pPhrase->nToken = ii+1;
101232        p->pPhrase->aToken[ii].n = nToken;
101233        memcpy(&zTemp[nTemp], zToken, nToken);
101234        nTemp += nToken;
101235        if( iEnd<nInput && zInput[iEnd]=='*' ){
101236          p->pPhrase->aToken[ii].isPrefix = 1;
101237        }else{
101238          p->pPhrase->aToken[ii].isPrefix = 0;
101239        }
101240      }
101241    }
101242
101243    pModule->xClose(pCursor);
101244    pCursor = 0;
101245  }
101246
101247  if( rc==SQLITE_DONE ){
101248    int jj;
101249    char *zNew = NULL;
101250    int nNew = 0;
101251    int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
101252    nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(struct PhraseToken);
101253    p = fts3ReallocOrFree(p, nByte + nTemp);
101254    if( !p ){
101255      goto no_mem;
101256    }
101257    if( zTemp ){
101258      zNew = &(((char *)p)[nByte]);
101259      memcpy(zNew, zTemp, nTemp);
101260    }else{
101261      memset(p, 0, nByte+nTemp);
101262    }
101263    p->pPhrase = (Fts3Phrase *)&p[1];
101264    for(jj=0; jj<p->pPhrase->nToken; jj++){
101265      p->pPhrase->aToken[jj].z = &zNew[nNew];
101266      nNew += p->pPhrase->aToken[jj].n;
101267    }
101268    sqlite3_free(zTemp);
101269    p->eType = FTSQUERY_PHRASE;
101270    p->pPhrase->iColumn = pParse->iDefaultCol;
101271    rc = SQLITE_OK;
101272  }
101273
101274  *ppExpr = p;
101275  return rc;
101276no_mem:
101277
101278  if( pCursor ){
101279    pModule->xClose(pCursor);
101280  }
101281  sqlite3_free(zTemp);
101282  sqlite3_free(p);
101283  *ppExpr = 0;
101284  return SQLITE_NOMEM;
101285}
101286
101287/*
101288** Function getNextNode(), which is called by fts3ExprParse(), may itself
101289** call fts3ExprParse(). So this forward declaration is required.
101290*/
101291static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
101292
101293/*
101294** The output variable *ppExpr is populated with an allocated Fts3Expr
101295** structure, or set to 0 if the end of the input buffer is reached.
101296**
101297** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
101298** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
101299** If SQLITE_ERROR is returned, pContext is populated with an error message.
101300*/
101301static int getNextNode(
101302  ParseContext *pParse,                   /* fts3 query parse context */
101303  const char *z, int n,                   /* Input string */
101304  Fts3Expr **ppExpr,                      /* OUT: expression */
101305  int *pnConsumed                         /* OUT: Number of bytes consumed */
101306){
101307  static const struct Fts3Keyword {
101308    char *z;                              /* Keyword text */
101309    unsigned char n;                      /* Length of the keyword */
101310    unsigned char parenOnly;              /* Only valid in paren mode */
101311    unsigned char eType;                  /* Keyword code */
101312  } aKeyword[] = {
101313    { "OR" ,  2, 0, FTSQUERY_OR   },
101314    { "AND",  3, 1, FTSQUERY_AND  },
101315    { "NOT",  3, 1, FTSQUERY_NOT  },
101316    { "NEAR", 4, 0, FTSQUERY_NEAR }
101317  };
101318  int ii;
101319  int iCol;
101320  int iColLen;
101321  int rc;
101322  Fts3Expr *pRet = 0;
101323
101324  const char *zInput = z;
101325  int nInput = n;
101326
101327  /* Skip over any whitespace before checking for a keyword, an open or
101328  ** close bracket, or a quoted string.
101329  */
101330  while( nInput>0 && fts3isspace(*zInput) ){
101331    nInput--;
101332    zInput++;
101333  }
101334  if( nInput==0 ){
101335    return SQLITE_DONE;
101336  }
101337
101338  /* See if we are dealing with a keyword. */
101339  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
101340    const struct Fts3Keyword *pKey = &aKeyword[ii];
101341
101342    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
101343      continue;
101344    }
101345
101346    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
101347      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
101348      int nKey = pKey->n;
101349      char cNext;
101350
101351      /* If this is a "NEAR" keyword, check for an explicit nearness. */
101352      if( pKey->eType==FTSQUERY_NEAR ){
101353        assert( nKey==4 );
101354        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
101355          nNear = 0;
101356          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
101357            nNear = nNear * 10 + (zInput[nKey] - '0');
101358          }
101359        }
101360      }
101361
101362      /* At this point this is probably a keyword. But for that to be true,
101363      ** the next byte must contain either whitespace, an open or close
101364      ** parenthesis, a quote character, or EOF.
101365      */
101366      cNext = zInput[nKey];
101367      if( fts3isspace(cNext)
101368       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
101369      ){
101370        pRet = (Fts3Expr *)sqlite3_malloc(sizeof(Fts3Expr));
101371        if( !pRet ){
101372          return SQLITE_NOMEM;
101373        }
101374        memset(pRet, 0, sizeof(Fts3Expr));
101375        pRet->eType = pKey->eType;
101376        pRet->nNear = nNear;
101377        *ppExpr = pRet;
101378        *pnConsumed = (int)((zInput - z) + nKey);
101379        return SQLITE_OK;
101380      }
101381
101382      /* Turns out that wasn't a keyword after all. This happens if the
101383      ** user has supplied a token such as "ORacle". Continue.
101384      */
101385    }
101386  }
101387
101388  /* Check for an open bracket. */
101389  if( sqlite3_fts3_enable_parentheses ){
101390    if( *zInput=='(' ){
101391      int nConsumed;
101392      int rc;
101393      pParse->nNest++;
101394      rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
101395      if( rc==SQLITE_OK && !*ppExpr ){
101396        rc = SQLITE_DONE;
101397      }
101398      *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
101399      return rc;
101400    }
101401
101402    /* Check for a close bracket. */
101403    if( *zInput==')' ){
101404      pParse->nNest--;
101405      *pnConsumed = (int)((zInput - z) + 1);
101406      return SQLITE_DONE;
101407    }
101408  }
101409
101410  /* See if we are dealing with a quoted phrase. If this is the case, then
101411  ** search for the closing quote and pass the whole string to getNextString()
101412  ** for processing. This is easy to do, as fts3 has no syntax for escaping
101413  ** a quote character embedded in a string.
101414  */
101415  if( *zInput=='"' ){
101416    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
101417    *pnConsumed = (int)((zInput - z) + ii + 1);
101418    if( ii==nInput ){
101419      return SQLITE_ERROR;
101420    }
101421    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
101422  }
101423
101424
101425  /* If control flows to this point, this must be a regular token, or
101426  ** the end of the input. Read a regular token using the sqlite3_tokenizer
101427  ** interface. Before doing so, figure out if there is an explicit
101428  ** column specifier for the token.
101429  **
101430  ** TODO: Strangely, it is not possible to associate a column specifier
101431  ** with a quoted phrase, only with a single token. Not sure if this was
101432  ** an implementation artifact or an intentional decision when fts3 was
101433  ** first implemented. Whichever it was, this module duplicates the
101434  ** limitation.
101435  */
101436  iCol = pParse->iDefaultCol;
101437  iColLen = 0;
101438  for(ii=0; ii<pParse->nCol; ii++){
101439    const char *zStr = pParse->azCol[ii];
101440    int nStr = (int)strlen(zStr);
101441    if( nInput>nStr && zInput[nStr]==':'
101442     && sqlite3_strnicmp(zStr, zInput, nStr)==0
101443    ){
101444      iCol = ii;
101445      iColLen = (int)((zInput - z) + nStr + 1);
101446      break;
101447    }
101448  }
101449  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
101450  *pnConsumed += iColLen;
101451  return rc;
101452}
101453
101454/*
101455** The argument is an Fts3Expr structure for a binary operator (any type
101456** except an FTSQUERY_PHRASE). Return an integer value representing the
101457** precedence of the operator. Lower values have a higher precedence (i.e.
101458** group more tightly). For example, in the C language, the == operator
101459** groups more tightly than ||, and would therefore have a higher precedence.
101460**
101461** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
101462** is defined), the order of the operators in precedence from highest to
101463** lowest is:
101464**
101465**   NEAR
101466**   NOT
101467**   AND (including implicit ANDs)
101468**   OR
101469**
101470** Note that when using the old query syntax, the OR operator has a higher
101471** precedence than the AND operator.
101472*/
101473static int opPrecedence(Fts3Expr *p){
101474  assert( p->eType!=FTSQUERY_PHRASE );
101475  if( sqlite3_fts3_enable_parentheses ){
101476    return p->eType;
101477  }else if( p->eType==FTSQUERY_NEAR ){
101478    return 1;
101479  }else if( p->eType==FTSQUERY_OR ){
101480    return 2;
101481  }
101482  assert( p->eType==FTSQUERY_AND );
101483  return 3;
101484}
101485
101486/*
101487** Argument ppHead contains a pointer to the current head of a query
101488** expression tree being parsed. pPrev is the expression node most recently
101489** inserted into the tree. This function adds pNew, which is always a binary
101490** operator node, into the expression tree based on the relative precedence
101491** of pNew and the existing nodes of the tree. This may result in the head
101492** of the tree changing, in which case *ppHead is set to the new root node.
101493*/
101494static void insertBinaryOperator(
101495  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
101496  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
101497  Fts3Expr *pNew           /* New binary node to insert into expression tree */
101498){
101499  Fts3Expr *pSplit = pPrev;
101500  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
101501    pSplit = pSplit->pParent;
101502  }
101503
101504  if( pSplit->pParent ){
101505    assert( pSplit->pParent->pRight==pSplit );
101506    pSplit->pParent->pRight = pNew;
101507    pNew->pParent = pSplit->pParent;
101508  }else{
101509    *ppHead = pNew;
101510  }
101511  pNew->pLeft = pSplit;
101512  pSplit->pParent = pNew;
101513}
101514
101515/*
101516** Parse the fts3 query expression found in buffer z, length n. This function
101517** returns either when the end of the buffer is reached or an unmatched
101518** closing bracket - ')' - is encountered.
101519**
101520** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
101521** parsed form of the expression and *pnConsumed is set to the number of
101522** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
101523** (out of memory error) or SQLITE_ERROR (parse error) is returned.
101524*/
101525static int fts3ExprParse(
101526  ParseContext *pParse,                   /* fts3 query parse context */
101527  const char *z, int n,                   /* Text of MATCH query */
101528  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
101529  int *pnConsumed                         /* OUT: Number of bytes consumed */
101530){
101531  Fts3Expr *pRet = 0;
101532  Fts3Expr *pPrev = 0;
101533  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
101534  int nIn = n;
101535  const char *zIn = z;
101536  int rc = SQLITE_OK;
101537  int isRequirePhrase = 1;
101538
101539  while( rc==SQLITE_OK ){
101540    Fts3Expr *p = 0;
101541    int nByte = 0;
101542    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
101543    if( rc==SQLITE_OK ){
101544      int isPhrase;
101545
101546      if( !sqlite3_fts3_enable_parentheses
101547       && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot
101548      ){
101549        /* Create an implicit NOT operator. */
101550        Fts3Expr *pNot = sqlite3_malloc(sizeof(Fts3Expr));
101551        if( !pNot ){
101552          sqlite3Fts3ExprFree(p);
101553          rc = SQLITE_NOMEM;
101554          goto exprparse_out;
101555        }
101556        memset(pNot, 0, sizeof(Fts3Expr));
101557        pNot->eType = FTSQUERY_NOT;
101558        pNot->pRight = p;
101559        if( pNotBranch ){
101560          pNot->pLeft = pNotBranch;
101561        }
101562        pNotBranch = pNot;
101563        p = pPrev;
101564      }else{
101565        int eType = p->eType;
101566        assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
101567        isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
101568
101569        /* The isRequirePhrase variable is set to true if a phrase or
101570        ** an expression contained in parenthesis is required. If a
101571        ** binary operator (AND, OR, NOT or NEAR) is encounted when
101572        ** isRequirePhrase is set, this is a syntax error.
101573        */
101574        if( !isPhrase && isRequirePhrase ){
101575          sqlite3Fts3ExprFree(p);
101576          rc = SQLITE_ERROR;
101577          goto exprparse_out;
101578        }
101579
101580        if( isPhrase && !isRequirePhrase ){
101581          /* Insert an implicit AND operator. */
101582          Fts3Expr *pAnd;
101583          assert( pRet && pPrev );
101584          pAnd = sqlite3_malloc(sizeof(Fts3Expr));
101585          if( !pAnd ){
101586            sqlite3Fts3ExprFree(p);
101587            rc = SQLITE_NOMEM;
101588            goto exprparse_out;
101589          }
101590          memset(pAnd, 0, sizeof(Fts3Expr));
101591          pAnd->eType = FTSQUERY_AND;
101592          insertBinaryOperator(&pRet, pPrev, pAnd);
101593          pPrev = pAnd;
101594        }
101595
101596        /* This test catches attempts to make either operand of a NEAR
101597        ** operator something other than a phrase. For example, either of
101598        ** the following:
101599        **
101600        **    (bracketed expression) NEAR phrase
101601        **    phrase NEAR (bracketed expression)
101602        **
101603        ** Return an error in either case.
101604        */
101605        if( pPrev && (
101606            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
101607         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
101608        )){
101609          sqlite3Fts3ExprFree(p);
101610          rc = SQLITE_ERROR;
101611          goto exprparse_out;
101612        }
101613
101614        if( isPhrase ){
101615          if( pRet ){
101616            assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
101617            pPrev->pRight = p;
101618            p->pParent = pPrev;
101619          }else{
101620            pRet = p;
101621          }
101622        }else{
101623          insertBinaryOperator(&pRet, pPrev, p);
101624        }
101625        isRequirePhrase = !isPhrase;
101626      }
101627      assert( nByte>0 );
101628    }
101629    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
101630    nIn -= nByte;
101631    zIn += nByte;
101632    pPrev = p;
101633  }
101634
101635  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
101636    rc = SQLITE_ERROR;
101637  }
101638
101639  if( rc==SQLITE_DONE ){
101640    rc = SQLITE_OK;
101641    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
101642      if( !pRet ){
101643        rc = SQLITE_ERROR;
101644      }else{
101645        Fts3Expr *pIter = pNotBranch;
101646        while( pIter->pLeft ){
101647          pIter = pIter->pLeft;
101648        }
101649        pIter->pLeft = pRet;
101650        pRet = pNotBranch;
101651      }
101652    }
101653  }
101654  *pnConsumed = n - nIn;
101655
101656exprparse_out:
101657  if( rc!=SQLITE_OK ){
101658    sqlite3Fts3ExprFree(pRet);
101659    sqlite3Fts3ExprFree(pNotBranch);
101660    pRet = 0;
101661  }
101662  *ppExpr = pRet;
101663  return rc;
101664}
101665
101666/*
101667** Parameters z and n contain a pointer to and length of a buffer containing
101668** an fts3 query expression, respectively. This function attempts to parse the
101669** query expression and create a tree of Fts3Expr structures representing the
101670** parsed expression. If successful, *ppExpr is set to point to the head
101671** of the parsed expression tree and SQLITE_OK is returned. If an error
101672** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
101673** error) is returned and *ppExpr is set to 0.
101674**
101675** If parameter n is a negative number, then z is assumed to point to a
101676** nul-terminated string and the length is determined using strlen().
101677**
101678** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
101679** use to normalize query tokens while parsing the expression. The azCol[]
101680** array, which is assumed to contain nCol entries, should contain the names
101681** of each column in the target fts3 table, in order from left to right.
101682** Column names must be nul-terminated strings.
101683**
101684** The iDefaultCol parameter should be passed the index of the table column
101685** that appears on the left-hand-side of the MATCH operator (the default
101686** column to match against for tokens for which a column name is not explicitly
101687** specified as part of the query string), or -1 if tokens may by default
101688** match any table column.
101689*/
101690SQLITE_PRIVATE int sqlite3Fts3ExprParse(
101691  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
101692  char **azCol,                       /* Array of column names for fts3 table */
101693  int nCol,                           /* Number of entries in azCol[] */
101694  int iDefaultCol,                    /* Default column to query */
101695  const char *z, int n,               /* Text of MATCH query */
101696  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
101697){
101698  int nParsed;
101699  int rc;
101700  ParseContext sParse;
101701  sParse.pTokenizer = pTokenizer;
101702  sParse.azCol = (const char **)azCol;
101703  sParse.nCol = nCol;
101704  sParse.iDefaultCol = iDefaultCol;
101705  sParse.nNest = 0;
101706  if( z==0 ){
101707    *ppExpr = 0;
101708    return SQLITE_OK;
101709  }
101710  if( n<0 ){
101711    n = (int)strlen(z);
101712  }
101713  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
101714
101715  /* Check for mismatched parenthesis */
101716  if( rc==SQLITE_OK && sParse.nNest ){
101717    rc = SQLITE_ERROR;
101718    sqlite3Fts3ExprFree(*ppExpr);
101719    *ppExpr = 0;
101720  }
101721
101722  return rc;
101723}
101724
101725/*
101726** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
101727*/
101728SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
101729  if( p ){
101730    sqlite3Fts3ExprFree(p->pLeft);
101731    sqlite3Fts3ExprFree(p->pRight);
101732    sqlite3_free(p->aDoclist);
101733    sqlite3_free(p);
101734  }
101735}
101736
101737/****************************************************************************
101738*****************************************************************************
101739** Everything after this point is just test code.
101740*/
101741
101742#ifdef SQLITE_TEST
101743
101744
101745/*
101746** Function to query the hash-table of tokenizers (see README.tokenizers).
101747*/
101748static int queryTestTokenizer(
101749  sqlite3 *db,
101750  const char *zName,
101751  const sqlite3_tokenizer_module **pp
101752){
101753  int rc;
101754  sqlite3_stmt *pStmt;
101755  const char zSql[] = "SELECT fts3_tokenizer(?)";
101756
101757  *pp = 0;
101758  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
101759  if( rc!=SQLITE_OK ){
101760    return rc;
101761  }
101762
101763  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
101764  if( SQLITE_ROW==sqlite3_step(pStmt) ){
101765    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
101766      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
101767    }
101768  }
101769
101770  return sqlite3_finalize(pStmt);
101771}
101772
101773/*
101774** This function is part of the test interface for the query parser. It
101775** writes a text representation of the query expression pExpr into the
101776** buffer pointed to by argument zBuf. It is assumed that zBuf is large
101777** enough to store the required text representation.
101778*/
101779static void exprToString(Fts3Expr *pExpr, char *zBuf){
101780  switch( pExpr->eType ){
101781    case FTSQUERY_PHRASE: {
101782      Fts3Phrase *pPhrase = pExpr->pPhrase;
101783      int i;
101784      zBuf += sprintf(zBuf, "PHRASE %d %d", pPhrase->iColumn, pPhrase->isNot);
101785      for(i=0; i<pPhrase->nToken; i++){
101786        zBuf += sprintf(zBuf," %.*s",pPhrase->aToken[i].n,pPhrase->aToken[i].z);
101787        zBuf += sprintf(zBuf,"%s", (pPhrase->aToken[i].isPrefix?"+":""));
101788      }
101789      return;
101790    }
101791
101792    case FTSQUERY_NEAR:
101793      zBuf += sprintf(zBuf, "NEAR/%d ", pExpr->nNear);
101794      break;
101795    case FTSQUERY_NOT:
101796      zBuf += sprintf(zBuf, "NOT ");
101797      break;
101798    case FTSQUERY_AND:
101799      zBuf += sprintf(zBuf, "AND ");
101800      break;
101801    case FTSQUERY_OR:
101802      zBuf += sprintf(zBuf, "OR ");
101803      break;
101804  }
101805
101806  zBuf += sprintf(zBuf, "{");
101807  exprToString(pExpr->pLeft, zBuf);
101808  zBuf += strlen(zBuf);
101809  zBuf += sprintf(zBuf, "} ");
101810
101811  zBuf += sprintf(zBuf, "{");
101812  exprToString(pExpr->pRight, zBuf);
101813  zBuf += strlen(zBuf);
101814  zBuf += sprintf(zBuf, "}");
101815}
101816
101817/*
101818** This is the implementation of a scalar SQL function used to test the
101819** expression parser. It should be called as follows:
101820**
101821**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
101822**
101823** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
101824** to parse the query expression (see README.tokenizers). The second argument
101825** is the query expression to parse. Each subsequent argument is the name
101826** of a column of the fts3 table that the query expression may refer to.
101827** For example:
101828**
101829**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
101830*/
101831static void fts3ExprTest(
101832  sqlite3_context *context,
101833  int argc,
101834  sqlite3_value **argv
101835){
101836  sqlite3_tokenizer_module const *pModule = 0;
101837  sqlite3_tokenizer *pTokenizer = 0;
101838  int rc;
101839  char **azCol = 0;
101840  const char *zExpr;
101841  int nExpr;
101842  int nCol;
101843  int ii;
101844  Fts3Expr *pExpr;
101845  sqlite3 *db = sqlite3_context_db_handle(context);
101846
101847  if( argc<3 ){
101848    sqlite3_result_error(context,
101849        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
101850    );
101851    return;
101852  }
101853
101854  rc = queryTestTokenizer(db,
101855                          (const char *)sqlite3_value_text(argv[0]), &pModule);
101856  if( rc==SQLITE_NOMEM ){
101857    sqlite3_result_error_nomem(context);
101858    goto exprtest_out;
101859  }else if( !pModule ){
101860    sqlite3_result_error(context, "No such tokenizer module", -1);
101861    goto exprtest_out;
101862  }
101863
101864  rc = pModule->xCreate(0, 0, &pTokenizer);
101865  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
101866  if( rc==SQLITE_NOMEM ){
101867    sqlite3_result_error_nomem(context);
101868    goto exprtest_out;
101869  }
101870  pTokenizer->pModule = pModule;
101871
101872  zExpr = (const char *)sqlite3_value_text(argv[1]);
101873  nExpr = sqlite3_value_bytes(argv[1]);
101874  nCol = argc-2;
101875  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
101876  if( !azCol ){
101877    sqlite3_result_error_nomem(context);
101878    goto exprtest_out;
101879  }
101880  for(ii=0; ii<nCol; ii++){
101881    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
101882  }
101883
101884  rc = sqlite3Fts3ExprParse(
101885      pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
101886  );
101887  if( rc==SQLITE_NOMEM ){
101888    sqlite3_result_error_nomem(context);
101889    goto exprtest_out;
101890  }else if( rc==SQLITE_OK ){
101891    char zBuf[4096];
101892    exprToString(pExpr, zBuf);
101893    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
101894    sqlite3Fts3ExprFree(pExpr);
101895  }else{
101896    sqlite3_result_error(context, "Error parsing expression", -1);
101897  }
101898
101899exprtest_out:
101900  if( pModule && pTokenizer ){
101901    rc = pModule->xDestroy(pTokenizer);
101902  }
101903  sqlite3_free(azCol);
101904}
101905
101906/*
101907** Register the query expression parser test function fts3_exprtest()
101908** with database connection db.
101909*/
101910SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
101911  return sqlite3_create_function(
101912      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
101913  );
101914}
101915
101916#endif
101917#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
101918
101919/************** End of fts3_expr.c *******************************************/
101920/************** Begin file fts3_hash.c ***************************************/
101921/*
101922** 2001 September 22
101923**
101924** The author disclaims copyright to this source code.  In place of
101925** a legal notice, here is a blessing:
101926**
101927**    May you do good and not evil.
101928**    May you find forgiveness for yourself and forgive others.
101929**    May you share freely, never taking more than you give.
101930**
101931*************************************************************************
101932** This is the implementation of generic hash-tables used in SQLite.
101933** We've modified it slightly to serve as a standalone hash table
101934** implementation for the full-text indexing module.
101935*/
101936
101937/*
101938** The code in this file is only compiled if:
101939**
101940**     * The FTS3 module is being built as an extension
101941**       (in which case SQLITE_CORE is not defined), or
101942**
101943**     * The FTS3 module is being built into the core of
101944**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
101945*/
101946#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
101947
101948
101949
101950/*
101951** Malloc and Free functions
101952*/
101953static void *fts3HashMalloc(int n){
101954  void *p = sqlite3_malloc(n);
101955  if( p ){
101956    memset(p, 0, n);
101957  }
101958  return p;
101959}
101960static void fts3HashFree(void *p){
101961  sqlite3_free(p);
101962}
101963
101964/* Turn bulk memory into a hash table object by initializing the
101965** fields of the Hash structure.
101966**
101967** "pNew" is a pointer to the hash table that is to be initialized.
101968** keyClass is one of the constants
101969** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
101970** determines what kind of key the hash table will use.  "copyKey" is
101971** true if the hash table should make its own private copy of keys and
101972** false if it should just use the supplied pointer.
101973*/
101974SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
101975  assert( pNew!=0 );
101976  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
101977  pNew->keyClass = keyClass;
101978  pNew->copyKey = copyKey;
101979  pNew->first = 0;
101980  pNew->count = 0;
101981  pNew->htsize = 0;
101982  pNew->ht = 0;
101983}
101984
101985/* Remove all entries from a hash table.  Reclaim all memory.
101986** Call this routine to delete a hash table or to reset a hash table
101987** to the empty state.
101988*/
101989SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
101990  Fts3HashElem *elem;         /* For looping over all elements of the table */
101991
101992  assert( pH!=0 );
101993  elem = pH->first;
101994  pH->first = 0;
101995  fts3HashFree(pH->ht);
101996  pH->ht = 0;
101997  pH->htsize = 0;
101998  while( elem ){
101999    Fts3HashElem *next_elem = elem->next;
102000    if( pH->copyKey && elem->pKey ){
102001      fts3HashFree(elem->pKey);
102002    }
102003    fts3HashFree(elem);
102004    elem = next_elem;
102005  }
102006  pH->count = 0;
102007}
102008
102009/*
102010** Hash and comparison functions when the mode is FTS3_HASH_STRING
102011*/
102012static int fts3StrHash(const void *pKey, int nKey){
102013  const char *z = (const char *)pKey;
102014  int h = 0;
102015  if( nKey<=0 ) nKey = (int) strlen(z);
102016  while( nKey > 0  ){
102017    h = (h<<3) ^ h ^ *z++;
102018    nKey--;
102019  }
102020  return h & 0x7fffffff;
102021}
102022static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
102023  if( n1!=n2 ) return 1;
102024  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
102025}
102026
102027/*
102028** Hash and comparison functions when the mode is FTS3_HASH_BINARY
102029*/
102030static int fts3BinHash(const void *pKey, int nKey){
102031  int h = 0;
102032  const char *z = (const char *)pKey;
102033  while( nKey-- > 0 ){
102034    h = (h<<3) ^ h ^ *(z++);
102035  }
102036  return h & 0x7fffffff;
102037}
102038static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
102039  if( n1!=n2 ) return 1;
102040  return memcmp(pKey1,pKey2,n1);
102041}
102042
102043/*
102044** Return a pointer to the appropriate hash function given the key class.
102045**
102046** The C syntax in this function definition may be unfamilar to some
102047** programmers, so we provide the following additional explanation:
102048**
102049** The name of the function is "ftsHashFunction".  The function takes a
102050** single parameter "keyClass".  The return value of ftsHashFunction()
102051** is a pointer to another function.  Specifically, the return value
102052** of ftsHashFunction() is a pointer to a function that takes two parameters
102053** with types "const void*" and "int" and returns an "int".
102054*/
102055static int (*ftsHashFunction(int keyClass))(const void*,int){
102056  if( keyClass==FTS3_HASH_STRING ){
102057    return &fts3StrHash;
102058  }else{
102059    assert( keyClass==FTS3_HASH_BINARY );
102060    return &fts3BinHash;
102061  }
102062}
102063
102064/*
102065** Return a pointer to the appropriate hash function given the key class.
102066**
102067** For help in interpreted the obscure C code in the function definition,
102068** see the header comment on the previous function.
102069*/
102070static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
102071  if( keyClass==FTS3_HASH_STRING ){
102072    return &fts3StrCompare;
102073  }else{
102074    assert( keyClass==FTS3_HASH_BINARY );
102075    return &fts3BinCompare;
102076  }
102077}
102078
102079/* Link an element into the hash table
102080*/
102081static void fts3HashInsertElement(
102082  Fts3Hash *pH,            /* The complete hash table */
102083  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
102084  Fts3HashElem *pNew       /* The element to be inserted */
102085){
102086  Fts3HashElem *pHead;     /* First element already in pEntry */
102087  pHead = pEntry->chain;
102088  if( pHead ){
102089    pNew->next = pHead;
102090    pNew->prev = pHead->prev;
102091    if( pHead->prev ){ pHead->prev->next = pNew; }
102092    else             { pH->first = pNew; }
102093    pHead->prev = pNew;
102094  }else{
102095    pNew->next = pH->first;
102096    if( pH->first ){ pH->first->prev = pNew; }
102097    pNew->prev = 0;
102098    pH->first = pNew;
102099  }
102100  pEntry->count++;
102101  pEntry->chain = pNew;
102102}
102103
102104
102105/* Resize the hash table so that it cantains "new_size" buckets.
102106** "new_size" must be a power of 2.  The hash table might fail
102107** to resize if sqliteMalloc() fails.
102108**
102109** Return non-zero if a memory allocation error occurs.
102110*/
102111static int fts3Rehash(Fts3Hash *pH, int new_size){
102112  struct _fts3ht *new_ht;          /* The new hash table */
102113  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
102114  int (*xHash)(const void*,int);   /* The hash function */
102115
102116  assert( (new_size & (new_size-1))==0 );
102117  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
102118  if( new_ht==0 ) return 1;
102119  fts3HashFree(pH->ht);
102120  pH->ht = new_ht;
102121  pH->htsize = new_size;
102122  xHash = ftsHashFunction(pH->keyClass);
102123  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
102124    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
102125    next_elem = elem->next;
102126    fts3HashInsertElement(pH, &new_ht[h], elem);
102127  }
102128  return 0;
102129}
102130
102131/* This function (for internal use only) locates an element in an
102132** hash table that matches the given key.  The hash for this key has
102133** already been computed and is passed as the 4th parameter.
102134*/
102135static Fts3HashElem *fts3FindElementByHash(
102136  const Fts3Hash *pH, /* The pH to be searched */
102137  const void *pKey,   /* The key we are searching for */
102138  int nKey,
102139  int h               /* The hash for this key. */
102140){
102141  Fts3HashElem *elem;            /* Used to loop thru the element list */
102142  int count;                     /* Number of elements left to test */
102143  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
102144
102145  if( pH->ht ){
102146    struct _fts3ht *pEntry = &pH->ht[h];
102147    elem = pEntry->chain;
102148    count = pEntry->count;
102149    xCompare = ftsCompareFunction(pH->keyClass);
102150    while( count-- && elem ){
102151      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
102152        return elem;
102153      }
102154      elem = elem->next;
102155    }
102156  }
102157  return 0;
102158}
102159
102160/* Remove a single entry from the hash table given a pointer to that
102161** element and a hash on the element's key.
102162*/
102163static void fts3RemoveElementByHash(
102164  Fts3Hash *pH,         /* The pH containing "elem" */
102165  Fts3HashElem* elem,   /* The element to be removed from the pH */
102166  int h                 /* Hash value for the element */
102167){
102168  struct _fts3ht *pEntry;
102169  if( elem->prev ){
102170    elem->prev->next = elem->next;
102171  }else{
102172    pH->first = elem->next;
102173  }
102174  if( elem->next ){
102175    elem->next->prev = elem->prev;
102176  }
102177  pEntry = &pH->ht[h];
102178  if( pEntry->chain==elem ){
102179    pEntry->chain = elem->next;
102180  }
102181  pEntry->count--;
102182  if( pEntry->count<=0 ){
102183    pEntry->chain = 0;
102184  }
102185  if( pH->copyKey && elem->pKey ){
102186    fts3HashFree(elem->pKey);
102187  }
102188  fts3HashFree( elem );
102189  pH->count--;
102190  if( pH->count<=0 ){
102191    assert( pH->first==0 );
102192    assert( pH->count==0 );
102193    fts3HashClear(pH);
102194  }
102195}
102196
102197SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
102198  const Fts3Hash *pH,
102199  const void *pKey,
102200  int nKey
102201){
102202  int h;                          /* A hash on key */
102203  int (*xHash)(const void*,int);  /* The hash function */
102204
102205  if( pH==0 || pH->ht==0 ) return 0;
102206  xHash = ftsHashFunction(pH->keyClass);
102207  assert( xHash!=0 );
102208  h = (*xHash)(pKey,nKey);
102209  assert( (pH->htsize & (pH->htsize-1))==0 );
102210  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
102211}
102212
102213/*
102214** Attempt to locate an element of the hash table pH with a key
102215** that matches pKey,nKey.  Return the data for this element if it is
102216** found, or NULL if there is no match.
102217*/
102218SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
102219  Fts3HashElem *pElem;            /* The element that matches key (if any) */
102220
102221  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
102222  return pElem ? pElem->data : 0;
102223}
102224
102225/* Insert an element into the hash table pH.  The key is pKey,nKey
102226** and the data is "data".
102227**
102228** If no element exists with a matching key, then a new
102229** element is created.  A copy of the key is made if the copyKey
102230** flag is set.  NULL is returned.
102231**
102232** If another element already exists with the same key, then the
102233** new data replaces the old data and the old data is returned.
102234** The key is not copied in this instance.  If a malloc fails, then
102235** the new data is returned and the hash table is unchanged.
102236**
102237** If the "data" parameter to this function is NULL, then the
102238** element corresponding to "key" is removed from the hash table.
102239*/
102240SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
102241  Fts3Hash *pH,        /* The hash table to insert into */
102242  const void *pKey,    /* The key */
102243  int nKey,            /* Number of bytes in the key */
102244  void *data           /* The data */
102245){
102246  int hraw;                 /* Raw hash value of the key */
102247  int h;                    /* the hash of the key modulo hash table size */
102248  Fts3HashElem *elem;       /* Used to loop thru the element list */
102249  Fts3HashElem *new_elem;   /* New element added to the pH */
102250  int (*xHash)(const void*,int);  /* The hash function */
102251
102252  assert( pH!=0 );
102253  xHash = ftsHashFunction(pH->keyClass);
102254  assert( xHash!=0 );
102255  hraw = (*xHash)(pKey, nKey);
102256  assert( (pH->htsize & (pH->htsize-1))==0 );
102257  h = hraw & (pH->htsize-1);
102258  elem = fts3FindElementByHash(pH,pKey,nKey,h);
102259  if( elem ){
102260    void *old_data = elem->data;
102261    if( data==0 ){
102262      fts3RemoveElementByHash(pH,elem,h);
102263    }else{
102264      elem->data = data;
102265    }
102266    return old_data;
102267  }
102268  if( data==0 ) return 0;
102269  if( (pH->htsize==0 && fts3Rehash(pH,8))
102270   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
102271  ){
102272    pH->count = 0;
102273    return data;
102274  }
102275  assert( pH->htsize>0 );
102276  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
102277  if( new_elem==0 ) return data;
102278  if( pH->copyKey && pKey!=0 ){
102279    new_elem->pKey = fts3HashMalloc( nKey );
102280    if( new_elem->pKey==0 ){
102281      fts3HashFree(new_elem);
102282      return data;
102283    }
102284    memcpy((void*)new_elem->pKey, pKey, nKey);
102285  }else{
102286    new_elem->pKey = (void*)pKey;
102287  }
102288  new_elem->nKey = nKey;
102289  pH->count++;
102290  assert( pH->htsize>0 );
102291  assert( (pH->htsize & (pH->htsize-1))==0 );
102292  h = hraw & (pH->htsize-1);
102293  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
102294  new_elem->data = data;
102295  return 0;
102296}
102297
102298#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
102299
102300/************** End of fts3_hash.c *******************************************/
102301/************** Begin file fts3_porter.c *************************************/
102302/*
102303** 2006 September 30
102304**
102305** The author disclaims copyright to this source code.  In place of
102306** a legal notice, here is a blessing:
102307**
102308**    May you do good and not evil.
102309**    May you find forgiveness for yourself and forgive others.
102310**    May you share freely, never taking more than you give.
102311**
102312*************************************************************************
102313** Implementation of the full-text-search tokenizer that implements
102314** a Porter stemmer.
102315*/
102316
102317/*
102318** The code in this file is only compiled if:
102319**
102320**     * The FTS3 module is being built as an extension
102321**       (in which case SQLITE_CORE is not defined), or
102322**
102323**     * The FTS3 module is being built into the core of
102324**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
102325*/
102326#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
102327
102328
102329
102330
102331/*
102332** Class derived from sqlite3_tokenizer
102333*/
102334typedef struct porter_tokenizer {
102335  sqlite3_tokenizer base;      /* Base class */
102336} porter_tokenizer;
102337
102338/*
102339** Class derived from sqlit3_tokenizer_cursor
102340*/
102341typedef struct porter_tokenizer_cursor {
102342  sqlite3_tokenizer_cursor base;
102343  const char *zInput;          /* input we are tokenizing */
102344  int nInput;                  /* size of the input */
102345  int iOffset;                 /* current position in zInput */
102346  int iToken;                  /* index of next token to be returned */
102347  char *zToken;                /* storage for current token */
102348  int nAllocated;              /* space allocated to zToken buffer */
102349} porter_tokenizer_cursor;
102350
102351
102352/*
102353** Create a new tokenizer instance.
102354*/
102355static int porterCreate(
102356  int argc, const char * const *argv,
102357  sqlite3_tokenizer **ppTokenizer
102358){
102359  porter_tokenizer *t;
102360
102361  UNUSED_PARAMETER(argc);
102362  UNUSED_PARAMETER(argv);
102363
102364  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
102365  if( t==NULL ) return SQLITE_NOMEM;
102366  memset(t, 0, sizeof(*t));
102367  *ppTokenizer = &t->base;
102368  return SQLITE_OK;
102369}
102370
102371/*
102372** Destroy a tokenizer
102373*/
102374static int porterDestroy(sqlite3_tokenizer *pTokenizer){
102375  sqlite3_free(pTokenizer);
102376  return SQLITE_OK;
102377}
102378
102379/*
102380** Prepare to begin tokenizing a particular string.  The input
102381** string to be tokenized is zInput[0..nInput-1].  A cursor
102382** used to incrementally tokenize this string is returned in
102383** *ppCursor.
102384*/
102385static int porterOpen(
102386  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
102387  const char *zInput, int nInput,        /* String to be tokenized */
102388  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
102389){
102390  porter_tokenizer_cursor *c;
102391
102392  UNUSED_PARAMETER(pTokenizer);
102393
102394  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
102395  if( c==NULL ) return SQLITE_NOMEM;
102396
102397  c->zInput = zInput;
102398  if( zInput==0 ){
102399    c->nInput = 0;
102400  }else if( nInput<0 ){
102401    c->nInput = (int)strlen(zInput);
102402  }else{
102403    c->nInput = nInput;
102404  }
102405  c->iOffset = 0;                 /* start tokenizing at the beginning */
102406  c->iToken = 0;
102407  c->zToken = NULL;               /* no space allocated, yet. */
102408  c->nAllocated = 0;
102409
102410  *ppCursor = &c->base;
102411  return SQLITE_OK;
102412}
102413
102414/*
102415** Close a tokenization cursor previously opened by a call to
102416** porterOpen() above.
102417*/
102418static int porterClose(sqlite3_tokenizer_cursor *pCursor){
102419  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
102420  sqlite3_free(c->zToken);
102421  sqlite3_free(c);
102422  return SQLITE_OK;
102423}
102424/*
102425** Vowel or consonant
102426*/
102427static const char cType[] = {
102428   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
102429   1, 1, 1, 2, 1
102430};
102431
102432/*
102433** isConsonant() and isVowel() determine if their first character in
102434** the string they point to is a consonant or a vowel, according
102435** to Porter ruls.
102436**
102437** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
102438** 'Y' is a consonant unless it follows another consonant,
102439** in which case it is a vowel.
102440**
102441** In these routine, the letters are in reverse order.  So the 'y' rule
102442** is that 'y' is a consonant unless it is followed by another
102443** consonent.
102444*/
102445static int isVowel(const char*);
102446static int isConsonant(const char *z){
102447  int j;
102448  char x = *z;
102449  if( x==0 ) return 0;
102450  assert( x>='a' && x<='z' );
102451  j = cType[x-'a'];
102452  if( j<2 ) return j;
102453  return z[1]==0 || isVowel(z + 1);
102454}
102455static int isVowel(const char *z){
102456  int j;
102457  char x = *z;
102458  if( x==0 ) return 0;
102459  assert( x>='a' && x<='z' );
102460  j = cType[x-'a'];
102461  if( j<2 ) return 1-j;
102462  return isConsonant(z + 1);
102463}
102464
102465/*
102466** Let any sequence of one or more vowels be represented by V and let
102467** C be sequence of one or more consonants.  Then every word can be
102468** represented as:
102469**
102470**           [C] (VC){m} [V]
102471**
102472** In prose:  A word is an optional consonant followed by zero or
102473** vowel-consonant pairs followed by an optional vowel.  "m" is the
102474** number of vowel consonant pairs.  This routine computes the value
102475** of m for the first i bytes of a word.
102476**
102477** Return true if the m-value for z is 1 or more.  In other words,
102478** return true if z contains at least one vowel that is followed
102479** by a consonant.
102480**
102481** In this routine z[] is in reverse order.  So we are really looking
102482** for an instance of of a consonant followed by a vowel.
102483*/
102484static int m_gt_0(const char *z){
102485  while( isVowel(z) ){ z++; }
102486  if( *z==0 ) return 0;
102487  while( isConsonant(z) ){ z++; }
102488  return *z!=0;
102489}
102490
102491/* Like mgt0 above except we are looking for a value of m which is
102492** exactly 1
102493*/
102494static int m_eq_1(const char *z){
102495  while( isVowel(z) ){ z++; }
102496  if( *z==0 ) return 0;
102497  while( isConsonant(z) ){ z++; }
102498  if( *z==0 ) return 0;
102499  while( isVowel(z) ){ z++; }
102500  if( *z==0 ) return 1;
102501  while( isConsonant(z) ){ z++; }
102502  return *z==0;
102503}
102504
102505/* Like mgt0 above except we are looking for a value of m>1 instead
102506** or m>0
102507*/
102508static int m_gt_1(const char *z){
102509  while( isVowel(z) ){ z++; }
102510  if( *z==0 ) return 0;
102511  while( isConsonant(z) ){ z++; }
102512  if( *z==0 ) return 0;
102513  while( isVowel(z) ){ z++; }
102514  if( *z==0 ) return 0;
102515  while( isConsonant(z) ){ z++; }
102516  return *z!=0;
102517}
102518
102519/*
102520** Return TRUE if there is a vowel anywhere within z[0..n-1]
102521*/
102522static int hasVowel(const char *z){
102523  while( isConsonant(z) ){ z++; }
102524  return *z!=0;
102525}
102526
102527/*
102528** Return TRUE if the word ends in a double consonant.
102529**
102530** The text is reversed here. So we are really looking at
102531** the first two characters of z[].
102532*/
102533static int doubleConsonant(const char *z){
102534  return isConsonant(z) && z[0]==z[1];
102535}
102536
102537/*
102538** Return TRUE if the word ends with three letters which
102539** are consonant-vowel-consonent and where the final consonant
102540** is not 'w', 'x', or 'y'.
102541**
102542** The word is reversed here.  So we are really checking the
102543** first three letters and the first one cannot be in [wxy].
102544*/
102545static int star_oh(const char *z){
102546  return
102547    isConsonant(z) &&
102548    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
102549    isVowel(z+1) &&
102550    isConsonant(z+2);
102551}
102552
102553/*
102554** If the word ends with zFrom and xCond() is true for the stem
102555** of the word that preceeds the zFrom ending, then change the
102556** ending to zTo.
102557**
102558** The input word *pz and zFrom are both in reverse order.  zTo
102559** is in normal order.
102560**
102561** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
102562** match.  Not that TRUE is returned even if xCond() fails and
102563** no substitution occurs.
102564*/
102565static int stem(
102566  char **pz,             /* The word being stemmed (Reversed) */
102567  const char *zFrom,     /* If the ending matches this... (Reversed) */
102568  const char *zTo,       /* ... change the ending to this (not reversed) */
102569  int (*xCond)(const char*)   /* Condition that must be true */
102570){
102571  char *z = *pz;
102572  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
102573  if( *zFrom!=0 ) return 0;
102574  if( xCond && !xCond(z) ) return 1;
102575  while( *zTo ){
102576    *(--z) = *(zTo++);
102577  }
102578  *pz = z;
102579  return 1;
102580}
102581
102582/*
102583** This is the fallback stemmer used when the porter stemmer is
102584** inappropriate.  The input word is copied into the output with
102585** US-ASCII case folding.  If the input word is too long (more
102586** than 20 bytes if it contains no digits or more than 6 bytes if
102587** it contains digits) then word is truncated to 20 or 6 bytes
102588** by taking 10 or 3 bytes from the beginning and end.
102589*/
102590static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
102591  int i, mx, j;
102592  int hasDigit = 0;
102593  for(i=0; i<nIn; i++){
102594    char c = zIn[i];
102595    if( c>='A' && c<='Z' ){
102596      zOut[i] = c - 'A' + 'a';
102597    }else{
102598      if( c>='0' && c<='9' ) hasDigit = 1;
102599      zOut[i] = c;
102600    }
102601  }
102602  mx = hasDigit ? 3 : 10;
102603  if( nIn>mx*2 ){
102604    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
102605      zOut[j] = zOut[i];
102606    }
102607    i = j;
102608  }
102609  zOut[i] = 0;
102610  *pnOut = i;
102611}
102612
102613
102614/*
102615** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
102616** zOut is at least big enough to hold nIn bytes.  Write the actual
102617** size of the output word (exclusive of the '\0' terminator) into *pnOut.
102618**
102619** Any upper-case characters in the US-ASCII character set ([A-Z])
102620** are converted to lower case.  Upper-case UTF characters are
102621** unchanged.
102622**
102623** Words that are longer than about 20 bytes are stemmed by retaining
102624** a few bytes from the beginning and the end of the word.  If the
102625** word contains digits, 3 bytes are taken from the beginning and
102626** 3 bytes from the end.  For long words without digits, 10 bytes
102627** are taken from each end.  US-ASCII case folding still applies.
102628**
102629** If the input word contains not digits but does characters not
102630** in [a-zA-Z] then no stemming is attempted and this routine just
102631** copies the input into the input into the output with US-ASCII
102632** case folding.
102633**
102634** Stemming never increases the length of the word.  So there is
102635** no chance of overflowing the zOut buffer.
102636*/
102637static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
102638  int i, j;
102639  char zReverse[28];
102640  char *z, *z2;
102641  if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
102642    /* The word is too big or too small for the porter stemmer.
102643    ** Fallback to the copy stemmer */
102644    copy_stemmer(zIn, nIn, zOut, pnOut);
102645    return;
102646  }
102647  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
102648    char c = zIn[i];
102649    if( c>='A' && c<='Z' ){
102650      zReverse[j] = c + 'a' - 'A';
102651    }else if( c>='a' && c<='z' ){
102652      zReverse[j] = c;
102653    }else{
102654      /* The use of a character not in [a-zA-Z] means that we fallback
102655      ** to the copy stemmer */
102656      copy_stemmer(zIn, nIn, zOut, pnOut);
102657      return;
102658    }
102659  }
102660  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
102661  z = &zReverse[j+1];
102662
102663
102664  /* Step 1a */
102665  if( z[0]=='s' ){
102666    if(
102667     !stem(&z, "sess", "ss", 0) &&
102668     !stem(&z, "sei", "i", 0)  &&
102669     !stem(&z, "ss", "ss", 0)
102670    ){
102671      z++;
102672    }
102673  }
102674
102675  /* Step 1b */
102676  z2 = z;
102677  if( stem(&z, "dee", "ee", m_gt_0) ){
102678    /* Do nothing.  The work was all in the test */
102679  }else if(
102680     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
102681      && z!=z2
102682  ){
102683     if( stem(&z, "ta", "ate", 0) ||
102684         stem(&z, "lb", "ble", 0) ||
102685         stem(&z, "zi", "ize", 0) ){
102686       /* Do nothing.  The work was all in the test */
102687     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
102688       z++;
102689     }else if( m_eq_1(z) && star_oh(z) ){
102690       *(--z) = 'e';
102691     }
102692  }
102693
102694  /* Step 1c */
102695  if( z[0]=='y' && hasVowel(z+1) ){
102696    z[0] = 'i';
102697  }
102698
102699  /* Step 2 */
102700  switch( z[1] ){
102701   case 'a':
102702     stem(&z, "lanoita", "ate", m_gt_0) ||
102703     stem(&z, "lanoit", "tion", m_gt_0);
102704     break;
102705   case 'c':
102706     stem(&z, "icne", "ence", m_gt_0) ||
102707     stem(&z, "icna", "ance", m_gt_0);
102708     break;
102709   case 'e':
102710     stem(&z, "rezi", "ize", m_gt_0);
102711     break;
102712   case 'g':
102713     stem(&z, "igol", "log", m_gt_0);
102714     break;
102715   case 'l':
102716     stem(&z, "ilb", "ble", m_gt_0) ||
102717     stem(&z, "illa", "al", m_gt_0) ||
102718     stem(&z, "iltne", "ent", m_gt_0) ||
102719     stem(&z, "ile", "e", m_gt_0) ||
102720     stem(&z, "ilsuo", "ous", m_gt_0);
102721     break;
102722   case 'o':
102723     stem(&z, "noitazi", "ize", m_gt_0) ||
102724     stem(&z, "noita", "ate", m_gt_0) ||
102725     stem(&z, "rota", "ate", m_gt_0);
102726     break;
102727   case 's':
102728     stem(&z, "msila", "al", m_gt_0) ||
102729     stem(&z, "ssenevi", "ive", m_gt_0) ||
102730     stem(&z, "ssenluf", "ful", m_gt_0) ||
102731     stem(&z, "ssensuo", "ous", m_gt_0);
102732     break;
102733   case 't':
102734     stem(&z, "itila", "al", m_gt_0) ||
102735     stem(&z, "itivi", "ive", m_gt_0) ||
102736     stem(&z, "itilib", "ble", m_gt_0);
102737     break;
102738  }
102739
102740  /* Step 3 */
102741  switch( z[0] ){
102742   case 'e':
102743     stem(&z, "etaci", "ic", m_gt_0) ||
102744     stem(&z, "evita", "", m_gt_0)   ||
102745     stem(&z, "ezila", "al", m_gt_0);
102746     break;
102747   case 'i':
102748     stem(&z, "itici", "ic", m_gt_0);
102749     break;
102750   case 'l':
102751     stem(&z, "laci", "ic", m_gt_0) ||
102752     stem(&z, "luf", "", m_gt_0);
102753     break;
102754   case 's':
102755     stem(&z, "ssen", "", m_gt_0);
102756     break;
102757  }
102758
102759  /* Step 4 */
102760  switch( z[1] ){
102761   case 'a':
102762     if( z[0]=='l' && m_gt_1(z+2) ){
102763       z += 2;
102764     }
102765     break;
102766   case 'c':
102767     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
102768       z += 4;
102769     }
102770     break;
102771   case 'e':
102772     if( z[0]=='r' && m_gt_1(z+2) ){
102773       z += 2;
102774     }
102775     break;
102776   case 'i':
102777     if( z[0]=='c' && m_gt_1(z+2) ){
102778       z += 2;
102779     }
102780     break;
102781   case 'l':
102782     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
102783       z += 4;
102784     }
102785     break;
102786   case 'n':
102787     if( z[0]=='t' ){
102788       if( z[2]=='a' ){
102789         if( m_gt_1(z+3) ){
102790           z += 3;
102791         }
102792       }else if( z[2]=='e' ){
102793         stem(&z, "tneme", "", m_gt_1) ||
102794         stem(&z, "tnem", "", m_gt_1) ||
102795         stem(&z, "tne", "", m_gt_1);
102796       }
102797     }
102798     break;
102799   case 'o':
102800     if( z[0]=='u' ){
102801       if( m_gt_1(z+2) ){
102802         z += 2;
102803       }
102804     }else if( z[3]=='s' || z[3]=='t' ){
102805       stem(&z, "noi", "", m_gt_1);
102806     }
102807     break;
102808   case 's':
102809     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
102810       z += 3;
102811     }
102812     break;
102813   case 't':
102814     stem(&z, "eta", "", m_gt_1) ||
102815     stem(&z, "iti", "", m_gt_1);
102816     break;
102817   case 'u':
102818     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
102819       z += 3;
102820     }
102821     break;
102822   case 'v':
102823   case 'z':
102824     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
102825       z += 3;
102826     }
102827     break;
102828  }
102829
102830  /* Step 5a */
102831  if( z[0]=='e' ){
102832    if( m_gt_1(z+1) ){
102833      z++;
102834    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
102835      z++;
102836    }
102837  }
102838
102839  /* Step 5b */
102840  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
102841    z++;
102842  }
102843
102844  /* z[] is now the stemmed word in reverse order.  Flip it back
102845  ** around into forward order and return.
102846  */
102847  *pnOut = i = (int)strlen(z);
102848  zOut[i] = 0;
102849  while( *z ){
102850    zOut[--i] = *(z++);
102851  }
102852}
102853
102854/*
102855** Characters that can be part of a token.  We assume any character
102856** whose value is greater than 0x80 (any UTF character) can be
102857** part of a token.  In other words, delimiters all must have
102858** values of 0x7f or lower.
102859*/
102860static const char porterIdChar[] = {
102861/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
102862    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
102863    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
102864    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
102865    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
102866    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
102867};
102868#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
102869
102870/*
102871** Extract the next token from a tokenization cursor.  The cursor must
102872** have been opened by a prior call to porterOpen().
102873*/
102874static int porterNext(
102875  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
102876  const char **pzToken,               /* OUT: *pzToken is the token text */
102877  int *pnBytes,                       /* OUT: Number of bytes in token */
102878  int *piStartOffset,                 /* OUT: Starting offset of token */
102879  int *piEndOffset,                   /* OUT: Ending offset of token */
102880  int *piPosition                     /* OUT: Position integer of token */
102881){
102882  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
102883  const char *z = c->zInput;
102884
102885  while( c->iOffset<c->nInput ){
102886    int iStartOffset, ch;
102887
102888    /* Scan past delimiter characters */
102889    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
102890      c->iOffset++;
102891    }
102892
102893    /* Count non-delimiter characters. */
102894    iStartOffset = c->iOffset;
102895    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
102896      c->iOffset++;
102897    }
102898
102899    if( c->iOffset>iStartOffset ){
102900      int n = c->iOffset-iStartOffset;
102901      if( n>c->nAllocated ){
102902        c->nAllocated = n+20;
102903        c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
102904        if( c->zToken==NULL ) return SQLITE_NOMEM;
102905      }
102906      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
102907      *pzToken = c->zToken;
102908      *piStartOffset = iStartOffset;
102909      *piEndOffset = c->iOffset;
102910      *piPosition = c->iToken++;
102911      return SQLITE_OK;
102912    }
102913  }
102914  return SQLITE_DONE;
102915}
102916
102917/*
102918** The set of routines that implement the porter-stemmer tokenizer
102919*/
102920static const sqlite3_tokenizer_module porterTokenizerModule = {
102921  0,
102922  porterCreate,
102923  porterDestroy,
102924  porterOpen,
102925  porterClose,
102926  porterNext,
102927};
102928
102929/*
102930** Allocate a new porter tokenizer.  Return a pointer to the new
102931** tokenizer in *ppModule
102932*/
102933SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
102934  sqlite3_tokenizer_module const**ppModule
102935){
102936  *ppModule = &porterTokenizerModule;
102937}
102938
102939#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
102940
102941/************** End of fts3_porter.c *****************************************/
102942/************** Begin file fts3_tokenizer.c **********************************/
102943/*
102944** 2007 June 22
102945**
102946** The author disclaims copyright to this source code.  In place of
102947** a legal notice, here is a blessing:
102948**
102949**    May you do good and not evil.
102950**    May you find forgiveness for yourself and forgive others.
102951**    May you share freely, never taking more than you give.
102952**
102953******************************************************************************
102954**
102955** This is part of an SQLite module implementing full-text search.
102956** This particular file implements the generic tokenizer interface.
102957*/
102958
102959/*
102960** The code in this file is only compiled if:
102961**
102962**     * The FTS3 module is being built as an extension
102963**       (in which case SQLITE_CORE is not defined), or
102964**
102965**     * The FTS3 module is being built into the core of
102966**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
102967*/
102968#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
102969
102970#ifndef SQLITE_CORE
102971  SQLITE_EXTENSION_INIT1
102972#endif
102973
102974
102975/*
102976** Implementation of the SQL scalar function for accessing the underlying
102977** hash table. This function may be called as follows:
102978**
102979**   SELECT <function-name>(<key-name>);
102980**   SELECT <function-name>(<key-name>, <pointer>);
102981**
102982** where <function-name> is the name passed as the second argument
102983** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
102984**
102985** If the <pointer> argument is specified, it must be a blob value
102986** containing a pointer to be stored as the hash data corresponding
102987** to the string <key-name>. If <pointer> is not specified, then
102988** the string <key-name> must already exist in the has table. Otherwise,
102989** an error is returned.
102990**
102991** Whether or not the <pointer> argument is specified, the value returned
102992** is a blob containing the pointer stored as the hash data corresponding
102993** to string <key-name> (after the hash-table is updated, if applicable).
102994*/
102995static void scalarFunc(
102996  sqlite3_context *context,
102997  int argc,
102998  sqlite3_value **argv
102999){
103000  Fts3Hash *pHash;
103001  void *pPtr = 0;
103002  const unsigned char *zName;
103003  int nName;
103004
103005  assert( argc==1 || argc==2 );
103006
103007  pHash = (Fts3Hash *)sqlite3_user_data(context);
103008
103009  zName = sqlite3_value_text(argv[0]);
103010  nName = sqlite3_value_bytes(argv[0])+1;
103011
103012  if( argc==2 ){
103013    void *pOld;
103014    int n = sqlite3_value_bytes(argv[1]);
103015    if( n!=sizeof(pPtr) ){
103016      sqlite3_result_error(context, "argument type mismatch", -1);
103017      return;
103018    }
103019    pPtr = *(void **)sqlite3_value_blob(argv[1]);
103020    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
103021    if( pOld==pPtr ){
103022      sqlite3_result_error(context, "out of memory", -1);
103023      return;
103024    }
103025  }else{
103026    pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
103027    if( !pPtr ){
103028      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
103029      sqlite3_result_error(context, zErr, -1);
103030      sqlite3_free(zErr);
103031      return;
103032    }
103033  }
103034
103035  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
103036}
103037
103038static int fts3IsIdChar(char c){
103039  static const char isFtsIdChar[] = {
103040      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
103041      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
103042      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
103043      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
103044      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
103045      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
103046      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
103047      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
103048  };
103049  return (c&0x80 || isFtsIdChar[(int)(c)]);
103050}
103051
103052SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
103053  const char *z1;
103054  const char *z2 = 0;
103055
103056  /* Find the start of the next token. */
103057  z1 = zStr;
103058  while( z2==0 ){
103059    char c = *z1;
103060    switch( c ){
103061      case '\0': return 0;        /* No more tokens here */
103062      case '\'':
103063      case '"':
103064      case '`': {
103065        z2 = z1;
103066        while( *++z2 && (*z2!=c || *++z2==c) );
103067        break;
103068      }
103069      case '[':
103070        z2 = &z1[1];
103071        while( *z2 && z2[0]!=']' ) z2++;
103072        if( *z2 ) z2++;
103073        break;
103074
103075      default:
103076        if( fts3IsIdChar(*z1) ){
103077          z2 = &z1[1];
103078          while( fts3IsIdChar(*z2) ) z2++;
103079        }else{
103080          z1++;
103081        }
103082    }
103083  }
103084
103085  *pn = (int)(z2-z1);
103086  return z1;
103087}
103088
103089SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
103090  Fts3Hash *pHash,                /* Tokenizer hash table */
103091  const char *zArg,               /* Possible tokenizer specification */
103092  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
103093  const char **pzTokenizer,       /* OUT: Set to zArg if is tokenizer */
103094  char **pzErr                    /* OUT: Set to malloced error message */
103095){
103096  int rc;
103097  char *z = (char *)zArg;
103098  int n;
103099  char *zCopy;
103100  char *zEnd;                     /* Pointer to nul-term of zCopy */
103101  sqlite3_tokenizer_module *m;
103102
103103  if( !z ){
103104    zCopy = sqlite3_mprintf("simple");
103105  }else{
103106    if( sqlite3_strnicmp(z, "tokenize", 8) || fts3IsIdChar(z[8])){
103107      return SQLITE_OK;
103108    }
103109    zCopy = sqlite3_mprintf("%s", &z[8]);
103110    *pzTokenizer = zArg;
103111  }
103112  if( !zCopy ){
103113    return SQLITE_NOMEM;
103114  }
103115
103116  zEnd = &zCopy[strlen(zCopy)];
103117
103118  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
103119  z[n] = '\0';
103120  sqlite3Fts3Dequote(z);
103121
103122  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, z, (int)strlen(z)+1);
103123  if( !m ){
103124    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
103125    rc = SQLITE_ERROR;
103126  }else{
103127    char const **aArg = 0;
103128    int iArg = 0;
103129    z = &z[n+1];
103130    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
103131      int nNew = sizeof(char *)*(iArg+1);
103132      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
103133      if( !aNew ){
103134        sqlite3_free(zCopy);
103135        sqlite3_free((void *)aArg);
103136        return SQLITE_NOMEM;
103137      }
103138      aArg = aNew;
103139      aArg[iArg++] = z;
103140      z[n] = '\0';
103141      sqlite3Fts3Dequote(z);
103142      z = &z[n+1];
103143    }
103144    rc = m->xCreate(iArg, aArg, ppTok);
103145    assert( rc!=SQLITE_OK || *ppTok );
103146    if( rc!=SQLITE_OK ){
103147      *pzErr = sqlite3_mprintf("unknown tokenizer");
103148    }else{
103149      (*ppTok)->pModule = m;
103150    }
103151    sqlite3_free((void *)aArg);
103152  }
103153
103154  sqlite3_free(zCopy);
103155  return rc;
103156}
103157
103158
103159#ifdef SQLITE_TEST
103160
103161
103162/*
103163** Implementation of a special SQL scalar function for testing tokenizers
103164** designed to be used in concert with the Tcl testing framework. This
103165** function must be called with two arguments:
103166**
103167**   SELECT <function-name>(<key-name>, <input-string>);
103168**   SELECT <function-name>(<key-name>, <pointer>);
103169**
103170** where <function-name> is the name passed as the second argument
103171** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
103172** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
103173**
103174** The return value is a string that may be interpreted as a Tcl
103175** list. For each token in the <input-string>, three elements are
103176** added to the returned list. The first is the token position, the
103177** second is the token text (folded, stemmed, etc.) and the third is the
103178** substring of <input-string> associated with the token. For example,
103179** using the built-in "simple" tokenizer:
103180**
103181**   SELECT fts_tokenizer_test('simple', 'I don't see how');
103182**
103183** will return the string:
103184**
103185**   "{0 i I 1 dont don't 2 see see 3 how how}"
103186**
103187*/
103188static void testFunc(
103189  sqlite3_context *context,
103190  int argc,
103191  sqlite3_value **argv
103192){
103193  Fts3Hash *pHash;
103194  sqlite3_tokenizer_module *p;
103195  sqlite3_tokenizer *pTokenizer = 0;
103196  sqlite3_tokenizer_cursor *pCsr = 0;
103197
103198  const char *zErr = 0;
103199
103200  const char *zName;
103201  int nName;
103202  const char *zInput;
103203  int nInput;
103204
103205  const char *zArg = 0;
103206
103207  const char *zToken;
103208  int nToken;
103209  int iStart;
103210  int iEnd;
103211  int iPos;
103212
103213  Tcl_Obj *pRet;
103214
103215  assert( argc==2 || argc==3 );
103216
103217  nName = sqlite3_value_bytes(argv[0]);
103218  zName = (const char *)sqlite3_value_text(argv[0]);
103219  nInput = sqlite3_value_bytes(argv[argc-1]);
103220  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
103221
103222  if( argc==3 ){
103223    zArg = (const char *)sqlite3_value_text(argv[1]);
103224  }
103225
103226  pHash = (Fts3Hash *)sqlite3_user_data(context);
103227  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
103228
103229  if( !p ){
103230    char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
103231    sqlite3_result_error(context, zErr, -1);
103232    sqlite3_free(zErr);
103233    return;
103234  }
103235
103236  pRet = Tcl_NewObj();
103237  Tcl_IncrRefCount(pRet);
103238
103239  if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
103240    zErr = "error in xCreate()";
103241    goto finish;
103242  }
103243  pTokenizer->pModule = p;
103244  if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
103245    zErr = "error in xOpen()";
103246    goto finish;
103247  }
103248  pCsr->pTokenizer = pTokenizer;
103249
103250  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
103251    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
103252    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
103253    zToken = &zInput[iStart];
103254    nToken = iEnd-iStart;
103255    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
103256  }
103257
103258  if( SQLITE_OK!=p->xClose(pCsr) ){
103259    zErr = "error in xClose()";
103260    goto finish;
103261  }
103262  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
103263    zErr = "error in xDestroy()";
103264    goto finish;
103265  }
103266
103267finish:
103268  if( zErr ){
103269    sqlite3_result_error(context, zErr, -1);
103270  }else{
103271    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
103272  }
103273  Tcl_DecrRefCount(pRet);
103274}
103275
103276static
103277int registerTokenizer(
103278  sqlite3 *db,
103279  char *zName,
103280  const sqlite3_tokenizer_module *p
103281){
103282  int rc;
103283  sqlite3_stmt *pStmt;
103284  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
103285
103286  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
103287  if( rc!=SQLITE_OK ){
103288    return rc;
103289  }
103290
103291  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
103292  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
103293  sqlite3_step(pStmt);
103294
103295  return sqlite3_finalize(pStmt);
103296}
103297
103298static
103299int queryTokenizer(
103300  sqlite3 *db,
103301  char *zName,
103302  const sqlite3_tokenizer_module **pp
103303){
103304  int rc;
103305  sqlite3_stmt *pStmt;
103306  const char zSql[] = "SELECT fts3_tokenizer(?)";
103307
103308  *pp = 0;
103309  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
103310  if( rc!=SQLITE_OK ){
103311    return rc;
103312  }
103313
103314  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
103315  if( SQLITE_ROW==sqlite3_step(pStmt) ){
103316    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
103317      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
103318    }
103319  }
103320
103321  return sqlite3_finalize(pStmt);
103322}
103323
103324SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
103325
103326/*
103327** Implementation of the scalar function fts3_tokenizer_internal_test().
103328** This function is used for testing only, it is not included in the
103329** build unless SQLITE_TEST is defined.
103330**
103331** The purpose of this is to test that the fts3_tokenizer() function
103332** can be used as designed by the C-code in the queryTokenizer and
103333** registerTokenizer() functions above. These two functions are repeated
103334** in the README.tokenizer file as an example, so it is important to
103335** test them.
103336**
103337** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
103338** function with no arguments. An assert() will fail if a problem is
103339** detected. i.e.:
103340**
103341**     SELECT fts3_tokenizer_internal_test();
103342**
103343*/
103344static void intTestFunc(
103345  sqlite3_context *context,
103346  int argc,
103347  sqlite3_value **argv
103348){
103349  int rc;
103350  const sqlite3_tokenizer_module *p1;
103351  const sqlite3_tokenizer_module *p2;
103352  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
103353
103354  UNUSED_PARAMETER(argc);
103355  UNUSED_PARAMETER(argv);
103356
103357  /* Test the query function */
103358  sqlite3Fts3SimpleTokenizerModule(&p1);
103359  rc = queryTokenizer(db, "simple", &p2);
103360  assert( rc==SQLITE_OK );
103361  assert( p1==p2 );
103362  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
103363  assert( rc==SQLITE_ERROR );
103364  assert( p2==0 );
103365  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
103366
103367  /* Test the storage function */
103368  rc = registerTokenizer(db, "nosuchtokenizer", p1);
103369  assert( rc==SQLITE_OK );
103370  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
103371  assert( rc==SQLITE_OK );
103372  assert( p2==p1 );
103373
103374  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
103375}
103376
103377#endif
103378
103379/*
103380** Set up SQL objects in database db used to access the contents of
103381** the hash table pointed to by argument pHash. The hash table must
103382** been initialised to use string keys, and to take a private copy
103383** of the key when a value is inserted. i.e. by a call similar to:
103384**
103385**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
103386**
103387** This function adds a scalar function (see header comment above
103388** scalarFunc() in this file for details) and, if ENABLE_TABLE is
103389** defined at compilation time, a temporary virtual table (see header
103390** comment above struct HashTableVtab) to the database schema. Both
103391** provide read/write access to the contents of *pHash.
103392**
103393** The third argument to this function, zName, is used as the name
103394** of both the scalar and, if created, the virtual table.
103395*/
103396SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
103397  sqlite3 *db,
103398  Fts3Hash *pHash,
103399  const char *zName
103400){
103401  int rc = SQLITE_OK;
103402  void *p = (void *)pHash;
103403  const int any = SQLITE_ANY;
103404
103405#ifdef SQLITE_TEST
103406  char *zTest = 0;
103407  char *zTest2 = 0;
103408  void *pdb = (void *)db;
103409  zTest = sqlite3_mprintf("%s_test", zName);
103410  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
103411  if( !zTest || !zTest2 ){
103412    rc = SQLITE_NOMEM;
103413  }
103414#endif
103415
103416  if( SQLITE_OK!=rc
103417   || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
103418   || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
103419#ifdef SQLITE_TEST
103420   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
103421   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
103422   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
103423#endif
103424   );
103425
103426#ifdef SQLITE_TEST
103427  sqlite3_free(zTest);
103428  sqlite3_free(zTest2);
103429#endif
103430
103431  return rc;
103432}
103433
103434#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
103435
103436/************** End of fts3_tokenizer.c **************************************/
103437/************** Begin file fts3_tokenizer1.c *********************************/
103438/*
103439** 2006 Oct 10
103440**
103441** The author disclaims copyright to this source code.  In place of
103442** a legal notice, here is a blessing:
103443**
103444**    May you do good and not evil.
103445**    May you find forgiveness for yourself and forgive others.
103446**    May you share freely, never taking more than you give.
103447**
103448******************************************************************************
103449**
103450** Implementation of the "simple" full-text-search tokenizer.
103451*/
103452
103453/*
103454** The code in this file is only compiled if:
103455**
103456**     * The FTS3 module is being built as an extension
103457**       (in which case SQLITE_CORE is not defined), or
103458**
103459**     * The FTS3 module is being built into the core of
103460**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
103461*/
103462#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
103463
103464
103465
103466
103467typedef struct simple_tokenizer {
103468  sqlite3_tokenizer base;
103469  char delim[128];             /* flag ASCII delimiters */
103470} simple_tokenizer;
103471
103472typedef struct simple_tokenizer_cursor {
103473  sqlite3_tokenizer_cursor base;
103474  const char *pInput;          /* input we are tokenizing */
103475  int nBytes;                  /* size of the input */
103476  int iOffset;                 /* current position in pInput */
103477  int iToken;                  /* index of next token to be returned */
103478  char *pToken;                /* storage for current token */
103479  int nTokenAllocated;         /* space allocated to zToken buffer */
103480} simple_tokenizer_cursor;
103481
103482
103483static int simpleDelim(simple_tokenizer *t, unsigned char c){
103484  return c<0x80 && t->delim[c];
103485}
103486
103487/*
103488** Create a new tokenizer instance.
103489*/
103490static int simpleCreate(
103491  int argc, const char * const *argv,
103492  sqlite3_tokenizer **ppTokenizer
103493){
103494  simple_tokenizer *t;
103495
103496  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
103497  if( t==NULL ) return SQLITE_NOMEM;
103498  memset(t, 0, sizeof(*t));
103499
103500  /* TODO(shess) Delimiters need to remain the same from run to run,
103501  ** else we need to reindex.  One solution would be a meta-table to
103502  ** track such information in the database, then we'd only want this
103503  ** information on the initial create.
103504  */
103505  if( argc>1 ){
103506    int i, n = (int)strlen(argv[1]);
103507    for(i=0; i<n; i++){
103508      unsigned char ch = argv[1][i];
103509      /* We explicitly don't support UTF-8 delimiters for now. */
103510      if( ch>=0x80 ){
103511        sqlite3_free(t);
103512        return SQLITE_ERROR;
103513      }
103514      t->delim[ch] = 1;
103515    }
103516  } else {
103517    /* Mark non-alphanumeric ASCII characters as delimiters */
103518    int i;
103519    for(i=1; i<0x80; i++){
103520      t->delim[i] = !isalnum(i) ? -1 : 0;
103521    }
103522  }
103523
103524  *ppTokenizer = &t->base;
103525  return SQLITE_OK;
103526}
103527
103528/*
103529** Destroy a tokenizer
103530*/
103531static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
103532  sqlite3_free(pTokenizer);
103533  return SQLITE_OK;
103534}
103535
103536/*
103537** Prepare to begin tokenizing a particular string.  The input
103538** string to be tokenized is pInput[0..nBytes-1].  A cursor
103539** used to incrementally tokenize this string is returned in
103540** *ppCursor.
103541*/
103542static int simpleOpen(
103543  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
103544  const char *pInput, int nBytes,        /* String to be tokenized */
103545  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
103546){
103547  simple_tokenizer_cursor *c;
103548
103549  UNUSED_PARAMETER(pTokenizer);
103550
103551  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
103552  if( c==NULL ) return SQLITE_NOMEM;
103553
103554  c->pInput = pInput;
103555  if( pInput==0 ){
103556    c->nBytes = 0;
103557  }else if( nBytes<0 ){
103558    c->nBytes = (int)strlen(pInput);
103559  }else{
103560    c->nBytes = nBytes;
103561  }
103562  c->iOffset = 0;                 /* start tokenizing at the beginning */
103563  c->iToken = 0;
103564  c->pToken = NULL;               /* no space allocated, yet. */
103565  c->nTokenAllocated = 0;
103566
103567  *ppCursor = &c->base;
103568  return SQLITE_OK;
103569}
103570
103571/*
103572** Close a tokenization cursor previously opened by a call to
103573** simpleOpen() above.
103574*/
103575static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
103576  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
103577  sqlite3_free(c->pToken);
103578  sqlite3_free(c);
103579  return SQLITE_OK;
103580}
103581
103582/*
103583** Extract the next token from a tokenization cursor.  The cursor must
103584** have been opened by a prior call to simpleOpen().
103585*/
103586static int simpleNext(
103587  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
103588  const char **ppToken,               /* OUT: *ppToken is the token text */
103589  int *pnBytes,                       /* OUT: Number of bytes in token */
103590  int *piStartOffset,                 /* OUT: Starting offset of token */
103591  int *piEndOffset,                   /* OUT: Ending offset of token */
103592  int *piPosition                     /* OUT: Position integer of token */
103593){
103594  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
103595  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
103596  unsigned char *p = (unsigned char *)c->pInput;
103597
103598  while( c->iOffset<c->nBytes ){
103599    int iStartOffset;
103600
103601    /* Scan past delimiter characters */
103602    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
103603      c->iOffset++;
103604    }
103605
103606    /* Count non-delimiter characters. */
103607    iStartOffset = c->iOffset;
103608    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
103609      c->iOffset++;
103610    }
103611
103612    if( c->iOffset>iStartOffset ){
103613      int i, n = c->iOffset-iStartOffset;
103614      if( n>c->nTokenAllocated ){
103615        c->nTokenAllocated = n+20;
103616        c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
103617        if( c->pToken==NULL ) return SQLITE_NOMEM;
103618      }
103619      for(i=0; i<n; i++){
103620        /* TODO(shess) This needs expansion to handle UTF-8
103621        ** case-insensitivity.
103622        */
103623        unsigned char ch = p[iStartOffset+i];
103624        c->pToken[i] = (char)(ch<0x80 ? tolower(ch) : ch);
103625      }
103626      *ppToken = c->pToken;
103627      *pnBytes = n;
103628      *piStartOffset = iStartOffset;
103629      *piEndOffset = c->iOffset;
103630      *piPosition = c->iToken++;
103631
103632      return SQLITE_OK;
103633    }
103634  }
103635  return SQLITE_DONE;
103636}
103637
103638/*
103639** The set of routines that implement the simple tokenizer
103640*/
103641static const sqlite3_tokenizer_module simpleTokenizerModule = {
103642  0,
103643  simpleCreate,
103644  simpleDestroy,
103645  simpleOpen,
103646  simpleClose,
103647  simpleNext,
103648};
103649
103650/*
103651** Allocate a new simple tokenizer.  Return a pointer to the new
103652** tokenizer in *ppModule
103653*/
103654SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
103655  sqlite3_tokenizer_module const**ppModule
103656){
103657  *ppModule = &simpleTokenizerModule;
103658}
103659
103660#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
103661
103662/************** End of fts3_tokenizer1.c *************************************/
103663/************** Begin file fts3_write.c **************************************/
103664/*
103665** 2009 Oct 23
103666**
103667** The author disclaims copyright to this source code.  In place of
103668** a legal notice, here is a blessing:
103669**
103670**    May you do good and not evil.
103671**    May you find forgiveness for yourself and forgive others.
103672**    May you share freely, never taking more than you give.
103673**
103674******************************************************************************
103675**
103676** This file is part of the SQLite FTS3 extension module. Specifically,
103677** this file contains code to insert, update and delete rows from FTS3
103678** tables. It also contains code to merge FTS3 b-tree segments. Some
103679** of the sub-routines used to merge segments are also used by the query
103680** code in fts3.c.
103681*/
103682
103683#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
103684
103685
103686typedef struct PendingList PendingList;
103687typedef struct SegmentNode SegmentNode;
103688typedef struct SegmentWriter SegmentWriter;
103689
103690/*
103691** Data structure used while accumulating terms in the pending-terms hash
103692** table. The hash table entry maps from term (a string) to a malloc'd
103693** instance of this structure.
103694*/
103695struct PendingList {
103696  int nData;
103697  char *aData;
103698  int nSpace;
103699  sqlite3_int64 iLastDocid;
103700  sqlite3_int64 iLastCol;
103701  sqlite3_int64 iLastPos;
103702};
103703
103704/*
103705** An instance of this structure is used to iterate through the terms on
103706** a contiguous set of segment b-tree leaf nodes. Although the details of
103707** this structure are only manipulated by code in this file, opaque handles
103708** of type Fts3SegReader* are also used by code in fts3.c to iterate through
103709** terms when querying the full-text index. See functions:
103710**
103711**   sqlite3Fts3SegReaderNew()
103712**   sqlite3Fts3SegReaderFree()
103713**   sqlite3Fts3SegReaderIterate()
103714**
103715** Methods used to manipulate Fts3SegReader structures:
103716**
103717**   fts3SegReaderNext()
103718**   fts3SegReaderFirstDocid()
103719**   fts3SegReaderNextDocid()
103720*/
103721struct Fts3SegReader {
103722  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
103723  sqlite3_int64 iStartBlock;
103724  sqlite3_int64 iEndBlock;
103725  sqlite3_stmt *pStmt;            /* SQL Statement to access leaf nodes */
103726  char *aNode;                    /* Pointer to node data (or NULL) */
103727  int nNode;                      /* Size of buffer at aNode (or 0) */
103728  int nTermAlloc;                 /* Allocated size of zTerm buffer */
103729  Fts3HashElem **ppNextElem;
103730
103731  /* Variables set by fts3SegReaderNext(). These may be read directly
103732  ** by the caller. They are valid from the time SegmentReaderNew() returns
103733  ** until SegmentReaderNext() returns something other than SQLITE_OK
103734  ** (i.e. SQLITE_DONE).
103735  */
103736  int nTerm;                      /* Number of bytes in current term */
103737  char *zTerm;                    /* Pointer to current term */
103738  char *aDoclist;                 /* Pointer to doclist of current entry */
103739  int nDoclist;                   /* Size of doclist in current entry */
103740
103741  /* The following variables are used to iterate through the current doclist */
103742  char *pOffsetList;
103743  sqlite3_int64 iDocid;
103744};
103745
103746#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
103747
103748/*
103749** An instance of this structure is used to create a segment b-tree in the
103750** database. The internal details of this type are only accessed by the
103751** following functions:
103752**
103753**   fts3SegWriterAdd()
103754**   fts3SegWriterFlush()
103755**   fts3SegWriterFree()
103756*/
103757struct SegmentWriter {
103758  SegmentNode *pTree;             /* Pointer to interior tree structure */
103759  sqlite3_int64 iFirst;           /* First slot in %_segments written */
103760  sqlite3_int64 iFree;            /* Next free slot in %_segments */
103761  char *zTerm;                    /* Pointer to previous term buffer */
103762  int nTerm;                      /* Number of bytes in zTerm */
103763  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
103764  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
103765  int nSize;                      /* Size of allocation at aData */
103766  int nData;                      /* Bytes of data in aData */
103767  char *aData;                    /* Pointer to block from malloc() */
103768};
103769
103770/*
103771** Type SegmentNode is used by the following three functions to create
103772** the interior part of the segment b+-tree structures (everything except
103773** the leaf nodes). These functions and type are only ever used by code
103774** within the fts3SegWriterXXX() family of functions described above.
103775**
103776**   fts3NodeAddTerm()
103777**   fts3NodeWrite()
103778**   fts3NodeFree()
103779*/
103780struct SegmentNode {
103781  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
103782  SegmentNode *pRight;            /* Pointer to right-sibling */
103783  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
103784  int nEntry;                     /* Number of terms written to node so far */
103785  char *zTerm;                    /* Pointer to previous term buffer */
103786  int nTerm;                      /* Number of bytes in zTerm */
103787  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
103788  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
103789  int nData;                      /* Bytes of valid data so far */
103790  char *aData;                    /* Node data */
103791};
103792
103793/*
103794** Valid values for the second argument to fts3SqlStmt().
103795*/
103796#define SQL_DELETE_CONTENT             0
103797#define SQL_IS_EMPTY                   1
103798#define SQL_DELETE_ALL_CONTENT         2
103799#define SQL_DELETE_ALL_SEGMENTS        3
103800#define SQL_DELETE_ALL_SEGDIR          4
103801#define SQL_SELECT_CONTENT_BY_ROWID    5
103802#define SQL_NEXT_SEGMENT_INDEX         6
103803#define SQL_INSERT_SEGMENTS            7
103804#define SQL_NEXT_SEGMENTS_ID           8
103805#define SQL_INSERT_SEGDIR              9
103806#define SQL_SELECT_LEVEL              10
103807#define SQL_SELECT_ALL_LEVEL          11
103808#define SQL_SELECT_LEVEL_COUNT        12
103809#define SQL_SELECT_SEGDIR_COUNT_MAX   13
103810#define SQL_DELETE_SEGDIR_BY_LEVEL    14
103811#define SQL_DELETE_SEGMENTS_RANGE     15
103812#define SQL_CONTENT_INSERT            16
103813#define SQL_GET_BLOCK                 17
103814
103815/*
103816** This function is used to obtain an SQLite prepared statement handle
103817** for the statement identified by the second argument. If successful,
103818** *pp is set to the requested statement handle and SQLITE_OK returned.
103819** Otherwise, an SQLite error code is returned and *pp is set to 0.
103820**
103821** If argument apVal is not NULL, then it must point to an array with
103822** at least as many entries as the requested statement has bound
103823** parameters. The values are bound to the statements parameters before
103824** returning.
103825*/
103826static int fts3SqlStmt(
103827  Fts3Table *p,                   /* Virtual table handle */
103828  int eStmt,                      /* One of the SQL_XXX constants above */
103829  sqlite3_stmt **pp,              /* OUT: Statement handle */
103830  sqlite3_value **apVal           /* Values to bind to statement */
103831){
103832  const char *azSql[] = {
103833/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
103834/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
103835/* 2  */  "DELETE FROM %Q.'%q_content'",
103836/* 3  */  "DELETE FROM %Q.'%q_segments'",
103837/* 4  */  "DELETE FROM %Q.'%q_segdir'",
103838/* 5  */  "SELECT * FROM %Q.'%q_content' WHERE rowid=?",
103839/* 6  */  "SELECT coalesce(max(idx)+1, 0) FROM %Q.'%q_segdir' WHERE level=?",
103840/* 7  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
103841/* 8  */  "SELECT coalesce(max(blockid)+1, 1) FROM %Q.'%q_segments'",
103842/* 9  */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
103843
103844          /* Return segments in order from oldest to newest.*/
103845/* 10 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
103846            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
103847/* 11 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
103848            "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
103849
103850/* 12 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
103851/* 13 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
103852
103853/* 14 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
103854/* 15 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
103855/* 16 */  "INSERT INTO %Q.'%q_content' VALUES(%z)",
103856/* 17 */  "SELECT block FROM %Q.'%q_segments' WHERE blockid = ?",
103857  };
103858  int rc = SQLITE_OK;
103859  sqlite3_stmt *pStmt;
103860
103861  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
103862  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
103863
103864  pStmt = p->aStmt[eStmt];
103865  if( !pStmt ){
103866    char *zSql;
103867    if( eStmt==SQL_CONTENT_INSERT ){
103868      int i;                      /* Iterator variable */
103869      char *zVarlist;             /* The "?, ?, ..." string */
103870      zVarlist = (char *)sqlite3_malloc(2*p->nColumn+2);
103871      if( !zVarlist ){
103872        *pp = 0;
103873        return SQLITE_NOMEM;
103874      }
103875      zVarlist[0] = '?';
103876      zVarlist[p->nColumn*2+1] = '\0';
103877      for(i=1; i<=p->nColumn; i++){
103878        zVarlist[i*2-1] = ',';
103879        zVarlist[i*2] = '?';
103880      }
103881      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, zVarlist);
103882    }else{
103883      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
103884    }
103885    if( !zSql ){
103886      rc = SQLITE_NOMEM;
103887    }else{
103888      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
103889      sqlite3_free(zSql);
103890      assert( rc==SQLITE_OK || pStmt==0 );
103891      p->aStmt[eStmt] = pStmt;
103892    }
103893  }
103894  if( apVal ){
103895    int i;
103896    int nParam = sqlite3_bind_parameter_count(pStmt);
103897    for(i=0; rc==SQLITE_OK && i<nParam; i++){
103898      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
103899    }
103900  }
103901  *pp = pStmt;
103902  return rc;
103903}
103904
103905/*
103906** Similar to fts3SqlStmt(). Except, after binding the parameters in
103907** array apVal[] to the SQL statement identified by eStmt, the statement
103908** is executed.
103909**
103910** Returns SQLITE_OK if the statement is successfully executed, or an
103911** SQLite error code otherwise.
103912*/
103913static int fts3SqlExec(Fts3Table *p, int eStmt, sqlite3_value **apVal){
103914  sqlite3_stmt *pStmt;
103915  int rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
103916  if( rc==SQLITE_OK ){
103917    sqlite3_step(pStmt);
103918    rc = sqlite3_reset(pStmt);
103919  }
103920  return rc;
103921}
103922
103923
103924/*
103925** Read a single block from the %_segments table. If the specified block
103926** does not exist, return SQLITE_CORRUPT. If some other error (malloc, IO
103927** etc.) occurs, return the appropriate SQLite error code.
103928**
103929** Otherwise, if successful, set *pzBlock to point to a buffer containing
103930** the block read from the database, and *pnBlock to the size of the read
103931** block in bytes.
103932**
103933** WARNING: The returned buffer is only valid until the next call to
103934** sqlite3Fts3ReadBlock().
103935*/
103936SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
103937  Fts3Table *p,
103938  sqlite3_int64 iBlock,
103939  char const **pzBlock,
103940  int *pnBlock
103941){
103942  sqlite3_stmt *pStmt;
103943  int rc = fts3SqlStmt(p, SQL_GET_BLOCK, &pStmt, 0);
103944  if( rc!=SQLITE_OK ) return rc;
103945  sqlite3_reset(pStmt);
103946
103947  if( pzBlock ){
103948    sqlite3_bind_int64(pStmt, 1, iBlock);
103949    rc = sqlite3_step(pStmt);
103950    if( rc!=SQLITE_ROW ){
103951      return (rc==SQLITE_DONE ? SQLITE_CORRUPT : rc);
103952    }
103953
103954    *pnBlock = sqlite3_column_bytes(pStmt, 0);
103955    *pzBlock = (char *)sqlite3_column_blob(pStmt, 0);
103956    if( sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
103957      return SQLITE_CORRUPT;
103958    }
103959  }
103960  return SQLITE_OK;
103961}
103962
103963/*
103964** Set *ppStmt to a statement handle that may be used to iterate through
103965** all rows in the %_segdir table, from oldest to newest. If successful,
103966** return SQLITE_OK. If an error occurs while preparing the statement,
103967** return an SQLite error code.
103968**
103969** There is only ever one instance of this SQL statement compiled for
103970** each FTS3 table.
103971**
103972** The statement returns the following columns from the %_segdir table:
103973**
103974**   0: idx
103975**   1: start_block
103976**   2: leaves_end_block
103977**   3: end_block
103978**   4: root
103979*/
103980SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, sqlite3_stmt **ppStmt){
103981  return fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, ppStmt, 0);
103982}
103983
103984
103985/*
103986** Append a single varint to a PendingList buffer. SQLITE_OK is returned
103987** if successful, or an SQLite error code otherwise.
103988**
103989** This function also serves to allocate the PendingList structure itself.
103990** For example, to create a new PendingList structure containing two
103991** varints:
103992**
103993**   PendingList *p = 0;
103994**   fts3PendingListAppendVarint(&p, 1);
103995**   fts3PendingListAppendVarint(&p, 2);
103996*/
103997static int fts3PendingListAppendVarint(
103998  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
103999  sqlite3_int64 i                 /* Value to append to data */
104000){
104001  PendingList *p = *pp;
104002
104003  /* Allocate or grow the PendingList as required. */
104004  if( !p ){
104005    p = sqlite3_malloc(sizeof(*p) + 100);
104006    if( !p ){
104007      return SQLITE_NOMEM;
104008    }
104009    p->nSpace = 100;
104010    p->aData = (char *)&p[1];
104011    p->nData = 0;
104012  }
104013  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
104014    int nNew = p->nSpace * 2;
104015    p = sqlite3_realloc(p, sizeof(*p) + nNew);
104016    if( !p ){
104017      sqlite3_free(*pp);
104018      *pp = 0;
104019      return SQLITE_NOMEM;
104020    }
104021    p->nSpace = nNew;
104022    p->aData = (char *)&p[1];
104023  }
104024
104025  /* Append the new serialized varint to the end of the list. */
104026  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
104027  p->aData[p->nData] = '\0';
104028  *pp = p;
104029  return SQLITE_OK;
104030}
104031
104032/*
104033** Add a docid/column/position entry to a PendingList structure. Non-zero
104034** is returned if the structure is sqlite3_realloced as part of adding
104035** the entry. Otherwise, zero.
104036**
104037** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
104038** Zero is always returned in this case. Otherwise, if no OOM error occurs,
104039** it is set to SQLITE_OK.
104040*/
104041static int fts3PendingListAppend(
104042  PendingList **pp,               /* IN/OUT: PendingList structure */
104043  sqlite3_int64 iDocid,           /* Docid for entry to add */
104044  sqlite3_int64 iCol,             /* Column for entry to add */
104045  sqlite3_int64 iPos,             /* Position of term for entry to add */
104046  int *pRc                        /* OUT: Return code */
104047){
104048  PendingList *p = *pp;
104049  int rc = SQLITE_OK;
104050
104051  assert( !p || p->iLastDocid<=iDocid );
104052
104053  if( !p || p->iLastDocid!=iDocid ){
104054    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
104055    if( p ){
104056      assert( p->nData<p->nSpace );
104057      assert( p->aData[p->nData]==0 );
104058      p->nData++;
104059    }
104060    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
104061      goto pendinglistappend_out;
104062    }
104063    p->iLastCol = -1;
104064    p->iLastPos = 0;
104065    p->iLastDocid = iDocid;
104066  }
104067  if( iCol>0 && p->iLastCol!=iCol ){
104068    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
104069     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
104070    ){
104071      goto pendinglistappend_out;
104072    }
104073    p->iLastCol = iCol;
104074    p->iLastPos = 0;
104075  }
104076  if( iCol>=0 ){
104077    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
104078    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
104079    if( rc==SQLITE_OK ){
104080      p->iLastPos = iPos;
104081    }
104082  }
104083
104084 pendinglistappend_out:
104085  *pRc = rc;
104086  if( p!=*pp ){
104087    *pp = p;
104088    return 1;
104089  }
104090  return 0;
104091}
104092
104093/*
104094** Tokenize the nul-terminated string zText and add all tokens to the
104095** pending-terms hash-table. The docid used is that currently stored in
104096** p->iPrevDocid, and the column is specified by argument iCol.
104097**
104098** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
104099*/
104100static int fts3PendingTermsAdd(Fts3Table *p, const char *zText, int iCol){
104101  int rc;
104102  int iStart;
104103  int iEnd;
104104  int iPos;
104105
104106  char const *zToken;
104107  int nToken;
104108
104109  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
104110  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
104111  sqlite3_tokenizer_cursor *pCsr;
104112  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
104113      const char**,int*,int*,int*,int*);
104114
104115  assert( pTokenizer && pModule );
104116
104117  rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
104118  if( rc!=SQLITE_OK ){
104119    return rc;
104120  }
104121  pCsr->pTokenizer = pTokenizer;
104122
104123  xNext = pModule->xNext;
104124  while( SQLITE_OK==rc
104125      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
104126  ){
104127    PendingList *pList;
104128
104129    /* Positions cannot be negative; we use -1 as a terminator internally.
104130    ** Tokens must have a non-zero length.
104131    */
104132    if( iPos<0 || !zToken || nToken<=0 ){
104133      rc = SQLITE_ERROR;
104134      break;
104135    }
104136
104137    pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
104138    if( pList ){
104139      p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
104140    }
104141    if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
104142      if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
104143        /* Malloc failed while inserting the new entry. This can only
104144        ** happen if there was no previous entry for this token.
104145        */
104146        assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
104147        sqlite3_free(pList);
104148        rc = SQLITE_NOMEM;
104149      }
104150    }
104151    if( rc==SQLITE_OK ){
104152      p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
104153    }
104154  }
104155
104156  pModule->xClose(pCsr);
104157  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
104158}
104159
104160/*
104161** Calling this function indicates that subsequent calls to
104162** fts3PendingTermsAdd() are to add term/position-list pairs for the
104163** contents of the document with docid iDocid.
104164*/
104165static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
104166  /* TODO(shess) Explore whether partially flushing the buffer on
104167  ** forced-flush would provide better performance.  I suspect that if
104168  ** we ordered the doclists by size and flushed the largest until the
104169  ** buffer was half empty, that would let the less frequent terms
104170  ** generate longer doclists.
104171  */
104172  if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
104173    int rc = sqlite3Fts3PendingTermsFlush(p);
104174    if( rc!=SQLITE_OK ) return rc;
104175  }
104176  p->iPrevDocid = iDocid;
104177  return SQLITE_OK;
104178}
104179
104180SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
104181  Fts3HashElem *pElem;
104182  for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
104183    sqlite3_free(fts3HashData(pElem));
104184  }
104185  fts3HashClear(&p->pendingTerms);
104186  p->nPendingData = 0;
104187}
104188
104189/*
104190** This function is called by the xUpdate() method as part of an INSERT
104191** operation. It adds entries for each term in the new record to the
104192** pendingTerms hash table.
104193**
104194** Argument apVal is the same as the similarly named argument passed to
104195** fts3InsertData(). Parameter iDocid is the docid of the new row.
104196*/
104197static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal){
104198  int i;                          /* Iterator variable */
104199  for(i=2; i<p->nColumn+2; i++){
104200    const char *zText = (const char *)sqlite3_value_text(apVal[i]);
104201    if( zText ){
104202      int rc = fts3PendingTermsAdd(p, zText, i-2);
104203      if( rc!=SQLITE_OK ){
104204        return rc;
104205      }
104206    }
104207  }
104208  return SQLITE_OK;
104209}
104210
104211/*
104212** This function is called by the xUpdate() method for an INSERT operation.
104213** The apVal parameter is passed a copy of the apVal argument passed by
104214** SQLite to the xUpdate() method. i.e:
104215**
104216**   apVal[0]                Not used for INSERT.
104217**   apVal[1]                rowid
104218**   apVal[2]                Left-most user-defined column
104219**   ...
104220**   apVal[p->nColumn+1]     Right-most user-defined column
104221**   apVal[p->nColumn+2]     Hidden column with same name as table
104222**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
104223*/
104224static int fts3InsertData(
104225  Fts3Table *p,                   /* Full-text table */
104226  sqlite3_value **apVal,          /* Array of values to insert */
104227  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
104228){
104229  int rc;                         /* Return code */
104230  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
104231
104232  /* Locate the statement handle used to insert data into the %_content
104233  ** table. The SQL for this statement is:
104234  **
104235  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
104236  **
104237  ** The statement features N '?' variables, where N is the number of user
104238  ** defined columns in the FTS3 table, plus one for the docid field.
104239  */
104240  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
104241  if( rc!=SQLITE_OK ){
104242    return rc;
104243  }
104244
104245  /* There is a quirk here. The users INSERT statement may have specified
104246  ** a value for the "rowid" field, for the "docid" field, or for both.
104247  ** Which is a problem, since "rowid" and "docid" are aliases for the
104248  ** same value. For example:
104249  **
104250  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
104251  **
104252  ** In FTS3, this is an error. It is an error to specify non-NULL values
104253  ** for both docid and some other rowid alias.
104254  */
104255  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
104256    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
104257     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
104258    ){
104259      /* A rowid/docid conflict. */
104260      return SQLITE_ERROR;
104261    }
104262    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
104263    if( rc!=SQLITE_OK ) return rc;
104264  }
104265
104266  /* Execute the statement to insert the record. Set *piDocid to the
104267  ** new docid value.
104268  */
104269  sqlite3_step(pContentInsert);
104270  rc = sqlite3_reset(pContentInsert);
104271
104272  *piDocid = sqlite3_last_insert_rowid(p->db);
104273  return rc;
104274}
104275
104276
104277
104278/*
104279** Remove all data from the FTS3 table. Clear the hash table containing
104280** pending terms.
104281*/
104282static int fts3DeleteAll(Fts3Table *p){
104283  int rc;                         /* Return code */
104284
104285  /* Discard the contents of the pending-terms hash table. */
104286  sqlite3Fts3PendingTermsClear(p);
104287
104288  /* Delete everything from the %_content, %_segments and %_segdir tables. */
104289  rc = fts3SqlExec(p, SQL_DELETE_ALL_CONTENT, 0);
104290  if( rc==SQLITE_OK ){
104291    rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGMENTS, 0);
104292  }
104293  if( rc==SQLITE_OK ){
104294    rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGDIR, 0);
104295  }
104296  return rc;
104297}
104298
104299/*
104300** The first element in the apVal[] array is assumed to contain the docid
104301** (an integer) of a row about to be deleted. Remove all terms from the
104302** full-text index.
104303*/
104304static int fts3DeleteTerms(Fts3Table *p, sqlite3_value **apVal){
104305  int rc;
104306  sqlite3_stmt *pSelect;
104307
104308  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
104309  if( rc==SQLITE_OK ){
104310    if( SQLITE_ROW==sqlite3_step(pSelect) ){
104311      int i;
104312      for(i=1; i<=p->nColumn; i++){
104313        const char *zText = (const char *)sqlite3_column_text(pSelect, i);
104314        rc = fts3PendingTermsAdd(p, zText, -1);
104315        if( rc!=SQLITE_OK ){
104316          sqlite3_reset(pSelect);
104317          return rc;
104318        }
104319      }
104320    }
104321    rc = sqlite3_reset(pSelect);
104322  }else{
104323    sqlite3_reset(pSelect);
104324  }
104325  return rc;
104326}
104327
104328/*
104329** Forward declaration to account for the circular dependency between
104330** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
104331*/
104332static int fts3SegmentMerge(Fts3Table *, int);
104333
104334/*
104335** This function allocates a new level iLevel index in the segdir table.
104336** Usually, indexes are allocated within a level sequentially starting
104337** with 0, so the allocated index is one greater than the value returned
104338** by:
104339**
104340**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
104341**
104342** However, if there are already FTS3_MERGE_COUNT indexes at the requested
104343** level, they are merged into a single level (iLevel+1) segment and the
104344** allocated index is 0.
104345**
104346** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
104347** returned. Otherwise, an SQLite error code is returned.
104348*/
104349static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
104350  int rc;                         /* Return Code */
104351  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
104352  int iNext = 0;                  /* Result of query pNextIdx */
104353
104354  /* Set variable iNext to the next available segdir index at level iLevel. */
104355  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
104356  if( rc==SQLITE_OK ){
104357    sqlite3_bind_int(pNextIdx, 1, iLevel);
104358    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
104359      iNext = sqlite3_column_int(pNextIdx, 0);
104360    }
104361    rc = sqlite3_reset(pNextIdx);
104362  }
104363
104364  if( rc==SQLITE_OK ){
104365    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
104366    ** full, merge all segments in level iLevel into a single iLevel+1
104367    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
104368    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
104369    */
104370    if( iNext>=FTS3_MERGE_COUNT ){
104371      rc = fts3SegmentMerge(p, iLevel);
104372      *piIdx = 0;
104373    }else{
104374      *piIdx = iNext;
104375    }
104376  }
104377
104378  return rc;
104379}
104380
104381/*
104382** Move the iterator passed as the first argument to the next term in the
104383** segment. If successful, SQLITE_OK is returned. If there is no next term,
104384** SQLITE_DONE. Otherwise, an SQLite error code.
104385*/
104386static int fts3SegReaderNext(Fts3SegReader *pReader){
104387  char *pNext;                    /* Cursor variable */
104388  int nPrefix;                    /* Number of bytes in term prefix */
104389  int nSuffix;                    /* Number of bytes in term suffix */
104390
104391  if( !pReader->aDoclist ){
104392    pNext = pReader->aNode;
104393  }else{
104394    pNext = &pReader->aDoclist[pReader->nDoclist];
104395  }
104396
104397  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
104398    int rc;
104399    if( fts3SegReaderIsPending(pReader) ){
104400      Fts3HashElem *pElem = *(pReader->ppNextElem);
104401      if( pElem==0 ){
104402        pReader->aNode = 0;
104403      }else{
104404        PendingList *pList = (PendingList *)fts3HashData(pElem);
104405        pReader->zTerm = (char *)fts3HashKey(pElem);
104406        pReader->nTerm = fts3HashKeysize(pElem);
104407        pReader->nNode = pReader->nDoclist = pList->nData + 1;
104408        pReader->aNode = pReader->aDoclist = pList->aData;
104409        pReader->ppNextElem++;
104410        assert( pReader->aNode );
104411      }
104412      return SQLITE_OK;
104413    }
104414    if( !pReader->pStmt ){
104415      pReader->aNode = 0;
104416      return SQLITE_OK;
104417    }
104418    rc = sqlite3_step(pReader->pStmt);
104419    if( rc!=SQLITE_ROW ){
104420      pReader->aNode = 0;
104421      return (rc==SQLITE_DONE ? SQLITE_OK : rc);
104422    }
104423    pReader->nNode = sqlite3_column_bytes(pReader->pStmt, 0);
104424    pReader->aNode = (char *)sqlite3_column_blob(pReader->pStmt, 0);
104425    pNext = pReader->aNode;
104426  }
104427
104428  pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
104429  pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
104430
104431  if( nPrefix+nSuffix>pReader->nTermAlloc ){
104432    int nNew = (nPrefix+nSuffix)*2;
104433    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
104434    if( !zNew ){
104435      return SQLITE_NOMEM;
104436    }
104437    pReader->zTerm = zNew;
104438    pReader->nTermAlloc = nNew;
104439  }
104440  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
104441  pReader->nTerm = nPrefix+nSuffix;
104442  pNext += nSuffix;
104443  pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
104444  assert( pNext<&pReader->aNode[pReader->nNode] );
104445  pReader->aDoclist = pNext;
104446  pReader->pOffsetList = 0;
104447  return SQLITE_OK;
104448}
104449
104450/*
104451** Set the SegReader to point to the first docid in the doclist associated
104452** with the current term.
104453*/
104454static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
104455  int n;
104456  assert( pReader->aDoclist );
104457  assert( !pReader->pOffsetList );
104458  n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
104459  pReader->pOffsetList = &pReader->aDoclist[n];
104460}
104461
104462/*
104463** Advance the SegReader to point to the next docid in the doclist
104464** associated with the current term.
104465**
104466** If arguments ppOffsetList and pnOffsetList are not NULL, then
104467** *ppOffsetList is set to point to the first column-offset list
104468** in the doclist entry (i.e. immediately past the docid varint).
104469** *pnOffsetList is set to the length of the set of column-offset
104470** lists, not including the nul-terminator byte. For example:
104471*/
104472static void fts3SegReaderNextDocid(
104473  Fts3SegReader *pReader,
104474  char **ppOffsetList,
104475  int *pnOffsetList
104476){
104477  char *p = pReader->pOffsetList;
104478  char c = 0;
104479
104480  /* Pointer p currently points at the first byte of an offset list. The
104481  ** following two lines advance it to point one byte past the end of
104482  ** the same offset list.
104483  */
104484  while( *p | c ) c = *p++ & 0x80;
104485  p++;
104486
104487  /* If required, populate the output variables with a pointer to and the
104488  ** size of the previous offset-list.
104489  */
104490  if( ppOffsetList ){
104491    *ppOffsetList = pReader->pOffsetList;
104492    *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
104493  }
104494
104495  /* If there are no more entries in the doclist, set pOffsetList to
104496  ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
104497  ** Fts3SegReader.pOffsetList to point to the next offset list before
104498  ** returning.
104499  */
104500  if( p>=&pReader->aDoclist[pReader->nDoclist] ){
104501    pReader->pOffsetList = 0;
104502  }else{
104503    sqlite3_int64 iDelta;
104504    pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
104505    pReader->iDocid += iDelta;
104506  }
104507}
104508
104509/*
104510** Free all allocations associated with the iterator passed as the
104511** second argument.
104512*/
104513SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *p, Fts3SegReader *pReader){
104514  if( pReader ){
104515    if( pReader->pStmt ){
104516      /* Move the leaf-range SELECT statement to the aLeavesStmt[] array,
104517      ** so that it can be reused when required by another query.
104518      */
104519      assert( p->nLeavesStmt<p->nLeavesTotal );
104520      sqlite3_reset(pReader->pStmt);
104521      p->aLeavesStmt[p->nLeavesStmt++] = pReader->pStmt;
104522    }
104523    if( !fts3SegReaderIsPending(pReader) ){
104524      sqlite3_free(pReader->zTerm);
104525    }
104526    sqlite3_free(pReader);
104527  }
104528}
104529
104530/*
104531** Allocate a new SegReader object.
104532*/
104533SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
104534  Fts3Table *p,                   /* Virtual table handle */
104535  int iAge,                       /* Segment "age". */
104536  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
104537  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
104538  sqlite3_int64 iEndBlock,        /* Final block of segment */
104539  const char *zRoot,              /* Buffer containing root node */
104540  int nRoot,                      /* Size of buffer containing root node */
104541  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
104542){
104543  int rc = SQLITE_OK;             /* Return code */
104544  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
104545  int nExtra = 0;                 /* Bytes to allocate segment root node */
104546
104547  if( iStartLeaf==0 ){
104548    nExtra = nRoot;
104549  }
104550
104551  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
104552  if( !pReader ){
104553    return SQLITE_NOMEM;
104554  }
104555  memset(pReader, 0, sizeof(Fts3SegReader));
104556  pReader->iStartBlock = iStartLeaf;
104557  pReader->iIdx = iAge;
104558  pReader->iEndBlock = iEndBlock;
104559
104560  if( nExtra ){
104561    /* The entire segment is stored in the root node. */
104562    pReader->aNode = (char *)&pReader[1];
104563    pReader->nNode = nRoot;
104564    memcpy(pReader->aNode, zRoot, nRoot);
104565  }else{
104566    /* If the text of the SQL statement to iterate through a contiguous
104567    ** set of entries in the %_segments table has not yet been composed,
104568    ** compose it now.
104569    */
104570    if( !p->zSelectLeaves ){
104571      p->zSelectLeaves = sqlite3_mprintf(
104572          "SELECT block FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ? "
104573          "ORDER BY blockid", p->zDb, p->zName
104574      );
104575      if( !p->zSelectLeaves ){
104576        rc = SQLITE_NOMEM;
104577        goto finished;
104578      }
104579    }
104580
104581    /* If there are no free statements in the aLeavesStmt[] array, prepare
104582    ** a new statement now. Otherwise, reuse a prepared statement from
104583    ** aLeavesStmt[].
104584    */
104585    if( p->nLeavesStmt==0 ){
104586      if( p->nLeavesTotal==p->nLeavesAlloc ){
104587        int nNew = p->nLeavesAlloc + 16;
104588        sqlite3_stmt **aNew = (sqlite3_stmt **)sqlite3_realloc(
104589            p->aLeavesStmt, nNew*sizeof(sqlite3_stmt *)
104590        );
104591        if( !aNew ){
104592          rc = SQLITE_NOMEM;
104593          goto finished;
104594        }
104595        p->nLeavesAlloc = nNew;
104596        p->aLeavesStmt = aNew;
104597      }
104598      rc = sqlite3_prepare_v2(p->db, p->zSelectLeaves, -1, &pReader->pStmt, 0);
104599      if( rc!=SQLITE_OK ){
104600        goto finished;
104601      }
104602      p->nLeavesTotal++;
104603    }else{
104604      pReader->pStmt = p->aLeavesStmt[--p->nLeavesStmt];
104605    }
104606
104607    /* Bind the start and end leaf blockids to the prepared SQL statement. */
104608    sqlite3_bind_int64(pReader->pStmt, 1, iStartLeaf);
104609    sqlite3_bind_int64(pReader->pStmt, 2, iEndLeaf);
104610  }
104611  rc = fts3SegReaderNext(pReader);
104612
104613 finished:
104614  if( rc==SQLITE_OK ){
104615    *ppReader = pReader;
104616  }else{
104617    sqlite3Fts3SegReaderFree(p, pReader);
104618  }
104619  return rc;
104620}
104621
104622/*
104623** This is a comparison function used as a qsort() callback when sorting
104624** an array of pending terms by term. This occurs as part of flushing
104625** the contents of the pending-terms hash table to the database.
104626*/
104627static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
104628  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
104629  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
104630  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
104631  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
104632
104633  int n = (n1<n2 ? n1 : n2);
104634  int c = memcmp(z1, z2, n);
104635  if( c==0 ){
104636    c = n1 - n2;
104637  }
104638  return c;
104639}
104640
104641/*
104642** This function is used to allocate an Fts3SegReader that iterates through
104643** a subset of the terms stored in the Fts3Table.pendingTerms array.
104644*/
104645SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
104646  Fts3Table *p,                   /* Virtual table handle */
104647  const char *zTerm,              /* Term to search for */
104648  int nTerm,                      /* Size of buffer zTerm */
104649  int isPrefix,                   /* True for a term-prefix query */
104650  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
104651){
104652  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
104653  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
104654  int nElem = 0;                  /* Size of array at aElem */
104655  int rc = SQLITE_OK;             /* Return Code */
104656
104657  if( isPrefix ){
104658    int nAlloc = 0;               /* Size of allocated array at aElem */
104659    Fts3HashElem *pE = 0;         /* Iterator variable */
104660
104661    for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
104662      char *zKey = (char *)fts3HashKey(pE);
104663      int nKey = fts3HashKeysize(pE);
104664      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
104665        if( nElem==nAlloc ){
104666          Fts3HashElem **aElem2;
104667          nAlloc += 16;
104668          aElem2 = (Fts3HashElem **)sqlite3_realloc(
104669              aElem, nAlloc*sizeof(Fts3HashElem *)
104670          );
104671          if( !aElem2 ){
104672            rc = SQLITE_NOMEM;
104673            nElem = 0;
104674            break;
104675          }
104676          aElem = aElem2;
104677        }
104678        aElem[nElem++] = pE;
104679      }
104680    }
104681
104682    /* If more than one term matches the prefix, sort the Fts3HashElem
104683    ** objects in term order using qsort(). This uses the same comparison
104684    ** callback as is used when flushing terms to disk.
104685    */
104686    if( nElem>1 ){
104687      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
104688    }
104689
104690  }else{
104691    Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
104692    if( pE ){
104693      aElem = &pE;
104694      nElem = 1;
104695    }
104696  }
104697
104698  if( nElem>0 ){
104699    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
104700    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
104701    if( !pReader ){
104702      rc = SQLITE_NOMEM;
104703    }else{
104704      memset(pReader, 0, nByte);
104705      pReader->iIdx = 0x7FFFFFFF;
104706      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
104707      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
104708      fts3SegReaderNext(pReader);
104709    }
104710  }
104711
104712  if( isPrefix ){
104713    sqlite3_free(aElem);
104714  }
104715  *ppReader = pReader;
104716  return rc;
104717}
104718
104719
104720/*
104721** The second argument to this function is expected to be a statement of
104722** the form:
104723**
104724**   SELECT
104725**     idx,                  -- col 0
104726**     start_block,          -- col 1
104727**     leaves_end_block,     -- col 2
104728**     end_block,            -- col 3
104729**     root                  -- col 4
104730**   FROM %_segdir ...
104731**
104732** This function allocates and initializes a Fts3SegReader structure to
104733** iterate through the terms stored in the segment identified by the
104734** current row that pStmt is pointing to.
104735**
104736** If successful, the Fts3SegReader is left pointing to the first term
104737** in the segment and SQLITE_OK is returned. Otherwise, an SQLite error
104738** code is returned.
104739*/
104740static int fts3SegReaderNew(
104741  Fts3Table *p,                   /* Virtual table handle */
104742  sqlite3_stmt *pStmt,            /* See above */
104743  int iAge,                       /* Segment "age". */
104744  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
104745){
104746  return sqlite3Fts3SegReaderNew(p, iAge,
104747      sqlite3_column_int64(pStmt, 1),
104748      sqlite3_column_int64(pStmt, 2),
104749      sqlite3_column_int64(pStmt, 3),
104750      sqlite3_column_blob(pStmt, 4),
104751      sqlite3_column_bytes(pStmt, 4),
104752      ppReader
104753  );
104754}
104755
104756/*
104757** Compare the entries pointed to by two Fts3SegReader structures.
104758** Comparison is as follows:
104759**
104760**   1) EOF is greater than not EOF.
104761**
104762**   2) The current terms (if any) are compared using memcmp(). If one
104763**      term is a prefix of another, the longer term is considered the
104764**      larger.
104765**
104766**   3) By segment age. An older segment is considered larger.
104767*/
104768static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
104769  int rc;
104770  if( pLhs->aNode && pRhs->aNode ){
104771    int rc2 = pLhs->nTerm - pRhs->nTerm;
104772    if( rc2<0 ){
104773      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
104774    }else{
104775      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
104776    }
104777    if( rc==0 ){
104778      rc = rc2;
104779    }
104780  }else{
104781    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
104782  }
104783  if( rc==0 ){
104784    rc = pRhs->iIdx - pLhs->iIdx;
104785  }
104786  assert( rc!=0 );
104787  return rc;
104788}
104789
104790/*
104791** A different comparison function for SegReader structures. In this
104792** version, it is assumed that each SegReader points to an entry in
104793** a doclist for identical terms. Comparison is made as follows:
104794**
104795**   1) EOF (end of doclist in this case) is greater than not EOF.
104796**
104797**   2) By current docid.
104798**
104799**   3) By segment age. An older segment is considered larger.
104800*/
104801static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
104802  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
104803  if( rc==0 ){
104804    if( pLhs->iDocid==pRhs->iDocid ){
104805      rc = pRhs->iIdx - pLhs->iIdx;
104806    }else{
104807      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
104808    }
104809  }
104810  assert( pLhs->aNode && pRhs->aNode );
104811  return rc;
104812}
104813
104814/*
104815** Compare the term that the Fts3SegReader object passed as the first argument
104816** points to with the term specified by arguments zTerm and nTerm.
104817**
104818** If the pSeg iterator is already at EOF, return 0. Otherwise, return
104819** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
104820** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
104821*/
104822static int fts3SegReaderTermCmp(
104823  Fts3SegReader *pSeg,            /* Segment reader object */
104824  const char *zTerm,              /* Term to compare to */
104825  int nTerm                       /* Size of term zTerm in bytes */
104826){
104827  int res = 0;
104828  if( pSeg->aNode ){
104829    if( pSeg->nTerm>nTerm ){
104830      res = memcmp(pSeg->zTerm, zTerm, nTerm);
104831    }else{
104832      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
104833    }
104834    if( res==0 ){
104835      res = pSeg->nTerm-nTerm;
104836    }
104837  }
104838  return res;
104839}
104840
104841/*
104842** Argument apSegment is an array of nSegment elements. It is known that
104843** the final (nSegment-nSuspect) members are already in sorted order
104844** (according to the comparison function provided). This function shuffles
104845** the array around until all entries are in sorted order.
104846*/
104847static void fts3SegReaderSort(
104848  Fts3SegReader **apSegment,                     /* Array to sort entries of */
104849  int nSegment,                                  /* Size of apSegment array */
104850  int nSuspect,                                  /* Unsorted entry count */
104851  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
104852){
104853  int i;                          /* Iterator variable */
104854
104855  assert( nSuspect<=nSegment );
104856
104857  if( nSuspect==nSegment ) nSuspect--;
104858  for(i=nSuspect-1; i>=0; i--){
104859    int j;
104860    for(j=i; j<(nSegment-1); j++){
104861      Fts3SegReader *pTmp;
104862      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
104863      pTmp = apSegment[j+1];
104864      apSegment[j+1] = apSegment[j];
104865      apSegment[j] = pTmp;
104866    }
104867  }
104868
104869#ifndef NDEBUG
104870  /* Check that the list really is sorted now. */
104871  for(i=0; i<(nSuspect-1); i++){
104872    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
104873  }
104874#endif
104875}
104876
104877/*
104878** Insert a record into the %_segments table.
104879*/
104880static int fts3WriteSegment(
104881  Fts3Table *p,                   /* Virtual table handle */
104882  sqlite3_int64 iBlock,           /* Block id for new block */
104883  char *z,                        /* Pointer to buffer containing block data */
104884  int n                           /* Size of buffer z in bytes */
104885){
104886  sqlite3_stmt *pStmt;
104887  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
104888  if( rc==SQLITE_OK ){
104889    sqlite3_bind_int64(pStmt, 1, iBlock);
104890    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
104891    sqlite3_step(pStmt);
104892    rc = sqlite3_reset(pStmt);
104893  }
104894  return rc;
104895}
104896
104897/*
104898** Insert a record into the %_segdir table.
104899*/
104900static int fts3WriteSegdir(
104901  Fts3Table *p,                   /* Virtual table handle */
104902  int iLevel,                     /* Value for "level" field */
104903  int iIdx,                       /* Value for "idx" field */
104904  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
104905  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
104906  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
104907  char *zRoot,                    /* Blob value for "root" field */
104908  int nRoot                       /* Number of bytes in buffer zRoot */
104909){
104910  sqlite3_stmt *pStmt;
104911  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
104912  if( rc==SQLITE_OK ){
104913    sqlite3_bind_int(pStmt, 1, iLevel);
104914    sqlite3_bind_int(pStmt, 2, iIdx);
104915    sqlite3_bind_int64(pStmt, 3, iStartBlock);
104916    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
104917    sqlite3_bind_int64(pStmt, 5, iEndBlock);
104918    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
104919    sqlite3_step(pStmt);
104920    rc = sqlite3_reset(pStmt);
104921  }
104922  return rc;
104923}
104924
104925/*
104926** Return the size of the common prefix (if any) shared by zPrev and
104927** zNext, in bytes. For example,
104928**
104929**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
104930**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
104931**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
104932*/
104933static int fts3PrefixCompress(
104934  const char *zPrev,              /* Buffer containing previous term */
104935  int nPrev,                      /* Size of buffer zPrev in bytes */
104936  const char *zNext,              /* Buffer containing next term */
104937  int nNext                       /* Size of buffer zNext in bytes */
104938){
104939  int n;
104940  UNUSED_PARAMETER(nNext);
104941  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
104942  return n;
104943}
104944
104945/*
104946** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
104947** (according to memcmp) than the previous term.
104948*/
104949static int fts3NodeAddTerm(
104950  Fts3Table *p,               /* Virtual table handle */
104951  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
104952  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
104953  const char *zTerm,              /* Pointer to buffer containing term */
104954  int nTerm                       /* Size of term in bytes */
104955){
104956  SegmentNode *pTree = *ppTree;
104957  int rc;
104958  SegmentNode *pNew;
104959
104960  /* First try to append the term to the current node. Return early if
104961  ** this is possible.
104962  */
104963  if( pTree ){
104964    int nData = pTree->nData;     /* Current size of node in bytes */
104965    int nReq = nData;             /* Required space after adding zTerm */
104966    int nPrefix;                  /* Number of bytes of prefix compression */
104967    int nSuffix;                  /* Suffix length */
104968
104969    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
104970    nSuffix = nTerm-nPrefix;
104971
104972    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
104973    if( nReq<=p->nNodeSize || !pTree->zTerm ){
104974
104975      if( nReq>p->nNodeSize ){
104976        /* An unusual case: this is the first term to be added to the node
104977        ** and the static node buffer (p->nNodeSize bytes) is not large
104978        ** enough. Use a separately malloced buffer instead This wastes
104979        ** p->nNodeSize bytes, but since this scenario only comes about when
104980        ** the database contain two terms that share a prefix of almost 2KB,
104981        ** this is not expected to be a serious problem.
104982        */
104983        assert( pTree->aData==(char *)&pTree[1] );
104984        pTree->aData = (char *)sqlite3_malloc(nReq);
104985        if( !pTree->aData ){
104986          return SQLITE_NOMEM;
104987        }
104988      }
104989
104990      if( pTree->zTerm ){
104991        /* There is no prefix-length field for first term in a node */
104992        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
104993      }
104994
104995      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
104996      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
104997      pTree->nData = nData + nSuffix;
104998      pTree->nEntry++;
104999
105000      if( isCopyTerm ){
105001        if( pTree->nMalloc<nTerm ){
105002          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
105003          if( !zNew ){
105004            return SQLITE_NOMEM;
105005          }
105006          pTree->nMalloc = nTerm*2;
105007          pTree->zMalloc = zNew;
105008        }
105009        pTree->zTerm = pTree->zMalloc;
105010        memcpy(pTree->zTerm, zTerm, nTerm);
105011        pTree->nTerm = nTerm;
105012      }else{
105013        pTree->zTerm = (char *)zTerm;
105014        pTree->nTerm = nTerm;
105015      }
105016      return SQLITE_OK;
105017    }
105018  }
105019
105020  /* If control flows to here, it was not possible to append zTerm to the
105021  ** current node. Create a new node (a right-sibling of the current node).
105022  ** If this is the first node in the tree, the term is added to it.
105023  **
105024  ** Otherwise, the term is not added to the new node, it is left empty for
105025  ** now. Instead, the term is inserted into the parent of pTree. If pTree
105026  ** has no parent, one is created here.
105027  */
105028  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
105029  if( !pNew ){
105030    return SQLITE_NOMEM;
105031  }
105032  memset(pNew, 0, sizeof(SegmentNode));
105033  pNew->nData = 1 + FTS3_VARINT_MAX;
105034  pNew->aData = (char *)&pNew[1];
105035
105036  if( pTree ){
105037    SegmentNode *pParent = pTree->pParent;
105038    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
105039    if( pTree->pParent==0 ){
105040      pTree->pParent = pParent;
105041    }
105042    pTree->pRight = pNew;
105043    pNew->pLeftmost = pTree->pLeftmost;
105044    pNew->pParent = pParent;
105045    pNew->zMalloc = pTree->zMalloc;
105046    pNew->nMalloc = pTree->nMalloc;
105047    pTree->zMalloc = 0;
105048  }else{
105049    pNew->pLeftmost = pNew;
105050    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
105051  }
105052
105053  *ppTree = pNew;
105054  return rc;
105055}
105056
105057/*
105058** Helper function for fts3NodeWrite().
105059*/
105060static int fts3TreeFinishNode(
105061  SegmentNode *pTree,
105062  int iHeight,
105063  sqlite3_int64 iLeftChild
105064){
105065  int nStart;
105066  assert( iHeight>=1 && iHeight<128 );
105067  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
105068  pTree->aData[nStart] = (char)iHeight;
105069  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
105070  return nStart;
105071}
105072
105073/*
105074** Write the buffer for the segment node pTree and all of its peers to the
105075** database. Then call this function recursively to write the parent of
105076** pTree and its peers to the database.
105077**
105078** Except, if pTree is a root node, do not write it to the database. Instead,
105079** set output variables *paRoot and *pnRoot to contain the root node.
105080**
105081** If successful, SQLITE_OK is returned and output variable *piLast is
105082** set to the largest blockid written to the database (or zero if no
105083** blocks were written to the db). Otherwise, an SQLite error code is
105084** returned.
105085*/
105086static int fts3NodeWrite(
105087  Fts3Table *p,                   /* Virtual table handle */
105088  SegmentNode *pTree,             /* SegmentNode handle */
105089  int iHeight,                    /* Height of this node in tree */
105090  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
105091  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
105092  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
105093  char **paRoot,                  /* OUT: Data for root node */
105094  int *pnRoot                     /* OUT: Size of root node in bytes */
105095){
105096  int rc = SQLITE_OK;
105097
105098  if( !pTree->pParent ){
105099    /* Root node of the tree. */
105100    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
105101    *piLast = iFree-1;
105102    *pnRoot = pTree->nData - nStart;
105103    *paRoot = &pTree->aData[nStart];
105104  }else{
105105    SegmentNode *pIter;
105106    sqlite3_int64 iNextFree = iFree;
105107    sqlite3_int64 iNextLeaf = iLeaf;
105108    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
105109      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
105110      int nWrite = pIter->nData - nStart;
105111
105112      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
105113      iNextFree++;
105114      iNextLeaf += (pIter->nEntry+1);
105115    }
105116    if( rc==SQLITE_OK ){
105117      assert( iNextLeaf==iFree );
105118      rc = fts3NodeWrite(
105119          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
105120      );
105121    }
105122  }
105123
105124  return rc;
105125}
105126
105127/*
105128** Free all memory allocations associated with the tree pTree.
105129*/
105130static void fts3NodeFree(SegmentNode *pTree){
105131  if( pTree ){
105132    SegmentNode *p = pTree->pLeftmost;
105133    fts3NodeFree(p->pParent);
105134    while( p ){
105135      SegmentNode *pRight = p->pRight;
105136      if( p->aData!=(char *)&p[1] ){
105137        sqlite3_free(p->aData);
105138      }
105139      assert( pRight==0 || p->zMalloc==0 );
105140      sqlite3_free(p->zMalloc);
105141      sqlite3_free(p);
105142      p = pRight;
105143    }
105144  }
105145}
105146
105147/*
105148** Add a term to the segment being constructed by the SegmentWriter object
105149** *ppWriter. When adding the first term to a segment, *ppWriter should
105150** be passed NULL. This function will allocate a new SegmentWriter object
105151** and return it via the input/output variable *ppWriter in this case.
105152**
105153** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
105154*/
105155static int fts3SegWriterAdd(
105156  Fts3Table *p,                   /* Virtual table handle */
105157  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
105158  int isCopyTerm,                 /* True if buffer zTerm must be copied */
105159  const char *zTerm,              /* Pointer to buffer containing term */
105160  int nTerm,                      /* Size of term in bytes */
105161  const char *aDoclist,           /* Pointer to buffer containing doclist */
105162  int nDoclist                    /* Size of doclist in bytes */
105163){
105164  int nPrefix;                    /* Size of term prefix in bytes */
105165  int nSuffix;                    /* Size of term suffix in bytes */
105166  int nReq;                       /* Number of bytes required on leaf page */
105167  int nData;
105168  SegmentWriter *pWriter = *ppWriter;
105169
105170  if( !pWriter ){
105171    int rc;
105172    sqlite3_stmt *pStmt;
105173
105174    /* Allocate the SegmentWriter structure */
105175    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
105176    if( !pWriter ) return SQLITE_NOMEM;
105177    memset(pWriter, 0, sizeof(SegmentWriter));
105178    *ppWriter = pWriter;
105179
105180    /* Allocate a buffer in which to accumulate data */
105181    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
105182    if( !pWriter->aData ) return SQLITE_NOMEM;
105183    pWriter->nSize = p->nNodeSize;
105184
105185    /* Find the next free blockid in the %_segments table */
105186    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
105187    if( rc!=SQLITE_OK ) return rc;
105188    if( SQLITE_ROW==sqlite3_step(pStmt) ){
105189      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
105190      pWriter->iFirst = pWriter->iFree;
105191    }
105192    rc = sqlite3_reset(pStmt);
105193    if( rc!=SQLITE_OK ) return rc;
105194  }
105195  nData = pWriter->nData;
105196
105197  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
105198  nSuffix = nTerm-nPrefix;
105199
105200  /* Figure out how many bytes are required by this new entry */
105201  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
105202    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
105203    nSuffix +                               /* Term suffix */
105204    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
105205    nDoclist;                               /* Doclist data */
105206
105207  if( nData>0 && nData+nReq>p->nNodeSize ){
105208    int rc;
105209
105210    /* The current leaf node is full. Write it out to the database. */
105211    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
105212    if( rc!=SQLITE_OK ) return rc;
105213
105214    /* Add the current term to the interior node tree. The term added to
105215    ** the interior tree must:
105216    **
105217    **   a) be greater than the largest term on the leaf node just written
105218    **      to the database (still available in pWriter->zTerm), and
105219    **
105220    **   b) be less than or equal to the term about to be added to the new
105221    **      leaf node (zTerm/nTerm).
105222    **
105223    ** In other words, it must be the prefix of zTerm 1 byte longer than
105224    ** the common prefix (if any) of zTerm and pWriter->zTerm.
105225    */
105226    assert( nPrefix<nTerm );
105227    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
105228    if( rc!=SQLITE_OK ) return rc;
105229
105230    nData = 0;
105231    pWriter->nTerm = 0;
105232
105233    nPrefix = 0;
105234    nSuffix = nTerm;
105235    nReq = 1 +                              /* varint containing prefix size */
105236      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
105237      nTerm +                               /* Term suffix */
105238      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
105239      nDoclist;                             /* Doclist data */
105240  }
105241
105242  /* If the buffer currently allocated is too small for this entry, realloc
105243  ** the buffer to make it large enough.
105244  */
105245  if( nReq>pWriter->nSize ){
105246    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
105247    if( !aNew ) return SQLITE_NOMEM;
105248    pWriter->aData = aNew;
105249    pWriter->nSize = nReq;
105250  }
105251  assert( nData+nReq<=pWriter->nSize );
105252
105253  /* Append the prefix-compressed term and doclist to the buffer. */
105254  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
105255  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
105256  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
105257  nData += nSuffix;
105258  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
105259  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
105260  pWriter->nData = nData + nDoclist;
105261
105262  /* Save the current term so that it can be used to prefix-compress the next.
105263  ** If the isCopyTerm parameter is true, then the buffer pointed to by
105264  ** zTerm is transient, so take a copy of the term data. Otherwise, just
105265  ** store a copy of the pointer.
105266  */
105267  if( isCopyTerm ){
105268    if( nTerm>pWriter->nMalloc ){
105269      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
105270      if( !zNew ){
105271        return SQLITE_NOMEM;
105272      }
105273      pWriter->nMalloc = nTerm*2;
105274      pWriter->zMalloc = zNew;
105275      pWriter->zTerm = zNew;
105276    }
105277    assert( pWriter->zTerm==pWriter->zMalloc );
105278    memcpy(pWriter->zTerm, zTerm, nTerm);
105279  }else{
105280    pWriter->zTerm = (char *)zTerm;
105281  }
105282  pWriter->nTerm = nTerm;
105283
105284  return SQLITE_OK;
105285}
105286
105287/*
105288** Flush all data associated with the SegmentWriter object pWriter to the
105289** database. This function must be called after all terms have been added
105290** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
105291** returned. Otherwise, an SQLite error code.
105292*/
105293static int fts3SegWriterFlush(
105294  Fts3Table *p,                   /* Virtual table handle */
105295  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
105296  int iLevel,                     /* Value for 'level' column of %_segdir */
105297  int iIdx                        /* Value for 'idx' column of %_segdir */
105298){
105299  int rc;                         /* Return code */
105300  if( pWriter->pTree ){
105301    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
105302    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
105303    char *zRoot = NULL;           /* Pointer to buffer containing root node */
105304    int nRoot = 0;                /* Size of buffer zRoot */
105305
105306    iLastLeaf = pWriter->iFree;
105307    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
105308    if( rc==SQLITE_OK ){
105309      rc = fts3NodeWrite(p, pWriter->pTree, 1,
105310          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
105311    }
105312    if( rc==SQLITE_OK ){
105313      rc = fts3WriteSegdir(
105314          p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
105315    }
105316  }else{
105317    /* The entire tree fits on the root node. Write it to the segdir table. */
105318    rc = fts3WriteSegdir(
105319        p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
105320  }
105321  return rc;
105322}
105323
105324/*
105325** Release all memory held by the SegmentWriter object passed as the
105326** first argument.
105327*/
105328static void fts3SegWriterFree(SegmentWriter *pWriter){
105329  if( pWriter ){
105330    sqlite3_free(pWriter->aData);
105331    sqlite3_free(pWriter->zMalloc);
105332    fts3NodeFree(pWriter->pTree);
105333    sqlite3_free(pWriter);
105334  }
105335}
105336
105337/*
105338** The first value in the apVal[] array is assumed to contain an integer.
105339** This function tests if there exist any documents with docid values that
105340** are different from that integer. i.e. if deleting the document with docid
105341** apVal[0] would mean the FTS3 table were empty.
105342**
105343** If successful, *pisEmpty is set to true if the table is empty except for
105344** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
105345** error occurs, an SQLite error code is returned.
105346*/
105347static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
105348  sqlite3_stmt *pStmt;
105349  int rc;
105350  rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
105351  if( rc==SQLITE_OK ){
105352    if( SQLITE_ROW==sqlite3_step(pStmt) ){
105353      *pisEmpty = sqlite3_column_int(pStmt, 0);
105354    }
105355    rc = sqlite3_reset(pStmt);
105356  }
105357  return rc;
105358}
105359
105360/*
105361** Set *pnSegment to the number of segments of level iLevel in the database.
105362**
105363** Return SQLITE_OK if successful, or an SQLite error code if not.
105364*/
105365static int fts3SegmentCount(Fts3Table *p, int iLevel, int *pnSegment){
105366  sqlite3_stmt *pStmt;
105367  int rc;
105368
105369  assert( iLevel>=0 );
105370  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_COUNT, &pStmt, 0);
105371  if( rc!=SQLITE_OK ) return rc;
105372  sqlite3_bind_int(pStmt, 1, iLevel);
105373  if( SQLITE_ROW==sqlite3_step(pStmt) ){
105374    *pnSegment = sqlite3_column_int(pStmt, 0);
105375  }
105376  return sqlite3_reset(pStmt);
105377}
105378
105379/*
105380** Set *pnSegment to the total number of segments in the database. Set
105381** *pnMax to the largest segment level in the database (segment levels
105382** are stored in the 'level' column of the %_segdir table).
105383**
105384** Return SQLITE_OK if successful, or an SQLite error code if not.
105385*/
105386static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
105387  sqlite3_stmt *pStmt;
105388  int rc;
105389
105390  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
105391  if( rc!=SQLITE_OK ) return rc;
105392  if( SQLITE_ROW==sqlite3_step(pStmt) ){
105393    *pnSegment = sqlite3_column_int(pStmt, 0);
105394    *pnMax = sqlite3_column_int(pStmt, 1);
105395  }
105396  return sqlite3_reset(pStmt);
105397}
105398
105399/*
105400** This function is used after merging multiple segments into a single large
105401** segment to delete the old, now redundant, segment b-trees. Specifically,
105402** it:
105403**
105404**   1) Deletes all %_segments entries for the segments associated with
105405**      each of the SegReader objects in the array passed as the third
105406**      argument, and
105407**
105408**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
105409**      entries regardless of level if (iLevel<0).
105410**
105411** SQLITE_OK is returned if successful, otherwise an SQLite error code.
105412*/
105413static int fts3DeleteSegdir(
105414  Fts3Table *p,                   /* Virtual table handle */
105415  int iLevel,                     /* Level of %_segdir entries to delete */
105416  Fts3SegReader **apSegment,      /* Array of SegReader objects */
105417  int nReader                     /* Size of array apSegment */
105418){
105419  int rc;                         /* Return Code */
105420  int i;                          /* Iterator variable */
105421  sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
105422
105423  rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
105424  for(i=0; rc==SQLITE_OK && i<nReader; i++){
105425    Fts3SegReader *pSegment = apSegment[i];
105426    if( pSegment->iStartBlock ){
105427      sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
105428      sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
105429      sqlite3_step(pDelete);
105430      rc = sqlite3_reset(pDelete);
105431    }
105432  }
105433  if( rc!=SQLITE_OK ){
105434    return rc;
105435  }
105436
105437  if( iLevel>=0 ){
105438    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
105439    if( rc==SQLITE_OK ){
105440      sqlite3_bind_int(pDelete, 1, iLevel);
105441      sqlite3_step(pDelete);
105442      rc = sqlite3_reset(pDelete);
105443    }
105444  }else{
105445    rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGDIR, 0);
105446  }
105447
105448  return rc;
105449}
105450
105451/*
105452** When this function is called, buffer *ppList (size *pnList bytes) contains
105453** a position list that may (or may not) feature multiple columns. This
105454** function adjusts the pointer *ppList and the length *pnList so that they
105455** identify the subset of the position list that corresponds to column iCol.
105456**
105457** If there are no entries in the input position list for column iCol, then
105458** *pnList is set to zero before returning.
105459*/
105460static void fts3ColumnFilter(
105461  int iCol,                       /* Column to filter on */
105462  char **ppList,                  /* IN/OUT: Pointer to position list */
105463  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
105464){
105465  char *pList = *ppList;
105466  int nList = *pnList;
105467  char *pEnd = &pList[nList];
105468  int iCurrent = 0;
105469  char *p = pList;
105470
105471  assert( iCol>=0 );
105472  while( 1 ){
105473    char c = 0;
105474    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
105475
105476    if( iCol==iCurrent ){
105477      nList = (int)(p - pList);
105478      break;
105479    }
105480
105481    nList -= (int)(p - pList);
105482    pList = p;
105483    if( nList==0 ){
105484      break;
105485    }
105486    p = &pList[1];
105487    p += sqlite3Fts3GetVarint32(p, &iCurrent);
105488  }
105489
105490  *ppList = pList;
105491  *pnList = nList;
105492}
105493
105494/*
105495** sqlite3Fts3SegReaderIterate() callback used when merging multiple
105496** segments to create a single, larger segment.
105497*/
105498static int fts3MergeCallback(
105499  Fts3Table *p,                   /* FTS3 Virtual table handle */
105500  void *pContext,                 /* Pointer to SegmentWriter* to write with */
105501  char *zTerm,                    /* Term to write to the db */
105502  int nTerm,                      /* Number of bytes in zTerm */
105503  char *aDoclist,                 /* Doclist associated with zTerm */
105504  int nDoclist                    /* Number of bytes in doclist */
105505){
105506  SegmentWriter **ppW = (SegmentWriter **)pContext;
105507  return fts3SegWriterAdd(p, ppW, 1, zTerm, nTerm, aDoclist, nDoclist);
105508}
105509
105510/*
105511** sqlite3Fts3SegReaderIterate() callback used when flushing the contents
105512** of the pending-terms hash table to the database.
105513*/
105514static int fts3FlushCallback(
105515  Fts3Table *p,                   /* FTS3 Virtual table handle */
105516  void *pContext,                 /* Pointer to SegmentWriter* to write with */
105517  char *zTerm,                    /* Term to write to the db */
105518  int nTerm,                      /* Number of bytes in zTerm */
105519  char *aDoclist,                 /* Doclist associated with zTerm */
105520  int nDoclist                    /* Number of bytes in doclist */
105521){
105522  SegmentWriter **ppW = (SegmentWriter **)pContext;
105523  return fts3SegWriterAdd(p, ppW, 0, zTerm, nTerm, aDoclist, nDoclist);
105524}
105525
105526/*
105527** This function is used to iterate through a contiguous set of terms
105528** stored in the full-text index. It merges data contained in one or
105529** more segments to support this.
105530**
105531** The second argument is passed an array of pointers to SegReader objects
105532** allocated with sqlite3Fts3SegReaderNew(). This function merges the range
105533** of terms selected by each SegReader. If a single term is present in
105534** more than one segment, the associated doclists are merged. For each
105535** term and (possibly merged) doclist in the merged range, the callback
105536** function xFunc is invoked with its arguments set as follows.
105537**
105538**   arg 0: Copy of 'p' parameter passed to this function
105539**   arg 1: Copy of 'pContext' parameter passed to this function
105540**   arg 2: Pointer to buffer containing term
105541**   arg 3: Size of arg 2 buffer in bytes
105542**   arg 4: Pointer to buffer containing doclist
105543**   arg 5: Size of arg 2 buffer in bytes
105544**
105545** The 4th argument to this function is a pointer to a structure of type
105546** Fts3SegFilter, defined in fts3Int.h. The contents of this structure
105547** further restrict the range of terms that callbacks are made for and
105548** modify the behaviour of this function. See comments above structure
105549** definition for details.
105550*/
105551SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
105552  Fts3Table *p,                   /* Virtual table handle */
105553  Fts3SegReader **apSegment,      /* Array of Fts3SegReader objects */
105554  int nSegment,                   /* Size of apSegment array */
105555  Fts3SegFilter *pFilter,         /* Restrictions on range of iteration */
105556  int (*xFunc)(Fts3Table *, void *, char *, int, char *, int),  /* Callback */
105557  void *pContext                  /* Callback context (2nd argument) */
105558){
105559  int i;                          /* Iterator variable */
105560  char *aBuffer = 0;              /* Buffer to merge doclists in */
105561  int nAlloc = 0;                 /* Allocated size of aBuffer buffer */
105562  int rc = SQLITE_OK;             /* Return code */
105563
105564  int isIgnoreEmpty =  (pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
105565  int isRequirePos =   (pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
105566  int isColFilter =    (pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
105567  int isPrefix =       (pFilter->flags & FTS3_SEGMENT_PREFIX);
105568
105569  /* If there are zero segments, this function is a no-op. This scenario
105570  ** comes about only when reading from an empty database.
105571  */
105572  if( nSegment==0 ) goto finished;
105573
105574  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
105575  ** for, then advance each segment iterator until it points to a term of
105576  ** equal or greater value than the specified term. This prevents many
105577  ** unnecessary merge/sort operations for the case where single segment
105578  ** b-tree leaf nodes contain more than one term.
105579  */
105580  if( pFilter->zTerm ){
105581    int nTerm = pFilter->nTerm;
105582    const char *zTerm = pFilter->zTerm;
105583    for(i=0; i<nSegment; i++){
105584      Fts3SegReader *pSeg = apSegment[i];
105585      while( fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 ){
105586        rc = fts3SegReaderNext(pSeg);
105587        if( rc!=SQLITE_OK ) goto finished; }
105588    }
105589  }
105590
105591  fts3SegReaderSort(apSegment, nSegment, nSegment, fts3SegReaderCmp);
105592  while( apSegment[0]->aNode ){
105593    int nTerm = apSegment[0]->nTerm;
105594    char *zTerm = apSegment[0]->zTerm;
105595    int nMerge = 1;
105596
105597    /* If this is a prefix-search, and if the term that apSegment[0] points
105598    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
105599    ** required callbacks have been made. In this case exit early.
105600    **
105601    ** Similarly, if this is a search for an exact match, and the first term
105602    ** of segment apSegment[0] is not a match, exit early.
105603    */
105604    if( pFilter->zTerm ){
105605      if( nTerm<pFilter->nTerm
105606       || (!isPrefix && nTerm>pFilter->nTerm)
105607       || memcmp(zTerm, pFilter->zTerm, pFilter->nTerm)
105608    ){
105609        goto finished;
105610      }
105611    }
105612
105613    while( nMerge<nSegment
105614        && apSegment[nMerge]->aNode
105615        && apSegment[nMerge]->nTerm==nTerm
105616        && 0==memcmp(zTerm, apSegment[nMerge]->zTerm, nTerm)
105617    ){
105618      nMerge++;
105619    }
105620
105621    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
105622    if( nMerge==1 && !isIgnoreEmpty ){
105623      Fts3SegReader *p0 = apSegment[0];
105624      rc = xFunc(p, pContext, zTerm, nTerm, p0->aDoclist, p0->nDoclist);
105625      if( rc!=SQLITE_OK ) goto finished;
105626    }else{
105627      int nDoclist = 0;           /* Size of doclist */
105628      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
105629
105630      /* The current term of the first nMerge entries in the array
105631      ** of Fts3SegReader objects is the same. The doclists must be merged
105632      ** and a single term added to the new segment.
105633      */
105634      for(i=0; i<nMerge; i++){
105635        fts3SegReaderFirstDocid(apSegment[i]);
105636      }
105637      fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
105638      while( apSegment[0]->pOffsetList ){
105639        int j;                    /* Number of segments that share a docid */
105640        char *pList;
105641        int nList;
105642        int nByte;
105643        sqlite3_int64 iDocid = apSegment[0]->iDocid;
105644        fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
105645        j = 1;
105646        while( j<nMerge
105647            && apSegment[j]->pOffsetList
105648            && apSegment[j]->iDocid==iDocid
105649        ){
105650          fts3SegReaderNextDocid(apSegment[j], 0, 0);
105651          j++;
105652        }
105653
105654        if( isColFilter ){
105655          fts3ColumnFilter(pFilter->iCol, &pList, &nList);
105656        }
105657
105658        if( !isIgnoreEmpty || nList>0 ){
105659          nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
105660          if( nDoclist+nByte>nAlloc ){
105661            char *aNew;
105662            nAlloc = nDoclist+nByte*2;
105663            aNew = sqlite3_realloc(aBuffer, nAlloc);
105664            if( !aNew ){
105665              rc = SQLITE_NOMEM;
105666              goto finished;
105667            }
105668            aBuffer = aNew;
105669          }
105670          nDoclist += sqlite3Fts3PutVarint(&aBuffer[nDoclist], iDocid-iPrev);
105671          iPrev = iDocid;
105672          if( isRequirePos ){
105673            memcpy(&aBuffer[nDoclist], pList, nList);
105674            nDoclist += nList;
105675            aBuffer[nDoclist++] = '\0';
105676          }
105677        }
105678
105679        fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
105680      }
105681
105682      if( nDoclist>0 ){
105683        rc = xFunc(p, pContext, zTerm, nTerm, aBuffer, nDoclist);
105684        if( rc!=SQLITE_OK ) goto finished;
105685      }
105686    }
105687
105688    /* If there is a term specified to filter on, and this is not a prefix
105689    ** search, return now. The callback that corresponds to the required
105690    ** term (if such a term exists in the index) has already been made.
105691    */
105692    if( pFilter->zTerm && !isPrefix ){
105693      goto finished;
105694    }
105695
105696    for(i=0; i<nMerge; i++){
105697      rc = fts3SegReaderNext(apSegment[i]);
105698      if( rc!=SQLITE_OK ) goto finished;
105699    }
105700    fts3SegReaderSort(apSegment, nSegment, nMerge, fts3SegReaderCmp);
105701  }
105702
105703 finished:
105704  sqlite3_free(aBuffer);
105705  return rc;
105706}
105707
105708/*
105709** Merge all level iLevel segments in the database into a single
105710** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
105711** single segment with a level equal to the numerically largest level
105712** currently present in the database.
105713**
105714** If this function is called with iLevel<0, but there is only one
105715** segment in the database, SQLITE_DONE is returned immediately.
105716** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
105717** an SQLite error code is returned.
105718*/
105719static int fts3SegmentMerge(Fts3Table *p, int iLevel){
105720  int i;                          /* Iterator variable */
105721  int rc;                         /* Return code */
105722  int iIdx;                       /* Index of new segment */
105723  int iNewLevel;                  /* Level to create new segment at */
105724  sqlite3_stmt *pStmt = 0;
105725  SegmentWriter *pWriter = 0;
105726  int nSegment = 0;               /* Number of segments being merged */
105727  Fts3SegReader **apSegment = 0;  /* Array of Segment iterators */
105728  Fts3SegReader *pPending = 0;    /* Iterator for pending-terms */
105729  Fts3SegFilter filter;           /* Segment term filter condition */
105730
105731  if( iLevel<0 ){
105732    /* This call is to merge all segments in the database to a single
105733    ** segment. The level of the new segment is equal to the the numerically
105734    ** greatest segment level currently present in the database. The index
105735    ** of the new segment is always 0.
105736    */
105737    iIdx = 0;
105738    rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pPending);
105739    if( rc!=SQLITE_OK ) goto finished;
105740    rc = fts3SegmentCountMax(p, &nSegment, &iNewLevel);
105741    if( rc!=SQLITE_OK ) goto finished;
105742    nSegment += (pPending!=0);
105743    if( nSegment<=1 ){
105744      return SQLITE_DONE;
105745    }
105746  }else{
105747    /* This call is to merge all segments at level iLevel. Find the next
105748    ** available segment index at level iLevel+1. The call to
105749    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
105750    ** a single iLevel+2 segment if necessary.
105751    */
105752    iNewLevel = iLevel+1;
105753    rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
105754    if( rc!=SQLITE_OK ) goto finished;
105755    rc = fts3SegmentCount(p, iLevel, &nSegment);
105756    if( rc!=SQLITE_OK ) goto finished;
105757  }
105758  assert( nSegment>0 );
105759  assert( iNewLevel>=0 );
105760
105761  /* Allocate space for an array of pointers to segment iterators. */
105762  apSegment = (Fts3SegReader**)sqlite3_malloc(sizeof(Fts3SegReader *)*nSegment);
105763  if( !apSegment ){
105764    rc = SQLITE_NOMEM;
105765    goto finished;
105766  }
105767  memset(apSegment, 0, sizeof(Fts3SegReader *)*nSegment);
105768
105769  /* Allocate a Fts3SegReader structure for each segment being merged. A
105770  ** Fts3SegReader stores the state data required to iterate through all
105771  ** entries on all leaves of a single segment.
105772  */
105773  assert( SQL_SELECT_LEVEL+1==SQL_SELECT_ALL_LEVEL);
105774  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL+(iLevel<0), &pStmt, 0);
105775  if( rc!=SQLITE_OK ) goto finished;
105776  sqlite3_bind_int(pStmt, 1, iLevel);
105777  for(i=0; SQLITE_ROW==(sqlite3_step(pStmt)); i++){
105778    rc = fts3SegReaderNew(p, pStmt, i, &apSegment[i]);
105779    if( rc!=SQLITE_OK ){
105780      goto finished;
105781    }
105782  }
105783  rc = sqlite3_reset(pStmt);
105784  if( pPending ){
105785    apSegment[i] = pPending;
105786    pPending = 0;
105787  }
105788  pStmt = 0;
105789  if( rc!=SQLITE_OK ) goto finished;
105790
105791  memset(&filter, 0, sizeof(Fts3SegFilter));
105792  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
105793  filter.flags |= (iLevel<0 ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
105794  rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment,
105795      &filter, fts3MergeCallback, (void *)&pWriter
105796  );
105797  if( rc!=SQLITE_OK ) goto finished;
105798
105799  rc = fts3DeleteSegdir(p, iLevel, apSegment, nSegment);
105800  if( rc==SQLITE_OK ){
105801    rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
105802  }
105803
105804 finished:
105805  fts3SegWriterFree(pWriter);
105806  if( apSegment ){
105807    for(i=0; i<nSegment; i++){
105808      sqlite3Fts3SegReaderFree(p, apSegment[i]);
105809    }
105810    sqlite3_free(apSegment);
105811  }
105812  sqlite3Fts3SegReaderFree(p, pPending);
105813  sqlite3_reset(pStmt);
105814  return rc;
105815}
105816
105817
105818/*
105819** Flush the contents of pendingTerms to a level 0 segment.
105820*/
105821SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
105822  int rc;                         /* Return Code */
105823  int idx;                        /* Index of new segment created */
105824  SegmentWriter *pWriter = 0;     /* Used to write the segment */
105825  Fts3SegReader *pReader = 0;     /* Used to iterate through the hash table */
105826
105827  /* Allocate a SegReader object to iterate through the contents of the
105828  ** pending-terms table. If an error occurs, or if there are no terms
105829  ** in the pending-terms table, return immediately.
105830  */
105831  rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pReader);
105832  if( rc!=SQLITE_OK || pReader==0 ){
105833    return rc;
105834  }
105835
105836  /* Determine the next index at level 0. If level 0 is already full, this
105837  ** call may merge all existing level 0 segments into a single level 1
105838  ** segment.
105839  */
105840  rc = fts3AllocateSegdirIdx(p, 0, &idx);
105841
105842  /* If no errors have occured, iterate through the contents of the
105843  ** pending-terms hash table using the Fts3SegReader iterator. The callback
105844  ** writes each term (along with its doclist) to the database via the
105845  ** SegmentWriter handle pWriter.
105846  */
105847  if( rc==SQLITE_OK ){
105848    void *c = (void *)&pWriter;   /* SegReaderIterate() callback context */
105849    Fts3SegFilter f;              /* SegReaderIterate() parameters */
105850
105851    memset(&f, 0, sizeof(Fts3SegFilter));
105852    f.flags = FTS3_SEGMENT_REQUIRE_POS;
105853    rc = sqlite3Fts3SegReaderIterate(p, &pReader, 1, &f, fts3FlushCallback, c);
105854  }
105855  assert( pWriter || rc!=SQLITE_OK );
105856
105857  /* If no errors have occured, flush the SegmentWriter object to the
105858  ** database. Then delete the SegmentWriter and Fts3SegReader objects
105859  ** allocated by this function.
105860  */
105861  if( rc==SQLITE_OK ){
105862    rc = fts3SegWriterFlush(p, pWriter, 0, idx);
105863  }
105864  fts3SegWriterFree(pWriter);
105865  sqlite3Fts3SegReaderFree(p, pReader);
105866
105867  if( rc==SQLITE_OK ){
105868    sqlite3Fts3PendingTermsClear(p);
105869  }
105870  return rc;
105871}
105872
105873/*
105874** Handle a 'special' INSERT of the form:
105875**
105876**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
105877**
105878** Argument pVal contains the result of <expr>. Currently the only
105879** meaningful value to insert is the text 'optimize'.
105880*/
105881static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
105882  int rc;                         /* Return Code */
105883  const char *zVal = (const char *)sqlite3_value_text(pVal);
105884  int nVal = sqlite3_value_bytes(pVal);
105885
105886  if( !zVal ){
105887    return SQLITE_NOMEM;
105888  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
105889    rc = fts3SegmentMerge(p, -1);
105890    if( rc==SQLITE_DONE ){
105891      rc = SQLITE_OK;
105892    }else{
105893      sqlite3Fts3PendingTermsClear(p);
105894    }
105895#ifdef SQLITE_TEST
105896  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
105897    p->nNodeSize = atoi(&zVal[9]);
105898    rc = SQLITE_OK;
105899  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
105900    p->nMaxPendingData = atoi(&zVal[11]);
105901    rc = SQLITE_OK;
105902#endif
105903  }else{
105904    rc = SQLITE_ERROR;
105905  }
105906
105907  return rc;
105908}
105909
105910/*
105911** This function does the work for the xUpdate method of FTS3 virtual
105912** tables.
105913*/
105914SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
105915  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
105916  int nArg,                       /* Size of argument array */
105917  sqlite3_value **apVal,          /* Array of arguments */
105918  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
105919){
105920  Fts3Table *p = (Fts3Table *)pVtab;
105921  int rc = SQLITE_OK;             /* Return Code */
105922  int isRemove = 0;               /* True for an UPDATE or DELETE */
105923  sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
105924
105925
105926  /* If this is a DELETE or UPDATE operation, remove the old record. */
105927  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
105928    int isEmpty;
105929    rc = fts3IsEmpty(p, apVal, &isEmpty);
105930    if( rc==SQLITE_OK ){
105931      if( isEmpty ){
105932        /* Deleting this row means the whole table is empty. In this case
105933        ** delete the contents of all three tables and throw away any
105934        ** data in the pendingTerms hash table.
105935        */
105936        rc = fts3DeleteAll(p);
105937      }else{
105938        isRemove = 1;
105939        iRemove = sqlite3_value_int64(apVal[0]);
105940        rc = fts3PendingTermsDocid(p, iRemove);
105941        if( rc==SQLITE_OK ){
105942          rc = fts3DeleteTerms(p, apVal);
105943          if( rc==SQLITE_OK ){
105944            rc = fts3SqlExec(p, SQL_DELETE_CONTENT, apVal);
105945          }
105946        }
105947      }
105948    }
105949  }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
105950    return fts3SpecialInsert(p, apVal[p->nColumn+2]);
105951  }
105952
105953  /* If this is an INSERT or UPDATE operation, insert the new record. */
105954  if( nArg>1 && rc==SQLITE_OK ){
105955    rc = fts3InsertData(p, apVal, pRowid);
105956    if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
105957      rc = fts3PendingTermsDocid(p, *pRowid);
105958    }
105959    if( rc==SQLITE_OK ){
105960      rc = fts3InsertTerms(p, apVal);
105961    }
105962  }
105963
105964  return rc;
105965}
105966
105967/*
105968** Flush any data in the pending-terms hash table to disk. If successful,
105969** merge all segments in the database (including the new segment, if
105970** there was any data to flush) into a single segment.
105971*/
105972SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
105973  int rc;
105974  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
105975  if( rc==SQLITE_OK ){
105976    rc = fts3SegmentMerge(p, -1);
105977    if( rc==SQLITE_OK ){
105978      rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
105979      if( rc==SQLITE_OK ){
105980        sqlite3Fts3PendingTermsClear(p);
105981      }
105982    }else{
105983      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
105984      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
105985    }
105986  }
105987  return rc;
105988}
105989
105990#endif
105991
105992/************** End of fts3_write.c ******************************************/
105993/************** Begin file fts3_snippet.c ************************************/
105994/*
105995** 2009 Oct 23
105996**
105997** The author disclaims copyright to this source code.  In place of
105998** a legal notice, here is a blessing:
105999**
106000**    May you do good and not evil.
106001**    May you find forgiveness for yourself and forgive others.
106002**    May you share freely, never taking more than you give.
106003**
106004******************************************************************************
106005*/
106006
106007#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
106008
106009
106010typedef struct Snippet Snippet;
106011
106012/*
106013** An instance of the following structure keeps track of generated
106014** matching-word offset information and snippets.
106015*/
106016struct Snippet {
106017  int nMatch;                     /* Total number of matches */
106018  int nAlloc;                     /* Space allocated for aMatch[] */
106019  struct snippetMatch {  /* One entry for each matching term */
106020    char snStatus;       /* Status flag for use while constructing snippets */
106021    short int nByte;     /* Number of bytes in the term */
106022    short int iCol;      /* The column that contains the match */
106023    short int iTerm;     /* The index in Query.pTerms[] of the matching term */
106024    int iToken;          /* The index of the matching document token */
106025    int iStart;          /* The offset to the first character of the term */
106026  } *aMatch;                      /* Points to space obtained from malloc */
106027  char *zOffset;                  /* Text rendering of aMatch[] */
106028  int nOffset;                    /* strlen(zOffset) */
106029  char *zSnippet;                 /* Snippet text */
106030  int nSnippet;                   /* strlen(zSnippet) */
106031};
106032
106033
106034/* It is not safe to call isspace(), tolower(), or isalnum() on
106035** hi-bit-set characters.  This is the same solution used in the
106036** tokenizer.
106037*/
106038static int fts3snippetIsspace(char c){
106039  return (c&0x80)==0 ? isspace(c) : 0;
106040}
106041
106042
106043/*
106044** A StringBuffer object holds a zero-terminated string that grows
106045** arbitrarily by appending.  Space to hold the string is obtained
106046** from sqlite3_malloc().  After any memory allocation failure,
106047** StringBuffer.z is set to NULL and no further allocation is attempted.
106048*/
106049typedef struct StringBuffer {
106050  char *z;         /* Text of the string.  Space from malloc. */
106051  int nUsed;       /* Number bytes of z[] used, not counting \000 terminator */
106052  int nAlloc;      /* Bytes allocated for z[] */
106053} StringBuffer;
106054
106055
106056/*
106057** Initialize a new StringBuffer.
106058*/
106059static void fts3SnippetSbInit(StringBuffer *p){
106060  p->nAlloc = 100;
106061  p->nUsed = 0;
106062  p->z = sqlite3_malloc( p->nAlloc );
106063}
106064
106065/*
106066** Append text to the string buffer.
106067*/
106068static void fts3SnippetAppend(StringBuffer *p, const char *zNew, int nNew){
106069  if( p->z==0 ) return;
106070  if( nNew<0 ) nNew = (int)strlen(zNew);
106071  if( p->nUsed + nNew >= p->nAlloc ){
106072    int nAlloc;
106073    char *zNew;
106074
106075    nAlloc = p->nUsed + nNew + p->nAlloc;
106076    zNew = sqlite3_realloc(p->z, nAlloc);
106077    if( zNew==0 ){
106078      sqlite3_free(p->z);
106079      p->z = 0;
106080      return;
106081    }
106082    p->z = zNew;
106083    p->nAlloc = nAlloc;
106084  }
106085  memcpy(&p->z[p->nUsed], zNew, nNew);
106086  p->nUsed += nNew;
106087  p->z[p->nUsed] = 0;
106088}
106089
106090/* If the StringBuffer ends in something other than white space, add a
106091** single space character to the end.
106092*/
106093static void fts3SnippetAppendWhiteSpace(StringBuffer *p){
106094  if( p->z && p->nUsed && !fts3snippetIsspace(p->z[p->nUsed-1]) ){
106095    fts3SnippetAppend(p, " ", 1);
106096  }
106097}
106098
106099/* Remove white space from the end of the StringBuffer */
106100static void fts3SnippetTrimWhiteSpace(StringBuffer *p){
106101  if( p->z ){
106102    while( p->nUsed && fts3snippetIsspace(p->z[p->nUsed-1]) ){
106103      p->nUsed--;
106104    }
106105    p->z[p->nUsed] = 0;
106106  }
106107}
106108
106109/*
106110** Release all memory associated with the Snippet structure passed as
106111** an argument.
106112*/
106113static void fts3SnippetFree(Snippet *p){
106114  if( p ){
106115    sqlite3_free(p->aMatch);
106116    sqlite3_free(p->zOffset);
106117    sqlite3_free(p->zSnippet);
106118    sqlite3_free(p);
106119  }
106120}
106121
106122/*
106123** Append a single entry to the p->aMatch[] log.
106124*/
106125static int snippetAppendMatch(
106126  Snippet *p,               /* Append the entry to this snippet */
106127  int iCol, int iTerm,      /* The column and query term */
106128  int iToken,               /* Matching token in document */
106129  int iStart, int nByte     /* Offset and size of the match */
106130){
106131  int i;
106132  struct snippetMatch *pMatch;
106133  if( p->nMatch+1>=p->nAlloc ){
106134    struct snippetMatch *pNew;
106135    p->nAlloc = p->nAlloc*2 + 10;
106136    pNew = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
106137    if( pNew==0 ){
106138      p->aMatch = 0;
106139      p->nMatch = 0;
106140      p->nAlloc = 0;
106141      return SQLITE_NOMEM;
106142    }
106143    p->aMatch = pNew;
106144  }
106145  i = p->nMatch++;
106146  pMatch = &p->aMatch[i];
106147  pMatch->iCol = (short)iCol;
106148  pMatch->iTerm = (short)iTerm;
106149  pMatch->iToken = iToken;
106150  pMatch->iStart = iStart;
106151  pMatch->nByte = (short)nByte;
106152  return SQLITE_OK;
106153}
106154
106155/*
106156** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
106157*/
106158#define FTS3_ROTOR_SZ   (32)
106159#define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
106160
106161/*
106162** Function to iterate through the tokens of a compiled expression.
106163**
106164** Except, skip all tokens on the right-hand side of a NOT operator.
106165** This function is used to find tokens as part of snippet and offset
106166** generation and we do nt want snippets and offsets to report matches
106167** for tokens on the RHS of a NOT.
106168*/
106169static int fts3NextExprToken(Fts3Expr **ppExpr, int *piToken){
106170  Fts3Expr *p = *ppExpr;
106171  int iToken = *piToken;
106172  if( iToken<0 ){
106173    /* In this case the expression p is the root of an expression tree.
106174    ** Move to the first token in the expression tree.
106175    */
106176    while( p->pLeft ){
106177      p = p->pLeft;
106178    }
106179    iToken = 0;
106180  }else{
106181    assert(p && p->eType==FTSQUERY_PHRASE );
106182    if( iToken<(p->pPhrase->nToken-1) ){
106183      iToken++;
106184    }else{
106185      iToken = 0;
106186      while( p->pParent && p->pParent->pLeft!=p ){
106187        assert( p->pParent->pRight==p );
106188        p = p->pParent;
106189      }
106190      p = p->pParent;
106191      if( p ){
106192        assert( p->pRight!=0 );
106193        p = p->pRight;
106194        while( p->pLeft ){
106195          p = p->pLeft;
106196        }
106197      }
106198    }
106199  }
106200
106201  *ppExpr = p;
106202  *piToken = iToken;
106203  return p?1:0;
106204}
106205
106206/*
106207** Return TRUE if the expression node pExpr is located beneath the
106208** RHS of a NOT operator.
106209*/
106210static int fts3ExprBeneathNot(Fts3Expr *p){
106211  Fts3Expr *pParent;
106212  while( p ){
106213    pParent = p->pParent;
106214    if( pParent && pParent->eType==FTSQUERY_NOT && pParent->pRight==p ){
106215      return 1;
106216    }
106217    p = pParent;
106218  }
106219  return 0;
106220}
106221
106222/*
106223** Add entries to pSnippet->aMatch[] for every match that occurs against
106224** document zDoc[0..nDoc-1] which is stored in column iColumn.
106225*/
106226static int snippetOffsetsOfColumn(
106227  Fts3Cursor *pCur,         /* The fulltest search cursor */
106228  Snippet *pSnippet,             /* The Snippet object to be filled in */
106229  int iColumn,                   /* Index of fulltext table column */
106230  const char *zDoc,              /* Text of the fulltext table column */
106231  int nDoc                       /* Length of zDoc in bytes */
106232){
106233  const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
106234  sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
106235  sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
106236  Fts3Table *pVtab;                /* The full text index */
106237  int nColumn;                         /* Number of columns in the index */
106238  int i, j;                            /* Loop counters */
106239  int rc;                              /* Return code */
106240  unsigned int match, prevMatch;       /* Phrase search bitmasks */
106241  const char *zToken;                  /* Next token from the tokenizer */
106242  int nToken;                          /* Size of zToken */
106243  int iBegin, iEnd, iPos;              /* Offsets of beginning and end */
106244
106245  /* The following variables keep a circular buffer of the last
106246  ** few tokens */
106247  unsigned int iRotor = 0;             /* Index of current token */
106248  int iRotorBegin[FTS3_ROTOR_SZ];      /* Beginning offset of token */
106249  int iRotorLen[FTS3_ROTOR_SZ];        /* Length of token */
106250
106251  pVtab =  (Fts3Table *)pCur->base.pVtab;
106252  nColumn = pVtab->nColumn;
106253  pTokenizer = pVtab->pTokenizer;
106254  pTModule = pTokenizer->pModule;
106255  rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
106256  if( rc ) return rc;
106257  pTCursor->pTokenizer = pTokenizer;
106258
106259  prevMatch = 0;
106260  while( (rc = pTModule->xNext(pTCursor, &zToken, &nToken,
106261                               &iBegin, &iEnd, &iPos))==SQLITE_OK ){
106262    Fts3Expr *pIter = pCur->pExpr;
106263    int iIter = -1;
106264    iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
106265    iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
106266    match = 0;
106267    for(i=0; i<(FTS3_ROTOR_SZ-1) && fts3NextExprToken(&pIter, &iIter); i++){
106268      int nPhrase;                    /* Number of tokens in current phrase */
106269      struct PhraseToken *pToken;     /* Current token */
106270      int iCol;                       /* Column index */
106271
106272      if( fts3ExprBeneathNot(pIter) ) continue;
106273      nPhrase = pIter->pPhrase->nToken;
106274      pToken = &pIter->pPhrase->aToken[iIter];
106275      iCol = pIter->pPhrase->iColumn;
106276      if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
106277      if( pToken->n>nToken ) continue;
106278      if( !pToken->isPrefix && pToken->n<nToken ) continue;
106279      assert( pToken->n<=nToken );
106280      if( memcmp(pToken->z, zToken, pToken->n) ) continue;
106281      if( iIter>0 && (prevMatch & (1<<i))==0 ) continue;
106282      match |= 1<<i;
106283      if( i==(FTS3_ROTOR_SZ-2) || nPhrase==iIter+1 ){
106284        for(j=nPhrase-1; j>=0; j--){
106285          int k = (iRotor-j) & FTS3_ROTOR_MASK;
106286          rc = snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
106287                                  iRotorBegin[k], iRotorLen[k]);
106288          if( rc ) goto end_offsets_of_column;
106289        }
106290      }
106291    }
106292    prevMatch = match<<1;
106293    iRotor++;
106294  }
106295end_offsets_of_column:
106296  pTModule->xClose(pTCursor);
106297  return rc==SQLITE_DONE ? SQLITE_OK : rc;
106298}
106299
106300/*
106301** Remove entries from the pSnippet structure to account for the NEAR
106302** operator. When this is called, pSnippet contains the list of token
106303** offsets produced by treating all NEAR operators as AND operators.
106304** This function removes any entries that should not be present after
106305** accounting for the NEAR restriction. For example, if the queried
106306** document is:
106307**
106308**     "A B C D E A"
106309**
106310** and the query is:
106311**
106312**     A NEAR/0 E
106313**
106314** then when this function is called the Snippet contains token offsets
106315** 0, 4 and 5. This function removes the "0" entry (because the first A
106316** is not near enough to an E).
106317**
106318** When this function is called, the value pointed to by parameter piLeft is
106319** the integer id of the left-most token in the expression tree headed by
106320** pExpr. This function increments *piLeft by the total number of tokens
106321** in the expression tree headed by pExpr.
106322**
106323** Return 1 if any trimming occurs.  Return 0 if no trimming is required.
106324*/
106325static int trimSnippetOffsets(
106326  Fts3Expr *pExpr,      /* The search expression */
106327  Snippet *pSnippet,    /* The set of snippet offsets to be trimmed */
106328  int *piLeft           /* Index of left-most token in pExpr */
106329){
106330  if( pExpr ){
106331    if( trimSnippetOffsets(pExpr->pLeft, pSnippet, piLeft) ){
106332      return 1;
106333    }
106334
106335    switch( pExpr->eType ){
106336      case FTSQUERY_PHRASE:
106337        *piLeft += pExpr->pPhrase->nToken;
106338        break;
106339      case FTSQUERY_NEAR: {
106340        /* The right-hand-side of a NEAR operator is always a phrase. The
106341        ** left-hand-side is either a phrase or an expression tree that is
106342        ** itself headed by a NEAR operator. The following initializations
106343        ** set local variable iLeft to the token number of the left-most
106344        ** token in the right-hand phrase, and iRight to the right most
106345        ** token in the same phrase. For example, if we had:
106346        **
106347        **     <col> MATCH '"abc def" NEAR/2 "ghi jkl"'
106348        **
106349        ** then iLeft will be set to 2 (token number of ghi) and nToken will
106350        ** be set to 4.
106351        */
106352        Fts3Expr *pLeft = pExpr->pLeft;
106353        Fts3Expr *pRight = pExpr->pRight;
106354        int iLeft = *piLeft;
106355        int nNear = pExpr->nNear;
106356        int nToken = pRight->pPhrase->nToken;
106357        int jj, ii;
106358        if( pLeft->eType==FTSQUERY_NEAR ){
106359          pLeft = pLeft->pRight;
106360        }
106361        assert( pRight->eType==FTSQUERY_PHRASE );
106362        assert( pLeft->eType==FTSQUERY_PHRASE );
106363        nToken += pLeft->pPhrase->nToken;
106364
106365        for(ii=0; ii<pSnippet->nMatch; ii++){
106366          struct snippetMatch *p = &pSnippet->aMatch[ii];
106367          if( p->iTerm==iLeft ){
106368            int isOk = 0;
106369            /* Snippet ii is an occurence of query term iLeft in the document.
106370            ** It occurs at position (p->iToken) of the document. We now
106371            ** search for an instance of token (iLeft-1) somewhere in the
106372            ** range (p->iToken - nNear)...(p->iToken + nNear + nToken) within
106373            ** the set of snippetMatch structures. If one is found, proceed.
106374            ** If one cannot be found, then remove snippets ii..(ii+N-1)
106375            ** from the matching snippets, where N is the number of tokens
106376            ** in phrase pRight->pPhrase.
106377            */
106378            for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
106379              struct snippetMatch *p2 = &pSnippet->aMatch[jj];
106380              if( p2->iTerm==(iLeft-1) ){
106381                if( p2->iToken>=(p->iToken-nNear-1)
106382                 && p2->iToken<(p->iToken+nNear+nToken)
106383                ){
106384                  isOk = 1;
106385                }
106386              }
106387            }
106388            if( !isOk ){
106389              int kk;
106390              for(kk=0; kk<pRight->pPhrase->nToken; kk++){
106391                pSnippet->aMatch[kk+ii].iTerm = -2;
106392              }
106393              return 1;
106394            }
106395          }
106396          if( p->iTerm==(iLeft-1) ){
106397            int isOk = 0;
106398            for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
106399              struct snippetMatch *p2 = &pSnippet->aMatch[jj];
106400              if( p2->iTerm==iLeft ){
106401                if( p2->iToken<=(p->iToken+nNear+1)
106402                 && p2->iToken>(p->iToken-nNear-nToken)
106403                ){
106404                  isOk = 1;
106405                }
106406              }
106407            }
106408            if( !isOk ){
106409              int kk;
106410              for(kk=0; kk<pLeft->pPhrase->nToken; kk++){
106411                pSnippet->aMatch[ii-kk].iTerm = -2;
106412              }
106413              return 1;
106414            }
106415          }
106416        }
106417        break;
106418      }
106419    }
106420
106421    if( trimSnippetOffsets(pExpr->pRight, pSnippet, piLeft) ){
106422      return 1;
106423    }
106424  }
106425  return 0;
106426}
106427
106428/*
106429** Compute all offsets for the current row of the query.
106430** If the offsets have already been computed, this routine is a no-op.
106431*/
106432static int snippetAllOffsets(Fts3Cursor *pCsr, Snippet **ppSnippet){
106433  Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;  /* The FTS3 virtual table */
106434  int nColumn;           /* Number of columns.  Docid does count */
106435  int iColumn;           /* Index of of a column */
106436  int i;                 /* Loop index */
106437  int iFirst;            /* First column to search */
106438  int iLast;             /* Last coumn to search */
106439  int iTerm = 0;
106440  Snippet *pSnippet;
106441  int rc = SQLITE_OK;
106442
106443  if( pCsr->pExpr==0 ){
106444    return SQLITE_OK;
106445  }
106446
106447  pSnippet = (Snippet *)sqlite3_malloc(sizeof(Snippet));
106448  *ppSnippet = pSnippet;
106449  if( !pSnippet ){
106450    return SQLITE_NOMEM;
106451  }
106452  memset(pSnippet, 0, sizeof(Snippet));
106453
106454  nColumn = p->nColumn;
106455  iColumn = (pCsr->eSearch - 2);
106456  if( iColumn<0 || iColumn>=nColumn ){
106457    /* Look for matches over all columns of the full-text index */
106458    iFirst = 0;
106459    iLast = nColumn-1;
106460  }else{
106461    /* Look for matches in the iColumn-th column of the index only */
106462    iFirst = iColumn;
106463    iLast = iColumn;
106464  }
106465  for(i=iFirst; rc==SQLITE_OK && i<=iLast; i++){
106466    const char *zDoc;
106467    int nDoc;
106468    zDoc = (const char*)sqlite3_column_text(pCsr->pStmt, i+1);
106469    nDoc = sqlite3_column_bytes(pCsr->pStmt, i+1);
106470    if( zDoc==0 && sqlite3_column_type(pCsr->pStmt, i+1)!=SQLITE_NULL ){
106471      rc = SQLITE_NOMEM;
106472    }else{
106473      rc = snippetOffsetsOfColumn(pCsr, pSnippet, i, zDoc, nDoc);
106474    }
106475  }
106476
106477  while( trimSnippetOffsets(pCsr->pExpr, pSnippet, &iTerm) ){
106478    iTerm = 0;
106479  }
106480
106481  return rc;
106482}
106483
106484/*
106485** Convert the information in the aMatch[] array of the snippet
106486** into the string zOffset[0..nOffset-1]. This string is used as
106487** the return of the SQL offsets() function.
106488*/
106489static void snippetOffsetText(Snippet *p){
106490  int i;
106491  int cnt = 0;
106492  StringBuffer sb;
106493  char zBuf[200];
106494  if( p->zOffset ) return;
106495  fts3SnippetSbInit(&sb);
106496  for(i=0; i<p->nMatch; i++){
106497    struct snippetMatch *pMatch = &p->aMatch[i];
106498    if( pMatch->iTerm>=0 ){
106499      /* If snippetMatch.iTerm is less than 0, then the match was
106500      ** discarded as part of processing the NEAR operator (see the
106501      ** trimSnippetOffsetsForNear() function for details). Ignore
106502      ** it in this case
106503      */
106504      zBuf[0] = ' ';
106505      sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
106506          pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
106507      fts3SnippetAppend(&sb, zBuf, -1);
106508      cnt++;
106509    }
106510  }
106511  p->zOffset = sb.z;
106512  p->nOffset = sb.z ? sb.nUsed : 0;
106513}
106514
106515/*
106516** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
106517** of matching words some of which might be in zDoc.  zDoc is column
106518** number iCol.
106519**
106520** iBreak is suggested spot in zDoc where we could begin or end an
106521** excerpt.  Return a value similar to iBreak but possibly adjusted
106522** to be a little left or right so that the break point is better.
106523*/
106524static int wordBoundary(
106525  int iBreak,                   /* The suggested break point */
106526  const char *zDoc,             /* Document text */
106527  int nDoc,                     /* Number of bytes in zDoc[] */
106528  struct snippetMatch *aMatch,  /* Matching words */
106529  int nMatch,                   /* Number of entries in aMatch[] */
106530  int iCol                      /* The column number for zDoc[] */
106531){
106532  int i;
106533  if( iBreak<=10 ){
106534    return 0;
106535  }
106536  if( iBreak>=nDoc-10 ){
106537    return nDoc;
106538  }
106539  for(i=0; ALWAYS(i<nMatch) && aMatch[i].iCol<iCol; i++){}
106540  while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
106541  if( i<nMatch ){
106542    if( aMatch[i].iStart<iBreak+10 ){
106543      return aMatch[i].iStart;
106544    }
106545    if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
106546      return aMatch[i-1].iStart;
106547    }
106548  }
106549  for(i=1; i<=10; i++){
106550    if( fts3snippetIsspace(zDoc[iBreak-i]) ){
106551      return iBreak - i + 1;
106552    }
106553    if( fts3snippetIsspace(zDoc[iBreak+i]) ){
106554      return iBreak + i + 1;
106555    }
106556  }
106557  return iBreak;
106558}
106559
106560
106561
106562/*
106563** Allowed values for Snippet.aMatch[].snStatus
106564*/
106565#define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
106566#define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */
106567
106568/*
106569** Generate the text of a snippet.
106570*/
106571static void snippetText(
106572  Fts3Cursor *pCursor,   /* The cursor we need the snippet for */
106573  Snippet *pSnippet,
106574  const char *zStartMark,     /* Markup to appear before each match */
106575  const char *zEndMark,       /* Markup to appear after each match */
106576  const char *zEllipsis       /* Ellipsis mark */
106577){
106578  int i, j;
106579  struct snippetMatch *aMatch;
106580  int nMatch;
106581  int nDesired;
106582  StringBuffer sb;
106583  int tailCol;
106584  int tailOffset;
106585  int iCol;
106586  int nDoc;
106587  const char *zDoc;
106588  int iStart, iEnd;
106589  int tailEllipsis = 0;
106590  int iMatch;
106591
106592
106593  sqlite3_free(pSnippet->zSnippet);
106594  pSnippet->zSnippet = 0;
106595  aMatch = pSnippet->aMatch;
106596  nMatch = pSnippet->nMatch;
106597  fts3SnippetSbInit(&sb);
106598
106599  for(i=0; i<nMatch; i++){
106600    aMatch[i].snStatus = SNIPPET_IGNORE;
106601  }
106602  nDesired = 0;
106603  for(i=0; i<FTS3_ROTOR_SZ; i++){
106604    for(j=0; j<nMatch; j++){
106605      if( aMatch[j].iTerm==i ){
106606        aMatch[j].snStatus = SNIPPET_DESIRED;
106607        nDesired++;
106608        break;
106609      }
106610    }
106611  }
106612
106613  iMatch = 0;
106614  tailCol = -1;
106615  tailOffset = 0;
106616  for(i=0; i<nMatch && nDesired>0; i++){
106617    if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
106618    nDesired--;
106619    iCol = aMatch[i].iCol;
106620    zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
106621    nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
106622    iStart = aMatch[i].iStart - 40;
106623    iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
106624    if( iStart<=10 ){
106625      iStart = 0;
106626    }
106627    if( iCol==tailCol && iStart<=tailOffset+20 ){
106628      iStart = tailOffset;
106629    }
106630    if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
106631      fts3SnippetTrimWhiteSpace(&sb);
106632      fts3SnippetAppendWhiteSpace(&sb);
106633      fts3SnippetAppend(&sb, zEllipsis, -1);
106634      fts3SnippetAppendWhiteSpace(&sb);
106635    }
106636    iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
106637    iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
106638    if( iEnd>=nDoc-10 ){
106639      iEnd = nDoc;
106640      tailEllipsis = 0;
106641    }else{
106642      tailEllipsis = 1;
106643    }
106644    while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
106645    while( iStart<iEnd ){
106646      while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
106647             && aMatch[iMatch].iCol<=iCol ){
106648        iMatch++;
106649      }
106650      if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
106651             && aMatch[iMatch].iCol==iCol ){
106652        fts3SnippetAppend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
106653        iStart = aMatch[iMatch].iStart;
106654        fts3SnippetAppend(&sb, zStartMark, -1);
106655        fts3SnippetAppend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
106656        fts3SnippetAppend(&sb, zEndMark, -1);
106657        iStart += aMatch[iMatch].nByte;
106658        for(j=iMatch+1; j<nMatch; j++){
106659          if( aMatch[j].iTerm==aMatch[iMatch].iTerm
106660              && aMatch[j].snStatus==SNIPPET_DESIRED ){
106661            nDesired--;
106662            aMatch[j].snStatus = SNIPPET_IGNORE;
106663          }
106664        }
106665      }else{
106666        fts3SnippetAppend(&sb, &zDoc[iStart], iEnd - iStart);
106667        iStart = iEnd;
106668      }
106669    }
106670    tailCol = iCol;
106671    tailOffset = iEnd;
106672  }
106673  fts3SnippetTrimWhiteSpace(&sb);
106674  if( tailEllipsis ){
106675    fts3SnippetAppendWhiteSpace(&sb);
106676    fts3SnippetAppend(&sb, zEllipsis, -1);
106677  }
106678  pSnippet->zSnippet = sb.z;
106679  pSnippet->nSnippet = sb.z ? sb.nUsed : 0;
106680}
106681
106682SQLITE_PRIVATE void sqlite3Fts3Offsets(
106683  sqlite3_context *pCtx,          /* SQLite function call context */
106684  Fts3Cursor *pCsr                /* Cursor object */
106685){
106686  Snippet *p;                     /* Snippet structure */
106687  int rc = snippetAllOffsets(pCsr, &p);
106688  if( rc==SQLITE_OK ){
106689    snippetOffsetText(p);
106690    if( p->zOffset ){
106691      sqlite3_result_text(pCtx, p->zOffset, p->nOffset, SQLITE_TRANSIENT);
106692    }else{
106693      sqlite3_result_error_nomem(pCtx);
106694    }
106695  }else{
106696    sqlite3_result_error_nomem(pCtx);
106697  }
106698  fts3SnippetFree(p);
106699}
106700
106701SQLITE_PRIVATE void sqlite3Fts3Snippet(
106702  sqlite3_context *pCtx,          /* SQLite function call context */
106703  Fts3Cursor *pCsr,               /* Cursor object */
106704  const char *zStart,             /* Snippet start text - "<b>" */
106705  const char *zEnd,               /* Snippet end text - "</b>" */
106706  const char *zEllipsis           /* Snippet ellipsis text - "<b>...</b>" */
106707){
106708  Snippet *p;                     /* Snippet structure */
106709  int rc = snippetAllOffsets(pCsr, &p);
106710  if( rc==SQLITE_OK ){
106711    snippetText(pCsr, p, zStart, zEnd, zEllipsis);
106712    if( p->zSnippet ){
106713      sqlite3_result_text(pCtx, p->zSnippet, p->nSnippet, SQLITE_TRANSIENT);
106714    }else{
106715      sqlite3_result_error_nomem(pCtx);
106716    }
106717  }else{
106718    sqlite3_result_error_nomem(pCtx);
106719  }
106720  fts3SnippetFree(p);
106721}
106722
106723/*************************************************************************
106724** Below this point is the alternative, experimental snippet() implementation.
106725*/
106726
106727#define SNIPPET_BUFFER_CHUNK  64
106728#define SNIPPET_BUFFER_SIZE   SNIPPET_BUFFER_CHUNK*4
106729#define SNIPPET_BUFFER_MASK   (SNIPPET_BUFFER_SIZE-1)
106730
106731static void fts3GetDeltaPosition(char **pp, int *piPos){
106732  int iVal;
106733  *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
106734  *piPos += (iVal-2);
106735}
106736
106737/*
106738** Iterate through all phrase nodes in an FTS3 query, except those that
106739** are part of a sub-tree that is the right-hand-side of a NOT operator.
106740** For each phrase node found, the supplied callback function is invoked.
106741**
106742** If the callback function returns anything other than SQLITE_OK,
106743** the iteration is abandoned and the error code returned immediately.
106744** Otherwise, SQLITE_OK is returned after a callback has been made for
106745** all eligible phrase nodes.
106746*/
106747static int fts3ExprIterate(
106748  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
106749  int (*x)(Fts3Expr *, void *),   /* Callback function to invoke for phrases */
106750  void *pCtx                      /* Second argument to pass to callback */
106751){
106752  int rc;
106753  int eType = pExpr->eType;
106754  if( eType==FTSQUERY_NOT ){
106755    rc = SQLITE_OK;
106756  }else if( eType!=FTSQUERY_PHRASE ){
106757    assert( pExpr->pLeft && pExpr->pRight );
106758    rc = fts3ExprIterate(pExpr->pLeft, x, pCtx);
106759    if( rc==SQLITE_OK ){
106760      rc = fts3ExprIterate(pExpr->pRight, x, pCtx);
106761    }
106762  }else{
106763    rc = x(pExpr, pCtx);
106764  }
106765  return rc;
106766}
106767
106768typedef struct LoadDoclistCtx LoadDoclistCtx;
106769struct LoadDoclistCtx {
106770  Fts3Table *pTab;                /* FTS3 Table */
106771  int nPhrase;                    /* Number of phrases so far */
106772};
106773
106774static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, void *ctx){
106775  int rc = SQLITE_OK;
106776  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
106777  p->nPhrase++;
106778  if( pExpr->isLoaded==0 ){
106779    rc = sqlite3Fts3ExprLoadDoclist(p->pTab, pExpr);
106780    pExpr->isLoaded = 1;
106781    if( rc==SQLITE_OK && pExpr->aDoclist ){
106782      pExpr->pCurrent = pExpr->aDoclist;
106783      pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent,&pExpr->iCurrent);
106784    }
106785  }
106786  return rc;
106787}
106788
106789static int fts3ExprLoadDoclists(Fts3Cursor *pCsr, int *pnPhrase){
106790  int rc;
106791  LoadDoclistCtx sCtx = {0, 0};
106792  sCtx.pTab = (Fts3Table *)pCsr->base.pVtab;
106793  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
106794  *pnPhrase = sCtx.nPhrase;
106795  return rc;
106796}
106797
106798/*
106799** Each call to this function populates a chunk of a snippet-buffer
106800** SNIPPET_BUFFER_CHUNK bytes in size.
106801**
106802** Return true if the end of the data has been reached (and all subsequent
106803** calls to fts3LoadSnippetBuffer() with the same arguments will be no-ops),
106804** or false otherwise.
106805*/
106806static int fts3LoadSnippetBuffer(
106807  int iPos,                       /* Document token offset to load data for */
106808  u8 *aBuffer,                    /* Circular snippet buffer to populate */
106809  int nList,                      /* Number of position lists in appList */
106810  char **apList,                  /* IN/OUT: nList position list pointers */
106811  int *aiPrev                     /* IN/OUT: Previous positions read */
106812){
106813  int i;
106814  int nFin = 0;
106815
106816  assert( (iPos&(SNIPPET_BUFFER_CHUNK-1))==0 );
106817
106818  memset(&aBuffer[iPos&SNIPPET_BUFFER_MASK], 0, SNIPPET_BUFFER_CHUNK);
106819
106820  for(i=0; i<nList; i++){
106821    int iPrev = aiPrev[i];
106822    char *pList = apList[i];
106823
106824    if( !pList ){
106825      nFin++;
106826      continue;
106827    }
106828
106829    while( iPrev<(iPos+SNIPPET_BUFFER_CHUNK) ){
106830      if( iPrev>=iPos ){
106831        aBuffer[iPrev&SNIPPET_BUFFER_MASK] = (u8)(i+1);
106832      }
106833      if( 0==((*pList)&0xFE) ){
106834        nFin++;
106835        break;
106836      }
106837      fts3GetDeltaPosition(&pList, &iPrev);
106838    }
106839
106840    aiPrev[i] = iPrev;
106841    apList[i] = pList;
106842  }
106843
106844  return (nFin==nList);
106845}
106846
106847typedef struct SnippetCtx SnippetCtx;
106848struct SnippetCtx {
106849  Fts3Cursor *pCsr;
106850  int iCol;
106851  int iPhrase;
106852  int *aiPrev;
106853  int *anToken;
106854  char **apList;
106855};
106856
106857static int fts3SnippetFindPositions(Fts3Expr *pExpr, void *ctx){
106858  SnippetCtx *p = (SnippetCtx *)ctx;
106859  int iPhrase = p->iPhrase++;
106860  char *pCsr;
106861
106862  p->anToken[iPhrase] = pExpr->pPhrase->nToken;
106863  pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
106864
106865  if( pCsr ){
106866    int iVal;
106867    pCsr += sqlite3Fts3GetVarint32(pCsr, &iVal);
106868    p->apList[iPhrase] = pCsr;
106869    p->aiPrev[iPhrase] = iVal-2;
106870  }
106871  return SQLITE_OK;
106872}
106873
106874static void fts3SnippetCnt(
106875  int iIdx,
106876  int nSnippet,
106877  int *anCnt,
106878  u8 *aBuffer,
106879  int *anToken,
106880  u64 *pHlmask
106881){
106882  int iSub =  (iIdx-1)&SNIPPET_BUFFER_MASK;
106883  int iAdd =  (iIdx+nSnippet-1)&SNIPPET_BUFFER_MASK;
106884  int iSub2 = (iIdx+(nSnippet/3)-1)&SNIPPET_BUFFER_MASK;
106885  int iAdd2 = (iIdx+(nSnippet*2/3)-1)&SNIPPET_BUFFER_MASK;
106886
106887  u64 h = *pHlmask;
106888
106889  anCnt[ aBuffer[iSub]  ]--;
106890  anCnt[ aBuffer[iSub2] ]--;
106891  anCnt[ aBuffer[iAdd]  ]++;
106892  anCnt[ aBuffer[iAdd2] ]++;
106893
106894  h = h >> 1;
106895  if( aBuffer[iAdd] ){
106896    int j;
106897    for(j=anToken[aBuffer[iAdd]-1]; j>=1; j--){
106898      h |= (u64)1 << (nSnippet-j);
106899    }
106900  }
106901  *pHlmask = h;
106902}
106903
106904static int fts3SnippetScore(int n, int *anCnt){
106905  int j;
106906  int iScore = 0;
106907  for(j=1; j<=n; j++){
106908    int nCnt = anCnt[j];
106909    iScore += nCnt + (nCnt ? 1000 : 0);
106910  }
106911  return iScore;
106912}
106913
106914static int fts3BestSnippet(
106915  int nSnippet,                   /* Desired snippet length */
106916  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
106917  int iCol,                       /* Index of column to create snippet from */
106918  int *piPos,                     /* OUT: Starting token for best snippet */
106919  u64 *pHlmask                    /* OUT: Highlight mask for best snippet */
106920){
106921  int rc;                         /* Return Code */
106922  u8 aBuffer[SNIPPET_BUFFER_SIZE];/* Circular snippet buffer */
106923  int *aiPrev;                    /* Used by fts3LoadSnippetBuffer() */
106924  int *anToken;                   /* Number of tokens in each phrase */
106925  char **apList;                  /* Array of position lists */
106926  int *anCnt;                     /* Running totals of phrase occurences */
106927  int nList;
106928
106929  int i;
106930
106931  u64 hlmask = 0;                 /* Current mask of highlighted terms */
106932  u64 besthlmask = 0;             /* Mask of highlighted terms for iBestPos */
106933  int iBestPos = 0;               /* Starting position of 'best' snippet */
106934  int iBestScore = 0;             /* Score of best snippet higher->better */
106935  SnippetCtx sCtx;
106936
106937  /* Iterate through the phrases in the expression to count them. The same
106938  ** callback makes sure the doclists are loaded for each phrase.
106939  */
106940  rc = fts3ExprLoadDoclists(pCsr, &nList);
106941  if( rc!=SQLITE_OK ){
106942    return rc;
106943  }
106944
106945  /* Now that it is known how many phrases there are, allocate and zero
106946  ** the required arrays using malloc().
106947  */
106948  apList = sqlite3_malloc(
106949      sizeof(u8*)*nList +         /* apList */
106950      sizeof(int)*(nList) +       /* anToken */
106951      sizeof(int)*nList +         /* aiPrev */
106952      sizeof(int)*(nList+1)       /* anCnt */
106953  );
106954  if( !apList ){
106955    return SQLITE_NOMEM;
106956  }
106957  memset(apList, 0, sizeof(u8*)*nList+sizeof(int)*nList+sizeof(int)*nList);
106958  anToken = (int *)&apList[nList];
106959  aiPrev = &anToken[nList];
106960  anCnt = &aiPrev[nList];
106961
106962  /* Initialize the contents of the aiPrev and aiList arrays. */
106963  sCtx.pCsr = pCsr;
106964  sCtx.iCol = iCol;
106965  sCtx.apList = apList;
106966  sCtx.aiPrev = aiPrev;
106967  sCtx.anToken = anToken;
106968  sCtx.iPhrase = 0;
106969  (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sCtx);
106970
106971  /* Load the first two chunks of data into the buffer. */
106972  memset(aBuffer, 0, SNIPPET_BUFFER_SIZE);
106973  fts3LoadSnippetBuffer(0, aBuffer, nList, apList, aiPrev);
106974  fts3LoadSnippetBuffer(SNIPPET_BUFFER_CHUNK, aBuffer, nList, apList, aiPrev);
106975
106976  /* Set the initial contents of the highlight-mask and anCnt[] array. */
106977  for(i=1-nSnippet; i<=0; i++){
106978    fts3SnippetCnt(i, nSnippet, anCnt, aBuffer, anToken, &hlmask);
106979  }
106980  iBestScore = fts3SnippetScore(nList, anCnt);
106981  besthlmask = hlmask;
106982  iBestPos = 0;
106983
106984  for(i=1; 1; i++){
106985    int iScore;
106986
106987    if( 0==(i&(SNIPPET_BUFFER_CHUNK-1)) ){
106988      int iLoad = i + SNIPPET_BUFFER_CHUNK;
106989      if( fts3LoadSnippetBuffer(iLoad, aBuffer, nList, apList, aiPrev) ) break;
106990    }
106991
106992    /* Figure out how highly a snippet starting at token offset i scores
106993    ** according to fts3SnippetScore(). If it is higher than any previously
106994    ** considered position, save the current position, score and hlmask as
106995    ** the best snippet candidate found so far.
106996    */
106997    fts3SnippetCnt(i, nSnippet, anCnt, aBuffer, anToken, &hlmask);
106998    iScore = fts3SnippetScore(nList, anCnt);
106999    if( iScore>iBestScore ){
107000      iBestPos = i;
107001      iBestScore = iScore;
107002      besthlmask = hlmask;
107003    }
107004  }
107005
107006  sqlite3_free(apList);
107007  *piPos = iBestPos;
107008  *pHlmask = besthlmask;
107009  return SQLITE_OK;
107010}
107011
107012typedef struct StrBuffer StrBuffer;
107013struct StrBuffer {
107014  char *z;
107015  int n;
107016  int nAlloc;
107017};
107018
107019static int fts3StringAppend(
107020  StrBuffer *pStr,
107021  const char *zAppend,
107022  int nAppend
107023){
107024  if( nAppend<0 ){
107025    nAppend = (int)strlen(zAppend);
107026  }
107027
107028  if( pStr->n+nAppend+1>=pStr->nAlloc ){
107029    int nAlloc = pStr->nAlloc+nAppend+100;
107030    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
107031    if( !zNew ){
107032      return SQLITE_NOMEM;
107033    }
107034    pStr->z = zNew;
107035    pStr->nAlloc = nAlloc;
107036  }
107037
107038  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
107039  pStr->n += nAppend;
107040  pStr->z[pStr->n] = '\0';
107041
107042  return SQLITE_OK;
107043}
107044
107045static int fts3SnippetText(
107046  Fts3Cursor *pCsr,               /* FTS3 Cursor */
107047  const char *zDoc,               /* Document to extract snippet from */
107048  int nDoc,                       /* Size of zDoc in bytes */
107049  int nSnippet,                   /* Number of tokens in extracted snippet */
107050  int iPos,                       /* Index of first document token in snippet */
107051  u64 hlmask,                     /* Bitmask of terms to highlight in snippet */
107052  const char *zOpen,              /* String inserted before highlighted term */
107053  const char *zClose,             /* String inserted after highlighted term */
107054  const char *zEllipsis,
107055  char **pzSnippet                /* OUT: Snippet text */
107056){
107057  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
107058  int rc;                         /* Return code */
107059  int iCurrent = 0;
107060  int iStart = 0;
107061  int iEnd;
107062
107063  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
107064  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
107065  const char *ZDUMMY;             /* Dummy arguments used with tokenizer */
107066  int DUMMY1, DUMMY2, DUMMY3;     /* Dummy arguments used with tokenizer */
107067
107068  StrBuffer res = {0, 0, 0};   /* Result string */
107069
107070  /* Open a token cursor on the document. Read all tokens up to and
107071  ** including token iPos (the first token of the snippet). Set variable
107072  ** iStart to the byte offset in zDoc of the start of token iPos.
107073  */
107074  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
107075  rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
107076  while( rc==SQLITE_OK && iCurrent<iPos ){
107077    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iStart, &DUMMY2, &iCurrent);
107078  }
107079  iEnd = iStart;
107080
107081  if( rc==SQLITE_OK && iStart>0 ){
107082    rc = fts3StringAppend(&res, zEllipsis, -1);
107083  }
107084
107085  while( rc==SQLITE_OK ){
107086    int iBegin;
107087    int iFin;
107088    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
107089
107090    if( rc==SQLITE_OK ){
107091      if( iCurrent>=(iPos+nSnippet) ){
107092        rc = SQLITE_DONE;
107093      }else{
107094        iEnd = iFin;
107095        if( hlmask & ((u64)1 << (iCurrent-iPos)) ){
107096          if( fts3StringAppend(&res, &zDoc[iStart], iBegin-iStart)
107097           || fts3StringAppend(&res, zOpen, -1)
107098           || fts3StringAppend(&res, &zDoc[iBegin], iEnd-iBegin)
107099           || fts3StringAppend(&res, zClose, -1)
107100          ){
107101            rc = SQLITE_NOMEM;
107102          }
107103          iStart = iEnd;
107104        }
107105      }
107106    }
107107  }
107108  assert( rc!=SQLITE_OK );
107109  if( rc==SQLITE_DONE ){
107110    rc = fts3StringAppend(&res, &zDoc[iStart], iEnd-iStart);
107111    if( rc==SQLITE_OK ){
107112      rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
107113      if( rc==SQLITE_OK ){
107114        rc = fts3StringAppend(&res, zEllipsis, -1);
107115      }else if( rc==SQLITE_DONE ){
107116        rc = fts3StringAppend(&res, &zDoc[iEnd], -1);
107117      }
107118    }
107119  }
107120
107121  pMod->xClose(pC);
107122  if( rc!=SQLITE_OK ){
107123    sqlite3_free(res.z);
107124  }else{
107125    *pzSnippet = res.z;
107126  }
107127  return rc;
107128}
107129
107130
107131/*
107132** An instance of this structure is used to collect the 'global' part of
107133** the matchinfo statistics. The 'global' part consists of the following:
107134**
107135**   1. The number of phrases in the query (nPhrase).
107136**
107137**   2. The number of columns in the FTS3 table (nCol).
107138**
107139**   3. A matrix of (nPhrase*nCol) integers containing the sum of the
107140**      number of hits for each phrase in each column across all rows
107141**      of the table.
107142**
107143** The total size of the global matchinfo array, assuming the number of
107144** columns is N and the number of phrases is P is:
107145**
107146**   2 + P*(N+1)
107147**
107148** The number of hits for the 3rd phrase in the second column is found
107149** using the expression:
107150**
107151**   aGlobal[2 + P*(1+2) + 1]
107152*/
107153typedef struct MatchInfo MatchInfo;
107154struct MatchInfo {
107155  Fts3Table *pTab;                /* FTS3 Table */
107156  Fts3Cursor *pCursor;            /* FTS3 Cursor */
107157  int iPhrase;                    /* Number of phrases so far */
107158  int nCol;                       /* Number of columns in table */
107159  u32 *aGlobal;                   /* Pre-allocated buffer */
107160};
107161
107162/*
107163** This function is used to count the entries in a column-list (delta-encoded
107164** list of term offsets within a single column of a single row).
107165*/
107166static int fts3ColumnlistCount(char **ppCollist){
107167  char *pEnd = *ppCollist;
107168  char c = 0;
107169  int nEntry = 0;
107170
107171  /* A column-list is terminated by either a 0x01 or 0x00. */
107172  while( 0xFE & (*pEnd | c) ){
107173    c = *pEnd++ & 0x80;
107174    if( !c ) nEntry++;
107175  }
107176
107177  *ppCollist = pEnd;
107178  return nEntry;
107179}
107180
107181static void fts3LoadColumnlistCounts(char **pp, u32 *aOut){
107182  char *pCsr = *pp;
107183  while( *pCsr ){
107184    sqlite3_int64 iCol = 0;
107185    if( *pCsr==0x01 ){
107186      pCsr++;
107187      pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
107188    }
107189    aOut[iCol] += fts3ColumnlistCount(&pCsr);
107190  }
107191  pCsr++;
107192  *pp = pCsr;
107193}
107194
107195/*
107196** fts3ExprIterate() callback used to collect the "global" matchinfo stats
107197** for a single query.
107198*/
107199static int fts3ExprGlobalMatchinfoCb(
107200  Fts3Expr *pExpr,                /* Phrase expression node */
107201  void *pCtx                      /* Pointer to MatchInfo structure */
107202){
107203  MatchInfo *p = (MatchInfo *)pCtx;
107204  char *pCsr;
107205  char *pEnd;
107206  const int iStart = 2 + p->nCol*p->iPhrase;
107207
107208  assert( pExpr->isLoaded );
107209
107210  /* Fill in the global hit count matrix row for this phrase. */
107211  pCsr = pExpr->aDoclist;
107212  pEnd = &pExpr->aDoclist[pExpr->nDoclist];
107213  while( pCsr<pEnd ){
107214    while( *pCsr++ & 0x80 );
107215    fts3LoadColumnlistCounts(&pCsr, &p->aGlobal[iStart]);
107216  }
107217
107218  p->iPhrase++;
107219  return SQLITE_OK;
107220}
107221
107222static int fts3ExprLocalMatchinfoCb(
107223  Fts3Expr *pExpr,                /* Phrase expression node */
107224  void *pCtx                      /* Pointer to MatchInfo structure */
107225){
107226  MatchInfo *p = (MatchInfo *)pCtx;
107227  int iPhrase = p->iPhrase++;
107228
107229  if( pExpr->aDoclist ){
107230    char *pCsr;
107231    int iOffset = 2 + p->nCol*(p->aGlobal[0]+iPhrase);
107232
107233    memset(&p->aGlobal[iOffset], 0, p->nCol*sizeof(u32));
107234    pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
107235    if( pCsr ) fts3LoadColumnlistCounts(&pCsr, &p->aGlobal[iOffset]);
107236  }
107237
107238  return SQLITE_OK;
107239}
107240
107241/*
107242** Populate pCsr->aMatchinfo[] with data for the current row. The 'matchinfo'
107243** data is an array of 32-bit unsigned integers (C type u32).
107244*/
107245static int fts3GetMatchinfo(Fts3Cursor *pCsr){
107246  MatchInfo g;
107247  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
107248  if( pCsr->aMatchinfo==0 ){
107249    int rc;
107250    int nPhrase;
107251    int nMatchinfo;
107252
107253    g.pTab = pTab;
107254    g.nCol = pTab->nColumn;
107255    g.iPhrase = 0;
107256    rc = fts3ExprLoadDoclists(pCsr, &nPhrase);
107257    if( rc!=SQLITE_OK ){
107258      return rc;
107259    }
107260
107261    nMatchinfo = 2 + 2*g.nCol*nPhrase;
107262
107263    g.iPhrase = 0;
107264    g.aGlobal = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo);
107265    if( !g.aGlobal ){
107266      return SQLITE_NOMEM;
107267    }
107268    memset(g.aGlobal, 0, sizeof(u32)*nMatchinfo);
107269
107270    g.aGlobal[0] = nPhrase;
107271    g.aGlobal[1] = g.nCol;
107272    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprGlobalMatchinfoCb, (void *)&g);
107273
107274    pCsr->aMatchinfo = g.aGlobal;
107275  }
107276
107277  g.pTab = pTab;
107278  g.pCursor = pCsr;
107279  g.nCol = pTab->nColumn;
107280  g.iPhrase = 0;
107281  g.aGlobal = pCsr->aMatchinfo;
107282
107283  if( pCsr->isMatchinfoOk ){
107284    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLocalMatchinfoCb, (void *)&g);
107285    pCsr->isMatchinfoOk = 0;
107286  }
107287
107288  return SQLITE_OK;
107289}
107290
107291SQLITE_PRIVATE void sqlite3Fts3Snippet2(
107292  sqlite3_context *pCtx,          /* SQLite function call context */
107293  Fts3Cursor *pCsr,               /* Cursor object */
107294  const char *zStart,             /* Snippet start text - "<b>" */
107295  const char *zEnd,               /* Snippet end text - "</b>" */
107296  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
107297  int iCol,                       /* Extract snippet from this column */
107298  int nToken                      /* Approximate number of tokens in snippet */
107299){
107300  int rc;
107301  int iPos = 0;
107302  u64 hlmask = 0;
107303  char *z = 0;
107304  int nDoc;
107305  const char *zDoc;
107306
107307  rc = fts3BestSnippet(nToken, pCsr, iCol, &iPos, &hlmask);
107308
107309  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
107310  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
107311
107312  if( rc==SQLITE_OK ){
107313    rc = fts3SnippetText(
107314        pCsr, zDoc, nDoc, nToken, iPos, hlmask, zStart, zEnd, zEllipsis, &z);
107315  }
107316  if( rc!=SQLITE_OK ){
107317    sqlite3_result_error_code(pCtx, rc);
107318  }else{
107319    sqlite3_result_text(pCtx, z, -1, sqlite3_free);
107320  }
107321}
107322
107323SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *pContext, Fts3Cursor *pCsr){
107324  int rc = fts3GetMatchinfo(pCsr);
107325  if( rc!=SQLITE_OK ){
107326    sqlite3_result_error_code(pContext, rc);
107327  }else{
107328    int n = sizeof(u32)*(2+pCsr->aMatchinfo[0]*pCsr->aMatchinfo[1]*2);
107329    sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
107330  }
107331}
107332
107333#endif
107334
107335/************** End of fts3_snippet.c ****************************************/
107336/************** Begin file rtree.c *******************************************/
107337/*
107338** 2001 September 15
107339**
107340** The author disclaims copyright to this source code.  In place of
107341** a legal notice, here is a blessing:
107342**
107343**    May you do good and not evil.
107344**    May you find forgiveness for yourself and forgive others.
107345**    May you share freely, never taking more than you give.
107346**
107347*************************************************************************
107348** This file contains code for implementations of the r-tree and r*-tree
107349** algorithms packaged as an SQLite virtual table module.
107350*/
107351
107352#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
107353
107354/*
107355** This file contains an implementation of a couple of different variants
107356** of the r-tree algorithm. See the README file for further details. The
107357** same data-structure is used for all, but the algorithms for insert and
107358** delete operations vary. The variants used are selected at compile time
107359** by defining the following symbols:
107360*/
107361
107362/* Either, both or none of the following may be set to activate
107363** r*tree variant algorithms.
107364*/
107365#define VARIANT_RSTARTREE_CHOOSESUBTREE 0
107366#define VARIANT_RSTARTREE_REINSERT      1
107367
107368/*
107369** Exactly one of the following must be set to 1.
107370*/
107371#define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
107372#define VARIANT_GUTTMAN_LINEAR_SPLIT    0
107373#define VARIANT_RSTARTREE_SPLIT         1
107374
107375#define VARIANT_GUTTMAN_SPLIT \
107376        (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
107377
107378#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
107379  #define PickNext QuadraticPickNext
107380  #define PickSeeds QuadraticPickSeeds
107381  #define AssignCells splitNodeGuttman
107382#endif
107383#if VARIANT_GUTTMAN_LINEAR_SPLIT
107384  #define PickNext LinearPickNext
107385  #define PickSeeds LinearPickSeeds
107386  #define AssignCells splitNodeGuttman
107387#endif
107388#if VARIANT_RSTARTREE_SPLIT
107389  #define AssignCells splitNodeStartree
107390#endif
107391
107392
107393#ifndef SQLITE_CORE
107394  SQLITE_EXTENSION_INIT1
107395#else
107396#endif
107397
107398
107399#ifndef SQLITE_AMALGAMATION
107400typedef sqlite3_int64 i64;
107401typedef unsigned char u8;
107402typedef unsigned int u32;
107403#endif
107404
107405typedef struct Rtree Rtree;
107406typedef struct RtreeCursor RtreeCursor;
107407typedef struct RtreeNode RtreeNode;
107408typedef struct RtreeCell RtreeCell;
107409typedef struct RtreeConstraint RtreeConstraint;
107410typedef union RtreeCoord RtreeCoord;
107411
107412/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
107413#define RTREE_MAX_DIMENSIONS 5
107414
107415/* Size of hash table Rtree.aHash. This hash table is not expected to
107416** ever contain very many entries, so a fixed number of buckets is
107417** used.
107418*/
107419#define HASHSIZE 128
107420
107421/*
107422** An rtree virtual-table object.
107423*/
107424struct Rtree {
107425  sqlite3_vtab base;
107426  sqlite3 *db;                /* Host database connection */
107427  int iNodeSize;              /* Size in bytes of each node in the node table */
107428  int nDim;                   /* Number of dimensions */
107429  int nBytesPerCell;          /* Bytes consumed per cell */
107430  int iDepth;                 /* Current depth of the r-tree structure */
107431  char *zDb;                  /* Name of database containing r-tree table */
107432  char *zName;                /* Name of r-tree table */
107433  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
107434  int nBusy;                  /* Current number of users of this structure */
107435
107436  /* List of nodes removed during a CondenseTree operation. List is
107437  ** linked together via the pointer normally used for hash chains -
107438  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
107439  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
107440  */
107441  RtreeNode *pDeleted;
107442  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
107443
107444  /* Statements to read/write/delete a record from xxx_node */
107445  sqlite3_stmt *pReadNode;
107446  sqlite3_stmt *pWriteNode;
107447  sqlite3_stmt *pDeleteNode;
107448
107449  /* Statements to read/write/delete a record from xxx_rowid */
107450  sqlite3_stmt *pReadRowid;
107451  sqlite3_stmt *pWriteRowid;
107452  sqlite3_stmt *pDeleteRowid;
107453
107454  /* Statements to read/write/delete a record from xxx_parent */
107455  sqlite3_stmt *pReadParent;
107456  sqlite3_stmt *pWriteParent;
107457  sqlite3_stmt *pDeleteParent;
107458
107459  int eCoordType;
107460};
107461
107462/* Possible values for eCoordType: */
107463#define RTREE_COORD_REAL32 0
107464#define RTREE_COORD_INT32  1
107465
107466/*
107467** The minimum number of cells allowed for a node is a third of the
107468** maximum. In Gutman's notation:
107469**
107470**     m = M/3
107471**
107472** If an R*-tree "Reinsert" operation is required, the same number of
107473** cells are removed from the overfull node and reinserted into the tree.
107474*/
107475#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
107476#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
107477#define RTREE_MAXCELLS 51
107478
107479/*
107480** An rtree cursor object.
107481*/
107482struct RtreeCursor {
107483  sqlite3_vtab_cursor base;
107484  RtreeNode *pNode;                 /* Node cursor is currently pointing at */
107485  int iCell;                        /* Index of current cell in pNode */
107486  int iStrategy;                    /* Copy of idxNum search parameter */
107487  int nConstraint;                  /* Number of entries in aConstraint */
107488  RtreeConstraint *aConstraint;     /* Search constraints. */
107489};
107490
107491union RtreeCoord {
107492  float f;
107493  int i;
107494};
107495
107496/*
107497** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
107498** formatted as a double. This macro assumes that local variable pRtree points
107499** to the Rtree structure associated with the RtreeCoord.
107500*/
107501#define DCOORD(coord) (                           \
107502  (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
107503    ((double)coord.f) :                           \
107504    ((double)coord.i)                             \
107505)
107506
107507/*
107508** A search constraint.
107509*/
107510struct RtreeConstraint {
107511  int iCoord;                       /* Index of constrained coordinate */
107512  int op;                           /* Constraining operation */
107513  double rValue;                    /* Constraint value. */
107514};
107515
107516/* Possible values for RtreeConstraint.op */
107517#define RTREE_EQ 0x41
107518#define RTREE_LE 0x42
107519#define RTREE_LT 0x43
107520#define RTREE_GE 0x44
107521#define RTREE_GT 0x45
107522
107523/*
107524** An rtree structure node.
107525**
107526** Data format (RtreeNode.zData):
107527**
107528**   1. If the node is the root node (node 1), then the first 2 bytes
107529**      of the node contain the tree depth as a big-endian integer.
107530**      For non-root nodes, the first 2 bytes are left unused.
107531**
107532**   2. The next 2 bytes contain the number of entries currently
107533**      stored in the node.
107534**
107535**   3. The remainder of the node contains the node entries. Each entry
107536**      consists of a single 8-byte integer followed by an even number
107537**      of 4-byte coordinates. For leaf nodes the integer is the rowid
107538**      of a record. For internal nodes it is the node number of a
107539**      child page.
107540*/
107541struct RtreeNode {
107542  RtreeNode *pParent;               /* Parent node */
107543  i64 iNode;
107544  int nRef;
107545  int isDirty;
107546  u8 *zData;
107547  RtreeNode *pNext;                 /* Next node in this hash chain */
107548};
107549#define NCELL(pNode) readInt16(&(pNode)->zData[2])
107550
107551/*
107552** Structure to store a deserialized rtree record.
107553*/
107554struct RtreeCell {
107555  i64 iRowid;
107556  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
107557};
107558
107559#ifndef MAX
107560# define MAX(x,y) ((x) < (y) ? (y) : (x))
107561#endif
107562#ifndef MIN
107563# define MIN(x,y) ((x) > (y) ? (y) : (x))
107564#endif
107565
107566/*
107567** Functions to deserialize a 16 bit integer, 32 bit real number and
107568** 64 bit integer. The deserialized value is returned.
107569*/
107570static int readInt16(u8 *p){
107571  return (p[0]<<8) + p[1];
107572}
107573static void readCoord(u8 *p, RtreeCoord *pCoord){
107574  u32 i = (
107575    (((u32)p[0]) << 24) +
107576    (((u32)p[1]) << 16) +
107577    (((u32)p[2]) <<  8) +
107578    (((u32)p[3]) <<  0)
107579  );
107580  *(u32 *)pCoord = i;
107581}
107582static i64 readInt64(u8 *p){
107583  return (
107584    (((i64)p[0]) << 56) +
107585    (((i64)p[1]) << 48) +
107586    (((i64)p[2]) << 40) +
107587    (((i64)p[3]) << 32) +
107588    (((i64)p[4]) << 24) +
107589    (((i64)p[5]) << 16) +
107590    (((i64)p[6]) <<  8) +
107591    (((i64)p[7]) <<  0)
107592  );
107593}
107594
107595/*
107596** Functions to serialize a 16 bit integer, 32 bit real number and
107597** 64 bit integer. The value returned is the number of bytes written
107598** to the argument buffer (always 2, 4 and 8 respectively).
107599*/
107600static int writeInt16(u8 *p, int i){
107601  p[0] = (i>> 8)&0xFF;
107602  p[1] = (i>> 0)&0xFF;
107603  return 2;
107604}
107605static int writeCoord(u8 *p, RtreeCoord *pCoord){
107606  u32 i;
107607  assert( sizeof(RtreeCoord)==4 );
107608  assert( sizeof(u32)==4 );
107609  i = *(u32 *)pCoord;
107610  p[0] = (i>>24)&0xFF;
107611  p[1] = (i>>16)&0xFF;
107612  p[2] = (i>> 8)&0xFF;
107613  p[3] = (i>> 0)&0xFF;
107614  return 4;
107615}
107616static int writeInt64(u8 *p, i64 i){
107617  p[0] = (i>>56)&0xFF;
107618  p[1] = (i>>48)&0xFF;
107619  p[2] = (i>>40)&0xFF;
107620  p[3] = (i>>32)&0xFF;
107621  p[4] = (i>>24)&0xFF;
107622  p[5] = (i>>16)&0xFF;
107623  p[6] = (i>> 8)&0xFF;
107624  p[7] = (i>> 0)&0xFF;
107625  return 8;
107626}
107627
107628/*
107629** Increment the reference count of node p.
107630*/
107631static void nodeReference(RtreeNode *p){
107632  if( p ){
107633    p->nRef++;
107634  }
107635}
107636
107637/*
107638** Clear the content of node p (set all bytes to 0x00).
107639*/
107640static void nodeZero(Rtree *pRtree, RtreeNode *p){
107641  if( p ){
107642    memset(&p->zData[2], 0, pRtree->iNodeSize-2);
107643    p->isDirty = 1;
107644  }
107645}
107646
107647/*
107648** Given a node number iNode, return the corresponding key to use
107649** in the Rtree.aHash table.
107650*/
107651static int nodeHash(i64 iNode){
107652  return (
107653    (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
107654    (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
107655  ) % HASHSIZE;
107656}
107657
107658/*
107659** Search the node hash table for node iNode. If found, return a pointer
107660** to it. Otherwise, return 0.
107661*/
107662static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
107663  RtreeNode *p;
107664  assert( iNode!=0 );
107665  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
107666  return p;
107667}
107668
107669/*
107670** Add node pNode to the node hash table.
107671*/
107672static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
107673  if( pNode ){
107674    int iHash;
107675    assert( pNode->pNext==0 );
107676    iHash = nodeHash(pNode->iNode);
107677    pNode->pNext = pRtree->aHash[iHash];
107678    pRtree->aHash[iHash] = pNode;
107679  }
107680}
107681
107682/*
107683** Remove node pNode from the node hash table.
107684*/
107685static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
107686  RtreeNode **pp;
107687  if( pNode->iNode!=0 ){
107688    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
107689    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
107690    *pp = pNode->pNext;
107691    pNode->pNext = 0;
107692  }
107693}
107694
107695/*
107696** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
107697** indicating that node has not yet been assigned a node number. It is
107698** assigned a node number when nodeWrite() is called to write the
107699** node contents out to the database.
107700*/
107701static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
107702  RtreeNode *pNode;
107703  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
107704  if( pNode ){
107705    memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
107706    pNode->zData = (u8 *)&pNode[1];
107707    pNode->nRef = 1;
107708    pNode->pParent = pParent;
107709    pNode->isDirty = 1;
107710    nodeReference(pParent);
107711  }
107712  return pNode;
107713}
107714
107715/*
107716** Obtain a reference to an r-tree node.
107717*/
107718static int
107719nodeAcquire(
107720  Rtree *pRtree,             /* R-tree structure */
107721  i64 iNode,                 /* Node number to load */
107722  RtreeNode *pParent,        /* Either the parent node or NULL */
107723  RtreeNode **ppNode         /* OUT: Acquired node */
107724){
107725  int rc;
107726  RtreeNode *pNode;
107727
107728  /* Check if the requested node is already in the hash table. If so,
107729  ** increase its reference count and return it.
107730  */
107731  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
107732    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
107733    if( pParent && !pNode->pParent ){
107734      nodeReference(pParent);
107735      pNode->pParent = pParent;
107736    }
107737    pNode->nRef++;
107738    *ppNode = pNode;
107739    return SQLITE_OK;
107740  }
107741
107742  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
107743  if( !pNode ){
107744    *ppNode = 0;
107745    return SQLITE_NOMEM;
107746  }
107747  pNode->pParent = pParent;
107748  pNode->zData = (u8 *)&pNode[1];
107749  pNode->nRef = 1;
107750  pNode->iNode = iNode;
107751  pNode->isDirty = 0;
107752  pNode->pNext = 0;
107753
107754  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
107755  rc = sqlite3_step(pRtree->pReadNode);
107756  if( rc==SQLITE_ROW ){
107757    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
107758    memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
107759    nodeReference(pParent);
107760  }else{
107761    sqlite3_free(pNode);
107762    pNode = 0;
107763  }
107764
107765  *ppNode = pNode;
107766  rc = sqlite3_reset(pRtree->pReadNode);
107767
107768  if( rc==SQLITE_OK && iNode==1 ){
107769    pRtree->iDepth = readInt16(pNode->zData);
107770  }
107771
107772  assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
107773  nodeHashInsert(pRtree, pNode);
107774
107775  return rc;
107776}
107777
107778/*
107779** Overwrite cell iCell of node pNode with the contents of pCell.
107780*/
107781static void nodeOverwriteCell(
107782  Rtree *pRtree,
107783  RtreeNode *pNode,
107784  RtreeCell *pCell,
107785  int iCell
107786){
107787  int ii;
107788  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
107789  p += writeInt64(p, pCell->iRowid);
107790  for(ii=0; ii<(pRtree->nDim*2); ii++){
107791    p += writeCoord(p, &pCell->aCoord[ii]);
107792  }
107793  pNode->isDirty = 1;
107794}
107795
107796/*
107797** Remove cell the cell with index iCell from node pNode.
107798*/
107799static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
107800  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
107801  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
107802  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
107803  memmove(pDst, pSrc, nByte);
107804  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
107805  pNode->isDirty = 1;
107806}
107807
107808/*
107809** Insert the contents of cell pCell into node pNode. If the insert
107810** is successful, return SQLITE_OK.
107811**
107812** If there is not enough free space in pNode, return SQLITE_FULL.
107813*/
107814static int
107815nodeInsertCell(
107816  Rtree *pRtree,
107817  RtreeNode *pNode,
107818  RtreeCell *pCell
107819){
107820  int nCell;                    /* Current number of cells in pNode */
107821  int nMaxCell;                 /* Maximum number of cells for pNode */
107822
107823  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
107824  nCell = NCELL(pNode);
107825
107826  assert(nCell<=nMaxCell);
107827
107828  if( nCell<nMaxCell ){
107829    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
107830    writeInt16(&pNode->zData[2], nCell+1);
107831    pNode->isDirty = 1;
107832  }
107833
107834  return (nCell==nMaxCell);
107835}
107836
107837/*
107838** If the node is dirty, write it out to the database.
107839*/
107840static int
107841nodeWrite(Rtree *pRtree, RtreeNode *pNode){
107842  int rc = SQLITE_OK;
107843  if( pNode->isDirty ){
107844    sqlite3_stmt *p = pRtree->pWriteNode;
107845    if( pNode->iNode ){
107846      sqlite3_bind_int64(p, 1, pNode->iNode);
107847    }else{
107848      sqlite3_bind_null(p, 1);
107849    }
107850    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
107851    sqlite3_step(p);
107852    pNode->isDirty = 0;
107853    rc = sqlite3_reset(p);
107854    if( pNode->iNode==0 && rc==SQLITE_OK ){
107855      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
107856      nodeHashInsert(pRtree, pNode);
107857    }
107858  }
107859  return rc;
107860}
107861
107862/*
107863** Release a reference to a node. If the node is dirty and the reference
107864** count drops to zero, the node data is written to the database.
107865*/
107866static int
107867nodeRelease(Rtree *pRtree, RtreeNode *pNode){
107868  int rc = SQLITE_OK;
107869  if( pNode ){
107870    assert( pNode->nRef>0 );
107871    pNode->nRef--;
107872    if( pNode->nRef==0 ){
107873      if( pNode->iNode==1 ){
107874        pRtree->iDepth = -1;
107875      }
107876      if( pNode->pParent ){
107877        rc = nodeRelease(pRtree, pNode->pParent);
107878      }
107879      if( rc==SQLITE_OK ){
107880        rc = nodeWrite(pRtree, pNode);
107881      }
107882      nodeHashDelete(pRtree, pNode);
107883      sqlite3_free(pNode);
107884    }
107885  }
107886  return rc;
107887}
107888
107889/*
107890** Return the 64-bit integer value associated with cell iCell of
107891** node pNode. If pNode is a leaf node, this is a rowid. If it is
107892** an internal node, then the 64-bit integer is a child page number.
107893*/
107894static i64 nodeGetRowid(
107895  Rtree *pRtree,
107896  RtreeNode *pNode,
107897  int iCell
107898){
107899  assert( iCell<NCELL(pNode) );
107900  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
107901}
107902
107903/*
107904** Return coordinate iCoord from cell iCell in node pNode.
107905*/
107906static void nodeGetCoord(
107907  Rtree *pRtree,
107908  RtreeNode *pNode,
107909  int iCell,
107910  int iCoord,
107911  RtreeCoord *pCoord           /* Space to write result to */
107912){
107913  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
107914}
107915
107916/*
107917** Deserialize cell iCell of node pNode. Populate the structure pointed
107918** to by pCell with the results.
107919*/
107920static void nodeGetCell(
107921  Rtree *pRtree,
107922  RtreeNode *pNode,
107923  int iCell,
107924  RtreeCell *pCell
107925){
107926  int ii;
107927  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
107928  for(ii=0; ii<pRtree->nDim*2; ii++){
107929    nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
107930  }
107931}
107932
107933
107934/* Forward declaration for the function that does the work of
107935** the virtual table module xCreate() and xConnect() methods.
107936*/
107937static int rtreeInit(
107938  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
107939);
107940
107941/*
107942** Rtree virtual table module xCreate method.
107943*/
107944static int rtreeCreate(
107945  sqlite3 *db,
107946  void *pAux,
107947  int argc, const char *const*argv,
107948  sqlite3_vtab **ppVtab,
107949  char **pzErr
107950){
107951  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
107952}
107953
107954/*
107955** Rtree virtual table module xConnect method.
107956*/
107957static int rtreeConnect(
107958  sqlite3 *db,
107959  void *pAux,
107960  int argc, const char *const*argv,
107961  sqlite3_vtab **ppVtab,
107962  char **pzErr
107963){
107964  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
107965}
107966
107967/*
107968** Increment the r-tree reference count.
107969*/
107970static void rtreeReference(Rtree *pRtree){
107971  pRtree->nBusy++;
107972}
107973
107974/*
107975** Decrement the r-tree reference count. When the reference count reaches
107976** zero the structure is deleted.
107977*/
107978static void rtreeRelease(Rtree *pRtree){
107979  pRtree->nBusy--;
107980  if( pRtree->nBusy==0 ){
107981    sqlite3_finalize(pRtree->pReadNode);
107982    sqlite3_finalize(pRtree->pWriteNode);
107983    sqlite3_finalize(pRtree->pDeleteNode);
107984    sqlite3_finalize(pRtree->pReadRowid);
107985    sqlite3_finalize(pRtree->pWriteRowid);
107986    sqlite3_finalize(pRtree->pDeleteRowid);
107987    sqlite3_finalize(pRtree->pReadParent);
107988    sqlite3_finalize(pRtree->pWriteParent);
107989    sqlite3_finalize(pRtree->pDeleteParent);
107990    sqlite3_free(pRtree);
107991  }
107992}
107993
107994/*
107995** Rtree virtual table module xDisconnect method.
107996*/
107997static int rtreeDisconnect(sqlite3_vtab *pVtab){
107998  rtreeRelease((Rtree *)pVtab);
107999  return SQLITE_OK;
108000}
108001
108002/*
108003** Rtree virtual table module xDestroy method.
108004*/
108005static int rtreeDestroy(sqlite3_vtab *pVtab){
108006  Rtree *pRtree = (Rtree *)pVtab;
108007  int rc;
108008  char *zCreate = sqlite3_mprintf(
108009    "DROP TABLE '%q'.'%q_node';"
108010    "DROP TABLE '%q'.'%q_rowid';"
108011    "DROP TABLE '%q'.'%q_parent';",
108012    pRtree->zDb, pRtree->zName,
108013    pRtree->zDb, pRtree->zName,
108014    pRtree->zDb, pRtree->zName
108015  );
108016  if( !zCreate ){
108017    rc = SQLITE_NOMEM;
108018  }else{
108019    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
108020    sqlite3_free(zCreate);
108021  }
108022  if( rc==SQLITE_OK ){
108023    rtreeRelease(pRtree);
108024  }
108025
108026  return rc;
108027}
108028
108029/*
108030** Rtree virtual table module xOpen method.
108031*/
108032static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
108033  int rc = SQLITE_NOMEM;
108034  RtreeCursor *pCsr;
108035
108036  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
108037  if( pCsr ){
108038    memset(pCsr, 0, sizeof(RtreeCursor));
108039    pCsr->base.pVtab = pVTab;
108040    rc = SQLITE_OK;
108041  }
108042  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
108043
108044  return rc;
108045}
108046
108047/*
108048** Rtree virtual table module xClose method.
108049*/
108050static int rtreeClose(sqlite3_vtab_cursor *cur){
108051  Rtree *pRtree = (Rtree *)(cur->pVtab);
108052  int rc;
108053  RtreeCursor *pCsr = (RtreeCursor *)cur;
108054  sqlite3_free(pCsr->aConstraint);
108055  rc = nodeRelease(pRtree, pCsr->pNode);
108056  sqlite3_free(pCsr);
108057  return rc;
108058}
108059
108060/*
108061** Rtree virtual table module xEof method.
108062**
108063** Return non-zero if the cursor does not currently point to a valid
108064** record (i.e if the scan has finished), or zero otherwise.
108065*/
108066static int rtreeEof(sqlite3_vtab_cursor *cur){
108067  RtreeCursor *pCsr = (RtreeCursor *)cur;
108068  return (pCsr->pNode==0);
108069}
108070
108071/*
108072** Cursor pCursor currently points to a cell in a non-leaf page.
108073** Return true if the sub-tree headed by the cell is filtered
108074** (excluded) by the constraints in the pCursor->aConstraint[]
108075** array, or false otherwise.
108076*/
108077static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
108078  RtreeCell cell;
108079  int ii;
108080  int bRes = 0;
108081
108082  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
108083  for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
108084    RtreeConstraint *p = &pCursor->aConstraint[ii];
108085    double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
108086    double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
108087
108088    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
108089        || p->op==RTREE_GT || p->op==RTREE_EQ
108090    );
108091
108092    switch( p->op ){
108093      case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
108094      case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
108095      case RTREE_EQ:
108096        bRes = (p->rValue>cell_max || p->rValue<cell_min);
108097        break;
108098    }
108099  }
108100
108101  return bRes;
108102}
108103
108104/*
108105** Return true if the cell that cursor pCursor currently points to
108106** would be filtered (excluded) by the constraints in the
108107** pCursor->aConstraint[] array, or false otherwise.
108108**
108109** This function assumes that the cell is part of a leaf node.
108110*/
108111static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
108112  RtreeCell cell;
108113  int ii;
108114
108115  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
108116  for(ii=0; ii<pCursor->nConstraint; ii++){
108117    RtreeConstraint *p = &pCursor->aConstraint[ii];
108118    double coord = DCOORD(cell.aCoord[p->iCoord]);
108119    int res;
108120    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
108121        || p->op==RTREE_GT || p->op==RTREE_EQ
108122    );
108123    switch( p->op ){
108124      case RTREE_LE: res = (coord<=p->rValue); break;
108125      case RTREE_LT: res = (coord<p->rValue);  break;
108126      case RTREE_GE: res = (coord>=p->rValue); break;
108127      case RTREE_GT: res = (coord>p->rValue);  break;
108128      case RTREE_EQ: res = (coord==p->rValue); break;
108129    }
108130
108131    if( !res ) return 1;
108132  }
108133
108134  return 0;
108135}
108136
108137/*
108138** Cursor pCursor currently points at a node that heads a sub-tree of
108139** height iHeight (if iHeight==0, then the node is a leaf). Descend
108140** to point to the left-most cell of the sub-tree that matches the
108141** configured constraints.
108142*/
108143static int descendToCell(
108144  Rtree *pRtree,
108145  RtreeCursor *pCursor,
108146  int iHeight,
108147  int *pEof                 /* OUT: Set to true if cannot descend */
108148){
108149  int isEof;
108150  int rc;
108151  int ii;
108152  RtreeNode *pChild;
108153  sqlite3_int64 iRowid;
108154
108155  RtreeNode *pSavedNode = pCursor->pNode;
108156  int iSavedCell = pCursor->iCell;
108157
108158  assert( iHeight>=0 );
108159
108160  if( iHeight==0 ){
108161    isEof = testRtreeEntry(pRtree, pCursor);
108162  }else{
108163    isEof = testRtreeCell(pRtree, pCursor);
108164  }
108165  if( isEof || iHeight==0 ){
108166    *pEof = isEof;
108167    return SQLITE_OK;
108168  }
108169
108170  iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
108171  rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
108172  if( rc!=SQLITE_OK ){
108173    return rc;
108174  }
108175
108176  nodeRelease(pRtree, pCursor->pNode);
108177  pCursor->pNode = pChild;
108178  isEof = 1;
108179  for(ii=0; isEof && ii<NCELL(pChild); ii++){
108180    pCursor->iCell = ii;
108181    rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
108182    if( rc!=SQLITE_OK ){
108183      return rc;
108184    }
108185  }
108186
108187  if( isEof ){
108188    assert( pCursor->pNode==pChild );
108189    nodeReference(pSavedNode);
108190    nodeRelease(pRtree, pChild);
108191    pCursor->pNode = pSavedNode;
108192    pCursor->iCell = iSavedCell;
108193  }
108194
108195  *pEof = isEof;
108196  return SQLITE_OK;
108197}
108198
108199/*
108200** One of the cells in node pNode is guaranteed to have a 64-bit
108201** integer value equal to iRowid. Return the index of this cell.
108202*/
108203static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
108204  int ii;
108205  for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
108206    assert( ii<(NCELL(pNode)-1) );
108207  }
108208  return ii;
108209}
108210
108211/*
108212** Return the index of the cell containing a pointer to node pNode
108213** in its parent. If pNode is the root node, return -1.
108214*/
108215static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
108216  RtreeNode *pParent = pNode->pParent;
108217  if( pParent ){
108218    return nodeRowidIndex(pRtree, pParent, pNode->iNode);
108219  }
108220  return -1;
108221}
108222
108223/*
108224** Rtree virtual table module xNext method.
108225*/
108226static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
108227  Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
108228  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
108229  int rc = SQLITE_OK;
108230
108231  if( pCsr->iStrategy==1 ){
108232    /* This "scan" is a direct lookup by rowid. There is no next entry. */
108233    nodeRelease(pRtree, pCsr->pNode);
108234    pCsr->pNode = 0;
108235  }
108236
108237  else if( pCsr->pNode ){
108238    /* Move to the next entry that matches the configured constraints. */
108239    int iHeight = 0;
108240    while( pCsr->pNode ){
108241      RtreeNode *pNode = pCsr->pNode;
108242      int nCell = NCELL(pNode);
108243      for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
108244        int isEof;
108245        rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
108246        if( rc!=SQLITE_OK || !isEof ){
108247          return rc;
108248        }
108249      }
108250      pCsr->pNode = pNode->pParent;
108251      pCsr->iCell = nodeParentIndex(pRtree, pNode);
108252      nodeReference(pCsr->pNode);
108253      nodeRelease(pRtree, pNode);
108254      iHeight++;
108255    }
108256  }
108257
108258  return rc;
108259}
108260
108261/*
108262** Rtree virtual table module xRowid method.
108263*/
108264static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
108265  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
108266  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
108267
108268  assert(pCsr->pNode);
108269  *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
108270
108271  return SQLITE_OK;
108272}
108273
108274/*
108275** Rtree virtual table module xColumn method.
108276*/
108277static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
108278  Rtree *pRtree = (Rtree *)cur->pVtab;
108279  RtreeCursor *pCsr = (RtreeCursor *)cur;
108280
108281  if( i==0 ){
108282    i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
108283    sqlite3_result_int64(ctx, iRowid);
108284  }else{
108285    RtreeCoord c;
108286    nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
108287    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
108288      sqlite3_result_double(ctx, c.f);
108289    }else{
108290      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
108291      sqlite3_result_int(ctx, c.i);
108292    }
108293  }
108294
108295  return SQLITE_OK;
108296}
108297
108298/*
108299** Use nodeAcquire() to obtain the leaf node containing the record with
108300** rowid iRowid. If successful, set *ppLeaf to point to the node and
108301** return SQLITE_OK. If there is no such record in the table, set
108302** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
108303** to zero and return an SQLite error code.
108304*/
108305static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
108306  int rc;
108307  *ppLeaf = 0;
108308  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
108309  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
108310    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
108311    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
108312    sqlite3_reset(pRtree->pReadRowid);
108313  }else{
108314    rc = sqlite3_reset(pRtree->pReadRowid);
108315  }
108316  return rc;
108317}
108318
108319
108320/*
108321** Rtree virtual table module xFilter method.
108322*/
108323static int rtreeFilter(
108324  sqlite3_vtab_cursor *pVtabCursor,
108325  int idxNum, const char *idxStr,
108326  int argc, sqlite3_value **argv
108327){
108328  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
108329  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
108330
108331  RtreeNode *pRoot = 0;
108332  int ii;
108333  int rc = SQLITE_OK;
108334
108335  rtreeReference(pRtree);
108336
108337  sqlite3_free(pCsr->aConstraint);
108338  pCsr->aConstraint = 0;
108339  pCsr->iStrategy = idxNum;
108340
108341  if( idxNum==1 ){
108342    /* Special case - lookup by rowid. */
108343    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
108344    i64 iRowid = sqlite3_value_int64(argv[0]);
108345    rc = findLeafNode(pRtree, iRowid, &pLeaf);
108346    pCsr->pNode = pLeaf;
108347    if( pLeaf && rc==SQLITE_OK ){
108348      pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
108349    }
108350  }else{
108351    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
108352    ** with the configured constraints.
108353    */
108354    if( argc>0 ){
108355      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
108356      pCsr->nConstraint = argc;
108357      if( !pCsr->aConstraint ){
108358        rc = SQLITE_NOMEM;
108359      }else{
108360        assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
108361        for(ii=0; ii<argc; ii++){
108362          RtreeConstraint *p = &pCsr->aConstraint[ii];
108363          p->op = idxStr[ii*2];
108364          p->iCoord = idxStr[ii*2+1]-'a';
108365          p->rValue = sqlite3_value_double(argv[ii]);
108366        }
108367      }
108368    }
108369
108370    if( rc==SQLITE_OK ){
108371      pCsr->pNode = 0;
108372      rc = nodeAcquire(pRtree, 1, 0, &pRoot);
108373    }
108374    if( rc==SQLITE_OK ){
108375      int isEof = 1;
108376      int nCell = NCELL(pRoot);
108377      pCsr->pNode = pRoot;
108378      for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
108379        assert( pCsr->pNode==pRoot );
108380        rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
108381        if( !isEof ){
108382          break;
108383        }
108384      }
108385      if( rc==SQLITE_OK && isEof ){
108386        assert( pCsr->pNode==pRoot );
108387        nodeRelease(pRtree, pRoot);
108388        pCsr->pNode = 0;
108389      }
108390      assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
108391    }
108392  }
108393
108394  rtreeRelease(pRtree);
108395  return rc;
108396}
108397
108398/*
108399** Rtree virtual table module xBestIndex method. There are three
108400** table scan strategies to choose from (in order from most to
108401** least desirable):
108402**
108403**   idxNum     idxStr        Strategy
108404**   ------------------------------------------------
108405**     1        Unused        Direct lookup by rowid.
108406**     2        See below     R-tree query.
108407**     3        Unused        Full table scan.
108408**   ------------------------------------------------
108409**
108410** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
108411** 2 is used, idxStr is formatted to contain 2 bytes for each
108412** constraint used. The first two bytes of idxStr correspond to
108413** the constraint in sqlite3_index_info.aConstraintUsage[] with
108414** (argvIndex==1) etc.
108415**
108416** The first of each pair of bytes in idxStr identifies the constraint
108417** operator as follows:
108418**
108419**   Operator    Byte Value
108420**   ----------------------
108421**      =        0x41 ('A')
108422**     <=        0x42 ('B')
108423**      <        0x43 ('C')
108424**     >=        0x44 ('D')
108425**      >        0x45 ('E')
108426**   ----------------------
108427**
108428** The second of each pair of bytes identifies the coordinate column
108429** to which the constraint applies. The leftmost coordinate column
108430** is 'a', the second from the left 'b' etc.
108431*/
108432static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
108433  int rc = SQLITE_OK;
108434  int ii, cCol;
108435
108436  int iIdx = 0;
108437  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
108438  memset(zIdxStr, 0, sizeof(zIdxStr));
108439
108440  assert( pIdxInfo->idxStr==0 );
108441  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
108442    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
108443
108444    if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
108445      /* We have an equality constraint on the rowid. Use strategy 1. */
108446      int jj;
108447      for(jj=0; jj<ii; jj++){
108448        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
108449        pIdxInfo->aConstraintUsage[jj].omit = 0;
108450      }
108451      pIdxInfo->idxNum = 1;
108452      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
108453      pIdxInfo->aConstraintUsage[jj].omit = 1;
108454
108455      /* This strategy involves a two rowid lookups on an B-Tree structures
108456      ** and then a linear search of an R-Tree node. This should be
108457      ** considered almost as quick as a direct rowid lookup (for which
108458      ** sqlite uses an internal cost of 0.0).
108459      */
108460      pIdxInfo->estimatedCost = 10.0;
108461      return SQLITE_OK;
108462    }
108463
108464    if( p->usable && p->iColumn>0 ){
108465      u8 op = 0;
108466      switch( p->op ){
108467        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
108468        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
108469        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
108470        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
108471        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
108472      }
108473      if( op ){
108474        /* Make sure this particular constraint has not been used before.
108475        ** If it has been used before, ignore it.
108476        **
108477        ** A <= or < can be used if there is a prior >= or >.
108478        ** A >= or > can be used if there is a prior < or <=.
108479        ** A <= or < is disqualified if there is a prior <=, <, or ==.
108480        ** A >= or > is disqualified if there is a prior >=, >, or ==.
108481        ** A == is disqualifed if there is any prior constraint.
108482        */
108483        int j, opmsk;
108484        static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
108485        assert( compatible[RTREE_EQ & 7]==0 );
108486        assert( compatible[RTREE_LT & 7]==1 );
108487        assert( compatible[RTREE_LE & 7]==1 );
108488        assert( compatible[RTREE_GT & 7]==2 );
108489        assert( compatible[RTREE_GE & 7]==2 );
108490        cCol = p->iColumn - 1 + 'a';
108491        opmsk = compatible[op & 7];
108492        for(j=0; j<iIdx; j+=2){
108493          if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
108494            op = 0;
108495            break;
108496          }
108497        }
108498      }
108499      if( op ){
108500        assert( iIdx<sizeof(zIdxStr)-1 );
108501        zIdxStr[iIdx++] = op;
108502        zIdxStr[iIdx++] = cCol;
108503        pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
108504        pIdxInfo->aConstraintUsage[ii].omit = 1;
108505      }
108506    }
108507  }
108508
108509  pIdxInfo->idxNum = 2;
108510  pIdxInfo->needToFreeIdxStr = 1;
108511  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
108512    return SQLITE_NOMEM;
108513  }
108514  assert( iIdx>=0 );
108515  pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
108516  return rc;
108517}
108518
108519/*
108520** Return the N-dimensional volumn of the cell stored in *p.
108521*/
108522static float cellArea(Rtree *pRtree, RtreeCell *p){
108523  float area = 1.0;
108524  int ii;
108525  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108526    area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
108527  }
108528  return area;
108529}
108530
108531/*
108532** Return the margin length of cell p. The margin length is the sum
108533** of the objects size in each dimension.
108534*/
108535static float cellMargin(Rtree *pRtree, RtreeCell *p){
108536  float margin = 0.0;
108537  int ii;
108538  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108539    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
108540  }
108541  return margin;
108542}
108543
108544/*
108545** Store the union of cells p1 and p2 in p1.
108546*/
108547static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
108548  int ii;
108549  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
108550    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108551      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
108552      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
108553    }
108554  }else{
108555    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108556      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
108557      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
108558    }
108559  }
108560}
108561
108562/*
108563** Return true if the area covered by p2 is a subset of the area covered
108564** by p1. False otherwise.
108565*/
108566static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
108567  int ii;
108568  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
108569  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108570    RtreeCoord *a1 = &p1->aCoord[ii];
108571    RtreeCoord *a2 = &p2->aCoord[ii];
108572    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
108573     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
108574    ){
108575      return 0;
108576    }
108577  }
108578  return 1;
108579}
108580
108581/*
108582** Return the amount cell p would grow by if it were unioned with pCell.
108583*/
108584static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
108585  float area;
108586  RtreeCell cell;
108587  memcpy(&cell, p, sizeof(RtreeCell));
108588  area = cellArea(pRtree, &cell);
108589  cellUnion(pRtree, &cell, pCell);
108590  return (cellArea(pRtree, &cell)-area);
108591}
108592
108593#if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
108594static float cellOverlap(
108595  Rtree *pRtree,
108596  RtreeCell *p,
108597  RtreeCell *aCell,
108598  int nCell,
108599  int iExclude
108600){
108601  int ii;
108602  float overlap = 0.0;
108603  for(ii=0; ii<nCell; ii++){
108604    if( ii!=iExclude ){
108605      int jj;
108606      float o = 1.0;
108607      for(jj=0; jj<(pRtree->nDim*2); jj+=2){
108608        double x1;
108609        double x2;
108610
108611        x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
108612        x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
108613
108614        if( x2<x1 ){
108615          o = 0.0;
108616          break;
108617        }else{
108618          o = o * (x2-x1);
108619        }
108620      }
108621      overlap += o;
108622    }
108623  }
108624  return overlap;
108625}
108626#endif
108627
108628#if VARIANT_RSTARTREE_CHOOSESUBTREE
108629static float cellOverlapEnlargement(
108630  Rtree *pRtree,
108631  RtreeCell *p,
108632  RtreeCell *pInsert,
108633  RtreeCell *aCell,
108634  int nCell,
108635  int iExclude
108636){
108637  float before;
108638  float after;
108639  before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
108640  cellUnion(pRtree, p, pInsert);
108641  after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
108642  return after-before;
108643}
108644#endif
108645
108646
108647/*
108648** This function implements the ChooseLeaf algorithm from Gutman[84].
108649** ChooseSubTree in r*tree terminology.
108650*/
108651static int ChooseLeaf(
108652  Rtree *pRtree,               /* Rtree table */
108653  RtreeCell *pCell,            /* Cell to insert into rtree */
108654  int iHeight,                 /* Height of sub-tree rooted at pCell */
108655  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
108656){
108657  int rc;
108658  int ii;
108659  RtreeNode *pNode;
108660  rc = nodeAcquire(pRtree, 1, 0, &pNode);
108661
108662  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
108663    int iCell;
108664    sqlite3_int64 iBest;
108665
108666    float fMinGrowth;
108667    float fMinArea;
108668    float fMinOverlap;
108669
108670    int nCell = NCELL(pNode);
108671    RtreeCell cell;
108672    RtreeNode *pChild;
108673
108674    RtreeCell *aCell = 0;
108675
108676#if VARIANT_RSTARTREE_CHOOSESUBTREE
108677    if( ii==(pRtree->iDepth-1) ){
108678      int jj;
108679      aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
108680      if( !aCell ){
108681        rc = SQLITE_NOMEM;
108682        nodeRelease(pRtree, pNode);
108683        pNode = 0;
108684        continue;
108685      }
108686      for(jj=0; jj<nCell; jj++){
108687        nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
108688      }
108689    }
108690#endif
108691
108692    /* Select the child node which will be enlarged the least if pCell
108693    ** is inserted into it. Resolve ties by choosing the entry with
108694    ** the smallest area.
108695    */
108696    for(iCell=0; iCell<nCell; iCell++){
108697      float growth;
108698      float area;
108699      float overlap = 0.0;
108700      nodeGetCell(pRtree, pNode, iCell, &cell);
108701      growth = cellGrowth(pRtree, &cell, pCell);
108702      area = cellArea(pRtree, &cell);
108703#if VARIANT_RSTARTREE_CHOOSESUBTREE
108704      if( ii==(pRtree->iDepth-1) ){
108705        overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
108706      }
108707#endif
108708      if( (iCell==0)
108709       || (overlap<fMinOverlap)
108710       || (overlap==fMinOverlap && growth<fMinGrowth)
108711       || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
108712      ){
108713        fMinOverlap = overlap;
108714        fMinGrowth = growth;
108715        fMinArea = area;
108716        iBest = cell.iRowid;
108717      }
108718    }
108719
108720    sqlite3_free(aCell);
108721    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
108722    nodeRelease(pRtree, pNode);
108723    pNode = pChild;
108724  }
108725
108726  *ppLeaf = pNode;
108727  return rc;
108728}
108729
108730/*
108731** A cell with the same content as pCell has just been inserted into
108732** the node pNode. This function updates the bounding box cells in
108733** all ancestor elements.
108734*/
108735static void AdjustTree(
108736  Rtree *pRtree,                    /* Rtree table */
108737  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
108738  RtreeCell *pCell                  /* This cell was just inserted */
108739){
108740  RtreeNode *p = pNode;
108741  while( p->pParent ){
108742    RtreeCell cell;
108743    RtreeNode *pParent = p->pParent;
108744    int iCell = nodeParentIndex(pRtree, p);
108745
108746    nodeGetCell(pRtree, pParent, iCell, &cell);
108747    if( !cellContains(pRtree, &cell, pCell) ){
108748      cellUnion(pRtree, &cell, pCell);
108749      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
108750    }
108751
108752    p = pParent;
108753  }
108754}
108755
108756/*
108757** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
108758*/
108759static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
108760  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
108761  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
108762  sqlite3_step(pRtree->pWriteRowid);
108763  return sqlite3_reset(pRtree->pWriteRowid);
108764}
108765
108766/*
108767** Write mapping (iNode->iPar) to the <rtree>_parent table.
108768*/
108769static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
108770  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
108771  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
108772  sqlite3_step(pRtree->pWriteParent);
108773  return sqlite3_reset(pRtree->pWriteParent);
108774}
108775
108776static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
108777
108778#if VARIANT_GUTTMAN_LINEAR_SPLIT
108779/*
108780** Implementation of the linear variant of the PickNext() function from
108781** Guttman[84].
108782*/
108783static RtreeCell *LinearPickNext(
108784  Rtree *pRtree,
108785  RtreeCell *aCell,
108786  int nCell,
108787  RtreeCell *pLeftBox,
108788  RtreeCell *pRightBox,
108789  int *aiUsed
108790){
108791  int ii;
108792  for(ii=0; aiUsed[ii]; ii++);
108793  aiUsed[ii] = 1;
108794  return &aCell[ii];
108795}
108796
108797/*
108798** Implementation of the linear variant of the PickSeeds() function from
108799** Guttman[84].
108800*/
108801static void LinearPickSeeds(
108802  Rtree *pRtree,
108803  RtreeCell *aCell,
108804  int nCell,
108805  int *piLeftSeed,
108806  int *piRightSeed
108807){
108808  int i;
108809  int iLeftSeed = 0;
108810  int iRightSeed = 1;
108811  float maxNormalInnerWidth = 0.0;
108812
108813  /* Pick two "seed" cells from the array of cells. The algorithm used
108814  ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
108815  ** indices of the two seed cells in the array are stored in local
108816  ** variables iLeftSeek and iRightSeed.
108817  */
108818  for(i=0; i<pRtree->nDim; i++){
108819    float x1 = DCOORD(aCell[0].aCoord[i*2]);
108820    float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
108821    float x3 = x1;
108822    float x4 = x2;
108823    int jj;
108824
108825    int iCellLeft = 0;
108826    int iCellRight = 0;
108827
108828    for(jj=1; jj<nCell; jj++){
108829      float left = DCOORD(aCell[jj].aCoord[i*2]);
108830      float right = DCOORD(aCell[jj].aCoord[i*2+1]);
108831
108832      if( left<x1 ) x1 = left;
108833      if( right>x4 ) x4 = right;
108834      if( left>x3 ){
108835        x3 = left;
108836        iCellRight = jj;
108837      }
108838      if( right<x2 ){
108839        x2 = right;
108840        iCellLeft = jj;
108841      }
108842    }
108843
108844    if( x4!=x1 ){
108845      float normalwidth = (x3 - x2) / (x4 - x1);
108846      if( normalwidth>maxNormalInnerWidth ){
108847        iLeftSeed = iCellLeft;
108848        iRightSeed = iCellRight;
108849      }
108850    }
108851  }
108852
108853  *piLeftSeed = iLeftSeed;
108854  *piRightSeed = iRightSeed;
108855}
108856#endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
108857
108858#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
108859/*
108860** Implementation of the quadratic variant of the PickNext() function from
108861** Guttman[84].
108862*/
108863static RtreeCell *QuadraticPickNext(
108864  Rtree *pRtree,
108865  RtreeCell *aCell,
108866  int nCell,
108867  RtreeCell *pLeftBox,
108868  RtreeCell *pRightBox,
108869  int *aiUsed
108870){
108871  #define FABS(a) ((a)<0.0?-1.0*(a):(a))
108872
108873  int iSelect = -1;
108874  float fDiff;
108875  int ii;
108876  for(ii=0; ii<nCell; ii++){
108877    if( aiUsed[ii]==0 ){
108878      float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
108879      float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
108880      float diff = FABS(right-left);
108881      if( iSelect<0 || diff>fDiff ){
108882        fDiff = diff;
108883        iSelect = ii;
108884      }
108885    }
108886  }
108887  aiUsed[iSelect] = 1;
108888  return &aCell[iSelect];
108889}
108890
108891/*
108892** Implementation of the quadratic variant of the PickSeeds() function from
108893** Guttman[84].
108894*/
108895static void QuadraticPickSeeds(
108896  Rtree *pRtree,
108897  RtreeCell *aCell,
108898  int nCell,
108899  int *piLeftSeed,
108900  int *piRightSeed
108901){
108902  int ii;
108903  int jj;
108904
108905  int iLeftSeed = 0;
108906  int iRightSeed = 1;
108907  float fWaste = 0.0;
108908
108909  for(ii=0; ii<nCell; ii++){
108910    for(jj=ii+1; jj<nCell; jj++){
108911      float right = cellArea(pRtree, &aCell[jj]);
108912      float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
108913      float waste = growth - right;
108914
108915      if( waste>fWaste ){
108916        iLeftSeed = ii;
108917        iRightSeed = jj;
108918        fWaste = waste;
108919      }
108920    }
108921  }
108922
108923  *piLeftSeed = iLeftSeed;
108924  *piRightSeed = iRightSeed;
108925}
108926#endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
108927
108928/*
108929** Arguments aIdx, aDistance and aSpare all point to arrays of size
108930** nIdx. The aIdx array contains the set of integers from 0 to
108931** (nIdx-1) in no particular order. This function sorts the values
108932** in aIdx according to the indexed values in aDistance. For
108933** example, assuming the inputs:
108934**
108935**   aIdx      = { 0,   1,   2,   3 }
108936**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
108937**
108938** this function sets the aIdx array to contain:
108939**
108940**   aIdx      = { 0,   1,   2,   3 }
108941**
108942** The aSpare array is used as temporary working space by the
108943** sorting algorithm.
108944*/
108945static void SortByDistance(
108946  int *aIdx,
108947  int nIdx,
108948  float *aDistance,
108949  int *aSpare
108950){
108951  if( nIdx>1 ){
108952    int iLeft = 0;
108953    int iRight = 0;
108954
108955    int nLeft = nIdx/2;
108956    int nRight = nIdx-nLeft;
108957    int *aLeft = aIdx;
108958    int *aRight = &aIdx[nLeft];
108959
108960    SortByDistance(aLeft, nLeft, aDistance, aSpare);
108961    SortByDistance(aRight, nRight, aDistance, aSpare);
108962
108963    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
108964    aLeft = aSpare;
108965
108966    while( iLeft<nLeft || iRight<nRight ){
108967      if( iLeft==nLeft ){
108968        aIdx[iLeft+iRight] = aRight[iRight];
108969        iRight++;
108970      }else if( iRight==nRight ){
108971        aIdx[iLeft+iRight] = aLeft[iLeft];
108972        iLeft++;
108973      }else{
108974        float fLeft = aDistance[aLeft[iLeft]];
108975        float fRight = aDistance[aRight[iRight]];
108976        if( fLeft<fRight ){
108977          aIdx[iLeft+iRight] = aLeft[iLeft];
108978          iLeft++;
108979        }else{
108980          aIdx[iLeft+iRight] = aRight[iRight];
108981          iRight++;
108982        }
108983      }
108984    }
108985
108986#if 0
108987    /* Check that the sort worked */
108988    {
108989      int jj;
108990      for(jj=1; jj<nIdx; jj++){
108991        float left = aDistance[aIdx[jj-1]];
108992        float right = aDistance[aIdx[jj]];
108993        assert( left<=right );
108994      }
108995    }
108996#endif
108997  }
108998}
108999
109000/*
109001** Arguments aIdx, aCell and aSpare all point to arrays of size
109002** nIdx. The aIdx array contains the set of integers from 0 to
109003** (nIdx-1) in no particular order. This function sorts the values
109004** in aIdx according to dimension iDim of the cells in aCell. The
109005** minimum value of dimension iDim is considered first, the
109006** maximum used to break ties.
109007**
109008** The aSpare array is used as temporary working space by the
109009** sorting algorithm.
109010*/
109011static void SortByDimension(
109012  Rtree *pRtree,
109013  int *aIdx,
109014  int nIdx,
109015  int iDim,
109016  RtreeCell *aCell,
109017  int *aSpare
109018){
109019  if( nIdx>1 ){
109020
109021    int iLeft = 0;
109022    int iRight = 0;
109023
109024    int nLeft = nIdx/2;
109025    int nRight = nIdx-nLeft;
109026    int *aLeft = aIdx;
109027    int *aRight = &aIdx[nLeft];
109028
109029    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
109030    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
109031
109032    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
109033    aLeft = aSpare;
109034    while( iLeft<nLeft || iRight<nRight ){
109035      double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
109036      double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
109037      double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
109038      double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
109039      if( (iLeft!=nLeft) && ((iRight==nRight)
109040       || (xleft1<xright1)
109041       || (xleft1==xright1 && xleft2<xright2)
109042      )){
109043        aIdx[iLeft+iRight] = aLeft[iLeft];
109044        iLeft++;
109045      }else{
109046        aIdx[iLeft+iRight] = aRight[iRight];
109047        iRight++;
109048      }
109049    }
109050
109051#if 0
109052    /* Check that the sort worked */
109053    {
109054      int jj;
109055      for(jj=1; jj<nIdx; jj++){
109056        float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
109057        float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
109058        float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
109059        float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
109060        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
109061      }
109062    }
109063#endif
109064  }
109065}
109066
109067#if VARIANT_RSTARTREE_SPLIT
109068/*
109069** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
109070*/
109071static int splitNodeStartree(
109072  Rtree *pRtree,
109073  RtreeCell *aCell,
109074  int nCell,
109075  RtreeNode *pLeft,
109076  RtreeNode *pRight,
109077  RtreeCell *pBboxLeft,
109078  RtreeCell *pBboxRight
109079){
109080  int **aaSorted;
109081  int *aSpare;
109082  int ii;
109083
109084  int iBestDim;
109085  int iBestSplit;
109086  float fBestMargin;
109087
109088  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
109089
109090  aaSorted = (int **)sqlite3_malloc(nByte);
109091  if( !aaSorted ){
109092    return SQLITE_NOMEM;
109093  }
109094
109095  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
109096  memset(aaSorted, 0, nByte);
109097  for(ii=0; ii<pRtree->nDim; ii++){
109098    int jj;
109099    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
109100    for(jj=0; jj<nCell; jj++){
109101      aaSorted[ii][jj] = jj;
109102    }
109103    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
109104  }
109105
109106  for(ii=0; ii<pRtree->nDim; ii++){
109107    float margin = 0.0;
109108    float fBestOverlap;
109109    float fBestArea;
109110    int iBestLeft;
109111    int nLeft;
109112
109113    for(
109114      nLeft=RTREE_MINCELLS(pRtree);
109115      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
109116      nLeft++
109117    ){
109118      RtreeCell left;
109119      RtreeCell right;
109120      int kk;
109121      float overlap;
109122      float area;
109123
109124      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
109125      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
109126      for(kk=1; kk<(nCell-1); kk++){
109127        if( kk<nLeft ){
109128          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
109129        }else{
109130          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
109131        }
109132      }
109133      margin += cellMargin(pRtree, &left);
109134      margin += cellMargin(pRtree, &right);
109135      overlap = cellOverlap(pRtree, &left, &right, 1, -1);
109136      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
109137      if( (nLeft==RTREE_MINCELLS(pRtree))
109138       || (overlap<fBestOverlap)
109139       || (overlap==fBestOverlap && area<fBestArea)
109140      ){
109141        iBestLeft = nLeft;
109142        fBestOverlap = overlap;
109143        fBestArea = area;
109144      }
109145    }
109146
109147    if( ii==0 || margin<fBestMargin ){
109148      iBestDim = ii;
109149      fBestMargin = margin;
109150      iBestSplit = iBestLeft;
109151    }
109152  }
109153
109154  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
109155  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
109156  for(ii=0; ii<nCell; ii++){
109157    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
109158    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
109159    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
109160    nodeInsertCell(pRtree, pTarget, pCell);
109161    cellUnion(pRtree, pBbox, pCell);
109162  }
109163
109164  sqlite3_free(aaSorted);
109165  return SQLITE_OK;
109166}
109167#endif
109168
109169#if VARIANT_GUTTMAN_SPLIT
109170/*
109171** Implementation of the regular R-tree SplitNode from Guttman[1984].
109172*/
109173static int splitNodeGuttman(
109174  Rtree *pRtree,
109175  RtreeCell *aCell,
109176  int nCell,
109177  RtreeNode *pLeft,
109178  RtreeNode *pRight,
109179  RtreeCell *pBboxLeft,
109180  RtreeCell *pBboxRight
109181){
109182  int iLeftSeed = 0;
109183  int iRightSeed = 1;
109184  int *aiUsed;
109185  int i;
109186
109187  aiUsed = sqlite3_malloc(sizeof(int)*nCell);
109188  if( !aiUsed ){
109189    return SQLITE_NOMEM;
109190  }
109191  memset(aiUsed, 0, sizeof(int)*nCell);
109192
109193  PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
109194
109195  memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
109196  memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
109197  nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
109198  nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
109199  aiUsed[iLeftSeed] = 1;
109200  aiUsed[iRightSeed] = 1;
109201
109202  for(i=nCell-2; i>0; i--){
109203    RtreeCell *pNext;
109204    pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
109205    float diff =
109206      cellGrowth(pRtree, pBboxLeft, pNext) -
109207      cellGrowth(pRtree, pBboxRight, pNext)
109208    ;
109209    if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
109210     || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
109211    ){
109212      nodeInsertCell(pRtree, pRight, pNext);
109213      cellUnion(pRtree, pBboxRight, pNext);
109214    }else{
109215      nodeInsertCell(pRtree, pLeft, pNext);
109216      cellUnion(pRtree, pBboxLeft, pNext);
109217    }
109218  }
109219
109220  sqlite3_free(aiUsed);
109221  return SQLITE_OK;
109222}
109223#endif
109224
109225static int updateMapping(
109226  Rtree *pRtree,
109227  i64 iRowid,
109228  RtreeNode *pNode,
109229  int iHeight
109230){
109231  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
109232  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
109233  if( iHeight>0 ){
109234    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
109235    if( pChild ){
109236      nodeRelease(pRtree, pChild->pParent);
109237      nodeReference(pNode);
109238      pChild->pParent = pNode;
109239    }
109240  }
109241  return xSetMapping(pRtree, iRowid, pNode->iNode);
109242}
109243
109244static int SplitNode(
109245  Rtree *pRtree,
109246  RtreeNode *pNode,
109247  RtreeCell *pCell,
109248  int iHeight
109249){
109250  int i;
109251  int newCellIsRight = 0;
109252
109253  int rc = SQLITE_OK;
109254  int nCell = NCELL(pNode);
109255  RtreeCell *aCell;
109256  int *aiUsed;
109257
109258  RtreeNode *pLeft = 0;
109259  RtreeNode *pRight = 0;
109260
109261  RtreeCell leftbbox;
109262  RtreeCell rightbbox;
109263
109264  /* Allocate an array and populate it with a copy of pCell and
109265  ** all cells from node pLeft. Then zero the original node.
109266  */
109267  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
109268  if( !aCell ){
109269    rc = SQLITE_NOMEM;
109270    goto splitnode_out;
109271  }
109272  aiUsed = (int *)&aCell[nCell+1];
109273  memset(aiUsed, 0, sizeof(int)*(nCell+1));
109274  for(i=0; i<nCell; i++){
109275    nodeGetCell(pRtree, pNode, i, &aCell[i]);
109276  }
109277  nodeZero(pRtree, pNode);
109278  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
109279  nCell++;
109280
109281  if( pNode->iNode==1 ){
109282    pRight = nodeNew(pRtree, pNode, 1);
109283    pLeft = nodeNew(pRtree, pNode, 1);
109284    pRtree->iDepth++;
109285    pNode->isDirty = 1;
109286    writeInt16(pNode->zData, pRtree->iDepth);
109287  }else{
109288    pLeft = pNode;
109289    pRight = nodeNew(pRtree, pLeft->pParent, 1);
109290    nodeReference(pLeft);
109291  }
109292
109293  if( !pLeft || !pRight ){
109294    rc = SQLITE_NOMEM;
109295    goto splitnode_out;
109296  }
109297
109298  memset(pLeft->zData, 0, pRtree->iNodeSize);
109299  memset(pRight->zData, 0, pRtree->iNodeSize);
109300
109301  rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
109302  if( rc!=SQLITE_OK ){
109303    goto splitnode_out;
109304  }
109305
109306  /* Ensure both child nodes have node numbers assigned to them. */
109307  if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
109308   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
109309  ){
109310    goto splitnode_out;
109311  }
109312
109313  rightbbox.iRowid = pRight->iNode;
109314  leftbbox.iRowid = pLeft->iNode;
109315
109316  if( pNode->iNode==1 ){
109317    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
109318    if( rc!=SQLITE_OK ){
109319      goto splitnode_out;
109320    }
109321  }else{
109322    RtreeNode *pParent = pLeft->pParent;
109323    int iCell = nodeParentIndex(pRtree, pLeft);
109324    nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
109325    AdjustTree(pRtree, pParent, &leftbbox);
109326  }
109327  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
109328    goto splitnode_out;
109329  }
109330
109331  for(i=0; i<NCELL(pRight); i++){
109332    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
109333    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
109334    if( iRowid==pCell->iRowid ){
109335      newCellIsRight = 1;
109336    }
109337    if( rc!=SQLITE_OK ){
109338      goto splitnode_out;
109339    }
109340  }
109341  if( pNode->iNode==1 ){
109342    for(i=0; i<NCELL(pLeft); i++){
109343      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
109344      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
109345      if( rc!=SQLITE_OK ){
109346        goto splitnode_out;
109347      }
109348    }
109349  }else if( newCellIsRight==0 ){
109350    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
109351  }
109352
109353  if( rc==SQLITE_OK ){
109354    rc = nodeRelease(pRtree, pRight);
109355    pRight = 0;
109356  }
109357  if( rc==SQLITE_OK ){
109358    rc = nodeRelease(pRtree, pLeft);
109359    pLeft = 0;
109360  }
109361
109362splitnode_out:
109363  nodeRelease(pRtree, pRight);
109364  nodeRelease(pRtree, pLeft);
109365  sqlite3_free(aCell);
109366  return rc;
109367}
109368
109369static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
109370  int rc = SQLITE_OK;
109371  if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
109372    sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
109373    if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
109374      i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
109375      rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
109376    }else{
109377      rc = SQLITE_ERROR;
109378    }
109379    sqlite3_reset(pRtree->pReadParent);
109380    if( rc==SQLITE_OK ){
109381      rc = fixLeafParent(pRtree, pLeaf->pParent);
109382    }
109383  }
109384  return rc;
109385}
109386
109387static int deleteCell(Rtree *, RtreeNode *, int, int);
109388
109389static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
109390  int rc;
109391  RtreeNode *pParent;
109392  int iCell;
109393
109394  assert( pNode->nRef==1 );
109395
109396  /* Remove the entry in the parent cell. */
109397  iCell = nodeParentIndex(pRtree, pNode);
109398  pParent = pNode->pParent;
109399  pNode->pParent = 0;
109400  if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1))
109401   || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
109402  ){
109403    return rc;
109404  }
109405
109406  /* Remove the xxx_node entry. */
109407  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
109408  sqlite3_step(pRtree->pDeleteNode);
109409  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
109410    return rc;
109411  }
109412
109413  /* Remove the xxx_parent entry. */
109414  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
109415  sqlite3_step(pRtree->pDeleteParent);
109416  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
109417    return rc;
109418  }
109419
109420  /* Remove the node from the in-memory hash table and link it into
109421  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
109422  */
109423  nodeHashDelete(pRtree, pNode);
109424  pNode->iNode = iHeight;
109425  pNode->pNext = pRtree->pDeleted;
109426  pNode->nRef++;
109427  pRtree->pDeleted = pNode;
109428
109429  return SQLITE_OK;
109430}
109431
109432static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
109433  RtreeNode *pParent = pNode->pParent;
109434  if( pParent ){
109435    int ii;
109436    int nCell = NCELL(pNode);
109437    RtreeCell box;                            /* Bounding box for pNode */
109438    nodeGetCell(pRtree, pNode, 0, &box);
109439    for(ii=1; ii<nCell; ii++){
109440      RtreeCell cell;
109441      nodeGetCell(pRtree, pNode, ii, &cell);
109442      cellUnion(pRtree, &box, &cell);
109443    }
109444    box.iRowid = pNode->iNode;
109445    ii = nodeParentIndex(pRtree, pNode);
109446    nodeOverwriteCell(pRtree, pParent, &box, ii);
109447    fixBoundingBox(pRtree, pParent);
109448  }
109449}
109450
109451/*
109452** Delete the cell at index iCell of node pNode. After removing the
109453** cell, adjust the r-tree data structure if required.
109454*/
109455static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
109456  int rc;
109457
109458  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
109459    return rc;
109460  }
109461
109462  /* Remove the cell from the node. This call just moves bytes around
109463  ** the in-memory node image, so it cannot fail.
109464  */
109465  nodeDeleteCell(pRtree, pNode, iCell);
109466
109467  /* If the node is not the tree root and now has less than the minimum
109468  ** number of cells, remove it from the tree. Otherwise, update the
109469  ** cell in the parent node so that it tightly contains the updated
109470  ** node.
109471  */
109472  if( pNode->iNode!=1 ){
109473    RtreeNode *pParent = pNode->pParent;
109474    if( (pParent->iNode!=1 || NCELL(pParent)!=1)
109475     && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
109476    ){
109477      rc = removeNode(pRtree, pNode, iHeight);
109478    }else{
109479      fixBoundingBox(pRtree, pNode);
109480    }
109481  }
109482
109483  return rc;
109484}
109485
109486static int Reinsert(
109487  Rtree *pRtree,
109488  RtreeNode *pNode,
109489  RtreeCell *pCell,
109490  int iHeight
109491){
109492  int *aOrder;
109493  int *aSpare;
109494  RtreeCell *aCell;
109495  float *aDistance;
109496  int nCell;
109497  float aCenterCoord[RTREE_MAX_DIMENSIONS];
109498  int iDim;
109499  int ii;
109500  int rc = SQLITE_OK;
109501
109502  memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
109503
109504  nCell = NCELL(pNode)+1;
109505
109506  /* Allocate the buffers used by this operation. The allocation is
109507  ** relinquished before this function returns.
109508  */
109509  aCell = (RtreeCell *)sqlite3_malloc(nCell * (
109510    sizeof(RtreeCell) +         /* aCell array */
109511    sizeof(int)       +         /* aOrder array */
109512    sizeof(int)       +         /* aSpare array */
109513    sizeof(float)               /* aDistance array */
109514  ));
109515  if( !aCell ){
109516    return SQLITE_NOMEM;
109517  }
109518  aOrder    = (int *)&aCell[nCell];
109519  aSpare    = (int *)&aOrder[nCell];
109520  aDistance = (float *)&aSpare[nCell];
109521
109522  for(ii=0; ii<nCell; ii++){
109523    if( ii==(nCell-1) ){
109524      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
109525    }else{
109526      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
109527    }
109528    aOrder[ii] = ii;
109529    for(iDim=0; iDim<pRtree->nDim; iDim++){
109530      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
109531      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
109532    }
109533  }
109534  for(iDim=0; iDim<pRtree->nDim; iDim++){
109535    aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
109536  }
109537
109538  for(ii=0; ii<nCell; ii++){
109539    aDistance[ii] = 0.0;
109540    for(iDim=0; iDim<pRtree->nDim; iDim++){
109541      float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) -
109542          DCOORD(aCell[ii].aCoord[iDim*2]);
109543      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
109544    }
109545  }
109546
109547  SortByDistance(aOrder, nCell, aDistance, aSpare);
109548  nodeZero(pRtree, pNode);
109549
109550  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
109551    RtreeCell *p = &aCell[aOrder[ii]];
109552    nodeInsertCell(pRtree, pNode, p);
109553    if( p->iRowid==pCell->iRowid ){
109554      if( iHeight==0 ){
109555        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
109556      }else{
109557        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
109558      }
109559    }
109560  }
109561  if( rc==SQLITE_OK ){
109562    fixBoundingBox(pRtree, pNode);
109563  }
109564  for(; rc==SQLITE_OK && ii<nCell; ii++){
109565    /* Find a node to store this cell in. pNode->iNode currently contains
109566    ** the height of the sub-tree headed by the cell.
109567    */
109568    RtreeNode *pInsert;
109569    RtreeCell *p = &aCell[aOrder[ii]];
109570    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
109571    if( rc==SQLITE_OK ){
109572      int rc2;
109573      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
109574      rc2 = nodeRelease(pRtree, pInsert);
109575      if( rc==SQLITE_OK ){
109576        rc = rc2;
109577      }
109578    }
109579  }
109580
109581  sqlite3_free(aCell);
109582  return rc;
109583}
109584
109585/*
109586** Insert cell pCell into node pNode. Node pNode is the head of a
109587** subtree iHeight high (leaf nodes have iHeight==0).
109588*/
109589static int rtreeInsertCell(
109590  Rtree *pRtree,
109591  RtreeNode *pNode,
109592  RtreeCell *pCell,
109593  int iHeight
109594){
109595  int rc = SQLITE_OK;
109596  if( iHeight>0 ){
109597    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
109598    if( pChild ){
109599      nodeRelease(pRtree, pChild->pParent);
109600      nodeReference(pNode);
109601      pChild->pParent = pNode;
109602    }
109603  }
109604  if( nodeInsertCell(pRtree, pNode, pCell) ){
109605#if VARIANT_RSTARTREE_REINSERT
109606    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
109607      rc = SplitNode(pRtree, pNode, pCell, iHeight);
109608    }else{
109609      pRtree->iReinsertHeight = iHeight;
109610      rc = Reinsert(pRtree, pNode, pCell, iHeight);
109611    }
109612#else
109613    rc = SplitNode(pRtree, pNode, pCell, iHeight);
109614#endif
109615  }else{
109616    AdjustTree(pRtree, pNode, pCell);
109617    if( iHeight==0 ){
109618      rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
109619    }else{
109620      rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
109621    }
109622  }
109623  return rc;
109624}
109625
109626static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
109627  int ii;
109628  int rc = SQLITE_OK;
109629  int nCell = NCELL(pNode);
109630
109631  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
109632    RtreeNode *pInsert;
109633    RtreeCell cell;
109634    nodeGetCell(pRtree, pNode, ii, &cell);
109635
109636    /* Find a node to store this cell in. pNode->iNode currently contains
109637    ** the height of the sub-tree headed by the cell.
109638    */
109639    rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
109640    if( rc==SQLITE_OK ){
109641      int rc2;
109642      rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
109643      rc2 = nodeRelease(pRtree, pInsert);
109644      if( rc==SQLITE_OK ){
109645        rc = rc2;
109646      }
109647    }
109648  }
109649  return rc;
109650}
109651
109652/*
109653** Select a currently unused rowid for a new r-tree record.
109654*/
109655static int newRowid(Rtree *pRtree, i64 *piRowid){
109656  int rc;
109657  sqlite3_bind_null(pRtree->pWriteRowid, 1);
109658  sqlite3_bind_null(pRtree->pWriteRowid, 2);
109659  sqlite3_step(pRtree->pWriteRowid);
109660  rc = sqlite3_reset(pRtree->pWriteRowid);
109661  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
109662  return rc;
109663}
109664
109665#ifndef NDEBUG
109666static int hashIsEmpty(Rtree *pRtree){
109667  int ii;
109668  for(ii=0; ii<HASHSIZE; ii++){
109669    assert( !pRtree->aHash[ii] );
109670  }
109671  return 1;
109672}
109673#endif
109674
109675/*
109676** The xUpdate method for rtree module virtual tables.
109677*/
109678static int rtreeUpdate(
109679  sqlite3_vtab *pVtab,
109680  int nData,
109681  sqlite3_value **azData,
109682  sqlite_int64 *pRowid
109683){
109684  Rtree *pRtree = (Rtree *)pVtab;
109685  int rc = SQLITE_OK;
109686
109687  rtreeReference(pRtree);
109688
109689  assert(nData>=1);
109690  assert(hashIsEmpty(pRtree));
109691
109692  /* If azData[0] is not an SQL NULL value, it is the rowid of a
109693  ** record to delete from the r-tree table. The following block does
109694  ** just that.
109695  */
109696  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
109697    i64 iDelete;                /* The rowid to delete */
109698    RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
109699    int iCell;                  /* Index of iDelete cell in pLeaf */
109700    RtreeNode *pRoot;
109701
109702    /* Obtain a reference to the root node to initialise Rtree.iDepth */
109703    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
109704
109705    /* Obtain a reference to the leaf node that contains the entry
109706    ** about to be deleted.
109707    */
109708    if( rc==SQLITE_OK ){
109709      iDelete = sqlite3_value_int64(azData[0]);
109710      rc = findLeafNode(pRtree, iDelete, &pLeaf);
109711    }
109712
109713    /* Delete the cell in question from the leaf node. */
109714    if( rc==SQLITE_OK ){
109715      int rc2;
109716      iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
109717      rc = deleteCell(pRtree, pLeaf, iCell, 0);
109718      rc2 = nodeRelease(pRtree, pLeaf);
109719      if( rc==SQLITE_OK ){
109720        rc = rc2;
109721      }
109722    }
109723
109724    /* Delete the corresponding entry in the <rtree>_rowid table. */
109725    if( rc==SQLITE_OK ){
109726      sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
109727      sqlite3_step(pRtree->pDeleteRowid);
109728      rc = sqlite3_reset(pRtree->pDeleteRowid);
109729    }
109730
109731    /* Check if the root node now has exactly one child. If so, remove
109732    ** it, schedule the contents of the child for reinsertion and
109733    ** reduce the tree height by one.
109734    **
109735    ** This is equivalent to copying the contents of the child into
109736    ** the root node (the operation that Gutman's paper says to perform
109737    ** in this scenario).
109738    */
109739    if( rc==SQLITE_OK && pRtree->iDepth>0 ){
109740      if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
109741        RtreeNode *pChild;
109742        i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
109743        rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
109744        if( rc==SQLITE_OK ){
109745          rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
109746        }
109747        if( rc==SQLITE_OK ){
109748          pRtree->iDepth--;
109749          writeInt16(pRoot->zData, pRtree->iDepth);
109750          pRoot->isDirty = 1;
109751        }
109752      }
109753    }
109754
109755    /* Re-insert the contents of any underfull nodes removed from the tree. */
109756    for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
109757      if( rc==SQLITE_OK ){
109758        rc = reinsertNodeContent(pRtree, pLeaf);
109759      }
109760      pRtree->pDeleted = pLeaf->pNext;
109761      sqlite3_free(pLeaf);
109762    }
109763
109764    /* Release the reference to the root node. */
109765    if( rc==SQLITE_OK ){
109766      rc = nodeRelease(pRtree, pRoot);
109767    }else{
109768      nodeRelease(pRtree, pRoot);
109769    }
109770  }
109771
109772  /* If the azData[] array contains more than one element, elements
109773  ** (azData[2]..azData[argc-1]) contain a new record to insert into
109774  ** the r-tree structure.
109775  */
109776  if( rc==SQLITE_OK && nData>1 ){
109777    /* Insert a new record into the r-tree */
109778    RtreeCell cell;
109779    int ii;
109780    RtreeNode *pLeaf;
109781
109782    /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
109783    assert( nData==(pRtree->nDim*2 + 3) );
109784    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
109785      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
109786        cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
109787        cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
109788        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
109789          rc = SQLITE_CONSTRAINT;
109790          goto constraint;
109791        }
109792      }
109793    }else{
109794      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
109795        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
109796        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
109797        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
109798          rc = SQLITE_CONSTRAINT;
109799          goto constraint;
109800        }
109801      }
109802    }
109803
109804    /* Figure out the rowid of the new row. */
109805    if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
109806      rc = newRowid(pRtree, &cell.iRowid);
109807    }else{
109808      cell.iRowid = sqlite3_value_int64(azData[2]);
109809      sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
109810      if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
109811        sqlite3_reset(pRtree->pReadRowid);
109812        rc = SQLITE_CONSTRAINT;
109813        goto constraint;
109814      }
109815      rc = sqlite3_reset(pRtree->pReadRowid);
109816    }
109817
109818    if( rc==SQLITE_OK ){
109819      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
109820    }
109821    if( rc==SQLITE_OK ){
109822      int rc2;
109823      pRtree->iReinsertHeight = -1;
109824      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
109825      rc2 = nodeRelease(pRtree, pLeaf);
109826      if( rc==SQLITE_OK ){
109827        rc = rc2;
109828      }
109829    }
109830  }
109831
109832constraint:
109833  rtreeRelease(pRtree);
109834  return rc;
109835}
109836
109837/*
109838** The xRename method for rtree module virtual tables.
109839*/
109840static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
109841  Rtree *pRtree = (Rtree *)pVtab;
109842  int rc = SQLITE_NOMEM;
109843  char *zSql = sqlite3_mprintf(
109844    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
109845    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
109846    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
109847    , pRtree->zDb, pRtree->zName, zNewName
109848    , pRtree->zDb, pRtree->zName, zNewName
109849    , pRtree->zDb, pRtree->zName, zNewName
109850  );
109851  if( zSql ){
109852    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
109853    sqlite3_free(zSql);
109854  }
109855  return rc;
109856}
109857
109858static sqlite3_module rtreeModule = {
109859  0,                         /* iVersion */
109860  rtreeCreate,                /* xCreate - create a table */
109861  rtreeConnect,               /* xConnect - connect to an existing table */
109862  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
109863  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
109864  rtreeDestroy,               /* xDestroy - Drop a table */
109865  rtreeOpen,                  /* xOpen - open a cursor */
109866  rtreeClose,                 /* xClose - close a cursor */
109867  rtreeFilter,                /* xFilter - configure scan constraints */
109868  rtreeNext,                  /* xNext - advance a cursor */
109869  rtreeEof,                   /* xEof */
109870  rtreeColumn,                /* xColumn - read data */
109871  rtreeRowid,                 /* xRowid - read data */
109872  rtreeUpdate,                /* xUpdate - write data */
109873  0,                          /* xBegin - begin transaction */
109874  0,                          /* xSync - sync transaction */
109875  0,                          /* xCommit - commit transaction */
109876  0,                          /* xRollback - rollback transaction */
109877  0,                          /* xFindFunction - function overloading */
109878  rtreeRename                 /* xRename - rename the table */
109879};
109880
109881static int rtreeSqlInit(
109882  Rtree *pRtree,
109883  sqlite3 *db,
109884  const char *zDb,
109885  const char *zPrefix,
109886  int isCreate
109887){
109888  int rc = SQLITE_OK;
109889
109890  #define N_STATEMENT 9
109891  static const char *azSql[N_STATEMENT] = {
109892    /* Read and write the xxx_node table */
109893    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
109894    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
109895    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
109896
109897    /* Read and write the xxx_rowid table */
109898    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
109899    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
109900    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
109901
109902    /* Read and write the xxx_parent table */
109903    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
109904    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
109905    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
109906  };
109907  sqlite3_stmt **appStmt[N_STATEMENT];
109908  int i;
109909
109910  pRtree->db = db;
109911
109912  if( isCreate ){
109913    char *zCreate = sqlite3_mprintf(
109914"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
109915"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
109916"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
109917"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
109918      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
109919    );
109920    if( !zCreate ){
109921      return SQLITE_NOMEM;
109922    }
109923    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
109924    sqlite3_free(zCreate);
109925    if( rc!=SQLITE_OK ){
109926      return rc;
109927    }
109928  }
109929
109930  appStmt[0] = &pRtree->pReadNode;
109931  appStmt[1] = &pRtree->pWriteNode;
109932  appStmt[2] = &pRtree->pDeleteNode;
109933  appStmt[3] = &pRtree->pReadRowid;
109934  appStmt[4] = &pRtree->pWriteRowid;
109935  appStmt[5] = &pRtree->pDeleteRowid;
109936  appStmt[6] = &pRtree->pReadParent;
109937  appStmt[7] = &pRtree->pWriteParent;
109938  appStmt[8] = &pRtree->pDeleteParent;
109939
109940  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
109941    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
109942    if( zSql ){
109943      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
109944    }else{
109945      rc = SQLITE_NOMEM;
109946    }
109947    sqlite3_free(zSql);
109948  }
109949
109950  return rc;
109951}
109952
109953/*
109954** This routine queries database handle db for the page-size used by
109955** database zDb. If successful, the page-size in bytes is written to
109956** *piPageSize and SQLITE_OK returned. Otherwise, and an SQLite error
109957** code is returned.
109958*/
109959static int getPageSize(sqlite3 *db, const char *zDb, int *piPageSize){
109960  int rc = SQLITE_NOMEM;
109961  char *zSql;
109962  sqlite3_stmt *pStmt = 0;
109963
109964  zSql = sqlite3_mprintf("PRAGMA %Q.page_size", zDb);
109965  if( !zSql ){
109966    return SQLITE_NOMEM;
109967  }
109968
109969  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
109970  sqlite3_free(zSql);
109971  if( rc!=SQLITE_OK ){
109972    return rc;
109973  }
109974
109975  if( SQLITE_ROW==sqlite3_step(pStmt) ){
109976    *piPageSize = sqlite3_column_int(pStmt, 0);
109977  }
109978  return sqlite3_finalize(pStmt);
109979}
109980
109981/*
109982** This function is the implementation of both the xConnect and xCreate
109983** methods of the r-tree virtual table.
109984**
109985**   argv[0]   -> module name
109986**   argv[1]   -> database name
109987**   argv[2]   -> table name
109988**   argv[...] -> column names...
109989*/
109990static int rtreeInit(
109991  sqlite3 *db,                        /* Database connection */
109992  void *pAux,                         /* One of the RTREE_COORD_* constants */
109993  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
109994  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
109995  char **pzErr,                       /* OUT: Error message, if any */
109996  int isCreate                        /* True for xCreate, false for xConnect */
109997){
109998  int rc = SQLITE_OK;
109999  int iPageSize = 0;
110000  Rtree *pRtree;
110001  int nDb;              /* Length of string argv[1] */
110002  int nName;            /* Length of string argv[2] */
110003  int eCoordType = (int)pAux;
110004
110005  const char *aErrMsg[] = {
110006    0,                                                    /* 0 */
110007    "Wrong number of columns for an rtree table",         /* 1 */
110008    "Too few columns for an rtree table",                 /* 2 */
110009    "Too many columns for an rtree table"                 /* 3 */
110010  };
110011
110012  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
110013  if( aErrMsg[iErr] ){
110014    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
110015    return SQLITE_ERROR;
110016  }
110017
110018  rc = getPageSize(db, argv[1], &iPageSize);
110019  if( rc!=SQLITE_OK ){
110020    return rc;
110021  }
110022
110023  /* Allocate the sqlite3_vtab structure */
110024  nDb = strlen(argv[1]);
110025  nName = strlen(argv[2]);
110026  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
110027  if( !pRtree ){
110028    return SQLITE_NOMEM;
110029  }
110030  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
110031  pRtree->nBusy = 1;
110032  pRtree->base.pModule = &rtreeModule;
110033  pRtree->zDb = (char *)&pRtree[1];
110034  pRtree->zName = &pRtree->zDb[nDb+1];
110035  pRtree->nDim = (argc-4)/2;
110036  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
110037  pRtree->eCoordType = eCoordType;
110038  memcpy(pRtree->zDb, argv[1], nDb);
110039  memcpy(pRtree->zName, argv[2], nName);
110040
110041  /* Figure out the node size to use. By default, use 64 bytes less than
110042  ** the database page-size. This ensures that each node is stored on
110043  ** a single database page.
110044  **
110045  ** If the databasd page-size is so large that more than RTREE_MAXCELLS
110046  ** entries would fit in a single node, use a smaller node-size.
110047  */
110048  pRtree->iNodeSize = iPageSize-64;
110049  if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
110050    pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
110051  }
110052
110053  /* Create/Connect to the underlying relational database schema. If
110054  ** that is successful, call sqlite3_declare_vtab() to configure
110055  ** the r-tree table schema.
110056  */
110057  if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
110058    *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
110059  }else{
110060    char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
110061    char *zTmp;
110062    int ii;
110063    for(ii=4; zSql && ii<argc; ii++){
110064      zTmp = zSql;
110065      zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
110066      sqlite3_free(zTmp);
110067    }
110068    if( zSql ){
110069      zTmp = zSql;
110070      zSql = sqlite3_mprintf("%s);", zTmp);
110071      sqlite3_free(zTmp);
110072    }
110073    if( !zSql ){
110074      rc = SQLITE_NOMEM;
110075    }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
110076      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
110077    }
110078    sqlite3_free(zSql);
110079  }
110080
110081  if( rc==SQLITE_OK ){
110082    *ppVtab = (sqlite3_vtab *)pRtree;
110083  }else{
110084    rtreeRelease(pRtree);
110085  }
110086  return rc;
110087}
110088
110089
110090/*
110091** Implementation of a scalar function that decodes r-tree nodes to
110092** human readable strings. This can be used for debugging and analysis.
110093**
110094** The scalar function takes two arguments, a blob of data containing
110095** an r-tree node, and the number of dimensions the r-tree indexes.
110096** For a two-dimensional r-tree structure called "rt", to deserialize
110097** all nodes, a statement like:
110098**
110099**   SELECT rtreenode(2, data) FROM rt_node;
110100**
110101** The human readable string takes the form of a Tcl list with one
110102** entry for each cell in the r-tree node. Each entry is itself a
110103** list, containing the 8-byte rowid/pageno followed by the
110104** <num-dimension>*2 coordinates.
110105*/
110106static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
110107  char *zText = 0;
110108  RtreeNode node;
110109  Rtree tree;
110110  int ii;
110111
110112  memset(&node, 0, sizeof(RtreeNode));
110113  memset(&tree, 0, sizeof(Rtree));
110114  tree.nDim = sqlite3_value_int(apArg[0]);
110115  tree.nBytesPerCell = 8 + 8 * tree.nDim;
110116  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
110117
110118  for(ii=0; ii<NCELL(&node); ii++){
110119    char zCell[512];
110120    int nCell = 0;
110121    RtreeCell cell;
110122    int jj;
110123
110124    nodeGetCell(&tree, &node, ii, &cell);
110125    sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
110126    nCell = strlen(zCell);
110127    for(jj=0; jj<tree.nDim*2; jj++){
110128      sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
110129      nCell = strlen(zCell);
110130    }
110131
110132    if( zText ){
110133      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
110134      sqlite3_free(zText);
110135      zText = zTextNew;
110136    }else{
110137      zText = sqlite3_mprintf("{%s}", zCell);
110138    }
110139  }
110140
110141  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
110142}
110143
110144static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
110145  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
110146   || sqlite3_value_bytes(apArg[0])<2
110147  ){
110148    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
110149  }else{
110150    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
110151    sqlite3_result_int(ctx, readInt16(zBlob));
110152  }
110153}
110154
110155/*
110156** Register the r-tree module with database handle db. This creates the
110157** virtual table module "rtree" and the debugging/analysis scalar
110158** function "rtreenode".
110159*/
110160SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
110161  int rc = SQLITE_OK;
110162
110163  if( rc==SQLITE_OK ){
110164    int utf8 = SQLITE_UTF8;
110165    rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
110166  }
110167  if( rc==SQLITE_OK ){
110168    int utf8 = SQLITE_UTF8;
110169    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
110170  }
110171  if( rc==SQLITE_OK ){
110172    void *c = (void *)RTREE_COORD_REAL32;
110173    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
110174  }
110175  if( rc==SQLITE_OK ){
110176    void *c = (void *)RTREE_COORD_INT32;
110177    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
110178  }
110179
110180  return rc;
110181}
110182
110183#if !SQLITE_CORE
110184SQLITE_API int sqlite3_extension_init(
110185  sqlite3 *db,
110186  char **pzErrMsg,
110187  const sqlite3_api_routines *pApi
110188){
110189  SQLITE_EXTENSION_INIT2(pApi)
110190  return sqlite3RtreeInit(db);
110191}
110192#endif
110193
110194#endif
110195
110196/************** End of rtree.c ***********************************************/
110197/************** Begin file icu.c *********************************************/
110198/*
110199** 2007 May 6
110200**
110201** The author disclaims copyright to this source code.  In place of
110202** a legal notice, here is a blessing:
110203**
110204**    May you do good and not evil.
110205**    May you find forgiveness for yourself and forgive others.
110206**    May you share freely, never taking more than you give.
110207**
110208*************************************************************************
110209** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
110210**
110211** This file implements an integration between the ICU library
110212** ("International Components for Unicode", an open-source library
110213** for handling unicode data) and SQLite. The integration uses
110214** ICU to provide the following to SQLite:
110215**
110216**   * An implementation of the SQL regexp() function (and hence REGEXP
110217**     operator) using the ICU uregex_XX() APIs.
110218**
110219**   * Implementations of the SQL scalar upper() and lower() functions
110220**     for case mapping.
110221**
110222**   * Integration of ICU and SQLite collation seqences.
110223**
110224**   * An implementation of the LIKE operator that uses ICU to
110225**     provide case-independent matching.
110226*/
110227
110228#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
110229
110230/* Include ICU headers */
110231#include <unicode/utypes.h>
110232#include <unicode/uregex.h>
110233#include <unicode/ustring.h>
110234#include <unicode/ucol.h>
110235
110236
110237#ifndef SQLITE_CORE
110238  SQLITE_EXTENSION_INIT1
110239#else
110240#endif
110241
110242/*
110243** Maximum length (in bytes) of the pattern in a LIKE or GLOB
110244** operator.
110245*/
110246#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
110247# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
110248#endif
110249
110250/*
110251** Version of sqlite3_free() that is always a function, never a macro.
110252*/
110253static void xFree(void *p){
110254  sqlite3_free(p);
110255}
110256
110257/*
110258** Compare two UTF-8 strings for equality where the first string is
110259** a "LIKE" expression. Return true (1) if they are the same and
110260** false (0) if they are different.
110261*/
110262static int icuLikeCompare(
110263  const uint8_t *zPattern,   /* LIKE pattern */
110264  const uint8_t *zString,    /* The UTF-8 string to compare against */
110265  const UChar32 uEsc         /* The escape character */
110266){
110267  static const int MATCH_ONE = (UChar32)'_';
110268  static const int MATCH_ALL = (UChar32)'%';
110269
110270  int iPattern = 0;       /* Current byte index in zPattern */
110271  int iString = 0;        /* Current byte index in zString */
110272
110273  int prevEscape = 0;     /* True if the previous character was uEsc */
110274
110275  while( zPattern[iPattern]!=0 ){
110276
110277    /* Read (and consume) the next character from the input pattern. */
110278    UChar32 uPattern;
110279    U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
110280    assert(uPattern!=0);
110281
110282    /* There are now 4 possibilities:
110283    **
110284    **     1. uPattern is an unescaped match-all character "%",
110285    **     2. uPattern is an unescaped match-one character "_",
110286    **     3. uPattern is an unescaped escape character, or
110287    **     4. uPattern is to be handled as an ordinary character
110288    */
110289    if( !prevEscape && uPattern==MATCH_ALL ){
110290      /* Case 1. */
110291      uint8_t c;
110292
110293      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
110294      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
110295      ** test string.
110296      */
110297      while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
110298        if( c==MATCH_ONE ){
110299          if( zString[iString]==0 ) return 0;
110300          U8_FWD_1_UNSAFE(zString, iString);
110301        }
110302        iPattern++;
110303      }
110304
110305      if( zPattern[iPattern]==0 ) return 1;
110306
110307      while( zString[iString] ){
110308        if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
110309          return 1;
110310        }
110311        U8_FWD_1_UNSAFE(zString, iString);
110312      }
110313      return 0;
110314
110315    }else if( !prevEscape && uPattern==MATCH_ONE ){
110316      /* Case 2. */
110317      if( zString[iString]==0 ) return 0;
110318      U8_FWD_1_UNSAFE(zString, iString);
110319
110320    }else if( !prevEscape && uPattern==uEsc){
110321      /* Case 3. */
110322      prevEscape = 1;
110323
110324    }else{
110325      /* Case 4. */
110326      UChar32 uString;
110327      U8_NEXT_UNSAFE(zString, iString, uString);
110328      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
110329      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
110330      if( uString!=uPattern ){
110331        return 0;
110332      }
110333      prevEscape = 0;
110334    }
110335  }
110336
110337  return zString[iString]==0;
110338}
110339
110340/*
110341** Implementation of the like() SQL function.  This function implements
110342** the build-in LIKE operator.  The first argument to the function is the
110343** pattern and the second argument is the string.  So, the SQL statements:
110344**
110345**       A LIKE B
110346**
110347** is implemented as like(B, A). If there is an escape character E,
110348**
110349**       A LIKE B ESCAPE E
110350**
110351** is mapped to like(B, A, E).
110352*/
110353static void icuLikeFunc(
110354  sqlite3_context *context,
110355  int argc,
110356  sqlite3_value **argv
110357){
110358  const unsigned char *zA = sqlite3_value_text(argv[0]);
110359  const unsigned char *zB = sqlite3_value_text(argv[1]);
110360  UChar32 uEsc = 0;
110361
110362  /* Limit the length of the LIKE or GLOB pattern to avoid problems
110363  ** of deep recursion and N*N behavior in patternCompare().
110364  */
110365  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
110366    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
110367    return;
110368  }
110369
110370
110371  if( argc==3 ){
110372    /* The escape character string must consist of a single UTF-8 character.
110373    ** Otherwise, return an error.
110374    */
110375    int nE= sqlite3_value_bytes(argv[2]);
110376    const unsigned char *zE = sqlite3_value_text(argv[2]);
110377    int i = 0;
110378    if( zE==0 ) return;
110379    U8_NEXT(zE, i, nE, uEsc);
110380    if( i!=nE){
110381      sqlite3_result_error(context,
110382          "ESCAPE expression must be a single character", -1);
110383      return;
110384    }
110385  }
110386
110387  if( zA && zB ){
110388    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
110389  }
110390}
110391
110392/*
110393** This function is called when an ICU function called from within
110394** the implementation of an SQL scalar function returns an error.
110395**
110396** The scalar function context passed as the first argument is
110397** loaded with an error message based on the following two args.
110398*/
110399static void icuFunctionError(
110400  sqlite3_context *pCtx,       /* SQLite scalar function context */
110401  const char *zName,           /* Name of ICU function that failed */
110402  UErrorCode e                 /* Error code returned by ICU function */
110403){
110404  char zBuf[128];
110405  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
110406  zBuf[127] = '\0';
110407  sqlite3_result_error(pCtx, zBuf, -1);
110408}
110409
110410/*
110411** Function to delete compiled regexp objects. Registered as
110412** a destructor function with sqlite3_set_auxdata().
110413*/
110414static void icuRegexpDelete(void *p){
110415  URegularExpression *pExpr = (URegularExpression *)p;
110416  uregex_close(pExpr);
110417}
110418
110419/*
110420** Implementation of SQLite REGEXP operator. This scalar function takes
110421** two arguments. The first is a regular expression pattern to compile
110422** the second is a string to match against that pattern. If either
110423** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
110424** is 1 if the string matches the pattern, or 0 otherwise.
110425**
110426** SQLite maps the regexp() function to the regexp() operator such
110427** that the following two are equivalent:
110428**
110429**     zString REGEXP zPattern
110430**     regexp(zPattern, zString)
110431**
110432** Uses the following ICU regexp APIs:
110433**
110434**     uregex_open()
110435**     uregex_matches()
110436**     uregex_close()
110437*/
110438static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
110439  UErrorCode status = U_ZERO_ERROR;
110440  URegularExpression *pExpr;
110441  UBool res;
110442  const UChar *zString = sqlite3_value_text16(apArg[1]);
110443
110444  /* If the left hand side of the regexp operator is NULL,
110445  ** then the result is also NULL.
110446  */
110447  if( !zString ){
110448    return;
110449  }
110450
110451  pExpr = sqlite3_get_auxdata(p, 0);
110452  if( !pExpr ){
110453    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
110454    if( !zPattern ){
110455      return;
110456    }
110457    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
110458
110459    if( U_SUCCESS(status) ){
110460      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
110461    }else{
110462      assert(!pExpr);
110463      icuFunctionError(p, "uregex_open", status);
110464      return;
110465    }
110466  }
110467
110468  /* Configure the text that the regular expression operates on. */
110469  uregex_setText(pExpr, zString, -1, &status);
110470  if( !U_SUCCESS(status) ){
110471    icuFunctionError(p, "uregex_setText", status);
110472    return;
110473  }
110474
110475  /* Attempt the match */
110476  res = uregex_matches(pExpr, 0, &status);
110477  if( !U_SUCCESS(status) ){
110478    icuFunctionError(p, "uregex_matches", status);
110479    return;
110480  }
110481
110482  /* Set the text that the regular expression operates on to a NULL
110483  ** pointer. This is not really necessary, but it is tidier than
110484  ** leaving the regular expression object configured with an invalid
110485  ** pointer after this function returns.
110486  */
110487  uregex_setText(pExpr, 0, 0, &status);
110488
110489  /* Return 1 or 0. */
110490  sqlite3_result_int(p, res ? 1 : 0);
110491}
110492
110493/*
110494** Implementations of scalar functions for case mapping - upper() and
110495** lower(). Function upper() converts its input to upper-case (ABC).
110496** Function lower() converts to lower-case (abc).
110497**
110498** ICU provides two types of case mapping, "general" case mapping and
110499** "language specific". Refer to ICU documentation for the differences
110500** between the two.
110501**
110502** To utilise "general" case mapping, the upper() or lower() scalar
110503** functions are invoked with one argument:
110504**
110505**     upper('ABC') -> 'abc'
110506**     lower('abc') -> 'ABC'
110507**
110508** To access ICU "language specific" case mapping, upper() or lower()
110509** should be invoked with two arguments. The second argument is the name
110510** of the locale to use. Passing an empty string ("") or SQL NULL value
110511** as the second argument is the same as invoking the 1 argument version
110512** of upper() or lower().
110513**
110514**     lower('I', 'en_us') -> 'i'
110515**     lower('I', 'tr_tr') -> 'ı' (small dotless i)
110516**
110517** http://www.icu-project.org/userguide/posix.html#case_mappings
110518*/
110519static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
110520  const UChar *zInput;
110521  UChar *zOutput;
110522  int nInput;
110523  int nOutput;
110524
110525  UErrorCode status = U_ZERO_ERROR;
110526  const char *zLocale = 0;
110527
110528  assert(nArg==1 || nArg==2);
110529  if( nArg==2 ){
110530    zLocale = (const char *)sqlite3_value_text(apArg[1]);
110531  }
110532
110533  zInput = sqlite3_value_text16(apArg[0]);
110534  if( !zInput ){
110535    return;
110536  }
110537  nInput = sqlite3_value_bytes16(apArg[0]);
110538
110539  nOutput = nInput * 2 + 2;
110540  zOutput = sqlite3_malloc(nOutput);
110541  if( !zOutput ){
110542    return;
110543  }
110544
110545  if( sqlite3_user_data(p) ){
110546    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
110547  }else{
110548    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
110549  }
110550
110551  if( !U_SUCCESS(status) ){
110552    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
110553    return;
110554  }
110555
110556  sqlite3_result_text16(p, zOutput, -1, xFree);
110557}
110558
110559/*
110560** Collation sequence destructor function. The pCtx argument points to
110561** a UCollator structure previously allocated using ucol_open().
110562*/
110563static void icuCollationDel(void *pCtx){
110564  UCollator *p = (UCollator *)pCtx;
110565  ucol_close(p);
110566}
110567
110568/*
110569** Collation sequence comparison function. The pCtx argument points to
110570** a UCollator structure previously allocated using ucol_open().
110571*/
110572static int icuCollationColl(
110573  void *pCtx,
110574  int nLeft,
110575  const void *zLeft,
110576  int nRight,
110577  const void *zRight
110578){
110579  UCollationResult res;
110580  UCollator *p = (UCollator *)pCtx;
110581  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
110582  switch( res ){
110583    case UCOL_LESS:    return -1;
110584    case UCOL_GREATER: return +1;
110585    case UCOL_EQUAL:   return 0;
110586  }
110587  assert(!"Unexpected return value from ucol_strcoll()");
110588  return 0;
110589}
110590
110591/*
110592** Implementation of the scalar function icu_load_collation().
110593**
110594** This scalar function is used to add ICU collation based collation
110595** types to an SQLite database connection. It is intended to be called
110596** as follows:
110597**
110598**     SELECT icu_load_collation(<locale>, <collation-name>);
110599**
110600** Where <locale> is a string containing an ICU locale identifier (i.e.
110601** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
110602** collation sequence to create.
110603*/
110604static void icuLoadCollation(
110605  sqlite3_context *p,
110606  int nArg,
110607  sqlite3_value **apArg
110608){
110609  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
110610  UErrorCode status = U_ZERO_ERROR;
110611  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
110612  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
110613  UCollator *pUCollator;    /* ICU library collation object */
110614  int rc;                   /* Return code from sqlite3_create_collation_x() */
110615
110616  assert(nArg==2);
110617  zLocale = (const char *)sqlite3_value_text(apArg[0]);
110618  zName = (const char *)sqlite3_value_text(apArg[1]);
110619
110620  if( !zLocale || !zName ){
110621    return;
110622  }
110623
110624  pUCollator = ucol_open(zLocale, &status);
110625  if( !U_SUCCESS(status) ){
110626    icuFunctionError(p, "ucol_open", status);
110627    return;
110628  }
110629  assert(p);
110630
110631  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
110632      icuCollationColl, icuCollationDel
110633  );
110634  if( rc!=SQLITE_OK ){
110635    ucol_close(pUCollator);
110636    sqlite3_result_error(p, "Error registering collation function", -1);
110637  }
110638}
110639
110640/*
110641** Register the ICU extension functions with database db.
110642*/
110643SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
110644  struct IcuScalar {
110645    const char *zName;                        /* Function name */
110646    int nArg;                                 /* Number of arguments */
110647    int enc;                                  /* Optimal text encoding */
110648    void *pContext;                           /* sqlite3_user_data() context */
110649    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
110650  } scalars[] = {
110651    {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
110652
110653    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
110654    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
110655    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
110656    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
110657
110658    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
110659    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
110660    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
110661    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
110662
110663    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
110664    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
110665
110666    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
110667  };
110668
110669  int rc = SQLITE_OK;
110670  int i;
110671
110672  for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
110673    struct IcuScalar *p = &scalars[i];
110674    rc = sqlite3_create_function(
110675        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
110676    );
110677  }
110678
110679  return rc;
110680}
110681
110682#if !SQLITE_CORE
110683SQLITE_API int sqlite3_extension_init(
110684  sqlite3 *db,
110685  char **pzErrMsg,
110686  const sqlite3_api_routines *pApi
110687){
110688  SQLITE_EXTENSION_INIT2(pApi)
110689  return sqlite3IcuInit(db);
110690}
110691#endif
110692
110693#endif
110694
110695/************** End of icu.c *************************************************/
110696/************** Begin file fts3_icu.c ****************************************/
110697/*
110698** 2007 June 22
110699**
110700** The author disclaims copyright to this source code.  In place of
110701** a legal notice, here is a blessing:
110702**
110703**    May you do good and not evil.
110704**    May you find forgiveness for yourself and forgive others.
110705**    May you share freely, never taking more than you give.
110706**
110707*************************************************************************
110708** This file implements a tokenizer for fts3 based on the ICU library.
110709**
110710** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
110711*/
110712
110713#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
110714#ifdef SQLITE_ENABLE_ICU
110715
110716
110717#include <unicode/ubrk.h>
110718#include <unicode/utf16.h>
110719
110720typedef struct IcuTokenizer IcuTokenizer;
110721typedef struct IcuCursor IcuCursor;
110722
110723struct IcuTokenizer {
110724  sqlite3_tokenizer base;
110725  char *zLocale;
110726};
110727
110728struct IcuCursor {
110729  sqlite3_tokenizer_cursor base;
110730
110731  UBreakIterator *pIter;      /* ICU break-iterator object */
110732  int nChar;                  /* Number of UChar elements in pInput */
110733  UChar *aChar;               /* Copy of input using utf-16 encoding */
110734  int *aOffset;               /* Offsets of each character in utf-8 input */
110735
110736  int nBuffer;
110737  char *zBuffer;
110738
110739  int iToken;
110740};
110741
110742/*
110743** Create a new tokenizer instance.
110744*/
110745static int icuCreate(
110746  int argc,                            /* Number of entries in argv[] */
110747  const char * const *argv,            /* Tokenizer creation arguments */
110748  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
110749){
110750  IcuTokenizer *p;
110751  int n = 0;
110752
110753  if( argc>0 ){
110754    n = strlen(argv[0])+1;
110755  }
110756  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
110757  if( !p ){
110758    return SQLITE_NOMEM;
110759  }
110760  memset(p, 0, sizeof(IcuTokenizer));
110761
110762  if( n ){
110763    p->zLocale = (char *)&p[1];
110764    memcpy(p->zLocale, argv[0], n);
110765  }
110766
110767  *ppTokenizer = (sqlite3_tokenizer *)p;
110768
110769  return SQLITE_OK;
110770}
110771
110772/*
110773** Destroy a tokenizer
110774*/
110775static int icuDestroy(sqlite3_tokenizer *pTokenizer){
110776  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
110777  sqlite3_free(p);
110778  return SQLITE_OK;
110779}
110780
110781/*
110782** Prepare to begin tokenizing a particular string.  The input
110783** string to be tokenized is pInput[0..nBytes-1].  A cursor
110784** used to incrementally tokenize this string is returned in
110785** *ppCursor.
110786*/
110787static int icuOpen(
110788  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
110789  const char *zInput,                    /* Input string */
110790  int nInput,                            /* Length of zInput in bytes */
110791  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
110792){
110793  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
110794  IcuCursor *pCsr;
110795
110796  const int32_t opt = U_FOLD_CASE_DEFAULT;
110797  UErrorCode status = U_ZERO_ERROR;
110798  int nChar;
110799
110800  UChar32 c;
110801  int iInput = 0;
110802  int iOut = 0;
110803
110804  *ppCursor = 0;
110805
110806  if( nInput<0 ){
110807    nInput = strlen(zInput);
110808  }
110809  nChar = nInput+1;
110810  pCsr = (IcuCursor *)sqlite3_malloc(
110811      sizeof(IcuCursor) +                /* IcuCursor */
110812      nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
110813      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
110814  );
110815  if( !pCsr ){
110816    return SQLITE_NOMEM;
110817  }
110818  memset(pCsr, 0, sizeof(IcuCursor));
110819  pCsr->aChar = (UChar *)&pCsr[1];
110820  pCsr->aOffset = (int *)&pCsr->aChar[nChar];
110821
110822  pCsr->aOffset[iOut] = iInput;
110823  U8_NEXT(zInput, iInput, nInput, c);
110824  while( c>0 ){
110825    int isError = 0;
110826    c = u_foldCase(c, opt);
110827    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
110828    if( isError ){
110829      sqlite3_free(pCsr);
110830      return SQLITE_ERROR;
110831    }
110832    pCsr->aOffset[iOut] = iInput;
110833
110834    if( iInput<nInput ){
110835      U8_NEXT(zInput, iInput, nInput, c);
110836    }else{
110837      c = 0;
110838    }
110839  }
110840
110841  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
110842  if( !U_SUCCESS(status) ){
110843    sqlite3_free(pCsr);
110844    return SQLITE_ERROR;
110845  }
110846  pCsr->nChar = iOut;
110847
110848  ubrk_first(pCsr->pIter);
110849  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
110850  return SQLITE_OK;
110851}
110852
110853/*
110854** Close a tokenization cursor previously opened by a call to icuOpen().
110855*/
110856static int icuClose(sqlite3_tokenizer_cursor *pCursor){
110857  IcuCursor *pCsr = (IcuCursor *)pCursor;
110858  ubrk_close(pCsr->pIter);
110859  sqlite3_free(pCsr->zBuffer);
110860  sqlite3_free(pCsr);
110861  return SQLITE_OK;
110862}
110863
110864/*
110865** Extract the next token from a tokenization cursor.
110866*/
110867static int icuNext(
110868  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
110869  const char **ppToken,               /* OUT: *ppToken is the token text */
110870  int *pnBytes,                       /* OUT: Number of bytes in token */
110871  int *piStartOffset,                 /* OUT: Starting offset of token */
110872  int *piEndOffset,                   /* OUT: Ending offset of token */
110873  int *piPosition                     /* OUT: Position integer of token */
110874){
110875  IcuCursor *pCsr = (IcuCursor *)pCursor;
110876
110877  int iStart = 0;
110878  int iEnd = 0;
110879  int nByte = 0;
110880
110881  while( iStart==iEnd ){
110882    UChar32 c;
110883
110884    iStart = ubrk_current(pCsr->pIter);
110885    iEnd = ubrk_next(pCsr->pIter);
110886    if( iEnd==UBRK_DONE ){
110887      return SQLITE_DONE;
110888    }
110889
110890    while( iStart<iEnd ){
110891      int iWhite = iStart;
110892      U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
110893      if( u_isspace(c) ){
110894        iStart = iWhite;
110895      }else{
110896        break;
110897      }
110898    }
110899    assert(iStart<=iEnd);
110900  }
110901
110902  do {
110903    UErrorCode status = U_ZERO_ERROR;
110904    if( nByte ){
110905      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
110906      if( !zNew ){
110907        return SQLITE_NOMEM;
110908      }
110909      pCsr->zBuffer = zNew;
110910      pCsr->nBuffer = nByte;
110911    }
110912
110913    u_strToUTF8(
110914        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
110915        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
110916        &status                                  /* Output success/failure */
110917    );
110918  } while( nByte>pCsr->nBuffer );
110919
110920  *ppToken = pCsr->zBuffer;
110921  *pnBytes = nByte;
110922  *piStartOffset = pCsr->aOffset[iStart];
110923  *piEndOffset = pCsr->aOffset[iEnd];
110924  *piPosition = pCsr->iToken++;
110925
110926  return SQLITE_OK;
110927}
110928
110929/*
110930** The set of routines that implement the simple tokenizer
110931*/
110932static const sqlite3_tokenizer_module icuTokenizerModule = {
110933  0,                           /* iVersion */
110934  icuCreate,                   /* xCreate  */
110935  icuDestroy,                  /* xCreate  */
110936  icuOpen,                     /* xOpen    */
110937  icuClose,                    /* xClose   */
110938  icuNext,                     /* xNext    */
110939};
110940
110941/*
110942** Set *ppModule to point at the implementation of the ICU tokenizer.
110943*/
110944SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
110945  sqlite3_tokenizer_module const**ppModule
110946){
110947  *ppModule = &icuTokenizerModule;
110948}
110949
110950#endif /* defined(SQLITE_ENABLE_ICU) */
110951#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
110952
110953/************** End of fts3_icu.c ********************************************/
110954// Begin Android Add
110955/*
110956** Change the default behavior of BEGIN to IMMEDIATE instead of DEFERRED.
110957*/
110958SQLITE_API int sqlite3_set_transaction_default_immediate(sqlite3* db, int immediate){
110959  sqlite3_mutex_enter(db->mutex);
110960    if( immediate ){
110961      db->flags|=SQLITE_BeginImmediate;
110962    }else{
110963      db->flags&=~SQLITE_BeginImmediate;
110964    }
110965    sqlite3_mutex_leave(db->mutex);
110966    return SQLITE_OK;
110967}
110968SQLITE_API void sqlite3_get_pager_stats(sqlite3_int64 * totalBytesOut,
110969                                        sqlite3_int64 * referencedBytesOut,
110970                                        sqlite3_int64 * dbBytesOut,
110971                                        int * numPagersOut){
110972   // TODO
110973   *totalBytesOut = 0;
110974   *referencedBytesOut = 0;
110975   *dbBytesOut = 0;
110976   *numPagersOut = 0;
110977}
110978// End Android Add
110979